@checksum-ai/runtime 4.1.1-beta.9 → 4.2.0

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
@@ -743,7 +743,7 @@ Details: ${ue.message}`),GKt(ue)&&(Se=`${Se}
743
743
  ${vke.prettifyError(ue)}`),new Cpe(Se,JSON.stringify(n))}else{let ue=Mm(u,this.schema);if(!ue.valid){let Se="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(Se=`${Se}
744
744
  Details: ${ue.errors.map(Ct=>`${Ct.keywordLocation}: ${Ct.error}`).join(`
745
745
  `)}`),new Cpe(Se,JSON.stringify(n))}_=u}let g=QTe(s),E=W8.configure(g.callbacks,this.callbacks,g.tags||c,this.tags,g.metadata,this.metadata,{verbose:this.verbose}),x;EJ(n)&&(x=n.id),!x&&zqt(g)&&(x=g.toolCall.id);let P=await(E==null?void 0:E.handleToolStart(this.toJSON(),typeof n=="string"?n:JSON.stringify(n),g.runId,void 0,void 0,void 0,g.runName,x));delete g.runId;let M;try{let ue=await this._call(_,P,g);M=slt(ue)?await GXt(ue,async Se=>{try{await(P==null?void 0:P.handleToolEvent(Se))}catch(Ct){await(P==null?void 0:P.handleToolError(Ct))}}):ue}catch(ue){throw await(P==null?void 0:P.handleToolError(ue)),ue}let X,W;if(this.responseFormat==="content_and_artifact")if(Array.isArray(M)&&M.length===2)[X,W]=M;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
746
- Result: ${JSON.stringify(M)}`);else X=M;let ce=i0n({content:X,artifact:W,toolCallId:x,name:this.name,metadata:this.metadata});return await(P==null?void 0:P.handleToolEnd(ce)),ce}},t(fee,"StructuredTool"),fee),pee,t0n=(pee=class extends vtr{schema=il.object({input:il.string().optional()}).transform(n=>n.input);constructor(n){super(n)}call(n,s){let c=typeof n=="string"||n==null?{input:n}:n;return super.call(c,s)}},t(pee,"Tool"),pee),dee,r0n=(dee=class extends t0n{static lc_name(){return"DynamicTool"}name;description;func;constructor(n){super(n),this.name=n.name,this.description=n.description,this.func=n.func,this.returnDirect=n.returnDirect??this.returnDirect}async call(n,s){let c=QTe(s);return c.runName===void 0&&(c.runName=this.name),super.call(n,c)}_call(n,s,c){return this.func(n,s,c)}},t(dee,"DynamicTool"),dee),_ee,n0n=(_ee=class extends vtr{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(n){super(n),this.name=n.name,this.description=n.description,this.func=n.func,this.returnDirect=n.returnDirect??this.returnDirect,this.schema=n.schema}async call(n,s,c){let u=QTe(s);return u.runName===void 0&&(u.runName=this.name),super.call(n,u,c)}_call(n,s,c){return this.func(n,s,c)}},t(_ee,"DynamicStructuredTool"),_ee);function nut(i,n){var g;let s=Pxe(n.schema),c=Lde(n.schema);if(!n.schema||s||c)return new r0n({...n,description:n.description??((g=n.schema)==null?void 0:g.description)??`${n.name} tool`,func:t(async(E,x,P)=>new Promise((M,X)=>{let W=w0(P,{callbacks:x==null?void 0:x.getChild()});Vv.runWithConfig(Ow(W),async()=>{try{M(i(E,W))}catch(ce){X(ce)}})}),"func")});let u=n.schema,_=n.description??n.schema.description??`${n.name} tool`;return new n0n({...n,description:_,schema:u,func:t(async(E,x,P)=>new Promise((M,X)=>{let W,ce=t(()=>{P!=null&&P.signal&&W&&P.signal.removeEventListener("abort",W)},"cleanup");P!=null&&P.signal&&(W=t(()=>{ce(),X(hO(P.signal))},"listener"),P.signal.addEventListener("abort",W,{once:!0}));let ue=w0(P,{callbacks:x==null?void 0:x.getChild()});Vv.runWithConfig(Ow(ue),async()=>{var Se;try{let Ct=await i(E,ue);if(slt(Ct)){M(Ct);return}if((Se=P==null?void 0:P.signal)!=null&&Se.aborted){ce();return}ce(),M(Ct)}catch(Ct){ce(),X(Ct)}})}),"func")})}t(nut,"tool");function i0n(i){let{content:n,artifact:s,toolCallId:c,metadata:u}=i;return c&&!bHt(n)?typeof n=="string"||Array.isArray(n)&&n.every(_=>typeof _=="object")?new VIe({status:"success",content:n,artifact:s,tool_call_id:c,name:i.name,metadata:u}):new VIe({status:"success",content:s0n(n),artifact:s,tool_call_id:c,name:i.name,metadata:u}):n}t(i0n,"_formatToolOutput");function s0n(i){try{return JSON.stringify(i)??""}catch{return`${i}`}}t(s0n,"_stringify");var dN=class dN{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 n={},s=this.toolRecord.tools;for(let c of Object.keys(s))n[c]=u=>this._addSingleTool(c,u);return n}static describeTool(n,s){if(n instanceof il.ZodObject){let c={},u=n.shape;for(let _ of Object.keys(u)){let g=u[_],E=s==null?void 0:s[_];typeof E=="string"?c[_]=g.describe(E):E&&typeof E=="object"?c[_]=dN.describeTool(g,E):c[_]=g}return il.object(c).strict()}if(n instanceof il.ZodArray){let c=n.element;return s&&typeof s=="object"&&s.element?il.array(dN.describeTool(c,s.element)):n}return n instanceof il.ZodOptional?dN.describeTool(n.unwrap(),s).optional():n instanceof il.ZodNullable?dN.describeTool(n.unwrap(),s).nullable():typeof s=="string"?n.describe(s):n}_addSingleTool(n,s){let c=s.name??String(n),_=this.toolRecord.tools[n]._create({...s,name:c,params:s.params,handler:s.handler}),g=this.toolRecord.tools[n],E=dN.describeTool(g,s.params),P=nut(t(async M=>{let X=E.parse(M);return s.handler(X)},"validatedHandler"),{name:_.name,description:_.description,schema:E});return this.toolsMap[n]=P,P}_buildOne(n,s){return this._addSingleTool(n,{...s,name:String(n)})}static buildTool(n,s,c){let u=String(s),g=n.tools[s]._create({name:u,description:"",handler:c,params:{}}),E=n.tools[s],x=dN.describeTool(E,{});return nut(t(async X=>{let W=x.parse(X);return c(W)},"validatedHandler"),{name:g.name,description:g.description,schema:x})}};t(dN,"AbstractToolContainer");var e5=dN;var Eke=class Eke{constructor(n,s){this.version=n;let c={};for(let _ in s)c[_]=_;this.names=c;let u={};for(let _ in s){let g=s[_];Object.defineProperty(g,"name",{value:_,configurable:!1,enumerable:!0,writable:!1}),g._create=(E=>x=>{let P=x.name??E;return{...x,name:P}})(_),u[_]=g}this.tools=u}static create(n,s){return new Eke(n,s)}};t(Eke,"ToolProtocol");var bke=Eke;var Oh=bke.create("v1",{readFile:il.object({path:il.string()}),getState:il.object({thought:il.string(),pageId:il.string().optional(),includeAllPages:il.boolean().optional()}),invokeCode:il.object({code:il.string().refine(i=>{let n=i.trim();return n.includes("page.getByChecksumId(")||n.includes("page.getByChecksumId(")||n.startsWith("const ")||n.startsWith("let ")||n.startsWith("var ")||n.includes("=")||n.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:il.string(),pageId:il.string().optional()}),wait:il.object({time:il.number().optional()}),scroll:il.object({checksumId:il.string(),thought:il.string()}),final_result:il.object({result:il.enum(["pass","fail"]),thought:il.string(),visualAnalysis:il.string().optional()}),getElementScreenshot:il.object({checksumId:il.string(),thought:il.string()}),listPages:il.object({thought:il.string().optional()}),switchPage:il.object({pageId:il.string(),thought:il.string().optional()}),analyze:il.object({previousImmediateSteps:il.string(),currentFailingStep:il.string(),nextImmediateSteps:il.string(),testStepToStopAt:il.string()}),think:il.object({thought:il.string()})});var but=uc(Ctr(),1);var mx=Object.create(null);mx.open="0";mx.close="1";mx.ping="2";mx.pong="3";mx.message="4";mx.upgrade="5";mx.noop="6";var qde=Object.create(null);Object.keys(mx).forEach(i=>{qde[mx[i]]=i});var Hde={type:"error",data:"parser error"};var $de=t(({type:i,data:n},s,c)=>n instanceof ArrayBuffer||ArrayBuffer.isView(n)?c(s?n:"b"+Str(n,!0).toString("base64")):c(mx[i]+(n||"")),"encodePacket"),Str=t((i,n)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!n?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),sut;function wtr(i,n){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return n(Str(i.data,!1));$de(i,!0,s=>{sut||(sut=new TextEncoder),n(sut.encode(s))})}t(wtr,"encodePacketToBinary");var Gde=t((i,n)=>{if(typeof i!="string")return{type:"message",data:Itr(i,n)};let s=i.charAt(0);if(s==="b"){let c=Buffer.from(i.substring(1),"base64");return{type:"message",data:Itr(c,n)}}return qde[s]?i.length>1?{type:qde[s],data:i.substring(1)}:{type:qde[s]}:Hde},"decodePacket"),Itr=t((i,n)=>{switch(n){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 Ttr="",xtr=t((i,n)=>{let s=i.length,c=new Array(s),u=0;i.forEach((_,g)=>{$de(_,!1,E=>{c[g]=E,++u===s&&n(c.join(Ttr))})})},"encodePayload"),ktr=t((i,n)=>{let s=i.split(Ttr),c=[];for(let u=0;u<s.length;u++){let _=Gde(s[u],n);if(c.push(_),_.type==="error")break}return c},"decodePayload");function Dtr(){return new TransformStream({transform(i,n){wtr(i,s=>{let c=s.length,u;if(c<126)u=new Uint8Array(1),new DataView(u.buffer).setUint8(0,c);else if(c<65536){u=new Uint8Array(3);let _=new DataView(u.buffer);_.setUint8(0,126),_.setUint16(1,c)}else{u=new Uint8Array(9);let _=new DataView(u.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(c))}i.data&&typeof i.data!="string"&&(u[0]|=128),n.enqueue(u),n.enqueue(s)})}})}t(Dtr,"createPacketEncoderStream");var aut;function Cke(i){return i.reduce((n,s)=>n+s.length,0)}t(Cke,"totalLength");function Ske(i,n){if(i[0].length===n)return i.shift();let s=new Uint8Array(n),c=0;for(let u=0;u<n;u++)s[u]=i[0][c++],c===i[0].length&&(i.shift(),c=0);return i.length&&c<i[0].length&&(i[0]=i[0].slice(c)),s}t(Ske,"concatChunks");function Ntr(i,n){aut||(aut=new TextDecoder);let s=[],c=0,u=-1,_=!1;return new TransformStream({transform(g,E){for(s.push(g);;){if(c===0){if(Cke(s)<1)break;let x=Ske(s,1);_=(x[0]&128)===128,u=x[0]&127,u<126?c=3:u===126?c=1:c=2}else if(c===1){if(Cke(s)<2)break;let x=Ske(s,2);u=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),c=3}else if(c===2){if(Cke(s)<8)break;let x=Ske(s,8),P=new DataView(x.buffer,x.byteOffset,x.length),M=P.getUint32(0);if(M>Math.pow(2,21)-1){E.enqueue(Hde);break}u=M*Math.pow(2,32)+P.getUint32(4),c=3}else{if(Cke(s)<u)break;let x=Ske(s,u);E.enqueue(Gde(_?x:aut.decode(x),n)),c=0}if(u===0||u>i){E.enqueue(Hde);break}}}})}t(Ntr,"createPacketDecoderStream");var out=4;var Htr=uc(hV(),1);var _N=process.nextTick,Ib=global,Btr="nodebuffer";function Ftr(){return new cut}t(Ftr,"createCookieJar");function l0n(i){let n=i.split("; "),s=n[0].indexOf("=");if(s===-1)return;let c=n[0].substring(0,s).trim();if(!c.length)return;let u=n[0].substring(s+1).trim();u.charCodeAt(0)===34&&(u=u.slice(1,-1));let _={name:c,value:u};for(let g=1;g<n.length;g++){let E=n[g].split("=");if(E.length!==2)continue;let x=E[0].trim(),P=E[1].trim();switch(x){case"Expires":_.expires=new Date(P);break;case"Max-Age":let M=new Date;M.setUTCSeconds(M.getUTCSeconds()+parseInt(P,10)),_.expires=M;break;default:}}return _}t(l0n,"parse");var lut=class lut{constructor(){this._cookies=new Map}parseCookies(n){n&&n.forEach(s=>{let c=l0n(s);c&&this._cookies.set(c.name,c)})}get cookies(){let n=Date.now();return this._cookies.forEach((s,c)=>{var u;((u=s.expires)===null||u===void 0?void 0:u.getTime())<n&&this._cookies.delete(c)}),this._cookies.entries()}addCookies(n){let s=[];for(let[c,u]of this.cookies)s.push(`${c}=${u.value}`);s.length&&(n.setDisableHeaderCheck(!0),n.setRequestHeader("cookie",s.join("; ")))}appendCookies(n){for(let[s,c]of this.cookies)n.append("cookie",`${s}=${c.value}`)}};t(lut,"CookieJar");var cut=lut;function wke(i,...n){return n.reduce((s,c)=>(i.hasOwnProperty(c)&&(s[c]=i[c]),s),{})}t(wke,"pick");var u0n=Ib.setTimeout,f0n=Ib.clearTimeout;function mN(i,n){n.useNativeTimers?(i.setTimeoutFn=u0n.bind(Ib),i.clearTimeoutFn=f0n.bind(Ib)):(i.setTimeoutFn=Ib.setTimeout.bind(Ib),i.clearTimeoutFn=Ib.clearTimeout.bind(Ib))}t(mN,"installTimerFunctions");var p0n=1.33;function Rtr(i){return typeof i=="string"?d0n(i):Math.ceil((i.byteLength||i.size)*p0n)}t(Rtr,"byteLength");function d0n(i){let n=0,s=0;for(let c=0,u=i.length;c<u;c++)n=i.charCodeAt(c),n<128?s+=1:n<2048?s+=2:n<55296||n>=57344?s+=3:(c++,s+=4);return s}t(d0n,"utf8Length");function Ike(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}t(Ike,"randomString");function Otr(i){let n="";for(let s in i)i.hasOwnProperty(s)&&(n.length&&(n+="&"),n+=encodeURIComponent(s)+"="+encodeURIComponent(i[s]));return n}t(Otr,"encode");function Mtr(i){let n={},s=i.split("&");for(let c=0,u=s.length;c<u;c++){let _=s[c].split("=");n[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return n}t(Mtr,"decode");var $tr=uc(AV(),1);var O0n=(0,$tr.default)("engine.io-client:transport"),hut=class hut extends Error{constructor(n,s,c){super(n),this.description=s,this.context=c,this.type="TransportError"}};t(hut,"TransportError");var Nke=hut,gut=class gut extends Htr.Emitter{constructor(n){super(),this.writable=!1,mN(this,n),this.opts=n,this.query=n.query,this.socket=n.socket,this.supportsBinary=!n.forceBase64}onError(n,s,c){return super.emitReserved("error",new Nke(n,s,c)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(n){this.readyState==="open"?this.write(n):O0n("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(n){let s=Gde(n,this.socket.binaryType);this.onPacket(s)}onPacket(n){super.emitReserved("packet",n)}onClose(n){this.readyState="closed",super.emitReserved("close",n)}pause(n){}createUri(n,s={}){return n+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){let n=this.opts.hostname;return n.indexOf(":")===-1?n:"["+n+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(n){let s=Otr(n);return s.length?"?"+s:""}};t(gut,"Transport");var hN=gut;var Gtr=uc(AV(),1);var hx=(0,Gtr.default)("engine.io-client:polling"),Aut=class Aut extends hN{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(n){this.readyState="pausing";let s=t(()=>{hx("paused"),this.readyState="paused",n()},"pause");if(this._polling||!this.writable){let c=0;this._polling&&(hx("we are currently polling - waiting to pause"),c++,this.once("pollComplete",function(){hx("pre-pause polling complete"),--c||s()})),this.writable||(hx("we are currently writing - waiting to pause"),c++,this.once("drain",function(){hx("pre-pause writing complete"),--c||s()}))}else s()}_poll(){hx("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(n){hx("polling got data %s",n);let s=t(c=>{if(this.readyState==="opening"&&c.type==="open"&&this.onOpen(),c.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(c)},"callback");ktr(n,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():hx('ignoring poll - transport state "%s"',this.readyState))}doClose(){let n=t(()=>{hx("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(hx("transport open - closing"),n()):(hx("transport not open - deferring close"),this.once("open",n))}write(n){this.writable=!1,xtr(n,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let n=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Ike()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(n,s)}};t(Aut,"Polling");var Yde=Aut;var Xtr=uc(hV(),1);var Ytr=!1;try{Ytr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Ztr=Ytr;var err=uc(AV(),1);var yut=(0,err.default)("engine.io-client:polling");function M0n(){}t(M0n,"empty");var vut=class vut extends Yde{constructor(n){if(super(n),typeof location<"u"){let s=location.protocol==="https:",c=location.port;c||(c=s?"443":"80"),this.xd=typeof location<"u"&&n.hostname!==location.hostname||c!==n.port}}doWrite(n,s){let c=this.request({method:"POST",data:n});c.on("success",s),c.on("error",(u,_)=>{this.onError("xhr post error",u,_)})}doPoll(){yut("xhr poll");let n=this.request();n.on("data",this.onData.bind(this)),n.on("error",(s,c)=>{this.onError("xhr poll error",s,c)}),this.pollXhr=n}};t(vut,"BaseXHR");var Pke=vut,yee=class yee extends Xtr.Emitter{constructor(n,s,c){super(),this.createRequest=n,mN(this,c),this._opts=c,this._method=c.method||"GET",this._uri=s,this._data=c.data!==void 0?c.data:null,this._create()}_create(){var n;let s=wke(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;let c=this._xhr=this.createRequest(s);try{yut("xhr open %s: %s",this._method,this._uri),c.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){c.setDisableHeaderCheck&&c.setDisableHeaderCheck(!0);for(let u in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(u)&&c.setRequestHeader(u,this._opts.extraHeaders[u])}}catch{}if(this._method==="POST")try{c.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{c.setRequestHeader("Accept","*/*")}catch{}(n=this._opts.cookieJar)===null||n===void 0||n.addCookies(c),"withCredentials"in c&&(c.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(c.timeout=this._opts.requestTimeout),c.onreadystatechange=()=>{var u;c.readyState===3&&((u=this._opts.cookieJar)===null||u===void 0||u.parseCookies(c.getResponseHeader("set-cookie"))),c.readyState===4&&(c.status===200||c.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof c.status=="number"?c.status:0)},0))},yut("xhr data %s",this._data),c.send(this._data)}catch(u){this.setTimeoutFn(()=>{this._onError(u)},0);return}typeof document<"u"&&(this._index=yee.requestsCount++,yee.requests[this._index]=this)}_onError(n){this.emitReserved("error",n,this._xhr),this._cleanup(!0)}_cleanup(n){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=M0n,n)try{this._xhr.abort()}catch{}typeof document<"u"&&delete yee.requests[this._index],this._xhr=null}}_onLoad(){let n=this._xhr.responseText;n!==null&&(this.emitReserved("data",n),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};t(yee,"Request");var gN=yee;gN.requestsCount=0;gN.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ktr);else if(typeof addEventListener=="function"){let i="onpagehide"in Ib?"pagehide":"unload";addEventListener(i,Ktr,!1)}}function Ktr(){for(let i in gN.requests)gN.requests.hasOwnProperty(i)&&gN.requests[i].abort()}t(Ktr,"unloadHandler");var $Yn=function(){let i=L0n({xdomain:!1});return i&&i.responseType!==null}();function L0n(i){let n=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!n||Ztr))return new XMLHttpRequest}catch{}if(!n)try{return new Ib[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}t(L0n,"newRequest");var Q0n=but.default||but,Eut=class Eut extends Pke{request(n={}){var s;return Object.assign(n,{xd:this.xd,cookieJar:(s=this.socket)===null||s===void 0?void 0:s._cookieJar},this.opts),new gN(c=>new Q0n(c),this.uri(),n)}};t(Eut,"XHR");var vee=Eut;var GAn=uc(irr(),1),YAn=uc(Out(),1),ZAn=uc(Lut(),1),Kut=uc(Gut(),1),KAn=uc(tnr(),1);var rnr=uc(AV(),1);var eyn=(0,rnr.default)("engine.io-client:websocket"),tyn=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Xut=class Xut extends hN{get name(){return"websocket"}doOpen(){let n=this.uri(),s=this.opts.protocols,c=tyn?{}:wke(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(c.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(n,s,c)}catch(u){return this.emitReserved("error",u)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=n=>this.onClose({description:"websocket connection closed",context:n}),this.ws.onmessage=n=>this.onData(n.data),this.ws.onerror=n=>this.onError("websocket error",n)}write(n){this.writable=!1;for(let s=0;s<n.length;s++){let c=n[s],u=s===n.length-1;$de(c,this.supportsBinary,_=>{try{this.doWrite(c,_)}catch{eyn("websocket closed before onclose event")}u&&_N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let n=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Ike()),this.supportsBinary||(s.b64=1),this.createUri(n,s)}};t(Xut,"BaseWS");var qke=Xut,FZn=Ib.WebSocket||Ib.MozWebSocket;var eft=class eft extends qke{createSocket(n,s,c){var u;if(!((u=this.socket)===null||u===void 0)&&u._cookieJar){c.headers=c.headers||{},c.headers.cookie=typeof c.headers.cookie=="string"?[c.headers.cookie]:c.headers.cookie||[];for(let[_,g]of this.socket._cookieJar.cookies)c.headers.cookie.push(`${_}=${g.value}`)}return new Kut.default(n,s,c)}doWrite(n,s){let c={};n.options&&(c.compress=n.options.compress),this.opts.perMessageDeflate&&(typeof s=="string"?Buffer.byteLength(s):s.length)<this.opts.perMessageDeflate.threshold&&(c.compress=!1),this.ws.send(s,c)}};t(eft,"WS");var wee=eft;var nnr=uc(AV(),1);var o_e=(0,nnr.default)("engine.io-client:webtransport"),tft=class tft extends hN{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(n){return this.emitReserved("error",n)}this._transport.closed.then(()=>{o_e("transport closed gracefully"),this.onClose()}).catch(n=>{o_e("transport closed due to %s",n),this.onError("webtransport error",n)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(n=>{let s=Ntr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),c=n.readable.pipeThrough(s).getReader(),u=Dtr();u.readable.pipeTo(n.writable),this._writer=u.writable.getWriter();let _=t(()=>{c.read().then(({done:E,value:x})=>{if(E){o_e("session is closed");return}o_e("received chunk: %o",x),this.onPacket(x),_()}).catch(E=>{o_e("an error occurred while reading: %s",E)})},"read");_();let g={type:"open"};this.query.sid&&(g.data=`{"sid":"${this.query.sid}"}`),this._writer.write(g).then(()=>this.onOpen())})})}write(n){this.writable=!1;for(let s=0;s<n.length;s++){let c=n[s],u=s===n.length-1;this._writer.write(c).then(()=>{u&&_N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var n;(n=this._transport)===null||n===void 0||n.close()}};t(tft,"WT");var Iee=tft;var rft={websocket:wee,webtransport:Iee,polling:vee};var ryn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nyn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Tee(i){if(i.length>8e3)throw"URI too long";let n=i,s=i.indexOf("["),c=i.indexOf("]");s!=-1&&c!=-1&&(i=i.substring(0,s)+i.substring(s,c).replace(/:/g,";")+i.substring(c,i.length));let u=ryn.exec(i||""),_={},g=14;for(;g--;)_[nyn[g]]=u[g]||"";return s!=-1&&c!=-1&&(_.source=n,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=iyn(_,_.path),_.queryKey=syn(_,_.query),_}t(Tee,"parse");function iyn(i,n){let s=/\/{2,9}/g,c=n.replace(s,"/").split("/");return(n.slice(0,1)=="/"||n.length===0)&&c.splice(0,1),n.slice(-1)=="/"&&c.splice(c.length-1,1),c}t(iyn,"pathNames");function syn(i,n){let s={};return n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(c,u,_){u&&(s[u]=_)}),s}t(syn,"queryKey");var inr=uc(hV(),1);var snr=uc(AV(),1);var M_=(0,snr.default)("engine.io-client:socket"),nft=typeof addEventListener=="function"&&typeof removeEventListener=="function",c_e=[];nft&&addEventListener("offline",()=>{M_("closing %d connection(s) because the network was lost",c_e.length),c_e.forEach(i=>i())},!1);var xee=class xee extends inr.Emitter{constructor(n,s){if(super(),this.binaryType=Btr,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,n&&typeof n=="object"&&(s=n,n=null),n){let c=Tee(n);s.hostname=c.host,s.secure=c.protocol==="https"||c.protocol==="wss",s.port=c.port,c.query&&(s.query=c.query)}else s.host&&(s.hostname=Tee(s.host).host);mN(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(c=>{let u=c.prototype.name;this.transports.push(u),this._transportsByName[u]=c}),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},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Mtr(this.opts.query)),nft&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(M_("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},c_e.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=Ftr()),this._open()}createTransport(n){M_('creating transport "%s"',n);let s=Object.assign({},this.opts.query);s.EIO=out,s.transport=n,this.id&&(s.sid=this.id);let c=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[n]);return M_("options: %j",c),new this._transportsByName[n](c)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let n=this.opts.rememberUpgrade&&xee.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let s=this.createTransport(n);s.open(),this.setTransport(s)}setTransport(n){M_("setting transport %s",n.name),this.transport&&(M_("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=n,n.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){M_("socket open"),this.readyState="open",xee.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(M_('socket receive: type "%s", data "%s"',n.type,n.data),this.emitReserved("packet",n),this.emitReserved("heartbeat"),n.type){case"open":this.onHandshake(JSON.parse(n.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let s=new Error("server error");s.code=n.data,this._onError(s);break;case"message":this.emitReserved("data",n.data),this.emitReserved("message",n.data);break}else M_('packet received with socket readyState "%s"',this.readyState)}onHandshake(n){this.emitReserved("handshake",n),this.id=n.sid,this.transport.query.sid=n.sid,this._pingInterval=n.pingInterval,this._pingTimeout=n.pingTimeout,this._maxPayload=n.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let n=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+n,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},n),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 n=this._getWritablePackets();M_("flushing %d packets in socket",n.length),this.transport.send(n),this._prevBufferLen=n.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let c=0;c<this.writeBuffer.length;c++){let u=this.writeBuffer[c].data;if(u&&(s+=Rtr(u)),c>0&&s>this._maxPayload)return M_("only send %d out of %d packets",c,this.writeBuffer.length),this.writeBuffer.slice(0,c);s+=2}return M_("payload size is %d (max: %d)",s,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let n=Date.now()>this._pingTimeoutTime;return n&&(M_("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,_N(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),n}write(n,s,c){return this._sendPacket("message",n,s,c),this}send(n,s,c){return this._sendPacket("message",n,s,c),this}_sendPacket(n,s,c,u){if(typeof s=="function"&&(u=s,s=void 0),typeof c=="function"&&(u=c,c=null),this.readyState==="closing"||this.readyState==="closed")return;c=c||{},c.compress=c.compress!==!1;let _={type:n,data:s,options:c};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),u&&this.once("flush",u),this.flush()}close(){let n=t(()=>{this._onClose("forced close"),M_("socket closing - telling transport to close"),this.transport.close()},"close"),s=t(()=>{this.off("upgrade",s),this.off("upgradeError",s),n()},"cleanupAndClose"),c=t(()=>{this.once("upgrade",s),this.once("upgradeError",s)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?c():n()}):this.upgrading?c():n()),this}_onError(n){if(M_("socket error %j",n),xee.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return M_("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",n),this._onClose("transport error",n)}_onClose(n,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(M_('socket close with reason: "%s"',n),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nft&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let c=c_e.indexOf(this._offlineEventListener);c!==-1&&(M_("removing listener for the 'offline' event"),c_e.splice(c,1))}this.readyState="closed",this.id=null,this.emitReserved("close",n,s),this.writeBuffer=[],this._prevBufferLen=0}}};t(xee,"SocketWithoutUpgrade");var CV=xee;CV.protocol=out;var ift=class ift extends CV{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){M_("starting upgrade probes");for(let n=0;n<this._upgrades.length;n++)this._probe(this._upgrades[n])}}_probe(n){M_('probing transport "%s"',n);let s=this.createTransport(n),c=!1;CV.priorWebsocketSuccess=!1;let u=t(()=>{c||(M_('probe transport "%s" opened',n),s.send([{type:"ping",data:"probe"}]),s.once("packet",X=>{if(!c)if(X.type==="pong"&&X.data==="probe"){if(M_('probe transport "%s" pong',n),this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;CV.priorWebsocketSuccess=s.name==="websocket",M_('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{c||this.readyState!=="closed"&&(M_("changing transport and sending upgrade packet"),M(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{M_('probe transport "%s" failed',n);let W=new Error("probe error");W.transport=s.name,this.emitReserved("upgradeError",W)}}))},"onTransportOpen");function _(){c||(c=!0,M(),s.close(),s=null)}t(_,"freezeTransport");let g=t(X=>{let W=new Error("probe error: "+X);W.transport=s.name,_(),M_('probe transport "%s" failed because of error: %s',n,X),this.emitReserved("upgradeError",W)},"onerror");function E(){g("transport closed")}t(E,"onTransportClose");function x(){g("socket closed")}t(x,"onclose");function P(X){s&&X.name!==s.name&&(M_('"%s" works - aborting "%s"',X.name,s.name),_())}t(P,"onupgrade");let M=t(()=>{s.removeListener("open",u),s.removeListener("error",g),s.removeListener("close",E),this.off("close",x),this.off("upgrading",P)},"cleanup");s.once("open",u),s.once("error",g),s.once("close",E),this.once("close",x),this.once("upgrading",P),this._upgrades.indexOf("webtransport")!==-1&&n!=="webtransport"?this.setTimeoutFn(()=>{c||s.open()},200):s.open()}onHandshake(n){this._upgrades=this._filterUpgrades(n.upgrades),super.onHandshake(n)}_filterUpgrades(n){let s=[];for(let c=0;c<n.length;c++)~this.transports.indexOf(n[c])&&s.push(n[c]);return s}};t(ift,"SocketWithUpgrade");var Hke=ift,sft=class sft extends Hke{constructor(n,s={}){let c=typeof n=="object"?n:s;(!c.transports||c.transports&&typeof c.transports[0]=="string")&&(c.transports=(c.transports||["polling","websocket","webtransport"]).map(u=>rft[u]).filter(u=>!!u)),super(n,c)}};t(sft,"Socket");var kee=sft;var lKn=kee.protocol;var fnr=uc(DO(),1);var unr=(0,fnr.default)("socket.io-client:url");function pnr(i,n="",s){let c=i;s=s||typeof location<"u"&&location,i==null&&(i=s.protocol+"//"+s.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=s.protocol+i:i=s.host+i),/^(https?|wss?):\/\//.test(i)||(unr("protocol-less url %s",i),typeof s<"u"?i=s.protocol+"//"+i:i="https://"+i),unr("parse %s",i),c=Tee(i)),c.port||(/^(http|ws)$/.test(c.protocol)?c.port="80":/^(http|ws)s$/.test(c.protocol)&&(c.port="443")),c.path=c.path||"/";let _=c.host.indexOf(":")!==-1?"["+c.host+"]":c.host;return c.id=c.protocol+"://"+_+":"+c.port+n,c.href=c.protocol+"://"+_+(s&&s.port===c.port?"":":"+c.port),c}t(pnr,"url");var _ft={};OT(_ft,{Decoder:()=>pft,Encoder:()=>fft,PacketType:()=>Mu,isPacketValid:()=>Nyn,protocol:()=>ynr});var hnr=uc(hV(),1);var Syn=typeof ArrayBuffer=="function",wyn=t(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),dnr=Object.prototype.toString,Iyn=typeof Blob=="function"||typeof Blob<"u"&&dnr.call(Blob)==="[object BlobConstructor]",Tyn=typeof File=="function"||typeof File<"u"&&dnr.call(File)==="[object FileConstructor]";function u_e(i){return Syn&&(i instanceof ArrayBuffer||wyn(i))||Iyn&&i instanceof Blob||Tyn&&i instanceof File}t(u_e,"isBinary");function l_e(i,n){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let s=0,c=i.length;s<c;s++)if(l_e(i[s]))return!0;return!1}if(u_e(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return l_e(i.toJSON(),!0);for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s)&&l_e(i[s]))return!0;return!1}t(l_e,"hasBinary");function _nr(i){let n=[],s=i.data,c=i;return c.data=cft(s,n),c.attachments=n.length,{packet:c,buffers:n}}t(_nr,"deconstructPacket");function cft(i,n){if(!i)return i;if(u_e(i)){let s={_placeholder:!0,num:n.length};return n.push(i),s}else if(Array.isArray(i)){let s=new Array(i.length);for(let c=0;c<i.length;c++)s[c]=cft(i[c],n);return s}else if(typeof i=="object"&&!(i instanceof Date)){let s={};for(let c in i)Object.prototype.hasOwnProperty.call(i,c)&&(s[c]=cft(i[c],n));return s}return i}t(cft,"_deconstructPacket");function mnr(i,n){return i.data=lft(i.data,n),delete i.attachments,i}t(mnr,"reconstructPacket");function lft(i,n){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<n.length)return n[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let s=0;s<i.length;s++)i[s]=lft(i[s],n);else if(typeof i=="object")for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&(i[s]=lft(i[s],n));return i}t(lft,"_reconstructPacket");var gnr=uc(DO(),1);var uft=(0,gnr.default)("socket.io-parser"),Anr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ynr=5,Mu;(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"})(Mu||(Mu={}));var mft=class mft{constructor(n){this.replacer=n}encode(n){return uft("encoding packet %j",n),(n.type===Mu.EVENT||n.type===Mu.ACK)&&l_e(n)?this.encodeAsBinary({type:n.type===Mu.EVENT?Mu.BINARY_EVENT:Mu.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id}):[this.encodeAsString(n)]}encodeAsString(n){let s=""+n.type;return(n.type===Mu.BINARY_EVENT||n.type===Mu.BINARY_ACK)&&(s+=n.attachments+"-"),n.nsp&&n.nsp!=="/"&&(s+=n.nsp+","),n.id!=null&&(s+=n.id),n.data!=null&&(s+=JSON.stringify(n.data,this.replacer)),uft("encoded %j as %s",n,s),s}encodeAsBinary(n){let s=_nr(n),c=this.encodeAsString(s.packet),u=s.buffers;return u.unshift(c),u}};t(mft,"Encoder");var fft=mft,Kke=class Kke extends hnr.Emitter{constructor(n){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof n=="function"?{reviver:n}:n)}add(n){let s;if(typeof n=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(n);let c=s.type===Mu.BINARY_EVENT;c||s.type===Mu.BINARY_ACK?(s.type=c?Mu.EVENT:Mu.ACK,this.reconstructor=new dft(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(u_e(n)||n.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(n),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+n)}decodeString(n){let s=0,c={type:Number(n.charAt(0))};if(Mu[c.type]===void 0)throw new Error("unknown packet type "+c.type);if(c.type===Mu.BINARY_EVENT||c.type===Mu.BINARY_ACK){let _=s+1;for(;n.charAt(++s)!=="-"&&s!=n.length;);let g=n.substring(_,s);if(g!=Number(g)||n.charAt(s)!=="-")throw new Error("Illegal attachments");let E=Number(g);if(!vnr(E)||E<0)throw new Error("Illegal attachments");if(E>this.opts.maxAttachments)throw new Error("too many attachments");c.attachments=E}if(n.charAt(s+1)==="/"){let _=s+1;for(;++s&&!(n.charAt(s)===","||s===n.length););c.nsp=n.substring(_,s)}else c.nsp="/";let u=n.charAt(s+1);if(u!==""&&Number(u)==u){let _=s+1;for(;++s;){let g=n.charAt(s);if(g==null||Number(g)!=g){--s;break}if(s===n.length)break}c.id=Number(n.substring(_,s+1))}if(n.charAt(++s)){let _=this.tryParse(n.substr(s));if(Kke.isPayloadValid(c.type,_))c.data=_;else throw new Error("invalid payload")}return uft("decoded %s as %j",n,c),c}tryParse(n){try{return JSON.parse(n,this.opts.reviver)}catch{return!1}}static isPayloadValid(n,s){switch(n){case Mu.CONNECT:return Zke(s);case Mu.DISCONNECT:return s===void 0;case Mu.CONNECT_ERROR:return typeof s=="string"||Zke(s);case Mu.EVENT:case Mu.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&Anr.indexOf(s[0])===-1);case Mu.ACK:case Mu.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};t(Kke,"Decoder");var pft=Kke,hft=class hft{constructor(n){this.packet=n,this.buffers=[],this.reconPack=n}takeBinaryData(n){if(this.buffers.push(n),this.buffers.length===this.reconPack.attachments){let s=mnr(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};t(hft,"BinaryReconstructor");var dft=hft;function xyn(i){return typeof i=="string"}t(xyn,"isNamespaceValid");var vnr=Number.isInteger||function(i){return typeof i=="number"&&isFinite(i)&&Math.floor(i)===i};function kyn(i){return i===void 0||vnr(i)}t(kyn,"isAckIdValid");function Zke(i){return Object.prototype.toString.call(i)==="[object Object]"}t(Zke,"isObject");function Dyn(i,n){switch(i){case Mu.CONNECT:return n===void 0||Zke(n);case Mu.DISCONNECT:return n===void 0;case Mu.EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Anr.indexOf(n[0])===-1);case Mu.ACK:return Array.isArray(n);case Mu.CONNECT_ERROR:return typeof n=="string"||Zke(n);default:return!1}}t(Dyn,"isDataValid");function Nyn(i){return xyn(i.nsp)&&kyn(i.id)&&Dyn(i.type,i.data)}t(Nyn,"isPacketValid");function ZS(i,n,s){return i.on(n,s),t(function(){i.off(n,s)},"subDestroy")}t(ZS,"on");var bnr=uc(hV(),1),Enr=uc(DO(),1);var R1=(0,Enr.default)("socket.io-client:socket"),Pyn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gft=class gft extends bnr.Emitter{constructor(n,s,c){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=n,this.nsp=s,c&&c.auth&&(this.auth=c.auth),this._opts=Object.assign({},c),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let n=this.io;this.subs=[ZS(n,"open",this.onopen.bind(this)),ZS(n,"packet",this.onpacket.bind(this)),ZS(n,"error",this.onerror.bind(this)),ZS(n,"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(...n){return n.unshift("message"),this.emit.apply(this,n),this}emit(n,...s){var c,u,_;if(Pyn.hasOwnProperty(n))throw new Error('"'+n.toString()+'" is a reserved event name');if(s.unshift(n),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;let g={type:Mu.EVENT,data:s};if(g.options={},g.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){let M=this.ids++;R1("emitting packet with ack id %d",M);let X=s.pop();this._registerAckCallback(M,X),g.id=M}let E=(u=(c=this.io.engine)===null||c===void 0?void 0:c.transport)===null||u===void 0?void 0:u.writable,x=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!E?R1("discard packet as the transport is not currently writable"):x?(this.notifyOutgoingListeners(g),this.packet(g)):this.sendBuffer.push(g),this.flags={},this}_registerAckCallback(n,s){var c;let u=(c=this.flags.timeout)!==null&&c!==void 0?c:this._opts.ackTimeout;if(u===void 0){this.acks[n]=s;return}let _=this.io.setTimeoutFn(()=>{delete this.acks[n];for(let E=0;E<this.sendBuffer.length;E++)this.sendBuffer[E].id===n&&(R1("removing packet with ack id %d from the buffer",n),this.sendBuffer.splice(E,1));R1("event with ack id %d has timed out after %d ms",n,u),s.call(this,new Error("operation has timed out"))},u),g=t((...E)=>{this.io.clearTimeoutFn(_),s.apply(this,E)},"fn");g.withError=!0,this.acks[n]=g}emitWithAck(n,...s){return new Promise((c,u)=>{let _=t((g,E)=>g?u(g):c(E),"fn");_.withError=!0,s.push(_),this.emit(n,...s)})}_addToQueue(n){let s;typeof n[n.length-1]=="function"&&(s=n.pop());let c={id:this._queueSeq++,tryCount:0,pending:!1,args:n,flags:Object.assign({fromQueue:!0},this.flags)};n.push((u,..._)=>c!==this._queue[0]?R1("packet [%d] already acknowledged",c.id):(u!==null?c.tryCount>this._opts.retries&&(R1("packet [%d] is discarded after %d tries",c.id,c.tryCount),this._queue.shift(),s&&s(u)):(R1("packet [%d] was successfully sent",c.id),this._queue.shift(),s&&s(null,..._)),c.pending=!1,this._drainQueue())),this._queue.push(c),this._drainQueue()}_drainQueue(n=!1){if(R1("draining queue"),!this.connected||this._queue.length===0)return;let s=this._queue[0];if(s.pending&&!n){R1("packet [%d] has already been sent and is waiting for an ack",s.id);return}s.pending=!0,s.tryCount++,R1("sending packet [%d] (try n\xB0%d)",s.id,s.tryCount),this.flags=s.flags,this.emit.apply(this,s.args)}packet(n){n.nsp=this.nsp,this.io._packet(n)}onopen(){R1("transport is open - connecting"),typeof this.auth=="function"?this.auth(n=>{this._sendConnectPacket(n)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(n){this.packet({type:Mu.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},n):n})}onerror(n){this.connected||this.emitReserved("connect_error",n)}onclose(n,s){R1("close (%s)",n),this.connected=!1,delete this.id,this.emitReserved("disconnect",n,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(n=>{if(!this.sendBuffer.some(c=>String(c.id)===n)){let c=this.acks[n];delete this.acks[n],c.withError&&c.call(this,new Error("socket has been disconnected"))}})}onpacket(n){if(n.nsp===this.nsp)switch(n.type){case Mu.CONNECT:n.data&&n.data.sid?this.onconnect(n.data.sid,n.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 Mu.EVENT:case Mu.BINARY_EVENT:this.onevent(n);break;case Mu.ACK:case Mu.BINARY_ACK:this.onack(n);break;case Mu.DISCONNECT:this.ondisconnect();break;case Mu.CONNECT_ERROR:this.destroy();let c=new Error(n.data.message);c.data=n.data.data,this.emitReserved("connect_error",c);break}}onevent(n){let s=n.data||[];R1("emitting event %j",s),n.id!=null&&(R1("attaching ack callback to event"),s.push(this.ack(n.id))),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(n){if(this._anyListeners&&this._anyListeners.length){let s=this._anyListeners.slice();for(let c of s)c.apply(this,n)}super.emit.apply(this,n),this._pid&&n.length&&typeof n[n.length-1]=="string"&&(this._lastOffset=n[n.length-1])}ack(n){let s=this,c=!1;return function(...u){c||(c=!0,R1("sending ack %j",u),s.packet({type:Mu.ACK,id:n,data:u}))}}onack(n){let s=this.acks[n.id];if(typeof s!="function"){R1("bad ack %s",n.id);return}delete this.acks[n.id],R1("calling ack %s with %j",n.id,n.data),s.withError&&n.data.unshift(null),s.apply(this,n.data)}onconnect(n,s){R1("socket connected with id %s",n),this.id=n,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(n=>this.emitEvent(n)),this.receiveBuffer=[],this.sendBuffer.forEach(n=>{this.notifyOutgoingListeners(n),this.packet(n)}),this.sendBuffer=[]}ondisconnect(){R1("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(n=>n()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(R1("performing disconnect (%s)",this.nsp),this.packet({type:Mu.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(n){return this.flags.compress=n,this}get volatile(){return this.flags.volatile=!0,this}timeout(n){return this.flags.timeout=n,this}onAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(n),this}prependAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(n),this}offAny(n){if(!this._anyListeners)return this;if(n){let s=this._anyListeners;for(let c=0;c<s.length;c++)if(n===s[c])return s.splice(c,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(n),this}prependAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(n),this}offAnyOutgoing(n){if(!this._anyOutgoingListeners)return this;if(n){let s=this._anyOutgoingListeners;for(let c=0;c<s.length;c++)if(n===s[c])return s.splice(c,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(n){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let s=this._anyOutgoingListeners.slice();for(let c of s)c.apply(this,n.data)}}};t(gft,"Socket");var Dee=gft;function SV(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}t(SV,"Backoff");SV.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var n=Math.random(),s=Math.floor(n*this.jitter*i);i=Math.floor(n*10)&1?i+s:i-s}return Math.min(i,this.max)|0};SV.prototype.reset=function(){this.attempts=0};SV.prototype.setMin=function(i){this.ms=i};SV.prototype.setMax=function(i){this.max=i};SV.prototype.setJitter=function(i){this.jitter=i};var Cnr=uc(hV(),1),Snr=uc(DO(),1);var Ly=(0,Snr.default)("socket.io-client:manager"),Aft=class Aft extends Cnr.Emitter{constructor(n,s){var c;super(),this.nsps={},this.subs=[],n&&typeof n=="object"&&(s=n,n=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,mN(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((c=s.randomizationFactor)!==null&&c!==void 0?c:.5),this.backoff=new SV({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=n;let u=s.parser||_ft;this.encoder=new u.Encoder,this.decoder=new u.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(n){return arguments.length?(this._reconnection=!!n,n||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(n){return n===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=n,this)}reconnectionDelay(n){var s;return n===void 0?this._reconnectionDelay:(this._reconnectionDelay=n,(s=this.backoff)===null||s===void 0||s.setMin(n),this)}randomizationFactor(n){var s;return n===void 0?this._randomizationFactor:(this._randomizationFactor=n,(s=this.backoff)===null||s===void 0||s.setJitter(n),this)}reconnectionDelayMax(n){var s;return n===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=n,(s=this.backoff)===null||s===void 0||s.setMax(n),this)}timeout(n){return arguments.length?(this._timeout=n,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(n){if(Ly("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ly("opening %s",this.uri),this.engine=new kee(this.uri,this.opts);let s=this.engine,c=this;this._readyState="opening",this.skipReconnect=!1;let u=ZS(s,"open",function(){c.onopen(),n&&n()}),_=t(E=>{Ly("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",E),n?n(E):this.maybeReconnectOnOpen()},"onError"),g=ZS(s,"error",_);if(this._timeout!==!1){let E=this._timeout;Ly("connect attempt will timeout after %d",E);let x=this.setTimeoutFn(()=>{Ly("connect attempt timed out after %d",E),u(),_(new Error("timeout")),s.close()},E);this.opts.autoUnref&&x.unref(),this.subs.push(()=>{this.clearTimeoutFn(x)})}return this.subs.push(u),this.subs.push(g),this}connect(n){return this.open(n)}onopen(){Ly("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let n=this.engine;this.subs.push(ZS(n,"ping",this.onping.bind(this)),ZS(n,"data",this.ondata.bind(this)),ZS(n,"error",this.onerror.bind(this)),ZS(n,"close",this.onclose.bind(this)),ZS(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(n){try{this.decoder.add(n)}catch(s){this.onclose("parse error",s)}}ondecoded(n){_N(()=>{this.emitReserved("packet",n)},this.setTimeoutFn)}onerror(n){Ly("error",n),this.emitReserved("error",n)}socket(n,s){let c=this.nsps[n];return c?this._autoConnect&&!c.active&&c.connect():(c=new Dee(this,n,s),this.nsps[n]=c),c}_destroy(n){let s=Object.keys(this.nsps);for(let c of s)if(this.nsps[c].active){Ly("socket %s is still active, skipping close",c);return}this._close()}_packet(n){Ly("writing packet %j",n);let s=this.encoder.encode(n);for(let c=0;c<s.length;c++)this.engine.write(s[c],n.options)}cleanup(){Ly("cleanup"),this.subs.forEach(n=>n()),this.subs.length=0,this.decoder.destroy()}_close(){Ly("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(n,s){var c;Ly("closed due to %s",n),this.cleanup(),(c=this.engine)===null||c===void 0||c.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",n,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let n=this;if(this.backoff.attempts>=this._reconnectionAttempts)Ly("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let s=this.backoff.duration();Ly("will wait %dms before reconnect attempt",s),this._reconnecting=!0;let c=this.setTimeoutFn(()=>{n.skipReconnect||(Ly("attempting reconnect"),this.emitReserved("reconnect_attempt",n.backoff.attempts),!n.skipReconnect&&n.open(u=>{u?(Ly("reconnect attempt error"),n._reconnecting=!1,n.reconnect(),this.emitReserved("reconnect_error",u)):(Ly("reconnect success"),n.onreconnect())}))},s);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}}onreconnect(){let n=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",n)}};t(Aft,"Manager");var Nee=Aft;var Inr=uc(DO(),1);var wnr=(0,Inr.default)("socket.io-client"),f_e={};function p_e(i,n){typeof i=="object"&&(n=i,i=void 0),n=n||{};let s=pnr(i,n.path||"/socket.io"),c=s.source,u=s.id,_=s.path,g=f_e[u]&&_ in f_e[u].nsps,E=n.forceNew||n["force new connection"]||n.multiplex===!1||g,x;return E?(wnr("ignoring socket cache for %s",c),x=new Nee(c,n)):(f_e[u]||(wnr("new io instance for %s",c),f_e[u]=new Nee(c,n)),x=f_e[u]),s.query&&!n.query&&(n.query=s.queryKey),x.socket(s.path,n)}t(p_e,"lookup");Object.assign(p_e,{Manager:Nee,Socket:Dee,io:p_e,connect:p_e});var Xke={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},yft=class yft{constructor(n={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=n,this.url=n.url||Xke.URL,this.namespace=n.namespace||Xke.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((n,s)=>{this.resolveInitialization=c=>n(c),this.rejectInitialization=c=>s(c)}).then(n=>(this.resolution=n,this.log("\u2705 Client initialization successful"),n),n=>{throw this.resolution=n,this.logError("\u274C Client initialization failed:",n),n}).finally(()=>{this.disconnect()})}defineHandlers(n){return n}async startSession(n,s,c){try{if(await this.connect(),this.emit(n,s,u=>{this.resolveInitialization(u)}),c&&c>0){let u=new Promise((_,g)=>{setTimeout(()=>{g(new Error(`Session initialization timed out after ${c}ms`))},c)});return Promise.race([this.initializationPromise,u])}return this.initializationPromise}catch(u){throw this.logError("\u274C Failed to start session:",u),this.rejectInitialization(u),u}}isConnected(){var n;return((n=this.socket)==null?void 0:n.connected)||!1}getConnectionState(){return this.connectionState}success(n){return{success:!0,data:n}}error(n){return{success:!1,error:n}}log(n,...s){this.options.verbose&&console.log(`[${this.namespace}] ${n}`,...s)}logError(n,...s){this.options.verbose&&console.error(`[${this.namespace}] ${n}`,...s)}async connect(){var n;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((n=this.socket)!=null&&n.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(s){throw this.connectionState="disconnected",this.connectionPromise=null,s}return this.connectionPromise}establishConnection(){return new Promise((n,s)=>{let c=!1;try{let u=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${u}`),this.socket=p_e(u,{autoConnect:!0,reconnection:!0,reconnectionAttempts:Xke.RECONNECTION_ATTEMPTS,reconnectionDelay:Xke.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(n,s,c)}catch(u){this.logError("\u274C Failed to create socket connection:",u),c||s(u)}})}setupConnectionHandlers(n,s,c){if(!this.socket)return;let u={resolve:n,reject:s,connectionResolved:c};this.socket.on("connect",()=>this.handleConnect(u)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",_=>this.handleConnectError(_,u)),this.socket.on("disconnect",_=>this.handleDisconnect(_,u)),this.socket.io.on("reconnect_attempt",_=>this.handleReconnectAttempt(_)),this.socket.io.on("reconnect_error",_=>this.handleReconnectError(_)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(u))}handleConnect(n){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),n.connectionResolved||(n.connectionResolved=!0,n.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(n,s){var c;this.logError("\u274C Connection error:",n),this.connectionState="disconnected",!s.connectionResolved&&((c=this.socket)==null?void 0:c.disconnected)!==!1&&(s.connectionResolved=!0,s.reject(n))}handleDisconnect(n,s){this.log("\u{1F50C} Disconnected from socket:",n),this.connectionState="disconnected";let c=new Error(`Socket disconnected: ${n}`),u=!1;this.resolution===null&&n==="io server disconnect"&&(this.rejectInitialization(c),u=!0),!s.connectionResolved&&(n==="io server disconnect"||n==="transport close")&&(s.connectionResolved=!0,s.reject(c)),!u&&this.resolution===null&&this.connectionState==="disconnected"&&this.rejectInitialization(c)}handleReconnectAttempt(n){this.log(`\u{1F504} Reconnection attempt #${n}`),this.connectionState="reconnecting"}handleReconnectError(n){this.logError("\u274C Reconnection attempt failed:",n)}handleReconnectFailed(n){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),n.connectionResolved||(n.connectionResolved=!0,n.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(n,s){this.log(`\u{1F4E5} Gateway called method: ${n.key} with args:`,n.args);try{let c=this.validateGatewayCall(n);if(c){s(c);return}let u=this.handlers[n.key];if(!u){let g=`No handler registered for method: ${n.key}`;this.logError(`\u274C ${g}`),s(this.error(g));return}let _=await u(...n.args);s(this.success(_))}catch(c){this.logError("\u274C Error handling gateway call:",c),s(this.error(c.message||"Unknown error occurred"))}}validateGatewayCall(n){return n.key?Array.isArray(n.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(n,s,c){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${n}`),this.socket.emit(n,s,u=>{c(u)})}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"))}};t(yft,"AbstractClient");var e3e=yft;var Tnr,xnr,knr,Dnr,Nnr,Pnr,Bnr,Fnr,r3e=class r3e extends(Fnr=e3e,Bnr=Oh.names.getState,Pnr=Oh.names.invokeCode,Nnr=Oh.names.final_result,Dnr=Oh.names.wait,knr=Oh.names.getElementScreenshot,xnr=Oh.names.listPages,Tnr=Oh.names.switchPage,Fnr){constructor(s,c){super({verbose:Yu.testRun.autoRecovery.verboseConsoleLog,url:c.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=s;this.initData=c;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:t(async(s,c)=>{if(!this[s])throw new Error(`Tool ${s} not found`);return c.thought&&this.stepsThoughts.push(c.thought),await this[s].invoke(c)},"callLangChainTool"),getStatus:t(async s=>({sessionId:s,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[Bnr]=e5.buildTool(Oh,Oh.names.getState,async s=>this.getStateHandler(s));this[Pnr]=e5.buildTool(Oh,Oh.names.invokeCode,async s=>this.invokeCodeHandler(s));this[Nnr]=e5.buildTool(Oh,Oh.names.final_result,async s=>this.finalResultHandler(s));this[Dnr]=e5.buildTool(Oh,Oh.names.wait,async s=>this.waitHandler(s));this[knr]=e5.buildTool(Oh,Oh.names.getElementScreenshot,async s=>this.getElementScreenshotHandler(s));this[xnr]=e5.buildTool(Oh,Oh.names.listPages,async s=>this.listPagesHandler(s));this[Tnr]=e5.buildTool(Oh,Oh.names.switchPage,async s=>this.switchPageHandler(s))}async init(){let s={...this.initData,version:Oh.version};return await this.startSession("initialize",s).catch(c=>{this.utils.analytics.ARError({error:c.message});let u="Auto-Recovery attempt finished unsuccessfully";return this.utils.createChecksumStep({title:u,withError:!0}),this.utils.addAutoRecoveryErrorToReport(u,!1),{finalThought:u,stepsThoughts:[],result:"failed"}})}static async build(s){let c=await s.buildFallbackData();return new r3e(s,c)}async invokeCodeHandler(s){let c,u=this.utils.activePageGuid,g=!!(s.pageId&&s.pageId!==u?await this.utils.getPageById(s.pageId):void 0);return await this.utils.runConditionallyWithinStep(!0,s.thought||"Invoke Code",async()=>{try{g&&await this.utils.setActivePage(s.pageId);let E=await this.utils.invokeCode(s.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),c={success:!0,invokeCodeResult:`invokeCodeResult: ${E.result}`,appState:(await this.utils.buildFallbackData()).applicationState,actionEffects:E.effects}}catch(E){c={success:!1,invokeCodeResult:`Error while invoking code: ${E}`,appState:(await this.utils.buildFallbackData()).applicationState}}finally{if(g&&u)try{await this.utils.setActivePage(u)}catch(E){console.warn("Failed to switch back to original page:",E)}}}),c}async getStateHandler(s){return this.utils.createChecksumStep({title:s.thought}),this.utils.analytics.ARGetState(s.thought),{success:!0,appState:await this.utils.captureApplicationState(s.pageId,s.includeAllPages)}}async finalResultHandler(s){let c=s.result==="pass",u=this.initData.type==="assertion"?c?"soft_assertion":"hard_assertion":c?"finish":"failed",_={finalThought:s.thought,result:u,stepsThoughts:this.stepsThoughts};await Promise.resolve(),this.resolveInitialization(_);try{this.utils.analytics.ARFinalResult({finalThought:s.thought,result:u,stepsThoughts:this.stepsThoughts})}catch(g){console.warn("Failed to record auto-recovery final-result analytics:",g)}try{this.utils.addAutoRecoveryErrorToReport(s.thought,c)}catch(g){console.warn("Failed to add auto-recovery result to report:",g)}}async getElementScreenshotHandler(s){return{success:!0,screenshot:await this.utils.getScreenshotForElement(s.checksumId)}}async waitHandler(s){await new Promise(u=>setTimeout(u,s.time||5e3));let c=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${s.time} seconds, the current HTML of the application after the wait is: ${c.applicationState.reducedHTML}`}}async listPagesHandler(s){s.thought&&this.utils.createChecksumStep({title:s.thought});let c=await this.utils.pageInteractor.getTabsInfo(),u=c.map((g,E)=>`${E+1}. ${g.title||"Untitled"} (${g.url})
746
+ Result: ${JSON.stringify(M)}`);else X=M;let ce=i0n({content:X,artifact:W,toolCallId:x,name:this.name,metadata:this.metadata});return await(P==null?void 0:P.handleToolEnd(ce)),ce}},t(fee,"StructuredTool"),fee),pee,t0n=(pee=class extends vtr{schema=il.object({input:il.string().optional()}).transform(n=>n.input);constructor(n){super(n)}call(n,s){let c=typeof n=="string"||n==null?{input:n}:n;return super.call(c,s)}},t(pee,"Tool"),pee),dee,r0n=(dee=class extends t0n{static lc_name(){return"DynamicTool"}name;description;func;constructor(n){super(n),this.name=n.name,this.description=n.description,this.func=n.func,this.returnDirect=n.returnDirect??this.returnDirect}async call(n,s){let c=QTe(s);return c.runName===void 0&&(c.runName=this.name),super.call(n,c)}_call(n,s,c){return this.func(n,s,c)}},t(dee,"DynamicTool"),dee),_ee,n0n=(_ee=class extends vtr{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(n){super(n),this.name=n.name,this.description=n.description,this.func=n.func,this.returnDirect=n.returnDirect??this.returnDirect,this.schema=n.schema}async call(n,s,c){let u=QTe(s);return u.runName===void 0&&(u.runName=this.name),super.call(n,u,c)}_call(n,s,c){return this.func(n,s,c)}},t(_ee,"DynamicStructuredTool"),_ee);function nut(i,n){var g;let s=Pxe(n.schema),c=Lde(n.schema);if(!n.schema||s||c)return new r0n({...n,description:n.description??((g=n.schema)==null?void 0:g.description)??`${n.name} tool`,func:t(async(E,x,P)=>new Promise((M,X)=>{let W=w0(P,{callbacks:x==null?void 0:x.getChild()});Vv.runWithConfig(Ow(W),async()=>{try{M(i(E,W))}catch(ce){X(ce)}})}),"func")});let u=n.schema,_=n.description??n.schema.description??`${n.name} tool`;return new n0n({...n,description:_,schema:u,func:t(async(E,x,P)=>new Promise((M,X)=>{let W,ce=t(()=>{P!=null&&P.signal&&W&&P.signal.removeEventListener("abort",W)},"cleanup");P!=null&&P.signal&&(W=t(()=>{ce(),X(hO(P.signal))},"listener"),P.signal.addEventListener("abort",W,{once:!0}));let ue=w0(P,{callbacks:x==null?void 0:x.getChild()});Vv.runWithConfig(Ow(ue),async()=>{var Se;try{let Ct=await i(E,ue);if(slt(Ct)){M(Ct);return}if((Se=P==null?void 0:P.signal)!=null&&Se.aborted){ce();return}ce(),M(Ct)}catch(Ct){ce(),X(Ct)}})}),"func")})}t(nut,"tool");function i0n(i){let{content:n,artifact:s,toolCallId:c,metadata:u}=i;return c&&!bHt(n)?typeof n=="string"||Array.isArray(n)&&n.every(_=>typeof _=="object")?new VIe({status:"success",content:n,artifact:s,tool_call_id:c,name:i.name,metadata:u}):new VIe({status:"success",content:s0n(n),artifact:s,tool_call_id:c,name:i.name,metadata:u}):n}t(i0n,"_formatToolOutput");function s0n(i){try{return JSON.stringify(i)??""}catch{return`${i}`}}t(s0n,"_stringify");var dN=class dN{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 n={},s=this.toolRecord.tools;for(let c of Object.keys(s))n[c]=u=>this._addSingleTool(c,u);return n}static describeTool(n,s){if(n instanceof il.ZodObject){let c={},u=n.shape;for(let _ of Object.keys(u)){let g=u[_],E=s==null?void 0:s[_];typeof E=="string"?c[_]=g.describe(E):E&&typeof E=="object"?c[_]=dN.describeTool(g,E):c[_]=g}return il.object(c).strict()}if(n instanceof il.ZodArray){let c=n.element;return s&&typeof s=="object"&&s.element?il.array(dN.describeTool(c,s.element)):n}return n instanceof il.ZodOptional?dN.describeTool(n.unwrap(),s).optional():n instanceof il.ZodNullable?dN.describeTool(n.unwrap(),s).nullable():typeof s=="string"?n.describe(s):n}_addSingleTool(n,s){let c=s.name??String(n),_=this.toolRecord.tools[n]._create({...s,name:c,params:s.params,handler:s.handler}),g=this.toolRecord.tools[n],E=dN.describeTool(g,s.params),P=nut(t(async M=>{let X=E.parse(M);return s.handler(X)},"validatedHandler"),{name:_.name,description:_.description,schema:E});return this.toolsMap[n]=P,P}_buildOne(n,s){return this._addSingleTool(n,{...s,name:String(n)})}static buildTool(n,s,c){let u=String(s),g=n.tools[s]._create({name:u,description:"",handler:c,params:{}}),E=n.tools[s],x=dN.describeTool(E,{});return nut(t(async X=>{let W=x.parse(X);return c(W)},"validatedHandler"),{name:g.name,description:g.description,schema:x})}};t(dN,"AbstractToolContainer");var e5=dN;var Eke=class Eke{constructor(n,s){this.version=n;let c={};for(let _ in s)c[_]=_;this.names=c;let u={};for(let _ in s){let g=s[_];Object.defineProperty(g,"name",{value:_,configurable:!1,enumerable:!0,writable:!1}),g._create=(E=>x=>{let P=x.name??E;return{...x,name:P}})(_),u[_]=g}this.tools=u}static create(n,s){return new Eke(n,s)}};t(Eke,"ToolProtocol");var bke=Eke;var Oh=bke.create("v1",{readFile:il.object({path:il.string()}),getState:il.object({thought:il.string(),pageId:il.string().optional(),includeAllPages:il.boolean().optional()}),invokeCode:il.object({code:il.string().refine(i=>{let n=i.trim();return n.includes("page.getByChecksumId(")||n.includes("page.getByChecksumId(")||n.startsWith("const ")||n.startsWith("let ")||n.startsWith("var ")||n.includes("=")||n.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:il.string(),pageId:il.string().optional()}),wait:il.object({time:il.number().optional()}),scroll:il.object({checksumId:il.string(),thought:il.string()}),final_result:il.object({result:il.enum(["pass","fail"]),thought:il.string(),visualAnalysis:il.string().optional()}),getElementScreenshot:il.object({checksumId:il.string(),thought:il.string()}),listPages:il.object({thought:il.string().optional()}),switchPage:il.object({pageId:il.string(),thought:il.string().optional()}),analyze:il.object({previousImmediateSteps:il.string(),currentFailingStep:il.string(),nextImmediateSteps:il.string(),testStepToStopAt:il.string()}),think:il.object({thought:il.string()})});var but=uc(Ctr(),1);var mx=Object.create(null);mx.open="0";mx.close="1";mx.ping="2";mx.pong="3";mx.message="4";mx.upgrade="5";mx.noop="6";var qde=Object.create(null);Object.keys(mx).forEach(i=>{qde[mx[i]]=i});var Hde={type:"error",data:"parser error"};var $de=t(({type:i,data:n},s,c)=>n instanceof ArrayBuffer||ArrayBuffer.isView(n)?c(s?n:"b"+Str(n,!0).toString("base64")):c(mx[i]+(n||"")),"encodePacket"),Str=t((i,n)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!n?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),sut;function wtr(i,n){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return n(Str(i.data,!1));$de(i,!0,s=>{sut||(sut=new TextEncoder),n(sut.encode(s))})}t(wtr,"encodePacketToBinary");var Gde=t((i,n)=>{if(typeof i!="string")return{type:"message",data:Itr(i,n)};let s=i.charAt(0);if(s==="b"){let c=Buffer.from(i.substring(1),"base64");return{type:"message",data:Itr(c,n)}}return qde[s]?i.length>1?{type:qde[s],data:i.substring(1)}:{type:qde[s]}:Hde},"decodePacket"),Itr=t((i,n)=>{switch(n){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 Ttr="",xtr=t((i,n)=>{let s=i.length,c=new Array(s),u=0;i.forEach((_,g)=>{$de(_,!1,E=>{c[g]=E,++u===s&&n(c.join(Ttr))})})},"encodePayload"),ktr=t((i,n)=>{let s=i.split(Ttr),c=[];for(let u=0;u<s.length;u++){let _=Gde(s[u],n);if(c.push(_),_.type==="error")break}return c},"decodePayload");function Dtr(){return new TransformStream({transform(i,n){wtr(i,s=>{let c=s.length,u;if(c<126)u=new Uint8Array(1),new DataView(u.buffer).setUint8(0,c);else if(c<65536){u=new Uint8Array(3);let _=new DataView(u.buffer);_.setUint8(0,126),_.setUint16(1,c)}else{u=new Uint8Array(9);let _=new DataView(u.buffer);_.setUint8(0,127),_.setBigUint64(1,BigInt(c))}i.data&&typeof i.data!="string"&&(u[0]|=128),n.enqueue(u),n.enqueue(s)})}})}t(Dtr,"createPacketEncoderStream");var aut;function Cke(i){return i.reduce((n,s)=>n+s.length,0)}t(Cke,"totalLength");function Ske(i,n){if(i[0].length===n)return i.shift();let s=new Uint8Array(n),c=0;for(let u=0;u<n;u++)s[u]=i[0][c++],c===i[0].length&&(i.shift(),c=0);return i.length&&c<i[0].length&&(i[0]=i[0].slice(c)),s}t(Ske,"concatChunks");function Ntr(i,n){aut||(aut=new TextDecoder);let s=[],c=0,u=-1,_=!1;return new TransformStream({transform(g,E){for(s.push(g);;){if(c===0){if(Cke(s)<1)break;let x=Ske(s,1);_=(x[0]&128)===128,u=x[0]&127,u<126?c=3:u===126?c=1:c=2}else if(c===1){if(Cke(s)<2)break;let x=Ske(s,2);u=new DataView(x.buffer,x.byteOffset,x.length).getUint16(0),c=3}else if(c===2){if(Cke(s)<8)break;let x=Ske(s,8),P=new DataView(x.buffer,x.byteOffset,x.length),M=P.getUint32(0);if(M>Math.pow(2,21)-1){E.enqueue(Hde);break}u=M*Math.pow(2,32)+P.getUint32(4),c=3}else{if(Cke(s)<u)break;let x=Ske(s,u);E.enqueue(Gde(_?x:aut.decode(x),n)),c=0}if(u===0||u>i){E.enqueue(Hde);break}}}})}t(Ntr,"createPacketDecoderStream");var out=4;var Htr=uc(hV(),1);var _N=process.nextTick,Ib=global,Btr="nodebuffer";function Ftr(){return new cut}t(Ftr,"createCookieJar");function l0n(i){let n=i.split("; "),s=n[0].indexOf("=");if(s===-1)return;let c=n[0].substring(0,s).trim();if(!c.length)return;let u=n[0].substring(s+1).trim();u.charCodeAt(0)===34&&(u=u.slice(1,-1));let _={name:c,value:u};for(let g=1;g<n.length;g++){let E=n[g].split("=");if(E.length!==2)continue;let x=E[0].trim(),P=E[1].trim();switch(x){case"Expires":_.expires=new Date(P);break;case"Max-Age":let M=new Date;M.setUTCSeconds(M.getUTCSeconds()+parseInt(P,10)),_.expires=M;break;default:}}return _}t(l0n,"parse");var lut=class lut{constructor(){this._cookies=new Map}parseCookies(n){n&&n.forEach(s=>{let c=l0n(s);c&&this._cookies.set(c.name,c)})}get cookies(){let n=Date.now();return this._cookies.forEach((s,c)=>{var u;((u=s.expires)===null||u===void 0?void 0:u.getTime())<n&&this._cookies.delete(c)}),this._cookies.entries()}addCookies(n){let s=[];for(let[c,u]of this.cookies)s.push(`${c}=${u.value}`);s.length&&(n.setDisableHeaderCheck(!0),n.setRequestHeader("cookie",s.join("; ")))}appendCookies(n){for(let[s,c]of this.cookies)n.append("cookie",`${s}=${c.value}`)}};t(lut,"CookieJar");var cut=lut;function wke(i,...n){return n.reduce((s,c)=>(i.hasOwnProperty(c)&&(s[c]=i[c]),s),{})}t(wke,"pick");var u0n=Ib.setTimeout,f0n=Ib.clearTimeout;function mN(i,n){n.useNativeTimers?(i.setTimeoutFn=u0n.bind(Ib),i.clearTimeoutFn=f0n.bind(Ib)):(i.setTimeoutFn=Ib.setTimeout.bind(Ib),i.clearTimeoutFn=Ib.clearTimeout.bind(Ib))}t(mN,"installTimerFunctions");var p0n=1.33;function Rtr(i){return typeof i=="string"?d0n(i):Math.ceil((i.byteLength||i.size)*p0n)}t(Rtr,"byteLength");function d0n(i){let n=0,s=0;for(let c=0,u=i.length;c<u;c++)n=i.charCodeAt(c),n<128?s+=1:n<2048?s+=2:n<55296||n>=57344?s+=3:(c++,s+=4);return s}t(d0n,"utf8Length");function Ike(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}t(Ike,"randomString");function Otr(i){let n="";for(let s in i)i.hasOwnProperty(s)&&(n.length&&(n+="&"),n+=encodeURIComponent(s)+"="+encodeURIComponent(i[s]));return n}t(Otr,"encode");function Mtr(i){let n={},s=i.split("&");for(let c=0,u=s.length;c<u;c++){let _=s[c].split("=");n[decodeURIComponent(_[0])]=decodeURIComponent(_[1])}return n}t(Mtr,"decode");var $tr=uc(AV(),1);var O0n=(0,$tr.default)("engine.io-client:transport"),hut=class hut extends Error{constructor(n,s,c){super(n),this.description=s,this.context=c,this.type="TransportError"}};t(hut,"TransportError");var Nke=hut,gut=class gut extends Htr.Emitter{constructor(n){super(),this.writable=!1,mN(this,n),this.opts=n,this.query=n.query,this.socket=n.socket,this.supportsBinary=!n.forceBase64}onError(n,s,c){return super.emitReserved("error",new Nke(n,s,c)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(n){this.readyState==="open"?this.write(n):O0n("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(n){let s=Gde(n,this.socket.binaryType);this.onPacket(s)}onPacket(n){super.emitReserved("packet",n)}onClose(n){this.readyState="closed",super.emitReserved("close",n)}pause(n){}createUri(n,s={}){return n+"://"+this._hostname()+this._port()+this.opts.path+this._query(s)}_hostname(){let n=this.opts.hostname;return n.indexOf(":")===-1?n:"["+n+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(n){let s=Otr(n);return s.length?"?"+s:""}};t(gut,"Transport");var hN=gut;var Gtr=uc(AV(),1);var hx=(0,Gtr.default)("engine.io-client:polling"),Aut=class Aut extends hN{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(n){this.readyState="pausing";let s=t(()=>{hx("paused"),this.readyState="paused",n()},"pause");if(this._polling||!this.writable){let c=0;this._polling&&(hx("we are currently polling - waiting to pause"),c++,this.once("pollComplete",function(){hx("pre-pause polling complete"),--c||s()})),this.writable||(hx("we are currently writing - waiting to pause"),c++,this.once("drain",function(){hx("pre-pause writing complete"),--c||s()}))}else s()}_poll(){hx("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(n){hx("polling got data %s",n);let s=t(c=>{if(this.readyState==="opening"&&c.type==="open"&&this.onOpen(),c.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(c)},"callback");ktr(n,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():hx('ignoring poll - transport state "%s"',this.readyState))}doClose(){let n=t(()=>{hx("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(hx("transport open - closing"),n()):(hx("transport not open - deferring close"),this.once("open",n))}write(n){this.writable=!1,xtr(n,s=>{this.doWrite(s,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let n=this.opts.secure?"https":"http",s=this.query||{};return this.opts.timestampRequests!==!1&&(s[this.opts.timestampParam]=Ike()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(n,s)}};t(Aut,"Polling");var Yde=Aut;var Xtr=uc(hV(),1);var Ytr=!1;try{Ytr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Ztr=Ytr;var err=uc(AV(),1);var yut=(0,err.default)("engine.io-client:polling");function M0n(){}t(M0n,"empty");var vut=class vut extends Yde{constructor(n){if(super(n),typeof location<"u"){let s=location.protocol==="https:",c=location.port;c||(c=s?"443":"80"),this.xd=typeof location<"u"&&n.hostname!==location.hostname||c!==n.port}}doWrite(n,s){let c=this.request({method:"POST",data:n});c.on("success",s),c.on("error",(u,_)=>{this.onError("xhr post error",u,_)})}doPoll(){yut("xhr poll");let n=this.request();n.on("data",this.onData.bind(this)),n.on("error",(s,c)=>{this.onError("xhr poll error",s,c)}),this.pollXhr=n}};t(vut,"BaseXHR");var Pke=vut,yee=class yee extends Xtr.Emitter{constructor(n,s,c){super(),this.createRequest=n,mN(this,c),this._opts=c,this._method=c.method||"GET",this._uri=s,this._data=c.data!==void 0?c.data:null,this._create()}_create(){var n;let s=wke(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;let c=this._xhr=this.createRequest(s);try{yut("xhr open %s: %s",this._method,this._uri),c.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){c.setDisableHeaderCheck&&c.setDisableHeaderCheck(!0);for(let u in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(u)&&c.setRequestHeader(u,this._opts.extraHeaders[u])}}catch{}if(this._method==="POST")try{c.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{c.setRequestHeader("Accept","*/*")}catch{}(n=this._opts.cookieJar)===null||n===void 0||n.addCookies(c),"withCredentials"in c&&(c.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(c.timeout=this._opts.requestTimeout),c.onreadystatechange=()=>{var u;c.readyState===3&&((u=this._opts.cookieJar)===null||u===void 0||u.parseCookies(c.getResponseHeader("set-cookie"))),c.readyState===4&&(c.status===200||c.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof c.status=="number"?c.status:0)},0))},yut("xhr data %s",this._data),c.send(this._data)}catch(u){this.setTimeoutFn(()=>{this._onError(u)},0);return}typeof document<"u"&&(this._index=yee.requestsCount++,yee.requests[this._index]=this)}_onError(n){this.emitReserved("error",n,this._xhr),this._cleanup(!0)}_cleanup(n){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=M0n,n)try{this._xhr.abort()}catch{}typeof document<"u"&&delete yee.requests[this._index],this._xhr=null}}_onLoad(){let n=this._xhr.responseText;n!==null&&(this.emitReserved("data",n),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};t(yee,"Request");var gN=yee;gN.requestsCount=0;gN.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ktr);else if(typeof addEventListener=="function"){let i="onpagehide"in Ib?"pagehide":"unload";addEventListener(i,Ktr,!1)}}function Ktr(){for(let i in gN.requests)gN.requests.hasOwnProperty(i)&&gN.requests[i].abort()}t(Ktr,"unloadHandler");var $Yn=function(){let i=L0n({xdomain:!1});return i&&i.responseType!==null}();function L0n(i){let n=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!n||Ztr))return new XMLHttpRequest}catch{}if(!n)try{return new Ib[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}t(L0n,"newRequest");var Q0n=but.default||but,Eut=class Eut extends Pke{request(n={}){var s;return Object.assign(n,{xd:this.xd,cookieJar:(s=this.socket)===null||s===void 0?void 0:s._cookieJar},this.opts),new gN(c=>new Q0n(c),this.uri(),n)}};t(Eut,"XHR");var vee=Eut;var GAn=uc(irr(),1),YAn=uc(Out(),1),ZAn=uc(Lut(),1),Kut=uc(Gut(),1),KAn=uc(tnr(),1);var rnr=uc(AV(),1);var eyn=(0,rnr.default)("engine.io-client:websocket"),tyn=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Xut=class Xut extends hN{get name(){return"websocket"}doOpen(){let n=this.uri(),s=this.opts.protocols,c=tyn?{}:wke(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(c.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(n,s,c)}catch(u){return this.emitReserved("error",u)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=n=>this.onClose({description:"websocket connection closed",context:n}),this.ws.onmessage=n=>this.onData(n.data),this.ws.onerror=n=>this.onError("websocket error",n)}write(n){this.writable=!1;for(let s=0;s<n.length;s++){let c=n[s],u=s===n.length-1;$de(c,this.supportsBinary,_=>{try{this.doWrite(c,_)}catch{eyn("websocket closed before onclose event")}u&&_N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let n=this.opts.secure?"wss":"ws",s=this.query||{};return this.opts.timestampRequests&&(s[this.opts.timestampParam]=Ike()),this.supportsBinary||(s.b64=1),this.createUri(n,s)}};t(Xut,"BaseWS");var qke=Xut,FZn=Ib.WebSocket||Ib.MozWebSocket;var eft=class eft extends qke{createSocket(n,s,c){var u;if(!((u=this.socket)===null||u===void 0)&&u._cookieJar){c.headers=c.headers||{},c.headers.cookie=typeof c.headers.cookie=="string"?[c.headers.cookie]:c.headers.cookie||[];for(let[_,g]of this.socket._cookieJar.cookies)c.headers.cookie.push(`${_}=${g.value}`)}return new Kut.default(n,s,c)}doWrite(n,s){let c={};n.options&&(c.compress=n.options.compress),this.opts.perMessageDeflate&&(typeof s=="string"?Buffer.byteLength(s):s.length)<this.opts.perMessageDeflate.threshold&&(c.compress=!1),this.ws.send(s,c)}};t(eft,"WS");var wee=eft;var nnr=uc(AV(),1);var o_e=(0,nnr.default)("engine.io-client:webtransport"),tft=class tft extends hN{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(n){return this.emitReserved("error",n)}this._transport.closed.then(()=>{o_e("transport closed gracefully"),this.onClose()}).catch(n=>{o_e("transport closed due to %s",n),this.onError("webtransport error",n)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(n=>{let s=Ntr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),c=n.readable.pipeThrough(s).getReader(),u=Dtr();u.readable.pipeTo(n.writable),this._writer=u.writable.getWriter();let _=t(()=>{c.read().then(({done:E,value:x})=>{if(E){o_e("session is closed");return}o_e("received chunk: %o",x),this.onPacket(x),_()}).catch(E=>{o_e("an error occurred while reading: %s",E)})},"read");_();let g={type:"open"};this.query.sid&&(g.data=`{"sid":"${this.query.sid}"}`),this._writer.write(g).then(()=>this.onOpen())})})}write(n){this.writable=!1;for(let s=0;s<n.length;s++){let c=n[s],u=s===n.length-1;this._writer.write(c).then(()=>{u&&_N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var n;(n=this._transport)===null||n===void 0||n.close()}};t(tft,"WT");var Iee=tft;var rft={websocket:wee,webtransport:Iee,polling:vee};var ryn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nyn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Tee(i){if(i.length>8e3)throw"URI too long";let n=i,s=i.indexOf("["),c=i.indexOf("]");s!=-1&&c!=-1&&(i=i.substring(0,s)+i.substring(s,c).replace(/:/g,";")+i.substring(c,i.length));let u=ryn.exec(i||""),_={},g=14;for(;g--;)_[nyn[g]]=u[g]||"";return s!=-1&&c!=-1&&(_.source=n,_.host=_.host.substring(1,_.host.length-1).replace(/;/g,":"),_.authority=_.authority.replace("[","").replace("]","").replace(/;/g,":"),_.ipv6uri=!0),_.pathNames=iyn(_,_.path),_.queryKey=syn(_,_.query),_}t(Tee,"parse");function iyn(i,n){let s=/\/{2,9}/g,c=n.replace(s,"/").split("/");return(n.slice(0,1)=="/"||n.length===0)&&c.splice(0,1),n.slice(-1)=="/"&&c.splice(c.length-1,1),c}t(iyn,"pathNames");function syn(i,n){let s={};return n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(c,u,_){u&&(s[u]=_)}),s}t(syn,"queryKey");var inr=uc(hV(),1);var snr=uc(AV(),1);var M_=(0,snr.default)("engine.io-client:socket"),nft=typeof addEventListener=="function"&&typeof removeEventListener=="function",c_e=[];nft&&addEventListener("offline",()=>{M_("closing %d connection(s) because the network was lost",c_e.length),c_e.forEach(i=>i())},!1);var xee=class xee extends inr.Emitter{constructor(n,s){if(super(),this.binaryType=Btr,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,n&&typeof n=="object"&&(s=n,n=null),n){let c=Tee(n);s.hostname=c.host,s.secure=c.protocol==="https"||c.protocol==="wss",s.port=c.port,c.query&&(s.query=c.query)}else s.host&&(s.hostname=Tee(s.host).host);mN(this,s),this.secure=s.secure!=null?s.secure:typeof location<"u"&&location.protocol==="https:",s.hostname&&!s.port&&(s.port=this.secure?"443":"80"),this.hostname=s.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=s.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},s.transports.forEach(c=>{let u=c.prototype.name;this.transports.push(u),this._transportsByName[u]=c}),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},s),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Mtr(this.opts.query)),nft&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(M_("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},c_e.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=Ftr()),this._open()}createTransport(n){M_('creating transport "%s"',n);let s=Object.assign({},this.opts.query);s.EIO=out,s.transport=n,this.id&&(s.sid=this.id);let c=Object.assign({},this.opts,{query:s,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[n]);return M_("options: %j",c),new this._transportsByName[n](c)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let n=this.opts.rememberUpgrade&&xee.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let s=this.createTransport(n);s.open(),this.setTransport(s)}setTransport(n){M_("setting transport %s",n.name),this.transport&&(M_("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=n,n.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",s=>this._onClose("transport close",s))}onOpen(){M_("socket open"),this.readyState="open",xee.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(M_('socket receive: type "%s", data "%s"',n.type,n.data),this.emitReserved("packet",n),this.emitReserved("heartbeat"),n.type){case"open":this.onHandshake(JSON.parse(n.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let s=new Error("server error");s.code=n.data,this._onError(s);break;case"message":this.emitReserved("data",n.data),this.emitReserved("message",n.data);break}else M_('packet received with socket readyState "%s"',this.readyState)}onHandshake(n){this.emitReserved("handshake",n),this.id=n.sid,this.transport.query.sid=n.sid,this._pingInterval=n.pingInterval,this._pingTimeout=n.pingTimeout,this._maxPayload=n.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let n=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+n,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},n),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 n=this._getWritablePackets();M_("flushing %d packets in socket",n.length),this.transport.send(n),this._prevBufferLen=n.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let s=1;for(let c=0;c<this.writeBuffer.length;c++){let u=this.writeBuffer[c].data;if(u&&(s+=Rtr(u)),c>0&&s>this._maxPayload)return M_("only send %d out of %d packets",c,this.writeBuffer.length),this.writeBuffer.slice(0,c);s+=2}return M_("payload size is %d (max: %d)",s,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let n=Date.now()>this._pingTimeoutTime;return n&&(M_("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,_N(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),n}write(n,s,c){return this._sendPacket("message",n,s,c),this}send(n,s,c){return this._sendPacket("message",n,s,c),this}_sendPacket(n,s,c,u){if(typeof s=="function"&&(u=s,s=void 0),typeof c=="function"&&(u=c,c=null),this.readyState==="closing"||this.readyState==="closed")return;c=c||{},c.compress=c.compress!==!1;let _={type:n,data:s,options:c};this.emitReserved("packetCreate",_),this.writeBuffer.push(_),u&&this.once("flush",u),this.flush()}close(){let n=t(()=>{this._onClose("forced close"),M_("socket closing - telling transport to close"),this.transport.close()},"close"),s=t(()=>{this.off("upgrade",s),this.off("upgradeError",s),n()},"cleanupAndClose"),c=t(()=>{this.once("upgrade",s),this.once("upgradeError",s)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?c():n()}):this.upgrading?c():n()),this}_onError(n){if(M_("socket error %j",n),xee.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return M_("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",n),this._onClose("transport error",n)}_onClose(n,s){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(M_('socket close with reason: "%s"',n),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nft&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let c=c_e.indexOf(this._offlineEventListener);c!==-1&&(M_("removing listener for the 'offline' event"),c_e.splice(c,1))}this.readyState="closed",this.id=null,this.emitReserved("close",n,s),this.writeBuffer=[],this._prevBufferLen=0}}};t(xee,"SocketWithoutUpgrade");var CV=xee;CV.protocol=out;var ift=class ift extends CV{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){M_("starting upgrade probes");for(let n=0;n<this._upgrades.length;n++)this._probe(this._upgrades[n])}}_probe(n){M_('probing transport "%s"',n);let s=this.createTransport(n),c=!1;CV.priorWebsocketSuccess=!1;let u=t(()=>{c||(M_('probe transport "%s" opened',n),s.send([{type:"ping",data:"probe"}]),s.once("packet",X=>{if(!c)if(X.type==="pong"&&X.data==="probe"){if(M_('probe transport "%s" pong',n),this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;CV.priorWebsocketSuccess=s.name==="websocket",M_('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{c||this.readyState!=="closed"&&(M_("changing transport and sending upgrade packet"),M(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{M_('probe transport "%s" failed',n);let W=new Error("probe error");W.transport=s.name,this.emitReserved("upgradeError",W)}}))},"onTransportOpen");function _(){c||(c=!0,M(),s.close(),s=null)}t(_,"freezeTransport");let g=t(X=>{let W=new Error("probe error: "+X);W.transport=s.name,_(),M_('probe transport "%s" failed because of error: %s',n,X),this.emitReserved("upgradeError",W)},"onerror");function E(){g("transport closed")}t(E,"onTransportClose");function x(){g("socket closed")}t(x,"onclose");function P(X){s&&X.name!==s.name&&(M_('"%s" works - aborting "%s"',X.name,s.name),_())}t(P,"onupgrade");let M=t(()=>{s.removeListener("open",u),s.removeListener("error",g),s.removeListener("close",E),this.off("close",x),this.off("upgrading",P)},"cleanup");s.once("open",u),s.once("error",g),s.once("close",E),this.once("close",x),this.once("upgrading",P),this._upgrades.indexOf("webtransport")!==-1&&n!=="webtransport"?this.setTimeoutFn(()=>{c||s.open()},200):s.open()}onHandshake(n){this._upgrades=this._filterUpgrades(n.upgrades),super.onHandshake(n)}_filterUpgrades(n){let s=[];for(let c=0;c<n.length;c++)~this.transports.indexOf(n[c])&&s.push(n[c]);return s}};t(ift,"SocketWithUpgrade");var Hke=ift,sft=class sft extends Hke{constructor(n,s={}){let c=typeof n=="object"?n:s;(!c.transports||c.transports&&typeof c.transports[0]=="string")&&(c.transports=(c.transports||["polling","websocket","webtransport"]).map(u=>rft[u]).filter(u=>!!u)),super(n,c)}};t(sft,"Socket");var kee=sft;var lKn=kee.protocol;var fnr=uc(DO(),1);var unr=(0,fnr.default)("socket.io-client:url");function pnr(i,n="",s){let c=i;s=s||typeof location<"u"&&location,i==null&&(i=s.protocol+"//"+s.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=s.protocol+i:i=s.host+i),/^(https?|wss?):\/\//.test(i)||(unr("protocol-less url %s",i),typeof s<"u"?i=s.protocol+"//"+i:i="https://"+i),unr("parse %s",i),c=Tee(i)),c.port||(/^(http|ws)$/.test(c.protocol)?c.port="80":/^(http|ws)s$/.test(c.protocol)&&(c.port="443")),c.path=c.path||"/";let _=c.host.indexOf(":")!==-1?"["+c.host+"]":c.host;return c.id=c.protocol+"://"+_+":"+c.port+n,c.href=c.protocol+"://"+_+(s&&s.port===c.port?"":":"+c.port),c}t(pnr,"url");var _ft={};OT(_ft,{Decoder:()=>pft,Encoder:()=>fft,PacketType:()=>Mu,isPacketValid:()=>Nyn,protocol:()=>ynr});var hnr=uc(hV(),1);var Syn=typeof ArrayBuffer=="function",wyn=t(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),dnr=Object.prototype.toString,Iyn=typeof Blob=="function"||typeof Blob<"u"&&dnr.call(Blob)==="[object BlobConstructor]",Tyn=typeof File=="function"||typeof File<"u"&&dnr.call(File)==="[object FileConstructor]";function u_e(i){return Syn&&(i instanceof ArrayBuffer||wyn(i))||Iyn&&i instanceof Blob||Tyn&&i instanceof File}t(u_e,"isBinary");function l_e(i,n){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let s=0,c=i.length;s<c;s++)if(l_e(i[s]))return!0;return!1}if(u_e(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return l_e(i.toJSON(),!0);for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s)&&l_e(i[s]))return!0;return!1}t(l_e,"hasBinary");function _nr(i){let n=[],s=i.data,c=i;return c.data=cft(s,n),c.attachments=n.length,{packet:c,buffers:n}}t(_nr,"deconstructPacket");function cft(i,n){if(!i)return i;if(u_e(i)){let s={_placeholder:!0,num:n.length};return n.push(i),s}else if(Array.isArray(i)){let s=new Array(i.length);for(let c=0;c<i.length;c++)s[c]=cft(i[c],n);return s}else if(typeof i=="object"&&!(i instanceof Date)){let s={};for(let c in i)Object.prototype.hasOwnProperty.call(i,c)&&(s[c]=cft(i[c],n));return s}return i}t(cft,"_deconstructPacket");function mnr(i,n){return i.data=lft(i.data,n),delete i.attachments,i}t(mnr,"reconstructPacket");function lft(i,n){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<n.length)return n[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let s=0;s<i.length;s++)i[s]=lft(i[s],n);else if(typeof i=="object")for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&(i[s]=lft(i[s],n));return i}t(lft,"_reconstructPacket");var gnr=uc(DO(),1);var uft=(0,gnr.default)("socket.io-parser"),Anr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ynr=5,Mu;(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"})(Mu||(Mu={}));var mft=class mft{constructor(n){this.replacer=n}encode(n){return uft("encoding packet %j",n),(n.type===Mu.EVENT||n.type===Mu.ACK)&&l_e(n)?this.encodeAsBinary({type:n.type===Mu.EVENT?Mu.BINARY_EVENT:Mu.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id}):[this.encodeAsString(n)]}encodeAsString(n){let s=""+n.type;return(n.type===Mu.BINARY_EVENT||n.type===Mu.BINARY_ACK)&&(s+=n.attachments+"-"),n.nsp&&n.nsp!=="/"&&(s+=n.nsp+","),n.id!=null&&(s+=n.id),n.data!=null&&(s+=JSON.stringify(n.data,this.replacer)),uft("encoded %j as %s",n,s),s}encodeAsBinary(n){let s=_nr(n),c=this.encodeAsString(s.packet),u=s.buffers;return u.unshift(c),u}};t(mft,"Encoder");var fft=mft,Kke=class Kke extends hnr.Emitter{constructor(n){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof n=="function"?{reviver:n}:n)}add(n){let s;if(typeof n=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");s=this.decodeString(n);let c=s.type===Mu.BINARY_EVENT;c||s.type===Mu.BINARY_ACK?(s.type=c?Mu.EVENT:Mu.ACK,this.reconstructor=new dft(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(u_e(n)||n.base64)if(this.reconstructor)s=this.reconstructor.takeBinaryData(n),s&&(this.reconstructor=null,super.emitReserved("decoded",s));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+n)}decodeString(n){let s=0,c={type:Number(n.charAt(0))};if(Mu[c.type]===void 0)throw new Error("unknown packet type "+c.type);if(c.type===Mu.BINARY_EVENT||c.type===Mu.BINARY_ACK){let _=s+1;for(;n.charAt(++s)!=="-"&&s!=n.length;);let g=n.substring(_,s);if(g!=Number(g)||n.charAt(s)!=="-")throw new Error("Illegal attachments");let E=Number(g);if(!vnr(E)||E<0)throw new Error("Illegal attachments");if(E>this.opts.maxAttachments)throw new Error("too many attachments");c.attachments=E}if(n.charAt(s+1)==="/"){let _=s+1;for(;++s&&!(n.charAt(s)===","||s===n.length););c.nsp=n.substring(_,s)}else c.nsp="/";let u=n.charAt(s+1);if(u!==""&&Number(u)==u){let _=s+1;for(;++s;){let g=n.charAt(s);if(g==null||Number(g)!=g){--s;break}if(s===n.length)break}c.id=Number(n.substring(_,s+1))}if(n.charAt(++s)){let _=this.tryParse(n.substr(s));if(Kke.isPayloadValid(c.type,_))c.data=_;else throw new Error("invalid payload")}return uft("decoded %s as %j",n,c),c}tryParse(n){try{return JSON.parse(n,this.opts.reviver)}catch{return!1}}static isPayloadValid(n,s){switch(n){case Mu.CONNECT:return Zke(s);case Mu.DISCONNECT:return s===void 0;case Mu.CONNECT_ERROR:return typeof s=="string"||Zke(s);case Mu.EVENT:case Mu.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&Anr.indexOf(s[0])===-1);case Mu.ACK:case Mu.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};t(Kke,"Decoder");var pft=Kke,hft=class hft{constructor(n){this.packet=n,this.buffers=[],this.reconPack=n}takeBinaryData(n){if(this.buffers.push(n),this.buffers.length===this.reconPack.attachments){let s=mnr(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};t(hft,"BinaryReconstructor");var dft=hft;function xyn(i){return typeof i=="string"}t(xyn,"isNamespaceValid");var vnr=Number.isInteger||function(i){return typeof i=="number"&&isFinite(i)&&Math.floor(i)===i};function kyn(i){return i===void 0||vnr(i)}t(kyn,"isAckIdValid");function Zke(i){return Object.prototype.toString.call(i)==="[object Object]"}t(Zke,"isObject");function Dyn(i,n){switch(i){case Mu.CONNECT:return n===void 0||Zke(n);case Mu.DISCONNECT:return n===void 0;case Mu.EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Anr.indexOf(n[0])===-1);case Mu.ACK:return Array.isArray(n);case Mu.CONNECT_ERROR:return typeof n=="string"||Zke(n);default:return!1}}t(Dyn,"isDataValid");function Nyn(i){return xyn(i.nsp)&&kyn(i.id)&&Dyn(i.type,i.data)}t(Nyn,"isPacketValid");function ZS(i,n,s){return i.on(n,s),t(function(){i.off(n,s)},"subDestroy")}t(ZS,"on");var bnr=uc(hV(),1),Enr=uc(DO(),1);var R1=(0,Enr.default)("socket.io-client:socket"),Pyn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gft=class gft extends bnr.Emitter{constructor(n,s,c){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=n,this.nsp=s,c&&c.auth&&(this.auth=c.auth),this._opts=Object.assign({},c),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let n=this.io;this.subs=[ZS(n,"open",this.onopen.bind(this)),ZS(n,"packet",this.onpacket.bind(this)),ZS(n,"error",this.onerror.bind(this)),ZS(n,"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(...n){return n.unshift("message"),this.emit.apply(this,n),this}emit(n,...s){var c,u,_;if(Pyn.hasOwnProperty(n))throw new Error('"'+n.toString()+'" is a reserved event name');if(s.unshift(n),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(s),this;let g={type:Mu.EVENT,data:s};if(g.options={},g.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){let M=this.ids++;R1("emitting packet with ack id %d",M);let X=s.pop();this._registerAckCallback(M,X),g.id=M}let E=(u=(c=this.io.engine)===null||c===void 0?void 0:c.transport)===null||u===void 0?void 0:u.writable,x=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!E?R1("discard packet as the transport is not currently writable"):x?(this.notifyOutgoingListeners(g),this.packet(g)):this.sendBuffer.push(g),this.flags={},this}_registerAckCallback(n,s){var c;let u=(c=this.flags.timeout)!==null&&c!==void 0?c:this._opts.ackTimeout;if(u===void 0){this.acks[n]=s;return}let _=this.io.setTimeoutFn(()=>{delete this.acks[n];for(let E=0;E<this.sendBuffer.length;E++)this.sendBuffer[E].id===n&&(R1("removing packet with ack id %d from the buffer",n),this.sendBuffer.splice(E,1));R1("event with ack id %d has timed out after %d ms",n,u),s.call(this,new Error("operation has timed out"))},u),g=t((...E)=>{this.io.clearTimeoutFn(_),s.apply(this,E)},"fn");g.withError=!0,this.acks[n]=g}emitWithAck(n,...s){return new Promise((c,u)=>{let _=t((g,E)=>g?u(g):c(E),"fn");_.withError=!0,s.push(_),this.emit(n,...s)})}_addToQueue(n){let s;typeof n[n.length-1]=="function"&&(s=n.pop());let c={id:this._queueSeq++,tryCount:0,pending:!1,args:n,flags:Object.assign({fromQueue:!0},this.flags)};n.push((u,..._)=>c!==this._queue[0]?R1("packet [%d] already acknowledged",c.id):(u!==null?c.tryCount>this._opts.retries&&(R1("packet [%d] is discarded after %d tries",c.id,c.tryCount),this._queue.shift(),s&&s(u)):(R1("packet [%d] was successfully sent",c.id),this._queue.shift(),s&&s(null,..._)),c.pending=!1,this._drainQueue())),this._queue.push(c),this._drainQueue()}_drainQueue(n=!1){if(R1("draining queue"),!this.connected||this._queue.length===0)return;let s=this._queue[0];if(s.pending&&!n){R1("packet [%d] has already been sent and is waiting for an ack",s.id);return}s.pending=!0,s.tryCount++,R1("sending packet [%d] (try n\xB0%d)",s.id,s.tryCount),this.flags=s.flags,this.emit.apply(this,s.args)}packet(n){n.nsp=this.nsp,this.io._packet(n)}onopen(){R1("transport is open - connecting"),typeof this.auth=="function"?this.auth(n=>{this._sendConnectPacket(n)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(n){this.packet({type:Mu.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},n):n})}onerror(n){this.connected||this.emitReserved("connect_error",n)}onclose(n,s){R1("close (%s)",n),this.connected=!1,delete this.id,this.emitReserved("disconnect",n,s),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(n=>{if(!this.sendBuffer.some(c=>String(c.id)===n)){let c=this.acks[n];delete this.acks[n],c.withError&&c.call(this,new Error("socket has been disconnected"))}})}onpacket(n){if(n.nsp===this.nsp)switch(n.type){case Mu.CONNECT:n.data&&n.data.sid?this.onconnect(n.data.sid,n.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 Mu.EVENT:case Mu.BINARY_EVENT:this.onevent(n);break;case Mu.ACK:case Mu.BINARY_ACK:this.onack(n);break;case Mu.DISCONNECT:this.ondisconnect();break;case Mu.CONNECT_ERROR:this.destroy();let c=new Error(n.data.message);c.data=n.data.data,this.emitReserved("connect_error",c);break}}onevent(n){let s=n.data||[];R1("emitting event %j",s),n.id!=null&&(R1("attaching ack callback to event"),s.push(this.ack(n.id))),this.connected?this.emitEvent(s):this.receiveBuffer.push(Object.freeze(s))}emitEvent(n){if(this._anyListeners&&this._anyListeners.length){let s=this._anyListeners.slice();for(let c of s)c.apply(this,n)}super.emit.apply(this,n),this._pid&&n.length&&typeof n[n.length-1]=="string"&&(this._lastOffset=n[n.length-1])}ack(n){let s=this,c=!1;return function(...u){c||(c=!0,R1("sending ack %j",u),s.packet({type:Mu.ACK,id:n,data:u}))}}onack(n){let s=this.acks[n.id];if(typeof s!="function"){R1("bad ack %s",n.id);return}delete this.acks[n.id],R1("calling ack %s with %j",n.id,n.data),s.withError&&n.data.unshift(null),s.apply(this,n.data)}onconnect(n,s){R1("socket connected with id %s",n),this.id=n,this.recovered=s&&this._pid===s,this._pid=s,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(n=>this.emitEvent(n)),this.receiveBuffer=[],this.sendBuffer.forEach(n=>{this.notifyOutgoingListeners(n),this.packet(n)}),this.sendBuffer=[]}ondisconnect(){R1("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(n=>n()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(R1("performing disconnect (%s)",this.nsp),this.packet({type:Mu.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(n){return this.flags.compress=n,this}get volatile(){return this.flags.volatile=!0,this}timeout(n){return this.flags.timeout=n,this}onAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(n),this}prependAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(n),this}offAny(n){if(!this._anyListeners)return this;if(n){let s=this._anyListeners;for(let c=0;c<s.length;c++)if(n===s[c])return s.splice(c,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(n),this}prependAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(n),this}offAnyOutgoing(n){if(!this._anyOutgoingListeners)return this;if(n){let s=this._anyOutgoingListeners;for(let c=0;c<s.length;c++)if(n===s[c])return s.splice(c,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(n){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let s=this._anyOutgoingListeners.slice();for(let c of s)c.apply(this,n.data)}}};t(gft,"Socket");var Dee=gft;function SV(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}t(SV,"Backoff");SV.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var n=Math.random(),s=Math.floor(n*this.jitter*i);i=Math.floor(n*10)&1?i+s:i-s}return Math.min(i,this.max)|0};SV.prototype.reset=function(){this.attempts=0};SV.prototype.setMin=function(i){this.ms=i};SV.prototype.setMax=function(i){this.max=i};SV.prototype.setJitter=function(i){this.jitter=i};var Cnr=uc(hV(),1),Snr=uc(DO(),1);var Ly=(0,Snr.default)("socket.io-client:manager"),Aft=class Aft extends Cnr.Emitter{constructor(n,s){var c;super(),this.nsps={},this.subs=[],n&&typeof n=="object"&&(s=n,n=void 0),s=s||{},s.path=s.path||"/socket.io",this.opts=s,mN(this,s),this.reconnection(s.reconnection!==!1),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor((c=s.randomizationFactor)!==null&&c!==void 0?c:.5),this.backoff=new SV({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(s.timeout==null?2e4:s.timeout),this._readyState="closed",this.uri=n;let u=s.parser||_ft;this.encoder=new u.Encoder,this.decoder=new u.Decoder,this._autoConnect=s.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(n){return arguments.length?(this._reconnection=!!n,n||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(n){return n===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=n,this)}reconnectionDelay(n){var s;return n===void 0?this._reconnectionDelay:(this._reconnectionDelay=n,(s=this.backoff)===null||s===void 0||s.setMin(n),this)}randomizationFactor(n){var s;return n===void 0?this._randomizationFactor:(this._randomizationFactor=n,(s=this.backoff)===null||s===void 0||s.setJitter(n),this)}reconnectionDelayMax(n){var s;return n===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=n,(s=this.backoff)===null||s===void 0||s.setMax(n),this)}timeout(n){return arguments.length?(this._timeout=n,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(n){if(Ly("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ly("opening %s",this.uri),this.engine=new kee(this.uri,this.opts);let s=this.engine,c=this;this._readyState="opening",this.skipReconnect=!1;let u=ZS(s,"open",function(){c.onopen(),n&&n()}),_=t(E=>{Ly("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",E),n?n(E):this.maybeReconnectOnOpen()},"onError"),g=ZS(s,"error",_);if(this._timeout!==!1){let E=this._timeout;Ly("connect attempt will timeout after %d",E);let x=this.setTimeoutFn(()=>{Ly("connect attempt timed out after %d",E),u(),_(new Error("timeout")),s.close()},E);this.opts.autoUnref&&x.unref(),this.subs.push(()=>{this.clearTimeoutFn(x)})}return this.subs.push(u),this.subs.push(g),this}connect(n){return this.open(n)}onopen(){Ly("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let n=this.engine;this.subs.push(ZS(n,"ping",this.onping.bind(this)),ZS(n,"data",this.ondata.bind(this)),ZS(n,"error",this.onerror.bind(this)),ZS(n,"close",this.onclose.bind(this)),ZS(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(n){try{this.decoder.add(n)}catch(s){this.onclose("parse error",s)}}ondecoded(n){_N(()=>{this.emitReserved("packet",n)},this.setTimeoutFn)}onerror(n){Ly("error",n),this.emitReserved("error",n)}socket(n,s){let c=this.nsps[n];return c?this._autoConnect&&!c.active&&c.connect():(c=new Dee(this,n,s),this.nsps[n]=c),c}_destroy(n){let s=Object.keys(this.nsps);for(let c of s)if(this.nsps[c].active){Ly("socket %s is still active, skipping close",c);return}this._close()}_packet(n){Ly("writing packet %j",n);let s=this.encoder.encode(n);for(let c=0;c<s.length;c++)this.engine.write(s[c],n.options)}cleanup(){Ly("cleanup"),this.subs.forEach(n=>n()),this.subs.length=0,this.decoder.destroy()}_close(){Ly("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(n,s){var c;Ly("closed due to %s",n),this.cleanup(),(c=this.engine)===null||c===void 0||c.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",n,s),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let n=this;if(this.backoff.attempts>=this._reconnectionAttempts)Ly("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let s=this.backoff.duration();Ly("will wait %dms before reconnect attempt",s),this._reconnecting=!0;let c=this.setTimeoutFn(()=>{n.skipReconnect||(Ly("attempting reconnect"),this.emitReserved("reconnect_attempt",n.backoff.attempts),!n.skipReconnect&&n.open(u=>{u?(Ly("reconnect attempt error"),n._reconnecting=!1,n.reconnect(),this.emitReserved("reconnect_error",u)):(Ly("reconnect success"),n.onreconnect())}))},s);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}}onreconnect(){let n=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",n)}};t(Aft,"Manager");var Nee=Aft;var Inr=uc(DO(),1);var wnr=(0,Inr.default)("socket.io-client"),f_e={};function p_e(i,n){typeof i=="object"&&(n=i,i=void 0),n=n||{};let s=pnr(i,n.path||"/socket.io"),c=s.source,u=s.id,_=s.path,g=f_e[u]&&_ in f_e[u].nsps,E=n.forceNew||n["force new connection"]||n.multiplex===!1||g,x;return E?(wnr("ignoring socket cache for %s",c),x=new Nee(c,n)):(f_e[u]||(wnr("new io instance for %s",c),f_e[u]=new Nee(c,n)),x=f_e[u]),s.query&&!n.query&&(n.query=s.queryKey),x.socket(s.path,n)}t(p_e,"lookup");Object.assign(p_e,{Manager:Nee,Socket:Dee,io:p_e,connect:p_e});var Xke={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},yft=class yft{constructor(n={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=n,this.url=n.url||Xke.URL,this.namespace=n.namespace||Xke.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((n,s)=>{this.resolveInitialization=c=>n(c),this.rejectInitialization=c=>s(c)}).then(n=>(this.resolution=n,this.log("\u2705 Client initialization successful"),n),n=>{throw this.resolution=n,this.logError("\u274C Client initialization failed:",n),n}).finally(()=>{this.disconnect()})}defineHandlers(n){return n}async startSession(n,s,c){try{if(await this.connect(),this.emit(n,s,u=>{this.resolveInitialization(u)}),c&&c>0){let u=new Promise((_,g)=>{setTimeout(()=>{g(new Error(`Session initialization timed out after ${c}ms`))},c)});return Promise.race([this.initializationPromise,u])}return this.initializationPromise}catch(u){throw this.logError("\u274C Failed to start session:",u),this.rejectInitialization(u),u}}isConnected(){var n;return((n=this.socket)==null?void 0:n.connected)||!1}getConnectionState(){return this.connectionState}success(n){return{success:!0,data:n}}error(n){return{success:!1,error:n}}log(n,...s){this.options.verbose&&console.log(`[${this.namespace}] ${n}`,...s)}logError(n,...s){this.options.verbose&&console.error(`[${this.namespace}] ${n}`,...s)}async connect(){var n;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((n=this.socket)!=null&&n.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(s){throw this.connectionState="disconnected",this.connectionPromise=null,s}return this.connectionPromise}establishConnection(){return new Promise((n,s)=>{let c=!1;try{let u=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${u}`),this.socket=p_e(u,{autoConnect:!0,reconnection:!0,reconnectionAttempts:Xke.RECONNECTION_ATTEMPTS,reconnectionDelay:Xke.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(n,s,c)}catch(u){this.logError("\u274C Failed to create socket connection:",u),c||s(u)}})}setupConnectionHandlers(n,s,c){if(!this.socket)return;let u={resolve:n,reject:s,connectionResolved:c};this.socket.on("connect",()=>this.handleConnect(u)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",_=>this.handleConnectError(_,u)),this.socket.on("disconnect",_=>this.handleDisconnect(_,u)),this.socket.io.on("reconnect_attempt",_=>this.handleReconnectAttempt(_)),this.socket.io.on("reconnect_error",_=>this.handleReconnectError(_)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(u))}handleConnect(n){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),n.connectionResolved||(n.connectionResolved=!0,n.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(n,s){var c;this.logError("\u274C Connection error:",n),this.connectionState="disconnected",!s.connectionResolved&&((c=this.socket)==null?void 0:c.disconnected)!==!1&&(s.connectionResolved=!0,s.reject(n))}handleDisconnect(n,s){this.log("\u{1F50C} Disconnected from socket:",n),this.connectionState="disconnected";let c=new Error(`Socket disconnected: ${n}`),u=!1;this.resolution===null&&n==="io server disconnect"&&(this.rejectInitialization(c),u=!0),!s.connectionResolved&&(n==="io server disconnect"||n==="transport close")&&(s.connectionResolved=!0,s.reject(c)),!u&&this.resolution===null&&this.connectionState==="disconnected"&&this.rejectInitialization(c)}handleReconnectAttempt(n){this.log(`\u{1F504} Reconnection attempt #${n}`),this.connectionState="reconnecting"}handleReconnectError(n){this.logError("\u274C Reconnection attempt failed:",n)}handleReconnectFailed(n){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),n.connectionResolved||(n.connectionResolved=!0,n.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(n,s){this.log(`\u{1F4E5} Gateway called method: ${n.key} with args:`,n.args);try{let c=this.validateGatewayCall(n);if(c){s(c);return}let u=this.handlers[n.key];if(!u){let g=`No handler registered for method: ${n.key}`;this.logError(`\u274C ${g}`),s(this.error(g));return}let _=await u(...n.args);s(this.success(_))}catch(c){this.logError("\u274C Error handling gateway call:",c),s(this.error(c.message||"Unknown error occurred"))}}validateGatewayCall(n){return n.key?Array.isArray(n.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(n,s,c){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${n}`),this.socket.emit(n,s,u=>{c(u)})}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"))}};t(yft,"AbstractClient");var e3e=yft;var Tnr,xnr,knr,Dnr,Nnr,Pnr,Bnr,Fnr,r3e=class r3e extends(Fnr=e3e,Bnr=Oh.names.getState,Pnr=Oh.names.invokeCode,Nnr=Oh.names.final_result,Dnr=Oh.names.wait,knr=Oh.names.getElementScreenshot,xnr=Oh.names.listPages,Tnr=Oh.names.switchPage,Fnr){constructor(s,c){super({verbose:Yu.testRun.autoRecovery.verboseConsoleLog,url:c.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=s;this.initData=c;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:t(async(s,c)=>{if(!this[s])throw new Error(`Tool ${s} not found`);return c.thought&&this.stepsThoughts.push(c.thought),await this[s].invoke(c)},"callLangChainTool"),getStatus:t(async s=>({sessionId:s,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[Bnr]=e5.buildTool(Oh,Oh.names.getState,async s=>this.getStateHandler(s));this[Pnr]=e5.buildTool(Oh,Oh.names.invokeCode,async s=>this.invokeCodeHandler(s));this[Nnr]=e5.buildTool(Oh,Oh.names.final_result,async s=>this.finalResultHandler(s));this[Dnr]=e5.buildTool(Oh,Oh.names.wait,async s=>this.waitHandler(s));this[knr]=e5.buildTool(Oh,Oh.names.getElementScreenshot,async s=>this.getElementScreenshotHandler(s));this[xnr]=e5.buildTool(Oh,Oh.names.listPages,async s=>this.listPagesHandler(s));this[Tnr]=e5.buildTool(Oh,Oh.names.switchPage,async s=>this.switchPageHandler(s))}async init(){let s={...this.initData,version:Oh.version};return await this.startSession("initialize",s).catch(c=>{this.utils.analytics.ARError({error:c.message});let u="Auto-Recovery attempt finished unsuccessfully";return this.utils.createChecksumStep({title:u,withError:!0}),this.utils.addAutoRecoveryErrorToReport(u,!1),{finalThought:u,stepsThoughts:[],result:"failed"}})}static async build(s){let c=await s.buildFallbackData();return new r3e(s,c)}async invokeCodeHandler(s){let c,u=this.utils.activePageGuid,g=!!(s.pageId&&s.pageId!==u?await this.utils.getPageById(s.pageId):void 0);return await this.utils.runConditionallyWithinStep(!0,s.thought||"Invoke Code",async()=>{try{g&&await this.utils.setActivePage(s.pageId);let E=await this.utils.invokeCode(s.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),c={success:!0,invokeCodeResult:`invokeCodeResult: ${E.result}`,appState:(await this.utils.buildFallbackData()).applicationState,actionEffects:E.effects}}catch(E){c={success:!1,invokeCodeResult:`Error while invoking code: ${E}`,appState:(await this.utils.buildFallbackData()).applicationState}}finally{if(g&&u)try{await this.utils.setActivePage(u)}catch(E){console.warn("Failed to switch back to original page:",E)}}}),c}async getStateHandler(s){return this.utils.createChecksumStep({title:s.thought}),this.utils.analytics.ARGetState(s.thought),{success:!0,appState:await this.utils.captureApplicationState(s.pageId,s.includeAllPages)}}async finalResultHandler(s){let c=this.utils.isSuggestOnly?!1:s.result==="pass",u=this.initData.type==="assertion"?c?"soft_assertion":"hard_assertion":c?"finish":"failed",_={finalThought:s.thought,result:u,stepsThoughts:this.stepsThoughts};await Promise.resolve(),this.resolveInitialization(_);try{this.utils.analytics.ARFinalResult({finalThought:s.thought,result:u,stepsThoughts:this.stepsThoughts})}catch(g){console.warn("Failed to record auto-recovery final-result analytics:",g)}try{this.utils.addAutoRecoveryErrorToReport(s.thought,c)}catch(g){console.warn("Failed to add auto-recovery result to report:",g)}}async getElementScreenshotHandler(s){return{success:!0,screenshot:await this.utils.getScreenshotForElement(s.checksumId)}}async waitHandler(s){await new Promise(u=>setTimeout(u,s.time||5e3));let c=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${s.time} seconds, the current HTML of the application after the wait is: ${c.applicationState.reducedHTML}`}}async listPagesHandler(s){s.thought&&this.utils.createChecksumStep({title:s.thought});let c=await this.utils.pageInteractor.getTabsInfo(),u=c.map((g,E)=>`${E+1}. ${g.title||"Untitled"} (${g.url})
747
747
  - Page ID: ${g.id}
748
748
  - Active: ${g.active?"Yes":"No"}
749
749
  - New: ${g.new?"Yes":"No"}${g.lastAction?`
@@ -751,10 +751,10 @@ Result: ${JSON.stringify(M)}`);else X=M;let ce=i0n({content:X,artifact:W,toolCal
751
751
 
752
752
  `),_=`Available pages (${c.length}):
753
753
 
754
- ${u}`;return{success:!0,pages:c,message:_}}async switchPageHandler(s){if(!s.pageId)return{success:!1,message:"pageId is required"};s.thought&&this.utils.createChecksumStep({title:s.thought});try{await this.utils.setActivePage(s.pageId);let c=await this.utils.captureApplicationState();return{success:!0,activePageId:s.pageId,message:`Successfully switched to page ${s.pageId}`,appState:c}}catch(c){let u=c instanceof Error?c.message:String(c);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${s.pageId}: ${u}`}}}};t(r3e,"AutoRecoveryAgent");var t3e=r3e;var Onr=require("fs"),Mnr=uc(require("path"));var vft=class vft{constructor(n,s){this.sessionId=null;if(!lw.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let u=lw.getCurrentInstance();if(!u)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let _=u.getTestSuiteRunInfo();this.analytics=hR.createFromConfig(_,lw.isolatedMode,!0),this.fallbackId=n,this.fallbackType=s}updateToSessionId(n){this.sessionId!==n&&(this.sessionId=n)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(n){this.analytics.trackEventWithTable(n,this.metadata,this.tableName)}setFallbackType(n){this.fallbackType=n}aiFallbackStart(n){this.event({event:"AI Fallback Start",metadata:this.metadata,...n})}aiFallbackConfig(n){this.event({event:"AI Fallback Config",metadata:this.metadata,...n})}aiFallbackIterationResponse(n){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...n})}aiFallbackAssertion(n){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...n})}aiFallbackChangeVariable(n){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...n})}aiFallbackSummary(n){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...n})}aiFallbackActionExecution(n){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...n})}aiFallbackActionExecutionFailure(n){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...n})}aiFallbackEnd(n){this.event({event:"AI Fallback End",metadata:this.metadata,...n})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(n){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...n})}ARGetState(n){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:n})}ARInvokeCode(n,s){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:n,code:s})}ARFinalResult(n){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...n})}autoRecoveryDisconnect(n){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...n})}ARFinish(n){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...n})}ARError(n){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...n})}};t(vft,"RecoveryAnalytics");var n3e=vft;var Byn=500,Fyn=3,Ryn=5,Rnr=300;function bft(i){return i._guid}t(bft,"getPageGuid");var wV=class wV{constructor({page:n,evaluateWithChecksum:s,checksumPage:c,pageInteractor:u,arConfig:_,sessionId:g,runtimeFallbackData:E,fallbackData:x,variableStore:P,runtimePage:M,context:X}){this.reducedHtmlTimeoutMs=3e4;this.page=n,this._originalPage=n,this.evaluateWithChecksum=s,this.checksumPage=c,this._pageInteractor=u,this.arConfig=_,this.sessionId=g,this.runtimeFallbackData=E,this.fallbackData=x,this.variableStore=P,this.runtimePage=M,this.context=X,this._activePageGuid=bft(this.page),this._analytics=new n3e(this.sessionId,x.type)}get activePageGuid(){return this._activePageGuid}static async start(n){return new wV({...n})}async evaluateOnCurrentPage(n,s){return this.page!==this._originalPage?this.page.evaluate(n,s):this.evaluateWithChecksum(n,s)}async getPageById(n){return(this.context||this.page.context()).pages().find(u=>bft(u)===n)}async setActivePage(n){let s=await this.getPageById(n);if(!s||s.isClosed())throw new Error(`Page with ID ${n} is closed or not found`);this.page=s,this._activePageGuid=n}getMatcherResultFileData(n){let s=n.matcherResult;if((s==null?void 0:s.name)!=="toHaveScreenshot")return;let c=t((E,x=!0)=>{if(!E)return"";try{return(0,Onr.readFileSync)(E,x?"base64":"utf-8")}catch{return""}},"readFileSafe"),u=c(s==null?void 0:s.actual),_=c(s==null?void 0:s.diff),g=c(s==null?void 0:s.expected);if(!g)throw new Error("No expected file found for 'toHaveScreenshot'");return{...s,actual:u,diff:_,expected:g}}async getSelectionDataForChecksumId(n){return await this.evaluateOnCurrentPage(async c=>{let{selector:u,locator:_,clickOffset:g,parentFramesSelectors:E,invalid:x,rrwebId:P}=await window.checksum.testGenerator.getSelectorForChecksumId(c),M=await window.checksum.testGenerator.getElementForChecksumId(c),X=M instanceof HTMLOptionElement&&M.value?M.value:void 0;return{selector:u,locator:_,clickOffset:g,selectOptionValue:X,parentFramesSelectors:E,invalid:x,rrwebId:P}},n)}async getReducedHtml(n=wV.currentChecksumId,s=3){if(this.page.url()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:n};try{let c=await this.evaluateOnCurrentPage(async u=>window.checksum.testGenerator.reduceHTML({},u),{initialChecksumId:n,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return wV.currentChecksumId=c.currentChecksumId,{reducedHTML:c.reducedHTML,currentChecksumId:c.currentChecksumId}}catch(c){if(s>0)return await new Promise(_=>setTimeout(_,2e3)),this.getReducedHtml(n,s-1);let u=c instanceof Error?c.message:String(c);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${u}`,currentChecksumId:n}}}async getApplicationState(){let{reducedHTML:n}=await this.getReducedHtml();return{reducedHTML:n,screenshot:await this.getPageScreenshot()}}async capturePageState(n,s){let c=this.page,u=this._activePageGuid;try{this.page=n,this._activePageGuid=s;let{reducedHTML:_}=await this.getReducedHtml(),g=await this.getPageScreenshot();return{pageId:s,reducedHTML:_,screenshot:g,url:n.url()}}finally{this.page=c,this._activePageGuid=u}}async captureAllPagesState(){let s=(this.context||this.page.context()).pages(),c=[],u=[];for(let g of s){if(g.isClosed())continue;let E=bft(g);try{let x=await this.capturePageState(g,E);c.push(x)}catch(x){let P=x instanceof Error?x.message:String(x);u.push({pageId:E,url:g.url(),error:P}),console.warn(`Failed to capture state for page ${E} (${g.url()}):`,x)}}let _={pages:c};return u.length>0&&(_.failures=u),_}async captureApplicationState(n,s){if(s)return await this.captureAllPagesState();if(n&&n!==this._activePageGuid){let c=await this.getPageById(n);if(!c||c.isClosed())throw new Error(`Page with ID ${n} is closed or not found`);let u=await this.capturePageState(c,n);return{reducedHTML:u.reducedHTML,screenshot:u.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let s=(this.context||this.page.context()).pages().filter(g=>!g.isClosed()).length,c=new Promise((g,E)=>setTimeout(()=>E(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:u,currentChecksumId:_}=await Promise.race([this.getReducedHtml(),c]);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:u,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:_,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((g,E)=>(g[`variablesStore.${E.name}`]=E.value,g),{}),arConfig:this.arConfig,multiPageContext:{pageCount:s,hasMultiplePages:s>1}}}async scrollToElement(n){n&&await this.evaluateOnCurrentPage(async s=>{let c=document.querySelector(`[checksumid="${s}"]`);c==null||c.scrollIntoView({block:"center"})},n)}async getPageScreenshot(n=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var c;return(await this.page.screenshot({fullPage:!0,type:((c=n.modelConfig)==null?void 0:c.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(n){try{let s=Mnr.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return PY.toRecord(n,s)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(n){var ce;let s=n,c=n,u=[],_=n.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),g=_==null?void 0:_[1],E=_==null?void 0:_[2],x=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,P=(ce=n.match(x))==null?void 0:ce[1];if(!P)throw new Error("Checksum ID not found in the code");let M=await this.getSelectionDataForChecksumId(P);if(!(M!=null&&M.locator)||M.invalid)throw new Error(`Locator or selector not found for checksumId: ${P}`);c=c.replace(x,M.locator);let X=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,W=null;for(;(W=X.exec(n))!==null;){let ue=W[1],Se=this.variableStore.find(Ct=>Ct.name===ue);Se&&(u.push(Se),c=c.replace(W[0],`"${Se.value}"`))}return{originalCode:s,modifiedCode:c,usedVariables:u,checksumId:P,locator:M.locator,method:g,methodArgs:E}}async invokeCode(n){let s=this.page,c=s.url(),u=[],_=[],g,E=t(M=>{try{let X=M.request(),W=X.resourceType();(W==="xhr"||W==="fetch")&&M.status()>=400&&u.push({status:M.status(),method:X.method(),url:M.url()})}catch{}},"onResponse"),x=t(M=>_.push((M==null?void 0:M.message)??String(M)),"onPageError"),P=t(M=>{g||(g=M)},"onPopup");s.on("response",E),s.on("pageerror",x),s.on("popup",P);try{let M=await this.preprocessCode(n),{modifiedCode:X}=M,W=new Function("page",`return (async () => { return page.${X}; })()`),ce;return await this.step(X,async()=>ce=await W(this.page),!1,{box:!0,noLocation:!0,obtainStep:t(ue=>{ue!=null&&ue.stepId&&this.checksumPage.addAutoRecoveryStepId(ue.stepId)},"obtainStep")}),await s.waitForTimeout(Byn).catch(()=>{}),{success:!0,result:ce,effects:this.buildActionEffects(c,g,_,u)}}catch(M){throw console.log("Error while invoking code",M.message),M}finally{s.off("response",E),s.off("pageerror",x),s.off("popup",P)}}buildActionEffects(n,s,c,u){let _=t(x=>x.length>Rnr?`${x.slice(0,Rnr)}\u2026`:x,"clip"),g={},E=n;try{E=this.page.url()}catch{}if(E&&E!==n&&(g.navigation={from:n,to:_(E)}),s){let x="about:blank";try{s.isClosed()||(x=s.url())}catch{}g.openedNewPage={url:_(x)}}if(c.length&&(g.pageErrors=[...new Set(c)].slice(0,Fyn).map(_)),u.length){let x=new Set;g.networkErrors=u.filter(P=>{let M=`${P.status} ${P.method} ${P.url}`;return x.has(M)?!1:(x.add(M),!0)}).slice(0,Ryn).map(P=>({...P,url:_(P.url)}))}return Object.keys(g).length>0?g:void 0}addAutoRecoveryErrorToReport(n,s){let c=this.runtimeFallbackData.thoughts.failing,u=s?`\u2705 "${c}" auto-recovered`:`\u274C "${c}" failed`;this.checksumPage.addPwAnnotation({type:u,description:n.replace(/^"(.*)"$/,"$1")}),s&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${u}:
754
+ ${u}`;return{success:!0,pages:c,message:_}}async switchPageHandler(s){if(!s.pageId)return{success:!1,message:"pageId is required"};s.thought&&this.utils.createChecksumStep({title:s.thought});try{await this.utils.setActivePage(s.pageId);let c=await this.utils.captureApplicationState();return{success:!0,activePageId:s.pageId,message:`Successfully switched to page ${s.pageId}`,appState:c}}catch(c){let u=c instanceof Error?c.message:String(c);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${s.pageId}: ${u}`}}}};t(r3e,"AutoRecoveryAgent");var t3e=r3e;var Onr=require("fs"),Mnr=uc(require("path"));var vft=class vft{constructor(n,s){this.sessionId=null;if(!lw.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let u=lw.getCurrentInstance();if(!u)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let _=u.getTestSuiteRunInfo();this.analytics=hR.createFromConfig(_,lw.isolatedMode,!0),this.fallbackId=n,this.fallbackType=s}updateToSessionId(n){this.sessionId!==n&&(this.sessionId=n)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(n){this.analytics.trackEventWithTable(n,this.metadata,this.tableName)}setFallbackType(n){this.fallbackType=n}aiFallbackStart(n){this.event({event:"AI Fallback Start",metadata:this.metadata,...n})}aiFallbackConfig(n){this.event({event:"AI Fallback Config",metadata:this.metadata,...n})}aiFallbackIterationResponse(n){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...n})}aiFallbackAssertion(n){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...n})}aiFallbackChangeVariable(n){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...n})}aiFallbackSummary(n){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...n})}aiFallbackActionExecution(n){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...n})}aiFallbackActionExecutionFailure(n){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...n})}aiFallbackEnd(n){this.event({event:"AI Fallback End",metadata:this.metadata,...n})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(n){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...n})}ARGetState(n){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:n})}ARInvokeCode(n,s){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:n,code:s})}ARFinalResult(n){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...n})}autoRecoveryDisconnect(n){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...n})}ARFinish(n){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...n})}ARError(n){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...n})}};t(vft,"RecoveryAnalytics");var n3e=vft;var Byn=500,Fyn=3,Ryn=5,Rnr=300;function bft(i){return i._guid}t(bft,"getPageGuid");var wV=class wV{constructor({page:n,evaluateWithChecksum:s,checksumPage:c,pageInteractor:u,arConfig:_,sessionId:g,runtimeFallbackData:E,fallbackData:x,variableStore:P,runtimePage:M,context:X}){this.reducedHtmlTimeoutMs=3e4;this.page=n,this._originalPage=n,this.evaluateWithChecksum=s,this.checksumPage=c,this._pageInteractor=u,this.arConfig=_,this.sessionId=g,this.runtimeFallbackData=E,this.fallbackData=x,this.variableStore=P,this.runtimePage=M,this.context=X,this._activePageGuid=bft(this.page),this._analytics=new n3e(this.sessionId,x.type)}get activePageGuid(){return this._activePageGuid}get isSuggestOnly(){return this.arConfig.markRecovered===!1}static async start(n){return new wV({...n})}async evaluateOnCurrentPage(n,s){return this.page!==this._originalPage?this.page.evaluate(n,s):this.evaluateWithChecksum(n,s)}async getPageById(n){return(this.context||this.page.context()).pages().find(u=>bft(u)===n)}async setActivePage(n){let s=await this.getPageById(n);if(!s||s.isClosed())throw new Error(`Page with ID ${n} is closed or not found`);this.page=s,this._activePageGuid=n}getMatcherResultFileData(n){let s=n.matcherResult;if((s==null?void 0:s.name)!=="toHaveScreenshot")return;let c=t((E,x=!0)=>{if(!E)return"";try{return(0,Onr.readFileSync)(E,x?"base64":"utf-8")}catch{return""}},"readFileSafe"),u=c(s==null?void 0:s.actual),_=c(s==null?void 0:s.diff),g=c(s==null?void 0:s.expected);if(!g)throw new Error("No expected file found for 'toHaveScreenshot'");return{...s,actual:u,diff:_,expected:g}}async getSelectionDataForChecksumId(n){return await this.evaluateOnCurrentPage(async c=>{let{selector:u,locator:_,clickOffset:g,parentFramesSelectors:E,invalid:x,rrwebId:P}=await window.checksum.testGenerator.getSelectorForChecksumId(c),M=await window.checksum.testGenerator.getElementForChecksumId(c),X=M instanceof HTMLOptionElement&&M.value?M.value:void 0;return{selector:u,locator:_,clickOffset:g,selectOptionValue:X,parentFramesSelectors:E,invalid:x,rrwebId:P}},n)}async getReducedHtml(n=wV.currentChecksumId,s=3){if(this.page.url()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:n};try{let c=await this.evaluateOnCurrentPage(async u=>window.checksum.testGenerator.reduceHTML({},u),{initialChecksumId:n,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return wV.currentChecksumId=c.currentChecksumId,{reducedHTML:c.reducedHTML,currentChecksumId:c.currentChecksumId}}catch(c){if(s>0)return await new Promise(_=>setTimeout(_,2e3)),this.getReducedHtml(n,s-1);let u=c instanceof Error?c.message:String(c);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${u}`,currentChecksumId:n}}}async getApplicationState(){let{reducedHTML:n}=await this.getReducedHtml();return{reducedHTML:n,screenshot:await this.getPageScreenshot()}}async capturePageState(n,s){let c=this.page,u=this._activePageGuid;try{this.page=n,this._activePageGuid=s;let{reducedHTML:_}=await this.getReducedHtml(),g=await this.getPageScreenshot();return{pageId:s,reducedHTML:_,screenshot:g,url:n.url()}}finally{this.page=c,this._activePageGuid=u}}async captureAllPagesState(){let s=(this.context||this.page.context()).pages(),c=[],u=[];for(let g of s){if(g.isClosed())continue;let E=bft(g);try{let x=await this.capturePageState(g,E);c.push(x)}catch(x){let P=x instanceof Error?x.message:String(x);u.push({pageId:E,url:g.url(),error:P}),console.warn(`Failed to capture state for page ${E} (${g.url()}):`,x)}}let _={pages:c};return u.length>0&&(_.failures=u),_}async captureApplicationState(n,s){if(s)return await this.captureAllPagesState();if(n&&n!==this._activePageGuid){let c=await this.getPageById(n);if(!c||c.isClosed())throw new Error(`Page with ID ${n} is closed or not found`);let u=await this.capturePageState(c,n);return{reducedHTML:u.reducedHTML,screenshot:u.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let s=(this.context||this.page.context()).pages().filter(g=>!g.isClosed()).length,c=new Promise((g,E)=>setTimeout(()=>E(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:u,currentChecksumId:_}=await Promise.race([this.getReducedHtml(),c]);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:u,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:_,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((g,E)=>(g[`variablesStore.${E.name}`]=E.value,g),{}),arConfig:this.arConfig,multiPageContext:{pageCount:s,hasMultiplePages:s>1}}}async scrollToElement(n){n&&await this.evaluateOnCurrentPage(async s=>{let c=document.querySelector(`[checksumid="${s}"]`);c==null||c.scrollIntoView({block:"center"})},n)}async getPageScreenshot(n=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var c;return(await this.page.screenshot({fullPage:!0,type:((c=n.modelConfig)==null?void 0:c.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(n){try{let s=Mnr.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return PY.toRecord(n,s)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(n){var ce;let s=n,c=n,u=[],_=n.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),g=_==null?void 0:_[1],E=_==null?void 0:_[2],x=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,P=(ce=n.match(x))==null?void 0:ce[1];if(!P)throw new Error("Checksum ID not found in the code");let M=await this.getSelectionDataForChecksumId(P);if(!(M!=null&&M.locator)||M.invalid)throw new Error(`Locator or selector not found for checksumId: ${P}`);c=c.replace(x,M.locator);let X=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,W=null;for(;(W=X.exec(n))!==null;){let ue=W[1],Se=this.variableStore.find(Ct=>Ct.name===ue);Se&&(u.push(Se),c=c.replace(W[0],`"${Se.value}"`))}return{originalCode:s,modifiedCode:c,usedVariables:u,checksumId:P,locator:M.locator,method:g,methodArgs:E}}async invokeCode(n){let s=this.page,c=s.url(),u=[],_=[],g,E=t(M=>{try{let X=M.request(),W=X.resourceType();(W==="xhr"||W==="fetch")&&M.status()>=400&&u.push({status:M.status(),method:X.method(),url:M.url()})}catch{}},"onResponse"),x=t(M=>_.push((M==null?void 0:M.message)??String(M)),"onPageError"),P=t(M=>{g||(g=M)},"onPopup");s.on("response",E),s.on("pageerror",x),s.on("popup",P);try{let M=await this.preprocessCode(n),{modifiedCode:X}=M,W=new Function("page",`return (async () => { return page.${X}; })()`),ce;return await this.step(X,async()=>ce=await W(this.page),!1,{box:!0,noLocation:!0,obtainStep:t(ue=>{ue!=null&&ue.stepId&&this.checksumPage.addAutoRecoveryStepId(ue.stepId)},"obtainStep")}),await s.waitForTimeout(Byn).catch(()=>{}),{success:!0,result:ce,effects:this.buildActionEffects(c,g,_,u)}}catch(M){throw console.log("Error while invoking code",M.message),M}finally{s.off("response",E),s.off("pageerror",x),s.off("popup",P)}}buildActionEffects(n,s,c,u){let _=t(x=>x.length>Rnr?`${x.slice(0,Rnr)}\u2026`:x,"clip"),g={},E=n;try{E=this.page.url()}catch{}if(E&&E!==n&&(g.navigation={from:n,to:_(E)}),s){let x="about:blank";try{s.isClosed()||(x=s.url())}catch{}g.openedNewPage={url:_(x)}}if(c.length&&(g.pageErrors=[...new Set(c)].slice(0,Fyn).map(_)),u.length){let x=new Set;g.networkErrors=u.filter(P=>{let M=`${P.status} ${P.method} ${P.url}`;return x.has(M)?!1:(x.add(M),!0)}).slice(0,Ryn).map(P=>({...P,url:_(P.url)}))}return Object.keys(g).length>0?g:void 0}addAutoRecoveryErrorToReport(n,s){let c=this.runtimeFallbackData.thoughts.failing,u=s?`\u2705 "${c}" auto-recovered`:`\u274C "${c}" failed`;this.checksumPage.addPwAnnotation({type:u,description:n.replace(/^"(.*)"$/,"$1")}),s&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${u}:
755
755
  ${n}`)}get createChecksumStep(){return n=>this.checksumPage.createChecksumStep(n)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(n,s,c)=>this.checksumPage.runConditionallyWithinStep(n,s,c)}async getScreenshotForElement(n){var s;try{let c=await this.getSelectionDataForChecksumId(n);if(!c)throw new Error(`Locator not found for checksumId: ${n}`);let u=((s=this.arConfig.modelConfig)==null?void 0:s.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(c.selector).screenshot({type:u})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${n}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};t(wV,"AutoRecoveryRuntimeIteratorUtils"),wV.currentChecksumId="0";var i3e=wV;var EN=class EN extends n8{constructor(n,s,c,u,_,g,E){super(n,s,c,u,_,g,E),this.runtimePageContext=g}init(n){var s;return this.initializationData=n,(s=this.initializationData.fallbackConfig).arMode??(s.arMode="fast"),this}canResolve(n){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(n){let s=n.config.apiURL,c=n.config.apiKey;return await(await fetch(`${s}${EN.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:c},body:JSON.stringify({appName:n.testIdentification.testFileName,fallbackData:n})})).json()}async prepareSession(n){let s=await EN.registerSession(this.initializationData);this.utils=new i3e({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:s.arConfig,sessionId:s.sessionId,runtimeFallbackData:this.initializationData,fallbackData:n,variableStore:this.variables,runtimePage:this.runtimePageContext,context:this.context});try{this.agent=await t3e.build(this.utils)}catch(c){let u=c instanceof Error?c.message:String(c),_=c instanceof Error?c.stack:void 0;throw new Error(`Failed to prepare ARFallback: ${u}`)}}async resolve(n){let s=null,c=new Promise((_,g)=>{s=setTimeout(()=>{s=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${EN.TIMEOUT_MS/1e3} seconds`});let E="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:E,withError:!0}),this.utils.addAutoRecoveryErrorToReport(E,!1),g(new Error(E))},EN.TIMEOUT_MS)}),u=Date.now();await this.prepareSession(n),this.utils.analytics.ARStart();try{let _=await Promise.race([this.agent.init(),c]);return s!==null&&(clearTimeout(s),s=null),this.utils.analytics.ARFinish({duration:Date.now()-u}),{fbResult:_.result,thought:_.finalThought,stepsThoughts:_.stepsThoughts,steps:[]}}catch(_){throw s!==null&&(clearTimeout(s),s=null),this.utils.analytics.ARFinish({duration:Date.now()-u}),_}}};t(EN,"ARFallback"),EN.API_BASE_ROUTE="/auto-recovery",EN.TIMEOUT_MS=12e4;var CN=EN;var Lnr=t(i=>{let n=i.info();return n.annotations.some(s=>s.type==="bug")||n.tags.some(s=>s==="@bug")},"isKnownBugTest");var Eft=1e3*30;var NO=class NO extends MIe{constructor(s,c="normal",u,_,g,E,x,P,M,X,W,ce,ue){var gt,kt,Et;super(s,u,W,()=>this.pageInteractor,void 0);this.page=s;this.runMode=c;this.testRunAnalytics=_;this.monitorBridge=g;this.testInfo=E;this.checksumTestId=x;this.test=P;this.options=M;this.isReplMode=X;this.config=W;this.pageInteractorAPI=ce;this.lastInteractionTime=Date.now();this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.hasSuccessfulAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new KEe;this.previousSteps=[];this.scriptLoadWrapper=t(async(s,c)=>(!this.isTimeMachineFrame(c)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(s,c.page())),"scriptLoadWrapper");this.scriptLoadCheck=t(async s=>s.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=t(async s=>{await s.evaluate(async({appSpecificRules:c,esraTimeout:u,sessionRecorder:_,showFrontendLogs:g,showTMSeeker:E,filesObserver:x,nativeDialogObserver:P,assertionsObserver:M,actionsObserver:X,recordOptions:W})=>{var ce;(ce=window.checksum)==null||ce.testGenerator.init(c,{esraTimeout:u,showFrontendLogs:g,skipElementHighlighting:!0,recordOptions:W},{assertionGenerator:!1,sessionRecorder:_,filesObserver:x,nativeDialogObserver:P,assertionsObserver:M,actionsObserver:X});try{E&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:Eft,sessionRecorder:!this.isTimeMachineFrame(s)&&!!this.timeMachine,showFrontendLogs:Yu.isDevMode,showTMSeeker:this.isTimeMachineFrame(s)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1,recordOptions:void 0}),Ru(`[init] init script loaded for ${s.page().url()}`)},"scriptLoadCallback");Unr(M.printLogs),Lnr(P)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let Se=IV({config:this.config,throwIfAuthFailed:!0}),Ct=this.getPlaywrightProjectConfig();if(this.pageInteractor=new ole(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Ru,logError:Ru},{navigationTimeout:(gt=Ct.use)==null?void 0:gt.navigationTimeout,actionTimeout:(kt=Ct.use)==null?void 0:kt.actionTimeout,testAssetsDir:ile(q6()),waitActionDelay:1e3},this.pageInteractorAPI,Se),this.checkForActiveTracing(),this.resetFallbacks(),ue&&(this.highLevelThoughts=ue.highLevelThoughts??[],this.timeMachineBrowserContext=ue.timeMachineBrowserContext,this.variableStore=ue.variableStore),Yu.testRun.timeMachine.active){let Kt=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:c8t(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new DIe(this.framesMsgBroker,this.injectedScriptManager,{...Kt,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Yu.testRun.timeMachine.headless,webProxy:(Et=E.project.use)==null?void 0:Et.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(s,c,u,_,g,E,x,P,M,X=!1){let W=!1;x||(x=e8t(5),W=!0,console.warn(`Checksum test id was not defined for test "${E.title}" and was auto-generated. Please replace - "${E.title}" with -
756
756
  test(defineChecksumTest("${E.title}", "${x}"), async ({ page }) => {...`)),_.addTestInfo(x,E.testId,W),M.options.useChecksumAI!==void 0&&typeof M.options.useChecksumAI=="boolean"&&(M.options.useChecksumAI={actions:M.options.useChecksumAI,assertions:!1,visualComparison:!1});let ce=new WCe(M),ue=new NO(s,M.runMode,c,u,_,E,x,P,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:M.runMode!=="normal",useMockData:!1,printLogs:!1,...M.options},X,M,ce,{variableStore:g});return c.pages().length===0&&(P._checksum.expect.setPage(ue),P._checksum.checksumAI.page=ue,g.clearAll(),ue.testRunAnalytics.testRunStart()),await ue.asyncInit(),ue.proxy}async asyncInit(s=!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(),s||await this.prepareForTestArtifacts()}async makePage(s){let c=new NO(s,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await c.asyncInit(!0),c.proxy}getTimeMachinePage(){var s;return(s=this.timeMachine)==null?void 0:s.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(s){var c;return s===((c=this.timeMachine)==null?void 0:c.getFrame())}shouldRecordRRwebEvents(){return Yu.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let s=this.getPageGuid(this.page);NO.recentlyInteracted.set(s,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(s){let c=s.pages(),u=c[0],_=0;for(let g of c){let E=g._guid,x=NO.recentlyInteracted.get(E)||0;x>_&&(_=x,u=g)}return u}async goto(s,c){return this.recordInteraction(),this.page.goto(s,c)}async reload(s){return this.recordInteraction(),this.page.reload(s)}async goBack(s){return this.recordInteraction(),this.page.goBack(s)}async goForward(s){return this.recordInteraction(),this.page.goForward(s)}async click(s,c){return this.recordInteraction(),this.page.click(s,c)}async dblclick(s,c){return this.recordInteraction(),this.page.dblclick(s,c)}async fill(s,c,u){return this.recordInteraction(),this.page.fill(s,c,u)}async press(s,c,u){return this.recordInteraction(),this.page.press(s,c,u)}async check(s,c){return this.recordInteraction(),this.page.check(s,c)}async uncheck(s,c){return this.recordInteraction(),this.page.uncheck(s,c)}async selectOption(s,c,u){return this.recordInteraction(),this.page.selectOption(s,c,u)}async hover(s,c){return this.recordInteraction(),this.page.hover(s,c)}async type(s,c,u){return this.recordInteraction(),this.page.type(s,c,u)}async setInputFiles(s,c,u){return this.recordInteraction(),this.page.setInputFiles(s,c,u)}async tap(s,c){return this.recordInteraction(),this.page.tap(s,c)}async dragAndDrop(s,c,u){return this.recordInteraction(),this.page.dragAndDrop(s,c,u)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var u;let c=(u=this.getPlaywrightProjectConfig().use)==null?void 0:u.trace;this.traceMode=typeof c=="string"?c:c==null?void 0:c.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async s=>{this.injectedScriptManager.onFrameNavigated(s)})}checksumSelector(s){return this.checksumStepId=s,this.options.useChecksumSelectors&&this.setSelectorFallback(s),this.proxy}checksumAI(s,c,u){let _=this.addNewThought(s,"action",!!c);this.previousSteps.push({thought:_.thought,timestamp:Date.now()});let g=this.getPageGuid(this.page);return ole.setLastAction(g,s),c&&typeof c=="function"?this.test.step(s,async E=>{var x;try{return u!=null&&u.withDialog&&this.pageInteractor.listenToDialog(),await c()}catch(P){if(_.children=[],!this.options.useChecksumAI.actions||u!=null&&u.withDialog||u!=null&&u.skipAutoRecovery)throw P;this.setAIFallback(s,"action");try{return await this.initiateFallbackSequence({type:"action",error:P,method:void 0,args:[],testInfo:this.testInfo,step:E},{fallbackTypes:[S7,CN]})}catch(M){throw this.testRunAnalytics.testRunError({failedThought:s,error:(M==null?void 0:M.message)||"Unknown error"}),M}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(x=this.currentThought)==null?void 0:x.parent}}):(this.options.useChecksumAI.actions&&!(u!=null&&u.skipAutoRecovery)&&this.setAIFallback(s,"action"),this.proxy)}resolveAssetsFolder(s){return s.map(c=>Ax.join(ile(q6()),c))}getRuntimeOptions(){return this.options}addPwAnnotation(s){this.testInfo.annotations.push({type:s.type,description:`
757
- ${s.description}`})}async onTestComplete(s){this.testRunAnalytics.testRunEnd({success:s,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.hasSuccessfulAutoRecovery&&s}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(s,c=this.page){try{return c.mainFrame()._checksumInternal=!0,c._checksumInternal=!0,await s()}finally{c.mainFrame()._checksumInternal=!1,c._checksumInternal=!1}}async conditionallyWrapInternalSteps(s,c){return s?this.wrapInternalSteps(c):c()}async wrapNoLocationSteps(s){try{return this.testInfo._checksumNoLocation=!0,await s()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(s,c,u=[]){for(let _ of s){(_._stepId===c||_.stepId===c)&&u.push(_);let g=[_.steps,_._testInfoSteps,_._steps].filter(Boolean);for(let E of g)this.findAllStepsRecursively(E,c,u)}return u}makeChecksumStepFunction(s){return c=>{if(!s)return;let u=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,u).forEach(g=>{g.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(s){let c,u={box:!0,noLocation:!0,obtainStep:t(_=>{c=_},"obtainStep")};return await this.step(s.title,this.makeChecksumStepFunction(s.withError),!1,u),c!=null&&c.stepId&&this.arStepIds.push(c.stepId),c}async step(s,c,u=!0,{obtainStep:_=void 0,box:g=!1,noLocation:E=void 0}={}){let x=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=u===!0,E!==void 0&&(this.testInfo._checksumNoLocation=E),await this.test.step(s,c||(()=>{}),{obtainStep:_,box:g})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=x}}addErrorMessage(s,c){this.testInfo.addError(s,c)}async evaluateWithChecksum(s,c,u=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(u,()=>this.page.evaluate(s,c))}getChecksumTestId(){return this.checksumTestId}addNewThought(s,c,u=!1){let _={id:void 0,thought:s,type:c,children:u?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(_);else if(this.currentThought.children)this.currentThought.children.push(_),_.parent=this.currentThought;else{let g=this.currentThought.parent;g?(g.children.push(_),_.parent=g):this.highLevelThoughts.push(_)}return _.parent?_.id=`${_.parent.id}.${_.parent.children.length}`:_.id=`${++this.thoughtsCounter}`,this.currentThought=_,_}buildThoughtsChainForFallback(s=this.highLevelThoughts){let c=[];return s.forEach(u=>{c.push(u.thought),u.children&&c.push(...this.buildThoughtsChainForFallback(u.children))}),c}compoundSelection(...s){let c=super.compoundSelection(...s);return c.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),c}setSelectorFallback(s){let c={checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Eft};this.pushFallback(this.constructFallback(kue).init(c)),this.pushFallback(this.constructFallback(Tue).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(xue).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Eft}))}setAIFallback(s,c){var E;let u=((E=this.options.useChecksumAI)==null?void 0:E.arVersion)===1,_=t(()=>{var ce,ue,Se,Ct,gt,kt;let x=this.buildThoughtsChainForFallback(),P={title:this.testInfo.title},M={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},X={previous:x.slice(0,-1),failing:s,next:x.slice(1)},W={storyInfo:P,testIdentification:M,fallbackConfig:{arMode:(ce=this.options.useChecksumAI)==null?void 0:ce.arMode,overrideOptions:{...(ue=this.options.useChecksumAI)==null?void 0:ue.overrideOptions,...(Se=this.options.useChecksumAI)!=null&&Se.modelName&&!((gt=(Ct=this.options.useChecksumAI)==null?void 0:Ct.overrideOptions)!=null&&gt.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},oneShotSuggestOnly:(kt=this.options.useChecksumAI)==null?void 0:kt.oneShotSuggestOnly},thoughts:X,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(CN).init(W)},"createArFallback"),g=t(()=>{var x,P;return this.constructFallback(S7).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),arMode:(x=this.options.useChecksumAI)==null?void 0:x.arMode,overrideOptions:(P=this.options.useChecksumAI)==null?void 0:P.overrideOptions,fallbackType:c})},"createAIFallback");return u?this.pushFallback(g()):this.pushFallback(_()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,u,_){let g=s.fallbackAnalyticsPayload.iterationSteps,E=g.length>0?_/g.length:0;this.testRunAnalytics.testRunFallbackExecution({result:u.fbResult,failedThought:s.getFailedThought(),summary:u.summary,stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:_,avgDuration:E,success:["finish","soft_assertion"].includes(u.fbResult)}),this.arResults.push({failedThought:s.getFailedThought(),result:u.fbResult,thought:u.thought})}handleAutoRecovery(s,c,u,_){let g=u.stepsThoughts.length>0?_/u.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:s.failingThought,type:c.type,finalThought:u.thought,result:u.fbResult,duration:_,avgStepDuration:g,stepsThoughts:u.stepsThoughts,version:"v1"})}async runFallback(s,c){let u=Date.now(),_=s.resolve(c),g=await $m(_,s.timeout),E=Date.now()-u;s instanceof S7&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,g,E)),s instanceof CN&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,g,E));let x=g.thought?`: ${g.thought}`:"";if(!g||g.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${x}`,withError:!0}),new Error("Fallback failed");if(g.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${x}`,withError:!0}),new Vle(g.fbResult);if(this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof S7&&g.summary&&this.arSummaries.push(g.summary),s instanceof CN&&g.thought&&this.arSummaries.push(g.thought),this.createChecksumStep({title:`Recovery Complete${x}`}),g.steps.length===1){let P=g.steps[0];P.thought&&(this.currentThought.thought=P.thought)}else this.currentThought.children=g.steps.map((P,M)=>({id:`${this.currentThought.id}.${M+1}`,thought:P.thought,type:P.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(s,c,u){return s?await this.step(c,u):await u()}async onExecutionError(s){try{return await this.initiateFallbackSequence({type:"action",...s})}catch(c){if(!this.currentThought){let{locator:u,method:_}=s;this.testRunAnalytics.testRunActionExecutionFailure({locator:u.toString(),selector:u._selector,method:_,checksumStepId:this.checksumStepId,error:c.toString()})}throw c}}async initiateFallbackSequence(s,{fallbackTypes:c=void 0}={}){Ru(`[initiateFallbackSequence] with type: ${s.type}...`);let u=this.fallbacks.find(E=>E instanceof S7);if(u){let E=u.getFailedThought(),x=this.variableStore.getActiveVariables();this.fallbacks.forEach(P=>{P.setThought(E),P.setVariables(x)})}let _=this.fallbacks.find(E=>E instanceof CN);if(_){let E=_.failingThought;this.fallbacks.forEach(x=>{x instanceof CN&&x.setVariables(this.variableStore.getActiveVariables()),x.setThought(E)})}let g=this.fallbacks;c&&(g=g.filter(E=>c.reduce((x,P)=>x||E instanceof P,!1))),g=g.filter(E=>E.canResolve(s));try{for(let E of g){let x=E==null?void 0:E.toString();x&&console.log(`Using ${x}`);let P;try{let M=await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,E.getRecoveryAttemptTitle(s),async()=>await this.runFallback(E,s));P=!0}catch(M){if(P=!1,s.withChecksumAI&&M.message==="fetch failed")throw new Error(yR);M instanceof Vle&&M.fallbackResult==="hard_assertion"&&(s.error.fallbackResult="hard_assertion"),x&&console.log(`Failed to use ${x}`),E.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Due).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let s=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:s,testId:this.checksumTestId,fileName:Ax.basename(s)})}catch(s){Ru("Error shutting down RRweb events recording",s)}if(this.testRunAnalytics)return Ru("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[Due,xue,kue,Tue,S7];this.fallbacks.sort((c,u)=>s.indexOf(c.constructor)-s.indexOf(u.constructor))}constructFallback(s){return new s(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let c=await this.getTraceFilePath();c&&this.monitorBridge.addAsset({type:"trace",path:c,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let c=o8t(HEe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?l8t(HEe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=WJe(HEe(this.testInfo.file)),c=Ax.join(s,`${this.checksumTestId}.har.zip`);if(!(0,Tb.existsSync)(c))throw new Error("Could not find har file or zip file");let u=Ax.join(s,"tmp");(0,Tb.existsSync)(u)||(0,Tb.mkdirSync)(u);let _=(0,Tb.readFileSync)(c),g=await(0,Qnr.loadAsync)(_);for(let x of Object.keys(g.files)){let P=await g.file(x).async("string"),M=Ax.join(u,x);(0,Tb.writeFileSync)(M,P),this.unzippedHarData.push(M)}let E=Ax.join(u,"test.har");if(!(0,Tb.existsSync)(E))throw this.cleanupMockData(),new Error(`Could not find har file ${E} after unzipping ${c}`);return E}cleanupMockData(){this.unzippedHarData.forEach(s=>{(0,Tb.rmSync)(s)}),this.unzippedHarData.length>0&&(0,Tb.rmSync)(Ax.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let s={GET:0,POST:0,PUT:0,DELETE:0};try{let c=await this.prepareMockData();await this.page.routeFromHAR(c,{url:"*/**",notFound:"fallback",update:!1});let u=this.page._routes[0].handler;await this.page.route("**/*",_=>{let g=_.request().headers(),E=_.request().method();g["Checksum-Id"]=(++s[E]).toString(),_.request()._applyFallbackOverrides({headers:g}),u(_)})}catch(c){Ru("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=Ax.join(VU(q6()),"settings.asr");if(!(0,Tb.existsSync)(s)){Ru("Could not find ASR file");return}let{ungzip:c}=zJe();try{let u=await c((0,Tb.readFileSync)(s));this.appSpecificRules=JSON.parse(u)||{}}catch(u){Ru("Could not read ASR file",u.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(NO,"RuntimePage"),NO.recentlyInteracted=new Map;var s3e=NO;var o3e=require("fs");var PO={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Rei={defaultMerge:PO.defaultMerge};function Oyn(i,n){return n}t(Oyn,"defaultMetaDataUpdater");function Myn(i,n){return i.filter(s=>s!==void 0)}t(Myn,"defaultFilterValues");var jnr;(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"})(jnr||(jnr={}));function Jnr(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:Uyn(i)?1:i instanceof Set?3:i instanceof Map?4:5}t(Jnr,"getObjectType");function Lyn(i){let n=new Set;for(let s of i)for(let c of[...Object.keys(s),...Object.getOwnPropertySymbols(s)])n.add(c);return n}t(Lyn,"getKeys");function Qyn(i,n){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,n)}t(Qyn,"objectHasProperty");function znr(i){var c;let n=0,s=(c=i[0])==null?void 0:c[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var u;do{if(s===void 0)return{done:!0,value:void 0};let _=s.next();if(_.done===!0){n+=1,s=(u=i[n])==null?void 0:u[Symbol.iterator]();continue}return{done:!1,value:_.value}}while(!0)}}}}}t(znr,"getIterableOfIterables");var Vnr=["[object Object]","[object Module]"];function Uyn(i){if(!Vnr.includes(Object.prototype.toString.call(i)))return!1;let{constructor:n}=i;if(n===void 0)return!0;let s=n.prototype;return!(s===null||typeof s!="object"||!Vnr.includes(Object.prototype.toString.call(s))||!s.hasOwnProperty("isPrototypeOf"))}t(Uyn,"isRecord");function jyn(i,n,s){let c={};for(let u of Lyn(i)){let _=[];for(let x of i)Qyn(x,u)&&_.push(x[u]);if(_.length===0)continue;let g=n.metaDataUpdater(s,{key:u,parents:i}),E=qnr(_,n,g);E!==PO.skip&&(u==="__proto__"?Object.defineProperty(c,u,{value:E,configurable:!0,enumerable:!0,writable:!0}):c[u]=E)}return c}t(jyn,"mergeRecords$1");function Jyn(i){return i.flat()}t(Jyn,"mergeArrays$1");function Vyn(i){return new Set(znr(i))}t(Vyn,"mergeSets$1");function zyn(i){return new Map(znr(i))}t(zyn,"mergeMaps$1");function Wyn(i){return i.at(-1)}t(Wyn,"mergeOthers$1");var a3e={mergeRecords:jyn,mergeArrays:Jyn,mergeSets:Vyn,mergeMaps:zyn,mergeOthers:Wyn};function Wnr(...i){return qyn({})(...i)}t(Wnr,"deepmerge");function qyn(i,n){let s=Hyn(i,c);function c(...u){return qnr(u,s,n)}return t(c,"customizedDeepmerge"),c}t(qyn,"deepmergeCustom");function Hyn(i,n){return{defaultMergeFunctions:a3e,mergeFunctions:{...a3e,...Object.fromEntries(Object.entries(i).filter(([s,c])=>Object.hasOwn(a3e,s)).map(([s,c])=>c===!1?[s,a3e.mergeOthers]:[s,c]))},metaDataUpdater:i.metaDataUpdater??Oyn,deepmerge:n,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Myn,actions:PO}}t(Hyn,"getUtils");function qnr(i,n,s){var _;let c=((_=n.filterValues)==null?void 0:_.call(n,i,s))??i;if(c.length===0)return;if(c.length===1)return Cft(c,n,s);let u=Jnr(c[0]);if(u!==0&&u!==5){for(let g=1;g<c.length;g++)if(Jnr(c[g])!==u)return Cft(c,n,s)}switch(u){case 1:return $yn(c,n,s);case 2:return Gyn(c,n,s);case 3:return Yyn(c,n,s);case 4:return Zyn(c,n,s);default:return Cft(c,n,s)}}t(qnr,"mergeUnknowns");function $yn(i,n,s){let c=n.mergeFunctions.mergeRecords(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeRecords!==n.defaultMergeFunctions.mergeRecords?n.defaultMergeFunctions.mergeRecords(i,n,s):c}t($yn,"mergeRecords");function Gyn(i,n,s){let c=n.mergeFunctions.mergeArrays(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeArrays!==n.defaultMergeFunctions.mergeArrays?n.defaultMergeFunctions.mergeArrays(i):c}t(Gyn,"mergeArrays");function Yyn(i,n,s){let c=n.mergeFunctions.mergeSets(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeSets!==n.defaultMergeFunctions.mergeSets?n.defaultMergeFunctions.mergeSets(i):c}t(Yyn,"mergeSets");function Zyn(i,n,s){let c=n.mergeFunctions.mergeMaps(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeMaps!==n.defaultMergeFunctions.mergeMaps?n.defaultMergeFunctions.mergeMaps(i):c}t(Zyn,"mergeMaps");function Cft(i,n,s){let c=n.mergeFunctions.mergeOthers(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeOthers!==n.defaultMergeFunctions.mergeOthers?n.defaultMergeFunctions.mergeOthers(i):c}t(Cft,"mergeOthers");var Hnr=!1;function Unr(i){Hnr=i}t(Unr,"setLogToConsole");function Ru(...i){Hnr&&console.log(...i)}t(Ru,"log");async function POt(i,n,s,c=6e4){if(!(n in i))return i;let u=t(()=>i[n](...s),"executor");return c===null?u():$m(u(),c,"Execution timeout")}t(POt,"executePlaywrightMethodWithTimeout");function Sft({envName:i,role:n}={}){return{envName:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_NAME??i,role:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_ROLE??n}}t(Sft,"applyRuntimeEnvOverrides");function wft(i,{role:n,environment:s}={},c=!1){var E,x;let u;if(s&&(u=(E=i.environments)==null?void 0:E.find(({name:P})=>s===P)),u||(u=(x=i.environments)==null?void 0:x.find(({default:P})=>P)),!u)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let _=u.users,g;if(_&&(n!==void 0&&(g=_.find(P=>P.role===n)),g||(g=_.find(P=>P.default))),!g)throw new Error(`User not found. Please make sure the users array for the "${u.name}" environment is properly defined in the checksum.config.ts file.`);if(s&&u.name!==s){if(c)throw new Error(`Could not find environment with name "${s}" in config file`);console.warn(`Could not find environment with name "${s}" in config file, trying to use default environment`)}if(n&&g.role!==n){if(c)throw new Error(`Could not find user with role "${n}" for environment "${s}" in config file`);console.warn(`Could not find user with role "${n}" for environment "${s}" in config file, trying to login with environment's default user`)}return{environment:u,user:g}}t(wft,"resolveEnvironment");function Kyn(i){let n=`${i??q6()}/login.ts`;if(!(0,o3e.existsSync)(n))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${n}`),new Error("Could not find login.ts file");try{return require(n).default}catch(s){throw console.warn("Error loading login.ts file",s),s}}t(Kyn,"requireLogin");async function Xyn(i,n,{environment:s,user:c,config:u}){try{let _=t(()=>n(i,{environment:s,user:c,config:u}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${c!=null&&c.role?` using ${c.role} role`:""}${s!=null&&s.name?` in ${s.name} environment`:""}`,_,{skipAutoRecovery:!0}):await _()}catch(_){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
757
+ ${s.description}`})}async onTestComplete(s){this.testRunAnalytics.testRunEnd({success:s,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.hasSuccessfulAutoRecovery&&s}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(s,c=this.page){try{return c.mainFrame()._checksumInternal=!0,c._checksumInternal=!0,await s()}finally{c.mainFrame()._checksumInternal=!1,c._checksumInternal=!1}}async conditionallyWrapInternalSteps(s,c){return s?this.wrapInternalSteps(c):c()}async wrapNoLocationSteps(s){try{return this.testInfo._checksumNoLocation=!0,await s()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(s,c,u=[]){for(let _ of s){(_._stepId===c||_.stepId===c)&&u.push(_);let g=[_.steps,_._testInfoSteps,_._steps].filter(Boolean);for(let E of g)this.findAllStepsRecursively(E,c,u)}return u}makeChecksumStepFunction(s){return c=>{if(!s)return;let u=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,u).forEach(g=>{g.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(s){let c,u={box:!0,noLocation:!0,obtainStep:t(_=>{c=_},"obtainStep")};return await this.step(s.title,this.makeChecksumStepFunction(s.withError),!1,u),c!=null&&c.stepId&&this.arStepIds.push(c.stepId),c}async step(s,c,u=!0,{obtainStep:_=void 0,box:g=!1,noLocation:E=void 0}={}){let x=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=u===!0,E!==void 0&&(this.testInfo._checksumNoLocation=E),await this.test.step(s,c||(()=>{}),{obtainStep:_,box:g})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=x}}addErrorMessage(s,c){this.testInfo.addError(s,c)}async evaluateWithChecksum(s,c,u=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(u,()=>this.page.evaluate(s,c))}getChecksumTestId(){return this.checksumTestId}addNewThought(s,c,u=!1){let _={id:void 0,thought:s,type:c,children:u?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(_);else if(this.currentThought.children)this.currentThought.children.push(_),_.parent=this.currentThought;else{let g=this.currentThought.parent;g?(g.children.push(_),_.parent=g):this.highLevelThoughts.push(_)}return _.parent?_.id=`${_.parent.id}.${_.parent.children.length}`:_.id=`${++this.thoughtsCounter}`,this.currentThought=_,_}buildThoughtsChainForFallback(s=this.highLevelThoughts){let c=[];return s.forEach(u=>{c.push(u.thought),u.children&&c.push(...this.buildThoughtsChainForFallback(u.children))}),c}compoundSelection(...s){let c=super.compoundSelection(...s);return c.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),c}setSelectorFallback(s){let c={checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Eft};this.pushFallback(this.constructFallback(kue).init(c)),this.pushFallback(this.constructFallback(Tue).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(xue).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Eft}))}setAIFallback(s,c){var E;let u=((E=this.options.useChecksumAI)==null?void 0:E.arVersion)===1,_=t(()=>{var ce,ue,Se,Ct,gt,kt;let x=this.buildThoughtsChainForFallback(),P={title:this.testInfo.title},M={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},X={previous:x.slice(0,-1),failing:s,next:x.slice(1)},W={storyInfo:P,testIdentification:M,fallbackConfig:{arMode:(ce=this.options.useChecksumAI)==null?void 0:ce.arMode,overrideOptions:{...(ue=this.options.useChecksumAI)==null?void 0:ue.overrideOptions,...(Se=this.options.useChecksumAI)!=null&&Se.modelName&&!((gt=(Ct=this.options.useChecksumAI)==null?void 0:Ct.overrideOptions)!=null&&gt.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},markRecovered:(kt=this.options.useChecksumAI)==null?void 0:kt.markRecovered},thoughts:X,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(CN).init(W)},"createArFallback"),g=t(()=>{var x,P;return this.constructFallback(S7).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),arMode:(x=this.options.useChecksumAI)==null?void 0:x.arMode,overrideOptions:(P=this.options.useChecksumAI)==null?void 0:P.overrideOptions,fallbackType:c})},"createAIFallback");return u?this.pushFallback(g()):this.pushFallback(_()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,u,_){let g=s.fallbackAnalyticsPayload.iterationSteps,E=g.length>0?_/g.length:0;this.testRunAnalytics.testRunFallbackExecution({result:u.fbResult,failedThought:s.getFailedThought(),summary:u.summary,stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:_,avgDuration:E,success:["finish","soft_assertion"].includes(u.fbResult)}),this.arResults.push({failedThought:s.getFailedThought(),result:u.fbResult,thought:u.thought})}handleAutoRecovery(s,c,u,_){let g=u.stepsThoughts.length>0?_/u.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:s.failingThought,type:c.type,finalThought:u.thought,result:u.fbResult,duration:_,avgStepDuration:g,stepsThoughts:u.stepsThoughts,version:"v1"})}async runFallback(s,c){let u=Date.now(),_=s.resolve(c),g=await $m(_,s.timeout),E=Date.now()-u;s instanceof S7&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,g,E)),s instanceof CN&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,g,E));let x=g.thought?`: ${g.thought}`:"";if(!g||g.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${x}`,withError:!0}),new Error("Fallback failed");if(g.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${x}`,withError:!0}),new Vle(g.fbResult);if(this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof S7&&g.summary&&this.arSummaries.push(g.summary),s instanceof CN&&g.thought&&this.arSummaries.push(g.thought),this.createChecksumStep({title:`Recovery Complete${x}`}),g.steps.length===1){let P=g.steps[0];P.thought&&(this.currentThought.thought=P.thought)}else this.currentThought.children=g.steps.map((P,M)=>({id:`${this.currentThought.id}.${M+1}`,thought:P.thought,type:P.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(s,c,u){return s?await this.step(c,u):await u()}async onExecutionError(s){try{return await this.initiateFallbackSequence({type:"action",...s})}catch(c){if(!this.currentThought){let{locator:u,method:_}=s;this.testRunAnalytics.testRunActionExecutionFailure({locator:u.toString(),selector:u._selector,method:_,checksumStepId:this.checksumStepId,error:c.toString()})}throw c}}async initiateFallbackSequence(s,{fallbackTypes:c=void 0}={}){Ru(`[initiateFallbackSequence] with type: ${s.type}...`);let u=this.fallbacks.find(E=>E instanceof S7);if(u){let E=u.getFailedThought(),x=this.variableStore.getActiveVariables();this.fallbacks.forEach(P=>{P.setThought(E),P.setVariables(x)})}let _=this.fallbacks.find(E=>E instanceof CN);if(_){let E=_.failingThought;this.fallbacks.forEach(x=>{x instanceof CN&&x.setVariables(this.variableStore.getActiveVariables()),x.setThought(E)})}let g=this.fallbacks;c&&(g=g.filter(E=>c.reduce((x,P)=>x||E instanceof P,!1))),g=g.filter(E=>E.canResolve(s));try{for(let E of g){let x=E==null?void 0:E.toString();x&&console.log(`Using ${x}`);let P;try{let M=await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,E.getRecoveryAttemptTitle(s),async()=>await this.runFallback(E,s));P=!0}catch(M){if(P=!1,s.withChecksumAI&&M.message==="fetch failed")throw new Error(yR);M instanceof Vle&&M.fallbackResult==="hard_assertion"&&(s.error.fallbackResult="hard_assertion"),x&&console.log(`Failed to use ${x}`),E.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Due).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let s=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:s,testId:this.checksumTestId,fileName:Ax.basename(s)})}catch(s){Ru("Error shutting down RRweb events recording",s)}if(this.testRunAnalytics)return Ru("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[Due,xue,kue,Tue,S7];this.fallbacks.sort((c,u)=>s.indexOf(c.constructor)-s.indexOf(u.constructor))}constructFallback(s){return new s(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let c=await this.getTraceFilePath();c&&this.monitorBridge.addAsset({type:"trace",path:c,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let c=o8t(HEe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?l8t(HEe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=WJe(HEe(this.testInfo.file)),c=Ax.join(s,`${this.checksumTestId}.har.zip`);if(!(0,Tb.existsSync)(c))throw new Error("Could not find har file or zip file");let u=Ax.join(s,"tmp");(0,Tb.existsSync)(u)||(0,Tb.mkdirSync)(u);let _=(0,Tb.readFileSync)(c),g=await(0,Qnr.loadAsync)(_);for(let x of Object.keys(g.files)){let P=await g.file(x).async("string"),M=Ax.join(u,x);(0,Tb.writeFileSync)(M,P),this.unzippedHarData.push(M)}let E=Ax.join(u,"test.har");if(!(0,Tb.existsSync)(E))throw this.cleanupMockData(),new Error(`Could not find har file ${E} after unzipping ${c}`);return E}cleanupMockData(){this.unzippedHarData.forEach(s=>{(0,Tb.rmSync)(s)}),this.unzippedHarData.length>0&&(0,Tb.rmSync)(Ax.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let s={GET:0,POST:0,PUT:0,DELETE:0};try{let c=await this.prepareMockData();await this.page.routeFromHAR(c,{url:"*/**",notFound:"fallback",update:!1});let u=this.page._routes[0].handler;await this.page.route("**/*",_=>{let g=_.request().headers(),E=_.request().method();g["Checksum-Id"]=(++s[E]).toString(),_.request()._applyFallbackOverrides({headers:g}),u(_)})}catch(c){Ru("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=Ax.join(VU(q6()),"settings.asr");if(!(0,Tb.existsSync)(s)){Ru("Could not find ASR file");return}let{ungzip:c}=zJe();try{let u=await c((0,Tb.readFileSync)(s));this.appSpecificRules=JSON.parse(u)||{}}catch(u){Ru("Could not read ASR file",u.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(NO,"RuntimePage"),NO.recentlyInteracted=new Map;var s3e=NO;var o3e=require("fs");var PO={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Rei={defaultMerge:PO.defaultMerge};function Oyn(i,n){return n}t(Oyn,"defaultMetaDataUpdater");function Myn(i,n){return i.filter(s=>s!==void 0)}t(Myn,"defaultFilterValues");var jnr;(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"})(jnr||(jnr={}));function Jnr(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:Uyn(i)?1:i instanceof Set?3:i instanceof Map?4:5}t(Jnr,"getObjectType");function Lyn(i){let n=new Set;for(let s of i)for(let c of[...Object.keys(s),...Object.getOwnPropertySymbols(s)])n.add(c);return n}t(Lyn,"getKeys");function Qyn(i,n){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,n)}t(Qyn,"objectHasProperty");function znr(i){var c;let n=0,s=(c=i[0])==null?void 0:c[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var u;do{if(s===void 0)return{done:!0,value:void 0};let _=s.next();if(_.done===!0){n+=1,s=(u=i[n])==null?void 0:u[Symbol.iterator]();continue}return{done:!1,value:_.value}}while(!0)}}}}}t(znr,"getIterableOfIterables");var Vnr=["[object Object]","[object Module]"];function Uyn(i){if(!Vnr.includes(Object.prototype.toString.call(i)))return!1;let{constructor:n}=i;if(n===void 0)return!0;let s=n.prototype;return!(s===null||typeof s!="object"||!Vnr.includes(Object.prototype.toString.call(s))||!s.hasOwnProperty("isPrototypeOf"))}t(Uyn,"isRecord");function jyn(i,n,s){let c={};for(let u of Lyn(i)){let _=[];for(let x of i)Qyn(x,u)&&_.push(x[u]);if(_.length===0)continue;let g=n.metaDataUpdater(s,{key:u,parents:i}),E=qnr(_,n,g);E!==PO.skip&&(u==="__proto__"?Object.defineProperty(c,u,{value:E,configurable:!0,enumerable:!0,writable:!0}):c[u]=E)}return c}t(jyn,"mergeRecords$1");function Jyn(i){return i.flat()}t(Jyn,"mergeArrays$1");function Vyn(i){return new Set(znr(i))}t(Vyn,"mergeSets$1");function zyn(i){return new Map(znr(i))}t(zyn,"mergeMaps$1");function Wyn(i){return i.at(-1)}t(Wyn,"mergeOthers$1");var a3e={mergeRecords:jyn,mergeArrays:Jyn,mergeSets:Vyn,mergeMaps:zyn,mergeOthers:Wyn};function Wnr(...i){return qyn({})(...i)}t(Wnr,"deepmerge");function qyn(i,n){let s=Hyn(i,c);function c(...u){return qnr(u,s,n)}return t(c,"customizedDeepmerge"),c}t(qyn,"deepmergeCustom");function Hyn(i,n){return{defaultMergeFunctions:a3e,mergeFunctions:{...a3e,...Object.fromEntries(Object.entries(i).filter(([s,c])=>Object.hasOwn(a3e,s)).map(([s,c])=>c===!1?[s,a3e.mergeOthers]:[s,c]))},metaDataUpdater:i.metaDataUpdater??Oyn,deepmerge:n,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Myn,actions:PO}}t(Hyn,"getUtils");function qnr(i,n,s){var _;let c=((_=n.filterValues)==null?void 0:_.call(n,i,s))??i;if(c.length===0)return;if(c.length===1)return Cft(c,n,s);let u=Jnr(c[0]);if(u!==0&&u!==5){for(let g=1;g<c.length;g++)if(Jnr(c[g])!==u)return Cft(c,n,s)}switch(u){case 1:return $yn(c,n,s);case 2:return Gyn(c,n,s);case 3:return Yyn(c,n,s);case 4:return Zyn(c,n,s);default:return Cft(c,n,s)}}t(qnr,"mergeUnknowns");function $yn(i,n,s){let c=n.mergeFunctions.mergeRecords(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeRecords!==n.defaultMergeFunctions.mergeRecords?n.defaultMergeFunctions.mergeRecords(i,n,s):c}t($yn,"mergeRecords");function Gyn(i,n,s){let c=n.mergeFunctions.mergeArrays(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeArrays!==n.defaultMergeFunctions.mergeArrays?n.defaultMergeFunctions.mergeArrays(i):c}t(Gyn,"mergeArrays");function Yyn(i,n,s){let c=n.mergeFunctions.mergeSets(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeSets!==n.defaultMergeFunctions.mergeSets?n.defaultMergeFunctions.mergeSets(i):c}t(Yyn,"mergeSets");function Zyn(i,n,s){let c=n.mergeFunctions.mergeMaps(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeMaps!==n.defaultMergeFunctions.mergeMaps?n.defaultMergeFunctions.mergeMaps(i):c}t(Zyn,"mergeMaps");function Cft(i,n,s){let c=n.mergeFunctions.mergeOthers(i,n,s);return c===PO.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeOthers!==n.defaultMergeFunctions.mergeOthers?n.defaultMergeFunctions.mergeOthers(i):c}t(Cft,"mergeOthers");var Hnr=!1;function Unr(i){Hnr=i}t(Unr,"setLogToConsole");function Ru(...i){Hnr&&console.log(...i)}t(Ru,"log");async function POt(i,n,s,c=6e4){if(!(n in i))return i;let u=t(()=>i[n](...s),"executor");return c===null?u():$m(u(),c,"Execution timeout")}t(POt,"executePlaywrightMethodWithTimeout");function Sft({envName:i,role:n}={}){return{envName:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_NAME??i,role:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_ROLE??n}}t(Sft,"applyRuntimeEnvOverrides");function wft(i,{role:n,environment:s}={},c=!1){var E,x;let u;if(s&&(u=(E=i.environments)==null?void 0:E.find(({name:P})=>s===P)),u||(u=(x=i.environments)==null?void 0:x.find(({default:P})=>P)),!u)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let _=u.users,g;if(_&&(n!==void 0&&(g=_.find(P=>P.role===n)),g||(g=_.find(P=>P.default))),!g)throw new Error(`User not found. Please make sure the users array for the "${u.name}" environment is properly defined in the checksum.config.ts file.`);if(s&&u.name!==s){if(c)throw new Error(`Could not find environment with name "${s}" in config file`);console.warn(`Could not find environment with name "${s}" in config file, trying to use default environment`)}if(n&&g.role!==n){if(c)throw new Error(`Could not find user with role "${n}" for environment "${s}" in config file`);console.warn(`Could not find user with role "${n}" for environment "${s}" in config file, trying to login with environment's default user`)}return{environment:u,user:g}}t(wft,"resolveEnvironment");function Kyn(i){let n=`${i??q6()}/login.ts`;if(!(0,o3e.existsSync)(n))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${n}`),new Error("Could not find login.ts file");try{return require(n).default}catch(s){throw console.warn("Error loading login.ts file",s),s}}t(Kyn,"requireLogin");async function Xyn(i,n,{environment:s,user:c,config:u}){try{let _=t(()=>n(i,{environment:s,user:c,config:u}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${c!=null&&c.role?` using ${c.role} role`:""}${s!=null&&s.name?` in ${s.name} environment`:""}`,_,{skipAutoRecovery:!0}):await _()}catch(_){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
758
758
  `,_),_}}t(Xyn,"proceedWithLogin");function IV(i){let{config:n,folder:s,throwIfAuthFailed:c}=i,u=Kyn(s);return async(_,{role:g,environment:E}={})=>{let{envName:x,role:P}=Sft({envName:E,role:g}),{environment:M,user:X}=wft(n,{role:P,environment:x},i.throwIfEnvInfoInvalid);if(c&&!X)throw new Error("Could not find user credentials matching the provided role and/or environment");await Xyn(_,u,{environment:M,user:X,config:n})}}t(IV,"makeUnboundLogin");function $nr(i,{environmentName:n,userRole:s}){let c=IV(i);return u=>c(u,{environment:n,role:s})}t($nr,"makeBoundLogin");var Pee;function QIe(){if(Pee)return Pee;try{let i=(0,o3e.existsSync)(`${q6()}/checksum.config.ts`)?"checksum.config.ts":(0,o3e.existsSync)(`${q6()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return c3e(require(`${q6()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return c3e()}t(QIe,"loadChecksumConfig");function c3e(i={}){var s,c,u,_;let n={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1,skipTestsWithKnownBugs:!0},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,consecutiveActionDelay:100,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return((c=(s=i.options)==null?void 0:s.useChecksumAI)==null?void 0:c.visualComparison)===void 0&&((_=(u=i.options)==null?void 0:u.useChecksumAI)!=null&&_.assertions)&&(i.options.useChecksumAI.visualComparison=!0),Pee=Wnr(n,i),Yu.testRun.disableAutoRecovery&&(Pee.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),Yu.testRun.disableHostReports&&(Pee.options.hostReports=!1),Pee}t(c3e,"getChecksumConfig");var yR="Checksum failed connecting to the server";var yx=class yx{constructor(n){this.workerInfo=n;this.hasMonitor=!1;yx.monitorAgentPort?this.hasMonitor=!0:Ru("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}addAsset(n){this.signalUpload(n,["trace","har","rrweb-recording"].includes(n.type))}addChecksumTestMetadata(n){let s={type:"checksumTestMetadata",payload:n};this.sendMessage(s)}addTestInfo(n,s,c=!1){this.sendMessage({type:"testInfo",payload:{checksumTestId:n,pwTestId:s,usingChecksumTestIdPlaceholder:c}})}addSingleTestStats(n,s){this.sendMessage({type:"testStats",payload:{passed:n,healed:s}})}sendPlaywrightConfig(){yx.playwrightConfigSent||(this.sendMessage({type:"playwrightConfig",payload:this.buildPlaywrightConfig()}),yx.playwrightConfigSent=!0)}buildPlaywrightConfig(){let{use:n,testDir:s,testMatch:c,testIgnore:u,timeout:_,outputDir:g,retries:E}=this.workerInfo.project,{reporter:x,configFile:P,projects:M}=this.workerInfo.config,X=Object.keys(M).filter(W=>[n,s,c,u,_,g,E].includes(W)).reduce((W,ce)=>({...W,[ce]:M[ce]}),{});return{reporter:x,configFile:P,filteredProjects:X,use:n,testDir:s,testMatch:c,testIgnore:u,timeout:_,outputDir:g,retries:E}}sendMessage(n){if(this.hasMonitor)return fetch(`${yx.monitorAgentHost}:${yx.monitorAgentPort}`,{method:"POST",body:JSON.stringify(n)}).catch(s=>{Ru("Failed to send message to test run monitor",n,s)})}signalUpload(n,s=!1){return this.sendMessage({type:"asset",payload:n,watch:s})}};t(yx,"TestRunMonitorBridge"),yx.monitorAgentHost="http://localhost",yx.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT,yx.playwrightConfigSent=!1;var l3e=yx;var evn=t(()=>{let n=new Error().stack.split(`
759
759
  `).find(s=>s.includes(".checksum.spec.ts"));if(n)return{lineNumber:parseInt(n.split(":")[1]),columnNumber:parseInt(n.split(":")[2])}},"findCodeLocationFromStackTrace"),Ift=class Ift{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let n in this.store)Object.prototype.hasOwnProperty.call(this.store,n)&&delete this.store[n];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(n=>this.store[n])}setVariable(n,s){this.store[n]={name:n,value:s,type:s instanceof Function?"RandomValueGenerator":"FillValue"}}set(n,s,c){if(typeof s!="string")return!1;let u=evn();return n.store[s]={name:s,value:c,type:c instanceof Function?"RandomValueGenerator":"FillValue",...u,line:""},!0}get(n,s){var c;if(s in n)return n[s];if(!(s in n.store))throw new Error(`Variable ${s} is not defined`);return n.activeVariablesSet.add(s),(c=n.store[s])==null?void 0:c.value}};t(Ift,"VariableStore");var u3e=Ift;var Nir=require("@playwright/test"),Pir=uc(yir());var Ww=class Ww{constructor(n){this.options=n;this.importPluginPackages()}importPluginPackages(){Ww.pw??(Ww.pw=jft()),Ww.StealthPlugin??(Ww.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:n}=jft(),s=n(Ww.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),s}catch(n){throw console.error("[StealthProvider] Error creating fresh instance:",n),n}}buildChromiumWithPlugins(n){let{project:s}=this.options,c=s.use.userAgent,u=s.use.playwrightExtra||[],_=Ww.StealthPlugin();if(u.push(_),this.isCustomUserAgent(c)){_.enabledEvasions.delete("user-agent-override");let x=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:c});u.push(x)}let g=n??Ww.pw.chromium;return u.forEach((E,x)=>{try{!(E instanceof Pir.PuppeteerExtraPlugin)&&E!==_&&console.warn(`Plugin at index ${x} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),g.use(E)}catch(P){console.warn(P)}}),g}isCustomUserAgent(n){return n?!Object.values(Nir.devices).some(s=>n===s.userAgent):!1}};t(Ww,"StealthProvider");var d3e=Ww;function Bir(i,n){return{testSuiteRunId:n,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}t(Bir,"createDefaultTestSuiteRunInfo");var Rir=require("crypto");var BO=class BO{constructor(n){this.context=n;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++BO.instanceCounter,this.setContextProxy()}static makeContext(n){return new BO(n).proxy}_rawContext(){return this.context}setTestAssets(n){this._testAssets=n,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let n=await this.context.newPage();return await this.makePage(n)}async makePage(n){if(n._isChecksumPage===!0)return n;if(n.isClosed())throw new Error("Cannot initialize closed page");let s=this.getPageGuid(n);if(this.hasPage(s))return this.getPageByGuid(s);if(this._pagesInProgress.has(s))return this._pagesInProgress.get(s);let c=this._createPageInstance(n);this._pagesInProgress.set(s,c);try{let u=await c;return this._pagesInProgress.delete(s),this.addPage(u),u}catch(u){throw this._pagesInProgress.delete(s),u}}addPage(n){let s=this.getPageGuid(n);this._pages[s]=n,n.once("close",()=>{this.removePage(s)})}removePage(n){this._pages[n]&&delete this._pages[n]}async _createPageInstance(n){if(n.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await s3e.init(n,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(s){throw new Error(`Failed to initialize RuntimePage: ${s instanceof Error?s.message:String(s)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:t(function(s,c){return s.getContextMethod(c)},"get")})}setupPageListener(){this.context.on("page",async n=>{try{if(n.isClosed())return;await this.makePage(n)}catch(s){let c=s instanceof Error?s.message:String(s);if(c.includes("Page has already been closed")||c.includes("Target page, context or browser has been closed")){console.debug("[ChecksumBrowserContext] Skipping initialization of closed page");return}throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",s),s}})}getPageGuid(n){let s=this.pageGuidMap.get(n);return s||(s=`page@checksumctx_${this.instanceId}_${++BO.guidCounter}`,this.pageGuidMap.set(n,s)),s}getPageByGuid(n){return this._pages[n]}hasPage(n){return n in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(n){if(n in this){let c=this[n];return typeof c=="function"?c.bind(this):c}let s=this.context[n];return typeof s=="function"?s.bind(this.context):s}pages(){return this.getAllPages()}getPage(n){let s=this.getAllPages(),c=s[n];if(!c)throw new Error(`Page with index ${n} not found. Total pages: ${s.length}`);return c}};t(BO,"ChecksumBrowserContext"),BO.instanceCounter=0,BO.guidCounter=0;var _3e=BO;var Jft={},Oir=t((i,n,s={},c=!1)=>{let{runMode:u,environments:_}=n,g=_.find(x=>x.default),E=i.extend({baseURL:g.baseURL,bypassCSP:!0,permissions:t(async({},x,P)=>{await x(P.project.use.permissions)},"permissions"),proxy:t(async({proxy:x},P)=>{x?await P({...x,bypass:"127.0.0.1,localhost"}):await P(x)},"proxy"),browser:t(async({browser:x,browserName:P,launchOptions:M},X,W)=>{let ce=t(()=>(W.project.use.playwrightExtra||[]).some(gt=>gt.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),ue=t(async()=>{let Ct=await(await new d3e({project:W.project}).buildChromiumWithPlugins()).launch(M);await X(Ct)},"launchBrowserWithStealthPlugin");Yu.useRemoteDebugging.enabled&&ce()?await ue():await X(x)},"browser"),launchOptions:t(async({launchOptions:x},P)=>{let M=x!=null&&x.args?[...x.args]:[],X=t(W=>{M.includes(W)||M.push(W)},"pushArg");s.useMockData&&X("--disable-web-security"),Yu.bypassProxyForLocalhost&&X("--proxy-bypass-list=localhost,127.0.0.1"),Yu.useRemoteDebugging.enabled&&X(`--remote-debugging-port=${Yu.useRemoteDebugging.port}`),await P({...x,args:M})},"launchOptions"),variableStore:t(async({},x)=>{let P=new u3e;await x(P)},"variableStore"),vs:t(async({variableStore:x},P)=>{await P(x)},"vs"),variablesStore:t(async({variableStore:x},P)=>{await P(x)},"variablesStore"),testRunAnalytics:t(async({},x,P)=>{let M=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),Bir("playwright-run-version-unknown",(0,Rir.randomUUID)())}})(),X=Fir(P),W=lw.getTestRunInstance({...M,checksumTestId:X},process.env.CHECKSUM_ISOLATED_MODE==="true",P);await x(W)},"testRunAnalytics"),monitorBridge:[async({},x,P)=>{let M=new l3e(P);await x(M)},{scope:"worker"}],context:t(async({context:x,monitorBridge:P,variableStore:M,testRunAnalytics:X},W,ce)=>{let ue=_3e.makeContext(x);ue.setTestAssets({testRunAnalytics:X,monitorBridge:P,variableStore:M,testInfo:ce,checksumTestId:Fir(ce),test:E,config:n,isReplMode:c}),await W(ue),ue.cleanup()},"context"),page:t(async({page:x,context:P},M,X)=>{let W=await P.makePage(x);Object.defineProperty(W.constructor,"name",{value:"Page"}),await M(W),W&&typeof W.onTestComplete=="function"&&await W.onTestComplete(X.status==="passed"),W&&typeof W.shutdown=="function"&&await W.shutdown()},"page")});return{test:E,defineChecksumTest:Cvn}},"createChecksumTestExtension"),Cvn=t((i,n,s)=>{let u=new Error().stack.split(`
760
760
  `).filter(_=>_.includes(".checksum.spec.ts"))[0];if(!u)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Jft[u]=n,i},"defineChecksumTest");function Fir(i){let{file:n,line:s}=i,c=Object.keys(Jft).filter(_=>_.trim().includes(n.trim()));if(!c.length)return;let u=4;for(let _=0;_<u;_++)for(let g of c){let E;try{E=parseInt(g.split(":").reverse()[1])}catch{continue}if(E-_===parseInt(s))return Jft[g]}}t(Fir,"getCurrentTestIdFromMapping");var Svn=["toPass"],wvn=["toBeOK"],Ivn=["toBeAttached","toBeChecked","toBeDisabled","toBeEditable","toBeEmpty","toBeEnabled","toBeFocused","toBeHidden","toBeInViewport","toBeVisible","toContainClass","toContainText","toHaveAccessibleDescription","toHaveAccessibleErrorMessage","toHaveAccessibleName","toHaveAttribute","toHaveClass","toHaveCount","toHaveCSS","toHaveId","toHaveJSProperty","toHaveRole","toHaveScreenshot","toHaveText","toHaveValue","toHaveValues","toMatchAriaSnapshot"],Tvn=["toHaveScreenshot","toHaveTitle","toHaveURL"],xvn=["toMatchSnapshot"],kvn=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],Mir=[...kvn,...xvn],jti=[...Svn,...wvn,...Ivn,...Tvn];var Vft=class Vft{constructor(n,s,c=!1,u=!1,_={}){this.page=n;this.soft=c;this.skipAutoRecovery=u;this.configuration=_;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=t(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(s)}setThought(n){var s,c;n&&(this.checksumAIThought=this.page.addNewThought(n,"assertion"),this.useChecksumAIOptions=(s=this.page.getRuntimeOptions())==null?void 0:s.useChecksumAI,(c=this.useChecksumAIOptions)!=null&&c.assertions&&(this.page.setAIFallback(n,"assertion"),this.fallbackEnabled=!0))}get(n,s,c){if(typeof s!="string")return n[s];if(s==="checksumAI")return u=>(this.setThought(u),c);if(s==="withChecksumAI"||typeof n[s]=="function"){let u=s==="withChecksumAI"?this.withChecksumAIMatcher:n[s];return(..._)=>Mir.includes(s)?u.call(n,..._):this.checksumAIThought?this.executeMatcherWithinStep(u,n,..._):this.executeMatcher(u,n,..._)}else{let u=n[s];return new Proxy(u,this)}}findNestedErrors(n,s){n.error&&n.infectParentStepsWithError&&s.push(n.error);for(let c of n.steps)this.findNestedErrors(c,s)}async callMatcher(n,s,...c){this.beforeMatcherCall();let u=n.call(s,...c),_=u instanceof Promise?await u:u;if(this.step){let g=[];if(this.step.error?g.push(this.step.error):this.findNestedErrors(this.step,g),g.length)throw g[0]}return _}executeMatcherWithinStep(n,s,...c){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(n,s,...c).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:t(u=>this.step=u,"obtainStep")}).catch(u=>{if(!this.soft&&!(this.withChecksumAI&&u.message===yR))throw u}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(n,s,...c){try{return await this.callMatcher(n,s,...c)}catch(u){await this.onMatcherFailure(u)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(n){var c;return!(!this.fallbackEnabled||((c=n.matcherResult)==null?void 0:c.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(n){var s,c;if(!this.shouldInitiateFallback(n))throw Ru("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(s=this.checksumAIThought)==null?void 0:s.thought,error:n.message,matcher:(c=n.matcherResult)==null?void 0:c.name}),n;if(Ru("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAutoRecovery){if(this.soft)return;throw n}try{await this.page.initiateFallbackSequence({type:"assertion",error:n,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(u){if(this.soft)return;throw u}throw this.soft=!0,n}};t(Vft,"ExpectCallProxyHandler");var m3e=Vft;var g_e=class g_e{constructor(n=void 0,s={}){this.page=n;this.configuration=s}get(n,s){return s==="setPage"?c=>{this.page=c}:s==="extend"?(...c)=>{let u=n.extend(...c);return new Proxy(u,this)}:s==="configure"?c=>{let u=n.configure(c);return new Proxy(u,new g_e(this.page,{...this.configuration,...c}))}:s==="soft"?(...c)=>{let u=this.manipulateArgsAndExtractThought(c),_=n.soft(...c);return new Proxy(_,this.makeExpectCallProxyHandler(u,!0))}:s==="poll"?(...c)=>{let u=this.manipulateArgsAndExtractThought(c),_=n.poll(...c);return new Proxy(_,this.makeExpectCallProxyHandler(u))}:s==="skipAutoRecovery"?new Proxy(()=>{},{apply:t((u,_,g)=>{let E=this.manipulateArgsAndExtractThought(g),x=n.apply(_,g);return new Proxy(x,this.makeExpectCallProxyHandler(E,void 0,!0))},"apply"),get:t((u,_)=>new Proxy(n,new g_e(this.page,{...this.configuration,skipAutoRecovery:!0}))[_],"get")}):n[s]instanceof Function?n[s].bind(n):n[s]}apply(n,s,c){let u=this.manipulateArgsAndExtractThought(c),_=n.apply(s,c);return new Proxy(_,this.makeExpectCallProxyHandler(u))}makeExpectCallProxyHandler(n,s,c){var u,_;return new m3e(this.page,n,s===!0?!0:(u=this.configuration)==null?void 0:u.soft,c===!0?!0:(_=this.configuration)==null?void 0:_.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(n){let s,c=n[1];if(typeof c=="string")s=c,n[1]=void 0;else if(typeof c=="object"){if(c.checksumAI===!1){n[1].checksumAI=void 0;return}c.checksumAI&&typeof c.checksumAI=="string"?(s=c.checksumAI,n[1].checksumAI=void 0):c.message&&(s=c.message,n[1].message=void 0)}return s}};t(g_e,"ExpectProxyHandler");var h3e=g_e;var A3e=class A3e{constructor(n){this.expect=n;this.proxy=new Proxy(this.expect,new h3e)}static init(n){return new A3e(n).proxy}};t(A3e,"ChecksumExpect");var g3e=A3e;var Lir=require("@playwright/test");function Dvn(i){let n=QIe(),{options:s,apiKey:c,environments:u,defaultEnvironmentName:_}=n,g=u.find(ue=>ue.default);if(_&&(g=u.find(ue=>ue.name===_)),!g)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!g.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!g.users.find(ue=>ue.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!c)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let x=process.env.CHECKSUM_REPL==="true",{test:P,defineChecksumTest:M}=Oir(i??Lir.test,n,s,x),X=g3e.init(P.expect),W=Nvn();P._checksum={expect:X,checksumAI:W},x&&(console.log("Detected REPL mode"),P.beforeEach(async()=>{P.setTimeout(0)}),P.afterEach(async()=>{for(;;)await Dh(1e3)}));let ce=t(({name:ue,userRole:Se})=>{let{envName:Ct,role:gt}=Sft({envName:ue,role:Se}),{environment:kt,user:Et}=wft(n,{environment:Ct,role:gt},!0),Kt=$nr({config:n,throwIfEnvInfoInvalid:!0},{environmentName:kt.name,userRole:Et.role});return{environment:kt,user:Et,login:Kt}},"getEnvironment");return{test:P,expect:X,login:IV({config:n}),defineChecksumTest:M,getEnvironment:ce,checksumAI:W}}t(Dvn,"init");var zft=t(i=>new Proxy(i,{apply:t(function(s,c,u){let _={...s.options,...u[2]};return s.page.checksumAI(u[0],u[1],_)},"apply"),get:t(function(s,c){return c==="withDialog"?(s.options.withDialog=!0,zft(i)):c==="skipAutoRecovery"?(s.options.skipAutoRecovery=!0,zft(i)):s[c]},"get"),set:t(function(s,c,u){if(c==="page")return s[c]=u},"set")}),"makeChecksumAIProxy"),Nvn=t(()=>{let i=t(function(){},"func");return i.page=void 0,i.options={withDialog:!1,skipAutoRecovery:!1},zft(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,getChecksumConfig,getLogin,init});
package/package.json CHANGED
@@ -43,5 +43,5 @@
43
43
  "url": "https://github.com/checksum-ai/checksum-ai-monorepo/issues"
44
44
  },
45
45
  "homepage": "https://github.com/checksum-ai/checksum-ai-monorepo/tree/main/packages/runtime#readme",
46
- "version": "4.1.1-beta.9"
46
+ "version": "4.2.0"
47
47
  }