@checksum-ai/runtime 2.0.3-alpha → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1833,8 +1833,8 @@ ${o.style.help("(Use arrow keys)")}`);let be=w9e({items:w,active:W,renderItem({i
1833
1833
  ${o.style.description(ne.description)}`:"";return[[B,ce,Fe].filter(Boolean).join(" "),`${De??be}${fe}${ke}`]});var D9r=kf(l4e(),1);var h8n=kf(pdt(),1);var ZZi={icon:{cursor:$ne.pointer},style:{disabled:e(i=>D9r.default.dim(`- ${i}`),"disabled"),description:e(i=>D9r.default.cyan(i),"description")},helpMode:"auto"};function SVe(i){return!nw.isSeparator(i)&&!i.disabled}e(SVe,"isSelectable");function eea(i){return i.map(t=>{if(nw.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value);return{value:t.value,name:r,description:t.description,short:t.short??r,disabled:t.disabled??!1}})}e(eea,"normalizeChoices");var T9r=kI((i,t)=>{let{loop:r=!0,pageSize:a=7}=i,o=zne(!0),c=T8(ZZi,i.theme),[f,_]=sv("idle"),b=DI({status:f,theme:c}),C=zne(),w=rZ(()=>eea(i.choices),[i.choices]),T=rZ(()=>{let be=w.findIndex(SVe),De=w.findLastIndex(SVe);if(be===-1)throw new c4e("[select prompt] No selectable choices. All choices are disabled.");return{first:be,last:De}},[w]),k=rZ(()=>"default"in i?w.findIndex(be=>SVe(be)&&be.value===i.default):-1,[i.default,w]),[R,B]=sv(k===-1?T.first:k),U=w[R];TI((be,De)=>{if(clearTimeout(C.current),$P(be))_("done"),t(U.value);else if(u4e(be)||sVe(be)){if(De.clearLine(0),r||u4e(be)&&R!==T.first||sVe(be)&&R!==T.last){let Fe=u4e(be)?-1:1,ke=R;do ke=(ke+Fe+w.length)%w.length;while(!SVe(w[ke]));B(ke)}}else if(CLt(be)){De.clearLine(0);let Fe=Number(be.name)-1,ke=w[Fe];ke!=null&&SVe(ke)&&B(Fe)}else if(oVe(be))De.clearLine(0);else{let Fe=De.line.toLowerCase(),ke=w.findIndex(Oe=>nw.isSeparator(Oe)||!SVe(Oe)?!1:Oe.name.toLowerCase().startsWith(Fe));ke!==-1&&B(ke),C.current=setTimeout(()=>{De.clearLine(0)},700)}}),fce(()=>()=>{clearTimeout(C.current)},[]);let W=c.style.message(i.message,f),X="",ne="";(c.helpMode==="always"||c.helpMode==="auto"&&o.current)&&(o.current=!1,w.length>a?ne=`
1834
1834
  ${c.style.help("(Use arrow keys to reveal more choices)")}`:X=c.style.help("(Use arrow keys)"));let ce=w9e({items:w,active:R,renderItem({item:be,isActive:De}){if(nw.isSeparator(be))return` ${be.separator}`;if(be.disabled){let Oe=typeof be.disabled=="string"?be.disabled:"(disabled)";return c.style.disabled(`${be.name} ${Oe}`)}let Fe=De?c.style.highlight:Oe=>Oe,ke=De?c.icon.cursor:" ";return Fe(`${ke} ${be.name}`)},pageSize:a,loop:r});if(f==="done")return`${b} ${W} ${c.style.answer(U.short)}`;let fe=U.description?`
1835
1835
  ${c.style.description(U.description)}`:"";return`${[b,W,X].filter(Boolean).join(" ")}
1836
- ${ce}${ne}${fe}${h8n.default.cursorHide}`});var qVt=kf(require("child_process")),jI=require("fs"),MI=require("path");var kPn=kf(yPn());var Qme=kf(require("path")),oBr=require("fs");var tBr=require("path"),yUt=require("fs");function oca(i,t,r=10){let a=i;for(let o=0;o<r;o++){let c=(0,tBr.join)(a,"package.json");if((0,yUt.existsSync)(c))try{if(JSON.parse((0,yUt.readFileSync)(c,"utf8")).name===t)return a}catch{}a=(0,tBr.join)(a,"..")}}e(oca,"findRepositoryRoot");function vPn(i,t=10){return oca(i,"checksum-customer-engineering-workspace",t)}e(vPn,"findCustomerEngineeringRoot");var uBr=kf(CPn());var Mw=e((i,t)=>{if(i==null||i==="")return(t==null?void 0:t.default)??!1;let r=i.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(t==null?void 0:t.default)??!1},"parseBoolean");var Cca=__dirname,wPn=Qme.join(__dirname,".."),TPn=(0,oBr.existsSync)(wPn)?wPn:Cca;(0,uBr.config)({path:Qme.resolve(TPn,".env")});var aBr=Mw(process.env.CHECKSUM_RUNTIME_DEV_MODE);function wca(){let i=__dirname;for(;!(0,oBr.existsSync)(Qme.join(i,"package.json"));)i=Qme.join(i,"..");return i}e(wca,"findRoot");var ize=wca(),Sca=vPn(ize,10);(0,uBr.config)({path:[TPn,Sca].filter(Boolean).map(i=>Qme.resolve(i,".env")),override:!1});var bUt=Mw(process.env.CHECKSUM_VTG_E2E_TEST_MODE),SPn=Qme.join(ize,"vtg-build","index.html"),sBr=bUt?!0:Mw(process.env.CHECKSUM_RUNTIME_REPO_MODE),DPn=Mw(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),Dca=sBr?Qme.join(ize,"package","pw-report-template.html"):Qme.join(ize,"pw-report-template.html"),Tca=Mw(process.env.CHECKSUM_DEBUG_ANALYTICS),kca=Mw(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),i_={isDevMode:aBr,isRepoMode:sBr,CI:!!process.env.CI,checksumRootFolderBypass:bUt?"packages/runtime/test/e2e/checksum":sBr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(aBr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:ize+"/checksumlib.js"},runtimeRoot:ize,playwrightReporter:{htmlReportTemplatePath:Dca},bypassProxyForLocalhost:Mw(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:Mw(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:Mw(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Mw(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Mw(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Mw(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{defaultProvider:process.env.CHECKSUM_RUNTIME_MONITORING_DEFAULT_PROVIDER??"newrelic",debugAnalytics:Tca,logToConsole:kca,newrelic:{appName:process.env.CHECKSUM_RUNTIME_MONITORING_NEWRELIC_APP_NAME??"checksum-runtime",licenseKey:"b4f3f644f40df19fe3d385c75428a450FFFFNRAL",logging:Mw(process.env.NEW_RELIC_LOG_ENABLED,{default:!1})},segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Mw(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},vtg:{isSeparateProcess:DPn,isE2ETestMode:bUt,writeLogFile:Mw(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(aBr?"served-app":"served-build-file"),localUrl:`file://${SPn}`,localBuildPath:SPn,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:Mw(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:Mw(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||bUt,logAPIServer:{interval:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:DPn?!0:Mw(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:Mw(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:Mw(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:Mw(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:Mw(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:Mw(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var aze=class aze{constructor(t,r,a,o,c){this.traits=t;this.flushPromise=null;this.client=null;this.initialized=!1;this.isolatedMode=r,this.debugAnalytics=a,this.shouldLogToConsole=o,this.config=c||{enabled:!0,debugMode:a,logToConsole:o}}async executeWithPromise(t){return this.flushPromise?this.flushPromise:(this.flushPromise=(async()=>{try{await t()}finally{this.flushPromise=null}})(),this.flushPromise)}static flattenEvent(t){let r=e((a,o=[])=>{if(a==null||typeof a!="object")return{};try{return Object.entries(a).reduce((c,[f,_])=>{let b=[...o,f],C=b.join(".");if(typeof _=="object"&&_!==null&&!Array.isArray(_)){let w=r(_,b);Object.assign(c,w)}else c[C]=_;return c},{})}catch{return{}}},"flattenDeep");return r(t)}get analyticsEnabled(){var t;return this.isolatedMode&&!this.debugAnalytics?!1:((t=this.config)==null?void 0:t.enabled)??!0}get metadata(){return{...this.traits}}makeTableName(t){let r=this.debugAnalytics?"dev":"";return r?`${r}_${t}`:t}trackEventWithTable(t,r,a,o){if(o||this.shouldLogToConsole){let c=aze.flattenEvent(t);console.log("Analytics event tracked:",{eventType:t.event,tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,metadata:r,eventData:c,timestamp:new Date().toISOString()})}this.trackEventWithTableImpl(t,r,a,o)}trackEventWithTableImpl(t,r,a,o=!1){!this.analyticsEnabled||!this.config.enabled||(this.initialized||(this.initializeClient(),this.initialized=!0),this.safeExecute(()=>{let f={...aze.flattenEvent(t),tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,eventType:t.event,...r};this.sendEvent(f,a),(o||this.shouldLogToConsole)&&this.logEvent(t.event,f)},"tracking event"))}flushEvents(){return Promise.resolve()}async close(){if(!(!this.analyticsEnabled||!this.config.enabled||!this.initialized))return this.executeWithPromise(async()=>{await this.safeExecuteAsync(async()=>{await this.flushEvents(),this.shouldLogToConsoleEnabled&&console.log(`${this.getProviderName()} analytics session ended successfully`)},"closing analytics session")})}safeExecute(t,r){try{t()}catch(a){this.handleError(a,r)}}async safeExecuteAsync(t,r){try{await t()}catch(a){this.handleError(a,r)}}handleError(t,r){this.shouldLogToConsoleEnabled&&console.error(`Error ${r} in ${this.getProviderName()}:`,t.message)}logEvent(t,r){console.log(`${this.getProviderName()} event tracked: ${t}`,r)}get isClientReady(){return this.initialized&&this.client!==null}get shouldLogToConsoleEnabled(){return this.shouldLogToConsole}};e(aze,"AbstractAnalytics"),aze.DEFAULT_TABLE="generic_events";var sze=aze;var cBr=class cBr extends sze{constructor(r,a){let o={writeKey:i_.testRun.monitoring.segment.writeKey,enabled:!!i_.testRun.monitoring.segment.writeKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(this.client=new kPn.default({writeKey:this.config.writeKey,flushAt:1,flushInterval:1e3}))}sendEvent(r,a){this.client&&this.client.track({anonymousId:r.testSuiteRunId,event:r.eventType,properties:r})}async flushEvents(){this.client&&await dT(this.client.flush(),2e4)}getProviderName(){return"Segment"}};e(cBr,"SegmentRuntimeAnalytics");var xUt=cBr;var lBr=class lBr extends sze{constructor(r,a){let o={licenseKey:i_.testRun.monitoring.newrelic.licenseKey,appName:i_.testRun.monitoring.newrelic.appName,logging:i_.testRun.monitoring.newrelic.logging,enabled:!!i_.testRun.monitoring.newrelic.licenseKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(process.env.NEW_RELIC_LICENSE_KEY=this.config.licenseKey,process.env.NEW_RELIC_APP_NAME=this.config.appName,process.env.NEW_RELIC_LOG_ENABLED=this.config.logging.toString(),this.client=require("newrelic"))}sendEvent(r,a){this.client&&this.client.recordCustomEvent(this.makeTableName(a),r)}getProviderName(){return"New Relic"}recordMetric(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.recordMetric(r,a)},"recording metric")}addCustomAttributes(r){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.addCustomAttributes(r)},"adding custom attributes")}noticeError(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.noticeError(r,a)},"recording error")}};e(lBr,"NewRelicRuntimeAnalytics");var AUt=lBr;var pBr=class pBr{static createAnalytics(t,r={},a=!1,o=!1){switch(t){case"segment":return new xUt(r,a);case"newrelic":return new AUt(r,a);default:throw new Error(`Unsupported analytics provider: ${t}`)}}static createFromConfig(t={},r=!1,a=!1){return i_.testRun.monitoring.defaultProvider==="newrelic"?this.createAnalytics("newrelic",t,r,a):this.createAnalytics("segment",t,r)}};e(pBr,"AnalyticsFactory");var $me=pBr;var W9e=class W9e{constructor(t,r){this.analytics=$me.createFromConfig(t,r)}static getInstance(t={},r=!1){return W9e.instance||(W9e.instance=new W9e(t,r)),W9e.instance}get tableName(){return"runtime"}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}checksumConfig(t){this.event({event:"Checksum Config",metadata:this.metadata,config:t})}eventWithMessage(t,r){this.event({event:t,metadata:this.metadata,message:r})}get metadata(){return{...this.analytics.metadata,appName:"unknown",commitHash:"unknown",envName:"unknown",branch:"unknown",testSuiteRunId:"unknown",checksumRuntimeVersion:"unknown",...this.analytics.metadata}}async close(){return this.analytics.close()}};e(W9e,"RuntimeAnalytics");var EUt=W9e;var Vme=(C=>(C.Locator="locator",C.GetByRole="getByRole",C.GetByText="getByText",C.GetByLabel="getByLabel",C.GetByPlaceholder="getByPlaceholder",C.GetByAltText="getByAltText",C.GetByTitle="getByTitle",C.GetByTestId="getByTestId",C.FrameLocator="frameLocator",C))(Vme||{});var oze=(f=>(f.First="first",f.Last="last",f.Nth="nth",f.Filter="filter",f.Or="or",f.And="and",f))(oze||{});uQ();var Mca=!0,gBr=class gBr{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[];this.pendingMessages={};this.uuid=db();this.exposeFunctionsPromises=new Map;this.log=e(t=>{Mca&&console.log(`[FramesMsgBroker] ${this.uuid}:
1837
- ${t}`)},"log")}getFrameName(t){return Object.keys(this.frames).find(r=>this.frames[r]===t)}async safeExposeFunction(t,r,a){try{await t.exposeFunction(r,a),this.log(`[safeExposeFunction] ${r} exposed successfully`)}catch(o){this.log(`[safeExposeFunction] ${r}: ${o.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${AI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=this.exposeBrowserFunctions(o,t,a);this.exposeFunctionsPromises.set(o,c),await c,this.deliverPendingMessages(t,r)}async exposeBrowserFunctions(t,r,a){await this.safeExposeFunction(t,"checksumSendMessage",async(o,c,f=!1)=>{var b;this.log(`[checksumSendMessage] from ${r} to ${o}`);let _=this.frames[o];if(!_){if(f){(b=this.pendingMessages)[o]??(b[o]=[]),this.pendingMessages[o].push(c);return}throw new Error(`Frame ${o} not found`)}try{await _.evaluate(({message:C})=>window.postMessage(C,"*"),{message:c})}catch{}}),await this.safeExposeFunction(t,"checksumSendBroadcastMessage",async(o,c)=>{let f=this.channels[o]??[];this.log(`[checksumSendBroadcastMessage] on channel ${o} from ${r}`),this.log(`subscribers: ${f.map(_=>`(${_.originFrameGuid}) ${_.frame.url()}`).join(", ")}`),a&&this.writeEventsToFile(c);for(let _ of f)await this.notifySubscriber(_,c,r)}),await this.safeExposeFunction(t,"checksumBringPageToFront",async o=>{let c=this.frames[o];c&&await c.page().bringToFront()})}async notifySubscriber(t,r,a){if(t.originFrameGuid){let c=this.frames[a];if(c&&t.originFrameGuid!==AI(c))return}let o=this.getFrameName(t.frame);this.log(`handling message from ${a} to subscriber ${o}`);try{t.handler?await t.handler(r):await t.frame.evaluate(({message:c})=>window.postMessage(c,"*"),{message:r})}catch{}}writeEventsToFile(t){let r=require("fs"),a=require("path");this.events.push(...t),this.events.length%10===0&&r.writeFileSync(a.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}deliverPendingMessages(t,r){let a=this.pendingMessages[t];if(a){for(let o of a)r.evaluate(({message:c})=>window.postMessage(c,"*"),{message:o}).catch(()=>{});delete this.pendingMessages[t]}}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${AI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?AI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}};e(gBr,"FramesMsgBroker");var Xdt=gBr;var iAa=kf(oLr());var uLr=class uLr{constructor(){this.config={}}};e(uLr,"PageInteractorAPI");var vqt=uLr;var cLr=class cLr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(cLr,"ChecksumClient");var Oze=cLr;var lLr=class lLr extends vqt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new Oze({apiKey:r.apiKey,apiURL:r.apiURL})}};e(lLr,"RuntimePageInteractorAPI");var O0t=lLr;var pLr=kf(require("fs"));function y0a(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(y0a,"removeTryCatchAndTestInfo");var fLr=class fLr{static toString(t,r){let a=tRn(t,r);return Object.entries(a).map(([o,c])=>`
1836
+ ${ce}${ne}${fe}${h8n.default.cursorHide}`});var qVt=kf(require("child_process")),jI=require("fs"),MI=require("path");var kPn=kf(yPn());var Qme=kf(require("path")),oBr=require("fs");var tBr=require("path"),yUt=require("fs");function oca(i,t,r=10){let a=i;for(let o=0;o<r;o++){let c=(0,tBr.join)(a,"package.json");if((0,yUt.existsSync)(c))try{if(JSON.parse((0,yUt.readFileSync)(c,"utf8")).name===t)return a}catch{}a=(0,tBr.join)(a,"..")}}e(oca,"findRepositoryRoot");function vPn(i,t=10){return oca(i,"checksum-customer-engineering-workspace",t)}e(vPn,"findCustomerEngineeringRoot");var uBr=kf(CPn());var Mw=e((i,t)=>{if(i==null||i==="")return(t==null?void 0:t.default)??!1;let r=i.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(t==null?void 0:t.default)??!1},"parseBoolean");var Cca=__dirname,wPn=Qme.join(__dirname,".."),TPn=(0,oBr.existsSync)(wPn)?wPn:Cca;(0,uBr.config)({path:Qme.resolve(TPn,".env")});var aBr=Mw(process.env.CHECKSUM_RUNTIME_DEV_MODE);function wca(){let i=__dirname;for(;!(0,oBr.existsSync)(Qme.join(i,"package.json"));)i=Qme.join(i,"..");return i}e(wca,"findRoot");var ize=wca(),Sca=vPn(ize,10);(0,uBr.config)({path:[TPn,Sca].filter(Boolean).map(i=>Qme.resolve(i,".env")),override:!1});var bUt=Mw(process.env.CHECKSUM_VTG_E2E_TEST_MODE),SPn=Qme.join(ize,"vtg-build","index.html"),sBr=bUt?!0:Mw(process.env.CHECKSUM_RUNTIME_REPO_MODE),DPn=Mw(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),Dca=sBr?Qme.join(ize,"package","pw-report-template.html"):Qme.join(ize,"pw-report-template.html"),Tca=Mw(process.env.CHECKSUM_DEBUG_ANALYTICS),kca=Mw(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),i_={isDevMode:aBr,isRepoMode:sBr,CI:!!process.env.CI,checksumRootFolderBypass:bUt?"packages/runtime/test/e2e/checksum":sBr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(aBr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:ize+"/checksumlib.js"},runtimeRoot:ize,playwrightReporter:{htmlReportTemplatePath:Dca},bypassProxyForLocalhost:Mw(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:Mw(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:Mw(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Mw(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Mw(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Mw(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{defaultProvider:process.env.CHECKSUM_RUNTIME_MONITORING_DEFAULT_PROVIDER??"newrelic",debugAnalytics:Tca,logToConsole:kca,newrelic:{appName:process.env.CHECKSUM_RUNTIME_MONITORING_NEWRELIC_APP_NAME??"checksum-runtime",licenseKey:"b4f3f644f40df19fe3d385c75428a450FFFFNRAL",logging:Mw(process.env.NEW_RELIC_LOG_ENABLED,{default:!1})},segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Mw(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},vtg:{isSeparateProcess:DPn,isE2ETestMode:bUt,writeLogFile:Mw(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(aBr?"served-app":"served-build-file"),localUrl:`file://${SPn}`,localBuildPath:SPn,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:Mw(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:Mw(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||bUt,logAPIServer:{interval:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:DPn?!0:Mw(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:Mw(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:Mw(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:Mw(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:Mw(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:Mw(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var aze=class aze{constructor(t,r,a,o,c){this.traits=t;this.flushPromise=null;this.client=null;this.initialized=!1;this.isolatedMode=r,this.debugAnalytics=a,this.shouldLogToConsole=o,this.config=c||{enabled:!0,debugMode:a,logToConsole:o}}async executeWithPromise(t){return this.flushPromise?this.flushPromise:(this.flushPromise=(async()=>{try{await t()}finally{this.flushPromise=null}})(),this.flushPromise)}static flattenEvent(t){let r=e((a,o=[])=>{if(a==null||typeof a!="object")return{};try{return Object.entries(a).reduce((c,[f,_])=>{let b=[...o,f],C=b.join(".");if(typeof _=="object"&&_!==null&&!Array.isArray(_)){let w=r(_,b);Object.assign(c,w)}else c[C]=_;return c},{})}catch{return{}}},"flattenDeep");return r(t)}get analyticsEnabled(){var t;return this.isolatedMode&&!this.debugAnalytics?!1:((t=this.config)==null?void 0:t.enabled)??!0}get metadata(){return{...this.traits}}makeTableName(t){let r=this.debugAnalytics?"dev":"";return r?`${r}_${t}`:t}trackEventWithTable(t,r,a,o){if(o||this.shouldLogToConsole){let c=aze.flattenEvent(t);console.log("Analytics event tracked:",{eventType:t.event,tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,metadata:r,eventData:c,timestamp:new Date().toISOString()})}this.trackEventWithTableImpl(t,r,a,o)}trackEventWithTableImpl(t,r,a,o=!1){!this.analyticsEnabled||!this.config.enabled||(this.initialized||(this.initializeClient(),this.initialized=!0),this.safeExecute(()=>{let f={...aze.flattenEvent(t),tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,eventType:t.event,...r};this.sendEvent(f,a),(o||this.shouldLogToConsole)&&this.logEvent(t.event,f)},"tracking event"))}flushEvents(){return Promise.resolve()}async close(){if(!(!this.analyticsEnabled||!this.config.enabled||!this.initialized))return this.executeWithPromise(async()=>{await this.safeExecuteAsync(async()=>{await this.flushEvents(),this.shouldLogToConsoleEnabled&&console.log(`${this.getProviderName()} analytics session ended successfully`)},"closing analytics session")})}safeExecute(t,r){try{t()}catch(a){this.handleError(a,r)}}async safeExecuteAsync(t,r){try{await t()}catch(a){this.handleError(a,r)}}handleError(t,r){this.shouldLogToConsoleEnabled&&console.error(`Error ${r} in ${this.getProviderName()}:`,t.message)}logEvent(t,r){console.log(`${this.getProviderName()} event tracked: ${t}`,r)}get isClientReady(){return this.initialized&&this.client!==null}get shouldLogToConsoleEnabled(){return this.shouldLogToConsole}};e(aze,"AbstractAnalytics"),aze.DEFAULT_TABLE="generic_events";var sze=aze;var cBr=class cBr extends sze{constructor(r,a){let o={writeKey:i_.testRun.monitoring.segment.writeKey,enabled:!!i_.testRun.monitoring.segment.writeKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(this.client=new kPn.default({writeKey:this.config.writeKey,flushAt:1,flushInterval:1e3}))}sendEvent(r,a){this.client&&this.client.track({anonymousId:r.testSuiteRunId,event:r.eventType,properties:r})}async flushEvents(){this.client&&await dT(this.client.flush(),2e4)}getProviderName(){return"Segment"}};e(cBr,"SegmentRuntimeAnalytics");var xUt=cBr;var lBr=class lBr extends sze{constructor(r,a){let o={licenseKey:i_.testRun.monitoring.newrelic.licenseKey,appName:i_.testRun.monitoring.newrelic.appName,logging:i_.testRun.monitoring.newrelic.logging,enabled:!!i_.testRun.monitoring.newrelic.licenseKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(process.env.NEW_RELIC_LICENSE_KEY=this.config.licenseKey,process.env.NEW_RELIC_APP_NAME=this.config.appName,process.env.NEW_RELIC_LOG_ENABLED=this.config.logging.toString(),this.client=require("newrelic"))}sendEvent(r,a){this.client&&this.client.recordCustomEvent(this.makeTableName(a),r)}getProviderName(){return"New Relic"}recordMetric(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.recordMetric(r,a)},"recording metric")}addCustomAttributes(r){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.addCustomAttributes(r)},"adding custom attributes")}noticeError(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.noticeError(r,a)},"recording error")}};e(lBr,"NewRelicRuntimeAnalytics");var AUt=lBr;var pBr=class pBr{static createAnalytics(t,r={},a=!1,o=!1){switch(t){case"segment":return new xUt(r,a);case"newrelic":return new AUt(r,a);default:throw new Error(`Unsupported analytics provider: ${t}`)}}static createFromConfig(t={},r=!1,a=!1){return i_.testRun.monitoring.defaultProvider==="newrelic"?this.createAnalytics("newrelic",t,r,a):this.createAnalytics("segment",t,r)}};e(pBr,"AnalyticsFactory");var $me=pBr;var W9e=class W9e{constructor(t,r){this.analytics=$me.createFromConfig(t,r)}static getInstance(t={},r=!1){return W9e.instance||(W9e.instance=new W9e(t,r)),W9e.instance}get tableName(){return"runtime"}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}checksumConfig(t){this.event({event:"Checksum Config",metadata:this.metadata,config:t})}eventWithMessage(t,r){this.event({event:t,metadata:this.metadata,message:r})}get metadata(){return{...this.analytics.metadata,appName:"unknown",commitHash:"unknown",envName:"unknown",branch:"unknown",testSuiteRunId:"unknown",checksumRuntimeVersion:"unknown",...this.analytics.metadata}}async close(){return this.analytics.close()}};e(W9e,"RuntimeAnalytics");var EUt=W9e;var Vme=(C=>(C.Locator="locator",C.GetByRole="getByRole",C.GetByText="getByText",C.GetByLabel="getByLabel",C.GetByPlaceholder="getByPlaceholder",C.GetByAltText="getByAltText",C.GetByTitle="getByTitle",C.GetByTestId="getByTestId",C.FrameLocator="frameLocator",C))(Vme||{});var oze=(f=>(f.First="first",f.Last="last",f.Nth="nth",f.Filter="filter",f.Or="or",f.And="and",f))(oze||{});uQ();var Mca=!1,gBr=class gBr{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[];this.pendingMessages={};this.uuid=db();this.log=e(t=>{Mca&&console.log(`[FramesMsgBroker] ${this.uuid}:
1837
+ ${t}`)},"log");this.exposeFunctionsPromises=new Map}getFrameName(t){return Object.keys(this.frames).find(a=>this.frames[a]===t)}async safeExposeFunction(t,r,a,o){try{await t.exposeFunction(a,o),this.log(`[safeExposeFunction] ${a} exposed successfully`)}catch(c){this.log(`[safeExposeFunction] ${a}: ${c.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${AI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=(async()=>{await this.safeExposeFunction(o,r,"checksumSendMessage",async(f,_,b=!1)=>{var w;this.log(`[checksumSendMessage] from ${t} to ${f}`);let C=this.frames[f];if(!C){if(b){(w=this.pendingMessages)[f]??(w[f]=[]),this.pendingMessages[f].push(_);return}throw new Error(`Frame ${f} not found`)}try{await C.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}}),await this.safeExposeFunction(o,r,"checksumSendBroadcastMessage",async(f,_)=>{let b=this.channels[f]??[];if(this.log(`[checksumSendBroadcastMessage] on channel ${f} from ${t}`),this.log(`subscribers: ${b.map(C=>`(${C.originFrameGuid}) ${C.frame.url()}`).join(", ")}`),a){let C=require("fs"),w=require("path");this.events.push(..._),this.events.length%10===0&&C.writeFileSync(w.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}b.forEach(async C=>{if(C.originFrameGuid&&C.originFrameGuid!==AI(r))return;let w=this.getFrameName(C.frame);this.log(`handling message from ${t} to subscriber ${w}`);try{C.handler?await C.handler(_):await r.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}})}),await this.safeExposeFunction(o,r,"checksumBringPageToFront",async f=>{let _=this.frames[f];_&&await _.page().bringToFront()})})();this.exposeFunctionsPromises.set(o,c),await c,this.pendingMessages[t]&&(this.pendingMessages[t].forEach(async f=>{try{await r.evaluate(({message:_})=>{window.postMessage(_,"*")},{message:f})}catch{}}),delete this.pendingMessages[t])}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${AI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?AI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}};e(gBr,"FramesMsgBroker");var Xdt=gBr;var iAa=kf(oLr());var uLr=class uLr{constructor(){this.config={}}};e(uLr,"PageInteractorAPI");var vqt=uLr;var cLr=class cLr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(cLr,"ChecksumClient");var Oze=cLr;var lLr=class lLr extends vqt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new Oze({apiKey:r.apiKey,apiURL:r.apiURL})}};e(lLr,"RuntimePageInteractorAPI");var O0t=lLr;var pLr=kf(require("fs"));function y0a(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(y0a,"removeTryCatchAndTestInfo");var fLr=class fLr{static toString(t,r){let a=tRn(t,r);return Object.entries(a).map(([o,c])=>`
1838
1838
  ${c}`).join("")}static toRecord(t,r){return tRn(t,r)}};e(fLr,"ErrorFormatter");var Bze=fLr;function tRn(i,t){let a=(i.stack||"No stack trace available").split(`
1839
1839
  `),o={};for(let f of a){let _=f.match(/\(([^)]+):(\d+):(\d+)\)/)||f.match(/at ((?:[a-zA-Z]:\\|\/)[^:]+):(\d+):(\d+)/);if(_){let b=_[1];if(!b.includes(t)||b.includes("node_modules")||b.includes("<anonymous>")||b.includes("internal")||b.includes("loader")||b.startsWith("eval"))continue;try{if(!o[b]&&pLr.default.existsSync(b)){let C=pLr.default.readFileSync(b,"utf-8");o[b]=y0a(C)}}catch(C){o[b]=`Error reading file: ${C.message}`}}}let c={};for(let[f,_]of Object.entries(o)){let b=`
1840
1840
  --- File: ${f} ---
@@ -1918,7 +1918,7 @@ ${Z_t}`})).join(`
1918
1918
  ${Z_t}`),c=new hHe(r.sourceFile),f=(k=this.userStoryService.getStory())==null?void 0:k.internalTestId,_=(R=this.userStoryService.getStory())==null?void 0:R.goal,b=(B=this.userStoryService.getStory())==null?void 0:B.id;c.transformSourceFile([new oJt(r.sourceFile),new dJt(r.sourceFile,{internalTestId:f,title:_}),new sJt(r.sourceFile,r.testMirrors.filter(U=>U.internalTestId===f||U.storyId===b).map(U=>U.testBody),TXn(o))]);let C=this.testAssetsManager.getSavedTestFilePath(),{error:w}=await c.write(C,Z_t);return{filePath:(0,yHe.relative)(process.cwd(),C),error:w}}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(t){if(!this.vtgTestFileRunConfig)return;let r=await this.getReloadTestEnvironmentCode();await this.evaluationService.execute(r);let o=new tht(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest({mergeCustomCodeSteps:this.settingsService.getSettings().mergeCustomCodeSteps});return t&&await this.mergeTimestampsToReloadedActions(o),this.actionsManager.reloadTestSteps(o),o}async mergeTimestampsToReloadedActions(t){let r=this.actionsManager.actions,a=await this.apiService.post("llm/query",{systemMessage:BXn(),userMessage:RXn(r,t)});try{let o=await a.text(),c=JSON.parse(o),f=0;t.forEach((_,b)=>{var w,T;let C=c.map[b];if(C){let k=r.find(({id:R})=>R===C.id);if(k){_.timestamp=k.timestamp,f=k.timestamp;let R=f;(w=_.assertions)==null||w.forEach((B,U)=>{var ne;let W=C==null?void 0:C.assertions[U],X=(ne=k.assertions)==null?void 0:ne.find(({id:ce})=>ce===W);X?(B.timestamp=X.timestamp,R=X.timestamp):B.timestamp=R+1});return}}_.timestamp=f+1,(T=_.assertions)==null||T.forEach((k,R)=>{k.timestamp=f+R+1})})}catch(o){return pf.error("Failed to merge actions",o),null}}async getReloadTestImportCodeOfNewPackages(t,r,a){let o=new hHe(r);o.transformSourceFile([new oht(t,a,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new rht(t),new uht,new sht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new nht(r,c,{filterOutDefinedVariableNames:!0})]),(await o.getFormattedTestFileCode()).code}async getDeclaredVariableNames(t){return new pJt(this.evaluationService).extractDeclaredVariableNames(t)}async getReloadTestEnvironmentCode(){let t=this.testAssetsManager.getSavedTestFilePath(),r=mHe(t),a=IXn(),o=await this.getReloadCodeWithoutPackages(t,r,a);return[await this.getReloadTestImportCodeOfNewPackages(t,r,a),o].join(`
1919
1919
  `)}async getReloadCodeWithoutPackages(t,r,a){let o=new hHe(r);o.transformSourceFile([new fJt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new uJt,new oht(t,a,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new rht(t),new cJt(t,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[qXn.default.factory.createIdentifier("__filename")]}),new uht,new sht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new nht(r,c)]),(await o.getFormattedTestFileCode()).code}getLocalSavedJSONFilePath(t,r){var c;r??(r=r||((c=this.userStoryService.getStory())==null?void 0:c.id));let a=this.testAssetsManager.getLocalAutoSaveFileName(r);return`${t==="auto-save"?this.testAssetsManager.getLocalAutoSavePath():this.testAssetsManager.getLocalSavePath()}/${a}`}readLocalSavedDataFromJSONFile(t){let r=this.readJsonFile(t);return r?{...r,executedActions:r.executedActions.map(a=>({...a,timestamp:void 0}))}:null}readJsonFile(t){try{let r=(0,C7e.readFileSync)(t,"utf-8");return JSON.parse(r)}catch(r){return pf.error(`Error reading or parsing JSON file: ${r}`),null}}makeDraftData(){let t=this.userStoryService.getStory(),r=this.userStoryService.getTestGenerationData(),a=this.userStoryService.getEnvInfo(),o={};return t!=null&&t.version&&(o.version=t.version),t!=null&&t.testFlowDescription&&(o.testFlowDescription=t.testFlowDescription),{actions:this.actionsManager.actions,internalTestId:t.internalTestId,environmentUserId:a.user.username,description:t.goal,metadata:Object.keys(o).length>0?o:void 0}}async generateTestFileString(t){try{let r=this.makeDraftData(),a=t?`${t}.draft.spec.ts`:`test-${r.internalTestId}.draft.spec.ts`,o=await this.apiService.post("test-generation/generate-test-file-string",r);if(!o.ok)throw new Error(`test generation request failed: ${o.statusText}`);let c=await o.text();Gzn(c,a,this.testAssetsManager.getLocalSavePath())}catch(r){throw pf.error("Failed to generate test file string",r),new Error("Failed to generate test file string")}}localSave(){let t=JSON.stringify(this.vtgTestJSON,null,2),r=this.testAssetsManager.getAssetsFolderPath(),a=this.testAssetsManager.getLocalAutoSaveFileName(this.userStoryService.getStory().id);(0,C7e.writeFileSync)(`${r}/${a}`,t),(0,C7e.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/${a}`,t)}get vtgTestJSON(){var t;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(t=this.config.environments.find(r=>r.default))==null?void 0:t.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async extendedJSONBackup(){let t=await this.saveExtendedJson(),r=(0,yHe.dirname)(this.testAssetsManager.getSavedTestFilePath()),a=(0,yHe.join)(r,"test.extended.json");return(0,C7e.writeFileSync)(a,JSON.stringify(t,null,2)),{executedActions:t}}async localBackup(t){if(t){this.testAssetsManager.setCurrentSaveAsLocation(t);let r=this.testAssetsManager.getLocalSaveAsPath();Kzn(this.testAssetsManager.getLocalAutoSavePath(),r)}return await this.saveTestFile()}async saveExtendedJson(){let t=[...this.actionsManager.actions],r=[],a=e(async o=>{let{timestamp:c}=o,f="matcher"in o,_=o.timestamp&&(f||Vpt(o.eventCode)),{fullHTML:b,outerHTML:C,parentHTML:w,rrwebSnapshot:T}=o.timestamp?await this.getHTMLsForTimestamp(c,o.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},k=f?Die.generateSingleAssertionCode(o):Die.generateSingleActionCode(o,{newLineSeparator:`
1920
1920
  ${Z_t}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:b,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){pf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){pf.info(`processing assertion of ${c.assertions.length} assertions`);try{let b=await a(_);r.push(b)}catch(b){pf.error("Failed to extract data for assertion",b)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${aj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){pf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${aj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:b,rrwebSnapshot:C}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),w=await LXn(c);return{fullHTML:_,outerHTML:b,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return pf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,C7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){var t;try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();if(await this.saveTestFile(),!await this.settingsService.getIsGitReflectionEnabled()){let _=new Lzt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),b=e(T=>({complete:!1,error:!1,response:void 0,info:T}),"buildUploadAsset"),C=[],w=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await _.uploadAsset(b({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${w}.fix.checksum.spec.ts`})),C.push(b({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),C.push(b({type:"har",path:await UXn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(T=>T.eventCode==="upload_files").forEach(T=>{var k;(k=T.files)==null||k.forEach(R=>{C.push(b({type:"test-files",path:R}))})}),await Promise.all(C)}let o=this.actionsManager.actions.map(_=>({..._,parentFramesSelectors:_.parentFramesSelectors?_.parentFramesSelectors.filter(b=>b!=="iframe"):void 0})),c=this.userStoryService.getStory(),f={};c!=null&&c.version&&(f.version=c.version),c!=null&&c.testFlowDescription&&(f.testFlowDescription=c.testFlowDescription),await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(f).length>0?f:void 0})}catch(r){pf.error("Failed to upload test",r)}}};e(TWr,"VtgStorageService");var mJt=TWr;var kWr=class kWr{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){return!!this.userStoryTestGeneration}async fetchStory(t){if(i_.vtg.useFakeStory){this.story={...i_.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},pf.info("Using fake flow data",this.story);return}if(!t)throw new Error("no story id provided");try{let a=await(await this.apiService.post(`test-generation/info/${t}`)).json();if(!(a!=null&&a.id))throw new Error(`Story ${t} not found`);pf.info("Received flow data:",a);let{id:o,title:c,steps:f,startUrl:_,userRole:b,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:b,name:C},version:T,testFlowDescription:f,collectionName:k}}catch(r){throw pf.error(`Error fetching story by id ${t}:`,r),new Error(`Couldn't fetch story by id ${t}. Make sure the server is running and the story id is correct. Original error: ${JSON.stringify(r)}`)}}getEnvInfo(){return nVr(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.story.internalTestId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration={testGenerationId:r},this.userStoryTestGeneration}setTestGenerationData(t){this.userStoryTestGeneration=t}};e(kWr,"VtgUserStoryService");var _Jt=kWr;var IWr=class IWr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:b})=>b===r.id)),_={...o};return f?_.assertions=o.assertions.map(b=>{if(b.id===r.id){let C={...b,...r};return a=C,C}return b}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((b,C)=>b.timestamp!==C.timestamp?b.timestamp-C.timestamp:b.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var b,C,w;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(C=(b=T.action)==null?void 0:b.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=Cka(((w=_[k])==null?void 0:w.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new f7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=wka(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await SFe(_He([o],void 0,{generateAssertionsCode:!1},(_,b)=>{o=b}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(IWr,"VtgActionsManager");var hJt=IWr,Cka=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),wka=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var qWt=kf(kWt()),Gai=kf(require("net")),Kai=kf(pGr()),Yai=kf(Wai());var fKr=class fKr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(fKr,"ValidationError");var zHe=fKr,dKr=class dKr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(dKr,"NotFoundError");var JHe=dKr;var kv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(pf.error(`${t.method} ${t.path} error:`,o),o instanceof f7e)return r.status(200).json({error:o.message});if(o instanceof zHe)return r.status(400).send({error:o.message});if(o instanceof JHe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");var mKr=kf(kWt());var WHe=class WHe{constructor(){this.routesLogRules={};this.router=(0,mKr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,mKr.Router)(),a=t.startsWith(WHe.DEFAULT_API_PREFIX)?t:`${WHe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){pf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{pf.error(`Async process ${r} failed:`,c)})}};e(WHe,"VTGController"),WHe.DEFAULT_API_PREFIX="/api";var i5=WHe;var _Kr=class _Kr extends i5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",kv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let b=await SFe(_He([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:b})})),r.patch("/updateStep",kv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,b;f.type==="Assertion"&&(b=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(b=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(b.thought=void 0),C=await SFe(_He([b],void 0,{generateAssertionsCode:!1},(w,T)=>{b=T}))),c.status(200).json({step:b,code:C})})),r.delete("/deleteStep",kv(async(o,c)=>{let{id:f,options:_,type:b}=o.body;return this.actionsManager.deleteStep(f,b,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",kv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",kv(async(o,c)=>{let f=o.body;try{let _=null;return gMa(f)?_=await this.aiTestGenerationService.executeAction(f):yMa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",kv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",kv(async(o,c)=>{let _=PXn(o.body.code).map(b=>b&&"isChecksumAiWithDirectExpression"in b?{...b,isChecksumAiWithDirectExpression:!1}:b);return c.status(200).send(_)})),r.post("/steps-to-code",kv(async(o,c)=>{let f=_He(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(_Kr,"VtgStepsController");var IWt=_Kr;function gMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(gMa,"isAIExecuteActionArgs");function yMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(yMa,"isManualExecuteActionArgs");var hKr=class hKr extends i5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",kv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",kv(async(o,c)=>{let{step:f,target:_,processId:b}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,b),b,_.id,"AI locators generation");let C={processId:b,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return pf.error("Error generating AI locators:",C),c.status(500).send({processId:b,error:C.message})}})),a.post("/extract-css",kv(async(o,c)=>{let{step:f,target:_,processId:b,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,b,C),b,_.id,"CSS extraction");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error extracting CSS locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.post("/filter",kv(async(o,c)=>{let{step:f,target:_,processId:b,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,b,C),b,_.id,"locators filtering");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error filtering locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.delete("/process/:id",kv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),pf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",kv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:b}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,b);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.message})}})),r.post("/verify",kv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(hKr,"VtgLocatorsController");var PWt=hKr;var gKr=class gKr extends i5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",kv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(gKr,"MonacoController");var FWt=gKr;NI();var vMa=Nh.enum(["openai","anthropic","google-vertexai","groq"]),Hai=Nh.strictObject({message:Nh.string(),selection:Nh.object({locator:Nh.string()}).optional(),stepCode:Nh.string().optional(),messageHistory:Nh.array(Nh.object({type:Nh.enum(["user","assistant"]),content:Nh.string(),timestamp:Nh.string(),stepId:Nh.string()})).optional(),model:Nh.object({id:Nh.string(),name:Nh.string(),type:vMa,model:Nh.string(),thinking:Nh.boolean().optional()}).optional(),includeImage:Nh.boolean().optional(),includeHtml:Nh.boolean().optional(),includeCode:Nh.boolean().optional(),timestamp:Nh.number(),error:Nh.string().optional()});var yKr=class yKr extends i5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",kv(async(a,o)=>{let c=Hai.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(yKr,"AIChatController");var NWt=yKr;var Xai=kf(require("path"));var vKr=class vKr extends i5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",kv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",kv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",kv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",kv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new JHe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",kv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",kv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!Yzn(f))throw pf.error("Invalid folder name",{backupFolderName:f}),new zHe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",kv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",kv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(vKr,"VtgStorageController");var OWt=vKr;var bKr=class bKr extends i5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",kv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",kv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",kv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(bKr,"VtgAITestGenerationController");var BWt=bKr;var xKr=class xKr extends i5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.message})}})),r.post("/assertions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.message})}})),r.post("/stop-generate",kv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(xKr,"VtgThoughtsController");var RWt=xKr;var AKr=class AKr extends i5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",kv(async(o,c)=>{let f=o.body,{processId:_,id:b}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,b,"AI assertion generation");let C={processId:_,stepId:b,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.message})}})),r.post("/stop-generate",kv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",kv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",kv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),b=_.success?200:404;return c.status(b).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",kv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(AKr,"VtgAssertionsController");var LWt=AKr;var EKr=class EKr extends i5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",kv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",kv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(EKr,"VtgSettingsController");var MWt=EKr;var Zai=kf(kWt());var CKr=class CKr extends i5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",kv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(CKr,"VtgEvaluatorController");var jWt=CKr;var wKr=class wKr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){i_.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(i_.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){i_.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(pf.info("HTTP REQUESTS IN PROCESS"),pf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1921
- `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";pf.info("REQUEST INFO",JSON.stringify(f,null,2));let b=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),b.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(i_.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");pf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(wKr,"VTGExpressServerRoutesLoggerMiddleware");var UWt=wKr;var SKr=class SKr{constructor(t,r,a,o,c,f,_,b,C,w,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=b;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{pf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new UWt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,qWt.default)(),this.app.use((0,Yai.default)()),this.app.use(Kai.default.json({limit:"50mb"})),this.app.use(qWt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(qWt.default.static(Xai.default.join(i_.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{pf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),pf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Gai.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new IWt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new OWt(this.storageService,this.actionsManager,this.actionsService),a=new BWt(this.aiTestGenerationService),o=new RWt(this.aiThoughtsService),c=new LWt(this.assertionsService,this.aiAssertionsService),f=new MWt(this.settingsService),_=new PWt(this.locatorsService),b=new FWt(this.monacoService),C=new NWt(this.aiChatService),w=new jWt(this.evaluatorService),T=[t,r,a,o,c,f,_,b,w,C],k=(0,Zai.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(SKr,"VtgExpressServer");var QWt=SKr;var $Wt=require("fs");var i1t=class i1t{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,$Wt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,$Wt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,$Wt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${i1t.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(i1t,"VtgTestAssetsManager"),i1t.AUTO_SAVE_FOLDER_NAME="auto-save";var VWt=i1t;var bMa={useCDPSession:!0,trackLoadedResources:!0},DKr=class DKr extends XVt{constructor(r={},a={devtools:!1},o={},c,f){super({...bMa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let b=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:b}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,b,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:b,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(DKr,"ChecksumWebDriver");var zWt=DKr;var esi=require("fs"),tsi=kf(require("path"));var TKr=require("fs");var kKr=class kKr{constructor(t,r,a=i_.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,pf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:i_.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw pf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(i_.vtg.appSource){case"served-app":t=i_.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=i_.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${i_.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(i_.vtg.appSource==="build-file")try{let t=await TKr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await TKr.promises.writeFile(this.filePath,a,"utf8"),pf(`Successfully modified ${this.filePath}`)}catch(t){pf.error(`Error processing file ${this.filePath}:`,t)}}};e(kKr,"VtgFrontendLauncher");var JWt=kKr;var xMa=1e3,HWt=class HWt extends zWt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,HWt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),i_.vtg.isSeparateProcess||c==null?void 0:c.context());this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,i_.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return MVt({frontendTestGenerationConfig:{showFrontendLogs:i_.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{pf.error("Page closed")}),this.liveAppPage&&!i_.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new JWt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(b=>b.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(b=>b.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return pf.info("Waiting for frames to be available"),await FE(xMa),c(_-1);{let b="Could not connect to VTG frontend, check that the app is available";throw pf.error(b),new Error(b)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),f.on("console",_=>{let b=_.text();(b.includes("[VTG-DEBUG]")||b.includes("[FramesMsgBroker]"))&&console.log(`[BROWSER] ${b}`)}),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){pf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){pf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){pf.error("Error getting frame window",c)}})}catch(r){pf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new A9e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:pf.info,logError:pf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return $0t.makePage(a,r,this.injectedScriptManager)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await esi.promises.readFile(o,"utf8")}catch(c){return pf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(tsi.extname(o).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}e(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let b=await o.fetch(),C=b.status();if(C>299&&C<400){f++;let w=b.headers().location;if(!w){pf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${w}`),o.request().url=()=>new URL(w,c).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:b,headers:{...b.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}pf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){pf.warning("intercept error",c)}})}};e(HWt,"ChecksumVTGWebDriver");var WWt=HWt;var HHe=require("fs");var rsi=".settings.json",IKr=class IKr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${rsi}`:`${this.checksumRoot}/${rsi}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:i_.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:i_.vtg.aiAssertions.disabled,disableAILocators:i_.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,HHe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,HHe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,HHe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(IKr,"VtgSettingsService");var a1t=IKr;var i3e=require("fs");var PKr=class PKr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:C,...w}=this.cachedPromptData;return{...w,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),b=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:b.goal,steps:b.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){pf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(PKr,"ActionsAgent");var GWt=PKr;var FKr=class FKr extends p7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new eWe(c,r,a,this.remoteSessionId,{logPerformance:i_.vtg.aiAssertions.logPerformance}),this.actionsAgent=new GWt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw pf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return pf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw pf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return pf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){pf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw pf("No thought generated for action, got response",f),new Error("No thought generated");let b=r==="actions"?a.action:a.assertion;return pf(`Thought generated (${o})`,{type:r,stepId:b.id,locator:b.locator,thought:_.thought}),_}catch(f){throw pf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:b,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:b})},{id:r,thought:o,error:c,processId:a})}catch(f){pf.error("Error in AI thought generation",f)}}};e(FKr,"VTGThoughtsService");var KWt=FKr;var AMa=e(()=>{let t=new Error().stack.split(`
1921
+ `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";pf.info("REQUEST INFO",JSON.stringify(f,null,2));let b=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),b.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(i_.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");pf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(wKr,"VTGExpressServerRoutesLoggerMiddleware");var UWt=wKr;var SKr=class SKr{constructor(t,r,a,o,c,f,_,b,C,w,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=b;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{pf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new UWt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,qWt.default)(),this.app.use((0,Yai.default)()),this.app.use(Kai.default.json({limit:"50mb"})),this.app.use(qWt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(qWt.default.static(Xai.default.join(i_.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{pf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),pf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Gai.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new IWt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new OWt(this.storageService,this.actionsManager,this.actionsService),a=new BWt(this.aiTestGenerationService),o=new RWt(this.aiThoughtsService),c=new LWt(this.assertionsService,this.aiAssertionsService),f=new MWt(this.settingsService),_=new PWt(this.locatorsService),b=new FWt(this.monacoService),C=new NWt(this.aiChatService),w=new jWt(this.evaluatorService),T=[t,r,a,o,c,f,_,b,w,C],k=(0,Zai.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(SKr,"VtgExpressServer");var QWt=SKr;var $Wt=require("fs");var i1t=class i1t{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,$Wt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,$Wt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,$Wt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${i1t.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(i1t,"VtgTestAssetsManager"),i1t.AUTO_SAVE_FOLDER_NAME="auto-save";var VWt=i1t;var bMa={useCDPSession:!0,trackLoadedResources:!0},DKr=class DKr extends XVt{constructor(r={},a={devtools:!1},o={},c,f){super({...bMa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let b=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:b}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,b,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:b,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(DKr,"ChecksumWebDriver");var zWt=DKr;var esi=require("fs"),tsi=kf(require("path"));var TKr=require("fs");var kKr=class kKr{constructor(t,r,a=i_.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,pf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:i_.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw pf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(i_.vtg.appSource){case"served-app":t=i_.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=i_.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${i_.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(i_.vtg.appSource==="build-file")try{let t=await TKr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await TKr.promises.writeFile(this.filePath,a,"utf8"),pf(`Successfully modified ${this.filePath}`)}catch(t){pf.error(`Error processing file ${this.filePath}:`,t)}}};e(kKr,"VtgFrontendLauncher");var JWt=kKr;var xMa=1e3,HWt=class HWt extends zWt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,HWt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),i_.vtg.isSeparateProcess||c==null?void 0:c.context());this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,i_.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return MVt({frontendTestGenerationConfig:{showFrontendLogs:i_.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{pf.error("Page closed")}),this.liveAppPage&&!i_.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new JWt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(b=>b.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(b=>b.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return pf.info("Waiting for frames to be available"),await FE(xMa),c(_-1);{let b="Could not connect to VTG frontend, check that the app is available";throw pf.error(b),new Error(b)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){pf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){pf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){pf.error("Error getting frame window",c)}})}catch(r){pf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new A9e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:pf.info,logError:pf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return $0t.makePage(a,r,this.injectedScriptManager)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await esi.promises.readFile(o,"utf8")}catch(c){return pf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(tsi.extname(o).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}e(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let b=await o.fetch(),C=b.status();if(C>299&&C<400){f++;let w=b.headers().location;if(!w){pf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${w}`),o.request().url=()=>new URL(w,c).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:b,headers:{...b.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}pf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){pf.warning("intercept error",c)}})}};e(HWt,"ChecksumVTGWebDriver");var WWt=HWt;var HHe=require("fs");var rsi=".settings.json",IKr=class IKr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${rsi}`:`${this.checksumRoot}/${rsi}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:i_.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:i_.vtg.aiAssertions.disabled,disableAILocators:i_.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,HHe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,HHe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,HHe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(IKr,"VtgSettingsService");var a1t=IKr;var i3e=require("fs");var PKr=class PKr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:C,...w}=this.cachedPromptData;return{...w,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),b=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:b.goal,steps:b.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){pf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(PKr,"ActionsAgent");var GWt=PKr;var FKr=class FKr extends p7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new eWe(c,r,a,this.remoteSessionId,{logPerformance:i_.vtg.aiAssertions.logPerformance}),this.actionsAgent=new GWt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw pf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return pf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw pf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return pf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){pf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw pf("No thought generated for action, got response",f),new Error("No thought generated");let b=r==="actions"?a.action:a.assertion;return pf(`Thought generated (${o})`,{type:r,stepId:b.id,locator:b.locator,thought:_.thought}),_}catch(f){throw pf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:b,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:b})},{id:r,thought:o,error:c,processId:a})}catch(f){pf.error("Error in AI thought generation",f)}}};e(FKr,"VTGThoughtsService");var KWt=FKr;var AMa=e(()=>{let t=new Error().stack.split(`
1922
1922
  `).find(r=>r.includes(".checksum.spec.ts"));if(t)return{lineNumber:parseInt(t.split(":")[1]),columnNumber:parseInt(t.split(":")[2])}},"findCodeLocationFromStackTrace"),NKr=class NKr{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let t in this.store)Object.prototype.hasOwnProperty.call(this.store,t)&&delete this.store[t];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(t=>this.store[t])}setVariable(t,r){this.store[t]={name:t,value:r,type:r instanceof Function?"RandomValueGenerator":"FillValue"}}set(t,r,a){if(typeof r!="string")return!1;let o=AMa();return t.store[r]={name:r,value:a,type:a instanceof Function?"RandomValueGenerator":"FillValue",...o,line:""},!0}get(t,r){var a;if(r in t)return t[r];if(!(r in t.store))throw new Error(`Variable ${r} is not defined`);return t.activeVariablesSet.add(r),(a=t.store[r])==null?void 0:a.value}};e(NKr,"VariableStore");var YWt=NKr;var OKr=class OKr{constructor(t=new YWt){this._variableStore=t}get variableStore(){return this._variableStore}};e(OKr,"VTGVariableStoreService");var XWt=OKr;var GHe=kf(I8()),isi=require("net"),asi=require("crypto");var BKr=class BKr{constructor(t){this.processMessage=t;this.buffer=""}makeMessage(t){return`$CKSM_EVAL_MESSAGE:${t.length}$${t}`}async onMessage(t,r){for(this.buffer+=r.toString();;){let a=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!a)break;let o=parseInt(a[1],10),c=a[0].length,f=c+o;if(this.buffer.length<f)break;let _=this.buffer.slice(c,f);this.buffer=this.buffer.slice(f);try{let b=JSON.parse(_);await this.processMessage(b,t)}catch(b){console.error("Failed to parse message:",b)}}}};e(BKr,"VtgBridgeMessageParser");var ZWt=BKr;var af=kf(I8());var RKr=class RKr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=af.createSourceFile("snippet.ts",t,af.ScriptTarget.Latest,!0),a=new Set;af.forEachChild(r,b=>{af.isVariableStatement(b)&&b.declarationList.declarations.forEach(C=>{af.isIdentifier(C.name)?(a.add(C.name.text),this.declaredVariables.add(C.name.text)):(af.isArrayBindingPattern(C.name)||af.isObjectBindingPattern(C.name))&&(this.collectBindingNames(C.name,a),this.collectBindingNames(C.name,this.declaredVariables))})});let c=af.transform(r,[e(b=>{let C=b.factory,w=[new Map],T=e(B=>w[w.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(af.isBlock(B)||af.isFunctionLike(B)){if(w.push(new Map),af.forEachChild(B,W=>{if(af.isVariableStatement(W))for(let X of W.declarationList.declarations)af.isIdentifier(X.name)?w[w.length-1].set(X.name.text,X):(af.isArrayBindingPattern(X.name)||af.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,w[w.length-1])}),af.isFunctionLike(B))for(let W of B.parameters)af.isIdentifier(W.name)?(w[w.length-1].set(W.name.text,W),k.add(W.name.text)):(af.isArrayBindingPattern(W.name)||af.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,w[w.length-1]);let U=af.visitEachChild(B,R,b);return w.pop(),U}if(af.isArrowFunction(B))for(let U of B.parameters)af.isIdentifier(U.name)?(w[w.length-1].set(U.name.text,U),k.add(U.name.text)):(af.isArrayBindingPattern(U.name)||af.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,w[w.length-1]);if(af.isBinaryExpression(B)&&B.operatorToken.kind!==af.SyntaxKind.EqualsToken){let U=af.visitNode(B.left,R),W=af.visitNode(B.right,R);return C.createBinaryExpression(U,B.operatorToken,W)}if(af.isVariableDeclaration(B)&&B.initializer){let U=af.visitNode(B.initializer,R);return C.createVariableDeclaration(B.name,B.exclamationToken,B.type,U)}if(af.isVariableStatement(B)&&B.parent===r){let U=B.declarationList.declarations,W=[];for(let X of U)if(af.isObjectBindingPattern(X.name)||af.isArrayBindingPattern(X.name)){let ne=X.initializer?af.visitNode(X.initializer,R):void 0,ce=this.handleBindingPattern(X.name,ne,C,b);W.push(...ce.statements)}else if(af.isIdentifier(X.name)){let ne=X.name.text,ce=X.initializer?af.visitNode(X.initializer,R):void 0,fe=this.createGlobalAssignment(ne,ce,C);W.push(fe)}return W.length===0?C.createEmptyStatement():W.length===1?W[0]:C.createBlock(W,!0)}if(af.isIdentifier(B)&&!this.isLeftSideOfAssignment(B)&&!af.isPropertyAccessExpression(B.parent)&&!this.isPropertyOfElementAccess(B)&&!this.isDeclarationName(B)&&!this.isPropertyNameInObjectLiteral(B)&&!k.has(B.text)&&this.declaredVariables.has(B.text)){let U=B.text;return w[w.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,b)}if(af.isBinaryExpression(B)&&B.operatorToken.kind===af.SyntaxKind.EqualsToken&&af.isIdentifier(B.left)&&this.declaredVariables.has(B.left.text)&&!T(B.left.text)&&!k.has(B.left.text)){let U=B.left.text,W=af.visitNode(B.right,R);return C.createAssignment(this.createGlobalThisAccess(U,b),W)}if(af.isPropertyAccessExpression(B)&&af.isIdentifier(B.expression)&&this.declaredVariables.has(B.expression.text)&&!T(B.expression.text)&&!k.has(B.expression.text)){let U=B.expression.text,W=B.name.text,X=this.createGlobalThisAccess(U,b);return C.createPropertyAccessExpression(X,W)}return af.visitEachChild(B,R,b)},"visit");return B=>af.isSourceFile(B)?af.visitEachChild(B,R,b):af.visitNode(B,R)},"transformer")]),_=af.createPrinter().printFile(c.transformed[0]);return c.dispose(),_}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(t){this.declaredVariables.add(t)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(t,r){for(let a of t.elements)af.isBindingElement(a)&&(af.isIdentifier(a.name)?r.add(a.name.text):(af.isObjectBindingPattern(a.name)||af.isArrayBindingPattern(a.name))&&this.collectBindingNames(a.name,r))}collectBindingNamesForScope(t,r){for(let a of t.elements)af.isBindingElement(a)&&(af.isIdentifier(a.name)?r.set(a.name.text,a):(af.isObjectBindingPattern(a.name)||af.isArrayBindingPattern(a.name))&&this.collectBindingNamesForScope(a.name,r))}isInOuterScope(t){let r=t;for(;r.parent;){if(af.isFunctionLike(r.parent)||af.isBlock(r.parent)&&!af.isSourceFile(r.parent.parent))return!1;r=r.parent}return!0}isInShadowingTestCase(t){let r=af.isIdentifier(t)?t.text:"";if(r==="x"&&this.isInOuterConsoleLogOfNestedBlocks(t)||r==="b"&&this.isInFunctionScopeConsoleLog(t)||(r==="a"||r==="b")&&this.isInOutermostConsoleLog(t))return!1;let a=t.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(b=>a.includes(b)))return!1;let f=!1,_=t;for(;_.parent;){if(af.isCallExpression(_.parent)&&af.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"){f=!0;break}_=_.parent}return f}isInOutermostConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=t;for(;c.parent;)af.isCallExpression(c.parent)&&af.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(a=!0),af.isBlock(c.parent)&&c.parent.parent&&af.isFunctionDeclaration(c.parent.parent)&&(o=!0),c=c.parent;return a&&!o}isInFunctionScopeConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=!1,f=t;for(;f.parent;)af.isCallExpression(f.parent)&&af.isPropertyAccessExpression(f.parent.expression)&&f.parent.expression.name.text==="log"&&(a=!0),af.isBlock(f.parent)&&f.parent.parent&&af.isIfStatement(f.parent.parent)&&(o=!0),af.isBlock(f.parent)&&f.parent.parent&&af.isFunctionDeclaration(f.parent.parent)&&(c=!0),f=f.parent;return a&&c&&!o}isInOuterConsoleLogOfNestedBlocks(t){let r=!1,a=!1,o=!1,c=t;for(;c.parent;){if(af.isCallExpression(c.parent)&&af.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(r=!0),af.isBlock(c.parent)&&c.parent.parent&&af.isIfStatement(c.parent.parent)){let f=c.parent.parent;f.parent&&af.isBlock(f.parent)&&f.parent.parent&&af.isIfStatement(f.parent.parent)?a=!0:o=!0}c=c.parent}return r&&o&&!a}createGlobalThisAccess(t,r){let a=r.factory;return a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t))}createIsDeclaredCheck(t,r){let a=r.factory;return a.createConditionalExpression(a.createCallExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("isDeclared")),void 0,[a.createStringLiteral(t),a.createArrowFunction(void 0,void 0,[a.createParameterDeclaration(void 0,void 0,a.createIdentifier("c"))],void 0,a.createToken(af.SyntaxKind.EqualsGreaterThanToken),a.createCallExpression(a.createIdentifier("eval"),void 0,[a.createIdentifier("c")]))]),a.createToken(af.SyntaxKind.QuestionToken),a.createIdentifier(t),a.createToken(af.SyntaxKind.ColonToken),this.createGlobalThisAccess(t,r))}isLeftSideOfAssignment(t){return t.parent&&af.isBinaryExpression(t.parent)&&t.parent.operatorToken.kind===af.SyntaxKind.EqualsToken&&t.parent.left===t}isPropertyOfElementAccess(t){return t.parent&&af.isElementAccessExpression(t.parent)&&t.parent.argumentExpression===t}isDeclarationName(t){return t.parent&&(af.isVariableDeclaration(t.parent)||af.isParameter(t.parent)||af.isFunctionDeclaration(t.parent)||af.isClassDeclaration(t.parent)||af.isInterfaceDeclaration(t.parent)||af.isTypeAliasDeclaration(t.parent))&&t.parent.name===t}isPropertyNameInObjectLiteral(t){return t.parent&&af.isPropertyAssignment(t.parent)&&t.parent.name===t}testTransform(t){return this.transformVariables(t)}processComplexPatterns(t,r,a,o,c){for(let f of r)if(af.isObjectBindingPattern(f.name)||af.isArrayBindingPattern(f.name)){let _=[{pattern:f.name,parent:a}];for(;_.length>0;){let b=_.pop(),{pattern:C,parent:w}=b;for(let T of C.elements)if(af.isBindingElement(T)){if(T.dotDotDotToken){if(af.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(af.isArrayBindingPattern(C)){let U=C.elements.indexOf(T);R=t.createCallExpression(t.createPropertyAccessExpression(w,t.createIdentifier("slice")),void 0,[t.createNumericLiteral(U.toString())])}else{let U=[];for(let ce of C.elements)if(ce!==T&&af.isBindingElement(ce)&&!ce.dotDotDotToken){let fe=ce.propertyName?af.isIdentifier(ce.propertyName)?ce.propertyName.text:null:af.isIdentifier(ce.name)?ce.name.text:null;fe&&U.push(fe)}let W=U.map(ce=>t.createBindingElement(void 0,void 0,t.createIdentifier(ce),void 0));W.push(t.createBindingElement(t.createToken(af.SyntaxKind.DotDotDotToken),void 0,t.createIdentifier("rest"),void 0));let X=t.createVariableStatement(void 0,t.createVariableDeclarationList([t.createVariableDeclaration(t.createObjectBindingPattern(W),void 0,void 0,t.createIdentifier("tmp"))],af.NodeFlags.Const)),ne=t.createReturnStatement(t.createIdentifier("rest"));R=t.createCallExpression(t.createParenthesizedExpression(t.createArrowFunction(void 0,void 0,[t.createParameterDeclaration(void 0,void 0,t.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,t.createToken(af.SyntaxKind.EqualsGreaterThanToken),t.createBlock([X,ne],!0))),void 0,[w])}let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}continue}if(af.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(af.isObjectBindingPattern(C)){let U=T.propertyName&&af.isIdentifier(T.propertyName)?T.propertyName.text:k;R=t.createPropertyAccessExpression(w,t.createIdentifier(U))}else{let U=C.elements.indexOf(T);R=t.createElementAccessExpression(w,t.createNumericLiteral(U.toString()))}T.initializer&&(R=t.createConditionalExpression(t.createBinaryExpression(R,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),R));let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}else if(af.isObjectBindingPattern(T.name)||af.isArrayBindingPattern(T.name)){this.collectBindingNames(T.name,this.declaredVariables);let k;if(af.isObjectBindingPattern(C)){let R=T.propertyName&&af.isIdentifier(T.propertyName)?T.propertyName.text:null;R&&(k=t.createPropertyAccessExpression(w,t.createIdentifier(R)),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k}))}else if(af.isArrayBindingPattern(C)){let R=C.elements.indexOf(T);k=t.createElementAccessExpression(w,t.createNumericLiteral(R.toString())),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k})}}}}}}createGlobalAssignment(t,r,a){return a.createExpressionStatement(a.createAssignment(a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t)),r||a.createIdentifier("undefined")))}handleBindingPattern(t,r,a,o){let c=[],f=[];for(let _ of t.elements)if(af.isBindingElement(_)){if(_.dotDotDotToken&&af.isIdentifier(_.name)){let b=_.name.text;c.push(b);let C;if(af.isArrayBindingPattern(t)){let w=t.elements.indexOf(_);C=a.createCallExpression(a.createPropertyAccessExpression(r,a.createIdentifier("slice")),void 0,[a.createNumericLiteral(w)])}else C=this.createObjectRestHelper(_,t,r,a);f.push(this.createGlobalAssignment(b,C,a));continue}if(af.isIdentifier(_.name)){let b=_.name.text;c.push(b);let C;if(af.isObjectBindingPattern(t)){let w=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:b;C=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);C=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(C=a.createConditionalExpression(a.createBinaryExpression(C,a.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),C)),f.push(this.createGlobalAssignment(b,C,a))}else if(af.isObjectBindingPattern(_.name)||af.isArrayBindingPattern(_.name)){let b;if(af.isObjectBindingPattern(t)){let w=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!w)continue;b=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);b=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(b=a.createConditionalExpression(a.createBinaryExpression(b,a.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),b));let C=this.handleBindingPattern(_.name,b,a,o);c.push(...C.bindingNames),f.push(...C.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let b of r.elements)if(b!==t&&af.isBindingElement(b)&&!b.dotDotDotToken){let C=b.propertyName&&af.isIdentifier(b.propertyName)?b.propertyName.text:af.isIdentifier(b.name)?b.name.text:null;C&&c.push(C)}let f=[];for(let b of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(b),void 0));f.push(o.createBindingElement(o.createToken(af.SyntaxKind.DotDotDotToken),void 0,o.createIdentifier("rest"),void 0));let _=[o.createVariableStatement(void 0,o.createVariableDeclarationList([o.createVariableDeclaration(o.createObjectBindingPattern(f),void 0,void 0,o.createIdentifier("obj"))],af.NodeFlags.Const)),o.createReturnStatement(o.createIdentifier("rest"))];return o.createCallExpression(o.createParenthesizedExpression(o.createArrowFunction(void 0,void 0,[o.createParameterDeclaration(void 0,void 0,o.createIdentifier("obj"),void 0,void 0,void 0)],void 0,o.createToken(af.SyntaxKind.EqualsGreaterThanToken),o.createBlock(_,!0))),void 0,[a])}};e(RKr,"VariableTransformer");var eHt=RKr;var EMa=e(i=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(t,r){if(["log","info","warn","error","debug"].includes(r))return(...o)=>{t[r](...o);try{i.evaluate(c=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:c})},{level:r,args:o.map(c=>{try{return typeof c=="object"?JSON.stringify(c):String(c)}catch{return String(c)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:i._guid}).catch(c=>{})}catch{}};let a=t[r];return typeof a=="function"?a.bind(t):a}})},"consoleOverride");function nsi(i,t){return`
1923
1923
  try {
1924
1924
  (${EMa.toString()})(page);