@checksum-ai/runtime 1.2.13-alpha → 1.2.15-alpha
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/cli.js +4 -4
- package/index.js +134 -134
- package/package.json +1 -1
- package/test-run-monitor.js +15 -15
- package/vtg-pw-bridge-runner.js +42 -42
package/.env
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
CHECKSUM_RUNTIME_BUILD_TIME=2025-08-
|
|
1
|
+
CHECKSUM_RUNTIME_BUILD_TIME=2025-08-24T20:41:22.357Z
|
package/cli.js
CHANGED
|
@@ -1494,7 +1494,7 @@ Please make sure you are calling this method within a traceable function and tha
|
|
|
1494
1494
|
`)}var cAi,Dyr,iDe,OXe=ud(()=>{cAi=Object.prototype.hasOwnProperty;e(win,"hasOwnProperty");e(Tin,"_objectKeys");e(_ee,"_deepClone");e(T3t,"isInteger");e(k3t,"escapePathComponent");e(BXe,"unescapePathComponent");e(w3t,"hasUndefined");e(Sin,"patchErrorMessageFormatter");Dyr=class Dyr extends Error{constructor(n,a,u,f,g){super(Sin(n,{name:a,index:u,operation:f,tree:g})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:u}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:f}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:g}),Object.setPrototypeOf(this,new.target.prototype),this.message=Sin(n,{name:a,index:u,operation:f,tree:g})}};e(Dyr,"PatchError");iDe=Dyr});var Syr={};utr(Syr,{JsonPatchError:()=>I5,_areEquals:()=>RXe,applyOperation:()=>aDe,applyPatch:()=>P3t,applyReducer:()=>pAi,deepClone:()=>uAi,getValueByPointer:()=>I3t,validate:()=>kin,validator:()=>F3t});function I3t(i,n){if(n=="")return i;var a={op:"_get",path:n};return aDe(i,a),a.value}function aDe(i,n,a=!1,u=!0,f=!0,g=0){if(a&&(typeof a=="function"?a(n,0,i,n.path):F3t(n,0)),n.path===""){let A={newDocument:i};if(n.op==="add")return A.newDocument=n.value,A;if(n.op==="replace")return A.newDocument=n.value,A.removed=i,A;if(n.op==="move"||n.op==="copy")return A.newDocument=I3t(i,n.from),n.op==="move"&&(A.removed=i),A;if(n.op==="test"){if(A.test=RXe(i,n.value),A.test===!1)throw new I5("Test operation failed","TEST_OPERATION_FAILED",g,n,i);return A.newDocument=i,A}else{if(n.op==="remove")return A.removed=i,A.newDocument=null,A;if(n.op==="_get")return n.value=i,A;if(a)throw new I5("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",g,n,i);return A}}else{u||(i=_ee(i));let E=(n.path||"").split("/"),D=i,F=1,P=E.length,Q,R,W;for(typeof a=="function"?W=a:W=F3t;;){if(R=E[F],R&&R.indexOf("~")!=-1&&(R=BXe(R)),f&&(R=="__proto__"||R=="prototype"&&F>0&&E[F-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(a&&Q===void 0&&(D[R]===void 0?Q=E.slice(0,F).join("/"):F==P-1&&(Q=n.path),Q!==void 0&&W(n,0,i,Q)),F++,Array.isArray(D)){if(R==="-")R=D.length;else{if(a&&!T3t(R))throw new I5("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",g,n,i);T3t(R)&&(R=~~R)}if(F>=P){if(a&&n.op==="add"&&R>D.length)throw new I5("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",g,n,i);let q=lAi[n.op].call(n,D,R,i);if(q.test===!1)throw new I5("Test operation failed","TEST_OPERATION_FAILED",g,n,i);return q}}else if(F>=P){let q=mBe[n.op].call(n,D,R,i);if(q.test===!1)throw new I5("Test operation failed","TEST_OPERATION_FAILED",g,n,i);return q}if(D=D[R],a&&F<P&&(!D||typeof D!="object"))throw new I5("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",g,n,i)}}}function P3t(i,n,a,u=!0,f=!0){if(a&&!Array.isArray(n))throw new I5("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");u||(i=_ee(i));let g=new Array(n.length);for(let A=0,E=n.length;A<E;A++)g[A]=aDe(i,n[A],a,!0,f,A),i=g[A].newDocument;return g.newDocument=i,g}function pAi(i,n,a){let u=aDe(i,n);if(u.test===!1)throw new I5("Test operation failed","TEST_OPERATION_FAILED",a,n,i);return u.newDocument}function F3t(i,n,a,u){if(typeof i!="object"||i===null||Array.isArray(i))throw new I5("Operation is not an object","OPERATION_NOT_AN_OBJECT",n,i,a);if(mBe[i.op]){if(typeof i.path!="string")throw new I5("Operation `path` property is not a string","OPERATION_PATH_INVALID",n,i,a);if(i.path.indexOf("/")!==0&&i.path.length>0)throw new I5('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",n,i,a);if((i.op==="move"||i.op==="copy")&&typeof i.from!="string")throw new I5("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",n,i,a);if((i.op==="add"||i.op==="replace"||i.op==="test")&&i.value===void 0)throw new I5("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",n,i,a);if((i.op==="add"||i.op==="replace"||i.op==="test")&&w3t(i.value))throw new I5("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",n,i,a);if(a){if(i.op=="add"){var f=i.path.split("/").length,g=u.split("/").length;if(f!==g+1&&f!==g)throw new I5("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",n,i,a)}else if(i.op==="replace"||i.op==="remove"||i.op==="_get"){if(i.path!==u)throw new I5("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",n,i,a)}else if(i.op==="move"||i.op==="copy"){var A={op:"_get",path:i.from,value:void 0},E=kin([A],a);if(E&&E.name==="OPERATION_PATH_UNRESOLVABLE")throw new I5("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",n,i,a)}}}else throw new I5("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",n,i,a)}function kin(i,n,a){try{if(!Array.isArray(i))throw new I5("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(n)P3t(_ee(n),_ee(i),a||!0);else{a=a||F3t;for(var u=0;u<i.length;u++)a(i[u],u,n,void 0)}}catch(f){if(f instanceof I5)return f;throw f}}function RXe(i,n){if(i===n)return!0;if(i&&n&&typeof i=="object"&&typeof n=="object"){var a=Array.isArray(i),u=Array.isArray(n),f,g,A;if(a&&u){if(g=i.length,g!=n.length)return!1;for(f=g;f--!==0;)if(!RXe(i[f],n[f]))return!1;return!0}if(a!=u)return!1;var E=Object.keys(i);if(g=E.length,g!==Object.keys(n).length)return!1;for(f=g;f--!==0;)if(!n.hasOwnProperty(E[f]))return!1;for(f=g;f--!==0;)if(A=E[f],!RXe(i[A],n[A]))return!1;return!0}return i!==i&&n!==n}var I5,uAi,mBe,lAi,N3t=ud(()=>{OXe();I5=iDe,uAi=_ee,mBe={add:e(function(i,n,a){return i[n]=this.value,{newDocument:a}},"add"),remove:e(function(i,n,a){var u=i[n];return delete i[n],{newDocument:a,removed:u}},"remove"),replace:e(function(i,n,a){var u=i[n];return i[n]=this.value,{newDocument:a,removed:u}},"replace"),move:e(function(i,n,a){let u=I3t(a,this.path);u&&(u=_ee(u));let f=aDe(a,{op:"remove",path:this.from}).removed;return aDe(a,{op:"add",path:this.path,value:f}),{newDocument:a,removed:u}},"move"),copy:e(function(i,n,a){let u=I3t(a,this.from);return aDe(a,{op:"add",path:this.path,value:_ee(u)}),{newDocument:a}},"copy"),test:e(function(i,n,a){return{newDocument:a,test:RXe(i[n],this.value)}},"test"),_get:e(function(i,n,a){return this.value=i[n],{newDocument:a}},"_get")},lAi={add:e(function(i,n,a){return T3t(n)?i.splice(n,0,this.value):i[n]=this.value,{newDocument:a,index:n}},"add"),remove:e(function(i,n,a){var u=i.splice(n,1);return{newDocument:a,removed:u[0]}},"remove"),replace:e(function(i,n,a){var u=i[n];return i[n]=this.value,{newDocument:a,removed:u}},"replace"),move:mBe.move,copy:mBe.copy,test:mBe.test,_get:mBe._get};e(I3t,"getValueByPointer");e(aDe,"applyOperation");e(P3t,"applyPatch");e(pAi,"applyReducer");e(F3t,"validator");e(kin,"validate");e(RXe,"_areEquals")});var Iin=ud(()=>{OXe();N3t();});var $sa,Fin=ud(()=>{N3t();Iin();OXe();N3t();OXe();$sa={...Syr,JsonPatchError:iDe,deepClone:_ee,escapePathComponent:k3t,unescapePathComponent:BXe}});async function Pin(){return wyr===void 0&&(wyr={library:"langchain-js",runtime:hAi()}),wyr}function jz(i){var n;try{return typeof process<"u"?(n=process.env)==null?void 0:n[i]:Tyr()?Deno==null?void 0:Deno.env.get(i):void 0}catch{return}}var fAi,dAi,_Ai,Tyr,mAi,hAi,wyr,hBe=ud(()=>{fAi=e(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),dAi=e(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),_Ai=e(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),"isJsDom"),Tyr=e(()=>typeof Deno<"u","isDeno"),mAi=e(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Tyr(),"isNode"),hAi=e(()=>{let i;return fAi()?i="browser":mAi()?i="node":dAi()?i="webworker":_Ai()?i="jsdom":Tyr()?i="deno":i="other",i},"getEnv");e(Pin,"getRuntimeEnvironment");e(jz,"getEnvironmentVariable")});var Iyr,kyr,B3t,sDe,Nin,O3t=ud(()=>{uIe();TXe();hBe();Iyr=class Iyr{};e(Iyr,"BaseCallbackHandlerMethodsClass");kyr=Iyr,B3t=class B3t extends kyr{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,fyr(this.constructor)]}constructor(n){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:jz("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=n||{},n&&(this.ignoreLLM=n.ignoreLLM??this.ignoreLLM,this.ignoreChain=n.ignoreChain??this.ignoreChain,this.ignoreAgent=n.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=n.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=n.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=n.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(n._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return pme.prototype.toJSON.call(this)}toJSONNotImplemented(){return pme.prototype.toJSONNotImplemented.call(this)}static fromMethods(n){let u=class u extends B3t{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:pB()}),Object.assign(this,n)}};e(u,"Handler");let a=u;return new a}};e(B3t,"BaseCallbackHandler");sDe=B3t,Nin=e(i=>{let n=i;return n!==void 0&&typeof n.copy=="function"&&typeof n.name=="string"&&typeof n.awaitHandlers=="boolean"},"isBaseCallbackHandler")});function Fyr(i,n){return i&&!Array.isArray(i)&&typeof i=="object"?i:{[n]:i}}function gAi(i){return i.replace(/[-:.]/g,"")}function yAi(i,n,a){let u=a.toFixed(0).slice(0,3).padStart(3,"0");return gAi(`${new Date(i).toISOString().slice(0,-1)}${u}Z`)+n}function gBe(i){return typeof i._addRunToRunMap=="function"}var Pyr,dme,oDe=ud(()=>{O3t();e(Fyr,"_coerceToDict");e(gAi,"stripNonAlphanumeric");e(yAi,"convertToDottedOrderFormat");e(gBe,"isBaseTracer");Pyr=class Pyr extends sDe{constructor(n){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(n){return n instanceof Error?n.message+(n!=null&&n.stack?`
|
|
1495
1495
|
|
|
1496
1496
|
${n.stack}`:""):typeof n=="string"?n:`${n}`}_addChildRun(n,a){n.child_runs.push(a)}_addRunToRunMap(n){let a=yAi(n.start_time,n.id,n.execution_order),u={...n};if(u.parent_run_id!==void 0){let f=this.runMap.get(u.parent_run_id);f&&(this._addChildRun(f,u),f.child_execution_order=Math.max(f.child_execution_order,u.child_execution_order),u.trace_id=f.trace_id,f.dotted_order!==void 0&&(u.dotted_order=[f.dotted_order,a].join(".")))}else u.trace_id=u.id,u.dotted_order=a;return this.runMap.set(u.id,u),u}async _endTrace(n){var u;let a=n.parent_run_id!==void 0&&this.runMap.get(n.parent_run_id);a?a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order):await this.persistRun(n),this.runMap.delete(n.id),await((u=this.onRunUpdate)==null?void 0:u.call(this,n))}_getExecutionOrder(n){let a=n!==void 0&&this.runMap.get(n);return a?a.child_execution_order+1:1}_createRunForLLMStart(n,a,u,f,g,A,E,D){let F=this._getExecutionOrder(f),P=Date.now(),Q=E?{...g,metadata:E}:g,R={id:u,name:D??n.id[n.id.length-1],parent_run_id:f,start_time:P,serialized:n,events:[{name:"start",time:new Date(P).toISOString()}],inputs:{prompts:a},execution_order:F,child_runs:[],child_execution_order:F,run_type:"llm",extra:Q??{},tags:A||[]};return this._addRunToRunMap(R)}async handleLLMStart(n,a,u,f,g,A,E,D){var P,Q;let F=this.runMap.get(u)??this._createRunForLLMStart(n,a,u,f,g,A,E,D);return await((P=this.onRunCreate)==null?void 0:P.call(this,F)),await((Q=this.onLLMStart)==null?void 0:Q.call(this,F)),F}_createRunForChatModelStart(n,a,u,f,g,A,E,D){let F=this._getExecutionOrder(f),P=Date.now(),Q=E?{...g,metadata:E}:g,R={id:u,name:D??n.id[n.id.length-1],parent_run_id:f,start_time:P,serialized:n,events:[{name:"start",time:new Date(P).toISOString()}],inputs:{messages:a},execution_order:F,child_runs:[],child_execution_order:F,run_type:"llm",extra:Q??{},tags:A||[]};return this._addRunToRunMap(R)}async handleChatModelStart(n,a,u,f,g,A,E,D){var P,Q;let F=this.runMap.get(u)??this._createRunForChatModelStart(n,a,u,f,g,A,E,D);return await((P=this.onRunCreate)==null?void 0:P.call(this,F)),await((Q=this.onLLMStart)==null?void 0:Q.call(this,F)),F}async handleLLMEnd(n,a,u,f,g){var E;let A=this.runMap.get(a);if(!A||(A==null?void 0:A.run_type)!=="llm")throw new Error("No LLM run to end.");return A.end_time=Date.now(),A.outputs=n,A.events.push({name:"end",time:new Date(A.end_time).toISOString()}),A.extra={...A.extra,...g},await((E=this.onLLMEnd)==null?void 0:E.call(this,A)),await this._endTrace(A),A}async handleLLMError(n,a,u,f,g){var E;let A=this.runMap.get(a);if(!A||(A==null?void 0:A.run_type)!=="llm")throw new Error("No LLM run to end.");return A.end_time=Date.now(),A.error=this.stringifyError(n),A.events.push({name:"error",time:new Date(A.end_time).toISOString()}),A.extra={...A.extra,...g},await((E=this.onLLMError)==null?void 0:E.call(this,A)),await this._endTrace(A),A}_createRunForChainStart(n,a,u,f,g,A,E,D){let F=this._getExecutionOrder(f),P=Date.now(),Q={id:u,name:D??n.id[n.id.length-1],parent_run_id:f,start_time:P,serialized:n,events:[{name:"start",time:new Date(P).toISOString()}],inputs:a,execution_order:F,child_execution_order:F,run_type:E??"chain",child_runs:[],extra:A?{metadata:A}:{},tags:g||[]};return this._addRunToRunMap(Q)}async handleChainStart(n,a,u,f,g,A,E,D){var P,Q;let F=this.runMap.get(u)??this._createRunForChainStart(n,a,u,f,g,A,E,D);return await((P=this.onRunCreate)==null?void 0:P.call(this,F)),await((Q=this.onChainStart)==null?void 0:Q.call(this,F)),F}async handleChainEnd(n,a,u,f,g){var E;let A=this.runMap.get(a);if(!A)throw new Error("No chain run to end.");return A.end_time=Date.now(),A.outputs=Fyr(n,"output"),A.events.push({name:"end",time:new Date(A.end_time).toISOString()}),(g==null?void 0:g.inputs)!==void 0&&(A.inputs=Fyr(g.inputs,"input")),await((E=this.onChainEnd)==null?void 0:E.call(this,A)),await this._endTrace(A),A}async handleChainError(n,a,u,f,g){var E;let A=this.runMap.get(a);if(!A)throw new Error("No chain run to end.");return A.end_time=Date.now(),A.error=this.stringifyError(n),A.events.push({name:"error",time:new Date(A.end_time).toISOString()}),(g==null?void 0:g.inputs)!==void 0&&(A.inputs=Fyr(g.inputs,"input")),await((E=this.onChainError)==null?void 0:E.call(this,A)),await this._endTrace(A),A}_createRunForToolStart(n,a,u,f,g,A,E){let D=this._getExecutionOrder(f),F=Date.now(),P={id:u,name:E??n.id[n.id.length-1],parent_run_id:f,start_time:F,serialized:n,events:[{name:"start",time:new Date(F).toISOString()}],inputs:{input:a},execution_order:D,child_execution_order:D,run_type:"tool",child_runs:[],extra:A?{metadata:A}:{},tags:g||[]};return this._addRunToRunMap(P)}async handleToolStart(n,a,u,f,g,A,E){var F,P;let D=this.runMap.get(u)??this._createRunForToolStart(n,a,u,f,g,A,E);return await((F=this.onRunCreate)==null?void 0:F.call(this,D)),await((P=this.onToolStart)==null?void 0:P.call(this,D)),D}async handleToolEnd(n,a){var f;let u=this.runMap.get(a);if(!u||(u==null?void 0:u.run_type)!=="tool")throw new Error("No tool run to end");return u.end_time=Date.now(),u.outputs={output:n},u.events.push({name:"end",time:new Date(u.end_time).toISOString()}),await((f=this.onToolEnd)==null?void 0:f.call(this,u)),await this._endTrace(u),u}async handleToolError(n,a){var f;let u=this.runMap.get(a);if(!u||(u==null?void 0:u.run_type)!=="tool")throw new Error("No tool run to end");return u.end_time=Date.now(),u.error=this.stringifyError(n),u.events.push({name:"error",time:new Date(u.end_time).toISOString()}),await((f=this.onToolError)==null?void 0:f.call(this,u)),await this._endTrace(u),u}async handleAgentAction(n,a){var g;let u=this.runMap.get(a);if(!u||(u==null?void 0:u.run_type)!=="chain")return;let f=u;f.actions=f.actions||[],f.actions.push(n),f.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:n}}),await((g=this.onAgentAction)==null?void 0:g.call(this,u))}async handleAgentEnd(n,a){var f;let u=this.runMap.get(a);!u||(u==null?void 0:u.run_type)!=="chain"||(u.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:n}}),await((f=this.onAgentEnd)==null?void 0:f.call(this,u)))}_createRunForRetrieverStart(n,a,u,f,g,A,E){let D=this._getExecutionOrder(f),F=Date.now(),P={id:u,name:E??n.id[n.id.length-1],parent_run_id:f,start_time:F,serialized:n,events:[{name:"start",time:new Date(F).toISOString()}],inputs:{query:a},execution_order:D,child_execution_order:D,run_type:"retriever",child_runs:[],extra:A?{metadata:A}:{},tags:g||[]};return this._addRunToRunMap(P)}async handleRetrieverStart(n,a,u,f,g,A,E){var F,P;let D=this.runMap.get(u)??this._createRunForRetrieverStart(n,a,u,f,g,A,E);return await((F=this.onRunCreate)==null?void 0:F.call(this,D)),await((P=this.onRetrieverStart)==null?void 0:P.call(this,D)),D}async handleRetrieverEnd(n,a){var f;let u=this.runMap.get(a);if(!u||(u==null?void 0:u.run_type)!=="retriever")throw new Error("No retriever run to end");return u.end_time=Date.now(),u.outputs={documents:n},u.events.push({name:"end",time:new Date(u.end_time).toISOString()}),await((f=this.onRetrieverEnd)==null?void 0:f.call(this,u)),await this._endTrace(u),u}async handleRetrieverError(n,a){var f;let u=this.runMap.get(a);if(!u||(u==null?void 0:u.run_type)!=="retriever")throw new Error("No retriever run to end");return u.end_time=Date.now(),u.error=this.stringifyError(n),u.events.push({name:"error",time:new Date(u.end_time).toISOString()}),await((f=this.onRetrieverError)==null?void 0:f.call(this,u)),await this._endTrace(u),u}async handleText(n,a){var f;let u=this.runMap.get(a);!u||(u==null?void 0:u.run_type)!=="chain"||(u.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:n}}),await((f=this.onText)==null?void 0:f.call(this,u)))}async handleLLMNewToken(n,a,u,f,g,A){var D;let E=this.runMap.get(u);if(!E||(E==null?void 0:E.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return E.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:n,idx:a,chunk:A==null?void 0:A.chunk}}),await((D=this.onLLMNewToken)==null?void 0:D.call(this,E,n,{chunk:A==null?void 0:A.chunk})),E}};e(Pyr,"BaseTracer");dme=Pyr});var Lin=rn((soa,Rin)=>{"use strict";var Bin=e((i=0)=>n=>`\x1B[${38+i};5;${n}m`,"wrapAnsi256"),Oin=e((i=0)=>(n,a,u)=>`\x1B[${38+i};2;${n};${a};${u}m`,"wrapAnsi16m");function vAi(){let i=new Map,n={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};n.color.gray=n.color.blackBright,n.bgColor.bgGray=n.bgColor.bgBlackBright,n.color.grey=n.color.blackBright,n.bgColor.bgGrey=n.bgColor.bgBlackBright;for(let[a,u]of Object.entries(n)){for(let[f,g]of Object.entries(u))n[f]={open:`\x1B[${g[0]}m`,close:`\x1B[${g[1]}m`},u[f]=n[f],i.set(g[0],g[1]);Object.defineProperty(n,a,{value:u,enumerable:!1})}return Object.defineProperty(n,"codes",{value:i,enumerable:!1}),n.color.close="\x1B[39m",n.bgColor.close="\x1B[49m",n.color.ansi256=Bin(),n.color.ansi16m=Oin(),n.bgColor.ansi256=Bin(10),n.bgColor.ansi16m=Oin(10),Object.defineProperties(n,{rgbToAnsi256:{value:e((a,u,f)=>a===u&&u===f?a<8?16:a>248?231:Math.round((a-8)/247*24)+232:16+36*Math.round(a/255*5)+6*Math.round(u/255*5)+Math.round(f/255*5),"value"),enumerable:!1},hexToRgb:{value:e(a=>{let u=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(a.toString(16));if(!u)return[0,0,0];let{colorString:f}=u.groups;f.length===3&&(f=f.split("").map(A=>A+A).join(""));let g=Number.parseInt(f,16);return[g>>16&255,g>>8&255,g&255]},"value"),enumerable:!1},hexToAnsi256:{value:e(a=>n.rgbToAnsi256(...n.hexToRgb(a)),"value"),enumerable:!1}}),n}e(vAi,"assembleStyles");Object.defineProperty(Rin,"exports",{enumerable:!0,get:vAi})});function kq(i,n){return`${i.open}${n}${i.close}`}function mee(i,n){try{return JSON.stringify(i,null,2)}catch{return n}}function Min(i){return typeof i=="string"?i.trim():i==null?i:mee(i,i.toString())}function Xxe(i){if(!i.end_time)return"";let n=i.end_time-i.start_time;return n<1e3?`${n}ms`:`${(n/1e3).toFixed(2)}s`}var Nyr,e$,Byr,LXe,jin=ud(()=>{Nyr=jh(Lin(),1);oDe();e(kq,"wrap");e(mee,"tryJsonStringify");e(Min,"formatKVMapItem");e(Xxe,"elapsed");({color:e$}=Nyr.default),Byr=class Byr extends dme{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(n){return Promise.resolve()}getParents(n){let a=[],u=n;for(;u.parent_run_id;){let f=this.runMap.get(u.parent_run_id);if(f)a.push(f),u=f;else break}return a}getBreadcrumbs(n){let u=[...this.getParents(n).reverse(),n].map((f,g,A)=>{let E=`${f.execution_order}:${f.run_type}:${f.name}`;return g===A.length-1?kq(Nyr.default.bold,E):E}).join(" > ");return kq(e$.grey,u)}onChainStart(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.green,"[chain/start]")} [${a}] Entering Chain run with input: ${mee(n.inputs,"[inputs]")}`)}onChainEnd(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.cyan,"[chain/end]")} [${a}] [${Xxe(n)}] Exiting Chain run with output: ${mee(n.outputs,"[outputs]")}`)}onChainError(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.red,"[chain/error]")} [${a}] [${Xxe(n)}] Chain run errored with error: ${mee(n.error,"[error]")}`)}onLLMStart(n){let a=this.getBreadcrumbs(n),u="prompts"in n.inputs?{prompts:n.inputs.prompts.map(f=>f.trim())}:n.inputs;console.log(`${kq(e$.green,"[llm/start]")} [${a}] Entering LLM run with input: ${mee(u,"[inputs]")}`)}onLLMEnd(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.cyan,"[llm/end]")} [${a}] [${Xxe(n)}] Exiting LLM run with output: ${mee(n.outputs,"[response]")}`)}onLLMError(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.red,"[llm/error]")} [${a}] [${Xxe(n)}] LLM run errored with error: ${mee(n.error,"[error]")}`)}onToolStart(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.green,"[tool/start]")} [${a}] Entering Tool run with input: "${Min(n.inputs.input)}"`)}onToolEnd(n){var u;let a=this.getBreadcrumbs(n);console.log(`${kq(e$.cyan,"[tool/end]")} [${a}] [${Xxe(n)}] Exiting Tool run with output: "${Min((u=n.outputs)==null?void 0:u.output)}"`)}onToolError(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.red,"[tool/error]")} [${a}] [${Xxe(n)}] Tool run errored with error: ${mee(n.error,"[error]")}`)}onRetrieverStart(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.green,"[retriever/start]")} [${a}] Entering Retriever run with input: ${mee(n.inputs,"[inputs]")}`)}onRetrieverEnd(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.cyan,"[retriever/end]")} [${a}] [${Xxe(n)}] Exiting Retriever run with output: ${mee(n.outputs,"[outputs]")}`)}onRetrieverError(n){let a=this.getBreadcrumbs(n);console.log(`${kq(e$.red,"[retriever/error]")} [${a}] [${Xxe(n)}] Retriever run errored with error: ${mee(n.error,"[error]")}`)}onAgentAction(n){let a=n,u=this.getBreadcrumbs(n);console.log(`${kq(e$.blue,"[agent/action]")} [${u}] Agent selected action: ${mee(a.actions[a.actions.length-1],"[action]")}`)}};e(Byr,"ConsoleCallbackHandler");LXe=Byr});var Oyr=ud(()=>{m3t()});var Ryr,Qin,Uin=ud(()=>{h3t();hBe();Qin=e(()=>{if(Ryr===void 0){let i=jz("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Ryr=new rDe(i)}return Ryr},"getDefaultLangChainClientSingleton")});var R3t,yBe,qin=ud(()=>{Oyr();Cyr();hBe();oDe();Uin();R3t=class R3t extends dme{constructor(n={}){super(n),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:a,projectName:u,client:f}=n;this.projectName=u??jz("LANGCHAIN_PROJECT")??jz("LANGCHAIN_SESSION"),this.exampleId=a,this.client=f??Qin();let g=R3t.getTraceableRunTree();g&&this.updateFromRunTree(g)}async _convertToCreate(n,a=void 0){return{...n,extra:{...n.extra,runtime:await Pin()},child_runs:void 0,session_name:this.projectName,reference_example_id:n.parent_run_id?void 0:a}}async persistRun(n){}async onRunCreate(n){let a=await this._convertToCreate(n,this.exampleId);await this.client.createRun(a)}async onRunUpdate(n){let a={end_time:n.end_time,error:n.error,outputs:n.outputs,events:n.events,inputs:n.inputs,trace_id:n.trace_id,dotted_order:n.dotted_order,parent_run_id:n.parent_run_id,extra:n.extra,session_name:this.projectName};await this.client.updateRun(n.id,a)}getRun(n){return this.runMap.get(n)}updateFromRunTree(n){let a=n,u=new Set;for(;a.parent_run&&!(u.has(a.id)||(u.add(a.id),!a.parent_run));)a=a.parent_run;u.clear();let f=[a];for(;f.length>0;){let g=f.shift();!g||u.has(g.id)||(u.add(g.id),this.runMap.set(g.id,g),g.child_runs&&f.push(...g.child_runs))}this.client=n.client??this.client,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId}convertToRunTree(n){let a={},u=[];for(let[f,g]of this.runMap){let A=new Mle({...g,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});a[f]=A,u.push([f,g.dotted_order])}u.sort((f,g)=>!f[1]||!g[1]?0:f[1].localeCompare(g[1]));for(let[f]of u){let g=this.runMap.get(f),A=a[f];if(!(!g||!A)&&g.parent_run_id){let E=a[g.parent_run_id];E&&(E.child_runs.push(A),A.parent_run=E)}}return a[n]}static getTraceableRunTree(){try{return Cin(!0)}catch{return}}};e(R3t,"LangChainTracer");yBe=R3t});var Vin,cDe,Jin,Zxe,MXe=ud(()=>{Vin=Symbol.for("ls:tracing_async_local_storage"),cDe=Symbol.for("lc:context_variables"),Jin=e(i=>{globalThis[Vin]=i},"setGlobalAsyncLocalStorageInstance"),Zxe=e(()=>globalThis[Vin],"getGlobalAsyncLocalStorageInstance")});function xAi(){let i="default"in L3t.default?L3t.default.default:L3t.default;return new i({autoStart:!0,concurrency:1})}function AAi(){return typeof jXe>"u"&&(jXe=xAi()),jXe}async function ik(i,n){if(n===!0){let a=Zxe();a!==void 0?await a.run(void 0,async()=>i()):await i()}else jXe=AAi(),jXe.add(async()=>{let a=Zxe();a!==void 0?await a.run(void 0,async()=>i()):await i()})}var L3t,jXe,Win=ud(()=>{L3t=jh($Ct(),1);MXe();e(xAi,"createQueue");e(AAi,"getQueue");e(ik,"consumeCallback")});var $in=ud(()=>{Win()});var Hin,Gin=ud(()=>{hBe();Hin=e(i=>i!==void 0?i:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(a=>jz(a)==="true"),"isTracingEnabled")});function Lyr(i){var u;let n=Zxe();if(n===void 0)return;let a=n.getStore();return(u=a==null?void 0:a[cDe])==null?void 0:u[i]}var bAi,zin,Kin=ud(()=>{Oyr();MXe();e(Lyr,"getContextVariable");bAi=Symbol("lc:configure_hooks"),zin=e(()=>Lyr(bAi)||[],"_getConfigureHooks")});function qyr(i){return"name"in i?i:sDe.fromMethods(i)}var Vyr,Myr,Jyr,vBe,Wyr,jyr,$yr,M3t,Hyr,Qyr,Gyr,Uyr,uDe,_me,j3t=ud(()=>{uIe();O3t();jin();nDe();hBe();qin();$in();Gin();oDe();Kin();Vyr=class Vyr{setHandler(n){return this.setHandlers([n])}};e(Vyr,"BaseCallbackManager");Myr=Vyr,Jyr=class Jyr{constructor(n,a,u,f,g,A,E,D){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:u}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:f}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:g}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:A}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:E}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:D})}get parentRunId(){return this._parentRunId}async handleText(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;try{await((u=a.handleText)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleText: ${f}`),a.raiseError)throw f}},a.awaitHandlers)))}async handleCustomEvent(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;try{await((E=A.handleCustomEvent)==null?void 0:E.call(A,n,a,this.runId,this.tags,this.metadata))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleCustomEvent: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}};e(Jyr,"BaseRunManager");vBe=Jyr,Wyr=class Wyr extends vBe{getChild(n){let a=new _me(this.runId);return a.setHandlers(this.inheritableHandlers),a.addTags(this.inheritableTags),a.addMetadata(this.inheritableMetadata),n&&a.addTags([n],!1),a}async handleRetrieverEnd(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreRetriever)try{await((u=a.handleRetrieverEnd)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetriever`),a.raiseError)throw f}},a.awaitHandlers)))}async handleRetrieverError(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreRetriever)try{await((u=a.handleRetrieverError)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverError: ${f}`),a.raiseError)throw n}},a.awaitHandlers)))}};e(Wyr,"CallbackManagerForRetrieverRun");jyr=Wyr,$yr=class $yr extends vBe{async handleLLMNewToken(n,a,u,f,g,A){await Promise.all(this.handlers.map(E=>ik(async()=>{var D;if(!E.ignoreLLM)try{await((D=E.handleLLMNewToken)==null?void 0:D.call(E,n,a??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,A))}catch(F){if((E.raiseError?console.error:console.warn)(`Error in handler ${E.constructor.name}, handleLLMNewToken: ${F}`),E.raiseError)throw F}},E.awaitHandlers)))}async handleLLMError(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;if(!A.ignoreLLM)try{await((E=A.handleLLMError)==null?void 0:E.call(A,n,this.runId,this._parentRunId,this.tags,g))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleLLMError: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}async handleLLMEnd(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;if(!A.ignoreLLM)try{await((E=A.handleLLMEnd)==null?void 0:E.call(A,n,this.runId,this._parentRunId,this.tags,g))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleLLMEnd: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}};e($yr,"CallbackManagerForLLMRun");M3t=$yr,Hyr=class Hyr extends vBe{getChild(n){let a=new _me(this.runId);return a.setHandlers(this.inheritableHandlers),a.addTags(this.inheritableTags),a.addMetadata(this.inheritableMetadata),n&&a.addTags([n],!1),a}async handleChainError(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;if(!A.ignoreChain)try{await((E=A.handleChainError)==null?void 0:E.call(A,n,this.runId,this._parentRunId,this.tags,g))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleChainError: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}async handleChainEnd(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;if(!A.ignoreChain)try{await((E=A.handleChainEnd)==null?void 0:E.call(A,n,this.runId,this._parentRunId,this.tags,g))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleChainEnd: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}async handleAgentAction(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreAgent)try{await((u=a.handleAgentAction)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleAgentAction: ${f}`),a.raiseError)throw f}},a.awaitHandlers)))}async handleAgentEnd(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreAgent)try{await((u=a.handleAgentEnd)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleAgentEnd: ${f}`),a.raiseError)throw f}},a.awaitHandlers)))}};e(Hyr,"CallbackManagerForChainRun");Qyr=Hyr,Gyr=class Gyr extends vBe{getChild(n){let a=new _me(this.runId);return a.setHandlers(this.inheritableHandlers),a.addTags(this.inheritableTags),a.addMetadata(this.inheritableMetadata),n&&a.addTags([n],!1),a}async handleToolError(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreAgent)try{await((u=a.handleToolError)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolError: ${f}`),a.raiseError)throw f}},a.awaitHandlers)))}async handleToolEnd(n){await Promise.all(this.handlers.map(a=>ik(async()=>{var u;if(!a.ignoreAgent)try{await((u=a.handleToolEnd)==null?void 0:u.call(a,n,this.runId,this._parentRunId,this.tags))}catch(f){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolEnd: ${f}`),a.raiseError)throw f}},a.awaitHandlers)))}};e(Gyr,"CallbackManagerForToolRun");Uyr=Gyr,uDe=class uDe extends Myr{constructor(n,a){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=(a==null?void 0:a.handlers)??this.handlers,this.inheritableHandlers=(a==null?void 0:a.inheritableHandlers)??this.inheritableHandlers,this.tags=(a==null?void 0:a.tags)??this.tags,this.inheritableTags=(a==null?void 0:a.inheritableTags)??this.inheritableTags,this.metadata=(a==null?void 0:a.metadata)??this.metadata,this.inheritableMetadata=(a==null?void 0:a.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,a,u=void 0,f=void 0,g=void 0,A=void 0,E=void 0,D=void 0){return Promise.all(a.map(async(F,P)=>{let Q=P===0&&u?u:pB();return await Promise.all(this.handlers.map(R=>{if(!R.ignoreLLM)return gBe(R)&&R._createRunForLLMStart(n,[F],Q,this._parentRunId,g,this.tags,this.metadata,D),ik(async()=>{var W;try{await((W=R.handleLLMStart)==null?void 0:W.call(R,n,[F],Q,this._parentRunId,g,this.tags,this.metadata,D))}catch(q){if((R.raiseError?console.error:console.warn)(`Error in handler ${R.constructor.name}, handleLLMStart: ${q}`),R.raiseError)throw q}},R.awaitHandlers)})),new M3t(Q,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,a,u=void 0,f=void 0,g=void 0,A=void 0,E=void 0,D=void 0){return Promise.all(a.map(async(F,P)=>{let Q=P===0&&u?u:pB();return await Promise.all(this.handlers.map(R=>{if(!R.ignoreLLM)return gBe(R)&&R._createRunForChatModelStart(n,[F],Q,this._parentRunId,g,this.tags,this.metadata,D),ik(async()=>{var W,q;try{if(R.handleChatModelStart)await((W=R.handleChatModelStart)==null?void 0:W.call(R,n,[F],Q,this._parentRunId,g,this.tags,this.metadata,D));else if(R.handleLLMStart){let $=yyr(F);await((q=R.handleLLMStart)==null?void 0:q.call(R,n,[$],Q,this._parentRunId,g,this.tags,this.metadata,D))}}catch($){if((R.raiseError?console.error:console.warn)(`Error in handler ${R.constructor.name}, handleLLMStart: ${$}`),R.raiseError)throw $}},R.awaitHandlers)})),new M3t(Q,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,a,u=pB(),f=void 0,g=void 0,A=void 0,E=void 0){return await Promise.all(this.handlers.map(D=>{if(!D.ignoreChain)return gBe(D)&&D._createRunForChainStart(n,a,u,this._parentRunId,this.tags,this.metadata,f,E),ik(async()=>{var F;try{await((F=D.handleChainStart)==null?void 0:F.call(D,n,a,u,this._parentRunId,this.tags,this.metadata,f,E))}catch(P){if((D.raiseError?console.error:console.warn)(`Error in handler ${D.constructor.name}, handleChainStart: ${P}`),D.raiseError)throw P}},D.awaitHandlers)})),new Qyr(u,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,a,u=pB(),f=void 0,g=void 0,A=void 0,E=void 0){return await Promise.all(this.handlers.map(D=>{if(!D.ignoreAgent)return gBe(D)&&D._createRunForToolStart(n,a,u,this._parentRunId,this.tags,this.metadata,E),ik(async()=>{var F;try{await((F=D.handleToolStart)==null?void 0:F.call(D,n,a,u,this._parentRunId,this.tags,this.metadata,E))}catch(P){if((D.raiseError?console.error:console.warn)(`Error in handler ${D.constructor.name}, handleToolStart: ${P}`),D.raiseError)throw P}},D.awaitHandlers)})),new Uyr(u,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,a,u=pB(),f=void 0,g=void 0,A=void 0,E=void 0){return await Promise.all(this.handlers.map(D=>{if(!D.ignoreRetriever)return gBe(D)&&D._createRunForRetrieverStart(n,a,u,this._parentRunId,this.tags,this.metadata,E),ik(async()=>{var F;try{await((F=D.handleRetrieverStart)==null?void 0:F.call(D,n,a,u,this._parentRunId,this.tags,this.metadata,E))}catch(P){if((D.raiseError?console.error:console.warn)(`Error in handler ${D.constructor.name}, handleRetrieverStart: ${P}`),D.raiseError)throw P}},D.awaitHandlers)})),new jyr(u,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,a,u,f,g){await Promise.all(this.handlers.map(A=>ik(async()=>{var E;if(!A.ignoreCustomEvent)try{await((E=A.handleCustomEvent)==null?void 0:E.call(A,n,a,u,this.tags,this.metadata))}catch(D){if((A.raiseError?console.error:console.warn)(`Error in handler ${A.constructor.name}, handleCustomEvent: ${D}`),A.raiseError)throw D}},A.awaitHandlers)))}addHandler(n,a=!0){this.handlers.push(n),a&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(a=>a!==n),this.inheritableHandlers=this.inheritableHandlers.filter(a=>a!==n)}setHandlers(n,a=!0){this.handlers=[],this.inheritableHandlers=[];for(let u of n)this.addHandler(u,a)}addTags(n,a=!0){this.removeTags(n),this.tags.push(...n),a&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(a=>!n.includes(a)),this.inheritableTags=this.inheritableTags.filter(a=>!n.includes(a))}addMetadata(n,a=!0){this.metadata={...this.metadata,...n},a&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(let a of Object.keys(n))delete this.metadata[a],delete this.inheritableMetadata[a]}copy(n=[],a=!0){let u=new uDe(this._parentRunId);for(let f of this.handlers){let g=this.inheritableHandlers.includes(f);u.addHandler(f,g)}for(let f of this.tags){let g=this.inheritableTags.includes(f);u.addTags([f],g)}for(let f of Object.keys(this.metadata)){let g=Object.keys(this.inheritableMetadata).includes(f);u.addMetadata({[f]:this.metadata[f]},g)}for(let f of n)u.handlers.filter(g=>g.name==="console_callback_handler").some(g=>g.name===f.name)||u.addHandler(f,a);return u}static fromHandlers(n){let f=class f extends sDe{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:pB()}),Object.assign(this,n)}};e(f,"Handler");let a=f,u=new this;return u.addHandler(new a),u}static configure(n,a,u,f,g,A,E){return this._configureSync(n,a,u,f,g,A,E)}static _configureSync(n,a,u,f,g,A,E){var R,W;let D;(n||a)&&(Array.isArray(n)||!n?(D=new uDe,D.setHandlers((n==null?void 0:n.map(qyr))??[],!0)):D=n,D=D.copy(Array.isArray(a)?a.map(qyr):a==null?void 0:a.handlers,!1));let F=jz("LANGCHAIN_VERBOSE")==="true"||(E==null?void 0:E.verbose),P=((R=yBe.getTraceableRunTree())==null?void 0:R.tracingEnabled)||Hin(),Q=P||(jz("LANGCHAIN_TRACING")??!1);if(F||Q){if(D||(D=new uDe),F&&!D.handlers.some(q=>q.name===LXe.prototype.name)){let q=new LXe;D.addHandler(q,!0)}if(Q&&!D.handlers.some(q=>q.name==="langchain_tracer")&&P){let q=new yBe;D.addHandler(q,!0),D._parentRunId=((W=yBe.getTraceableRunTree())==null?void 0:W.id)??D._parentRunId}}for(let{contextVar:q,inheritable:$=!0,handlerClass:le,envVar:fe}of zin()){let me=fe&&jz(fe)==="true"&&le,De,Pe=q!==void 0?Lyr(q):void 0;Pe&&Nin(Pe)?De=Pe:me&&(De=new le({})),De!==void 0&&(D||(D=new uDe),D.handlers.some(ze=>ze.name===De.name)||D.addHandler(De,$))}return(u||f)&&D&&(D.addTags(u??[]),D.addTags(f??[],!1)),(g||A)&&D&&(D.addMetadata(g??{}),D.addMetadata(A??{},!1)),D}};e(uDe,"CallbackManager");_me=uDe;e(qyr,"ensureHandler")});var Kyr,Q3t,EAi,Yin,Yyr,zyr,QXe,Xin=ud(()=>{h3t();MXe();j3t();Kyr=class Kyr{getStore(){}run(n,a){return a()}enterWith(n){}};e(Kyr,"MockAsyncLocalStorage");Q3t=Kyr,EAi=new Q3t,Yin=Symbol.for("lc:child_config"),Yyr=class Yyr{getInstance(){return Zxe()??EAi}getRunnableConfig(){var a,u;return(u=(a=this.getInstance().getStore())==null?void 0:a.extra)==null?void 0:u[Yin]}runWithConfig(n,a,u){var P;let f=_me._configureSync(n==null?void 0:n.callbacks,void 0,n==null?void 0:n.tags,void 0,n==null?void 0:n.metadata),g=this.getInstance(),A=g.getStore(),E=f==null?void 0:f.getParentRunId(),D=(P=f==null?void 0:f.handlers)==null?void 0:P.find(Q=>(Q==null?void 0:Q.name)==="langchain_tracer"),F;return D&&E?F=D.convertToRunTree(E):u||(F=new Mle({name:"<runnable_lambda>",tracingEnabled:!1})),F&&(F.extra={...F.extra,[Yin]:n}),A!==void 0&&A[cDe]!==void 0&&(F===void 0&&(F={}),F[cDe]=A[cDe]),g.run(F,a)}initializeGlobalInstance(n){Zxe()===void 0&&Jin(n)}};e(Yyr,"AsyncLocalStorageProvider");zyr=Yyr,QXe=new zyr});var UXe=ud(()=>{Xin();MXe()});var eAe=ud(()=>{j3t();UXe()});var Xyr=ud(()=>{});var mme=ud(()=>{eAe();UXe();Xyr()});var Zin=ud(()=>{Fin();oDe();mme();_Be()});var evr=ud(()=>{});var ean=ud(()=>{oDe();mme();_Be();evr()});var DAi,SAi,q3t=ud(()=>{DAi=jh(UCt(),1),SAi=jh($Ct(),1)});var tan=ud(()=>{oDe()});var tvr=ud(()=>{});var ran=ud(()=>{});var nan=ud(()=>{lyr();tvr();ran()});var ian=ud(()=>{mme()});var aan=ud(()=>{UXe();eAe()});var IAi,hme=ud(()=>{IAi=jh(UCt(),1);Cyr();Zin();ean();TXe();mme();Xyr();eAe();q3t();tan();tvr();UXe();nan();ian();aan();myr()});var nvr=ud(()=>{zie()});var uan=ud(()=>{hme();_Be();zie();E3t();C3t();NXe();nvr();D3t();PXe();nDe()});var avr=ud(()=>{_Be();zie();E3t();C3t();NXe();D3t();nDe();uan();nvr();dyr();PXe()});function jle(i){i?(wB[0]=wB[16]=wB[1]=wB[2]=wB[3]=wB[4]=wB[5]=wB[6]=wB[7]=wB[8]=wB[9]=wB[10]=wB[11]=wB[12]=wB[13]=wB[14]=wB[15]=0,this.blocks=wB):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var PAi,_A,NAi,Kie,wB,lan=ud(()=>{"use strict";PAi=typeof window=="object"?window:{},_A="0123456789abcdef".split(""),NAi=[-2147483648,8388608,32768,128],Kie=[24,16,8,0],wB=[];e(jle,"Sha1");jle.prototype.update=function(i){if(!this.finalized){var n=typeof i!="string";n&&i.constructor===PAi.ArrayBuffer&&(i=new Uint8Array(i));for(var a,u=0,f,g=i.length||0,A=this.blocks;u<g;){if(this.hashed&&(this.hashed=!1,A[0]=this.block,A[16]=A[1]=A[2]=A[3]=A[4]=A[5]=A[6]=A[7]=A[8]=A[9]=A[10]=A[11]=A[12]=A[13]=A[14]=A[15]=0),n)for(f=this.start;u<g&&f<64;++u)A[f>>2]|=i[u]<<Kie[f++&3];else for(f=this.start;u<g&&f<64;++u)a=i.charCodeAt(u),a<128?A[f>>2]|=a<<Kie[f++&3]:a<2048?(A[f>>2]|=(192|a>>6)<<Kie[f++&3],A[f>>2]|=(128|a&63)<<Kie[f++&3]):a<55296||a>=57344?(A[f>>2]|=(224|a>>12)<<Kie[f++&3],A[f>>2]|=(128|a>>6&63)<<Kie[f++&3],A[f>>2]|=(128|a&63)<<Kie[f++&3]):(a=65536+((a&1023)<<10|i.charCodeAt(++u)&1023),A[f>>2]|=(240|a>>18)<<Kie[f++&3],A[f>>2]|=(128|a>>12&63)<<Kie[f++&3],A[f>>2]|=(128|a>>6&63)<<Kie[f++&3],A[f>>2]|=(128|a&63)<<Kie[f++&3]);this.lastByteIndex=f,this.bytes+=f-this.start,f>=64?(this.block=A[16],this.start=f-64,this.hash(),this.hashed=!0):this.start=f}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};jle.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var i=this.blocks,n=this.lastByteIndex;i[16]=this.block,i[n>>2]|=NAi[n&3],this.block=i[16],n>=56&&(this.hashed||this.hash(),i[0]=this.block,i[16]=i[1]=i[2]=i[3]=i[4]=i[5]=i[6]=i[7]=i[8]=i[9]=i[10]=i[11]=i[12]=i[13]=i[14]=i[15]=0),i[14]=this.hBytes<<3|this.bytes>>>29,i[15]=this.bytes<<3,this.hash()}};jle.prototype.hash=function(){var i=this.h0,n=this.h1,a=this.h2,u=this.h3,f=this.h4,g,A,E,D=this.blocks;for(A=16;A<80;++A)E=D[A-3]^D[A-8]^D[A-14]^D[A-16],D[A]=E<<1|E>>>31;for(A=0;A<20;A+=5)g=n&a|~n&u,E=i<<5|i>>>27,f=E+g+f+1518500249+D[A]<<0,n=n<<30|n>>>2,g=i&n|~i&a,E=f<<5|f>>>27,u=E+g+u+1518500249+D[A+1]<<0,i=i<<30|i>>>2,g=f&i|~f&n,E=u<<5|u>>>27,a=E+g+a+1518500249+D[A+2]<<0,f=f<<30|f>>>2,g=u&f|~u&i,E=a<<5|a>>>27,n=E+g+n+1518500249+D[A+3]<<0,u=u<<30|u>>>2,g=a&u|~a&f,E=n<<5|n>>>27,i=E+g+i+1518500249+D[A+4]<<0,a=a<<30|a>>>2;for(;A<40;A+=5)g=n^a^u,E=i<<5|i>>>27,f=E+g+f+1859775393+D[A]<<0,n=n<<30|n>>>2,g=i^n^a,E=f<<5|f>>>27,u=E+g+u+1859775393+D[A+1]<<0,i=i<<30|i>>>2,g=f^i^n,E=u<<5|u>>>27,a=E+g+a+1859775393+D[A+2]<<0,f=f<<30|f>>>2,g=u^f^i,E=a<<5|a>>>27,n=E+g+n+1859775393+D[A+3]<<0,u=u<<30|u>>>2,g=a^u^f,E=n<<5|n>>>27,i=E+g+i+1859775393+D[A+4]<<0,a=a<<30|a>>>2;for(;A<60;A+=5)g=n&a|n&u|a&u,E=i<<5|i>>>27,f=E+g+f-1894007588+D[A]<<0,n=n<<30|n>>>2,g=i&n|i&a|n&a,E=f<<5|f>>>27,u=E+g+u-1894007588+D[A+1]<<0,i=i<<30|i>>>2,g=f&i|f&n|i&n,E=u<<5|u>>>27,a=E+g+a-1894007588+D[A+2]<<0,f=f<<30|f>>>2,g=u&f|u&i|f&i,E=a<<5|a>>>27,n=E+g+n-1894007588+D[A+3]<<0,u=u<<30|u>>>2,g=a&u|a&f|u&f,E=n<<5|n>>>27,i=E+g+i-1894007588+D[A+4]<<0,a=a<<30|a>>>2;for(;A<80;A+=5)g=n^a^u,E=i<<5|i>>>27,f=E+g+f-899497514+D[A]<<0,n=n<<30|n>>>2,g=i^n^a,E=f<<5|f>>>27,u=E+g+u-899497514+D[A+1]<<0,i=i<<30|i>>>2,g=f^i^n,E=u<<5|u>>>27,a=E+g+a-899497514+D[A+2]<<0,f=f<<30|f>>>2,g=u^f^i,E=a<<5|a>>>27,n=E+g+n-899497514+D[A+3]<<0,u=u<<30|u>>>2,g=a^u^f,E=n<<5|n>>>27,i=E+g+i-899497514+D[A+4]<<0,a=a<<30|a>>>2;this.h0=this.h0+i<<0,this.h1=this.h1+n<<0,this.h2=this.h2+a<<0,this.h3=this.h3+u<<0,this.h4=this.h4+f<<0};jle.prototype.hex=function(){this.finalize();var i=this.h0,n=this.h1,a=this.h2,u=this.h3,f=this.h4;return _A[i>>28&15]+_A[i>>24&15]+_A[i>>20&15]+_A[i>>16&15]+_A[i>>12&15]+_A[i>>8&15]+_A[i>>4&15]+_A[i&15]+_A[n>>28&15]+_A[n>>24&15]+_A[n>>20&15]+_A[n>>16&15]+_A[n>>12&15]+_A[n>>8&15]+_A[n>>4&15]+_A[n&15]+_A[a>>28&15]+_A[a>>24&15]+_A[a>>20&15]+_A[a>>16&15]+_A[a>>12&15]+_A[a>>8&15]+_A[a>>4&15]+_A[a&15]+_A[u>>28&15]+_A[u>>24&15]+_A[u>>20&15]+_A[u>>16&15]+_A[u>>12&15]+_A[u>>8&15]+_A[u>>4&15]+_A[u&15]+_A[f>>28&15]+_A[f>>24&15]+_A[f>>20&15]+_A[f>>16&15]+_A[f>>12&15]+_A[f>>8&15]+_A[f>>4&15]+_A[f&15]};jle.prototype.toString=jle.prototype.hex;jle.prototype.digest=function(){this.finalize();var i=this.h0,n=this.h1,a=this.h2,u=this.h3,f=this.h4;return[i>>24&255,i>>16&255,i>>8&255,i&255,n>>24&255,n>>16&255,n>>8&255,n&255,a>>24&255,a>>16&255,a>>8&255,a&255,u>>24&255,u>>16&255,u>>8&255,u&255,f>>24&255,f>>16&255,f>>8&255,f&255]};jle.prototype.array=jle.prototype.digest;jle.prototype.arrayBuffer=function(){this.finalize();var i=new ArrayBuffer(20),n=new DataView(i);return n.setUint32(0,this.h0),n.setUint32(4,this.h1),n.setUint32(8,this.h2),n.setUint32(12,this.h3),n.setUint32(16,this.h4),i}});var pan=ud(()=>{lan()});var fan=ud(()=>{pan();nDe()});var dan=ud(()=>{TXe();NXe();nDe()});var han=rn(J3t=>{"use strict";J3t.byteLength=RAi;J3t.toByteArray=MAi;J3t.fromByteArray=UAi;var Qle=[],hee=[],OAi=typeof Uint8Array<"u"?Uint8Array:Array,svr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(lDe=0,_an=svr.length;lDe<_an;++lDe)Qle[lDe]=svr[lDe],hee[svr.charCodeAt(lDe)]=lDe;var lDe,_an;hee[45]=62;hee[95]=63;function man(i){var n=i.length;if(n%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var a=i.indexOf("=");a===-1&&(a=n);var u=a===n?0:4-a%4;return[a,u]}e(man,"getLens");function RAi(i){var n=man(i),a=n[0],u=n[1];return(a+u)*3/4-u}e(RAi,"byteLength");function LAi(i,n,a){return(n+a)*3/4-a}e(LAi,"_byteLength");function MAi(i){var n,a=man(i),u=a[0],f=a[1],g=new OAi(LAi(i,u,f)),A=0,E=f>0?u-4:u,D;for(D=0;D<E;D+=4)n=hee[i.charCodeAt(D)]<<18|hee[i.charCodeAt(D+1)]<<12|hee[i.charCodeAt(D+2)]<<6|hee[i.charCodeAt(D+3)],g[A++]=n>>16&255,g[A++]=n>>8&255,g[A++]=n&255;return f===2&&(n=hee[i.charCodeAt(D)]<<2|hee[i.charCodeAt(D+1)]>>4,g[A++]=n&255),f===1&&(n=hee[i.charCodeAt(D)]<<10|hee[i.charCodeAt(D+1)]<<4|hee[i.charCodeAt(D+2)]>>2,g[A++]=n>>8&255,g[A++]=n&255),g}e(MAi,"toByteArray");function jAi(i){return Qle[i>>18&63]+Qle[i>>12&63]+Qle[i>>6&63]+Qle[i&63]}e(jAi,"tripletToBase64");function QAi(i,n,a){for(var u,f=[],g=n;g<a;g+=3)u=(i[g]<<16&16711680)+(i[g+1]<<8&65280)+(i[g+2]&255),f.push(jAi(u));return f.join("")}e(QAi,"encodeChunk");function UAi(i){for(var n,a=i.length,u=a%3,f=[],g=16383,A=0,E=a-u;A<E;A+=g)f.push(QAi(i,A,A+g>E?E:A+g));return u===1?(n=i[a-1],f.push(Qle[n>>2]+Qle[n<<4&63]+"==")):u===2&&(n=(i[a-2]<<8)+i[a-1],f.push(Qle[n>>10]+Qle[n>>4&63]+Qle[n<<2&63]+"=")),f.join("")}e(UAi,"fromByteArray")});function WAi(i,n){let a=Array.from({length:i.length},(u,f)=>({start:f,end:f+1}));for(;a.length>1;){let u=null;for(let f=0;f<a.length-1;f++){let g=i.slice(a[f].start,a[f+1].end),A=n.get(g.join(","));A!=null&&(u==null||A<u[0])&&(u=[A,f])}if(u!=null){let f=u[1];a[f]={start:a[f].start,end:a[f+1].end},a.splice(f+1,1)}else break}return a}function $Ai(i,n){return i.length===1?[n.get(i.join(","))]:WAi(i,n).map(a=>n.get(i.slice(a.start,a.end).join(","))).filter(a=>a!=null)}function HAi(i){return i.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var gan,qAi,VAi,JAi,xBe,ovr,cvr,yan=ud(()=>{gan=jh(han(),1),qAi=Object.defineProperty,VAi=e((i,n,a)=>n in i?qAi(i,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[n]=a,"__defNormalProp"),JAi=e((i,n,a)=>(VAi(i,typeof n!="symbol"?n+"":n,a),a),"__publicField");e(WAi,"bytePairMerge");e($Ai,"bytePairEncode");e(HAi,"escapeRegex");ovr=(xBe=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(n,a){this.patStr=n.pat_str;let u=n.bpe_ranks.split(`
|
|
1497
|
-
`).filter(Boolean).reduce((f,g)=>{let[A,E,...D]=g.split(" "),F=Number.parseInt(E,10);return D.forEach((P,Q)=>f[P]=F+Q),f},{});for(let[f,g]of Object.entries(u)){let A=gan.default.toByteArray(f);this.rankMap.set(A.join(","),g),this.textMap.set(g,A)}this.specialTokens={...n.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((f,[g,A])=>(f[A]=this.textEncoder.encode(g),f),{})}encode(n,a=[],u="all"){let f=new RegExp(this.patStr,"ug"),g=ovr.specialTokenRegex(Object.keys(this.specialTokens)),A=[],E=new Set(a==="all"?Object.keys(this.specialTokens):a),D=new Set(u==="all"?Object.keys(this.specialTokens).filter(P=>!E.has(P)):u);if(D.size>0){let P=ovr.specialTokenRegex([...D]),Q=n.match(P);if(Q!=null)throw new Error(`The text contains a special token that is not allowed: ${Q[0]}`)}let F=0;for(;;){let P=null,Q=F;for(;g.lastIndex=Q,P=g.exec(n),!(P==null||E.has(P[0]));)Q=P.index+1;let R=(P==null?void 0:P.index)??n.length;for(let q of n.substring(F,R).matchAll(f)){let $=this.textEncoder.encode(q[0]),le=this.rankMap.get($.join(","));if(le!=null){A.push(le);continue}A.push(...$Ai($,this.rankMap))}if(P==null)break;let W=this.specialTokens[P[0]];A.push(W),F=P.index+P[0].length}return A}decode(n){let a=[],u=0;for(let A=0;A<n.length;++A){let E=n[A],D=this.textMap.get(E)??this.inverseSpecialTokens[E];D!=null&&(a.push(D),u+=D.length)}let f=new Uint8Array(u),g=0;for(let A of a)f.set(A,g),g+=A.length;return this.textDecoder.decode(f)}},e(xBe,"_Tiktoken"),xBe),cvr=ovr;JAi(cvr,"specialTokenRegex",i=>new RegExp(i.map(n=>HAi(n)).join("|"),"g"))});var van=ud(()=>{yan()});var xan=ud(()=>{van();q3t()});var Aan=ud(()=>{fan();dan();nDe();q3t();xan();hme()});var $3t=ud(()=>{mme();hme();eAe()});var ban=ud(()=>{});var Can=ud(()=>{lyr();avr();evr();Aan();j3t();hme();mme();$3t();ban();O3t()});var Dan=ud(()=>{Can()});var San=ud(()=>{hme();eAe()});var wan=ud(()=>{hme();eAe();mme()});var kan=ud(()=>{avr();hme();$3t()});var Ian=ud(()=>{hme();eAe();$3t();San();wan();kan()});var Fan=ud(()=>{Ian()});var ptr=(u=>(u.Alert="alert",u.Confirm="confirm",u.Prompt="prompt",u))(ptr||{});var _5=e(i=>new Promise(n=>setTimeout(n,i)),"awaitSleep"),ow=e(async(i,n=1e3,a)=>{if(n===null)return i;let u="guard-timed-out",f=e(async()=>(await _5(n+1e3),u),"guard"),g=await Promise.race([i,f()]);if(typeof g=="string"&&g===u)throw typeof a=="function"?new Error(a()):new Error(a??"guardReturnTimedOut");return g},"guardReturn");function _vt(i){return!!i&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(i)}e(_vt,"isActionOnElement");function bDr(i){return{click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",upload_files:"upload_files",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",reset:void 0,save:void 0,fail:void 0,wait:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,get_more_items:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0}[i]}e(bDr,"getActionEventCode");var Ave=e((i,n="page")=>n+"."+EDr(i,n),"injectBaseToLocatorString"),EDr=e((i,n="page")=>i.replace(".and(locator(",`.and(${n}.locator(`).replace(".or(locator(",`.or(${n}.locator(`),"injectBaseToLogicalLocatorString");var sIe=(F=>(F.Locator="locator",F.GetByRole="getByRole",F.GetByText="getByText",F.GetByLabel="getByLabel",F.GetByPlaceholder="getByPlaceholder",F.GetByAltText="getByAltText",F.GetByTitle="getByTitle",F.GetByTestId="getByTestId",F.FrameLocator="frameLocator",F))(sIe||{});var ftr=(P=>(P.UploadsCompleteWithErrors="uploads-complete-with-errors",P.UploadsComplete="uploads-complete",P.ReportComplete="report-complete",P.UploadProgress="upload-progress",P.Log="log",P.Trace="trace",P.PlaywrightConfig="playwrightConfig",P.Port="port",P.ChecksumTestMetadata="checksumTestMetadata",P.LogMemoryUsage="log-memory-usage",P))(ftr||{});var mvt="checksum";var XF=jh(require("path")),l_e=require("fs");async function wDr(i,n){let u=e(()=>{let D=eDn(i,n);if((0,l_e.existsSync)(D)||D.endsWith(".data")&&(D=D.replace(".data",".esra"),(0,l_e.existsSync)(D)))return D;throw new Error(`Could not find metadata file for test ${n}`)},"getFilePath")(),{ungzip:f}=SDr(),g=await f((0,l_e.readFileSync)(u)),A=JSON.parse(g),E=Object.keys(A);return E.length>0&&!A[E[0]].esraMetadata?E.reduce((D,F)=>({...D,[F]:{esraMetadata:A[F]}}),{}):A}e(wDr,"getMetadataForTestId");function eDn(i,n){return XF.join(tDn(i),`${n}.checksum.data`)}e(eDn,"getMetadataFilePath");function tDn(i){return XF.join(TDr(i),"esra")}e(tDn,"getMetadataFolderPath");function TDr(i){return XF.join(i,"test-data")}e(TDr,"getTestDataPath");var dtr=e(i=>{console.log("\x1B[31m%s\x1B[0m",i)},"printError"),kDr=e((i,n,a)=>{if(!n)return i;if(!a||!a.length)return i.locator(n);let u=i.frameLocator(a[0]);for(let f of a.slice(1))u=u.frameLocator(f);return u.locator(n)},"makeLocator");function IDr({isInit:i,excludeLogin:n}){return[...i?["example.checksum.spec.ts","github-actions.example.yml"]:[],...n?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example","tsconfig.json"]}e(IDr,"getRuntimeFiles");function FDr(i,n){try{let a=i.filter(u=>u.endsWith("checksum.config.ts")&&XF.dirname(u).endsWith("checksum"));return a.find(u=>u==="checksum/checksum.config.ts")?"checksum":a.length===1?XF.dirname(a[0]):n?XF.dirname(rDn(a,n)):XF.dirname(a.sort((u,f)=>f.length-u.length)[0])}catch{return"checksum"}}e(FDr,"findChecksumRootFolder");function rDn(i,n){let a=e(E=>E.split(XF.sep).filter(D=>D.length>0),"splitPath"),u=e((E,D)=>{let F=a(E),P=a(D),Q=Math.min(F.length,P.length),R=Math.abs(F.length-P.length);for(let W=0;W<Q;W++)if(F[W]!==P[W]){R+=2*(Q-W);break}return R},"directoryDistance"),f=null,g=1/0,A=XF.dirname(n);return i.forEach(E=>{let D=u(A,E);D<g&&(g=D,f=E)}),f}e(rDn,"getClosestPath");function PDr(i,n=2){let a=[],u=[],f=e(A=>{if(a.includes(A))return;a.push(A);let E=(0,l_e.readdirSync)(A);for(let D of E){let F=XF.join(A,D),P=(0,l_e.statSync)(F);if(!(P.isSymbolicLink()||F.includes("node_modules"))){if(P.isDirectory())f(F);else if(D==="checksum.config.ts"){u.push(F);return}}}},"searchDirectory"),g=XF.dirname(i);try{for(let A=0;A<n&&(f(g),g=XF.join(g,".."),A===n-1&&A<9&&!u.length&&(n+=2),!(XF.resolve(g)==="/"||!g||XF.resolve(g)===XF.resolve(process.cwd())));A++);return u}catch{return u}}e(PDr,"findChecksumRootQualifyingPathsForTestFile");var BDr=jh(NDr());var mtr=class mtr{constructor(n){this.toJSON=e(()=>this.data,"toJSON");this.data=n}getSimilar(n){let a=null,u=-1/0;for(let f of Object.keys(this.data)){let g=(0,BDr.levenshtein)([...n],[...f]);g>u&&(u=g,a=f)}return a?this.data[a]:null}};e(mtr,"SimilarityRecord");var _tr=mtr,bve=class bve extends _tr{constructor(n){super(bve.preprocessRectangles(n))}getRectangleByTextAndSizeRanking(n,a){a=!a||!Number(a)?0:Number(a);let u=this.getSimilar(n);if(!u||u.length===0)return null;let f=Math.min(Math.max(a,0),u.length-1);return u[f]}};e(bve,"RectangleIndex"),bve.preprocessRectangles=e(n=>{let a=[...new Map([...n].map(f=>[JSON.stringify(f.vertices),f])).values()],u={};return a.forEach(f=>{u[f.text]||(u[f.text]=[]),u[f.text].push(f),u[f.text].sort((g,A)=>{let E=bve.calculateArea(g.vertices),D=bve.calculateArea(A.vertices);return E-D})}),u},"preprocessRectangles"),bve.calculateArea=e(n=>{let a=Math.abs(n[1].x-n[0].x),u=Math.abs(n[3].y-n[0].y);return a*u},"calculateArea");var yvt=bve;var MDr=require("fs"),jDr=require("path");function p_e(i){return i._guid}e(p_e,"getPageOrFrameGuid");async function ODr(i,n,a){let u=i,f=u._mainFrame;try{u._mainFrame=n,await a(u)}finally{u._mainFrame=f}}e(ODr,"executeOnPageWithFrame");var nDn={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},htr={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},iDn=Object.fromEntries(Object.entries(htr).map(i=>i.reverse())),gtr={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},aDn=Object.fromEntries(Object.entries(gtr).map(i=>i.reverse()));var LDr={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},QHe={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var sDn="variableStore",cIe=sDn+".";var oDn=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(i,n,a,u,f,g,A){this.evaluateWithChecksum=i;this.getFrame=n;this.getTimeMachine=a;this.logger=u;this.options=f;this.pageInteractorAPI=g;this.loginFunction=A;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",i=>{this.newPagesIds.push(i._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async i=>{this.logger.log("File chooser event detected"),this.fileChooser=i},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((i=!0,n=1e4)=>new Promise(a=>{let f=0,g=e(()=>{if(this.activeDialog){let A=this.activeDialog;i&&(this.activeDialog=null),a(A)}else f>=n?a(null):(f+=1e3,setTimeout(g,1e3))},"checkDialog");g()}),"waitForDialog");this.performFileUploadAction=e(async(i,n)=>{if(!await i.evaluate(u=>u.tagName==="INPUT"&&u.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let a=n.files.map(u=>(0,jDr.join)(this.options.testAssetsDir,u)).filter(u=>(0,MDr.existsSync)(u)?!0:(this.logger.log(`Upload file not found: ${u}. Filtering out.`),!1));if(!a.length)throw new Error("No files to upload");await this.actionGuardReturn(i.setInputFiles(a),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(i,n)=>i.checksumid?this.getSelectionDataForChecksumId(i.checksumid,n):i.position?await this.evaluateWithChecksum(async([a,u])=>window.checksum.testGenerator.getSelectorByPosition(a,u),[i.position.x,i.position.y]):i.selector?{selector:i.selector,locator:`locator("${i.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async i=>{this.activeDialog=i},this.getPage().on("dialog",this.listeners.dialog)}removeListener(i){try{switch(i){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(i,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(i,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(i,this.listeners.page),this.listeners.page=null;break}}catch(n){this.logger.logError(`Error removing listener: ${i}`,n)}}getOpenedFileChooser(){if(this.fileChooser){let i=this.fileChooser;return this.fileChooser=void 0,i}return null}async handleFileChooserEvent(i=[]){let n=this.getOpenedFileChooser();if(!n)return{};let a="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([u,f])=>{window.checksum.testGenerator.addForceIncludeElement(f,u)},[a,n.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:a,customFiles:i}}}async addMoreItemsToDom(i,n){let a=i.querySelector(`[checksum-get-more-items='${n}']`);if(!a)throw new Error("Get more items root not found");let{items:u,hasMoreItems:f}=await this.getMoreItemsForTemplate(n);a.innerHTML=a.innerHTML+u,f||a.removeAttribute("checksum-get-more-items")}async getPageInfo(i){let n=p_e(i);return{id:n,url:i.url(),title:await i.title(),new:this.newPagesIds.includes(n),active:n===p_e(this.getPage())}}async getTabsInfo(){var u;let i=this.getPage(),n=await Promise.all(i.context().pages().map(f=>this.getPageInfo(f))),a=(u=this.getTimeMachine())==null?void 0:u.getPage();return a&&a!==i&&(n=n.filter(f=>f.id!==p_e(a))),this.newPagesIds=[],n}async getSelectionDataFromSelectorGenerator(i,n,a={}){if(a={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...a},!i||!_vt(bDr(n.action.type))||!n.action.checksumid)return{};let u=await i.generateSelectionForAction(n,a);return u?{locator:`locator("${u.selector}")`,...u}:{}}async translateActionResponseToAgentPotentialAction(i,n=void 0,{pageId:a}={}){let u=structuredClone(i.actionHiddenOverride??i.action),{selector:f,selectorWithVars:g,locator:A,locatorWithVars:E,clickOffset:D,selectOptionValue:F,compoundSelector:P,alternateLocators:Q,parentFramesSelectors:R}={...await this.getSelectionDataForAction(u,i.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(n,i)},W=await this.getESRAForSelector(f,R);if(!W&&f&&this.logger.logError("Error getting ESRA metadata"),(W==null?void 0:W.tag)==="select")switch(this.getActionEventCode(u.type)){case"input":u.type="selectoption";break;case"click":F&&(u.type="selectoption",u.value=F);break}let q={eventCode:this.getActionEventCode(u.type),selector:f,selectorWithVars:g,parentFramesSelectors:R,locator:A,locatorWithVars:E,clickOffset:D,pageId:a,compoundSelector:P,alternateLocators:Q,fillValue:u.value,fillValueName:u.valueName?`${cIe}${u.valueName}`:"",variables:i.variables,getMoreItemsId:u.getMoreItemsId,esraMetadata:W,thought:i.thought,userRole:u.userRole,canvas:u.canvas,id:u.id,codeContext:{frameTargetName:null}};switch(q.eventCode){case"drag_and_drop":{let{selector:$,selectorWithVars:le,locator:fe,locatorWithVars:me,parentFramesSelectors:De}={...await this.getSelectionDataForAction({type:i.action.type,checksumid:i.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(n,{...i,action:{type:i.action.type,checksumid:i.action.dropTargetChecksumid}},{useCompoundSelector:!1})};q.dropTarget={selector:$,locator:fe,parentFramesSelectors:De,esraMetadata:await this.getESRAForSelector($,De)}}break;case"upload_files":q.files=this.mapFileMIMETypeToFilename(u.files);break;case"switch_tab":{let $=this.getPage();q.switchToTab={id:u.tabId,index:$.context().pages().findIndex(le=>p_e(le)===u.tabId)};break}case"keystroke":q.fillValue=u.value}return q}async reauthenticate(i,n){let a=this.getPage();this.loginFunction&&(await Promise.all([a.context().clearCookies(),a.evaluate(()=>localStorage.clear())]),await this.loginFunction(n??a,{role:i}))}mapFileMIMETypeToFilename(i){return i.map(n=>{if(n.fileName)return n.fileName;switch(n.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(i,{useLocator:n=!1,handleActionFailed:a,monitorFlashingHTML:u=!0,timeout:f,allowForceClick:g=!0}={}){try{if(i.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let A=n?!!i.locator:!!i.selector;if(_vt(i.eventCode)&&!A)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");u&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${i.eventCode}. Selector: ${i.selector}, Position: ${i.clickOffset}, Parent frame: ${i.parentFramesSelectors}`);let E=e(()=>n?this.makeLocatorFromLocator(i.locator):this.makeLocator(i.selector,i.parentFramesSelectors),"getLocator"),D=e(async(F,P,Q={})=>this.actionGuardReturn(F,P,{timeout:f,...Q}),"performWithActionGuard");switch(i.eventCode){case"click":try{await D(E().click({position:i.clickOffset,timeout:f??this.options.actionTimeout}),"Click timeout")}catch(F){if(!g)throw F;this.logger.log("Error performing click, will attempt a force click",F.message),i.force=!0,await D(E().click({position:i.clickOffset,force:!0,timeout:f??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await D(E().dblclick({position:i.clickOffset,timeout:f??this.options.actionTimeout}),"DoubleClick timeout")}catch(F){if(!g)throw F;this.logger.log("Error performing double click, will attempt a force double click",F),i.force=!0,await D(E().dblclick({position:i.clickOffset,timeout:f??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await D(E().check({timeout:f??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await D(E().uncheck({timeout:f??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await D(E().dragTo(n?this.makeLocatorFromLocator(i.dropTarget.locator):this.makeLocator(i.dropTarget.selector,i.dropTarget.parentFramesSelectors),{timeout:f??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await D(E().fill(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await ow(E().click({position:i.clickOffset,timeout:f??this.options.actionTimeout}),1e4,"Click before type timeout"),await ow(E().pressSequentially(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await ow(E().clear({timeout:f??this.options.actionTimeout}),1e4,"Clear before type timeout"),await ow(E().pressSequentially(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await D(E().selectOption(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await D(E().hover({timeout:f??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await D(this.getFrame().goto(i.fillValue,{timeout:f??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let F=this.getPage();await D(F.keyboard.press(i.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(E(),i);break;case"wait":await _5(this.options.waitActionDelay??1e3);break;case"custom_code":await ODr(this.getPage(),this.getFrame(),async F=>{let P=`async (page) => {${i.fillValue}}`;await(0,eval)(P)(F)});break;case"logout_and_login":await this.reauthenticate(i.userRole);break;case"canvas_click":await this.canvasClick(E(),i.canvas);break}}catch(A){throw this.logger.log(`Error performing action: ${i.eventCode}, will attempt a correction template`,A),await(a==null?void 0:a()),A}this.logger.log(`Successfully performed action ${i.eventCode} with description "${i.thought}"`)}async getTextDetection(i){return new yvt(await this.pageInteractorAPI.getTextDetection(i))}async canvasClick(i,n){try{if(!await i.evaluate(g=>g.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let f=(await this.getTextDetection(await i.screenshot())).getRectangleByTextAndSizeRanking(n.canvasText,n.rectSizeIndex);if(!f)throw new Error(`Canvas click target not found for ${n.canvasText}`);this.logger.log(`Canvas click target: ${f}`),await this.actionGuardReturn(i.click({position:f.center}),"Canvas click could not be performed")}catch(a){throw this.logger.logError("Canvas click:",a.message),new Error("Canvas click action failed")}}getActionFillValue(i,n=!0){let a=i.fillValue;if(!a){let u=i.selector.match(/(?<=value.*)('|").*/);u&&(a=u[0].slice(1,-1))}return typeof a!="string"&&(a="X"),n&&(i.fillValue=a),a}actionGuardReturn(i,n,{isNavigation:a=!1,timeout:u}={}){return ow(i,u??(a?this.options.navigationTimeout:this.options.actionTimeout),n)}makeLocator(i,n=[]){return kDr(this.getFrame(),i,n)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}async takeScreenshot(i){let n=await this.getPage().screenshot({type:"jpeg",scale:"css",timeout:5e3,...i});return{base64:`data:image/jpeg;base64,${n.toString("base64")}`,buffer:n}}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(i,n){if(n!=null&&n.selector)return{...n,selector:n.selector,locator:n.locator,clickOffset:n.position};if(!i)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${i})`),{...n,selector:i,locator:`locator("${i}")`};let a=await this.evaluateWithChecksum(async u=>{let{selector:f,locator:g,clickOffset:A,parentFramesSelectors:E,invalid:D,rrwebId:F}=await window.checksum.testGenerator.getSelectorForChecksumId(u),P=await window.checksum.testGenerator.getElementForChecksumId(u),Q=P instanceof HTMLOptionElement&&P.value?P.value:void 0;return{selector:f,locator:g,clickOffset:A,selectOptionValue:Q,parentFramesSelectors:E,invalid:D,rrwebId:F}},i);if(oDn&&a.invalid&&a.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. Trying to use time machine...`);try{let u=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(a.rrwebId);a={...a,...u}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${i}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${a.selector} for checksumid: ${i} from time machine`)}return a!=null&&a.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),a}async getSelectionDataForRRwebIdAtReduceHTMLTime(i){if(!this.rrwebEventAtLastReducedHTML)return;let n=this.getTimeMachine();if(n)return n.executeTask(a=>a.evaluate(async({rrwebId:u})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(u,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:i}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(i,n){let a=await this.evaluateWithChecksum(async({selector:u,parentFramesSelectors:f})=>window.checksum.testGenerator.getSelectionDataForSelector(u,f),{selector:i,parentFramesSelectors:n});return a==null?void 0:a.esraMetadata}async getMoreItemsForTemplate(i){return await this.evaluateWithChecksum(async n=>window.checksum.testGenerator.getMoreItemsForTemplate(n,{}),i)??{items:"",hasMoreItems:!1}}scrollElementIntoViewByChecksumId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.scrollElementIntoViewByChecksumId(n),i)}scrollElementIntoViewByRrwebId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.scrollElementIntoViewByRrwebId(n),i)}generateLocatorByRrwebId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.generateLocatorByRrwebId(n),i)}getViewportHTML(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.extractViewportHTML())}scrollScrollableElement(i,n,a){return this.evaluateWithChecksum(async({rrwebId:u,direction:f,length:g})=>window.checksum.testGenerator.scrollScrollableElement(u,f,g),{rrwebId:i,direction:n,length:a})}async getCurrentReducedHTML({retriesLeft:i=3,retryWaitMS:n=2e3,initialChecksumId:a="0",extractESRAForInterpretationRequiredElements:u=!1,stopFlashingElementsDetection:f=!1,assignChecksumIdsToAllElements:g}={}){let A=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:E,currentChecksumId:D,flashingHTML:F,elementsForNodeInterpretation:P,lastRRwebEvent:Q,scrollableElements:R}=await this.evaluateWithChecksum(async q=>window.checksum.testGenerator.reduceHTML({},q),{initialChecksumId:a,extractESRAForInterpretationRequiredElements:u,stopFlashingElementsDetection:f,assignChecksumIdsToAllElements:g}),W=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${W.getTime()-A.getTime()}ms`),this.rrwebEventAtLastReducedHTML=Q,{reducedHTML:E,flashingHTML:F,elementsForNodeInterpretation:P,currentChecksumId:D,scrollableElements:R}}catch(E){if(i>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${E.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${n/1e3} seconds, ${i-1} to go.`),await _5(n),this.getCurrentReducedHTML({retriesLeft:i-1,retryWaitMS:n});throw E}}getActionEventCode(i){return htr[i]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var UHe=_TestGenerationPageInteractor;var IKn=jh(oTr());var Uue=jh(require("path")),hnr=require("fs");var lnr=require("path"),dxt=require("fs");function J5n(i,n,a=10){let u=i;for(let f=0;f<a;f++){let g=(0,lnr.join)(u,"package.json");if((0,dxt.existsSync)(g))try{if(JSON.parse((0,dxt.readFileSync)(g,"utf8")).name===n)return u}catch{}u=(0,lnr.join)(u,"..")}}e(J5n,"findRepositoryRoot");function _xt(i,n=10){return J5n(i,"checksum-customer-engineering-workspace",n)}e(_xt,"findCustomerEngineeringRoot");var gnr=jh(fTr());var P4=e((i,n)=>{if(i==null||i==="")return(n==null?void 0:n.default)??!1;let a=i.toLowerCase().trim();return a==="true"?!0:a==="false"?!1:(n==null?void 0:n.default)??!1},"parseBoolean");var sTn=__dirname,dTr=Uue.join(__dirname,".."),hTr=(0,hnr.existsSync)(dTr)?dTr:sTn;(0,gnr.config)({path:Uue.resolve(hTr,".env")});var _nr=P4(process.env.CHECKSUM_RUNTIME_DEV_MODE);function oTn(){let i=__dirname;for(;!(0,hnr.existsSync)(Uue.join(i,"package.json"));)i=Uue.join(i,"..");return i}e(oTn,"findRoot");var RIe=oTn(),cTn=_xt(RIe,10);(0,gnr.config)({path:[hTr,cTn].filter(Boolean).map(i=>Uue.resolve(i,".env")),override:!1});var hxt=P4(process.env.CHECKSUM_VTG_E2E_TEST_MODE),_Tr=Uue.join(RIe,"vtg-build","index.html"),mnr=hxt?!0:P4(process.env.CHECKSUM_RUNTIME_REPO_MODE),mTr=P4(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),uTn=mnr?Uue.join(RIe,"package","pw-report-template.html"):Uue.join(RIe,"pw-report-template.html"),lTn=P4(process.env.CHECKSUM_DEBUG_ANALYTICS),pTn=P4(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),zy={isDevMode:_nr,isRepoMode:mnr,CI:!!process.env.CI,checksumRootFolderBypass:hxt?"packages/runtime/test/e2e/checksum":mnr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(_nr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:RIe+"/checksumlib.js"},runtimeRoot:RIe,playwrightReporter:{htmlReportTemplatePath:uTn},bypassProxyForLocalhost:P4(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:P4(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:P4(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),testRun:{timeMachine:{active:!0,headless:!P4(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:P4(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{segment:{debugAnalytics:lTn,logToConsole:pTn,writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},disableAutoRecovery:P4(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:P4(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME}},vtg:{isSeparateProcess:mTr,isE2ETestMode:hxt,writeLogFile:P4(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(_nr?"served-app":"served-build-file"),localUrl:`file://${_Tr}`,localBuildPath:_Tr,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:P4(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:P4(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||hxt,logAPIServer:{interval:P4(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:P4(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:mTr?!0:P4(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:P4(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:P4(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:P4(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:P4(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:P4(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:P4(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:P4(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:P4(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:P4(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var ynr=jh(require("fs"));function fTn(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(n,a,u)=>u.trimEnd())}e(fTn,"removeTryCatchAndTestInfo");function gTr(i,n){let u=(i.stack||"No stack trace available").split(`
|
|
1497
|
+
`).filter(Boolean).reduce((f,g)=>{let[A,E,...D]=g.split(" "),F=Number.parseInt(E,10);return D.forEach((P,Q)=>f[P]=F+Q),f},{});for(let[f,g]of Object.entries(u)){let A=gan.default.toByteArray(f);this.rankMap.set(A.join(","),g),this.textMap.set(g,A)}this.specialTokens={...n.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((f,[g,A])=>(f[A]=this.textEncoder.encode(g),f),{})}encode(n,a=[],u="all"){let f=new RegExp(this.patStr,"ug"),g=ovr.specialTokenRegex(Object.keys(this.specialTokens)),A=[],E=new Set(a==="all"?Object.keys(this.specialTokens):a),D=new Set(u==="all"?Object.keys(this.specialTokens).filter(P=>!E.has(P)):u);if(D.size>0){let P=ovr.specialTokenRegex([...D]),Q=n.match(P);if(Q!=null)throw new Error(`The text contains a special token that is not allowed: ${Q[0]}`)}let F=0;for(;;){let P=null,Q=F;for(;g.lastIndex=Q,P=g.exec(n),!(P==null||E.has(P[0]));)Q=P.index+1;let R=(P==null?void 0:P.index)??n.length;for(let q of n.substring(F,R).matchAll(f)){let $=this.textEncoder.encode(q[0]),le=this.rankMap.get($.join(","));if(le!=null){A.push(le);continue}A.push(...$Ai($,this.rankMap))}if(P==null)break;let W=this.specialTokens[P[0]];A.push(W),F=P.index+P[0].length}return A}decode(n){let a=[],u=0;for(let A=0;A<n.length;++A){let E=n[A],D=this.textMap.get(E)??this.inverseSpecialTokens[E];D!=null&&(a.push(D),u+=D.length)}let f=new Uint8Array(u),g=0;for(let A of a)f.set(A,g),g+=A.length;return this.textDecoder.decode(f)}},e(xBe,"_Tiktoken"),xBe),cvr=ovr;JAi(cvr,"specialTokenRegex",i=>new RegExp(i.map(n=>HAi(n)).join("|"),"g"))});var van=ud(()=>{yan()});var xan=ud(()=>{van();q3t()});var Aan=ud(()=>{fan();dan();nDe();q3t();xan();hme()});var $3t=ud(()=>{mme();hme();eAe()});var ban=ud(()=>{});var Can=ud(()=>{lyr();avr();evr();Aan();j3t();hme();mme();$3t();ban();O3t()});var Dan=ud(()=>{Can()});var San=ud(()=>{hme();eAe()});var wan=ud(()=>{hme();eAe();mme()});var kan=ud(()=>{avr();hme();$3t()});var Ian=ud(()=>{hme();eAe();$3t();San();wan();kan()});var Fan=ud(()=>{Ian()});var ptr=(u=>(u.Alert="alert",u.Confirm="confirm",u.Prompt="prompt",u))(ptr||{});var _5=e(i=>new Promise(n=>setTimeout(n,i)),"awaitSleep"),ow=e(async(i,n=1e3,a)=>{if(n===null)return i;let u="guard-timed-out",f=e(async()=>(await _5(n+1e3),u),"guard"),g=await Promise.race([i,f()]);if(typeof g=="string"&&g===u)throw typeof a=="function"?new Error(a()):new Error(a??"guardReturnTimedOut");return g},"guardReturn");function _vt(i){return!!i&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(i)}e(_vt,"isActionOnElement");function bDr(i){return{click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",upload_files:"upload_files",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",reset:void 0,save:void 0,fail:void 0,wait:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,get_more_items:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0}[i]}e(bDr,"getActionEventCode");var Ave=e((i,n="page")=>n+"."+EDr(i,n),"injectBaseToLocatorString"),EDr=e((i,n="page")=>i.replace(".and(locator(",`.and(${n}.locator(`).replace(".or(locator(",`.or(${n}.locator(`),"injectBaseToLogicalLocatorString");var sIe=(F=>(F.Locator="locator",F.GetByRole="getByRole",F.GetByText="getByText",F.GetByLabel="getByLabel",F.GetByPlaceholder="getByPlaceholder",F.GetByAltText="getByAltText",F.GetByTitle="getByTitle",F.GetByTestId="getByTestId",F.FrameLocator="frameLocator",F))(sIe||{});var ftr=(F=>(F.UploadsCompleteWithErrors="uploads-complete-with-errors",F.UploadsComplete="uploads-complete",F.ReportComplete="report-complete",F.UploadProgress="upload-progress",F.Log="log",F.Trace="trace",F.PlaywrightConfig="playwrightConfig",F.Port="port",F.ChecksumTestMetadata="checksumTestMetadata",F))(ftr||{});var mvt="checksum";var XF=jh(require("path")),l_e=require("fs");async function wDr(i,n){let u=e(()=>{let D=eDn(i,n);if((0,l_e.existsSync)(D)||D.endsWith(".data")&&(D=D.replace(".data",".esra"),(0,l_e.existsSync)(D)))return D;throw new Error(`Could not find metadata file for test ${n}`)},"getFilePath")(),{ungzip:f}=SDr(),g=await f((0,l_e.readFileSync)(u)),A=JSON.parse(g),E=Object.keys(A);return E.length>0&&!A[E[0]].esraMetadata?E.reduce((D,F)=>({...D,[F]:{esraMetadata:A[F]}}),{}):A}e(wDr,"getMetadataForTestId");function eDn(i,n){return XF.join(tDn(i),`${n}.checksum.data`)}e(eDn,"getMetadataFilePath");function tDn(i){return XF.join(TDr(i),"esra")}e(tDn,"getMetadataFolderPath");function TDr(i){return XF.join(i,"test-data")}e(TDr,"getTestDataPath");var dtr=e(i=>{console.log("\x1B[31m%s\x1B[0m",i)},"printError"),kDr=e((i,n,a)=>{if(!n)return i;if(!a||!a.length)return i.locator(n);let u=i.frameLocator(a[0]);for(let f of a.slice(1))u=u.frameLocator(f);return u.locator(n)},"makeLocator");function IDr({isInit:i,excludeLogin:n}){return[...i?["example.checksum.spec.ts","github-actions.example.yml"]:[],...n?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example","tsconfig.json"]}e(IDr,"getRuntimeFiles");function FDr(i,n){try{let a=i.filter(u=>u.endsWith("checksum.config.ts")&&XF.dirname(u).endsWith("checksum"));return a.find(u=>u==="checksum/checksum.config.ts")?"checksum":a.length===1?XF.dirname(a[0]):n?XF.dirname(rDn(a,n)):XF.dirname(a.sort((u,f)=>f.length-u.length)[0])}catch{return"checksum"}}e(FDr,"findChecksumRootFolder");function rDn(i,n){let a=e(E=>E.split(XF.sep).filter(D=>D.length>0),"splitPath"),u=e((E,D)=>{let F=a(E),P=a(D),Q=Math.min(F.length,P.length),R=Math.abs(F.length-P.length);for(let W=0;W<Q;W++)if(F[W]!==P[W]){R+=2*(Q-W);break}return R},"directoryDistance"),f=null,g=1/0,A=XF.dirname(n);return i.forEach(E=>{let D=u(A,E);D<g&&(g=D,f=E)}),f}e(rDn,"getClosestPath");function PDr(i,n=2){let a=[],u=[],f=e(A=>{if(a.includes(A))return;a.push(A);let E=(0,l_e.readdirSync)(A);for(let D of E){let F=XF.join(A,D),P=(0,l_e.statSync)(F);if(!(P.isSymbolicLink()||F.includes("node_modules"))){if(P.isDirectory())f(F);else if(D==="checksum.config.ts"){u.push(F);return}}}},"searchDirectory"),g=XF.dirname(i);try{for(let A=0;A<n&&(f(g),g=XF.join(g,".."),A===n-1&&A<9&&!u.length&&(n+=2),!(XF.resolve(g)==="/"||!g||XF.resolve(g)===XF.resolve(process.cwd())));A++);return u}catch{return u}}e(PDr,"findChecksumRootQualifyingPathsForTestFile");var BDr=jh(NDr());var mtr=class mtr{constructor(n){this.toJSON=e(()=>this.data,"toJSON");this.data=n}getSimilar(n){let a=null,u=-1/0;for(let f of Object.keys(this.data)){let g=(0,BDr.levenshtein)([...n],[...f]);g>u&&(u=g,a=f)}return a?this.data[a]:null}};e(mtr,"SimilarityRecord");var _tr=mtr,bve=class bve extends _tr{constructor(n){super(bve.preprocessRectangles(n))}getRectangleByTextAndSizeRanking(n,a){a=!a||!Number(a)?0:Number(a);let u=this.getSimilar(n);if(!u||u.length===0)return null;let f=Math.min(Math.max(a,0),u.length-1);return u[f]}};e(bve,"RectangleIndex"),bve.preprocessRectangles=e(n=>{let a=[...new Map([...n].map(f=>[JSON.stringify(f.vertices),f])).values()],u={};return a.forEach(f=>{u[f.text]||(u[f.text]=[]),u[f.text].push(f),u[f.text].sort((g,A)=>{let E=bve.calculateArea(g.vertices),D=bve.calculateArea(A.vertices);return E-D})}),u},"preprocessRectangles"),bve.calculateArea=e(n=>{let a=Math.abs(n[1].x-n[0].x),u=Math.abs(n[3].y-n[0].y);return a*u},"calculateArea");var yvt=bve;var MDr=require("fs"),jDr=require("path");function p_e(i){return i._guid}e(p_e,"getPageOrFrameGuid");async function ODr(i,n,a){let u=i,f=u._mainFrame;try{u._mainFrame=n,await a(u)}finally{u._mainFrame=f}}e(ODr,"executeOnPageWithFrame");var nDn={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},htr={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},iDn=Object.fromEntries(Object.entries(htr).map(i=>i.reverse())),gtr={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},aDn=Object.fromEntries(Object.entries(gtr).map(i=>i.reverse()));var LDr={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},QHe={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var sDn="variableStore",cIe=sDn+".";var oDn=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(i,n,a,u,f,g,A){this.evaluateWithChecksum=i;this.getFrame=n;this.getTimeMachine=a;this.logger=u;this.options=f;this.pageInteractorAPI=g;this.loginFunction=A;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",i=>{this.newPagesIds.push(i._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async i=>{this.logger.log("File chooser event detected"),this.fileChooser=i},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((i=!0,n=1e4)=>new Promise(a=>{let f=0,g=e(()=>{if(this.activeDialog){let A=this.activeDialog;i&&(this.activeDialog=null),a(A)}else f>=n?a(null):(f+=1e3,setTimeout(g,1e3))},"checkDialog");g()}),"waitForDialog");this.performFileUploadAction=e(async(i,n)=>{if(!await i.evaluate(u=>u.tagName==="INPUT"&&u.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let a=n.files.map(u=>(0,jDr.join)(this.options.testAssetsDir,u)).filter(u=>(0,MDr.existsSync)(u)?!0:(this.logger.log(`Upload file not found: ${u}. Filtering out.`),!1));if(!a.length)throw new Error("No files to upload");await this.actionGuardReturn(i.setInputFiles(a),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(i,n)=>i.checksumid?this.getSelectionDataForChecksumId(i.checksumid,n):i.position?await this.evaluateWithChecksum(async([a,u])=>window.checksum.testGenerator.getSelectorByPosition(a,u),[i.position.x,i.position.y]):i.selector?{selector:i.selector,locator:`locator("${i.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async i=>{this.activeDialog=i},this.getPage().on("dialog",this.listeners.dialog)}removeListener(i){try{switch(i){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(i,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(i,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(i,this.listeners.page),this.listeners.page=null;break}}catch(n){this.logger.logError(`Error removing listener: ${i}`,n)}}getOpenedFileChooser(){if(this.fileChooser){let i=this.fileChooser;return this.fileChooser=void 0,i}return null}async handleFileChooserEvent(i=[]){let n=this.getOpenedFileChooser();if(!n)return{};let a="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([u,f])=>{window.checksum.testGenerator.addForceIncludeElement(f,u)},[a,n.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:a,customFiles:i}}}async addMoreItemsToDom(i,n){let a=i.querySelector(`[checksum-get-more-items='${n}']`);if(!a)throw new Error("Get more items root not found");let{items:u,hasMoreItems:f}=await this.getMoreItemsForTemplate(n);a.innerHTML=a.innerHTML+u,f||a.removeAttribute("checksum-get-more-items")}async getPageInfo(i){let n=p_e(i);return{id:n,url:i.url(),title:await i.title(),new:this.newPagesIds.includes(n),active:n===p_e(this.getPage())}}async getTabsInfo(){var u;let i=this.getPage(),n=await Promise.all(i.context().pages().map(f=>this.getPageInfo(f))),a=(u=this.getTimeMachine())==null?void 0:u.getPage();return a&&a!==i&&(n=n.filter(f=>f.id!==p_e(a))),this.newPagesIds=[],n}async getSelectionDataFromSelectorGenerator(i,n,a={}){if(a={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...a},!i||!_vt(bDr(n.action.type))||!n.action.checksumid)return{};let u=await i.generateSelectionForAction(n,a);return u?{locator:`locator("${u.selector}")`,...u}:{}}async translateActionResponseToAgentPotentialAction(i,n=void 0,{pageId:a}={}){let u=structuredClone(i.actionHiddenOverride??i.action),{selector:f,selectorWithVars:g,locator:A,locatorWithVars:E,clickOffset:D,selectOptionValue:F,compoundSelector:P,alternateLocators:Q,parentFramesSelectors:R}={...await this.getSelectionDataForAction(u,i.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(n,i)},W=await this.getESRAForSelector(f,R);if(!W&&f&&this.logger.logError("Error getting ESRA metadata"),(W==null?void 0:W.tag)==="select")switch(this.getActionEventCode(u.type)){case"input":u.type="selectoption";break;case"click":F&&(u.type="selectoption",u.value=F);break}let q={eventCode:this.getActionEventCode(u.type),selector:f,selectorWithVars:g,parentFramesSelectors:R,locator:A,locatorWithVars:E,clickOffset:D,pageId:a,compoundSelector:P,alternateLocators:Q,fillValue:u.value,fillValueName:u.valueName?`${cIe}${u.valueName}`:"",variables:i.variables,getMoreItemsId:u.getMoreItemsId,esraMetadata:W,thought:i.thought,userRole:u.userRole,canvas:u.canvas,id:u.id,codeContext:{frameTargetName:null}};switch(q.eventCode){case"drag_and_drop":{let{selector:$,selectorWithVars:le,locator:fe,locatorWithVars:me,parentFramesSelectors:De}={...await this.getSelectionDataForAction({type:i.action.type,checksumid:i.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(n,{...i,action:{type:i.action.type,checksumid:i.action.dropTargetChecksumid}},{useCompoundSelector:!1})};q.dropTarget={selector:$,locator:fe,parentFramesSelectors:De,esraMetadata:await this.getESRAForSelector($,De)}}break;case"upload_files":q.files=this.mapFileMIMETypeToFilename(u.files);break;case"switch_tab":{let $=this.getPage();q.switchToTab={id:u.tabId,index:$.context().pages().findIndex(le=>p_e(le)===u.tabId)};break}case"keystroke":q.fillValue=u.value}return q}async reauthenticate(i,n){let a=this.getPage();this.loginFunction&&(await Promise.all([a.context().clearCookies(),a.evaluate(()=>localStorage.clear())]),await this.loginFunction(n??a,{role:i}))}mapFileMIMETypeToFilename(i){return i.map(n=>{if(n.fileName)return n.fileName;switch(n.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(i,{useLocator:n=!1,handleActionFailed:a,monitorFlashingHTML:u=!0,timeout:f,allowForceClick:g=!0}={}){try{if(i.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let A=n?!!i.locator:!!i.selector;if(_vt(i.eventCode)&&!A)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");u&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${i.eventCode}. Selector: ${i.selector}, Position: ${i.clickOffset}, Parent frame: ${i.parentFramesSelectors}`);let E=e(()=>n?this.makeLocatorFromLocator(i.locator):this.makeLocator(i.selector,i.parentFramesSelectors),"getLocator"),D=e(async(F,P,Q={})=>this.actionGuardReturn(F,P,{timeout:f,...Q}),"performWithActionGuard");switch(i.eventCode){case"click":try{await D(E().click({position:i.clickOffset,timeout:f??this.options.actionTimeout}),"Click timeout")}catch(F){if(!g)throw F;this.logger.log("Error performing click, will attempt a force click",F.message),i.force=!0,await D(E().click({position:i.clickOffset,force:!0,timeout:f??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await D(E().dblclick({position:i.clickOffset,timeout:f??this.options.actionTimeout}),"DoubleClick timeout")}catch(F){if(!g)throw F;this.logger.log("Error performing double click, will attempt a force double click",F),i.force=!0,await D(E().dblclick({position:i.clickOffset,timeout:f??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await D(E().check({timeout:f??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await D(E().uncheck({timeout:f??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await D(E().dragTo(n?this.makeLocatorFromLocator(i.dropTarget.locator):this.makeLocator(i.dropTarget.selector,i.dropTarget.parentFramesSelectors),{timeout:f??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await D(E().fill(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await ow(E().click({position:i.clickOffset,timeout:f??this.options.actionTimeout}),1e4,"Click before type timeout"),await ow(E().pressSequentially(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await ow(E().clear({timeout:f??this.options.actionTimeout}),1e4,"Clear before type timeout"),await ow(E().pressSequentially(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await D(E().selectOption(this.getActionFillValue(i),{timeout:f??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await D(E().hover({timeout:f??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await D(this.getFrame().goto(i.fillValue,{timeout:f??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let F=this.getPage();await D(F.keyboard.press(i.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(E(),i);break;case"wait":await _5(this.options.waitActionDelay??1e3);break;case"custom_code":await ODr(this.getPage(),this.getFrame(),async F=>{let P=`async (page) => {${i.fillValue}}`;await(0,eval)(P)(F)});break;case"logout_and_login":await this.reauthenticate(i.userRole);break;case"canvas_click":await this.canvasClick(E(),i.canvas);break}}catch(A){throw this.logger.log(`Error performing action: ${i.eventCode}, will attempt a correction template`,A),await(a==null?void 0:a()),A}this.logger.log(`Successfully performed action ${i.eventCode} with description "${i.thought}"`)}async getTextDetection(i){return new yvt(await this.pageInteractorAPI.getTextDetection(i))}async canvasClick(i,n){try{if(!await i.evaluate(g=>g.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let f=(await this.getTextDetection(await i.screenshot())).getRectangleByTextAndSizeRanking(n.canvasText,n.rectSizeIndex);if(!f)throw new Error(`Canvas click target not found for ${n.canvasText}`);this.logger.log(`Canvas click target: ${f}`),await this.actionGuardReturn(i.click({position:f.center}),"Canvas click could not be performed")}catch(a){throw this.logger.logError("Canvas click:",a.message),new Error("Canvas click action failed")}}getActionFillValue(i,n=!0){let a=i.fillValue;if(!a){let u=i.selector.match(/(?<=value.*)('|").*/);u&&(a=u[0].slice(1,-1))}return typeof a!="string"&&(a="X"),n&&(i.fillValue=a),a}actionGuardReturn(i,n,{isNavigation:a=!1,timeout:u}={}){return ow(i,u??(a?this.options.navigationTimeout:this.options.actionTimeout),n)}makeLocator(i,n=[]){return kDr(this.getFrame(),i,n)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}async takeScreenshot(i){let n=await this.getPage().screenshot({type:"jpeg",scale:"css",timeout:5e3,...i});return{base64:`data:image/jpeg;base64,${n.toString("base64")}`,buffer:n}}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(i,n){if(n!=null&&n.selector)return{...n,selector:n.selector,locator:n.locator,clickOffset:n.position};if(!i)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${i})`),{...n,selector:i,locator:`locator("${i}")`};let a=await this.evaluateWithChecksum(async u=>{let{selector:f,locator:g,clickOffset:A,parentFramesSelectors:E,invalid:D,rrwebId:F}=await window.checksum.testGenerator.getSelectorForChecksumId(u),P=await window.checksum.testGenerator.getElementForChecksumId(u),Q=P instanceof HTMLOptionElement&&P.value?P.value:void 0;return{selector:f,locator:g,clickOffset:A,selectOptionValue:Q,parentFramesSelectors:E,invalid:D,rrwebId:F}},i);if(oDn&&a.invalid&&a.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. Trying to use time machine...`);try{let u=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(a.rrwebId);a={...a,...u}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${i}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${a.selector} for checksumid: ${i} from time machine`)}return a!=null&&a.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),a}async getSelectionDataForRRwebIdAtReduceHTMLTime(i){if(!this.rrwebEventAtLastReducedHTML)return;let n=this.getTimeMachine();if(n)return n.executeTask(a=>a.evaluate(async({rrwebId:u})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(u,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:i}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(i,n){let a=await this.evaluateWithChecksum(async({selector:u,parentFramesSelectors:f})=>window.checksum.testGenerator.getSelectionDataForSelector(u,f),{selector:i,parentFramesSelectors:n});return a==null?void 0:a.esraMetadata}async getMoreItemsForTemplate(i){return await this.evaluateWithChecksum(async n=>window.checksum.testGenerator.getMoreItemsForTemplate(n,{}),i)??{items:"",hasMoreItems:!1}}scrollElementIntoViewByChecksumId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.scrollElementIntoViewByChecksumId(n),i)}scrollElementIntoViewByRrwebId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.scrollElementIntoViewByRrwebId(n),i)}generateLocatorByRrwebId(i){return this.evaluateWithChecksum(async n=>window.checksum.testGenerator.generateLocatorByRrwebId(n),i)}getViewportHTML(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.extractViewportHTML())}scrollScrollableElement(i,n,a){return this.evaluateWithChecksum(async({rrwebId:u,direction:f,length:g})=>window.checksum.testGenerator.scrollScrollableElement(u,f,g),{rrwebId:i,direction:n,length:a})}async getCurrentReducedHTML({retriesLeft:i=3,retryWaitMS:n=2e3,initialChecksumId:a="0",extractESRAForInterpretationRequiredElements:u=!1,stopFlashingElementsDetection:f=!1,assignChecksumIdsToAllElements:g}={}){let A=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:E,currentChecksumId:D,flashingHTML:F,elementsForNodeInterpretation:P,lastRRwebEvent:Q,scrollableElements:R}=await this.evaluateWithChecksum(async q=>window.checksum.testGenerator.reduceHTML({},q),{initialChecksumId:a,extractESRAForInterpretationRequiredElements:u,stopFlashingElementsDetection:f,assignChecksumIdsToAllElements:g}),W=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${W.getTime()-A.getTime()}ms`),this.rrwebEventAtLastReducedHTML=Q,{reducedHTML:E,flashingHTML:F,elementsForNodeInterpretation:P,currentChecksumId:D,scrollableElements:R}}catch(E){if(i>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${E.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${n/1e3} seconds, ${i-1} to go.`),await _5(n),this.getCurrentReducedHTML({retriesLeft:i-1,retryWaitMS:n});throw E}}getActionEventCode(i){return htr[i]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var UHe=_TestGenerationPageInteractor;var IKn=jh(oTr());var Uue=jh(require("path")),hnr=require("fs");var lnr=require("path"),dxt=require("fs");function J5n(i,n,a=10){let u=i;for(let f=0;f<a;f++){let g=(0,lnr.join)(u,"package.json");if((0,dxt.existsSync)(g))try{if(JSON.parse((0,dxt.readFileSync)(g,"utf8")).name===n)return u}catch{}u=(0,lnr.join)(u,"..")}}e(J5n,"findRepositoryRoot");function _xt(i,n=10){return J5n(i,"checksum-customer-engineering-workspace",n)}e(_xt,"findCustomerEngineeringRoot");var gnr=jh(fTr());var P4=e((i,n)=>{if(i==null||i==="")return(n==null?void 0:n.default)??!1;let a=i.toLowerCase().trim();return a==="true"?!0:a==="false"?!1:(n==null?void 0:n.default)??!1},"parseBoolean");var sTn=__dirname,dTr=Uue.join(__dirname,".."),hTr=(0,hnr.existsSync)(dTr)?dTr:sTn;(0,gnr.config)({path:Uue.resolve(hTr,".env")});var _nr=P4(process.env.CHECKSUM_RUNTIME_DEV_MODE);function oTn(){let i=__dirname;for(;!(0,hnr.existsSync)(Uue.join(i,"package.json"));)i=Uue.join(i,"..");return i}e(oTn,"findRoot");var RIe=oTn(),cTn=_xt(RIe,10);(0,gnr.config)({path:[hTr,cTn].filter(Boolean).map(i=>Uue.resolve(i,".env")),override:!1});var hxt=P4(process.env.CHECKSUM_VTG_E2E_TEST_MODE),_Tr=Uue.join(RIe,"vtg-build","index.html"),mnr=hxt?!0:P4(process.env.CHECKSUM_RUNTIME_REPO_MODE),mTr=P4(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),uTn=mnr?Uue.join(RIe,"package","pw-report-template.html"):Uue.join(RIe,"pw-report-template.html"),lTn=P4(process.env.CHECKSUM_DEBUG_ANALYTICS),pTn=P4(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),zy={isDevMode:_nr,isRepoMode:mnr,CI:!!process.env.CI,checksumRootFolderBypass:hxt?"packages/runtime/test/e2e/checksum":mnr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(_nr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:RIe+"/checksumlib.js"},runtimeRoot:RIe,playwrightReporter:{htmlReportTemplatePath:uTn},bypassProxyForLocalhost:P4(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:P4(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:P4(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),testRun:{timeMachine:{active:!0,headless:!P4(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:P4(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{segment:{debugAnalytics:lTn,logToConsole:pTn,writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},disableAutoRecovery:P4(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:P4(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME}},vtg:{isSeparateProcess:mTr,isE2ETestMode:hxt,writeLogFile:P4(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(_nr?"served-app":"served-build-file"),localUrl:`file://${_Tr}`,localBuildPath:_Tr,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:P4(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:P4(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||hxt,logAPIServer:{interval:P4(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:P4(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:mTr?!0:P4(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:P4(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:P4(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:P4(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:P4(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:P4(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:P4(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:P4(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:P4(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:P4(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var ynr=jh(require("fs"));function fTn(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(n,a,u)=>u.trimEnd())}e(fTn,"removeTryCatchAndTestInfo");function gTr(i,n){let u=(i.stack||"No stack trace available").split(`
|
|
1498
1498
|
`),f="",g={};for(let A of u){let E=A.match(/\(([^)]+):(\d+):(\d+)\)/)||A.match(/at ((?:[a-zA-Z]:\\|\/)[^:]+):(\d+):(\d+)/);if(E){let D=E[1];if(!D.includes(n)||D.includes("node_modules")||D.includes("<anonymous>")||D.includes("internal")||D.includes("loader")||D.startsWith("eval"))continue;try{if(!g[D]&&ynr.default.existsSync(D)){let F=ynr.default.readFileSync(D,"utf-8");g[D]=fTn(F)}}catch(F){g[D]=`Error reading file: ${F.message}`}}}for(let[A,E]of Object.entries(g))f+=`
|
|
1499
1499
|
--- File: ${A} ---
|
|
1500
1500
|
${E}
|
|
@@ -1533,7 +1533,7 @@ ${De}${me}${Pe}${zVr.default.cursorHide}`});var T7t=jh(require("child_process"))
|
|
|
1533
1533
|
import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
|
|
1534
1534
|
|
|
1535
1535
|
export default getChecksumConfig(${JSON.stringify(this.config,null,2)});
|
|
1536
|
-
`;(0,aI.writeFileSync)(n,a)}async cleanup(){this.runtimeAnalytics&&(eS("Flushing events..."),await ow(this.runtimeAnalytics.close(),2e4)),this.deleteVolatileConfig(),
|
|
1536
|
+
`;(0,aI.writeFileSync)(n,a)}async cleanup(){this.runtimeAnalytics&&(eS("Flushing events..."),await ow(this.runtimeAnalytics.close(),2e4)),this.deleteVolatileConfig(),this.childProcesses.forEach(n=>{n.kill("SIGTERM")})}async getEnvInfo(){let n={commitHash:"",branch:"branch",environment:process.env.CI?"CI":"local",name:"name",startedAt:Date.now(),runtimeVersion:this.checksumRuntimeVersion,request:zy.testRun.request,platform:zy.testRun.platform};try{n.commitHash=await this.getCmdOutput("git rev-parse HEAD")}catch(a){console.log("Error getting git hash",a.message)}try{n.branch=await this.getCmdOutput("git rev-parse --abbrev-ref HEAD")}catch(a){console.log("Error getting branch",a.message)}return n.name=await this.getEnvName(),n}async getEnvName(){let n=this.getChecksumArg("title");if(typeof n=="string"&&(n==null?void 0:n.length)>0)return n;try{return await this.getCmdOutput("git log -1 --pretty=%B")}catch(a){console.log("Error getting name",a.message);return}}getVolatileConfigPath(){return(0,yB.join)(this.checksumRoot??"","checksum.config.tmp.ts")}deleteVolatileConfig(){let n=this.getVolatileConfigPath();(0,aI.existsSync)(n)&&(0,aI.rmSync)(n)}loadChecksumConfig(n={}){this.config={...this.readChecksumConfigFile(n)||{},...this.volatileChecksumConfig||{}},this.debugMode&&(this.config.options.printLogs=!0),this.traceChecksumConfig()}readChecksumConfigFile(n={}){let a=(0,yB.join)(this.checksumRoot,"checksum.config.ts");try{return require(a).default}catch(u){return n.muteChecksumConfigMissingError||console.warn("There was an error loading checksum.config.ts. Continuing with default configuration.",u.message),{}}}traceChecksumConfig(){if(!this.runtimeAnalytics)return;let n=Object.keys(this.config).reduce((a,u)=>({...a,[u]:typeof this.config[u]=="string"?this.config[u]:JSON.stringify(this.config[u])}),{});this.runtimeAnalytics.checksumConfig(this.config)}processConfigArg(){this.deleteVolatileConfig();let n=this.getChecksumArg("config");if(n)try{this.volatileChecksumConfig=JSON.parse(n)}catch(a){this.volatileChecksumConfig=void 0,console.log("Error parsing cksm config",a.message)}}getNonChecksumArgs(){return this.args.filter(n=>!this.isChecksumArg(n))}getArg(n){var f;let a=this.args.find(g=>g.startsWith(`${n}`)),u=(f=a==null?void 0:a.split("=")[1])==null?void 0:f.trim();return u||!!a}getChecksumArg(n){return this.getArg(`--cksm-${n}`)}getChecksumRootOrigin(){return(0,yB.join)(this.projectRootDirectory,"node_modules","@checksum-ai","runtime","checksum-root")}locateChecksumLibs(){try{this.findProjectRoot(),this.findChecksumRoot()}catch(n){console.log(n.message),process.exit(1)}}findProjectRoot(){let n=process.cwd();for(let a=0;a<6;a++){let u=(0,yB.join)(n,"node_modules","@checksum-ai","runtime");if((0,aI.existsSync)(u)){this.projectRootDirectory=n,eS("Project root directory found at",this.projectRootDirectory);return}if((0,yB.parse)(n).root===n)break;n=(0,yB.join)(n,"..")}throw new Error(process.env.CHECKSUM_RUNTIME_DEV_MODE?"Could not resolve checksum root origins, tried to look in node modules. please build the runtime":"Could not resolve checksum root origins")}setChecksumRoot(n){this.checksumRoot=n,eS("Checksum root directory found at",this.checksumRoot),this.createInternalFilesDir()}findChecksumRoot(){if(zy.checksumRootFolderBypass){let u=(0,yB.isAbsolute)(zy.checksumRootFolderBypass)?zy.checksumRootFolderBypass:(0,yB.join)(this.projectRootDirectory,zy.checksumRootFolderBypass);this.setChecksumRoot(u);return}let n=e(u=>{try{return(0,aI.readdirSync)(u).includes("checksum.config.ts")}catch{return!1}},"containsChecksumConfig"),a=[this.projectRootDirectory];for(;a.length;){let u=a.pop(),f=(0,aI.readdirSync)(u,{withFileTypes:!0});for(let g of f){let A=(0,yB.join)(u,g.name),E=A;if(g.isSymbolicLink())try{let D=(0,aI.readlinkSync)(A);if(!(0,aI.lstatSync)(D).isDirectory())continue;E=D}catch{continue}else if(!g.isDirectory())continue;if(g.name===mvt){if(n(E)){this.setChecksumRoot(E);return}}else a.push(A)}}throw new Error("Could not find checksum root folder. Run `npx checksumai init` to create one.")}log(n,a=!1){a?this.printError(n):console.log(n)}runtimeTrace(n,a){this.runtimeAnalytics.eventWithMessage(a,n)}isChecksumArg(n){return n.startsWith("--cksm-")}};e(qdr,"CLICommandBase");var aP=qdr;var Vdr=require("crypto");function YVr(i,n){return{testSuiteRunId:n,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(YVr,"createDefaultTestSuiteRunInfo");function XVr(i,n,a={}){let u=["mock-app","mock-app-2","mock-app-3"];return{...{appName:u[Math.floor(Math.random()*u.length)],commitHash:(0,Vdr.randomUUID)(),envName:"test-environment",branch:(0,Vdr.randomUUID)(),testSuiteRunId:n,checksumRuntimeVersion:i},...a}}e(XVr,"createMockTestSuiteRunInfo");var ZVr=`test.setTimeout(0);
|
|
1537
1537
|
globalThis.declarations = {};
|
|
1538
1538
|
globalThis.isDeclared = (name, evalCode) => {
|
|
1539
1539
|
try {
|
|
@@ -1607,9 +1607,9 @@ ${a.map(u=>[u.type,u.nestedLevel,this.getText(u.body)]).join(`,
|
|
|
1607
1607
|
${rJr}
|
|
1608
1608
|
${A}
|
|
1609
1609
|
${nJr}
|
|
1610
|
-
${(await u.getFormattedTestFileCode()).code}`)}loadVtgTestFileMirror(n){if(!n||!n.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let a=new h3e(n);return a.loadTestFromFile(),a}createActionJsonFileForExistingChecksumSpec(n,a){let u=n.testMirrors[0].translateStatementsToActions({mergeCustomCodeSteps:this.vtgSettingsService.getSettings().mergeCustomCodeSteps}),f=this.getActionJsonFilePath(a);(0,t$.writeFileSync)(f,JSON.stringify(u,null,2))}createFolderIfNotExists(n){return(0,t$.existsSync)(n)||(0,t$.mkdirSync)(n,{recursive:!0}),n}getSavePathForNewChecksumSpec(){return(0,Ule.join)(this.draftsFolderPath,"test.checksum.spec.ts")}getActionJsonFilePath(n){let a=this.getFileName(n).replace(".spec.ts",".json");return(0,Ule.join)(this.draftsFolderPath,a)}getEvalFilePath(n){let a=this.internalE2ETest?".eval.e2e.checksum.spec.ts":".eval.checksum.spec.ts";return(0,Ule.join)(this.draftsFolderPath,a)}getFileName(n){return n.split("/").pop()}};e(pvr,"VtgTestRunner");var H3t=pvr;var dvr=class dvr extends aP{constructor(a,u=!1,f=!1){super(a,u);this.vtgMode=f;this.MAX_COMPLETION_WAIT=2*3600*1e3;this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.playwrightIdToReportMetadata={};this.logFilter={"upload-progress":{logEveryMS:1e3*30,lastLogTimestamp:0,logOnValueChange:!0,value:""}}}get replMode(){return this.getChecksumArg("repl")??!1}logMemoryUsage(a,u){let f=process.memoryUsage(),g=Math.round(f.heapUsed/1024/1024),A=Math.round(f.heapTotal/1024/1024),E=Math.round(f.external/1024/1024),D=Math.round(f.rss/1024/1024),F=`[Memory] ${a}: Heap: ${g}MB/${A}MB, External: ${E}MB, RSS: ${D}MB`;u&&(F+=` | Child Process: ${u.stage} - Active: ${u.activeAssets}, Completed: ${u.completedAssets}, Errored: ${u.erroredAssets}, Total: ${u.totalAssets}`),console.log(F)}async run(){if(console.log("Running with fixed zip cleanup"),this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),this.vtgMode&&(this.config.options.hostReports=!1),!await this.getSession())return;this.testSuiteAnalytics=gFe.getInstance(this.testSuiteRunInfo,this.isolationMode),this.testSuiteAnalytics.genericEvent(`Project root found at ${this.projectRootDirectory}`,`Checksum root found at ${this.checksumRoot}`);let a={CHECKSUM_ROOT_FOLDER:this.checksumRoot,CHECKSUM_TEST_SUITE_INFO:JSON.stringify(this.testSuiteRunInfo)},u;try{u=await ow(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout"),a.CHECKSUM_UPLOAD_AGENT_PORT=u}catch{let E="Error starting test run monitor. Test results will not be available on checksum.";this.testSuiteAnalytics.testRunMonitorError({error:E}),this.log(E)}a.PW_TEST_HTML_REPORT_OPEN="never",this.isolationMode&&(a.CHECKSUM_ISOLATED_MODE="true"),this.testSuiteRunId&&(a.CHECKSUM_TEST_SUITE_ID=this.testSuiteRunId),this.replMode&&(a.CHECKSUM_REPL="true"),this.getChecksumArg("tm")&&(a.CHECKSUM_SHOW_TIME_MACHINE="true");let f=this.getNonChecksumArgs();this.vtgMode&&(await new H3t(this.getChecksumArg("id")||void 0,this.getChecksumArg("edit")||void 0,this.getChecksumArg("legacy")||!1,zy.vtg.isE2ETestMode,this.getChecksumArg("restore")||!1,this.checksumRoot,this.getInternalFilesDirPath()).initAndUpdateEnvAndPlaywrightArgs(a,f),zy.promptKillActivePlaywrightProcesses&&await this.promptKillActivePlaywrightProcesses()),this.replMode&&f.push("--debug");let g=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${f.map(A=>`"${A}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(g,a),await this.execCmd(`node ${__dirname}/repl.js`,a)):(this.testSuiteAnalytics.testSuiteStart(),await this.execCmd(g,a)),console.log(`Tests execution finished. Checksum is finalizing${this.isolationMode?"":" and uploading"} the report, please wait...`)}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.testSuiteAnalytics.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}loadPlaywrightConfigOptions(){var A,E;let a=e(D=>(eS("Using report folder",D),(0,gme.join)(D,"index.html")),"makeFilePath"),u,f="never";process.env.PLAYWRIGHT_HTML_OUTPUT_DIR&&(u=a(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR));let g=(A=this.playwrightConfig)==null?void 0:A.reporter;if(g instanceof Array){let D=g.filter(F=>F instanceof Array&&F[0]==="html");if(!process.env.PLAYWRIGHT_HTML_OUTPUT_DIR){let F=D.find(P=>{var Q;return(Q=P[1])==null?void 0:Q.outputFolder});F&&(u=a((0,gme.join)(this.checksumRoot,F[1].outputFolder)))}for(let F of D){let P=(E=F[1])==null?void 0:E.open;if(P==="always"||P==="on-failure"){f=P;break}}}u||(zy.isRepoMode?u=a((0,gme.join)(zy.runtimeRoot,"playwright-report")):u=a((0,gme.join)(this.projectRootDirectory,"playwright-report"))),this.playwrightConfigOptions={openReportCriteria:f,reportPath:u}}sendReportUploadRequest(){let a=e(D=>{this.testSuiteAnalytics.testSuiteError({error:D}),this.log(D),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false")},"makeError");if(!this.playwrightConfigOptions)return a("No playwright config options");let{reportPath:u,openReportCriteria:f}=this.playwrightConfigOptions;if(!(0,G3t.existsSync)(u))return a(`Could not find report file at ${u}`);eS("Sending report upload request",u);let g=this.saveMetadataToFile((0,gme.dirname)(u)),A={reportPath:u,pathToChecksumMetadata:g,openReportCriteria:f,didFail:this.didFail},E=Buffer.from(JSON.stringify(A)).toString("base64");this.testRunMonitorProcess.stdin.write(`cli:report=${E}`)}saveMetadataToFile(a){try{let u=(0,gme.join)(a,`checksum-metadata-${(0,fvr.randomUUID)()}.json`);return(0,G3t.writeFileSync)(u,JSON.stringify(this.playwrightIdToReportMetadata,null,2)),u}catch(u){let f=`Error saving metadata to file - ${u.message}`;this.testSuiteAnalytics.testSuiteError({error:f}),this.log(f);return}}startTestMonitorProcess(a){let f=[JSON.stringify({sessionId:a,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]],g={command:"node",args:[(0,gme.join)(__dirname,"test-run-monitor.js"),...f]};return zy.isRepoMode&&(g.command="yarn",g.args=["test-run-monitor",...f]),Pan.spawn(g.command,g.args)}startTestRunMonitor(a){return new Promise(u=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=this.startTestMonitorProcess(a),this.testRunMonitorProcess.stdout.on("data",f=>{let g=this.parseTRMMessages(f.toString().trim());if(g.length)for(let A of g){if(A.startsWith("trace")){this.logTRMMessage(A),this.handleTestRunMonitorTrace(A.substring("trace".length+1));continue}if(!A.startsWith("monitor")){this.logTRMMessage(A);continue}let E=e(()=>{let Q=A.substring("monitor".length+1),R=Q.indexOf("=");if(R===-1)return{key:Q,value:""};let[W,q]=[Q.substring(0,R),Q.substring(R+1)];return{key:W,value:q}},"getKeyAndValue"),{key:D,value:F}=E();if(!Object.values(ftr).includes(D)){this.logTRMMessage(`Received unknown monitor message: "${A}"`);continue}let P=D;this.logInterProcessEventMessage(P,F),D==="port"?u(F):this.handleTestRunMonitorMessage(P,F)}}),this.testRunMonitorProcess.on("exit",(f,g)=>{let A=`test run monitor process exited with code ${f} and signal ${g}`;this.testSuiteAnalytics.testRunMonitorError({error:A}),this.log(A)}),this.testRunMonitorProcess.stderr.on("data",f=>{let g=`TRM Error: ${f.toString().substring(0,300)}`;this.testSuiteAnalytics.testRunMonitorError({error:g}),this.log(g)}),this.testRunMonitorProcess.on("error",f=>{let g=`Error starting test run monitor: ${f.message}`;this.testSuiteAnalytics.testRunMonitorError({error:g}),this.log(g)})})}logInterProcessEventMessage(a,u){e(()=>{if(!this.logFilter[a])return!0;if(this.logFilter[a].logOnValueChange&&this.logFilter[a].value!==u)return this.logFilter[a].value=u,!0;if(this.logFilter[a].logEveryMS){let g=Date.now();if(g-this.logFilter[a].lastLogTimestamp>=this.logFilter[a].logEveryMS)return this.logFilter[a].lastLogTimestamp=g,!0}return!1},"shouldLog")()&&this.logTRMMessage(`Received monitor message: "${a}${u?`=${u}`:""}"`)}parseTRMMessages(a){let u=this.trmMessagesBuffer+a,f,g,A=e(()=>{f=u.indexOf("{trm}"),g=u.indexOf("{/trm}")},"findIndexes");A();let E=[];for(;f!==-1&&g!==-1&&g>f;){if(E.push(u.substring(f+"{trm}".length,g)),u=u.slice(g+"{/trm}".length).trim(),u.length&&!u.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",u),this.trmMessagesBuffer="",E;this.trmMessagesBuffer=u,A()}return E}setChecksumTestMetadata(a){let{retry:u,type:f,pwTestId:g}=a;this.playwrightIdToReportMetadata[g]||(this.playwrightIdToReportMetadata[g]={}),this.playwrightIdToReportMetadata[g][u]||(this.playwrightIdToReportMetadata[g][u]={}),this.playwrightIdToReportMetadata[g][u][f]=a}async handleTestRunMonitorTrace(a){let u=a.indexOf("="),[f,g]=u>-1?[a.substring(0,u),a.substring(u+1)]:[a,""];if(!Object.values(V6t).includes(f)){eS("Unknown trace event",f);return}try{let A=g?JSON.parse(g):{};switch(f){case"Upload Start":this.testSuiteAnalytics.uploadStart({filename:A.filename});break;case"Upload Complete":this.testSuiteAnalytics.uploadComplete({filename:A.filename});break;case"Upload Failed":this.testSuiteAnalytics.uploadFailed({filename:A.filename,error:A.error});break;case"Trace Processing Error":this.testSuiteAnalytics.traceProcessingError({error:A.error});break}}catch(A){eS(`Error parsing trace payload, ${A.message}`)}}async handleTestRunMonitorMessage(a,u){var f;switch(a){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let A=JSON.parse(u);this.testSuiteAnalytics.uploadsCompleteWithErrors(A)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"checksumTestMetadata":try{let A=JSON.parse(u);this.setChecksumTestMetadata(A)}catch(A){let E=`Error parsing test metadata event - ${A.message}`;this.testSuiteAnalytics.testSuiteError({error:E}),this.log(E)}break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.testSuiteAnalytics.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let A=u.slice(0,u.indexOf(":"))==="true",E=u.slice(u.indexOf(":")+1),D=this.handleStats(E);if(this.testSuiteAnalytics.testSuiteEnd({passed:D.passed,failed:D.failed,bug:D.bug,total:((f=D.tests)==null?void 0:f.length)||0}),await this.sendTestRunEnd(D),this.completeIndicators.report=!0,A){let F=`${this.checksumAppUrl}/#/test-runs/${this.testSuiteRunId}`,P=`Checksum report URL: ${F}`,Q="*".repeat(P.length);console.log(`${Q}
|
|
1610
|
+
${(await u.getFormattedTestFileCode()).code}`)}loadVtgTestFileMirror(n){if(!n||!n.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let a=new h3e(n);return a.loadTestFromFile(),a}createActionJsonFileForExistingChecksumSpec(n,a){let u=n.testMirrors[0].translateStatementsToActions({mergeCustomCodeSteps:this.vtgSettingsService.getSettings().mergeCustomCodeSteps}),f=this.getActionJsonFilePath(a);(0,t$.writeFileSync)(f,JSON.stringify(u,null,2))}createFolderIfNotExists(n){return(0,t$.existsSync)(n)||(0,t$.mkdirSync)(n,{recursive:!0}),n}getSavePathForNewChecksumSpec(){return(0,Ule.join)(this.draftsFolderPath,"test.checksum.spec.ts")}getActionJsonFilePath(n){let a=this.getFileName(n).replace(".spec.ts",".json");return(0,Ule.join)(this.draftsFolderPath,a)}getEvalFilePath(n){let a=this.internalE2ETest?".eval.e2e.checksum.spec.ts":".eval.checksum.spec.ts";return(0,Ule.join)(this.draftsFolderPath,a)}getFileName(n){return n.split("/").pop()}};e(pvr,"VtgTestRunner");var H3t=pvr;var dvr=class dvr extends aP{constructor(a,u=!1,f=!1){super(a,u);this.vtgMode=f;this.MAX_COMPLETION_WAIT=2*3600*1e3;this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.playwrightIdToReportMetadata={};this.logFilter={"upload-progress":{logEveryMS:1e3*30,lastLogTimestamp:0,logOnValueChange:!0,value:""}}}get replMode(){return this.getChecksumArg("repl")??!1}async run(){if(console.log("Running normal published version with har turned off"),this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),this.vtgMode&&(this.config.options.hostReports=!1),!await this.getSession())return;this.testSuiteAnalytics=gFe.getInstance(this.testSuiteRunInfo,this.isolationMode),this.testSuiteAnalytics.genericEvent(`Project root found at ${this.projectRootDirectory}`,`Checksum root found at ${this.checksumRoot}`);let a={CHECKSUM_ROOT_FOLDER:this.checksumRoot,CHECKSUM_TEST_SUITE_INFO:JSON.stringify(this.testSuiteRunInfo)},u;try{u=await ow(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout"),a.CHECKSUM_UPLOAD_AGENT_PORT=u}catch{let E="Error starting test run monitor. Test results will not be available on checksum.";this.testSuiteAnalytics.testRunMonitorError({error:E}),this.log(E)}a.PW_TEST_HTML_REPORT_OPEN="never",this.isolationMode&&(a.CHECKSUM_ISOLATED_MODE="true"),this.testSuiteRunId&&(a.CHECKSUM_TEST_SUITE_ID=this.testSuiteRunId),this.replMode&&(a.CHECKSUM_REPL="true"),this.getChecksumArg("tm")&&(a.CHECKSUM_SHOW_TIME_MACHINE="true");let f=this.getNonChecksumArgs();this.vtgMode&&(await new H3t(this.getChecksumArg("id")||void 0,this.getChecksumArg("edit")||void 0,this.getChecksumArg("legacy")||!1,zy.vtg.isE2ETestMode,this.getChecksumArg("restore")||!1,this.checksumRoot,this.getInternalFilesDirPath()).initAndUpdateEnvAndPlaywrightArgs(a,f),zy.promptKillActivePlaywrightProcesses&&await this.promptKillActivePlaywrightProcesses()),this.replMode&&f.push("--debug");let g=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${f.map(A=>`"${A}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(g,a),await this.execCmd(`node ${__dirname}/repl.js`,a)):(this.testSuiteAnalytics.testSuiteStart(),await this.execCmd(g,a)),console.log(`Tests execution finished. Checksum is finalizing${this.isolationMode?"":" and uploading"} the report, please wait...`)}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.testSuiteAnalytics.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}loadPlaywrightConfigOptions(){var A,E;let a=e(D=>(eS("Using report folder",D),(0,gme.join)(D,"index.html")),"makeFilePath"),u,f="never";process.env.PLAYWRIGHT_HTML_OUTPUT_DIR&&(u=a(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR));let g=(A=this.playwrightConfig)==null?void 0:A.reporter;if(g instanceof Array){let D=g.filter(F=>F instanceof Array&&F[0]==="html");if(!process.env.PLAYWRIGHT_HTML_OUTPUT_DIR){let F=D.find(P=>{var Q;return(Q=P[1])==null?void 0:Q.outputFolder});F&&(u=a((0,gme.join)(this.checksumRoot,F[1].outputFolder)))}for(let F of D){let P=(E=F[1])==null?void 0:E.open;if(P==="always"||P==="on-failure"){f=P;break}}}u||(zy.isRepoMode?u=a((0,gme.join)(zy.runtimeRoot,"playwright-report")):u=a((0,gme.join)(this.projectRootDirectory,"playwright-report"))),this.playwrightConfigOptions={openReportCriteria:f,reportPath:u}}sendReportUploadRequest(){let a=e(D=>{this.testSuiteAnalytics.testSuiteError({error:D}),this.log(D),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false")},"makeError");if(!this.playwrightConfigOptions)return a("No playwright config options");let{reportPath:u,openReportCriteria:f}=this.playwrightConfigOptions;if(!(0,G3t.existsSync)(u))return a(`Could not find report file at ${u}`);eS("Sending report upload request",u);let g=this.saveMetadataToFile((0,gme.dirname)(u)),A={reportPath:u,pathToChecksumMetadata:g,openReportCriteria:f,didFail:this.didFail},E=Buffer.from(JSON.stringify(A)).toString("base64");this.testRunMonitorProcess.stdin.write(`cli:report=${E}`)}saveMetadataToFile(a){try{let u=(0,gme.join)(a,`checksum-metadata-${(0,fvr.randomUUID)()}.json`);return(0,G3t.writeFileSync)(u,JSON.stringify(this.playwrightIdToReportMetadata,null,2)),u}catch(u){let f=`Error saving metadata to file - ${u.message}`;this.testSuiteAnalytics.testSuiteError({error:f}),this.log(f);return}}startTestMonitorProcess(a){let f=[JSON.stringify({sessionId:a,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]],g={command:"node",args:[(0,gme.join)(__dirname,"test-run-monitor.js"),...f]};return zy.isRepoMode&&(g.command="yarn",g.args=["test-run-monitor",...f]),Pan.spawn(g.command,g.args)}startTestRunMonitor(a){return new Promise(u=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=this.startTestMonitorProcess(a),this.testRunMonitorProcess.stdout.on("data",f=>{let g=this.parseTRMMessages(f.toString().trim());if(g.length)for(let A of g){if(A.startsWith("trace")){this.logTRMMessage(A),this.handleTestRunMonitorTrace(A.substring("trace".length+1));continue}if(!A.startsWith("monitor")){this.logTRMMessage(A);continue}let E=e(()=>{let Q=A.substring("monitor".length+1),R=Q.indexOf("=");if(R===-1)return{key:Q,value:""};let[W,q]=[Q.substring(0,R),Q.substring(R+1)];return{key:W,value:q}},"getKeyAndValue"),{key:D,value:F}=E();if(!Object.values(ftr).includes(D)){this.logTRMMessage(`Received unknown monitor message: "${A}"`);continue}let P=D;this.logInterProcessEventMessage(P,F),D==="port"?u(F):this.handleTestRunMonitorMessage(P,F)}}),this.testRunMonitorProcess.on("exit",(f,g)=>{let A=`test run monitor process exited with code ${f} and signal ${g}`;this.testSuiteAnalytics.testRunMonitorError({error:A}),this.log(A)}),this.testRunMonitorProcess.stderr.on("data",f=>{let g=`TRM Error: ${f.toString().substring(0,300)}`;this.testSuiteAnalytics.testRunMonitorError({error:g}),this.log(g)}),this.testRunMonitorProcess.on("error",f=>{let g=`Error starting test run monitor: ${f.message}`;this.testSuiteAnalytics.testRunMonitorError({error:g}),this.log(g)})})}logInterProcessEventMessage(a,u){e(()=>{if(!this.logFilter[a])return!0;if(this.logFilter[a].logOnValueChange&&this.logFilter[a].value!==u)return this.logFilter[a].value=u,!0;if(this.logFilter[a].logEveryMS){let g=Date.now();if(g-this.logFilter[a].lastLogTimestamp>=this.logFilter[a].logEveryMS)return this.logFilter[a].lastLogTimestamp=g,!0}return!1},"shouldLog")()&&this.logTRMMessage(`Received monitor message: "${a}${u?`=${u}`:""}"`)}parseTRMMessages(a){let u=this.trmMessagesBuffer+a,f,g,A=e(()=>{f=u.indexOf("{trm}"),g=u.indexOf("{/trm}")},"findIndexes");A();let E=[];for(;f!==-1&&g!==-1&&g>f;){if(E.push(u.substring(f+"{trm}".length,g)),u=u.slice(g+"{/trm}".length).trim(),u.length&&!u.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",u),this.trmMessagesBuffer="",E;this.trmMessagesBuffer=u,A()}return E}setChecksumTestMetadata(a){let{retry:u,type:f,pwTestId:g}=a;this.playwrightIdToReportMetadata[g]||(this.playwrightIdToReportMetadata[g]={}),this.playwrightIdToReportMetadata[g][u]||(this.playwrightIdToReportMetadata[g][u]={}),this.playwrightIdToReportMetadata[g][u][f]=a}async handleTestRunMonitorTrace(a){let u=a.indexOf("="),[f,g]=u>-1?[a.substring(0,u),a.substring(u+1)]:[a,""];if(!Object.values(V6t).includes(f)){eS("Unknown trace event",f);return}try{let A=g?JSON.parse(g):{};switch(f){case"Upload Start":this.testSuiteAnalytics.uploadStart({filename:A.filename});break;case"Upload Complete":this.testSuiteAnalytics.uploadComplete({filename:A.filename});break;case"Upload Failed":this.testSuiteAnalytics.uploadFailed({filename:A.filename,error:A.error});break;case"Trace Processing Error":this.testSuiteAnalytics.traceProcessingError({error:A.error});break}}catch(A){eS(`Error parsing trace payload, ${A.message}`)}}async handleTestRunMonitorMessage(a,u){var f;switch(a){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let A=JSON.parse(u);this.testSuiteAnalytics.uploadsCompleteWithErrors(A)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"checksumTestMetadata":try{let A=JSON.parse(u);this.setChecksumTestMetadata(A)}catch(A){let E=`Error parsing test metadata event - ${A.message}`;this.testSuiteAnalytics.testSuiteError({error:E}),this.log(E)}break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.testSuiteAnalytics.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let A=u.slice(0,u.indexOf(":"))==="true",E=u.slice(u.indexOf(":")+1),D=this.handleStats(E);if(this.testSuiteAnalytics.testSuiteEnd({passed:D.passed,failed:D.failed,bug:D.bug,total:((f=D.tests)==null?void 0:f.length)||0}),await this.sendTestRunEnd(D),this.completeIndicators.report=!0,A){let F=`${this.checksumAppUrl}/#/test-runs/${this.testSuiteRunId}`,P=`Checksum report URL: ${F}`,Q="*".repeat(P.length);console.log(`${Q}
|
|
1611
1611
|
${P}
|
|
1612
|
-
${Q}`),this.testSuiteAnalytics.reportComplete({stats:D,reportUrl:F})}else this.testSuiteAnalytics.testSuiteError({error:"An error occurred while uploading the test report to Checksum"}),this.testSuiteAnalytics.reportUploadError(),console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{if(this.isolationMode)break;let A=parseInt(u);(A<this.uploadProgress||A>=this.uploadProgress+10||A===100&&this.uploadProgress!==100)&&(this.uploadProgress=A,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(u);break;case"
|
|
1612
|
+
${Q}`),this.testSuiteAnalytics.reportComplete({stats:D,reportUrl:F})}else this.testSuiteAnalytics.testSuiteError({error:"An error occurred while uploading the test report to Checksum"}),this.testSuiteAnalytics.reportUploadError(),console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{if(this.isolationMode)break;let A=parseInt(u);(A<this.uploadProgress||A>=this.uploadProgress+10||A===100&&this.uploadProgress!==100)&&(this.uploadProgress=A,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(u);break;case"trace":let g=u;if(!Object.values(V6t).includes(g))return;this.testSuiteAnalytics.genericEvent(g);break;case"playwrightConfig":try{this.playwrightConfig||(this.playwrightConfig=JSON.parse(u),this.testSuiteAnalytics.playwrightConfig({config:this.playwrightConfig}),this.loadPlaywrightConfigOptions())}catch(A){let E=`Error parsing playwright config - ${A.message}`;this.testSuiteAnalytics.playwrightConfigError({error:E}),this.log(E)}break;default:this.testSuiteAnalytics.testRunMonitorError({error:`Unhandled test run monitor message: ${a}=${u}`}),this.log(`Unhandled test run monitor message: ${a}=${u}`)}}handleStats(a){let u={};try{a&&a.length>0?(u=JSON.parse(a),u.tests=u.tests.map(f=>{let g=this.playwrightIdToReportMetadata[f.playwrightTestId];if(!g)return f;let A=!1,E=!1,D=[];return Object.keys(g??{}).forEach(F=>{var P;if(g[F]){let Q=g[F].autoRecoveryMetadata;A=Q!=null&&Q.data.autoRecoveryTriggered?!0:A,E=Q!=null&&Q.data.autoRecovered?!0:E;let R=g[F].autoRecoverySummaries;(P=R==null?void 0:R.data)!=null&&P.length&&D.push(...R.data)}}),{...f,autoRecovered:E,autoRecoveryTriggered:A,autoRecoverySummaries:D}})):(this.testSuiteAnalytics.testSuiteError({error:"No stats received from test run monitor"}),eS("No stats received from test run monitor"))}catch(f){this.testSuiteAnalytics.testSuiteError({error:`Error parsing stats - ${f.message}`}),this.log(`Error parsing stats - ${f.message}`)}return u}async handleCompleteMessage(){let a=Date.now(),u=12;for(;;){if(Date.now()-a>this.MAX_COMPLETION_WAIT){console.log("Warning: Checksum wasn't able to upload all test assets or expected a file the couldn't be found. This might cause issues when viewing the report/trace."),this.testSuiteAnalytics.runtimeTimeout(),this.shutdown(1);return}if(Object.keys(this.completeIndicators).find(f=>!this.completeIndicators[f]))eS(this.completeIndicators),--u===0&&(this.testSuiteAnalytics.completionStatus({stats:this.completeIndicators}),u=12),await _5(5e3);else{this.testSuiteAnalytics.runtimeComplete(),console.log("Checksum test suite run has completed"),await this.shutdown(this.didFail?1:0);return}}}async shutdown(a=0){await this.cleanup(),process.exit(a)}async cleanup(){await super.cleanup(),this.testRunMonitorProcess&&(this.testRunMonitorProcess.stdin.write("cli:shutdown"),this.testRunMonitorProcess.kill())}async getSession(){let a,u;try{if(!this.config.options.hostReports)return this.setIsolatedMode(),!0;if(u=this.config.apiKey,!u||u==="<API key>"){let F="No API key found in checksum config - please set it in the config file - checksum.config.ts";return this.runtimeTrace(F,"Checksum Config Error"),this.log(F,!0),this.shutdown(1),!1}let f=await this.getEnvInfo(),g=JSON.stringify({...f,isHidden:!!this.config.options.hideReports}),A=await fetch(`${this.config.apiURL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:u},body:g}),{uuid:E,appName:D}=await A.json();return this.testSuiteRunId=E,f.commit=f.name,f.name=D,this.testSuiteRunInfo={appName:D,commitHash:f.commitHash,envName:f.name,branch:f.branch,testSuiteRunId:E,checksumRuntimeVersion:this.checksumRuntimeVersion},!0}catch(f){let g=`Error connecting to Checksum, the report will not be hosted - ${f.message}`;return this.runtimeTrace(g,"Test Suite Init Error"),this.log(g),this.setIsolatedMode(),!0}}setIsolatedMode(){this.testSuiteRunId=process.env.CHECKSUM_TEST_SUITE_ID||(0,fvr.randomUUID)(),this.isolationMode=!0,this.completeIndicators.upload=!0,zy.testRun.monitoring.segment.debugAnalytics?this.testSuiteRunInfo=XVr(this.checksumRuntimeVersion,this.testSuiteRunId):this.testSuiteRunInfo=YVr(this.checksumRuntimeVersion,this.testSuiteRunId)}async sendTestRunEnd(a){if(!this.isolationMode)try{let u="{}";try{u=JSON.stringify({...a,endedAt:Date.now()})}catch(f){this.testSuiteAnalytics.testSuiteError({error:`Error stringifying stats ${f.message}`}),this.log(`Error stringifying stats ${f.message}`,!0)}await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}`,"PATCH",u)}catch(u){return this.testSuiteAnalytics.testSuiteError({error:`Error sending test run end ${u.message}`}),this.log(`Error sending test run end ${u.message}`,!0),null}}async sendUploadsComplete(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}/uploads-completed`,"PATCH")}catch(a){this.testSuiteAnalytics.testSuiteError({error:`Error sending test run uploads complete - ${a.message}`}),this.log(`Error sending test run uploads complete - ${a.message}`,!0)}}async sendProcessingError(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}/process-error`,"PATCH")}catch(a){this.testSuiteAnalytics.testSuiteError({error:`Error sending test run processing error - ${a.message}`}),this.log(`Error sending test run processing error - ${a.message}`,!0)}}async updateTestRun(a,u,f=void 0){let g=await fetch(a,{method:u,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:f});return eS("Received update test run response from url:",a),await this.logApiResponse(g),g}async logApiResponse(a){try{if(!a.ok){let{status:f,statusText:g}=a,A=await a.text();this.testSuiteAnalytics.testSuiteError({status:f,statusText:g,error:A});return}a.headers.get("Content-Type").includes("application/json")?a.json().then(f=>{eS("API Response:",f)}):a.text().then(f=>{eS("API Response:",f)})}catch(u){this.testSuiteAnalytics.testSuiteError({error:`Error logging API response - ${u.message}`})}}logTRMMessage(a){(Array.isArray(a)?a:[a]).forEach(u=>{eS("[trm]",u)})}};e(dvr,"TestsRunner");var qXe=dvr;var _vr=class _vr extends aP{constructor(n,a=!1){super(n,a)}async run(n){switch(n){default:console.log(`
|
|
1613
1613
|
Checksum CLI
|
|
1614
1614
|
Usage: checksum [command] [options]
|
|
1615
1615
|
|