@checksum-ai/runtime 1.3.8 → 1.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1824,7 +1824,7 @@ ${this.executedSteps.map(c=>{switch(c.type){case"action":return c.thought;case"a
1824
1824
  `)[4].trim().match(/\(([^)]+)\)/);if(!(c&&c[1]))throw new Error;let f=c[1].split(":"),_=f.slice(0,-2).join(":"),b=f[f.length-2],w=`${T8n.default.basename(_)}:${b}`;a&&(console.log("\x1B[34m",w,"\x1B[0m",...r),setTimeout(()=>this.listeners.forEach(T=>T.onLog(...r)),0)),this.logStream&&this.logStream.write(`[${w}] ${r.map(T=>{if(typeof T=="object")try{return JSON.stringify(T,null,2)}catch{}return String(T)}).join(" ")}
1825
1825
  `)}catch{a&&console.log(...r)}}shouldLog(t){switch(t){case"warning":return this.logLevel==="all"||this.logLevel==="warnings";case"error":return!0;case"info":return this.logLevel==="all"}}addListener(t){this.listeners.push(t)}info(...t){this.log("info",...t)}warning(...t){this.log("warning",...t)}error(...t){this.log("error",...t)}setLogLevel(t){this.logLevel=t}setLogStream(t){this.logStream=t}};e(YPr,"Logger");var KPr=YPr,O9e=new KPr,Mea=Object.assign((...i)=>O9e.info(...i),{info:e((...i)=>O9e.info(...i),"info"),warning:e((...i)=>O9e.warning(...i),"warning"),error:e((...i)=>O9e.error(...i),"error"),setLogLevel:e(i=>O9e.setLogLevel(i),"setLogLevel"),setLogStream:e(i=>O9e.setLogStream(i),"setLogStream"),addLogListener:e(i=>O9e.addListener(i),"addLogListener")}),cf=Mea;var q0t=uf(bOn());var M0t=require("perf_hooks");var NRr=class NRr{constructor(t={}){this.options=t;this.priorityQueue=[];this.nonPriorityQueue=[];this.isRunning=!1;this.taskIndex=0;this.timeRunningTasks=0;this.timeGoingBack=0;this.tasksExecuted=0}enqueue(t){let r=this.taskIndex++,a={...t,index:r,queuedAt:M0t.performance.now()};if(t.priority)this.priorityQueue.push(a);else if(this.options.sortByTimestamp){let o=this.nonPriorityQueue.findIndex(c=>c.timestamp>t.timestamp);o===-1?this.nonPriorityQueue.push(a):this.nonPriorityQueue.splice(o,0,a)}else this.nonPriorityQueue.push(a);return r}popTask(){return this.priorityQueue.length>0?this.priorityQueue.shift():this.nonPriorityQueue.shift()}async runTasks(t){if(!this.isRunning){this.isRunning=!0;try{for(;this.getQueueLength()>0;){let r=this.popTask();if(!r)break;let a=M0t.performance.now();try{if(this.options.logPerformance){let c=M0t.performance.now()-r.queuedAt;cf.info(`Running task, timestamp: ${r.timestamp} \x1B[36m${r.name}\x1B[0m, index: ${r.index}, was pending for ${c}ms`)}await t(r);let o=M0t.performance.now()-a;this.timeRunningTasks+=o,this.options.logPerformance&&cf.info("Finished running task, took",o,"ms.","Queue lengths:",`priority=${this.priorityQueue.length}`,`non-priority=${this.nonPriorityQueue.length}`),this.tasksExecuted++}catch(o){cf.error("Task execution error:",o)}}}finally{this.isRunning=!1,this.getQueueLength()>0&&this.options.logPerformance&&cf.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}}getTasksAtTimestamp(t){return[...this.priorityQueue.filter(r=>r.timestamp===t),...this.nonPriorityQueue.filter(r=>r.timestamp===t)]}removeTasksAtTimestamp(t){this.priorityQueue=this.priorityQueue.filter(r=>r.timestamp!==t),this.nonPriorityQueue=this.nonPriorityQueue.filter(r=>r.timestamp!==t)}getQueueLength(){return this.priorityQueue.length+this.nonPriorityQueue.length}setTimeGoingBack(t){this.timeGoingBack=t}};e(NRr,"TaskTimeMachineQueue");var j0t=NRr;var U0t=require("perf_hooks");var ORr=class ORr{constructor(t,r,a={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0}){this.frameMsgBroker=t;this.injectedScriptManager=r;this.options=a;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.currentChecksumId="0";this.timeGoingBack=0;this.pagesWithCorsInterception=new Set;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(t,{retriesLeft:r=3,retryWaitMS:a=1e3}={})=>{try{let{reducedHTML:o,currentChecksumId:c}=await t.evaluate(async f=>{var _,b;return(b=(_=window==null?void 0:window.checksum)==null?void 0:_.testGenerator)==null?void 0:b.reduceHTML({},f)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=c,{reducedHTML:o}}catch(o){if(r>0)return await rA(a),this.getReducedHTMLWithRetries(t,{retriesLeft:r-1,retryWaitMS:a});throw o}},"getReducedHTMLWithRetries");if(this.taskQueue=new j0t({sortByTimestamp:a.sortByTimestamp,logPerformance:a.logPerformance}),a.webProxy){let{username:o,password:c,server:f}=a.webProxy;o&&c?this.webProxyAgent=new q0t.ProxyAgent({uri:`http://${o}:${c}@${f.replace("http://","")}`}):this.webProxyAgent=new q0t.ProxyAgent({uri:f})}}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(t,r,a){this.recordingFrame=t,this.frameMsgBroker.register("live",t),r?this.timeMachineFrame=r:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),await this.preventCrossOriginErrors(this.timeMachineFrame),this.options.frameMsgBrokerRegisterName&&this.frameMsgBroker.register(this.options.frameMsgBrokerRegisterName,this.timeMachineFrame),a&&a(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.timeMachineFrame.page().on("framenavigated",async o=>{await this.injectedScriptManager.onFrameNavigated(o)}),this.subscribeToRrwebEvents(),this.taskQueue=new j0t({sortByTimestamp:this.options.sortByTimestamp,logPerformance:this.options.logPerformance}),await this.start()}async preventCrossOriginErrors(t){try{let r=t.page(),a=CI(r);if(this.pagesWithCorsInterception.has(a))return;this.pagesWithCorsInterception.add(a),await r.route(/^https?:\/\/(?!(?:localhost|127\.0\.0\.1|::1)).*/,async(o,c)=>{var b;let _=o.request().url();try{let C=this.webProxyAgent?{dispatcher:this.webProxyAgent}:{},w=await(0,q0t.fetch)(_,C),T=w.status,k={};w.headers.forEach((ne,ce)=>k[ce]=ne),k["access-control-allow-origin"]="*";let R=parseInt(w.headers.get("content-length")||"0",10),B=25*1024*1024;if(R>B)return o.continue();if(!w.body){await o.fulfill({status:T,headers:k});return}let W=await w.arrayBuffer(),X=Buffer.from(W);await o.fulfill({status:T,headers:k,body:X})}catch(C){return(b=C.cause)==null||b.code,o.continue()}})}catch{}}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(t){this.timeMachineBrowserContext=t}async executeTask(t,r=void 0,{name:a,beforeTimestamp:o=!1,priority:c=!1}={}){return new Promise((f,_)=>{let b=e(async({shouldGoBack:C,shouldBatch:w}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&_(),C){let R=U0t.performance.now();await this.goBack(r,o),this.timeGoingBack+=U0t.performance.now()-R,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}let T=e(R=>async()=>{try{let B=U0t.performance.now(),U=await pD(R(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${a}, took ${U0t.performance.now()-B}ms with timeout of ${this.options.taskTimeout}ms`);f(U)}catch(B){cf.error("Task execution error:",B.message),_(B)}},"makeSafeRunTask"),k=[T(t)];if(this.taskQueue.getQueueLength()>0&&w){let R=this.taskQueue.getTasksAtTimestamp(r);k.push(...R.map(({task:B})=>T(()=>B({shouldGoBack:!1,shouldBatch:!1})))),this.taskQueue.removeTasksAtTimestamp(r),k.length&&console.log(`Batching to task "${a}" ${k.length-1} more tasks`)}for(let R of k)await R()},"taskWrapper");this.taskQueue.enqueue({name:a,task:b,timestamp:o?r-1:r,priority:c}),this.runTasks()})}executeReducedHTMLTask(t,{priority:r=!1}={}){if(this.reducedHTMLCache[t]){let a=new Ddt(this.reducedHTMLCache[t]);return Promise.resolve(a.getRrwebIdsReducedDomString())}return this.executeTask(async a=>{let o="",c=await this.getReducedHTMLWithRetries(a);return o=c==null?void 0:c.reducedHTML,o&&(this.reducedHTMLCache[t]=o),new Ddt(o).getRrwebIdsReducedDomString()},t,{name:"getReducedHTMLForTimestamp",priority:r})}goBack(t,r=!1){return this.currentBeforeTimestamp===r&&this.currentTimestamp===t?Promise.resolve():(this.currentTimestamp=t,this.currentBeforeTimestamp=r,this.timeMachineFrame.evaluate(({timestamp:a,beforeTimestamp:o})=>a===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(a,{beforeTimestamp:o}),{timestamp:t,beforeTimestamp:r}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}async runTasks(){await this.taskQueue.runTasks(async t=>{await t.task()})}async rrwebEventHandler(t){let r=JSON.stringify(t);try{await this.timeMachineFrame.evaluate(function(a){let o=JSON.parse(a);return window.checksum.timeMachine.handleEvents(o)},r)}catch{}return t=null,r}async makeBrowserContext(){let t=[];this.options.debugPort&&t.push(`--remote-debugging-port=${this.options.debugPort}`);let r=await xOn.chromium.launch({devtools:!1,headless:this.options.headless,args:t});return this.timeMachineBrowserContext=await r.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let t="rrweb";this.frameMsgBroker.subscribeToChannel(t,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler.bind(this)}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(t,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(t){try{await this.timeMachineFrame.evaluate(r=>window.checksum.timeMachine.setShouldHandleEvents(r),t)}catch{}}};e(ORr,"ChecksumTimeMachine");var Jve=ORr;var BRr=require("@playwright/test"),Q0t=uf(require("fs")),AOn=uf(require("fs/promises")),EOn=uf(require("readline")),COn=uf(require("path")),wOn=uf(PBt());var Gda=1e3,RRr=class RRr extends Jve{constructor(r,a,o={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(r,a,o);this.options=o;this.rrwebEventsBuffer="";this.didPostProcessRRwebEvents=!1;this.postProcessRRwebEvents=(0,wOn.debounce)(async()=>{return;try{let a=Q0t.default.createReadStream(this.options.recordRRwebEventsToFilePath),o=EOn.default.createInterface({input:a,crlfDelay:1/0});for await(let c of o)if(c.trim()!=="")try{let f=JSON.parse(c);Array.isArray(f)?r.push(...f):r.push(f)}catch(f){Qv(`Failed to parse line: ${c}`,f)}Q0t.default.writeFileSync(this.options.recordRRwebEventsToFilePath.replace(/([^\/]+)$/,"postprocessed.$1"),JSON.stringify(r)),this.didPostProcessRRwebEvents=!0}catch(a){Qv("Error post-processing RRweb events",a)}},100,{leading:!0,trailing:!0});if(this.options.recordRRwebEventsToFile){let c=this.options.recordRRwebEventsToFilePath,f=COn.default.dirname(c);Q0t.default.mkdirSync(f,{recursive:!0}),Q0t.default.writeFileSync(c,"")}}setTimeMachineBrowserContext(r){this.timeMachineBrowserContext=r}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){BRr.chromium._checksumInternal=!0;let r=await BRr.chromium.launch({devtools:!1,headless:this.options.headless,args:Gm.useRemoteDebugging.enabled?["--remote-debugging-port=4444"]:[]});return r._checksumInternal=!0,this.timeMachineBrowserContext=await r.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.startChunk=async()=>{},this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let r=await this.timeMachineBrowserContext.newPage();r._checksumInternal=!0;let a=r.mainFrame();return a._checksumInternal=!0,a}async rrwebEventHandler(r){let a=await super.rrwebEventHandler(r);if(this.options.recordRRwebEventsToFile){if(this.rrwebEventsBuffer+=a+`
1826
1826
  `,this.rrwebEventsBuffer.length>Gda){let o=this.rrwebEventsBuffer;this.rrwebEventsBuffer="",this.flushRRwebEventsToFile(o)}return a}}async flushRRwebEventsToFile(r){if(this.options.recordRRwebEventsToFile){r??(r=this.rrwebEventsBuffer);try{await AOn.default.appendFile(this.options.recordRRwebEventsToFilePath,r)}catch(a){Qv(a)}}}getRRwebFilePath(){return this.options.recordRRwebEventsToFilePath}};e(RRr,"RuntimeTimeMachine");var nqt=RRr;var TOn=uf(require("path"));var SOn=!1,MRr=class MRr{constructor(t,r,a){this.frame=t;this.base=r;this.getAnalytics=a;this.LOCATORS_TIMEOUT=SOn?9999999:5e3;this.HANDLES_TIMEOUT=SOn?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.frame)}setBase(t){this.base=t}setAnalytics(t){this.getAnalytics=t}init(...t){return this.sanitizeArgs(...t),new Proxy(this,{get:e((r,a)=>a==="setBase"?function(...o){this.setBase(o[0])}.bind(this):a==="setAnalytics"?function(...o){this.setAnalytics(o[0])}.bind(this):this.handleLocatorChain(r,a),"get")})}getLocatorSelector(t){if(t)return t._selector}sanitizeArgs(...t){if(t.length===1&&typeof t[0]=="object"){if(!t[0].anchors||typeof t[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=t[0].anchors,this.targetLocatorMethod=t[0].target;return}if(typeof t[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=t[0],t.length===2){if(typeof t[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=t[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;Qv("Waiting for locators..");let t=this.getLocatorsFromMethods();if(t.find(_=>!("_selector"in _)))throw new Error("Can't resolve at least one locator, make sure anchors and target are valid locators or strings");try{await Promise.all(t.map(async _=>pD(_.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(_){throw new Error(`Error while waiting for locators - ${_.message}`)}let r=await pD(this.getElementHandles(t),this.HANDLES_TIMEOUT);Qv(`Resolved to ${LRr(r)} elements from ${t.length} locators`);let a=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.frame)[0]),o=await this.frame.evaluate(async({handles:_,targetSelector:b})=>window.checksum.testGenerator.getCompoundSelector().select(_,b),{handles:r,targetSelector:a});if(!o||o.length===0)throw new Error("Could not generate selectors from handles");Qv(`Resolved compound selector to ${o.length} selectors`);let c=this.getBase(),f=c.locator(o[0]);return o.slice(1,50).forEach(_=>{f=f.or(c.locator(_))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:_,args:b})=>{f=f[_](...b)}),Qv(`Compound locator selector: ${this.getLocatorSelector(f)}`),this.resolvedLocator=f,f}handleLocatorChain(t,r){if(typeof r=="symbol")return;if(r==="constructor")return e(function(...f){return this[r](...f)},"Locator");if(r==="toString")return()=>this.toString();let a=e(()=>new Proxy(t,{get:e((c,f)=>c.handleLocatorChain(c,f),"get")}),"createLocatorProxy");return r==="valueOf"?e(function(){return a()},"Locator"):r==="then"?(c,f)=>{this.resolveLocator().then(_=>c(_)).catch(f)}:Object.values([...Object.values(yme),...Object.values(e$e)]).includes(r)?e(function(...f){return t.locatorsChain.push({name:r,args:f}),a()},"Locator"):e(async function(...f){return this.handleAction(r,f)},"Locator").bind(this)}async handleAction(t,r){var a,o;try{if(typeof t=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let c=await this.resolveLocator();return this.frame.executeLocatorAction?await this.frame.executeLocatorAction(c,t,r):await c[t](...r)}catch(c){throw Qv(`Failed to execute compound selection action: ${c}`),(o=(a=this.getAnalytics)==null?void 0:a.call(this))==null||o.compoundSelectionFailure({error:c.toString(),selector:this.toString()}),c}}async getElementHandles(t){Qv("Resolving compound selector elements");let r,a,o,c,f,_=e(()=>{f=2},"resetSameHandlesCount");do r=a,a=[],await Promise.all(t.map(async b=>{let C=await b.elementHandles({bypassChecksum:!0});if(C.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(b)}`);a.push(C)})),o=LRr(a),c=r?LRr(r):0,Qv(`Handles itteration, previous: ${r?c:"-"}, current: ${o}`),c!==o&&_(),await rA(this.HANDLES_INTERVAL);while(!r||c!==o||--f>0);return a}getLocatorsFromMethods(t=!0,r=!0,a=this.getBase()){return(t?this.anchorLocatorMethod(a):[]).concat(r&&this.targetLocatorMethod?[this.targetLocatorMethod(a)]:[]).map(o=>typeof o=="string"?a.getByText(o):o)}getBase(){return this.base}toString(){var t;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(t=this.targetLocatorMethod)==null?void 0:t.toString()})`})`}};e(MRr,"CompoundSelectorLocator");var Nze=MRr,LRr=e(i=>i.reduce((t,r)=>t+r.length,0),"countHandleElements");var jRr=require("path");var DOn=require("fs");var Kda=!0,URr=class URr{constructor(t){this.options=t;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async t=>{let r=CI(t);if(this.trackedFramesGuid.includes(r))return this.frameNavigationPromises[r]=new Promise(async a=>{await this.loadScript(t),a()}),this.frameNavigationPromises[r]},"onFrameNavigated");this.loadScript=e(async(t,{retriesLeft:r=3,retryWaitMS:a=2e3,useWrapper:o=!0}={})=>{var b,C;if(o&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(t,{retriesLeft:r,retryWaitMS:a,useWrapper:!1}),t);if(!this.addScriptTagOptions){this.log.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(t))return;let c=!1;try{c=this.scriptLoadCheck?await((b=this.scriptLoadCheck)==null?void 0:b.call(this,t)):!1}catch{}if(c||this.isFrameClosed(t))return;this.options.scriptAddWait&&(this.log.log(`Waiting ${this.options.scriptAddWait}[ms] before adding script...`),await rA(this.options.scriptAddWait),this.log.log("Done waiting before adding script"));try{await t.addScriptTag(await this.makeInjectedScriptOptionsForAddScriptTag())}catch(w){if(r>0)return this.log.warn(`[InjectedScriptManager] Failed to add script to frame ${CI(t)}, trying again in ${a/1e3} seconds, ${r-1} retries left.`,w.message),await rA(a),this.loadScript(t,{retriesLeft:r-1,retryWaitMS:a,useWrapper:o});throw w}let f=CI(t),_=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[f]=_,this.options.scriptInitWait&&(this.log.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await rA(this.options.scriptInitWait),this.log.log("Done waiting before onScriptLoad")),!this.isFrameClosed(t)){if(this.navigatingFrames[f]&&this.navigatingFrames[f]!==_)return this.log.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[f];try{await((C=this.scriptLoadCallback)==null?void 0:C.call(this,t))}catch(w){this.log.error("[WebDriver] onScriptLoad error",w)}}},"loadScript");this.log=new Proxy(console,{get:e((t,r)=>(...a)=>{if(!this.options.silenceLogs)return t[r].apply(t,a)},"get")});this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(t){return this.scriptLoadCallback=t,this}setScriptLoadCheck(t){return this.scriptLoadCheck=t,this}setScriptLoadWrapper(t){return this.scriptLoadWrapper=t,this}async addTrackedFrame(t,r=!0){let a="mainFrame"in t?t.mainFrame():t,o=CI(a);if(this.trackedFramesGuid.includes(o)||this.trackedFramesGuid.push(o),r)return this.onFrameNavigated(a)}getNavigationPromise(t){if(!t){this.log.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let r=typeof t=="string"?t:"mainFrame"in t?CI(t.mainFrame()):CI(t);return this.frameNavigationPromises[r]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,jRr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}async makeInjectedScriptOptionsForAddScriptTag(){if(this.options.scriptSource==="url"&&this.addScriptTagOptions.url&&Kda){let r=await(await fetch(this.addScriptTagOptions.url)).text(),a=(0,jRr.join)(process.cwd(),"checksumlib.js");return(0,DOn.writeFileSync)(a,r),{path:a}}return this.addScriptTagOptions}isFrameClosed(t){return t.isDetached()||t.page().isClosed()}};e(URr,"InjectedScriptManager");var Oze=URr;var VRr=class VRr{constructor(t){this.options=t}async handleError(t,r,a){let o=`Error in ${r} action during ${t} execution: ${a.message}`;throw new Error(o)}async guardedExecute(){try{return await(this.options.timeout!=null?pD(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(t){return this.handleError(this.options.method,this.constructor.name,t)}}};e(VRr,"Action");var iqt=VRr,zRr=class zRr extends iqt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(zRr,"PlaywrightAction");var qRr=zRr,JRr=class JRr extends iqt{constructor(r,a){super(r);this.pageInteractor=a}};e(JRr,"APIAction");var QRr=JRr,WRr=class WRr extends QRr{constructor(t,r){super(t,r.pageInteractor)}async execute(){try{let{locator:t,args:r}=this.options,[a,o]=r,c=await t.screenshot({timeout:3e4}),_=(await this.pageInteractor.getTextDetection(c)).getRectangleByTextAndSizeRanking(a,o);if(!_)throw new Error("No matching text found");await t.click({position:_.center})}catch(t){throw new Error(`Error in canvas click action: ${t.message}`)}}};e(WRr,"CanvasClickAction");var $Rr=WRr,sqt=class sqt{static createAction(t,r){return t.method in this.customActionMap?new this.customActionMap[t.method]({...t,timeout:15e3},r):new qRr(t)}};e(sqt,"ActionFactory"),sqt.customActionMap={canvasClick:$Rr};var aqt=sqt;var uqt=class uqt{constructor(t,r,a,o,c,f,_){this.frame=t;this.checksumPage=r;this.isReplMode=a;this.config=o;this.injectedScriptManager=c;this.getPageInteractor=f;this.onExecutionError=_;this.locatorStack=[];this.setFrameProxy(),this.checksumClient=new I$e({apiURL:this.config.apiURL,apiKey:this.config.apiKey})}static init(t,r,a,o,c,f,_=!1){return new uqt(t,r,_,f,a,o,c).proxy}setFrameProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.handleFrameMethod(a)},"get")})}handleFrameMethod(t){if(typeof t!="symbol")return typeof this[t]=="function"?t==="constructor"?this[t]:this[t].bind(this):[...Object.values(yme),...Object.values(e$e)].includes(t)?(this.pushToLocatorStack([{type:t,base:this.frame}]),e(function(a,o){try{return this.executeLocator(a,o)}catch(c){throw this.popLocatorChain(),c}},"Locator").bind(this)):this.frame[t]}page(){return this.checksumPage}compoundSelection(...t){var r;try{let a=this.locatorStack.length?(r=this.getCurrentLocatorInChain())==null?void 0:r.base:this.proxy;return new Nze(this.proxy,a).init(...t)}catch{throw new Error("Failed generating compound selector")}}async wrapInternalSteps(t,r=this.frame){try{return r._checksumInternal=!0,await t()}finally{r._checksumInternal=!1}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.frame)}pushToLocatorStack(t){this.locatorStack.push(t)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let t=this.getCurrentLocatorChain();return t==null?void 0:t[t.length-1]}getLocator(t,r){let a=this.getCurrentLocatorInChain();return a.base[a.type](t,r)}executeLocator(t,r){try{Qv(`
1827
- Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Qv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(yme),...Object.values(e$e)].includes(a)?["or","and"].includes(a)?(Qv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Qv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Qv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Qv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Qv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Qv("[executeLocatorAction] checksum libs not loaded")}}),await aqt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Qv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Qv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,b;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(b=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:b.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(uqt,"ChecksumFrame");var oqt=uqt;var cqt=class cqt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new Oze({scriptFile:Gm.checksumScript.path,scriptSource:Gm.checksumScript.source,scriptURL:Gm.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!Gm.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(b=>this.registerFrame(b)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=lqt();return new cqt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=oqt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(yme).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>TOn.join(eft(Nne()),r))}compoundSelection(...t){try{return new Nze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(cqt,"ChecksumPage");var Bze=cqt;Dqr();II();var dbe=class dbe{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Nh.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=dbe.describeTool(f,_):a[c]=f}return Nh.object(a).strict()}if(t instanceof Nh.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Nh.array(dbe.describeTool(a,r.element)):t}return t instanceof Nh.ZodOptional?dbe.describeTool(t.unwrap(),r).optional():t instanceof Nh.ZodNullable?dbe.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=dbe.describeTool(f,r.params),C=Aqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],b=dbe.describeTool(_,{});return Aqr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(dbe,"AbstractToolContainer");var n7e=dbe;II();var D$t=class D$t{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>b=>{let C=b.name??_;return{...b,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new D$t(t,r)}};e(D$t,"ToolProtocol");var S$t=D$t;var Aj=S$t.create("v1",{readFile:Nh.object({path:Nh.string()}),getState:Nh.object({thought:Nh.string()}),invokeCode:Nh.object({code:Nh.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Nh.string()}),wait:Nh.object({time:Nh.number().optional()}),scroll:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),final_result:Nh.object({result:Nh.enum(["pass","fail"]),thought:Nh.string(),visualAnalysis:Nh.string().optional()}),getElementScreenshot:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),analyze:Nh.object({previousImmediateSteps:Nh.string(),currentFailingStep:Nh.string(),nextImmediateSteps:Nh.string(),testStepToStopAt:Nh.string()}),think:Nh.object({thought:Nh.string()})});var $qr=uf(lqn(),1);var Mce=Object.create(null);Mce.open="0";Mce.close="1";Mce.ping="2";Mce.pong="3";Mce.message="4";Mce.upgrade="5";Mce.noop="6";var Umt=Object.create(null);Object.keys(Mce).forEach(i=>{Umt[Mce[i]]=i});var qmt={type:"error",data:"parser error"};var Qmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+pqn(t,!0).toString("base64")):a(Mce[i]+(t||"")),"encodePacket"),pqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),kqr;function fqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(pqn(i.data,!1));Qmt(i,!0,r=>{kqr||(kqr=new TextEncoder),t(kqr.encode(r))})}e(fqn,"encodePacketToBinary");var $mt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:dqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:dqn(a,t)}}return Umt[r]?i.length>1?{type:Umt[r],data:i.substring(1)}:{type:Umt[r]}:qmt},"decodePacket"),dqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var mqn="",_qn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{Qmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(mqn))})})},"encodePayload"),hqn=e((i,t)=>{let r=i.split(mqn),a=[];for(let o=0;o<r.length;o++){let c=$mt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function gqn(){return new TransformStream({transform(i,t){fqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(gqn,"createPacketEncoderStream");var Iqr;function T$t(i){return i.reduce((t,r)=>t+r.length,0)}e(T$t,"totalLength");function k$t(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(k$t,"concatChunks");function yqn(i,t){Iqr||(Iqr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(T$t(r)<1)break;let b=k$t(r,1);c=(b[0]&128)===128,o=b[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(T$t(r)<2)break;let b=k$t(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(T$t(r)<8)break;let b=k$t(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(qmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(T$t(r)<o)break;let b=k$t(r,o);_.enqueue($mt(c?b:Iqr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(qmt);break}}}})}e(yqn,"createPacketDecoderStream");var Pqr=4;var Oqn=uf(WPe(),1);var mbe=process.nextTick,Ez=global,bqn="nodebuffer";function xqn(){return new Fqr}e(xqn,"createCookieJar");function c2a(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let b=_[0].trim(),C=_[1].trim();switch(b){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(c2a,"parse");var Nqr=class Nqr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=c2a(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(Nqr,"CookieJar");var Fqr=Nqr;function I$t(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(I$t,"pick");var l2a=Ez.setTimeout,p2a=Ez.clearTimeout;function _be(i,t){t.useNativeTimers?(i.setTimeoutFn=l2a.bind(Ez),i.clearTimeoutFn=p2a.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(_be,"installTimerFunctions");var f2a=1.33;function Aqn(i){return typeof i=="string"?d2a(i):Math.ceil((i.byteLength||i.size)*f2a)}e(Aqn,"byteLength");function d2a(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(d2a,"utf8Length");function P$t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(P$t,"randomString");function Eqn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(Eqn,"encode");function Cqn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(Cqn,"decode");var Bqn=uf(KPe(),1);var R2a=(0,Bqn.default)("engine.io-client:transport"),Mqr=class Mqr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(Mqr,"TransportError");var R$t=Mqr,jqr=class jqr extends Oqn.Emitter{constructor(t){super(),this.writable=!1,_be(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new R$t(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):R2a("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=$mt(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=Eqn(t);return r.length?"?"+r:""}};e(jqr,"Transport");var hbe=jqr;var Rqn=uf(KPe(),1);var jce=(0,Rqn.default)("engine.io-client:polling"),Uqr=class Uqr extends hbe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{jce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(jce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){jce("pre-pause polling complete"),--a||r()})),this.writable||(jce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){jce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){jce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){jce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");hqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():jce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{jce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(jce("transport open - closing"),t()):(jce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,_qn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=P$t()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(Uqr,"Polling");var zmt=Uqr;var Uqn=uf(WPe(),1);var Lqn=!1;try{Lqn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Mqn=Lqn;var qqn=uf(KPe(),1);var qqr=(0,qqn.default)("engine.io-client:polling");function L2a(){}e(L2a,"empty");var Qqr=class Qqr extends zmt{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){qqr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(Qqr,"BaseXHR");var L$t=Qqr,TJe=class TJe extends Uqn.Emitter{constructor(t,r,a){super(),this.createRequest=t,_be(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=I$t(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{qqr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},qqr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=TJe.requestsCount++,TJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=L2a,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete TJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(TJe,"Request");var gbe=TJe;gbe.requestsCount=0;gbe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",jqn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,jqn,!1)}}function jqn(){for(let i in gbe.requests)gbe.requests.hasOwnProperty(i)&&gbe.requests[i].abort()}e(jqn,"unloadHandler");var u7s=function(){let i=M2a({xdomain:!1});return i&&i.responseType!==null}();function M2a(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Mqn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e(M2a,"newRequest");var j2a=$qr.default||$qr,Vqr=class Vqr extends L$t{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new gbe(a=>new j2a(a),this.uri(),t)}};e(Vqr,"XHR");var kJe=Vqr;var Gva=uf(zqn(),1),Kva=uf(iQr(),1),Yva=uf(sQr(),1),bQr=uf(gQr(),1),Xva=uf(QQn(),1);var $Qn=uf(KPe(),1);var eba=(0,$Qn.default)("engine.io-client:websocket"),tba=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",xQr=class xQr extends hbe{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=tba?{}:I$t(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;Qmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{eba("websocket closed before onclose event")}o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=P$t()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(xQr,"BaseWS");var Y$t=xQr,H7s=Ez.WebSocket||Ez.MozWebSocket;var AQr=class AQr extends Y$t{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new bQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(AQr,"WS");var OJe=AQr;var VQn=uf(KPe(),1);var r_t=(0,VQn.default)("engine.io-client:webtransport"),EQr=class EQr extends hbe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{r_t("transport closed gracefully"),this.onClose()}).catch(t=>{r_t("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=yqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=gqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){r_t("session is closed");return}r_t("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{r_t("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(EQr,"WT");var BJe=EQr;var CQr={websocket:OJe,webtransport:BJe,polling:kJe};var rba=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nba=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function RJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=rba.exec(i||""),c={},f=14;for(;f--;)c[nba[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=iba(c,c.path),c.queryKey=aba(c,c.query),c}e(RJe,"parse");function iba(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(iba,"pathNames");function aba(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(aba,"queryKey");var zQn=uf(WPe(),1);var JQn=uf(KPe(),1);var C7=(0,JQn.default)("engine.io-client:socket"),wQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",n_t=[];wQr&&addEventListener("offline",()=>{C7("closing %d connection(s) because the network was lost",n_t.length),n_t.forEach(i=>i())},!1);var LJe=class LJe extends zQn.Emitter{constructor(t,r){if(super(),this.binaryType=bqn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=RJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=RJe(r.host).host);_be(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Cqn(this.opts.query)),wQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(C7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},n_t.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=xqn()),this._open()}createTransport(t){C7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=Pqr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return C7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&LJe.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){C7("setting transport %s",t.name),this.transport&&(C7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){C7("socket open"),this.readyState="open",LJe.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(C7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else C7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();C7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=Aqn(o)),a>0&&r>this._maxPayload)return C7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return C7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(C7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,mbe(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),C7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(C7("socket error %j",t),LJe.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return C7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(C7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),wQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=n_t.indexOf(this._offlineEventListener);a!==-1&&(C7("removing listener for the 'offline' event"),n_t.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(LJe,"SocketWithoutUpgrade");var tFe=LJe;tFe.protocol=Pqr;var SQr=class SQr extends tFe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){C7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){C7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;tFe.priorWebsocketSuccess=!1;let o=e(()=>{a||(C7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(C7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;tFe.priorWebsocketSuccess=r.name==="websocket",C7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(C7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{C7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),C7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function b(){f("socket closed")}e(b,"onclose");function C(T){r&&T.name!==r.name&&(C7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",b),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",b),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(SQr,"SocketWithUpgrade");var X$t=SQr,DQr=class DQr extends X$t{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>CQr[o]).filter(o=>!!o)),super(t,a)}};e(DQr,"Socket");var MJe=DQr;var EDs=MJe.protocol;var XQn=uf(i_t(),1);var YQn=(0,XQn.default)("socket.io-client:url");function ZQn(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(YQn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),YQn("parse %s",i),a=RJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e(ZQn,"url");var MQr={};nQ(MQr,{Decoder:()=>RQr,Encoder:()=>BQr,PacketType:()=>RE,protocol:()=>p$n});var c$n=uf(WPe(),1);var Cba=typeof ArrayBuffer=="function",wba=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),e$n=Object.prototype.toString,Sba=typeof Blob=="function"||typeof Blob<"u"&&e$n.call(Blob)==="[object BlobConstructor]",Dba=typeof File=="function"||typeof File<"u"&&e$n.call(File)==="[object FileConstructor]";function s_t(i){return Cba&&(i instanceof ArrayBuffer||wba(i))||Sba&&i instanceof Blob||Dba&&i instanceof File}e(s_t,"isBinary");function a_t(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(a_t(i[r]))return!0;return!1}if(s_t(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return a_t(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&a_t(i[r]))return!0;return!1}e(a_t,"hasBinary");function t$n(i){let t=[],r=i.data,a=i;return a.data=IQr(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(t$n,"deconstructPacket");function IQr(i,t){if(!i)return i;if(s_t(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=IQr(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=IQr(i[a],t));return r}return i}e(IQr,"_deconstructPacket");function r$n(i,t){return i.data=PQr(i.data,t),delete i.attachments,i}e(r$n,"reconstructPacket");function PQr(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=PQr(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=PQr(i[r],t));return i}e(PQr,"_reconstructPacket");var l$n=uf(o$n(),1);var OQr=(0,l$n.default)("socket.io-parser"),$ba=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],p$n=5,RE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(RE||(RE={}));var jQr=class jQr{constructor(t){this.replacer=t}encode(t){return OQr("encoding packet %j",t),(t.type===RE.EVENT||t.type===RE.ACK)&&a_t(t)?this.encodeAsBinary({type:t.type===RE.EVENT?RE.BINARY_EVENT:RE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===RE.BINARY_EVENT||t.type===RE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),OQr("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=t$n(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(jQr,"Encoder");var BQr=jQr;function u$n(i){return Object.prototype.toString.call(i)==="[object Object]"}e(u$n,"isObject");var aVt=class aVt extends c$n.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===RE.BINARY_EVENT;a||r.type===RE.BINARY_ACK?(r.type=a?RE.EVENT:RE.ACK,this.reconstructor=new LQr(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(s_t(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(RE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===RE.BINARY_EVENT||a.type===RE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(aVt.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return OQr("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case RE.CONNECT:return u$n(r);case RE.DISCONNECT:return r===void 0;case RE.CONNECT_ERROR:return typeof r=="string"||u$n(r);case RE.EVENT:case RE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&$ba.indexOf(r[0])===-1);case RE.ACK:case RE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(aVt,"Decoder");var RQr=aVt,UQr=class UQr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=r$n(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(UQr,"BinaryReconstructor");var LQr=UQr;function yZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(yZ,"on");var f$n=uf(WPe(),1),d$n=uf(i_t(),1);var aO=(0,d$n.default)("socket.io-client:socket"),Vba=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),qQr=class qQr extends f$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[yZ(t,"open",this.onopen.bind(this)),yZ(t,"packet",this.onpacket.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Vba.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:RE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;aO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,b=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?aO("discard packet as the transport is not currently writable"):b?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(aO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));aO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(aO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(aO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(aO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){aO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,aO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){aO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:RE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){aO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case RE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case RE.EVENT:case RE.BINARY_EVENT:this.onevent(t);break;case RE.ACK:case RE.BINARY_ACK:this.onack(t);break;case RE.DISCONNECT:this.ondisconnect();break;case RE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];aO("emitting event %j",r),t.id!=null&&(aO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,aO("sending ack %j",o),r.packet({type:RE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){aO("bad ack %s",t.id);return}delete this.acks[t.id],aO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){aO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){aO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(aO("performing disconnect (%s)",this.nsp),this.packet({type:RE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(qQr,"Socket");var jJe=qQr;function rFe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(rFe,"Backoff");rFe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};rFe.prototype.reset=function(){this.attempts=0};rFe.prototype.setMin=function(i){this.ms=i};rFe.prototype.setMax=function(i){this.max=i};rFe.prototype.setJitter=function(i){this.jitter=i};var m$n=uf(WPe(),1),_$n=uf(i_t(),1);var Ej=(0,_$n.default)("socket.io-client:manager"),QQr=class QQr extends m$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,_be(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new rFe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||MQr;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Ej("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ej("opening %s",this.uri),this.engine=new MJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=yZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{Ej("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=yZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;Ej("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{Ej("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){Ej("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(yZ(t,"ping",this.onping.bind(this)),yZ(t,"data",this.ondata.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this)),yZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){mbe(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Ej("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new jJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){Ej("socket %s is still active, skipping close",a);return}this._close()}_packet(t){Ej("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){Ej("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Ej("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;Ej("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Ej("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();Ej("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(Ej("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(Ej("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(Ej("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(QQr,"Manager");var UJe=QQr;var g$n=uf(i_t(),1);var h$n=(0,g$n.default)("socket.io-client"),o_t={};function u_t(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=ZQn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=o_t[o]&&c in o_t[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(h$n("ignoring socket cache for %s",a),b=new UJe(a,t)):(o_t[o]||(h$n("new io instance for %s",a),o_t[o]=new UJe(a,t)),b=o_t[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(u_t,"lookup");Object.assign(u_t,{Manager:UJe,Socket:jJe,io:u_t,connect:u_t});var sVt={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},$Qr=class $Qr{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||sVt.URL,this.namespace=t.namespace||sVt.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r){try{return await this.connect(),this.emit(t,r,a=>{this.resolveInitialization(a)}),this.initializationPromise}catch(a){throw this.logError("\u274C Failed to start session:",a),this.rejectInitialization(a),a}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=u_t(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:sVt.RECONNECTION_ATTEMPTS,reconnectionDelay:sVt.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected",this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(t),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(new Error(t)))}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e($Qr,"AbstractClient");var oVt=$Qr;var y$n,v$n,b$n,x$n,A$n,E$n,cVt=class cVt extends(E$n=oVt,A$n=Aj.names.getState,x$n=Aj.names.invokeCode,b$n=Aj.names.final_result,v$n=Aj.names.wait,y$n=Aj.names.getElementScreenshot,E$n){constructor(r,a){super({verbose:Gm.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[A$n]=n7e.buildTool(Aj,Aj.names.getState,async r=>this.getStateHandler(r));this[x$n]=n7e.buildTool(Aj,Aj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[b$n]=n7e.buildTool(Aj,Aj.names.final_result,async r=>this.finalResultHandler(r));this[v$n]=n7e.buildTool(Aj,Aj.names.wait,async r=>this.waitHandler(r));this[y$n]=n7e.buildTool(Aj,Aj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:Aj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery Failed";return this.utils.createChecksumStep({title:o,withError:!0}),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new cVt(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){this.utils.createChecksumStep({title:"Error while invoking code",withError:!0}),a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought,a),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(cVt,"AutoRecoveryAgent");var uVt=cVt;var C$n=require("fs"),w$n=uf(require("path"));var VQr=class VQr extends $H{constructor(r,a){let o=$H.getCurrentTestInfo();if(!o)throw new Error("TestRunAnalytics must be initialized with testInfo before FallbackAnalytics can be used");let c=$H.getCurrentInstance();if(!c)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating FallbackAnalytics");let f=c.getTestSuiteRunInfo();super(f,$H.isolatedMode,o);this.sessionId=null;this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r,this.analytics&&this.analytics.alias({userId:r,previousId:this.fallbackId}))}get tableName(){return"auto_recovery"}get metadata(){return{...super.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){super.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(VQr,"AutoRecoveryAnalytics");var lVt=VQr;var nFe=class nFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=b,this.variableStore=C,this._analytics=new lVt(this.sessionId,b.type)}static async start(t){return new nFe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,C$n.readFileSync)(_,b?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:b,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:b,rrwebId:C}},t)}async getReducedHtml(t=nFe.currentChecksumId){let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return nFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let{reducedHTML:t,currentChecksumId:r}=await this.getReducedHtml();return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:t,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:r,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.runtimeFallbackData.testIdentification.testId,variableStore:this.variableStore.reduce((a,o)=>(a[`variablesStore.${o.name}`]=o.value,a),{}),arConfig:this.arConfig}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=w$n.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return N$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],b=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(b))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(b,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
1827
+ Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Qv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(yme),...Object.values(e$e)].includes(a)?["or","and"].includes(a)?(Qv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Qv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Qv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Qv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Qv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Qv("[executeLocatorAction] checksum libs not loaded")}}),await aqt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Qv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Qv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,b;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(b=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:b.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(uqt,"ChecksumFrame");var oqt=uqt;var cqt=class cqt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new Oze({scriptFile:Gm.checksumScript.path,scriptSource:Gm.checksumScript.source,scriptURL:Gm.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!Gm.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(b=>this.registerFrame(b)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=lqt();return new cqt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=oqt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(yme).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>TOn.join(eft(Nne()),r))}compoundSelection(...t){try{return new Nze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(cqt,"ChecksumPage");var Bze=cqt;Dqr();II();var dbe=class dbe{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Nh.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=dbe.describeTool(f,_):a[c]=f}return Nh.object(a).strict()}if(t instanceof Nh.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Nh.array(dbe.describeTool(a,r.element)):t}return t instanceof Nh.ZodOptional?dbe.describeTool(t.unwrap(),r).optional():t instanceof Nh.ZodNullable?dbe.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=dbe.describeTool(f,r.params),C=Aqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],b=dbe.describeTool(_,{});return Aqr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(dbe,"AbstractToolContainer");var n7e=dbe;II();var D$t=class D$t{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>b=>{let C=b.name??_;return{...b,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new D$t(t,r)}};e(D$t,"ToolProtocol");var S$t=D$t;var Aj=S$t.create("v1",{readFile:Nh.object({path:Nh.string()}),getState:Nh.object({thought:Nh.string()}),invokeCode:Nh.object({code:Nh.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Nh.string()}),wait:Nh.object({time:Nh.number().optional()}),scroll:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),final_result:Nh.object({result:Nh.enum(["pass","fail"]),thought:Nh.string(),visualAnalysis:Nh.string().optional()}),getElementScreenshot:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),analyze:Nh.object({previousImmediateSteps:Nh.string(),currentFailingStep:Nh.string(),nextImmediateSteps:Nh.string(),testStepToStopAt:Nh.string()}),think:Nh.object({thought:Nh.string()})});var $qr=uf(lqn(),1);var Mce=Object.create(null);Mce.open="0";Mce.close="1";Mce.ping="2";Mce.pong="3";Mce.message="4";Mce.upgrade="5";Mce.noop="6";var Umt=Object.create(null);Object.keys(Mce).forEach(i=>{Umt[Mce[i]]=i});var qmt={type:"error",data:"parser error"};var Qmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+pqn(t,!0).toString("base64")):a(Mce[i]+(t||"")),"encodePacket"),pqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),kqr;function fqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(pqn(i.data,!1));Qmt(i,!0,r=>{kqr||(kqr=new TextEncoder),t(kqr.encode(r))})}e(fqn,"encodePacketToBinary");var $mt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:dqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:dqn(a,t)}}return Umt[r]?i.length>1?{type:Umt[r],data:i.substring(1)}:{type:Umt[r]}:qmt},"decodePacket"),dqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var mqn="",_qn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{Qmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(mqn))})})},"encodePayload"),hqn=e((i,t)=>{let r=i.split(mqn),a=[];for(let o=0;o<r.length;o++){let c=$mt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function gqn(){return new TransformStream({transform(i,t){fqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(gqn,"createPacketEncoderStream");var Iqr;function T$t(i){return i.reduce((t,r)=>t+r.length,0)}e(T$t,"totalLength");function k$t(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(k$t,"concatChunks");function yqn(i,t){Iqr||(Iqr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(T$t(r)<1)break;let b=k$t(r,1);c=(b[0]&128)===128,o=b[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(T$t(r)<2)break;let b=k$t(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(T$t(r)<8)break;let b=k$t(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(qmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(T$t(r)<o)break;let b=k$t(r,o);_.enqueue($mt(c?b:Iqr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(qmt);break}}}})}e(yqn,"createPacketDecoderStream");var Pqr=4;var Oqn=uf(WPe(),1);var mbe=process.nextTick,Ez=global,bqn="nodebuffer";function xqn(){return new Fqr}e(xqn,"createCookieJar");function c2a(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let b=_[0].trim(),C=_[1].trim();switch(b){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(c2a,"parse");var Nqr=class Nqr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=c2a(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(Nqr,"CookieJar");var Fqr=Nqr;function I$t(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(I$t,"pick");var l2a=Ez.setTimeout,p2a=Ez.clearTimeout;function _be(i,t){t.useNativeTimers?(i.setTimeoutFn=l2a.bind(Ez),i.clearTimeoutFn=p2a.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(_be,"installTimerFunctions");var f2a=1.33;function Aqn(i){return typeof i=="string"?d2a(i):Math.ceil((i.byteLength||i.size)*f2a)}e(Aqn,"byteLength");function d2a(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(d2a,"utf8Length");function P$t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(P$t,"randomString");function Eqn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(Eqn,"encode");function Cqn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(Cqn,"decode");var Bqn=uf(KPe(),1);var R2a=(0,Bqn.default)("engine.io-client:transport"),Mqr=class Mqr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(Mqr,"TransportError");var R$t=Mqr,jqr=class jqr extends Oqn.Emitter{constructor(t){super(),this.writable=!1,_be(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new R$t(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):R2a("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=$mt(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=Eqn(t);return r.length?"?"+r:""}};e(jqr,"Transport");var hbe=jqr;var Rqn=uf(KPe(),1);var jce=(0,Rqn.default)("engine.io-client:polling"),Uqr=class Uqr extends hbe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{jce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(jce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){jce("pre-pause polling complete"),--a||r()})),this.writable||(jce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){jce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){jce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){jce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");hqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():jce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{jce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(jce("transport open - closing"),t()):(jce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,_qn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=P$t()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(Uqr,"Polling");var zmt=Uqr;var Uqn=uf(WPe(),1);var Lqn=!1;try{Lqn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Mqn=Lqn;var qqn=uf(KPe(),1);var qqr=(0,qqn.default)("engine.io-client:polling");function L2a(){}e(L2a,"empty");var Qqr=class Qqr extends zmt{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){qqr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(Qqr,"BaseXHR");var L$t=Qqr,TJe=class TJe extends Uqn.Emitter{constructor(t,r,a){super(),this.createRequest=t,_be(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=I$t(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{qqr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},qqr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=TJe.requestsCount++,TJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=L2a,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete TJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(TJe,"Request");var gbe=TJe;gbe.requestsCount=0;gbe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",jqn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,jqn,!1)}}function jqn(){for(let i in gbe.requests)gbe.requests.hasOwnProperty(i)&&gbe.requests[i].abort()}e(jqn,"unloadHandler");var u7s=function(){let i=M2a({xdomain:!1});return i&&i.responseType!==null}();function M2a(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Mqn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e(M2a,"newRequest");var j2a=$qr.default||$qr,Vqr=class Vqr extends L$t{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new gbe(a=>new j2a(a),this.uri(),t)}};e(Vqr,"XHR");var kJe=Vqr;var Gva=uf(zqn(),1),Kva=uf(iQr(),1),Yva=uf(sQr(),1),bQr=uf(gQr(),1),Xva=uf(QQn(),1);var $Qn=uf(KPe(),1);var eba=(0,$Qn.default)("engine.io-client:websocket"),tba=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",xQr=class xQr extends hbe{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=tba?{}:I$t(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;Qmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{eba("websocket closed before onclose event")}o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=P$t()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(xQr,"BaseWS");var Y$t=xQr,H7s=Ez.WebSocket||Ez.MozWebSocket;var AQr=class AQr extends Y$t{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new bQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(AQr,"WS");var OJe=AQr;var VQn=uf(KPe(),1);var r_t=(0,VQn.default)("engine.io-client:webtransport"),EQr=class EQr extends hbe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{r_t("transport closed gracefully"),this.onClose()}).catch(t=>{r_t("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=yqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=gqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){r_t("session is closed");return}r_t("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{r_t("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(EQr,"WT");var BJe=EQr;var CQr={websocket:OJe,webtransport:BJe,polling:kJe};var rba=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nba=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function RJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=rba.exec(i||""),c={},f=14;for(;f--;)c[nba[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=iba(c,c.path),c.queryKey=aba(c,c.query),c}e(RJe,"parse");function iba(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(iba,"pathNames");function aba(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(aba,"queryKey");var zQn=uf(WPe(),1);var JQn=uf(KPe(),1);var C7=(0,JQn.default)("engine.io-client:socket"),wQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",n_t=[];wQr&&addEventListener("offline",()=>{C7("closing %d connection(s) because the network was lost",n_t.length),n_t.forEach(i=>i())},!1);var LJe=class LJe extends zQn.Emitter{constructor(t,r){if(super(),this.binaryType=bqn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=RJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=RJe(r.host).host);_be(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Cqn(this.opts.query)),wQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(C7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},n_t.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=xqn()),this._open()}createTransport(t){C7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=Pqr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return C7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&LJe.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){C7("setting transport %s",t.name),this.transport&&(C7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){C7("socket open"),this.readyState="open",LJe.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(C7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else C7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();C7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=Aqn(o)),a>0&&r>this._maxPayload)return C7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return C7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(C7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,mbe(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),C7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(C7("socket error %j",t),LJe.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return C7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(C7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),wQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=n_t.indexOf(this._offlineEventListener);a!==-1&&(C7("removing listener for the 'offline' event"),n_t.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(LJe,"SocketWithoutUpgrade");var tFe=LJe;tFe.protocol=Pqr;var SQr=class SQr extends tFe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){C7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){C7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;tFe.priorWebsocketSuccess=!1;let o=e(()=>{a||(C7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(C7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;tFe.priorWebsocketSuccess=r.name==="websocket",C7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(C7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{C7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),C7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function b(){f("socket closed")}e(b,"onclose");function C(T){r&&T.name!==r.name&&(C7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",b),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",b),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(SQr,"SocketWithUpgrade");var X$t=SQr,DQr=class DQr extends X$t{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>CQr[o]).filter(o=>!!o)),super(t,a)}};e(DQr,"Socket");var MJe=DQr;var EDs=MJe.protocol;var XQn=uf(i_t(),1);var YQn=(0,XQn.default)("socket.io-client:url");function ZQn(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(YQn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),YQn("parse %s",i),a=RJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e(ZQn,"url");var MQr={};nQ(MQr,{Decoder:()=>RQr,Encoder:()=>BQr,PacketType:()=>RE,protocol:()=>p$n});var c$n=uf(WPe(),1);var Cba=typeof ArrayBuffer=="function",wba=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),e$n=Object.prototype.toString,Sba=typeof Blob=="function"||typeof Blob<"u"&&e$n.call(Blob)==="[object BlobConstructor]",Dba=typeof File=="function"||typeof File<"u"&&e$n.call(File)==="[object FileConstructor]";function s_t(i){return Cba&&(i instanceof ArrayBuffer||wba(i))||Sba&&i instanceof Blob||Dba&&i instanceof File}e(s_t,"isBinary");function a_t(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(a_t(i[r]))return!0;return!1}if(s_t(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return a_t(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&a_t(i[r]))return!0;return!1}e(a_t,"hasBinary");function t$n(i){let t=[],r=i.data,a=i;return a.data=IQr(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(t$n,"deconstructPacket");function IQr(i,t){if(!i)return i;if(s_t(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=IQr(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=IQr(i[a],t));return r}return i}e(IQr,"_deconstructPacket");function r$n(i,t){return i.data=PQr(i.data,t),delete i.attachments,i}e(r$n,"reconstructPacket");function PQr(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=PQr(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=PQr(i[r],t));return i}e(PQr,"_reconstructPacket");var l$n=uf(o$n(),1);var OQr=(0,l$n.default)("socket.io-parser"),$ba=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],p$n=5,RE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(RE||(RE={}));var jQr=class jQr{constructor(t){this.replacer=t}encode(t){return OQr("encoding packet %j",t),(t.type===RE.EVENT||t.type===RE.ACK)&&a_t(t)?this.encodeAsBinary({type:t.type===RE.EVENT?RE.BINARY_EVENT:RE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===RE.BINARY_EVENT||t.type===RE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),OQr("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=t$n(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(jQr,"Encoder");var BQr=jQr;function u$n(i){return Object.prototype.toString.call(i)==="[object Object]"}e(u$n,"isObject");var aVt=class aVt extends c$n.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===RE.BINARY_EVENT;a||r.type===RE.BINARY_ACK?(r.type=a?RE.EVENT:RE.ACK,this.reconstructor=new LQr(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(s_t(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(RE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===RE.BINARY_EVENT||a.type===RE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(aVt.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return OQr("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case RE.CONNECT:return u$n(r);case RE.DISCONNECT:return r===void 0;case RE.CONNECT_ERROR:return typeof r=="string"||u$n(r);case RE.EVENT:case RE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&$ba.indexOf(r[0])===-1);case RE.ACK:case RE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(aVt,"Decoder");var RQr=aVt,UQr=class UQr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=r$n(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(UQr,"BinaryReconstructor");var LQr=UQr;function yZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(yZ,"on");var f$n=uf(WPe(),1),d$n=uf(i_t(),1);var aO=(0,d$n.default)("socket.io-client:socket"),Vba=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),qQr=class qQr extends f$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[yZ(t,"open",this.onopen.bind(this)),yZ(t,"packet",this.onpacket.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Vba.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:RE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;aO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,b=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?aO("discard packet as the transport is not currently writable"):b?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(aO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));aO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(aO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(aO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(aO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){aO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,aO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){aO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:RE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){aO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case RE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case RE.EVENT:case RE.BINARY_EVENT:this.onevent(t);break;case RE.ACK:case RE.BINARY_ACK:this.onack(t);break;case RE.DISCONNECT:this.ondisconnect();break;case RE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];aO("emitting event %j",r),t.id!=null&&(aO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,aO("sending ack %j",o),r.packet({type:RE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){aO("bad ack %s",t.id);return}delete this.acks[t.id],aO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){aO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){aO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(aO("performing disconnect (%s)",this.nsp),this.packet({type:RE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(qQr,"Socket");var jJe=qQr;function rFe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(rFe,"Backoff");rFe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};rFe.prototype.reset=function(){this.attempts=0};rFe.prototype.setMin=function(i){this.ms=i};rFe.prototype.setMax=function(i){this.max=i};rFe.prototype.setJitter=function(i){this.jitter=i};var m$n=uf(WPe(),1),_$n=uf(i_t(),1);var Ej=(0,_$n.default)("socket.io-client:manager"),QQr=class QQr extends m$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,_be(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new rFe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||MQr;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Ej("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ej("opening %s",this.uri),this.engine=new MJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=yZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{Ej("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=yZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;Ej("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{Ej("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){Ej("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(yZ(t,"ping",this.onping.bind(this)),yZ(t,"data",this.ondata.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this)),yZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){mbe(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Ej("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new jJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){Ej("socket %s is still active, skipping close",a);return}this._close()}_packet(t){Ej("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){Ej("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Ej("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;Ej("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Ej("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();Ej("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(Ej("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(Ej("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(Ej("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(QQr,"Manager");var UJe=QQr;var g$n=uf(i_t(),1);var h$n=(0,g$n.default)("socket.io-client"),o_t={};function u_t(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=ZQn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=o_t[o]&&c in o_t[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(h$n("ignoring socket cache for %s",a),b=new UJe(a,t)):(o_t[o]||(h$n("new io instance for %s",a),o_t[o]=new UJe(a,t)),b=o_t[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(u_t,"lookup");Object.assign(u_t,{Manager:UJe,Socket:jJe,io:u_t,connect:u_t});var sVt={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},$Qr=class $Qr{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||sVt.URL,this.namespace=t.namespace||sVt.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r){try{return await this.connect(),this.emit(t,r,a=>{this.resolveInitialization(a)}),this.initializationPromise}catch(a){throw this.logError("\u274C Failed to start session:",a),this.rejectInitialization(a),a}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=u_t(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:sVt.RECONNECTION_ATTEMPTS,reconnectionDelay:sVt.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected",this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(t),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(new Error(t)))}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e($Qr,"AbstractClient");var oVt=$Qr;var y$n,v$n,b$n,x$n,A$n,E$n,cVt=class cVt extends(E$n=oVt,A$n=Aj.names.getState,x$n=Aj.names.invokeCode,b$n=Aj.names.final_result,v$n=Aj.names.wait,y$n=Aj.names.getElementScreenshot,E$n){constructor(r,a){super({verbose:Gm.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[A$n]=n7e.buildTool(Aj,Aj.names.getState,async r=>this.getStateHandler(r));this[x$n]=n7e.buildTool(Aj,Aj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[b$n]=n7e.buildTool(Aj,Aj.names.final_result,async r=>this.finalResultHandler(r));this[v$n]=n7e.buildTool(Aj,Aj.names.wait,async r=>this.waitHandler(r));this[y$n]=n7e.buildTool(Aj,Aj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:Aj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery attempt finished unsuccessfully";return this.utils.createChecksumStep({title:o,withError:!0}),this.utils.addAutoRecoveryErrorToReport(o,!1),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new cVt(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought,a),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(cVt,"AutoRecoveryAgent");var uVt=cVt;var C$n=require("fs"),w$n=uf(require("path"));var VQr=class VQr extends $H{constructor(r,a){let o=$H.getCurrentTestInfo();if(!o)throw new Error("TestRunAnalytics must be initialized with testInfo before FallbackAnalytics can be used");let c=$H.getCurrentInstance();if(!c)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating FallbackAnalytics");let f=c.getTestSuiteRunInfo();super(f,$H.isolatedMode,o);this.sessionId=null;this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r,this.analytics&&this.analytics.alias({userId:r,previousId:this.fallbackId}))}get tableName(){return"auto_recovery"}get metadata(){return{...super.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){super.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(VQr,"AutoRecoveryAnalytics");var lVt=VQr;var nFe=class nFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=b,this.variableStore=C,this._analytics=new lVt(this.sessionId,b.type)}static async start(t){return new nFe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,C$n.readFileSync)(_,b?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:b,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:b,rrwebId:C}},t)}async getReducedHtml(t=nFe.currentChecksumId){let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return nFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let{reducedHTML:t,currentChecksumId:r}=await this.getReducedHtml();return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:t,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:r,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.runtimeFallbackData.testIdentification.testId,variableStore:this.variableStore.reduce((a,o)=>(a[`variablesStore.${o.name}`]=o.value,a),{}),arConfig:this.arConfig}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=w$n.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return N$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],b=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(b))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(b,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
1828
1828
  ${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelConfig)==null?void 0:r.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}};e(nFe,"AutoRecoveryRuntimeIteratorUtils"),nFe.currentChecksumId="0";var pVt=nFe;var qJe=class qJe extends Lme{init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${qJe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await qJe.registerSession(this.initializationData);this.utils=new pVt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables});try{this.agent=await uVt.build(this.utils)}catch{throw new Error("Failed to prepare ARFallback")}}async resolve(t){let r=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();let a=await this.agent.init();return this.utils.analytics.ARFinish({duration:Date.now()-r}),{fbResult:a.result,thought:a.finalThought,stepsThoughts:a.stepsThoughts,steps:[]}}};e(qJe,"ARFallback"),qJe.API_BASE_ROUTE="/auto-recovery";var Abe=qJe;var zQr=1e3*30;var c_t=class c_t extends Bze{constructor(r,a="normal",o,c,f,_,b,C,w,T,k,R){var W,X,ne;super(r,T,()=>this.pageInteractor);this.page=r;this.runMode=a;this.testRunAnalytics=o;this.monitorBridge=c;this.testInfo=f;this.checksumTestId=_;this.test=b;this.options=C;this.isReplMode=w;this.config=T;this.pageInteractorAPI=k;this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new n$e;this.previousSteps=[];this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:zQr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:Gm.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Qv(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");D$n(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},dVt(this.page)),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let B=Ebe({config:this.config,throwIfAuthFailed:!0}),U=this.getPlaywrightProjectConfig();if(this.pageInteractor=new q6e(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Qv,logError:Qv},{navigationTimeout:(W=U.use)==null?void 0:W.navigationTimeout,actionTimeout:(X=U.use)==null?void 0:X.actionTimeout,testAssetsDir:eft(Nne()),waitActionDelay:1e3},this.pageInteractorAPI,B),this.checkForActiveTracing(),this.resetFallbacks(),R&&(this.highLevelThoughts=R.highLevelThoughts??[],this.pages=R.pages??{},this.timeMachineBrowserContext=R.timeMachineBrowserContext,this.variableStore=R.variableStore),Gm.testRun.timeMachine.active){let ce=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:jAn(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new nqt(this.framesMsgBroker,this.injectedScriptManager,{...ce,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Gm.testRun.timeMachine.headless,webProxy:(ne=f.project.use)==null?void 0:ne.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}this.pages[this.getPageGuid(r)]=this.proxy}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(r,a,o,c,f,_,b,C,w=!1){_||(_=TBt(5),console.warn(`Checksum test id was not defined for test "${f.title}" and was auto-generated. Please replace - "${f.title}" with -
1829
1829
  test(defineChecksumTest("${f.title}", "${_}"), async ({ page }) => {...`)),o.addTestInfo(_,f.testId),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let T=new P$e(C),k=new c_t(r,C.runMode,a,o,f,_,b,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},w,C,T,{variableStore:c});return b._checksum.expect.setPage(k),b._checksum.checksumAI.page=k,c.clearAll(),k.testRunAnalytics.testRunStart(),await k.asyncInit(),k.proxy}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=vZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async getPage(r){let a=this.page.context().pages()[r];if(!a)throw new Error(`Page with index ${r} not found`);return this.makePage(a)}async makePage(r){let a=this.getPageGuid(r);if(this.pages[a])return this.pages[a];let o=new c_t(r,this.runMode,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await o.asyncInit(!0),o.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return Gm.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}getPageGuid(r){return r._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);return this.previousSteps.push({thought:c.thought,timestamp:Date.now()}),a&&typeof a=="function"?this.test.step(r,async f=>{var _;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(b){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAIFallback)throw b;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:b,method:void 0,args:[],testInfo:this.testInfo,step:f},{fallbackTypes:[Dve,Abe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(_=this.currentThought)==null?void 0:_.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>vZ.join(eft(Nne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
1830
1830
  ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let b=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=b}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr};this.pushFallback(this.constructFallback(Cdt).init(a)),this.pushFallback(this.constructFallback(Adt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Edt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let b=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:b.slice(0,-1),failing:r,next:b.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Abe).init(k)},"createArFallback"),f=e(()=>{var b,C;return this.constructFallback(Dve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Gm.benchmark,arMode:(b=this.options.useChecksumAI)==null?void 0:b.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:Gm.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof Dve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Abe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let b=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Mft(f.fbResult);if(r instanceof Dve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Abe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${b}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Qv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Dve);if(o){let _=o.getFailedThought(),b=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(b)})}let c=this.fallbacks.find(_=>_ instanceof Abe);if(c){let _=c.failingThought;this.fallbacks.forEach(b=>{b instanceof Abe&&b.setVariables(this.variableStore.getActiveVariables()),b.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((b,C)=>b||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let b=_==null?void 0:_.toString();b&&console.log(`Using ${b}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(h4e);w instanceof Mft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),b&&console.log(`Failed to use ${b}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(wdt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:vZ.basename(r)})}catch(r){Qv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Qv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[wdt,Edt,Cdt,Adt,Dve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=MAn(IBt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?UAn(IBt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=P3r(IBt(this.testInfo.file)),a=vZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=vZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,S$n.loadAsync)(c);for(let b of Object.keys(f.files)){let C=await f.file(b).async("string"),w=vZ.join(o,b);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=vZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(vZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Qv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=vZ.join(YIe(Nne()),"settings.asr");if(!(0,Cz.existsSync)(r)){Qv("Could not find ASR file");return}let{ungzip:a}=I3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Qv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(c_t,"RuntimePage");var fVt=c_t;var hVt=require("fs");var u7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},GTs={defaultMerge:u7e.defaultMerge};function zba(i,t){return t}e(zba,"defaultMetaDataUpdater");function Jba(i,t){return i.filter(r=>r!==void 0)}e(Jba,"defaultFilterValues");var T$n;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(T$n||(T$n={}));function k$n(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:Gba(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(k$n,"getObjectType");function Wba(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(Wba,"getKeys");function Hba(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(Hba,"objectHasProperty");function P$n(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(P$n,"getIterableOfIterables");var I$n=["[object Object]","[object Module]"];function Gba(i){if(!I$n.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!I$n.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(Gba,"isRecord");function Kba(i,t,r){let a={};for(let o of Wba(i)){let c=[];for(let b of i)Hba(b,o)&&c.push(b[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=F$n(c,t,f);_!==u7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(Kba,"mergeRecords$1");function Yba(i){return i.flat()}e(Yba,"mergeArrays$1");function Xba(i){return new Set(P$n(i))}e(Xba,"mergeSets$1");function Zba(i){return new Map(P$n(i))}e(Zba,"mergeMaps$1");function exa(i){return i.at(-1)}e(exa,"mergeOthers$1");var mVt={mergeRecords:Kba,mergeArrays:Yba,mergeSets:Xba,mergeMaps:Zba,mergeOthers:exa};function _Vt(...i){return txa({})(...i)}e(_Vt,"deepmerge");function txa(i,t){let r=rxa(i,a);function a(...o){return F$n(o,r,t)}return e(a,"customizedDeepmerge"),a}e(txa,"deepmergeCustom");function rxa(i,t){return{defaultMergeFunctions:mVt,mergeFunctions:{...mVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(mVt,r)).map(([r,a])=>a===!1?[r,mVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??zba,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Jba,actions:u7e}}e(rxa,"getUtils");function F$n(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return JQr(a,t,r);let o=k$n(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(k$n(a[f])!==o)return JQr(a,t,r)}switch(o){case 1:return nxa(a,t,r);case 2:return ixa(a,t,r);case 3:return axa(a,t,r);case 4:return sxa(a,t,r);default:return JQr(a,t,r)}}e(F$n,"mergeUnknowns");function nxa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(nxa,"mergeRecords");function ixa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(ixa,"mergeArrays");function axa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(axa,"mergeSets");function sxa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(sxa,"mergeMaps");function JQr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(JQr,"mergeOthers");var N$n=!1;function D$n(i){N$n=i}e(D$n,"setLogToConsole");function Qv(...i){N$n&&console.log(...i)}e(Qv,"log");async function E8n(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}e(E8n,"executePlaywrightMethodWithTimeout");function l_t(i,{role:t,environment:r}={},a=!1){var _,b;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(b=i.environments)==null?void 0:b.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(l_t,"resolveEnvironment");function oxa(i){let t=`${i??Nne()}/login.ts`;if(!(0,hVt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(oxa,"requireLogin");async function uxa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "1.3.8",
3
+ "version": "1.3.10",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {