@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/.env +1 -1
- package/checksum-progress-reporter.js +1 -1
- package/cli.js +3 -3
- package/index.d.ts +6 -3
- package/index.js +3 -3
- package/package.json +1 -1
- package/test-run-monitor.js +92 -92
package/.env
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
CHECKSUM_RUNTIME_BUILD_TIME=2026-
|
|
1
|
+
CHECKSUM_RUNTIME_BUILD_TIME=2026-06-01T18:20:04.686Z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var n=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var l=(r,t)=>n(r,"name",{value:t,configurable:!0});var b=(r,t)=>{for(var e in t)n(r,e,{get:t[e],enumerable:!0})},A=(r,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of f(t))!T.call(r,o)&&o!==e&&n(r,o,{get:()=>t[o],enumerable:!(a=y(t,o))||a.enumerable});return r};var x=r=>A(n({},"__esModule",{value:!0}),r);var
|
|
1
|
+
"use strict";var n=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var l=(r,t)=>n(r,"name",{value:t,configurable:!0});var b=(r,t)=>{for(var e in t)n(r,e,{get:t[e],enumerable:!0})},A=(r,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of f(t))!T.call(r,o)&&o!==e&&n(r,o,{get:()=>t[o],enumerable:!(a=y(t,o))||a.enumerable});return r};var x=r=>A(n({},"__esModule",{value:!0}),r);var M={};b(M,{default:()=>s});module.exports=x(M);var h=require("path");var m=2e3;function P(r){switch(r){case"passed":return"passed";case"timedOut":return"timedOut";case"skipped":return"skipped";case"interrupted":return"interrupted";case"failed":default:return"failed"}}l(P,"toProgressStatus");var p=class p{constructor(){this.monitorPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT;this.startedAt=Date.now();this.rootDir=process.cwd();this.testsById=new Map;this.lastFlushAt=0;this.sendChain=Promise.resolve()}printsToStdio(){return!1}onBegin(t,e){this.guard(()=>{var a;t!=null&&t.rootDir&&(this.rootDir=t.rootDir);for(let o of((a=e==null?void 0:e.allTests)==null?void 0:a.call(e))??[])this.register(o);this.flush(!0)})}onTestBegin(t,e){this.guard(()=>{var o;let a=this.itemFor(t);a.status="running",a.startedAt=((o=e==null?void 0:e.startTime)==null?void 0:o.getTime())??Date.now(),a.endedAt=null,a.durationMs=null,a.retry=(e==null?void 0:e.retry)??0,this.flush()})}onTestEnd(t,e){this.guard(()=>{var o;let a=this.itemFor(t);a.status=P(e==null?void 0:e.status),a.endedAt=Date.now(),a.durationMs=(e==null?void 0:e.duration)??null,a.retry=(e==null?void 0:e.retry)??a.retry,a.startedAt==null&&(a.startedAt=((o=e==null?void 0:e.startTime)==null?void 0:o.getTime())??null),this.flush()})}async onEnd(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),await this.send()}itemFor(t){return this.testsById.get(t.id)??this.register(t)}register(t){var i,c,d,g,u;let e="";try{e=((d=(c=(i=t.parent)==null?void 0:i.project)==null?void 0:c.call(i))==null?void 0:d.name)??""}catch{}let a=((g=t.location)==null?void 0:g.file)??"";try{a&&(a=(0,h.relative)(this.rootDir,a))}catch{}let o={id:t.id,title:t.title??"",titlePath:this.titlePathOf(t),file:a,line:((u=t.location)==null?void 0:u.line)??0,project:e,status:"pending",startedAt:null,endedAt:null,durationMs:null,retry:0};return this.testsById.set(o.id,o),o}titlePathOf(t){var e;try{return(((e=t.titlePath)==null?void 0:e.call(t))??[]).filter(a=>!!a)}catch{return t.title?[t.title]:[]}}snapshot(){return{schemaVersion:1,source:"playwright",startedAt:this.startedAt,updatedAt:Date.now(),tests:[...this.testsById.values()]}}flush(t=!1){if(!this.monitorPort)return;let e=Date.now()-this.lastFlushAt;if(t||e>=m){this.lastFlushAt=Date.now(),this.send();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.lastFlushAt=Date.now(),this.send()},m-e))}send(){return this.monitorPort?(this.sendChain=this.sendChain.then(()=>this.postSnapshot()),this.sendChain):Promise.resolve()}async postSnapshot(){try{await fetch(`http://127.0.0.1:${this.monitorPort}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"runProgress",payload:this.snapshot()})})}catch{}}guard(t){try{t()}catch{}}};l(p,"ChecksumProgressReporter");var s=p;
|
package/cli.js
CHANGED
|
@@ -732,7 +732,7 @@ Details: ${ae.message}`),mir(ae)&&(he=`${he}
|
|
|
732
732
|
${Qke.prettifyError(ae)}`),new v_e(he,JSON.stringify(n))}else{let ae=qm(u,this.schema);if(!ae.valid){let he="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(he=`${he}
|
|
733
733
|
Details: ${ae.errors.map(ft=>`${ft.keywordLocation}: ${ft.error}`).join(`
|
|
734
734
|
`)}`),new v_e(he,JSON.stringify(n))}_=u}let h=i3e(s),b=D5.configure(h.callbacks,this.callbacks,h.tags||c,this.tags,h.metadata,this.metadata,{verbose:this.verbose}),S;DV(n)&&(S=n.id),!S&&uKt(h)&&(S=h.toolCall.id);let k=await(b==null?void 0:b.handleToolStart(this.toJSON(),typeof n=="string"?n:JSON.stringify(n),h.runId,void 0,void 0,void 0,h.runName,S));delete h.runId;let B;try{let ae=await this._call(_,k,h);B=Ppt(ae)?await msr(ae,async he=>{try{await(k==null?void 0:k.handleToolEvent(he))}catch(ft){await(k==null?void 0:k.handleToolError(ft))}}):ae}catch(ae){throw await(k==null?void 0:k.handleToolError(ae)),ae}let G,j;if(this.responseFormat==="content_and_artifact")if(Array.isArray(B)&&B.length===2)[G,j]=B;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
735
|
-
Result: ${JSON.stringify(B)}`);else G=B;let ie=D6n({content:G,artifact:j,toolCallId:S,name:this.name,metadata:this.metadata});return await(k==null?void 0:k.handleToolEnd(ie)),ie}},t(Lte,"StructuredTool"),Lte),Qte,I6n=(Qte=class extends jar{schema=ol.object({input:ol.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(Qte,"Tool"),Qte),Ute,T6n=(Ute=class extends I6n{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=i3e(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(Ute,"DynamicTool"),Ute),jte,k6n=(jte=class extends jar{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=i3e(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(jte,"DynamicStructuredTool"),jte);function Ddt(i,n){var h;let s=Z3e(n.schema),c=Rme(n.schema);if(!n.schema||s||c)return new T6n({...n,description:n.description??((h=n.schema)==null?void 0:h.description)??`${n.name} tool`,func:t(async(b,S,k)=>new Promise((B,G)=>{let j=W1(k,{callbacks:S==null?void 0:S.getChild()});_v.runWithConfig(mw(j),async()=>{try{B(i(b,j))}catch(ie){G(ie)}})}),"func")});let u=n.schema,_=n.description??n.schema.description??`${n.name} tool`;return new k6n({...n,description:_,schema:u,func:t(async(b,S,k)=>new Promise((B,G)=>{let j,ie=t(()=>{k!=null&&k.signal&&j&&k.signal.removeEventListener("abort",j)},"cleanup");k!=null&&k.signal&&(j=t(()=>{ie(),G(pM(k.signal))},"listener"),k.signal.addEventListener("abort",j,{once:!0}));let ae=W1(k,{callbacks:S==null?void 0:S.getChild()});_v.runWithConfig(mw(ae),async()=>{var he;try{let ft=await i(b,ae);if(Ppt(ft)){B(ft);return}if((he=k==null?void 0:k.signal)!=null&&he.aborted){ie();return}ie(),B(ft)}catch(ft){ie(),G(ft)}})}),"func")})}t(Ddt,"tool");function D6n(i){let{content:n,artifact:s,toolCallId:c,metadata:u}=i;return c&&!jKt(n)?typeof n=="string"||Array.isArray(n)&&n.every(_=>typeof _=="object")?new c8e({status:"success",content:n,artifact:s,tool_call_id:c,name:i.name,metadata:u}):new c8e({status:"success",content:N6n(n),artifact:s,tool_call_id:c,name:i.name,metadata:u}):n}t(D6n,"_formatToolOutput");function N6n(i){try{return JSON.stringify(i)??""}catch{return`${i}`}}t(N6n,"_stringify");var sP=class sP{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 ol.ZodObject){let c={},u=n.shape;for(let _ of Object.keys(u)){let h=u[_],b=s==null?void 0:s[_];typeof b=="string"?c[_]=h.describe(b):b&&typeof b=="object"?c[_]=sP.describeTool(h,b):c[_]=h}return ol.object(c).strict()}if(n instanceof ol.ZodArray){let c=n.element;return s&&typeof s=="object"&&s.element?ol.array(sP.describeTool(c,s.element)):n}return n instanceof ol.ZodOptional?sP.describeTool(n.unwrap(),s).optional():n instanceof ol.ZodNullable?sP.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}),h=this.toolRecord.tools[n],b=sP.describeTool(h,s.params),k=Ddt(t(async B=>{let G=b.parse(B);return s.handler(G)},"validatedHandler"),{name:_.name,description:_.description,schema:b});return this.toolsMap[n]=k,k}_buildOne(n,s){return this._addSingleTool(n,{...s,name:String(n)})}static buildTool(n,s,c){let u=String(s),h=n.tools[s]._create({name:u,description:"",handler:c,params:{}}),b=n.tools[s],S=sP.describeTool(b,{});return Ddt(t(async G=>{let j=S.parse(G);return c(j)},"validatedHandler"),{name:h.name,description:h.description,schema:S})}};t(sP,"AbstractToolContainer");var Q5=sP;var jke=class jke{constructor(n,s){this.version=n;let c={};for(let _ in s)c[_]=_;this.names=c;let u={};for(let _ in s){let h=s[_];Object.defineProperty(h,"name",{value:_,configurable:!1,enumerable:!0,writable:!1}),h._create=(b=>S=>{let k=S.name??b;return{...S,name:k}})(_),u[_]=h}this.tools=u}static create(n,s){return new jke(n,s)}};t(jke,"ToolProtocol");var Uke=jke;var Gh=Uke.create("v1",{readFile:ol.object({path:ol.string()}),getState:ol.object({thought:ol.string(),pageId:ol.string().optional(),includeAllPages:ol.boolean().optional()}),invokeCode:ol.object({code:ol.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:ol.string(),pageId:ol.string().optional()}),wait:ol.object({time:ol.number().optional()}),scroll:ol.object({checksumId:ol.string(),thought:ol.string()}),final_result:ol.object({result:ol.enum(["pass","fail"]),thought:ol.string(),visualAnalysis:ol.string().optional()}),getElementScreenshot:ol.object({checksumId:ol.string(),thought:ol.string()}),listPages:ol.object({thought:ol.string().optional()}),switchPage:ol.object({pageId:ol.string(),thought:ol.string().optional()}),analyze:ol.object({previousImmediateSteps:ol.string(),currentFailingStep:ol.string(),nextImmediateSteps:ol.string(),testStepToStopAt:ol.string()}),think:ol.object({thought:ol.string()})});var Hdt=Da(zar(),1);var HT=Object.create(null);HT.open="0";HT.close="1";HT.ping="2";HT.pong="3";HT.message="4";HT.upgrade="5";HT.noop="6";var Vme=Object.create(null);Object.keys(HT).forEach(i=>{Vme[HT[i]]=i});var zme={type:"error",data:"parser error"};var $me=t(({type:i,data:n},s,c)=>n instanceof ArrayBuffer||ArrayBuffer.isView(n)?c(s?n:"b"+$ar(n,!0).toString("base64")):c(HT[i]+(n||"")),"encodePacket"),$ar=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"),Pdt;function War(i,n){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return n($ar(i.data,!1));$me(i,!0,s=>{Pdt||(Pdt=new TextEncoder),n(Pdt.encode(s))})}t(War,"encodePacketToBinary");var Wme=t((i,n)=>{if(typeof i!="string")return{type:"message",data:qar(i,n)};let s=i.charAt(0);if(s==="b"){let c=Buffer.from(i.substring(1),"base64");return{type:"message",data:qar(c,n)}}return Vme[s]?i.length>1?{type:Vme[s],data:i.substring(1)}:{type:Vme[s]}:zme},"decodePacket"),qar=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 Har="",Gar=t((i,n)=>{let s=i.length,c=new Array(s),u=0;i.forEach((_,h)=>{$me(_,!1,b=>{c[h]=b,++u===s&&n(c.join(Har))})})},"encodePayload"),Yar=t((i,n)=>{let s=i.split(Har),c=[];for(let u=0;u<s.length;u++){let _=Wme(s[u],n);if(c.push(_),_.type==="error")break}return c},"decodePayload");function Zar(){return new TransformStream({transform(i,n){War(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(Zar,"createPacketEncoderStream");var Fdt;function Jke(i){return i.reduce((n,s)=>n+s.length,0)}t(Jke,"totalLength");function Vke(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(Vke,"concatChunks");function Kar(i,n){Fdt||(Fdt=new TextDecoder);let s=[],c=0,u=-1,_=!1;return new TransformStream({transform(h,b){for(s.push(h);;){if(c===0){if(Jke(s)<1)break;let S=Vke(s,1);_=(S[0]&128)===128,u=S[0]&127,u<126?c=3:u===126?c=1:c=2}else if(c===1){if(Jke(s)<2)break;let S=Vke(s,2);u=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),c=3}else if(c===2){if(Jke(s)<8)break;let S=Vke(s,8),k=new DataView(S.buffer,S.byteOffset,S.length),B=k.getUint32(0);if(B>Math.pow(2,21)-1){b.enqueue(zme);break}u=B*Math.pow(2,32)+k.getUint32(4),c=3}else{if(Jke(s)<u)break;let S=Vke(s,u);b.enqueue(Wme(_?S:Fdt.decode(S),n)),c=0}if(u===0||u>i){b.enqueue(zme);break}}}})}t(Kar,"createPacketDecoderStream");var Bdt=4;var mor=Da(Cz(),1);var aP=process.nextTick,Kb=global,eor="nodebuffer";function tor(){return new Rdt}t(tor,"createCookieJar");function R6n(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 h=1;h<n.length;h++){let b=n[h].split("=");if(b.length!==2)continue;let S=b[0].trim(),k=b[1].trim();switch(S){case"Expires":_.expires=new Date(k);break;case"Max-Age":let B=new Date;B.setUTCSeconds(B.getUTCSeconds()+parseInt(k,10)),_.expires=B;break;default:}}return _}t(R6n,"parse");var Odt=class Odt{constructor(){this._cookies=new Map}parseCookies(n){n&&n.forEach(s=>{let c=R6n(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(Odt,"CookieJar");var Rdt=Odt;function zke(i,...n){return n.reduce((s,c)=>(i.hasOwnProperty(c)&&(s[c]=i[c]),s),{})}t(zke,"pick");var O6n=Kb.setTimeout,M6n=Kb.clearTimeout;function oP(i,n){n.useNativeTimers?(i.setTimeoutFn=O6n.bind(Kb),i.clearTimeoutFn=M6n.bind(Kb)):(i.setTimeoutFn=Kb.setTimeout.bind(Kb),i.clearTimeoutFn=Kb.clearTimeout.bind(Kb))}t(oP,"installTimerFunctions");var L6n=1.33;function ror(i){return typeof i=="string"?Q6n(i):Math.ceil((i.byteLength||i.size)*L6n)}t(ror,"byteLength");function Q6n(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(Q6n,"utf8Length");function $ke(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}t($ke,"randomString");function nor(i){let n="";for(let s in i)i.hasOwnProperty(s)&&(n.length&&(n+="&"),n+=encodeURIComponent(s)+"="+encodeURIComponent(i[s]));return n}t(nor,"encode");function ior(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(ior,"decode");var hor=Da(wz(),1);var cCn=(0,hor.default)("engine.io-client:transport"),Vdt=class Vdt extends Error{constructor(n,s,c){super(n),this.description=s,this.context=c,this.type="TransportError"}};t(Vdt,"TransportError");var Yke=Vdt,zdt=class zdt extends mor.Emitter{constructor(n){super(),this.writable=!1,oP(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 Yke(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):cCn("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(n){let s=Wme(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=nor(n);return s.length?"?"+s:""}};t(zdt,"Transport");var cP=zdt;var gor=Da(wz(),1);var GT=(0,gor.default)("engine.io-client:polling"),$dt=class $dt extends cP{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(n){this.readyState="pausing";let s=t(()=>{GT("paused"),this.readyState="paused",n()},"pause");if(this._polling||!this.writable){let c=0;this._polling&&(GT("we are currently polling - waiting to pause"),c++,this.once("pollComplete",function(){GT("pre-pause polling complete"),--c||s()})),this.writable||(GT("we are currently writing - waiting to pause"),c++,this.once("drain",function(){GT("pre-pause writing complete"),--c||s()}))}else s()}_poll(){GT("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(n){GT("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");Yar(n,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():GT('ignoring poll - transport state "%s"',this.readyState))}doClose(){let n=t(()=>{GT("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(GT("transport open - closing"),n()):(GT("transport not open - deferring close"),this.once("open",n))}write(n){this.writable=!1,Gar(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]=$ke()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(n,s)}};t($dt,"Polling");var qme=$dt;var bor=Da(Cz(),1);var yor=!1;try{yor=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Aor=yor;var Eor=Da(wz(),1);var Wdt=(0,Eor.default)("engine.io-client:polling");function lCn(){}t(lCn,"empty");var qdt=class qdt extends qme{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(){Wdt("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(qdt,"BaseXHR");var Zke=qdt,Wte=class Wte extends bor.Emitter{constructor(n,s,c){super(),this.createRequest=n,oP(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=zke(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;let c=this._xhr=this.createRequest(s);try{Wdt("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))},Wdt("xhr data %s",this._data),c.send(this._data)}catch(u){this.setTimeoutFn(()=>{this._onError(u)},0);return}typeof document<"u"&&(this._index=Wte.requestsCount++,Wte.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=lCn,n)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Wte.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(Wte,"Request");var lP=Wte;lP.requestsCount=0;lP.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vor);else if(typeof addEventListener=="function"){let i="onpagehide"in Kb?"pagehide":"unload";addEventListener(i,vor,!1)}}function vor(){for(let i in lP.requests)lP.requests.hasOwnProperty(i)&&lP.requests[i].abort()}t(vor,"unloadHandler");var Qoi=function(){let i=uCn({xdomain:!1});return i&&i.responseType!==null}();function uCn(i){let n=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!n||Aor))return new XMLHttpRequest}catch{}if(!n)try{return new Kb[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}t(uCn,"newRequest");var fCn=Hdt.default||Hdt,Gdt=class Gdt extends Zke{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 lP(c=>new fCn(c),this.uri(),n)}};t(Gdt,"XHR");var qte=Gdt;var b4n=Da(wor(),1),E4n=Da(l_t(),1),x4n=Da(f_t(),1),S_t=Da(E_t(),1),C4n=Da(xcr(),1);var Ccr=Da(wz(),1);var w4n=(0,Ccr.default)("engine.io-client:websocket"),I4n=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",w_t=class w_t extends cP{get name(){return"websocket"}doOpen(){let n=this.uri(),s=this.opts.protocols,c=I4n?{}:zke(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;$me(c,this.supportsBinary,_=>{try{this.doWrite(c,_)}catch{w4n("websocket closed before onclose event")}u&&aP(()=>{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]=$ke()),this.supportsBinary||(s.b64=1),this.createUri(n,s)}};t(w_t,"BaseWS");var f5e=w_t,Sci=Kb.WebSocket||Kb.MozWebSocket;var I_t=class I_t extends f5e{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[_,h]of this.socket._cookieJar.cookies)c.headers.cookie.push(`${_}=${h.value}`)}return new S_t.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(I_t,"WS");var Kte=I_t;var Scr=Da(wz(),1);var ihe=(0,Scr.default)("engine.io-client:webtransport"),T_t=class T_t extends cP{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(()=>{ihe("transport closed gracefully"),this.onClose()}).catch(n=>{ihe("transport closed due to %s",n),this.onError("webtransport error",n)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(n=>{let s=Kar(Number.MAX_SAFE_INTEGER,this.socket.binaryType),c=n.readable.pipeThrough(s).getReader(),u=Zar();u.readable.pipeTo(n.writable),this._writer=u.writable.getWriter();let _=t(()=>{c.read().then(({done:b,value:S})=>{if(b){ihe("session is closed");return}ihe("received chunk: %o",S),this.onPacket(S),_()}).catch(b=>{ihe("an error occurred while reading: %s",b)})},"read");_();let h={type:"open"};this.query.sid&&(h.data=`{"sid":"${this.query.sid}"}`),this._writer.write(h).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&&aP(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var n;(n=this._transport)===null||n===void 0||n.close()}};t(T_t,"WT");var Xte=T_t;var k_t={websocket:Kte,webtransport:Xte,polling:qte};var T4n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,k4n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ere(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=T4n.exec(i||""),_={},h=14;for(;h--;)_[k4n[h]]=u[h]||"";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=D4n(_,_.path),_.queryKey=N4n(_,_.query),_}t(ere,"parse");function D4n(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(D4n,"pathNames");function N4n(i,n){let s={};return n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(c,u,_){u&&(s[u]=_)}),s}t(N4n,"queryKey");var wcr=Da(Cz(),1);var Icr=Da(wz(),1);var W_=(0,Icr.default)("engine.io-client:socket"),D_t=typeof addEventListener=="function"&&typeof removeEventListener=="function",she=[];D_t&&addEventListener("offline",()=>{W_("closing %d connection(s) because the network was lost",she.length),she.forEach(i=>i())},!1);var tre=class tre extends wcr.Emitter{constructor(n,s){if(super(),this.binaryType=eor,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=ere(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=ere(s.host).host);oP(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=ior(this.opts.query)),D_t&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(W_("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},she.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=tor()),this._open()}createTransport(n){W_('creating transport "%s"',n);let s=Object.assign({},this.opts.query);s.EIO=Bdt,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 W_("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&&tre.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){W_("setting transport %s",n.name),this.transport&&(W_("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(){W_("socket open"),this.readyState="open",tre.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(W_('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 W_('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();W_("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+=ror(u)),c>0&&s>this._maxPayload)return W_("only send %d out of %d packets",c,this.writeBuffer.length),this.writeBuffer.slice(0,c);s+=2}return W_("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&&(W_("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,aP(()=>{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"),W_("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(W_("socket error %j",n),tre.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return W_("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(W_('socket close with reason: "%s"',n),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),D_t&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let c=she.indexOf(this._offlineEventListener);c!==-1&&(W_("removing listener for the 'offline' event"),she.splice(c,1))}this.readyState="closed",this.id=null,this.emitReserved("close",n,s),this.writeBuffer=[],this._prevBufferLen=0}}};t(tre,"SocketWithoutUpgrade");var Nz=tre;Nz.protocol=Bdt;var N_t=class N_t extends Nz{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){W_("starting upgrade probes");for(let n=0;n<this._upgrades.length;n++)this._probe(this._upgrades[n])}}_probe(n){W_('probing transport "%s"',n);let s=this.createTransport(n),c=!1;Nz.priorWebsocketSuccess=!1;let u=t(()=>{c||(W_('probe transport "%s" opened',n),s.send([{type:"ping",data:"probe"}]),s.once("packet",G=>{if(!c)if(G.type==="pong"&&G.data==="probe"){if(W_('probe transport "%s" pong',n),this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;Nz.priorWebsocketSuccess=s.name==="websocket",W_('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{c||this.readyState!=="closed"&&(W_("changing transport and sending upgrade packet"),B(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{W_('probe transport "%s" failed',n);let j=new Error("probe error");j.transport=s.name,this.emitReserved("upgradeError",j)}}))},"onTransportOpen");function _(){c||(c=!0,B(),s.close(),s=null)}t(_,"freezeTransport");let h=t(G=>{let j=new Error("probe error: "+G);j.transport=s.name,_(),W_('probe transport "%s" failed because of error: %s',n,G),this.emitReserved("upgradeError",j)},"onerror");function b(){h("transport closed")}t(b,"onTransportClose");function S(){h("socket closed")}t(S,"onclose");function k(G){s&&G.name!==s.name&&(W_('"%s" works - aborting "%s"',G.name,s.name),_())}t(k,"onupgrade");let B=t(()=>{s.removeListener("open",u),s.removeListener("error",h),s.removeListener("close",b),this.off("close",S),this.off("upgrading",k)},"cleanup");s.once("open",u),s.once("error",h),s.once("close",b),this.once("close",S),this.once("upgrading",k),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(N_t,"SocketWithUpgrade");var p5e=N_t,P_t=class P_t extends p5e{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=>k_t[u]).filter(u=>!!u)),super(n,c)}};t(P_t,"Socket");var rre=P_t;var eli=rre.protocol;var Fcr=Da(nre(),1);var Pcr=(0,Fcr.default)("socket.io-client:url");function Bcr(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)||(Pcr("protocol-less url %s",i),typeof s<"u"?i=s.protocol+"//"+i:i="https://"+i),Pcr("parse %s",i),c=ere(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(Bcr,"url");var j_t={};Ck(j_t,{Decoder:()=>Q_t,Encoder:()=>L_t,PacketType:()=>ju,isPacketValid:()=>nSn,protocol:()=>jcr});var Lcr=Da(Cz(),1);var Y4n=typeof ArrayBuffer=="function",Z4n=t(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),Rcr=Object.prototype.toString,K4n=typeof Blob=="function"||typeof Blob<"u"&&Rcr.call(Blob)==="[object BlobConstructor]",X4n=typeof File=="function"||typeof File<"u"&&Rcr.call(File)==="[object FileConstructor]";function ohe(i){return Y4n&&(i instanceof ArrayBuffer||Z4n(i))||K4n&&i instanceof Blob||X4n&&i instanceof File}t(ohe,"isBinary");function ahe(i,n){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let s=0,c=i.length;s<c;s++)if(ahe(i[s]))return!0;return!1}if(ohe(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return ahe(i.toJSON(),!0);for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s)&&ahe(i[s]))return!0;return!1}t(ahe,"hasBinary");function Ocr(i){let n=[],s=i.data,c=i;return c.data=R_t(s,n),c.attachments=n.length,{packet:c,buffers:n}}t(Ocr,"deconstructPacket");function R_t(i,n){if(!i)return i;if(ohe(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]=R_t(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]=R_t(i[c],n));return s}return i}t(R_t,"_deconstructPacket");function Mcr(i,n){return i.data=O_t(i.data,n),delete i.attachments,i}t(Mcr,"reconstructPacket");function O_t(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]=O_t(i[s],n);else if(typeof i=="object")for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&(i[s]=O_t(i[s],n));return i}t(O_t,"_reconstructPacket");var Qcr=Da(nre(),1);var M_t=(0,Qcr.default)("socket.io-parser"),Ucr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],jcr=5,ju;(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"})(ju||(ju={}));var J_t=class J_t{constructor(n){this.replacer=n}encode(n){return M_t("encoding packet %j",n),(n.type===ju.EVENT||n.type===ju.ACK)&&ahe(n)?this.encodeAsBinary({type:n.type===ju.EVENT?ju.BINARY_EVENT:ju.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id}):[this.encodeAsString(n)]}encodeAsString(n){let s=""+n.type;return(n.type===ju.BINARY_EVENT||n.type===ju.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)),M_t("encoded %j as %s",n,s),s}encodeAsBinary(n){let s=Ocr(n),c=this.encodeAsString(s.packet),u=s.buffers;return u.unshift(c),u}};t(J_t,"Encoder");var L_t=J_t,g5e=class g5e extends Lcr.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===ju.BINARY_EVENT;c||s.type===ju.BINARY_ACK?(s.type=c?ju.EVENT:ju.ACK,this.reconstructor=new U_t(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(ohe(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(ju[c.type]===void 0)throw new Error("unknown packet type "+c.type);if(c.type===ju.BINARY_EVENT||c.type===ju.BINARY_ACK){let _=s+1;for(;n.charAt(++s)!=="-"&&s!=n.length;);let h=n.substring(_,s);if(h!=Number(h)||n.charAt(s)!=="-")throw new Error("Illegal attachments");let b=Number(h);if(!Jcr(b)||b<0)throw new Error("Illegal attachments");if(b>this.opts.maxAttachments)throw new Error("too many attachments");c.attachments=b}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 h=n.charAt(s);if(h==null||Number(h)!=h){--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(g5e.isPayloadValid(c.type,_))c.data=_;else throw new Error("invalid payload")}return M_t("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 ju.CONNECT:return h5e(s);case ju.DISCONNECT:return s===void 0;case ju.CONNECT_ERROR:return typeof s=="string"||h5e(s);case ju.EVENT:case ju.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&Ucr.indexOf(s[0])===-1);case ju.ACK:case ju.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};t(g5e,"Decoder");var Q_t=g5e,V_t=class V_t{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=Mcr(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};t(V_t,"BinaryReconstructor");var U_t=V_t;function eSn(i){return typeof i=="string"}t(eSn,"isNamespaceValid");var Jcr=Number.isInteger||function(i){return typeof i=="number"&&isFinite(i)&&Math.floor(i)===i};function tSn(i){return i===void 0||Jcr(i)}t(tSn,"isAckIdValid");function h5e(i){return Object.prototype.toString.call(i)==="[object Object]"}t(h5e,"isObject");function rSn(i,n){switch(i){case ju.CONNECT:return n===void 0||h5e(n);case ju.DISCONNECT:return n===void 0;case ju.EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Ucr.indexOf(n[0])===-1);case ju.ACK:return Array.isArray(n);case ju.CONNECT_ERROR:return typeof n=="string"||h5e(n);default:return!1}}t(rSn,"isDataValid");function nSn(i){return eSn(i.nsp)&&tSn(i.id)&&rSn(i.type,i.data)}t(nSn,"isPacketValid");function IC(i,n,s){return i.on(n,s),t(function(){i.off(n,s)},"subDestroy")}t(IC,"on");var Vcr=Da(Cz(),1),zcr=Da(nre(),1);var t1=(0,zcr.default)("socket.io-client:socket"),iSn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),z_t=class z_t extends Vcr.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=[IC(n,"open",this.onopen.bind(this)),IC(n,"packet",this.onpacket.bind(this)),IC(n,"error",this.onerror.bind(this)),IC(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(iSn.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 h={type:ju.EVENT,data:s};if(h.options={},h.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){let B=this.ids++;t1("emitting packet with ack id %d",B);let G=s.pop();this._registerAckCallback(B,G),h.id=B}let b=(u=(c=this.io.engine)===null||c===void 0?void 0:c.transport)===null||u===void 0?void 0:u.writable,S=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!b?t1("discard packet as the transport is not currently writable"):S?(this.notifyOutgoingListeners(h),this.packet(h)):this.sendBuffer.push(h),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 b=0;b<this.sendBuffer.length;b++)this.sendBuffer[b].id===n&&(t1("removing packet with ack id %d from the buffer",n),this.sendBuffer.splice(b,1));t1("event with ack id %d has timed out after %d ms",n,u),s.call(this,new Error("operation has timed out"))},u),h=t((...b)=>{this.io.clearTimeoutFn(_),s.apply(this,b)},"fn");h.withError=!0,this.acks[n]=h}emitWithAck(n,...s){return new Promise((c,u)=>{let _=t((h,b)=>h?u(h):c(b),"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]?t1("packet [%d] already acknowledged",c.id):(u!==null?c.tryCount>this._opts.retries&&(t1("packet [%d] is discarded after %d tries",c.id,c.tryCount),this._queue.shift(),s&&s(u)):(t1("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(t1("draining queue"),!this.connected||this._queue.length===0)return;let s=this._queue[0];if(s.pending&&!n){t1("packet [%d] has already been sent and is waiting for an ack",s.id);return}s.pending=!0,s.tryCount++,t1("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(){t1("transport is open - connecting"),typeof this.auth=="function"?this.auth(n=>{this._sendConnectPacket(n)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(n){this.packet({type:ju.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){t1("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 ju.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 ju.EVENT:case ju.BINARY_EVENT:this.onevent(n);break;case ju.ACK:case ju.BINARY_ACK:this.onack(n);break;case ju.DISCONNECT:this.ondisconnect();break;case ju.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||[];t1("emitting event %j",s),n.id!=null&&(t1("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,t1("sending ack %j",u),s.packet({type:ju.ACK,id:n,data:u}))}}onack(n){let s=this.acks[n.id];if(typeof s!="function"){t1("bad ack %s",n.id);return}delete this.acks[n.id],t1("calling ack %s with %j",n.id,n.data),s.withError&&n.data.unshift(null),s.apply(this,n.data)}onconnect(n,s){t1("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(){t1("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&&(t1("performing disconnect (%s)",this.nsp),this.packet({type:ju.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(z_t,"Socket");var ire=z_t;function Pz(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(Pz,"Backoff");Pz.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};Pz.prototype.reset=function(){this.attempts=0};Pz.prototype.setMin=function(i){this.ms=i};Pz.prototype.setMax=function(i){this.max=i};Pz.prototype.setJitter=function(i){this.jitter=i};var $cr=Da(Cz(),1),Wcr=Da(nre(),1);var o2=(0,Wcr.default)("socket.io-client:manager"),$_t=class $_t extends $cr.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,oP(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 Pz({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||j_t;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(o2("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;o2("opening %s",this.uri),this.engine=new rre(this.uri,this.opts);let s=this.engine,c=this;this._readyState="opening",this.skipReconnect=!1;let u=IC(s,"open",function(){c.onopen(),n&&n()}),_=t(b=>{o2("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",b),n?n(b):this.maybeReconnectOnOpen()},"onError"),h=IC(s,"error",_);if(this._timeout!==!1){let b=this._timeout;o2("connect attempt will timeout after %d",b);let S=this.setTimeoutFn(()=>{o2("connect attempt timed out after %d",b),u(),_(new Error("timeout")),s.close()},b);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(u),this.subs.push(h),this}connect(n){return this.open(n)}onopen(){o2("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let n=this.engine;this.subs.push(IC(n,"ping",this.onping.bind(this)),IC(n,"data",this.ondata.bind(this)),IC(n,"error",this.onerror.bind(this)),IC(n,"close",this.onclose.bind(this)),IC(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){aP(()=>{this.emitReserved("packet",n)},this.setTimeoutFn)}onerror(n){o2("error",n),this.emitReserved("error",n)}socket(n,s){let c=this.nsps[n];return c?this._autoConnect&&!c.active&&c.connect():(c=new ire(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){o2("socket %s is still active, skipping close",c);return}this._close()}_packet(n){o2("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(){o2("cleanup"),this.subs.forEach(n=>n()),this.subs.length=0,this.decoder.destroy()}_close(){o2("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(n,s){var c;o2("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)o2("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let s=this.backoff.duration();o2("will wait %dms before reconnect attempt",s),this._reconnecting=!0;let c=this.setTimeoutFn(()=>{n.skipReconnect||(o2("attempting reconnect"),this.emitReserved("reconnect_attempt",n.backoff.attempts),!n.skipReconnect&&n.open(u=>{u?(o2("reconnect attempt error"),n._reconnecting=!1,n.reconnect(),this.emitReserved("reconnect_error",u)):(o2("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($_t,"Manager");var sre=$_t;var Hcr=Da(nre(),1);var qcr=(0,Hcr.default)("socket.io-client"),che={};function lhe(i,n){typeof i=="object"&&(n=i,i=void 0),n=n||{};let s=Bcr(i,n.path||"/socket.io"),c=s.source,u=s.id,_=s.path,h=che[u]&&_ in che[u].nsps,b=n.forceNew||n["force new connection"]||n.multiplex===!1||h,S;return b?(qcr("ignoring socket cache for %s",c),S=new sre(c,n)):(che[u]||(qcr("new io instance for %s",c),che[u]=new sre(c,n)),S=che[u]),s.query&&!n.query&&(n.query=s.queryKey),S.socket(s.path,n)}t(lhe,"lookup");Object.assign(lhe,{Manager:sre,Socket:ire,io:lhe,connect:lhe});var y5e={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},W_t=class W_t{constructor(n={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=n,this.url=n.url||y5e.URL,this.namespace=n.namespace||y5e.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((_,h)=>{setTimeout(()=>{h(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=lhe(u,{autoConnect:!0,reconnection:!0,reconnectionAttempts:y5e.RECONNECTION_ATTEMPTS,reconnectionDelay:y5e.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 h=`No handler registered for method: ${n.key}`;this.logError(`\u274C ${h}`),s(this.error(h));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(W_t,"AbstractClient");var A5e=W_t;var Gcr,Ycr,Zcr,Kcr,Xcr,elr,tlr,rlr,b5e=class b5e extends(rlr=A5e,tlr=Gh.names.getState,elr=Gh.names.invokeCode,Xcr=Gh.names.final_result,Kcr=Gh.names.wait,Zcr=Gh.names.getElementScreenshot,Ycr=Gh.names.listPages,Gcr=Gh.names.switchPage,rlr){constructor(s,c){super({verbose:gc.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[tlr]=Q5.buildTool(Gh,Gh.names.getState,async s=>this.getStateHandler(s));this[elr]=Q5.buildTool(Gh,Gh.names.invokeCode,async s=>this.invokeCodeHandler(s));this[Xcr]=Q5.buildTool(Gh,Gh.names.final_result,async s=>this.finalResultHandler(s));this[Kcr]=Q5.buildTool(Gh,Gh.names.wait,async s=>this.waitHandler(s));this[Zcr]=Q5.buildTool(Gh,Gh.names.getElementScreenshot,async s=>this.getElementScreenshotHandler(s));this[Ycr]=Q5.buildTool(Gh,Gh.names.listPages,async s=>this.listPagesHandler(s));this[Gcr]=Q5.buildTool(Gh,Gh.names.switchPage,async s=>this.switchPageHandler(s))}async init(){let s={...this.initData,version:Gh.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 b5e(s,c)}async invokeCodeHandler(s){let c,u=this.utils.activePageGuid,h=!!(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{h&&await this.utils.setActivePage(s.pageId);let b=await this.utils.invokeCode(s.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),c={success:!0,invokeCodeResult:`invokeCodeResult: ${b.result}`,appState:(await this.utils.buildFallbackData()).applicationState,actionEffects:b.effects}}catch(b){c={success:!1,invokeCodeResult:`Error while invoking code: ${b}`,appState:(await this.utils.buildFallbackData()).applicationState}}finally{if(h&&u)try{await this.utils.setActivePage(u)}catch(b){console.warn("Failed to switch back to original page:",b)}}}),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(h){console.warn("Failed to record auto-recovery final-result analytics:",h)}try{this.utils.addAutoRecoveryErrorToReport(s.thought,c)}catch(h){console.warn("Failed to add auto-recovery result to report:",h)}}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((h,b)=>`${b+1}. ${h.title||"Untitled"} (${h.url})
|
|
735
|
+
Result: ${JSON.stringify(B)}`);else G=B;let ie=D6n({content:G,artifact:j,toolCallId:S,name:this.name,metadata:this.metadata});return await(k==null?void 0:k.handleToolEnd(ie)),ie}},t(Lte,"StructuredTool"),Lte),Qte,I6n=(Qte=class extends jar{schema=ol.object({input:ol.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(Qte,"Tool"),Qte),Ute,T6n=(Ute=class extends I6n{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=i3e(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(Ute,"DynamicTool"),Ute),jte,k6n=(jte=class extends jar{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=i3e(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(jte,"DynamicStructuredTool"),jte);function Ddt(i,n){var h;let s=Z3e(n.schema),c=Rme(n.schema);if(!n.schema||s||c)return new T6n({...n,description:n.description??((h=n.schema)==null?void 0:h.description)??`${n.name} tool`,func:t(async(b,S,k)=>new Promise((B,G)=>{let j=W1(k,{callbacks:S==null?void 0:S.getChild()});_v.runWithConfig(mw(j),async()=>{try{B(i(b,j))}catch(ie){G(ie)}})}),"func")});let u=n.schema,_=n.description??n.schema.description??`${n.name} tool`;return new k6n({...n,description:_,schema:u,func:t(async(b,S,k)=>new Promise((B,G)=>{let j,ie=t(()=>{k!=null&&k.signal&&j&&k.signal.removeEventListener("abort",j)},"cleanup");k!=null&&k.signal&&(j=t(()=>{ie(),G(pM(k.signal))},"listener"),k.signal.addEventListener("abort",j,{once:!0}));let ae=W1(k,{callbacks:S==null?void 0:S.getChild()});_v.runWithConfig(mw(ae),async()=>{var he;try{let ft=await i(b,ae);if(Ppt(ft)){B(ft);return}if((he=k==null?void 0:k.signal)!=null&&he.aborted){ie();return}ie(),B(ft)}catch(ft){ie(),G(ft)}})}),"func")})}t(Ddt,"tool");function D6n(i){let{content:n,artifact:s,toolCallId:c,metadata:u}=i;return c&&!jKt(n)?typeof n=="string"||Array.isArray(n)&&n.every(_=>typeof _=="object")?new c8e({status:"success",content:n,artifact:s,tool_call_id:c,name:i.name,metadata:u}):new c8e({status:"success",content:N6n(n),artifact:s,tool_call_id:c,name:i.name,metadata:u}):n}t(D6n,"_formatToolOutput");function N6n(i){try{return JSON.stringify(i)??""}catch{return`${i}`}}t(N6n,"_stringify");var sP=class sP{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 ol.ZodObject){let c={},u=n.shape;for(let _ of Object.keys(u)){let h=u[_],b=s==null?void 0:s[_];typeof b=="string"?c[_]=h.describe(b):b&&typeof b=="object"?c[_]=sP.describeTool(h,b):c[_]=h}return ol.object(c).strict()}if(n instanceof ol.ZodArray){let c=n.element;return s&&typeof s=="object"&&s.element?ol.array(sP.describeTool(c,s.element)):n}return n instanceof ol.ZodOptional?sP.describeTool(n.unwrap(),s).optional():n instanceof ol.ZodNullable?sP.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}),h=this.toolRecord.tools[n],b=sP.describeTool(h,s.params),k=Ddt(t(async B=>{let G=b.parse(B);return s.handler(G)},"validatedHandler"),{name:_.name,description:_.description,schema:b});return this.toolsMap[n]=k,k}_buildOne(n,s){return this._addSingleTool(n,{...s,name:String(n)})}static buildTool(n,s,c){let u=String(s),h=n.tools[s]._create({name:u,description:"",handler:c,params:{}}),b=n.tools[s],S=sP.describeTool(b,{});return Ddt(t(async G=>{let j=S.parse(G);return c(j)},"validatedHandler"),{name:h.name,description:h.description,schema:S})}};t(sP,"AbstractToolContainer");var Q5=sP;var jke=class jke{constructor(n,s){this.version=n;let c={};for(let _ in s)c[_]=_;this.names=c;let u={};for(let _ in s){let h=s[_];Object.defineProperty(h,"name",{value:_,configurable:!1,enumerable:!0,writable:!1}),h._create=(b=>S=>{let k=S.name??b;return{...S,name:k}})(_),u[_]=h}this.tools=u}static create(n,s){return new jke(n,s)}};t(jke,"ToolProtocol");var Uke=jke;var Gh=Uke.create("v1",{readFile:ol.object({path:ol.string()}),getState:ol.object({thought:ol.string(),pageId:ol.string().optional(),includeAllPages:ol.boolean().optional()}),invokeCode:ol.object({code:ol.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:ol.string(),pageId:ol.string().optional()}),wait:ol.object({time:ol.number().optional()}),scroll:ol.object({checksumId:ol.string(),thought:ol.string()}),final_result:ol.object({result:ol.enum(["pass","fail"]),thought:ol.string(),visualAnalysis:ol.string().optional()}),getElementScreenshot:ol.object({checksumId:ol.string(),thought:ol.string()}),listPages:ol.object({thought:ol.string().optional()}),switchPage:ol.object({pageId:ol.string(),thought:ol.string().optional()}),analyze:ol.object({previousImmediateSteps:ol.string(),currentFailingStep:ol.string(),nextImmediateSteps:ol.string(),testStepToStopAt:ol.string()}),think:ol.object({thought:ol.string()})});var Hdt=Da(zar(),1);var HT=Object.create(null);HT.open="0";HT.close="1";HT.ping="2";HT.pong="3";HT.message="4";HT.upgrade="5";HT.noop="6";var Vme=Object.create(null);Object.keys(HT).forEach(i=>{Vme[HT[i]]=i});var zme={type:"error",data:"parser error"};var $me=t(({type:i,data:n},s,c)=>n instanceof ArrayBuffer||ArrayBuffer.isView(n)?c(s?n:"b"+$ar(n,!0).toString("base64")):c(HT[i]+(n||"")),"encodePacket"),$ar=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"),Pdt;function War(i,n){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return n($ar(i.data,!1));$me(i,!0,s=>{Pdt||(Pdt=new TextEncoder),n(Pdt.encode(s))})}t(War,"encodePacketToBinary");var Wme=t((i,n)=>{if(typeof i!="string")return{type:"message",data:qar(i,n)};let s=i.charAt(0);if(s==="b"){let c=Buffer.from(i.substring(1),"base64");return{type:"message",data:qar(c,n)}}return Vme[s]?i.length>1?{type:Vme[s],data:i.substring(1)}:{type:Vme[s]}:zme},"decodePacket"),qar=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 Har="",Gar=t((i,n)=>{let s=i.length,c=new Array(s),u=0;i.forEach((_,h)=>{$me(_,!1,b=>{c[h]=b,++u===s&&n(c.join(Har))})})},"encodePayload"),Yar=t((i,n)=>{let s=i.split(Har),c=[];for(let u=0;u<s.length;u++){let _=Wme(s[u],n);if(c.push(_),_.type==="error")break}return c},"decodePayload");function Zar(){return new TransformStream({transform(i,n){War(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(Zar,"createPacketEncoderStream");var Fdt;function Jke(i){return i.reduce((n,s)=>n+s.length,0)}t(Jke,"totalLength");function Vke(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(Vke,"concatChunks");function Kar(i,n){Fdt||(Fdt=new TextDecoder);let s=[],c=0,u=-1,_=!1;return new TransformStream({transform(h,b){for(s.push(h);;){if(c===0){if(Jke(s)<1)break;let S=Vke(s,1);_=(S[0]&128)===128,u=S[0]&127,u<126?c=3:u===126?c=1:c=2}else if(c===1){if(Jke(s)<2)break;let S=Vke(s,2);u=new DataView(S.buffer,S.byteOffset,S.length).getUint16(0),c=3}else if(c===2){if(Jke(s)<8)break;let S=Vke(s,8),k=new DataView(S.buffer,S.byteOffset,S.length),B=k.getUint32(0);if(B>Math.pow(2,21)-1){b.enqueue(zme);break}u=B*Math.pow(2,32)+k.getUint32(4),c=3}else{if(Jke(s)<u)break;let S=Vke(s,u);b.enqueue(Wme(_?S:Fdt.decode(S),n)),c=0}if(u===0||u>i){b.enqueue(zme);break}}}})}t(Kar,"createPacketDecoderStream");var Bdt=4;var mor=Da(Cz(),1);var aP=process.nextTick,Kb=global,eor="nodebuffer";function tor(){return new Rdt}t(tor,"createCookieJar");function R6n(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 h=1;h<n.length;h++){let b=n[h].split("=");if(b.length!==2)continue;let S=b[0].trim(),k=b[1].trim();switch(S){case"Expires":_.expires=new Date(k);break;case"Max-Age":let B=new Date;B.setUTCSeconds(B.getUTCSeconds()+parseInt(k,10)),_.expires=B;break;default:}}return _}t(R6n,"parse");var Odt=class Odt{constructor(){this._cookies=new Map}parseCookies(n){n&&n.forEach(s=>{let c=R6n(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(Odt,"CookieJar");var Rdt=Odt;function zke(i,...n){return n.reduce((s,c)=>(i.hasOwnProperty(c)&&(s[c]=i[c]),s),{})}t(zke,"pick");var O6n=Kb.setTimeout,M6n=Kb.clearTimeout;function oP(i,n){n.useNativeTimers?(i.setTimeoutFn=O6n.bind(Kb),i.clearTimeoutFn=M6n.bind(Kb)):(i.setTimeoutFn=Kb.setTimeout.bind(Kb),i.clearTimeoutFn=Kb.clearTimeout.bind(Kb))}t(oP,"installTimerFunctions");var L6n=1.33;function ror(i){return typeof i=="string"?Q6n(i):Math.ceil((i.byteLength||i.size)*L6n)}t(ror,"byteLength");function Q6n(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(Q6n,"utf8Length");function $ke(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}t($ke,"randomString");function nor(i){let n="";for(let s in i)i.hasOwnProperty(s)&&(n.length&&(n+="&"),n+=encodeURIComponent(s)+"="+encodeURIComponent(i[s]));return n}t(nor,"encode");function ior(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(ior,"decode");var hor=Da(wz(),1);var cCn=(0,hor.default)("engine.io-client:transport"),Vdt=class Vdt extends Error{constructor(n,s,c){super(n),this.description=s,this.context=c,this.type="TransportError"}};t(Vdt,"TransportError");var Yke=Vdt,zdt=class zdt extends mor.Emitter{constructor(n){super(),this.writable=!1,oP(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 Yke(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):cCn("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(n){let s=Wme(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=nor(n);return s.length?"?"+s:""}};t(zdt,"Transport");var cP=zdt;var gor=Da(wz(),1);var GT=(0,gor.default)("engine.io-client:polling"),$dt=class $dt extends cP{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(n){this.readyState="pausing";let s=t(()=>{GT("paused"),this.readyState="paused",n()},"pause");if(this._polling||!this.writable){let c=0;this._polling&&(GT("we are currently polling - waiting to pause"),c++,this.once("pollComplete",function(){GT("pre-pause polling complete"),--c||s()})),this.writable||(GT("we are currently writing - waiting to pause"),c++,this.once("drain",function(){GT("pre-pause writing complete"),--c||s()}))}else s()}_poll(){GT("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(n){GT("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");Yar(n,this.socket.binaryType).forEach(s),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():GT('ignoring poll - transport state "%s"',this.readyState))}doClose(){let n=t(()=>{GT("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(GT("transport open - closing"),n()):(GT("transport not open - deferring close"),this.once("open",n))}write(n){this.writable=!1,Gar(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]=$ke()),!this.supportsBinary&&!s.sid&&(s.b64=1),this.createUri(n,s)}};t($dt,"Polling");var qme=$dt;var bor=Da(Cz(),1);var yor=!1;try{yor=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Aor=yor;var Eor=Da(wz(),1);var Wdt=(0,Eor.default)("engine.io-client:polling");function lCn(){}t(lCn,"empty");var qdt=class qdt extends qme{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(){Wdt("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(qdt,"BaseXHR");var Zke=qdt,Wte=class Wte extends bor.Emitter{constructor(n,s,c){super(),this.createRequest=n,oP(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=zke(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this._opts.xd;let c=this._xhr=this.createRequest(s);try{Wdt("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))},Wdt("xhr data %s",this._data),c.send(this._data)}catch(u){this.setTimeoutFn(()=>{this._onError(u)},0);return}typeof document<"u"&&(this._index=Wte.requestsCount++,Wte.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=lCn,n)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Wte.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(Wte,"Request");var lP=Wte;lP.requestsCount=0;lP.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vor);else if(typeof addEventListener=="function"){let i="onpagehide"in Kb?"pagehide":"unload";addEventListener(i,vor,!1)}}function vor(){for(let i in lP.requests)lP.requests.hasOwnProperty(i)&&lP.requests[i].abort()}t(vor,"unloadHandler");var Qoi=function(){let i=uCn({xdomain:!1});return i&&i.responseType!==null}();function uCn(i){let n=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!n||Aor))return new XMLHttpRequest}catch{}if(!n)try{return new Kb[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}t(uCn,"newRequest");var fCn=Hdt.default||Hdt,Gdt=class Gdt extends Zke{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 lP(c=>new fCn(c),this.uri(),n)}};t(Gdt,"XHR");var qte=Gdt;var b4n=Da(wor(),1),E4n=Da(l_t(),1),x4n=Da(f_t(),1),S_t=Da(E_t(),1),C4n=Da(xcr(),1);var Ccr=Da(wz(),1);var w4n=(0,Ccr.default)("engine.io-client:websocket"),I4n=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",w_t=class w_t extends cP{get name(){return"websocket"}doOpen(){let n=this.uri(),s=this.opts.protocols,c=I4n?{}:zke(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;$me(c,this.supportsBinary,_=>{try{this.doWrite(c,_)}catch{w4n("websocket closed before onclose event")}u&&aP(()=>{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]=$ke()),this.supportsBinary||(s.b64=1),this.createUri(n,s)}};t(w_t,"BaseWS");var f5e=w_t,Sci=Kb.WebSocket||Kb.MozWebSocket;var I_t=class I_t extends f5e{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[_,h]of this.socket._cookieJar.cookies)c.headers.cookie.push(`${_}=${h.value}`)}return new S_t.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(I_t,"WS");var Kte=I_t;var Scr=Da(wz(),1);var ihe=(0,Scr.default)("engine.io-client:webtransport"),T_t=class T_t extends cP{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(()=>{ihe("transport closed gracefully"),this.onClose()}).catch(n=>{ihe("transport closed due to %s",n),this.onError("webtransport error",n)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(n=>{let s=Kar(Number.MAX_SAFE_INTEGER,this.socket.binaryType),c=n.readable.pipeThrough(s).getReader(),u=Zar();u.readable.pipeTo(n.writable),this._writer=u.writable.getWriter();let _=t(()=>{c.read().then(({done:b,value:S})=>{if(b){ihe("session is closed");return}ihe("received chunk: %o",S),this.onPacket(S),_()}).catch(b=>{ihe("an error occurred while reading: %s",b)})},"read");_();let h={type:"open"};this.query.sid&&(h.data=`{"sid":"${this.query.sid}"}`),this._writer.write(h).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&&aP(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var n;(n=this._transport)===null||n===void 0||n.close()}};t(T_t,"WT");var Xte=T_t;var k_t={websocket:Kte,webtransport:Xte,polling:qte};var T4n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,k4n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ere(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=T4n.exec(i||""),_={},h=14;for(;h--;)_[k4n[h]]=u[h]||"";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=D4n(_,_.path),_.queryKey=N4n(_,_.query),_}t(ere,"parse");function D4n(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(D4n,"pathNames");function N4n(i,n){let s={};return n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(c,u,_){u&&(s[u]=_)}),s}t(N4n,"queryKey");var wcr=Da(Cz(),1);var Icr=Da(wz(),1);var W_=(0,Icr.default)("engine.io-client:socket"),D_t=typeof addEventListener=="function"&&typeof removeEventListener=="function",she=[];D_t&&addEventListener("offline",()=>{W_("closing %d connection(s) because the network was lost",she.length),she.forEach(i=>i())},!1);var tre=class tre extends wcr.Emitter{constructor(n,s){if(super(),this.binaryType=eor,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=ere(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=ere(s.host).host);oP(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=ior(this.opts.query)),D_t&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(W_("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},she.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=tor()),this._open()}createTransport(n){W_('creating transport "%s"',n);let s=Object.assign({},this.opts.query);s.EIO=Bdt,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 W_("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&&tre.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){W_("setting transport %s",n.name),this.transport&&(W_("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(){W_("socket open"),this.readyState="open",tre.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(W_('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 W_('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();W_("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+=ror(u)),c>0&&s>this._maxPayload)return W_("only send %d out of %d packets",c,this.writeBuffer.length),this.writeBuffer.slice(0,c);s+=2}return W_("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&&(W_("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,aP(()=>{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"),W_("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(W_("socket error %j",n),tre.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return W_("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(W_('socket close with reason: "%s"',n),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),D_t&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let c=she.indexOf(this._offlineEventListener);c!==-1&&(W_("removing listener for the 'offline' event"),she.splice(c,1))}this.readyState="closed",this.id=null,this.emitReserved("close",n,s),this.writeBuffer=[],this._prevBufferLen=0}}};t(tre,"SocketWithoutUpgrade");var Nz=tre;Nz.protocol=Bdt;var N_t=class N_t extends Nz{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){W_("starting upgrade probes");for(let n=0;n<this._upgrades.length;n++)this._probe(this._upgrades[n])}}_probe(n){W_('probing transport "%s"',n);let s=this.createTransport(n),c=!1;Nz.priorWebsocketSuccess=!1;let u=t(()=>{c||(W_('probe transport "%s" opened',n),s.send([{type:"ping",data:"probe"}]),s.once("packet",G=>{if(!c)if(G.type==="pong"&&G.data==="probe"){if(W_('probe transport "%s" pong',n),this.upgrading=!0,this.emitReserved("upgrading",s),!s)return;Nz.priorWebsocketSuccess=s.name==="websocket",W_('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{c||this.readyState!=="closed"&&(W_("changing transport and sending upgrade packet"),B(),this.setTransport(s),s.send([{type:"upgrade"}]),this.emitReserved("upgrade",s),s=null,this.upgrading=!1,this.flush())})}else{W_('probe transport "%s" failed',n);let j=new Error("probe error");j.transport=s.name,this.emitReserved("upgradeError",j)}}))},"onTransportOpen");function _(){c||(c=!0,B(),s.close(),s=null)}t(_,"freezeTransport");let h=t(G=>{let j=new Error("probe error: "+G);j.transport=s.name,_(),W_('probe transport "%s" failed because of error: %s',n,G),this.emitReserved("upgradeError",j)},"onerror");function b(){h("transport closed")}t(b,"onTransportClose");function S(){h("socket closed")}t(S,"onclose");function k(G){s&&G.name!==s.name&&(W_('"%s" works - aborting "%s"',G.name,s.name),_())}t(k,"onupgrade");let B=t(()=>{s.removeListener("open",u),s.removeListener("error",h),s.removeListener("close",b),this.off("close",S),this.off("upgrading",k)},"cleanup");s.once("open",u),s.once("error",h),s.once("close",b),this.once("close",S),this.once("upgrading",k),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(N_t,"SocketWithUpgrade");var p5e=N_t,P_t=class P_t extends p5e{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=>k_t[u]).filter(u=>!!u)),super(n,c)}};t(P_t,"Socket");var rre=P_t;var eli=rre.protocol;var Fcr=Da(nre(),1);var Pcr=(0,Fcr.default)("socket.io-client:url");function Bcr(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)||(Pcr("protocol-less url %s",i),typeof s<"u"?i=s.protocol+"//"+i:i="https://"+i),Pcr("parse %s",i),c=ere(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(Bcr,"url");var j_t={};Ck(j_t,{Decoder:()=>Q_t,Encoder:()=>L_t,PacketType:()=>ju,isPacketValid:()=>nSn,protocol:()=>jcr});var Lcr=Da(Cz(),1);var Y4n=typeof ArrayBuffer=="function",Z4n=t(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),Rcr=Object.prototype.toString,K4n=typeof Blob=="function"||typeof Blob<"u"&&Rcr.call(Blob)==="[object BlobConstructor]",X4n=typeof File=="function"||typeof File<"u"&&Rcr.call(File)==="[object FileConstructor]";function ohe(i){return Y4n&&(i instanceof ArrayBuffer||Z4n(i))||K4n&&i instanceof Blob||X4n&&i instanceof File}t(ohe,"isBinary");function ahe(i,n){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let s=0,c=i.length;s<c;s++)if(ahe(i[s]))return!0;return!1}if(ohe(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return ahe(i.toJSON(),!0);for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s)&&ahe(i[s]))return!0;return!1}t(ahe,"hasBinary");function Ocr(i){let n=[],s=i.data,c=i;return c.data=R_t(s,n),c.attachments=n.length,{packet:c,buffers:n}}t(Ocr,"deconstructPacket");function R_t(i,n){if(!i)return i;if(ohe(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]=R_t(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]=R_t(i[c],n));return s}return i}t(R_t,"_deconstructPacket");function Mcr(i,n){return i.data=O_t(i.data,n),delete i.attachments,i}t(Mcr,"reconstructPacket");function O_t(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]=O_t(i[s],n);else if(typeof i=="object")for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&(i[s]=O_t(i[s],n));return i}t(O_t,"_reconstructPacket");var Qcr=Da(nre(),1);var M_t=(0,Qcr.default)("socket.io-parser"),Ucr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],jcr=5,ju;(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"})(ju||(ju={}));var J_t=class J_t{constructor(n){this.replacer=n}encode(n){return M_t("encoding packet %j",n),(n.type===ju.EVENT||n.type===ju.ACK)&&ahe(n)?this.encodeAsBinary({type:n.type===ju.EVENT?ju.BINARY_EVENT:ju.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id}):[this.encodeAsString(n)]}encodeAsString(n){let s=""+n.type;return(n.type===ju.BINARY_EVENT||n.type===ju.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)),M_t("encoded %j as %s",n,s),s}encodeAsBinary(n){let s=Ocr(n),c=this.encodeAsString(s.packet),u=s.buffers;return u.unshift(c),u}};t(J_t,"Encoder");var L_t=J_t,g5e=class g5e extends Lcr.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===ju.BINARY_EVENT;c||s.type===ju.BINARY_ACK?(s.type=c?ju.EVENT:ju.ACK,this.reconstructor=new U_t(s),s.attachments===0&&super.emitReserved("decoded",s)):super.emitReserved("decoded",s)}else if(ohe(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(ju[c.type]===void 0)throw new Error("unknown packet type "+c.type);if(c.type===ju.BINARY_EVENT||c.type===ju.BINARY_ACK){let _=s+1;for(;n.charAt(++s)!=="-"&&s!=n.length;);let h=n.substring(_,s);if(h!=Number(h)||n.charAt(s)!=="-")throw new Error("Illegal attachments");let b=Number(h);if(!Jcr(b)||b<0)throw new Error("Illegal attachments");if(b>this.opts.maxAttachments)throw new Error("too many attachments");c.attachments=b}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 h=n.charAt(s);if(h==null||Number(h)!=h){--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(g5e.isPayloadValid(c.type,_))c.data=_;else throw new Error("invalid payload")}return M_t("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 ju.CONNECT:return h5e(s);case ju.DISCONNECT:return s===void 0;case ju.CONNECT_ERROR:return typeof s=="string"||h5e(s);case ju.EVENT:case ju.BINARY_EVENT:return Array.isArray(s)&&(typeof s[0]=="number"||typeof s[0]=="string"&&Ucr.indexOf(s[0])===-1);case ju.ACK:case ju.BINARY_ACK:return Array.isArray(s)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};t(g5e,"Decoder");var Q_t=g5e,V_t=class V_t{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=Mcr(this.reconPack,this.buffers);return this.finishedReconstruction(),s}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};t(V_t,"BinaryReconstructor");var U_t=V_t;function eSn(i){return typeof i=="string"}t(eSn,"isNamespaceValid");var Jcr=Number.isInteger||function(i){return typeof i=="number"&&isFinite(i)&&Math.floor(i)===i};function tSn(i){return i===void 0||Jcr(i)}t(tSn,"isAckIdValid");function h5e(i){return Object.prototype.toString.call(i)==="[object Object]"}t(h5e,"isObject");function rSn(i,n){switch(i){case ju.CONNECT:return n===void 0||h5e(n);case ju.DISCONNECT:return n===void 0;case ju.EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Ucr.indexOf(n[0])===-1);case ju.ACK:return Array.isArray(n);case ju.CONNECT_ERROR:return typeof n=="string"||h5e(n);default:return!1}}t(rSn,"isDataValid");function nSn(i){return eSn(i.nsp)&&tSn(i.id)&&rSn(i.type,i.data)}t(nSn,"isPacketValid");function IC(i,n,s){return i.on(n,s),t(function(){i.off(n,s)},"subDestroy")}t(IC,"on");var Vcr=Da(Cz(),1),zcr=Da(nre(),1);var t1=(0,zcr.default)("socket.io-client:socket"),iSn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),z_t=class z_t extends Vcr.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=[IC(n,"open",this.onopen.bind(this)),IC(n,"packet",this.onpacket.bind(this)),IC(n,"error",this.onerror.bind(this)),IC(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(iSn.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 h={type:ju.EVENT,data:s};if(h.options={},h.options.compress=this.flags.compress!==!1,typeof s[s.length-1]=="function"){let B=this.ids++;t1("emitting packet with ack id %d",B);let G=s.pop();this._registerAckCallback(B,G),h.id=B}let b=(u=(c=this.io.engine)===null||c===void 0?void 0:c.transport)===null||u===void 0?void 0:u.writable,S=this.connected&&!(!((_=this.io.engine)===null||_===void 0)&&_._hasPingExpired());return this.flags.volatile&&!b?t1("discard packet as the transport is not currently writable"):S?(this.notifyOutgoingListeners(h),this.packet(h)):this.sendBuffer.push(h),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 b=0;b<this.sendBuffer.length;b++)this.sendBuffer[b].id===n&&(t1("removing packet with ack id %d from the buffer",n),this.sendBuffer.splice(b,1));t1("event with ack id %d has timed out after %d ms",n,u),s.call(this,new Error("operation has timed out"))},u),h=t((...b)=>{this.io.clearTimeoutFn(_),s.apply(this,b)},"fn");h.withError=!0,this.acks[n]=h}emitWithAck(n,...s){return new Promise((c,u)=>{let _=t((h,b)=>h?u(h):c(b),"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]?t1("packet [%d] already acknowledged",c.id):(u!==null?c.tryCount>this._opts.retries&&(t1("packet [%d] is discarded after %d tries",c.id,c.tryCount),this._queue.shift(),s&&s(u)):(t1("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(t1("draining queue"),!this.connected||this._queue.length===0)return;let s=this._queue[0];if(s.pending&&!n){t1("packet [%d] has already been sent and is waiting for an ack",s.id);return}s.pending=!0,s.tryCount++,t1("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(){t1("transport is open - connecting"),typeof this.auth=="function"?this.auth(n=>{this._sendConnectPacket(n)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(n){this.packet({type:ju.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){t1("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 ju.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 ju.EVENT:case ju.BINARY_EVENT:this.onevent(n);break;case ju.ACK:case ju.BINARY_ACK:this.onack(n);break;case ju.DISCONNECT:this.ondisconnect();break;case ju.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||[];t1("emitting event %j",s),n.id!=null&&(t1("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,t1("sending ack %j",u),s.packet({type:ju.ACK,id:n,data:u}))}}onack(n){let s=this.acks[n.id];if(typeof s!="function"){t1("bad ack %s",n.id);return}delete this.acks[n.id],t1("calling ack %s with %j",n.id,n.data),s.withError&&n.data.unshift(null),s.apply(this,n.data)}onconnect(n,s){t1("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(){t1("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&&(t1("performing disconnect (%s)",this.nsp),this.packet({type:ju.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(z_t,"Socket");var ire=z_t;function Pz(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(Pz,"Backoff");Pz.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};Pz.prototype.reset=function(){this.attempts=0};Pz.prototype.setMin=function(i){this.ms=i};Pz.prototype.setMax=function(i){this.max=i};Pz.prototype.setJitter=function(i){this.jitter=i};var $cr=Da(Cz(),1),Wcr=Da(nre(),1);var o2=(0,Wcr.default)("socket.io-client:manager"),$_t=class $_t extends $cr.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,oP(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 Pz({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||j_t;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(o2("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;o2("opening %s",this.uri),this.engine=new rre(this.uri,this.opts);let s=this.engine,c=this;this._readyState="opening",this.skipReconnect=!1;let u=IC(s,"open",function(){c.onopen(),n&&n()}),_=t(b=>{o2("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",b),n?n(b):this.maybeReconnectOnOpen()},"onError"),h=IC(s,"error",_);if(this._timeout!==!1){let b=this._timeout;o2("connect attempt will timeout after %d",b);let S=this.setTimeoutFn(()=>{o2("connect attempt timed out after %d",b),u(),_(new Error("timeout")),s.close()},b);this.opts.autoUnref&&S.unref(),this.subs.push(()=>{this.clearTimeoutFn(S)})}return this.subs.push(u),this.subs.push(h),this}connect(n){return this.open(n)}onopen(){o2("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let n=this.engine;this.subs.push(IC(n,"ping",this.onping.bind(this)),IC(n,"data",this.ondata.bind(this)),IC(n,"error",this.onerror.bind(this)),IC(n,"close",this.onclose.bind(this)),IC(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){aP(()=>{this.emitReserved("packet",n)},this.setTimeoutFn)}onerror(n){o2("error",n),this.emitReserved("error",n)}socket(n,s){let c=this.nsps[n];return c?this._autoConnect&&!c.active&&c.connect():(c=new ire(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){o2("socket %s is still active, skipping close",c);return}this._close()}_packet(n){o2("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(){o2("cleanup"),this.subs.forEach(n=>n()),this.subs.length=0,this.decoder.destroy()}_close(){o2("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(n,s){var c;o2("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)o2("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let s=this.backoff.duration();o2("will wait %dms before reconnect attempt",s),this._reconnecting=!0;let c=this.setTimeoutFn(()=>{n.skipReconnect||(o2("attempting reconnect"),this.emitReserved("reconnect_attempt",n.backoff.attempts),!n.skipReconnect&&n.open(u=>{u?(o2("reconnect attempt error"),n._reconnecting=!1,n.reconnect(),this.emitReserved("reconnect_error",u)):(o2("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($_t,"Manager");var sre=$_t;var Hcr=Da(nre(),1);var qcr=(0,Hcr.default)("socket.io-client"),che={};function lhe(i,n){typeof i=="object"&&(n=i,i=void 0),n=n||{};let s=Bcr(i,n.path||"/socket.io"),c=s.source,u=s.id,_=s.path,h=che[u]&&_ in che[u].nsps,b=n.forceNew||n["force new connection"]||n.multiplex===!1||h,S;return b?(qcr("ignoring socket cache for %s",c),S=new sre(c,n)):(che[u]||(qcr("new io instance for %s",c),che[u]=new sre(c,n)),S=che[u]),s.query&&!n.query&&(n.query=s.queryKey),S.socket(s.path,n)}t(lhe,"lookup");Object.assign(lhe,{Manager:sre,Socket:ire,io:lhe,connect:lhe});var y5e={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},W_t=class W_t{constructor(n={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=n,this.url=n.url||y5e.URL,this.namespace=n.namespace||y5e.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((_,h)=>{setTimeout(()=>{h(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=lhe(u,{autoConnect:!0,reconnection:!0,reconnectionAttempts:y5e.RECONNECTION_ATTEMPTS,reconnectionDelay:y5e.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 h=`No handler registered for method: ${n.key}`;this.logError(`\u274C ${h}`),s(this.error(h));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(W_t,"AbstractClient");var A5e=W_t;var Gcr,Ycr,Zcr,Kcr,Xcr,elr,tlr,rlr,b5e=class b5e extends(rlr=A5e,tlr=Gh.names.getState,elr=Gh.names.invokeCode,Xcr=Gh.names.final_result,Kcr=Gh.names.wait,Zcr=Gh.names.getElementScreenshot,Ycr=Gh.names.listPages,Gcr=Gh.names.switchPage,rlr){constructor(s,c){super({verbose:gc.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[tlr]=Q5.buildTool(Gh,Gh.names.getState,async s=>this.getStateHandler(s));this[elr]=Q5.buildTool(Gh,Gh.names.invokeCode,async s=>this.invokeCodeHandler(s));this[Xcr]=Q5.buildTool(Gh,Gh.names.final_result,async s=>this.finalResultHandler(s));this[Kcr]=Q5.buildTool(Gh,Gh.names.wait,async s=>this.waitHandler(s));this[Zcr]=Q5.buildTool(Gh,Gh.names.getElementScreenshot,async s=>this.getElementScreenshotHandler(s));this[Ycr]=Q5.buildTool(Gh,Gh.names.listPages,async s=>this.listPagesHandler(s));this[Gcr]=Q5.buildTool(Gh,Gh.names.switchPage,async s=>this.switchPageHandler(s))}async init(){let s={...this.initData,version:Gh.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 b5e(s,c)}async invokeCodeHandler(s){let c,u=this.utils.activePageGuid,h=!!(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{h&&await this.utils.setActivePage(s.pageId);let b=await this.utils.invokeCode(s.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),c={success:!0,invokeCodeResult:`invokeCodeResult: ${b.result}`,appState:(await this.utils.buildFallbackData()).applicationState,actionEffects:b.effects}}catch(b){c={success:!1,invokeCodeResult:`Error while invoking code: ${b}`,appState:(await this.utils.buildFallbackData()).applicationState}}finally{if(h&&u)try{await this.utils.setActivePage(u)}catch(b){console.warn("Failed to switch back to original page:",b)}}}),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(h){console.warn("Failed to record auto-recovery final-result analytics:",h)}try{this.utils.addAutoRecoveryErrorToReport(s.thought,c)}catch(h){console.warn("Failed to add auto-recovery result to report:",h)}}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((h,b)=>`${b+1}. ${h.title||"Untitled"} (${h.url})
|
|
736
736
|
- Page ID: ${h.id}
|
|
737
737
|
- Active: ${h.active?"Yes":"No"}
|
|
738
738
|
- New: ${h.new?"Yes":"No"}${h.lastAction?`
|
|
@@ -740,10 +740,10 @@ Result: ${JSON.stringify(B)}`);else G=B;let ie=D6n({content:G,artifact:j,toolCal
|
|
|
740
740
|
|
|
741
741
|
`),_=`Available pages (${c.length}):
|
|
742
742
|
|
|
743
|
-
${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(b5e,"AutoRecoveryAgent");var v5e=b5e;var ilr=require("fs"),slr=Da(require("path"));var q_t=class q_t{constructor(n,s){this.sessionId=null;if(!Uk.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let u=Uk.getCurrentInstance();if(!u)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let _=u.getTestSuiteRunInfo();this.analytics=JS.createFromConfig(_,Uk.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(q_t,"RecoveryAnalytics");var E5e=q_t;var sSn=500,aSn=3,oSn=5,nlr=300;function H_t(i){return i._guid}t(H_t,"getPageGuid");var Fz=class Fz{constructor({page:n,evaluateWithChecksum:s,checksumPage:c,pageInteractor:u,arConfig:_,sessionId:h,runtimeFallbackData:b,fallbackData:S,variableStore:k,runtimePage:B,context:G}){this.reducedHtmlTimeoutMs=3e4;this.page=n,this._originalPage=n,this.evaluateWithChecksum=s,this.checksumPage=c,this._pageInteractor=u,this.arConfig=_,this.sessionId=h,this.runtimeFallbackData=b,this.fallbackData=S,this.variableStore=k,this.runtimePage=B,this.context=G,this._activePageGuid=H_t(this.page),this._analytics=new E5e(this.sessionId,S.type)}get activePageGuid(){return this._activePageGuid}static async start(n){return new Fz({...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=>H_t(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((b,S=!0)=>{if(!b)return"";try{return(0,ilr.readFileSync)(b,S?"base64":"utf-8")}catch{return""}},"readFileSafe"),u=c(s==null?void 0:s.actual),_=c(s==null?void 0:s.diff),h=c(s==null?void 0:s.expected);if(!h)throw new Error("No expected file found for 'toHaveScreenshot'");return{...s,actual:u,diff:_,expected:h}}async getSelectionDataForChecksumId(n){return await this.evaluateOnCurrentPage(async c=>{let{selector:u,locator:_,clickOffset:h,parentFramesSelectors:b,invalid:S,rrwebId:k}=await window.checksum.testGenerator.getSelectorForChecksumId(c),B=await window.checksum.testGenerator.getElementForChecksumId(c),G=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:u,locator:_,clickOffset:h,selectOptionValue:G,parentFramesSelectors:b,invalid:S,rrwebId:k}},n)}async getReducedHtml(n=Fz.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 Fz.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(),h=await this.getPageScreenshot();return{pageId:s,reducedHTML:_,screenshot:h,url:n.url()}}finally{this.page=c,this._activePageGuid=u}}async captureAllPagesState(){let s=(this.context||this.page.context()).pages(),c=[],u=[];for(let h of s){if(h.isClosed())continue;let b=H_t(h);try{let S=await this.capturePageState(h,b);c.push(S)}catch(S){let k=S instanceof Error?S.message:String(S);u.push({pageId:b,url:h.url(),error:k}),console.warn(`Failed to capture state for page ${b} (${h.url()}):`,S)}}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(h=>!h.isClosed()).length,c=new Promise((h,b)=>setTimeout(()=>b(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((h,b)=>(h[`variablesStore.${b.name}`]=b.value,h),{}),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=slr.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return nK.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 ie;let s=n,c=n,u=[],_=n.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),h=_==null?void 0:_[1],b=_==null?void 0:_[2],S=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,k=(ie=n.match(S))==null?void 0:ie[1];if(!k)throw new Error("Checksum ID not found in the code");let B=await this.getSelectionDataForChecksumId(k);if(!(B!=null&&B.locator)||B.invalid)throw new Error(`Locator or selector not found for checksumId: ${k}`);c=c.replace(S,B.locator);let G=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,j=null;for(;(j=G.exec(n))!==null;){let ae=j[1],he=this.variableStore.find(ft=>ft.name===ae);he&&(u.push(he),c=c.replace(j[0],`"${he.value}"`))}return{originalCode:s,modifiedCode:c,usedVariables:u,checksumId:k,locator:B.locator,method:h,methodArgs:b}}async invokeCode(n){let s=this.page,c=s.url(),u=[],_=[],h,b=t(B=>{try{let G=B.request(),j=G.resourceType();(j==="xhr"||j==="fetch")&&B.status()>=400&&u.push({status:B.status(),method:G.method(),url:B.url()})}catch{}},"onResponse"),S=t(B=>_.push((B==null?void 0:B.message)??String(B)),"onPageError"),k=t(B=>{h||(h=B)},"onPopup");s.on("response",b),s.on("pageerror",S),s.on("popup",k);try{let B=await this.preprocessCode(n),{modifiedCode:G}=B,j=new Function("page",`return (async () => { return page.${G}; })()`),ie;return await this.step(G,async()=>ie=await j(this.page),!1,{box:!0,noLocation:!0,obtainStep:t(ae=>{ae!=null&&ae.stepId&&this.checksumPage.addAutoRecoveryStepId(ae.stepId)},"obtainStep")}),await s.waitForTimeout(sSn).catch(()=>{}),{success:!0,result:ie,effects:this.buildActionEffects(c,h,_,u)}}catch(B){throw console.log("Error while invoking code",B.message),B}finally{s.off("response",b),s.off("pageerror",S),s.off("popup",k)}}buildActionEffects(n,s,c,u){let _=t(S=>S.length>nlr?`${S.slice(0,nlr)}\u2026`:S,"clip"),h={},b=n;try{b=this.page.url()}catch{}if(b&&b!==n&&(h.navigation={from:n,to:_(b)}),s){let S="about:blank";try{s.isClosed()||(S=s.url())}catch{}h.openedNewPage={url:_(S)}}if(c.length&&(h.pageErrors=[...new Set(c)].slice(0,aSn).map(_)),u.length){let S=new Set;h.networkErrors=u.filter(k=>{let B=`${k.status} ${k.method} ${k.url}`;return S.has(B)?!1:(S.add(B),!0)}).slice(0,oSn).map(k=>({...k,url:_(k.url)}))}return Object.keys(h).length>0?h: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}:
|
|
743
|
+
${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(b5e,"AutoRecoveryAgent");var v5e=b5e;var ilr=require("fs"),slr=Da(require("path"));var q_t=class q_t{constructor(n,s){this.sessionId=null;if(!Uk.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let u=Uk.getCurrentInstance();if(!u)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let _=u.getTestSuiteRunInfo();this.analytics=JS.createFromConfig(_,Uk.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(q_t,"RecoveryAnalytics");var E5e=q_t;var sSn=500,aSn=3,oSn=5,nlr=300;function H_t(i){return i._guid}t(H_t,"getPageGuid");var Fz=class Fz{constructor({page:n,evaluateWithChecksum:s,checksumPage:c,pageInteractor:u,arConfig:_,sessionId:h,runtimeFallbackData:b,fallbackData:S,variableStore:k,runtimePage:B,context:G}){this.reducedHtmlTimeoutMs=3e4;this.page=n,this._originalPage=n,this.evaluateWithChecksum=s,this.checksumPage=c,this._pageInteractor=u,this.arConfig=_,this.sessionId=h,this.runtimeFallbackData=b,this.fallbackData=S,this.variableStore=k,this.runtimePage=B,this.context=G,this._activePageGuid=H_t(this.page),this._analytics=new E5e(this.sessionId,S.type)}get activePageGuid(){return this._activePageGuid}get isSuggestOnly(){return this.arConfig.markRecovered===!1}static async start(n){return new Fz({...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=>H_t(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((b,S=!0)=>{if(!b)return"";try{return(0,ilr.readFileSync)(b,S?"base64":"utf-8")}catch{return""}},"readFileSafe"),u=c(s==null?void 0:s.actual),_=c(s==null?void 0:s.diff),h=c(s==null?void 0:s.expected);if(!h)throw new Error("No expected file found for 'toHaveScreenshot'");return{...s,actual:u,diff:_,expected:h}}async getSelectionDataForChecksumId(n){return await this.evaluateOnCurrentPage(async c=>{let{selector:u,locator:_,clickOffset:h,parentFramesSelectors:b,invalid:S,rrwebId:k}=await window.checksum.testGenerator.getSelectorForChecksumId(c),B=await window.checksum.testGenerator.getElementForChecksumId(c),G=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:u,locator:_,clickOffset:h,selectOptionValue:G,parentFramesSelectors:b,invalid:S,rrwebId:k}},n)}async getReducedHtml(n=Fz.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 Fz.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(),h=await this.getPageScreenshot();return{pageId:s,reducedHTML:_,screenshot:h,url:n.url()}}finally{this.page=c,this._activePageGuid=u}}async captureAllPagesState(){let s=(this.context||this.page.context()).pages(),c=[],u=[];for(let h of s){if(h.isClosed())continue;let b=H_t(h);try{let S=await this.capturePageState(h,b);c.push(S)}catch(S){let k=S instanceof Error?S.message:String(S);u.push({pageId:b,url:h.url(),error:k}),console.warn(`Failed to capture state for page ${b} (${h.url()}):`,S)}}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(h=>!h.isClosed()).length,c=new Promise((h,b)=>setTimeout(()=>b(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((h,b)=>(h[`variablesStore.${b.name}`]=b.value,h),{}),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=slr.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return nK.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 ie;let s=n,c=n,u=[],_=n.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),h=_==null?void 0:_[1],b=_==null?void 0:_[2],S=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,k=(ie=n.match(S))==null?void 0:ie[1];if(!k)throw new Error("Checksum ID not found in the code");let B=await this.getSelectionDataForChecksumId(k);if(!(B!=null&&B.locator)||B.invalid)throw new Error(`Locator or selector not found for checksumId: ${k}`);c=c.replace(S,B.locator);let G=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,j=null;for(;(j=G.exec(n))!==null;){let ae=j[1],he=this.variableStore.find(ft=>ft.name===ae);he&&(u.push(he),c=c.replace(j[0],`"${he.value}"`))}return{originalCode:s,modifiedCode:c,usedVariables:u,checksumId:k,locator:B.locator,method:h,methodArgs:b}}async invokeCode(n){let s=this.page,c=s.url(),u=[],_=[],h,b=t(B=>{try{let G=B.request(),j=G.resourceType();(j==="xhr"||j==="fetch")&&B.status()>=400&&u.push({status:B.status(),method:G.method(),url:B.url()})}catch{}},"onResponse"),S=t(B=>_.push((B==null?void 0:B.message)??String(B)),"onPageError"),k=t(B=>{h||(h=B)},"onPopup");s.on("response",b),s.on("pageerror",S),s.on("popup",k);try{let B=await this.preprocessCode(n),{modifiedCode:G}=B,j=new Function("page",`return (async () => { return page.${G}; })()`),ie;return await this.step(G,async()=>ie=await j(this.page),!1,{box:!0,noLocation:!0,obtainStep:t(ae=>{ae!=null&&ae.stepId&&this.checksumPage.addAutoRecoveryStepId(ae.stepId)},"obtainStep")}),await s.waitForTimeout(sSn).catch(()=>{}),{success:!0,result:ie,effects:this.buildActionEffects(c,h,_,u)}}catch(B){throw console.log("Error while invoking code",B.message),B}finally{s.off("response",b),s.off("pageerror",S),s.off("popup",k)}}buildActionEffects(n,s,c,u){let _=t(S=>S.length>nlr?`${S.slice(0,nlr)}\u2026`:S,"clip"),h={},b=n;try{b=this.page.url()}catch{}if(b&&b!==n&&(h.navigation={from:n,to:_(b)}),s){let S="about:blank";try{s.isClosed()||(S=s.url())}catch{}h.openedNewPage={url:_(S)}}if(c.length&&(h.pageErrors=[...new Set(c)].slice(0,aSn).map(_)),u.length){let S=new Set;h.networkErrors=u.filter(k=>{let B=`${k.status} ${k.method} ${k.url}`;return S.has(B)?!1:(S.add(B),!0)}).slice(0,oSn).map(k=>({...k,url:_(k.url)}))}return Object.keys(h).length>0?h: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}:
|
|
744
744
|
${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(Fz,"AutoRecoveryRuntimeIteratorUtils"),Fz.currentChecksumId="0";var x5e=Fz;var _P=class _P extends Jk{constructor(n,s,c,u,_,h,b){super(n,s,c,u,_,h,b),this.runtimePageContext=h}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}${_P.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 _P.registerSession(this.initializationData);this.utils=new x5e({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 v5e.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((_,h)=>{s=setTimeout(()=>{s=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${_P.TIMEOUT_MS/1e3} seconds`});let b="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:b,withError:!0}),this.utils.addAutoRecoveryErrorToReport(b,!1),h(new Error(b))},_P.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(_P,"ARFallback"),_P.API_BASE_ROUTE="/auto-recovery",_P.TIMEOUT_MS=12e4;var mP=_P;var alr=t(i=>{let n=i.info();return n.annotations.some(s=>s.type==="bug")||n.tags.some(s=>s==="@bug")},"isKnownBugTest");var G_t=1e3*30;var wM=class wM extends n8e{constructor(s,c="normal",u,_,h,b,S,k,B,G,j,ie,ae){var ct,At,gt;super(s,u,j,()=>this.pageInteractor,void 0);this.page=s;this.runMode=c;this.testRunAnalytics=_;this.monitorBridge=h;this.testInfo=b;this.checksumTestId=S;this.test=k;this.options=B;this.isReplMode=G;this.config=j;this.pageInteractorAPI=ie;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 gCe;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:h,showTMSeeker:b,filesObserver:S,nativeDialogObserver:k,assertionsObserver:B,actionsObserver:G,recordOptions:j})=>{var ie;(ie=window.checksum)==null||ie.testGenerator.init(c,{esraTimeout:u,showFrontendLogs:h,skipElementHighlighting:!0,recordOptions:j},{assertionGenerator:!1,sessionRecorder:_,filesObserver:S,nativeDialogObserver:k,assertionsObserver:B,actionsObserver:G});try{b&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:G_t,sessionRecorder:!this.isTimeMachineFrame(s)&&!!this.timeMachine,showFrontendLogs:gc.isDevMode,showTMSeeker:this.isTimeMachineFrame(s)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1,recordOptions:void 0}),Dc(`[init] init script loaded for ${s.page().url()}`)},"scriptLoadCallback");C5e(B.printLogs),alr(k)&&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 he=ulr({config:this.config,throwIfAuthFailed:!0}),ft=this.getPlaywrightProjectConfig();if(this.pageInteractor=new sfe(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Dc,logError:Dc},{navigationTimeout:(ct=ft.use)==null?void 0:ct.navigationTimeout,actionTimeout:(At=ft.use)==null?void 0:At.actionTimeout,testAssetsDir:rfe(SS()),waitActionDelay:1e3},this.pageInteractorAPI,he),this.checkForActiveTracing(),this.resetFallbacks(),ae&&(this.highLevelThoughts=ae.highLevelThoughts??[],this.timeMachineBrowserContext=ae.timeMachineBrowserContext,this.variableStore=ae.variableStore),gc.testRun.timeMachine.active){let zt=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:TNt(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new YTe(this.framesMsgBroker,this.injectedScriptManager,{...zt,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:gc.testRun.timeMachine.headless,webProxy:(gt=b.project.use)==null?void 0:gt.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(s,c,u,_,h,b,S,k,B,G=!1){let j=!1;S||(S=vNt(5),j=!0,console.warn(`Checksum test id was not defined for test "${b.title}" and was auto-generated. Please replace - "${b.title}" with -
|
|
745
745
|
test(defineChecksumTest("${b.title}", "${S}"), async ({ page }) => {...`)),_.addTestInfo(S,b.testId,j),B.options.useChecksumAI!==void 0&&typeof B.options.useChecksumAI=="boolean"&&(B.options.useChecksumAI={actions:B.options.useChecksumAI,assertions:!1,visualComparison:!1});let ie=new u4e(B),ae=new wM(s,B.runMode,c,u,_,b,S,k,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:B.runMode!=="normal",useMockData:!1,printLogs:!1,...B.options},G,B,ie,{variableStore:h});return c.pages().length===0&&(k._checksum.expect.setPage(ae),k._checksum.checksumAI.page=ae,h.clearAll(),ae.testRunAnalytics.testRunStart()),await ae.asyncInit(),ae.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 wM(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 gc.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let s=this.getPageGuid(this.page);wM.recentlyInteracted.set(s,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(s){let c=s.pages(),u=c[0],_=0;for(let h of c){let b=h._guid,S=wM.recentlyInteracted.get(b)||0;S>_&&(_=S,u=h)}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 h=this.getPageGuid(this.page);return sfe.setLastAction(h,s),c&&typeof c=="function"?this.test.step(s,async b=>{var S;try{return u!=null&&u.withDialog&&this.pageInteractor.listenToDialog(),await c()}catch(k){if(_.children=[],!this.options.useChecksumAI.actions||u!=null&&u.withDialog||u!=null&&u.skipAutoRecovery)throw k;this.setAIFallback(s,"action");try{return await this.initiateFallbackSequence({type:"action",error:k,method:void 0,args:[],testInfo:this.testInfo,step:b},{fallbackTypes:[hN,mP]})}catch(B){throw this.testRunAnalytics.testRunError({failedThought:s,error:(B==null?void 0:B.message)||"Unknown error"}),B}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(S=this.currentThought)==null?void 0:S.parent}}):(this.options.useChecksumAI.actions&&!(u!=null&&u.skipAutoRecovery)&&this.setAIFallback(s,"action"),this.proxy)}resolveAssetsFolder(s){return s.map(c=>ZT.join(rfe(SS()),c))}getRuntimeOptions(){return this.options}addPwAnnotation(s){this.testInfo.annotations.push({type:s.type,description:`
|
|
746
|
-
${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 h=[_.steps,_._testInfoSteps,_._steps].filter(Boolean);for(let b of h)this.findAllStepsRecursively(b,c,u)}return u}makeChecksumStepFunction(s){return c=>{if(!s)return;let u=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,u).forEach(h=>{h.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:h=!1,noLocation:b=void 0}={}){let S=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=u===!0,b!==void 0&&(this.testInfo._checksumNoLocation=b),await this.test.step(s,c||(()=>{}),{obtainStep:_,box:h})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=S}}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 h=this.currentThought.parent;h?(h.children.push(_),_.parent=h):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:G_t};this.pushFallback(this.constructFallback(wpe).init(c)),this.pushFallback(this.constructFallback(Cpe).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(Spe).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:G_t}))}setAIFallback(s,c){var b;let u=((b=this.options.useChecksumAI)==null?void 0:b.arVersion)===1,_=t(()=>{var ie,ae,he,ft,ct,At;let S=this.buildThoughtsChainForFallback(),k={title:this.testInfo.title},B={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},G={previous:S.slice(0,-1),failing:s,next:S.slice(1)},j={storyInfo:k,testIdentification:B,fallbackConfig:{arMode:(ie=this.options.useChecksumAI)==null?void 0:ie.arMode,overrideOptions:{...(ae=this.options.useChecksumAI)==null?void 0:ae.overrideOptions,...(he=this.options.useChecksumAI)!=null&&he.modelName&&!((ct=(ft=this.options.useChecksumAI)==null?void 0:ft.overrideOptions)!=null&&ct.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},oneShotSuggestOnly:(At=this.options.useChecksumAI)==null?void 0:At.oneShotSuggestOnly},thoughts:G,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(mP).init(j)},"createArFallback"),h=t(()=>{var S,k;return this.constructFallback(hN).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),arMode:(S=this.options.useChecksumAI)==null?void 0:S.arMode,overrideOptions:(k=this.options.useChecksumAI)==null?void 0:k.overrideOptions,fallbackType:c})},"createAIFallback");return u?this.pushFallback(h()):this.pushFallback(_()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,u,_){let h=s.fallbackAnalyticsPayload.iterationSteps,b=h.length>0?_/h.length:0;this.testRunAnalytics.testRunFallbackExecution({result:u.fbResult,failedThought:s.getFailedThought(),summary:u.summary,stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:_,avgDuration:b,success:["finish","soft_assertion"].includes(u.fbResult)}),this.arResults.push({failedThought:s.getFailedThought(),result:u.fbResult,thought:u.thought})}handleAutoRecovery(s,c,u,_){let h=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:h,stepsThoughts:u.stepsThoughts,version:"v1"})}async runFallback(s,c){let u=Date.now(),_=s.resolve(c),h=await Zd(_,s.timeout),b=Date.now()-u;s instanceof hN&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,h,b)),s instanceof mP&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,h,b));let S=h.thought?`: ${h.thought}`:"";if(!h||h.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${S}`,withError:!0}),new Error("Fallback failed");if(h.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${S}`,withError:!0}),new jfe(h.fbResult);if(this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof hN&&h.summary&&this.arSummaries.push(h.summary),s instanceof mP&&h.thought&&this.arSummaries.push(h.thought),this.createChecksumStep({title:`Recovery Complete${S}`}),h.steps.length===1){let k=h.steps[0];k.thought&&(this.currentThought.thought=k.thought)}else this.currentThought.children=h.steps.map((k,B)=>({id:`${this.currentThought.id}.${B+1}`,thought:k.thought,type:k.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}={}){Dc(`[initiateFallbackSequence] with type: ${s.type}...`);let u=this.fallbacks.find(b=>b instanceof hN);if(u){let b=u.getFailedThought(),S=this.variableStore.getActiveVariables();this.fallbacks.forEach(k=>{k.setThought(b),k.setVariables(S)})}let _=this.fallbacks.find(b=>b instanceof mP);if(_){let b=_.failingThought;this.fallbacks.forEach(S=>{S instanceof mP&&S.setVariables(this.variableStore.getActiveVariables()),S.setThought(b)})}let h=this.fallbacks;c&&(h=h.filter(b=>c.reduce((S,k)=>S||b instanceof k,!1))),h=h.filter(b=>b.canResolve(s));try{for(let b of h){let S=b==null?void 0:b.toString();S&&console.log(`Using ${S}`);let k;try{let B=await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,b.getRecoveryAttemptTitle(s),async()=>await this.runFallback(b,s));k=!0}catch(B){if(k=!1,s.withChecksumAI&&B.message==="fetch failed")throw new Error(WK);B instanceof jfe&&B.fallbackResult==="hard_assertion"&&(s.error.fallbackResult="hard_assertion"),S&&console.log(`Failed to use ${S}`),b.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Ipe).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:ZT.basename(s)})}catch(s){Dc("Error shutting down RRweb events recording",s)}if(this.testRunAnalytics)return Dc("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[Ipe,Spe,wpe,Cpe,hN];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=INt(pCe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?kNt(pCe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=gWe(pCe(this.testInfo.file)),c=ZT.join(s,`${this.checksumTestId}.har.zip`);if(!(0,Xb.existsSync)(c))throw new Error("Could not find har file or zip file");let u=ZT.join(s,"tmp");(0,Xb.existsSync)(u)||(0,Xb.mkdirSync)(u);let _=(0,Xb.readFileSync)(c),h=await(0,llr.loadAsync)(_);for(let S of Object.keys(h.files)){let k=await h.file(S).async("string"),B=ZT.join(u,S);(0,Xb.writeFileSync)(B,k),this.unzippedHarData.push(B)}let b=ZT.join(u,"test.har");if(!(0,Xb.existsSync)(b))throw this.cleanupMockData(),new Error(`Could not find har file ${b} after unzipping ${c}`);return b}cleanupMockData(){this.unzippedHarData.forEach(s=>{(0,Xb.rmSync)(s)}),this.unzippedHarData.length>0&&(0,Xb.rmSync)(ZT.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 h=_.request().headers(),b=_.request().method();h["Checksum-Id"]=(++s[b]).toString(),_.request()._applyFallbackOverrides({headers:h}),u(_)})}catch(c){Dc("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=ZT.join(Kj(SS()),"settings.asr");if(!(0,Xb.existsSync)(s)){Dc("Could not find ASR file");return}let{ungzip:c}=hWe();try{let u=await c((0,Xb.readFileSync)(s));this.appSpecificRules=JSON.parse(u)||{}}catch(u){Dc("Could not read ASR file",u.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(wM,"RuntimePage"),wM.recentlyInteracted=new Map;var olr=wM;var w5e=require("fs");var IM={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Sfi={defaultMerge:IM.defaultMerge};function lSn(i,n){return n}t(lSn,"defaultMetaDataUpdater");function uSn(i,n){return i.filter(s=>s!==void 0)}t(uSn,"defaultFilterValues");var flr;(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"})(flr||(flr={}));function plr(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:dSn(i)?1:i instanceof Set?3:i instanceof Map?4:5}t(plr,"getObjectType");function fSn(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(fSn,"getKeys");function pSn(i,n){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,n)}t(pSn,"objectHasProperty");function _lr(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(_lr,"getIterableOfIterables");var dlr=["[object Object]","[object Module]"];function dSn(i){if(!dlr.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"||!dlr.includes(Object.prototype.toString.call(s))||!s.hasOwnProperty("isPrototypeOf"))}t(dSn,"isRecord");function _Sn(i,n,s){let c={};for(let u of fSn(i)){let _=[];for(let S of i)pSn(S,u)&&_.push(S[u]);if(_.length===0)continue;let h=n.metaDataUpdater(s,{key:u,parents:i}),b=hlr(_,n,h);b!==IM.skip&&(u==="__proto__"?Object.defineProperty(c,u,{value:b,configurable:!0,enumerable:!0,writable:!0}):c[u]=b)}return c}t(_Sn,"mergeRecords$1");function mSn(i){return i.flat()}t(mSn,"mergeArrays$1");function hSn(i){return new Set(_lr(i))}t(hSn,"mergeSets$1");function gSn(i){return new Map(_lr(i))}t(gSn,"mergeMaps$1");function ySn(i){return i.at(-1)}t(ySn,"mergeOthers$1");var S5e={mergeRecords:_Sn,mergeArrays:mSn,mergeSets:hSn,mergeMaps:gSn,mergeOthers:ySn};function mlr(...i){return ASn({})(...i)}t(mlr,"deepmerge");function ASn(i,n){let s=vSn(i,c);function c(...u){return hlr(u,s,n)}return t(c,"customizedDeepmerge"),c}t(ASn,"deepmergeCustom");function vSn(i,n){return{defaultMergeFunctions:S5e,mergeFunctions:{...S5e,...Object.fromEntries(Object.entries(i).filter(([s,c])=>Object.hasOwn(S5e,s)).map(([s,c])=>c===!1?[s,S5e.mergeOthers]:[s,c]))},metaDataUpdater:i.metaDataUpdater??lSn,deepmerge:n,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??uSn,actions:IM}}t(vSn,"getUtils");function hlr(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 Y_t(c,n,s);let u=plr(c[0]);if(u!==0&&u!==5){for(let h=1;h<c.length;h++)if(plr(c[h])!==u)return Y_t(c,n,s)}switch(u){case 1:return bSn(c,n,s);case 2:return ESn(c,n,s);case 3:return xSn(c,n,s);case 4:return CSn(c,n,s);default:return Y_t(c,n,s)}}t(hlr,"mergeUnknowns");function bSn(i,n,s){let c=n.mergeFunctions.mergeRecords(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeRecords!==n.defaultMergeFunctions.mergeRecords?n.defaultMergeFunctions.mergeRecords(i,n,s):c}t(bSn,"mergeRecords");function ESn(i,n,s){let c=n.mergeFunctions.mergeArrays(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeArrays!==n.defaultMergeFunctions.mergeArrays?n.defaultMergeFunctions.mergeArrays(i):c}t(ESn,"mergeArrays");function xSn(i,n,s){let c=n.mergeFunctions.mergeSets(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeSets!==n.defaultMergeFunctions.mergeSets?n.defaultMergeFunctions.mergeSets(i):c}t(xSn,"mergeSets");function CSn(i,n,s){let c=n.mergeFunctions.mergeMaps(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeMaps!==n.defaultMergeFunctions.mergeMaps?n.defaultMergeFunctions.mergeMaps(i):c}t(CSn,"mergeMaps");function Y_t(i,n,s){let c=n.mergeFunctions.mergeOthers(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeOthers!==n.defaultMergeFunctions.mergeOthers?n.defaultMergeFunctions.mergeOthers(i):c}t(Y_t,"mergeOthers");var glr=!1;function C5e(i){glr=i}t(C5e,"setLogToConsole");function Dc(...i){glr&&console.log(...i)}t(Dc,"log");async function Zjt(i,n,s,c=6e4){if(!(n in i))return i;let u=t(()=>i[n](...s),"executor");return c===null?u():Zd(u(),c,"Execution timeout")}t(Zjt,"executePlaywrightMethodWithTimeout");function SSn({envName:i,role:n}={}){return{envName:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_NAME??i,role:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_ROLE??n}}t(SSn,"applyRuntimeEnvOverrides");function wSn(i,{role:n,environment:s}={},c=!1){var b,S;let u;if(s&&(u=(b=i.environments)==null?void 0:b.find(({name:k})=>s===k)),u||(u=(S=i.environments)==null?void 0:S.find(({default:k})=>k)),!u)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let _=u.users,h;if(_&&(n!==void 0&&(h=_.find(k=>k.role===n)),h||(h=_.find(k=>k.default))),!h)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&&h.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:h}}t(wSn,"resolveEnvironment");function ISn(i){let n=`${i??SS()}/login.ts`;if(!(0,w5e.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(ISn,"requireLogin");async function TSn(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:
|
|
746
|
+
${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 h=[_.steps,_._testInfoSteps,_._steps].filter(Boolean);for(let b of h)this.findAllStepsRecursively(b,c,u)}return u}makeChecksumStepFunction(s){return c=>{if(!s)return;let u=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,u).forEach(h=>{h.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:h=!1,noLocation:b=void 0}={}){let S=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=u===!0,b!==void 0&&(this.testInfo._checksumNoLocation=b),await this.test.step(s,c||(()=>{}),{obtainStep:_,box:h})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=S}}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 h=this.currentThought.parent;h?(h.children.push(_),_.parent=h):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:G_t};this.pushFallback(this.constructFallback(wpe).init(c)),this.pushFallback(this.constructFallback(Cpe).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(Spe).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:G_t}))}setAIFallback(s,c){var b;let u=((b=this.options.useChecksumAI)==null?void 0:b.arVersion)===1,_=t(()=>{var ie,ae,he,ft,ct,At;let S=this.buildThoughtsChainForFallback(),k={title:this.testInfo.title},B={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},G={previous:S.slice(0,-1),failing:s,next:S.slice(1)},j={storyInfo:k,testIdentification:B,fallbackConfig:{arMode:(ie=this.options.useChecksumAI)==null?void 0:ie.arMode,overrideOptions:{...(ae=this.options.useChecksumAI)==null?void 0:ae.overrideOptions,...(he=this.options.useChecksumAI)!=null&&he.modelName&&!((ct=(ft=this.options.useChecksumAI)==null?void 0:ft.overrideOptions)!=null&&ct.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},markRecovered:(At=this.options.useChecksumAI)==null?void 0:At.markRecovered},thoughts:G,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(mP).init(j)},"createArFallback"),h=t(()=>{var S,k;return this.constructFallback(hN).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),arMode:(S=this.options.useChecksumAI)==null?void 0:S.arMode,overrideOptions:(k=this.options.useChecksumAI)==null?void 0:k.overrideOptions,fallbackType:c})},"createAIFallback");return u?this.pushFallback(h()):this.pushFallback(_()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,u,_){let h=s.fallbackAnalyticsPayload.iterationSteps,b=h.length>0?_/h.length:0;this.testRunAnalytics.testRunFallbackExecution({result:u.fbResult,failedThought:s.getFailedThought(),summary:u.summary,stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:_,avgDuration:b,success:["finish","soft_assertion"].includes(u.fbResult)}),this.arResults.push({failedThought:s.getFailedThought(),result:u.fbResult,thought:u.thought})}handleAutoRecovery(s,c,u,_){let h=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:h,stepsThoughts:u.stepsThoughts,version:"v1"})}async runFallback(s,c){let u=Date.now(),_=s.resolve(c),h=await Zd(_,s.timeout),b=Date.now()-u;s instanceof hN&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,h,b)),s instanceof mP&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,h,b));let S=h.thought?`: ${h.thought}`:"";if(!h||h.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${S}`,withError:!0}),new Error("Fallback failed");if(h.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${S}`,withError:!0}),new jfe(h.fbResult);if(this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof hN&&h.summary&&this.arSummaries.push(h.summary),s instanceof mP&&h.thought&&this.arSummaries.push(h.thought),this.createChecksumStep({title:`Recovery Complete${S}`}),h.steps.length===1){let k=h.steps[0];k.thought&&(this.currentThought.thought=k.thought)}else this.currentThought.children=h.steps.map((k,B)=>({id:`${this.currentThought.id}.${B+1}`,thought:k.thought,type:k.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}={}){Dc(`[initiateFallbackSequence] with type: ${s.type}...`);let u=this.fallbacks.find(b=>b instanceof hN);if(u){let b=u.getFailedThought(),S=this.variableStore.getActiveVariables();this.fallbacks.forEach(k=>{k.setThought(b),k.setVariables(S)})}let _=this.fallbacks.find(b=>b instanceof mP);if(_){let b=_.failingThought;this.fallbacks.forEach(S=>{S instanceof mP&&S.setVariables(this.variableStore.getActiveVariables()),S.setThought(b)})}let h=this.fallbacks;c&&(h=h.filter(b=>c.reduce((S,k)=>S||b instanceof k,!1))),h=h.filter(b=>b.canResolve(s));try{for(let b of h){let S=b==null?void 0:b.toString();S&&console.log(`Using ${S}`);let k;try{let B=await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,b.getRecoveryAttemptTitle(s),async()=>await this.runFallback(b,s));k=!0}catch(B){if(k=!1,s.withChecksumAI&&B.message==="fetch failed")throw new Error(WK);B instanceof jfe&&B.fallbackResult==="hard_assertion"&&(s.error.fallbackResult="hard_assertion"),S&&console.log(`Failed to use ${S}`),b.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Ipe).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:ZT.basename(s)})}catch(s){Dc("Error shutting down RRweb events recording",s)}if(this.testRunAnalytics)return Dc("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[Ipe,Spe,wpe,Cpe,hN];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=INt(pCe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?kNt(pCe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=gWe(pCe(this.testInfo.file)),c=ZT.join(s,`${this.checksumTestId}.har.zip`);if(!(0,Xb.existsSync)(c))throw new Error("Could not find har file or zip file");let u=ZT.join(s,"tmp");(0,Xb.existsSync)(u)||(0,Xb.mkdirSync)(u);let _=(0,Xb.readFileSync)(c),h=await(0,llr.loadAsync)(_);for(let S of Object.keys(h.files)){let k=await h.file(S).async("string"),B=ZT.join(u,S);(0,Xb.writeFileSync)(B,k),this.unzippedHarData.push(B)}let b=ZT.join(u,"test.har");if(!(0,Xb.existsSync)(b))throw this.cleanupMockData(),new Error(`Could not find har file ${b} after unzipping ${c}`);return b}cleanupMockData(){this.unzippedHarData.forEach(s=>{(0,Xb.rmSync)(s)}),this.unzippedHarData.length>0&&(0,Xb.rmSync)(ZT.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 h=_.request().headers(),b=_.request().method();h["Checksum-Id"]=(++s[b]).toString(),_.request()._applyFallbackOverrides({headers:h}),u(_)})}catch(c){Dc("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=ZT.join(Kj(SS()),"settings.asr");if(!(0,Xb.existsSync)(s)){Dc("Could not find ASR file");return}let{ungzip:c}=hWe();try{let u=await c((0,Xb.readFileSync)(s));this.appSpecificRules=JSON.parse(u)||{}}catch(u){Dc("Could not read ASR file",u.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(wM,"RuntimePage"),wM.recentlyInteracted=new Map;var olr=wM;var w5e=require("fs");var IM={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Sfi={defaultMerge:IM.defaultMerge};function lSn(i,n){return n}t(lSn,"defaultMetaDataUpdater");function uSn(i,n){return i.filter(s=>s!==void 0)}t(uSn,"defaultFilterValues");var flr;(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"})(flr||(flr={}));function plr(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:dSn(i)?1:i instanceof Set?3:i instanceof Map?4:5}t(plr,"getObjectType");function fSn(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(fSn,"getKeys");function pSn(i,n){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,n)}t(pSn,"objectHasProperty");function _lr(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(_lr,"getIterableOfIterables");var dlr=["[object Object]","[object Module]"];function dSn(i){if(!dlr.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"||!dlr.includes(Object.prototype.toString.call(s))||!s.hasOwnProperty("isPrototypeOf"))}t(dSn,"isRecord");function _Sn(i,n,s){let c={};for(let u of fSn(i)){let _=[];for(let S of i)pSn(S,u)&&_.push(S[u]);if(_.length===0)continue;let h=n.metaDataUpdater(s,{key:u,parents:i}),b=hlr(_,n,h);b!==IM.skip&&(u==="__proto__"?Object.defineProperty(c,u,{value:b,configurable:!0,enumerable:!0,writable:!0}):c[u]=b)}return c}t(_Sn,"mergeRecords$1");function mSn(i){return i.flat()}t(mSn,"mergeArrays$1");function hSn(i){return new Set(_lr(i))}t(hSn,"mergeSets$1");function gSn(i){return new Map(_lr(i))}t(gSn,"mergeMaps$1");function ySn(i){return i.at(-1)}t(ySn,"mergeOthers$1");var S5e={mergeRecords:_Sn,mergeArrays:mSn,mergeSets:hSn,mergeMaps:gSn,mergeOthers:ySn};function mlr(...i){return ASn({})(...i)}t(mlr,"deepmerge");function ASn(i,n){let s=vSn(i,c);function c(...u){return hlr(u,s,n)}return t(c,"customizedDeepmerge"),c}t(ASn,"deepmergeCustom");function vSn(i,n){return{defaultMergeFunctions:S5e,mergeFunctions:{...S5e,...Object.fromEntries(Object.entries(i).filter(([s,c])=>Object.hasOwn(S5e,s)).map(([s,c])=>c===!1?[s,S5e.mergeOthers]:[s,c]))},metaDataUpdater:i.metaDataUpdater??lSn,deepmerge:n,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??uSn,actions:IM}}t(vSn,"getUtils");function hlr(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 Y_t(c,n,s);let u=plr(c[0]);if(u!==0&&u!==5){for(let h=1;h<c.length;h++)if(plr(c[h])!==u)return Y_t(c,n,s)}switch(u){case 1:return bSn(c,n,s);case 2:return ESn(c,n,s);case 3:return xSn(c,n,s);case 4:return CSn(c,n,s);default:return Y_t(c,n,s)}}t(hlr,"mergeUnknowns");function bSn(i,n,s){let c=n.mergeFunctions.mergeRecords(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeRecords!==n.defaultMergeFunctions.mergeRecords?n.defaultMergeFunctions.mergeRecords(i,n,s):c}t(bSn,"mergeRecords");function ESn(i,n,s){let c=n.mergeFunctions.mergeArrays(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeArrays!==n.defaultMergeFunctions.mergeArrays?n.defaultMergeFunctions.mergeArrays(i):c}t(ESn,"mergeArrays");function xSn(i,n,s){let c=n.mergeFunctions.mergeSets(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeSets!==n.defaultMergeFunctions.mergeSets?n.defaultMergeFunctions.mergeSets(i):c}t(xSn,"mergeSets");function CSn(i,n,s){let c=n.mergeFunctions.mergeMaps(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeMaps!==n.defaultMergeFunctions.mergeMaps?n.defaultMergeFunctions.mergeMaps(i):c}t(CSn,"mergeMaps");function Y_t(i,n,s){let c=n.mergeFunctions.mergeOthers(i,n,s);return c===IM.defaultMerge||n.useImplicitDefaultMerging&&c===void 0&&n.mergeFunctions.mergeOthers!==n.defaultMergeFunctions.mergeOthers?n.defaultMergeFunctions.mergeOthers(i):c}t(Y_t,"mergeOthers");var glr=!1;function C5e(i){glr=i}t(C5e,"setLogToConsole");function Dc(...i){glr&&console.log(...i)}t(Dc,"log");async function Zjt(i,n,s,c=6e4){if(!(n in i))return i;let u=t(()=>i[n](...s),"executor");return c===null?u():Zd(u(),c,"Execution timeout")}t(Zjt,"executePlaywrightMethodWithTimeout");function SSn({envName:i,role:n}={}){return{envName:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_NAME??i,role:process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_ROLE??n}}t(SSn,"applyRuntimeEnvOverrides");function wSn(i,{role:n,environment:s}={},c=!1){var b,S;let u;if(s&&(u=(b=i.environments)==null?void 0:b.find(({name:k})=>s===k)),u||(u=(S=i.environments)==null?void 0:S.find(({default:k})=>k)),!u)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let _=u.users,h;if(_&&(n!==void 0&&(h=_.find(k=>k.role===n)),h||(h=_.find(k=>k.default))),!h)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&&h.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:h}}t(wSn,"resolveEnvironment");function ISn(i){let n=`${i??SS()}/login.ts`;if(!(0,w5e.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(ISn,"requireLogin");async function TSn(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:
|
|
747
747
|
`,_),_}}t(TSn,"proceedWithLogin");function ulr(i){let{config:n,folder:s,throwIfAuthFailed:c}=i,u=ISn(s);return async(_,{role:h,environment:b}={})=>{let{envName:S,role:k}=SSn({envName:b,role:h}),{environment:B,user:G}=wSn(n,{role:k,environment:S},i.throwIfEnvInfoInvalid);if(c&&!G)throw new Error("Could not find user credentials matching the provided role and/or environment");await TSn(_,u,{environment:B,user:G,config:n})}}t(ulr,"makeUnboundLogin");var are;function cKt(){if(are)return are;try{let i=(0,w5e.existsSync)(`${SS()}/checksum.config.ts`)?"checksum.config.ts":(0,w5e.existsSync)(`${SS()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return I5e(require(`${SS()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return I5e()}t(cKt,"loadChecksumConfig");function I5e(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),are=mlr(n,i),gc.testRun.disableAutoRecovery&&(are.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),gc.testRun.disableHostReports&&(are.options.hostReports=!1),are}t(I5e,"getChecksumConfig");var WK="Checksum failed connecting to the server";var Llr=Da(require("child_process")),lmt=require("crypto"),yv=require("fs"),H1=require("path");var T5e=(k=>(k.RuntimeError="Runtime Error",k.TestRunMonitorError="Test Run Monitor Error",k.ChecksumConfigError="Checksum Config Error",k.InitializationError="Initialization Error",k.TraceProcessingError="Trace Processing Error",k.TestSuiteInitError="Test Suite Init Error",k.UploadStart="Upload Start",k.UploadComplete="Upload Complete",k.UploadFailed="Upload Failed",k))(T5e||{});var Bz=class Bz{constructor(n,s){this.isolatedMode=s,this.analytics=JS.createFromConfig(n,s,!1)}static getInstance(n,s){return Bz.instance||(Bz.instance=new Bz(n,s)),Bz.instance}get tableName(){return"test_suites"}get metadata(){return this.analytics.metadata}event(n){this.analytics.trackEventWithTable(n,this.metadata,this.tableName)}testSuiteStart(){let n={event:"Test Suite Start",metadata:this.metadata};this.event(n)}testSuiteEnd(n){this.event({event:"Test Suite End",metadata:this.metadata,...n})}checksumConfig(n){this.event({event:"Checksum Config",metadata:this.metadata,...n})}checksumConfigError(n){this.event({event:"Checksum Config Error",metadata:this.metadata,...n})}testSuiteError(n){this.event({event:"Test Suite Error",metadata:this.metadata,...n})}allUploadsComplete(){this.event({event:"All Uploads Complete",metadata:this.metadata})}testsFailed(){this.event({event:"Tests Failed",metadata:this.metadata})}testRunMonitorError(n){this.event({event:"Test Run Monitor Error",metadata:this.metadata,...n})}uploadStart(n){this.event({event:"Upload Start",metadata:this.metadata,...n})}uploadComplete(n){this.event({event:"Upload Complete",metadata:this.metadata,...n})}uploadFailed(n){this.event({event:"Upload Failed",metadata:this.metadata,...n})}traceProcessingError(n){this.event({event:"Trace Processing Error",metadata:this.metadata,...n})}uploadsCompleteWithErrors(n){this.event({event:"Uploads Complete With Errors",metadata:this.metadata,...n})}reportComplete(n){this.event({event:"Report Complete",metadata:this.metadata,...n})}playwrightConfig(n){this.event({event:"Playwright Config",metadata:this.metadata,...n})}playwrightConfigError(n){this.event({event:"Playwright Config Error",metadata:this.metadata,...n})}completionStatus(n){this.event({event:"Completion Status",metadata:this.metadata,...n})}reportUploadError(n={}){this.event({event:"Report Upload Error",metadata:this.metadata,...n})}runtimeTimeout(n={}){this.event({event:"Runtime Timeout",metadata:this.metadata,...n})}runtimeComplete(){this.event({event:"Runtime Complete",metadata:this.metadata})}genericEvent(n,s={}){this.event({event:n,metadata:this.metadata,...s})}};t(Bz,"TestSuiteAnalytics");var uhe=Bz;var D5e=Da(require("child_process")),Gm=require("fs"),lh=require("path");var Rz=class Rz{constructor(n,s){this.analytics=JS.createFromConfig(n,s)}static getInstance(n={},s=!1){return Rz.instance||(Rz.instance=new Rz(n,s)),Rz.instance}get tableName(){return"runtime"}event(n){this.analytics.trackEventWithTable(n,this.metadata,this.tableName)}checksumConfig(n){this.event({event:"Checksum Config",metadata:this.metadata,config:n})}eventWithMessage(n,s){this.event({event:n,metadata:this.metadata,message:s})}get metadata(){return{...this.analytics.metadata,appName:"unknown",commitHash:"unknown",envName:"unknown",branch:"unknown",testSuiteRunId:"unknown",checksumRuntimeVersion:"unknown",...this.analytics.metadata}}async close(){return this.analytics.close()}};t(Rz,"RuntimeAnalytics");var k5e=Rz;var ylr=".chk";var Z_t=class Z_t{constructor(n,s=!1,c){this.args=n;this.debugMode=s;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=t(n=>{console.log("\x1B[31m%s\x1B[0m",n,"\x1B[0m")},"printError");this.processConfigArg(),["exit","SIGINT","SIGTERM","uncaughtException"].forEach(u=>{process.on(u,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion(),c!=null&&c.skipChecksumDataLoad||this.loadChecksumData(c)}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{let n=gc.isRepoMode?(0,lh.join)(gc.runtimeRoot,"package","package.json"):"./package.json";return require(n).version}catch{return"unknown"}}getInternalFilesDirPath(){return(0,lh.join)(this.checksumRoot,ylr)}createInternalFilesDir(){let n=this.getInternalFilesDirPath();if((0,Gm.existsSync)(n)){Dc("Internal files directory already exists at",n);return}(0,Gm.mkdirSync)(n,{recursive:!0}),Dc("Internal files directory created at",n)}loadTracer(){this.runtimeAnalytics=k5e.getInstance({version:this.checksumRuntimeVersion},this.debugMode)}async execCmd(n,s={}){let c={...process.env,...s},u=await D5e.spawn(n,{env:c,shell:!0,stdio:"inherit"});return this.childProcesses.push(u),new Promise((h,b)=>{u.on("exit",S=>{S===0?h(!0):b(new Error(`Checksum failed execution with code: ${S} `)),this.childProcesses=this.childProcesses.filter(k=>k!==u)})})}async getCmdOutput(n){return new Promise(function(s,c){D5e.exec(n,(u,_,h)=>{if(u){c(`Error executing command: ${u.message}`);return}s(_.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let n=(0,lh.join)(this.checksumRoot,".auth");(0,Gm.existsSync)(n)||(0,Gm.writeFileSync)(n,"{}")}loadChecksumData(n={}){this.locateChecksumLibs(),this.loadChecksumConfig(n)}async patchPlaywright(n=!1){Dc("Patching playwright",n);let s=(0,lh.join)(__dirname,"./scripts/patch.js");(0,Gm.existsSync)(s)||(s=(0,lh.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let c=`node "${s}"${n?" off":""}`;try{await this.execCmd(c,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(u){console.log("Error patching playwright",u.message)}}getPlaywrightConfigFilePath(){return(0,lh.join)(this.checksumRoot,"playwright.config.ts")}getProgressReporterPath(){return gc.isRepoMode?(0,lh.join)(gc.runtimeRoot,"src/playwright-progress-reporter/checksum-progress-reporter.ts"):(0,lh.join)(__dirname,"checksum-progress-reporter.js")}getWrappedPlaywrightConfigPath(){return(0,lh.join)(this.checksumRoot??"","playwright.config.checksum.tmp.ts")}buildRunPlaywrightConfig(){let n=this.getPlaywrightConfigFilePath();try{let s=this.getWrappedPlaywrightConfigPath(),c=this.getProgressReporterPath();return(0,Gm.writeFileSync)(s,`// Auto-generated by @checksum-ai/runtime \u2014 wraps the project's Playwright
|
|
748
748
|
// config to add the Checksum progress reporter. Safe to delete.
|
|
749
749
|
import baseConfig from "./playwright.config";
|