@checksum-ai/runtime 4.14.0-beta.2 → 4.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/checksum-progress-reporter.js +17 -17
- package/cli.js +103 -103
- package/index.js +1 -1
- package/package.json +1 -1
- package/test-run-monitor.js +27 -27
package/index.js
CHANGED
|
@@ -320,7 +320,7 @@ ${r}`;return{success:!0,pages:u,message:f}}async switchPageHandler(c){if(!c.page
|
|
|
320
320
|
${c.description}`})}async onTestComplete(c){this.testRunAnalytics.testRunEnd({success:c,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasSuccessfulAutoRecovery&&c}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(c,u=this.page){try{return u.mainFrame()._checksumInternal=!0,u._checksumInternal=!0,await c()}finally{u.mainFrame()._checksumInternal=!1,u._checksumInternal=!1}}async conditionallyWrapInternalSteps(c,u){return c?this.wrapInternalSteps(u):u()}async wrapNoLocationSteps(c){try{return this.testInfo._checksumNoLocation=!0,await c()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(c,u,r=[]){for(let f of c){(f._stepId===u||f.stepId===u)&&r.push(f);let p=[f.steps,f._testInfoSteps,f._steps].filter(Boolean);for(let d of p)this.findAllStepsRecursively(d,u,r)}return r}makeChecksumStepFunction(c){return u=>{if(!c)return;let r=u._stepId||u.stepId;this.findAllStepsRecursively(u._testInfo._steps,r).forEach(p=>{p.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(c){let u,r={box:!0,noLocation:!0,obtainStep:s(f=>{u=f},"obtainStep")};if(await this.step(c.title,this.makeChecksumStepFunction(c.withError),!1,r),u?.stepId&&this.arStepIds.push(u.stepId),!u)throw new Error("Checksum step was not created");return u}async step(c,u,r=!0,{obtainStep:f=void 0,box:p=!1,noLocation:d=void 0}={}){let h=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=r===!0,d!==void 0&&(this.testInfo._checksumNoLocation=d),await this.test.step(c,u??(()=>{}),{obtainStep:f,box:p})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=h}}addErrorMessage(c,u){this.testInfo.addError(c,u)}async evaluateWithChecksum(c,u,r=!0){this.navigationPromise&&await this.navigationPromise;let f=this.page.evaluate.bind(this.page);return this.conditionallyWrapInternalSteps(r,()=>f(c,u))}getChecksumTestId(){return this.checksumTestId}addNewThought(c,u,r=!1){let f={thought:c,type:u,...r?{children:[]}:{}};if(!this.currentThought)this.highLevelThoughts.push(f);else if(this.currentThought.children)this.currentThought.children.push(f),f.parent=this.currentThought;else{let d=this.currentThought.parent;d?(d.children=d.children??[],d.children.push(f),f.parent=d):this.highLevelThoughts.push(f)}let p=f.parent;return p?f.id=`${p.id}.${p.children?.length??0}`:f.id=`${++this.thoughtsCounter}`,this.currentThought=f,f}buildThoughtsChainForFallback(c=this.highLevelThoughts){let u=[];return c.forEach(r=>{u.push(r.thought),r.children&&u.push(...this.buildThoughtsChainForFallback(r.children))}),u}compoundSelection(...c){let u=super.compoundSelection(...c);return u.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),u}setSelectorFallback(c){let u={checksumId:c,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:MQ};this.pushFallback(this.constructFallback(Ch).init(u)),this.pushFallback(this.constructFallback(Oh).init(u))}setCompoundSelectorFallback(c){this.pushFallback(this.constructFallback(wh).init({checksumId:c,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:MQ}))}setAIFallback(c,u){let r=this.options.useChecksumAI?.arVersion===1,f=s(()=>{let d=this.buildThoughtsChainForFallback(),h={title:this.testInfo.title},o={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},a={previous:d.slice(0,-1),failing:c,next:d.slice(1)},e={storyInfo:h,testIdentification:o,fallbackConfig:{arMode:this.options.useChecksumAI?.arMode,overrideOptions:{...this.options.useChecksumAI?.overrideOptions,...this.options.useChecksumAI?.modelName&&!this.options.useChecksumAI?.overrideOptions?.modelName?{modelName:this.options.useChecksumAI.modelName}:{}},markRecovered:this.options.useChecksumAI?.markRecovered},thoughts:a,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:u};return this.constructFallback(ji).init(e)},"createArFallback"),p=s(()=>{let d=typeof this.options.useChecksumAI=="object"?this.options.useChecksumAI:void 0,h=d?.arMode,o=d?.overrideOptions;return this.constructFallback(Ri).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),...h!==void 0?{arMode:h}:{},...o!==void 0?{overrideOptions:o}:{},fallbackType:u})},"createAIFallback");return r?this.pushFallback(p()):this.pushFallback(f()),this.proxy}pushFallback(c){this.fallbacks.push(c),this.sortFallbacks()}handleAIFallback(c,u,r,f){let p=c.fallbackAnalyticsPayload.iterationSteps,d=p.length>0?f/p.length:0,h=r.fbResult??"failed";this.testRunAnalytics.testRunFallbackExecution({result:h,failedThought:c.getFailedThought(),summary:r.summary??"",stepsPayload:c.fallbackAnalyticsPayload,type:c.fallbackType??u.type,duration:f,avgDuration:d,success:["finish","soft_assertion"].includes(h)}),this.arResults.push({failedThought:c.getFailedThought(),result:h,...r.thought!==void 0?{thought:r.thought}:{}})}handleAutoRecovery(c,u,r,f){let p=r.stepsThoughts??[],d=p.length>0?f/p.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:c.failingThought,type:u.type,finalThought:r.thought??"",result:r.fbResult??"failed",duration:f,avgStepDuration:d,stepsThoughts:p,version:"v1"})}async runFallback(c,u){let r=Date.now(),f=c.resolve(u),p=await tt(f,c.timeout),d=Date.now()-r;if(!p)throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:"Recovery Failed",withError:!0}),new Error("Fallback failed");c instanceof Ri&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(c,u,p,d)),c instanceof ji&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(c,u,p,d));let h=p.thought?`: ${p.thought}`:"";if(p.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${h}`,withError:!0}),new Error("Fallback failed");if(p.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${h}`,withError:!0}),new Xp(p.fbResult);this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),c instanceof Ri&&p.summary&&this.arSummaries.push(p.summary),c instanceof ji&&p.thought&&this.arSummaries.push(p.thought),this.createChecksumStep({title:`Recovery Complete${h}`});let o=this.currentThought;if(o&&p.steps.length===1){let a=p.steps[0];a?.thought&&(o.thought=a.thought)}else o&&(o.children=p.steps.map((a,e)=>({id:`${o.id}.${e+1}`,thought:a.thought??"",type:a.type,parent:o})))}async runConditionallyWithinStep(c,u,r){return c?this.step(u,r):r()}async onExecutionError(c){try{return await this.initiateFallbackSequence({...c,type:"action"})}catch(u){if(!this.currentThought){let{locator:r,method:f}=c;this.testRunAnalytics.testRunActionExecutionFailure({locator:r?.toString()??"",selector:r?._selector??"",method:f,checksumStepId:this.checksumStepId??"",error:u instanceof Error?u.toString():String(u)})}throw u}}async initiateFallbackSequence(c,{fallbackTypes:u}={}){he(`[initiateFallbackSequence] with type: ${c.type}...`);let r=this.fallbacks.find(d=>d instanceof Ri);if(r){let d=r.getFailedThought(),h=this.variableStore?.getActiveVariables()??[];this.fallbacks.forEach(o=>{o.setThought(d),o.setVariables(h)})}let f=this.fallbacks.find(d=>d instanceof ji);if(f){let d=f.failingThought;this.fallbacks.forEach(h=>{h instanceof ji&&h.setVariables(this.variableStore?.getActiveVariables()??[]),h.setThought(d)})}let p=this.fallbacks;u&&(p=p.filter(d=>u.reduce((h,o)=>h||d instanceof o,!1))),p=p.filter(d=>d.canResolve(c));try{for(let d of p){let h=d?.toString();h&&console.log(`Using ${h}`);try{await this.runConditionallyWithinStep(c.type!=="assertion"||!c.withChecksumAI,d.getRecoveryAttemptTitle(c),async()=>this.runFallback(d,c))}catch(o){if(c.withChecksumAI&&o.message==="fetch failed")throw new Error(za);o instanceof Xp&&o.fallbackResult==="hard_assertion"&&$Ue(c.error,"hard_assertion"),h&&console.log(`Failed to use ${h}`),d.cancel();continue}return!0}throw c.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Sh).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()&&this.timeMachine){let c=this.timeMachine;try{await c.flushRRwebEventsToFile();let u=c.getRRwebFilePath();u&&this.monitorBridge.addAsset({type:"rrweb-recording",path:u,testId:this.checksumTestId,fileName:Yo.basename(u)})}catch(u){he("Error shutting down RRweb events recording",u)}this.testRunAnalytics&&(he("Flushing analytics events......"),await this.testRunAnalytics.close())}}sortFallbacks(){let c=[Sh,wh,Ch,Oh,Ri];this.fallbacks.sort((u,r)=>c.indexOf(u.constructor)-c.indexOf(r.constructor))}constructFallback(c){return new c(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let u=await this.getTraceFilePath();u&&this.monitorBridge.addAsset({type:"trace",path:u,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let u=OH(Iy(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:u,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?CH(Iy(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}prepareMockData(){let c=BT(Iy(this.testInfo.file)),u=Yo.join(c,`${this.checksumTestId}.har.zip`);if(!(0,fn.existsSync)(u))throw new Error("Could not find har file or zip file");let r=Yo.join(c,"tmp");(0,fn.existsSync)(r)||(0,fn.mkdirSync)(r);let f=(0,fn.readFileSync)(u),p=rK(new Uint8Array(f));for(let[h,o]of Object.entries(p)){if(h.endsWith("/"))continue;let a=Yo.join(r,h);(0,fn.mkdirSync)(Yo.dirname(a),{recursive:!0}),(0,fn.writeFileSync)(a,o),this.unzippedHarData.push(a)}let d=Yo.join(r,"test.har");if(!(0,fn.existsSync)(d))throw this.cleanupMockData(),new Error(`Could not find har file ${d} after unzipping ${u}`);return d}cleanupMockData(){this.unzippedHarData.forEach(u=>{(0,fn.rmSync)(u)});let c=this.unzippedHarData[0];c&&(0,fn.rmSync)(Yo.dirname(c),{recursive:!0,force:!0})}async prepareAPIMock(){let c={GET:0,POST:0,PUT:0,DELETE:0};try{let u=this.prepareMockData();await this.page.routeFromHAR(u,{url:"*/**",notFound:"fallback",update:!1});let r=this.page._routes[0].handler;await this.page.route("**/*",f=>{let p=f.request().headers(),d=f.request().method(),h=(c[d]??0)+1;c[d]=h,p["Checksum-Id"]=h.toString(),f.request()._applyFallbackOverrides({headers:p}),r(f)})}catch(u){he("Error setting up mock data",u.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let c=Yo.join(Ic(To()),"settings.asr");if(!(0,fn.existsSync)(c)){he("Could not find ASR file");return}try{let u=await _T((0,fn.readFileSync)(c));this.appSpecificRules=JSON.parse(u.toString())||{}}catch(u){he("Could not read ASR file",u.message)}}addAutoRecoveryStepId(c){this.arStepIds.push(c)}};var $oe=require("fs"),Voe=require("module"),zoe=require("path"),Yoe=require("vm"),Koe=require("sucrase");function Zoe(i){let n=(0,$oe.readFileSync)(i,"utf8"),{code:c}=(0,Koe.transform)(n,{transforms:["typescript","imports"],filePath:i}),u={},r={exports:u};(0,Yoe.runInThisContext)(`(function (exports, require, module, __filename, __dirname) {
|
|
321
321
|
${c}
|
|
322
322
|
})`,{filename:i})(u,(0,Voe.createRequire)(i),r,i,(0,zoe.dirname)(i));let p=r.exports,d=p.default;return d===void 0?p:d}s(Zoe,"requireChecksumConfig");var HI=require("fs"),ire=require("module");var tc={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},x_t={defaultMerge:tc.defaultMerge};function VUe(i,n){return n}s(VUe,"defaultMetaDataUpdater");function zUe(i,n){return i.filter(c=>c!==void 0)}s(zUe,"defaultFilterValues");var Xoe;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(Xoe||(Xoe={}));function ere(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:ZUe(i)?1:i instanceof Set?3:i instanceof Map?4:5}s(ere,"getObjectType");function YUe(i){let n=new Set;for(let c of i)for(let u of[...Object.keys(c),...Object.getOwnPropertySymbols(c)])n.add(u);return n}s(YUe,"getKeys");function KUe(i,n){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,n)}s(KUe,"objectHasProperty");function nre(i){let n=0,c=i[0]?.[Symbol.iterator]();return{[Symbol.iterator](){return{next(){do{if(c===void 0)return{done:!0,value:void 0};let u=c.next();if(u.done===!0){n+=1,c=i[n]?.[Symbol.iterator]();continue}return{done:!1,value:u.value}}while(!0)}}}}}s(nre,"getIterableOfIterables");var tre=["[object Object]","[object Module]"];function ZUe(i){if(!tre.includes(Object.prototype.toString.call(i)))return!1;let{constructor:n}=i;if(n===void 0)return!0;let c=n.prototype;return!(c===null||typeof c!="object"||!tre.includes(Object.prototype.toString.call(c))||!c.hasOwnProperty("isPrototypeOf"))}s(ZUe,"isRecord");function XUe(i,n,c){let u={};for(let r of YUe(i)){let f=[];for(let h of i)KUe(h,r)&&f.push(h[r]);if(f.length===0)continue;let p=n.metaDataUpdater(c,{key:r,parents:i}),d=rre(f,n,p);d!==tc.skip&&(r==="__proto__"?Object.defineProperty(u,r,{value:d,configurable:!0,enumerable:!0,writable:!0}):u[r]=d)}return u}s(XUe,"mergeRecords$1");function eje(i){return i.flat()}s(eje,"mergeArrays$1");function tje(i){return new Set(nre(i))}s(tje,"mergeSets$1");function nje(i){return new Map(nre(i))}s(nje,"mergeMaps$1");function oje(i){return i.at(-1)}s(oje,"mergeOthers$1");var jI={mergeRecords:XUe,mergeArrays:eje,mergeSets:tje,mergeMaps:nje,mergeOthers:oje};function ore(...i){return rje({})(...i)}s(ore,"deepmerge");function rje(i,n){let c=ije(i,u);function u(...r){return rre(r,c,n)}return s(u,"customizedDeepmerge"),u}s(rje,"deepmergeCustom");function ije(i,n){return{defaultMergeFunctions:jI,mergeFunctions:{...jI,...Object.fromEntries(Object.entries(i).filter(([c,u])=>Object.hasOwn(jI,c)).map(([c,u])=>u===!1?[c,jI.mergeOthers]:[c,u]))},metaDataUpdater:i.metaDataUpdater??VUe,deepmerge:n,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??zUe,actions:tc}}s(ije,"getUtils");function rre(i,n,c){let u=n.filterValues?.(i,c)??i;if(u.length===0)return;if(u.length===1)return UQ(u,n,c);let r=ere(u[0]);if(r!==0&&r!==5){for(let f=1;f<u.length;f++)if(ere(u[f])!==r)return UQ(u,n,c)}switch(r){case 1:return aje(u,n,c);case 2:return cje(u,n,c);case 3:return lje(u,n,c);case 4:return sje(u,n,c);default:return UQ(u,n,c)}}s(rre,"mergeUnknowns");function aje(i,n,c){let u=n.mergeFunctions.mergeRecords(i,n,c);return u===tc.defaultMerge||n.useImplicitDefaultMerging&&u===void 0&&n.mergeFunctions.mergeRecords!==n.defaultMergeFunctions.mergeRecords?n.defaultMergeFunctions.mergeRecords(i,n,c):u}s(aje,"mergeRecords");function cje(i,n,c){let u=n.mergeFunctions.mergeArrays(i,n,c);return u===tc.defaultMerge||n.useImplicitDefaultMerging&&u===void 0&&n.mergeFunctions.mergeArrays!==n.defaultMergeFunctions.mergeArrays?n.defaultMergeFunctions.mergeArrays(i):u}s(cje,"mergeArrays");function lje(i,n,c){let u=n.mergeFunctions.mergeSets(i,n,c);return u===tc.defaultMerge||n.useImplicitDefaultMerging&&u===void 0&&n.mergeFunctions.mergeSets!==n.defaultMergeFunctions.mergeSets?n.defaultMergeFunctions.mergeSets(i):u}s(lje,"mergeSets");function sje(i,n,c){let u=n.mergeFunctions.mergeMaps(i,n,c);return u===tc.defaultMerge||n.useImplicitDefaultMerging&&u===void 0&&n.mergeFunctions.mergeMaps!==n.defaultMergeFunctions.mergeMaps?n.defaultMergeFunctions.mergeMaps(i):u}s(sje,"mergeMaps");function UQ(i,n,c){let u=n.mergeFunctions.mergeOthers(i,n,c);return u===tc.defaultMerge||n.useImplicitDefaultMerging&&u===void 0&&n.mergeFunctions.mergeOthers!==n.defaultMergeFunctions.mergeOthers?n.defaultMergeFunctions.mergeOthers(i):u}s(UQ,"mergeOthers");var are=!1;function qoe(i){are=i}s(qoe,"setLogToConsole");function he(...i){are&&console.log(...i)}s(he,"log");function uje(i,n){return i in n}s(uje,"isLocatorMethod");async function oee(i,n,c,u=6e4){if(!uje(n,i))return i;let r=s(()=>{let f=i[n];return typeof f=="function"?Reflect.apply(f,i,c):f},"executor");return u===null?r():tt(r(),u,"Execution timeout")}s(oee,"executePlaywrightMethodWithTimeout");function jQ({envName:i,role:n}={}){let c=process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_NAME??i,u=process.env.CHECKSUM_RUNTIME_ENV_OVERRIDE_ROLE??n;return{...c!==void 0?{envName:c}:{},...u!==void 0?{role:u}:{}}}s(jQ,"applyRuntimeEnvOverrides");function HQ(i,{role:n,environment:c}={},u=!1){let r;if(c&&(r=i.environments?.find(({name:d})=>c===d)),r??=i.environments?.find(({default:d})=>d),!r)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let f=r.users,p;if(f&&(n!==void 0&&(p=f.find(d=>d.role===n)),p??=f.find(d=>d.default)),!p)throw new Error(`User not found. Please make sure the users array for the "${r.name}" environment is properly defined in the checksum.config.ts file.`);if(c&&r.name!==c){if(u)throw new Error(`Could not find environment with name "${c}" in config file`);console.warn(`Could not find environment with name "${c}" in config file, trying to use default environment`)}if(n&&p.role!==n){if(u)throw new Error(`Could not find user with role "${n}" for environment "${c}" in config file`);console.warn(`Could not find user with role "${n}" for environment "${c}" in config file, trying to login with environment's default user`)}return{environment:r,user:p}}s(HQ,"resolveEnvironment");function fje(i){let n=`${i??To()}/login.ts`;if(!(0,HI.existsSync)(n))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${n}`),new Error("Could not find login.ts file");try{return(0,ire.createRequire)(__filename)(n).default}catch(c){throw console.warn("Error loading login.ts file",c),c}}s(fje,"requireLogin");async function dje(i,n,{environment:c,user:u,config:r}){try{let f=s(()=>n(i,{environment:c,user:u,config:r}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${u?.role?` using ${u.role} role`:""}${c?.name?` in ${c.name} environment`:""}`,f,{skipAutoRecovery:!0}):await f()}catch(f){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
|
|
323
|
-
`,f),f}}s(dje,"proceedWithLogin");function Ml(i){let{config:n,folder:c,throwIfAuthFailed:u}=i,r=fje(c);return async(f,{role:p,environment:d}={})=>{let{envName:h,role:o}=jQ({...d!==void 0?{envName:d}:{},...p!==void 0?{role:p}:{}}),{environment:a,user:e}=HQ(n,{...o!==void 0?{role:o}:{},...h!==void 0?{environment:h}:{}},i.throwIfEnvInfoInvalid);if(u&&!e)throw new Error("Could not find user credentials matching the provided role and/or environment");await dje(f,r,{environment:a,user:e,config:n})}}s(Ml,"makeUnboundLogin");function cre(i,{environmentName:n,userRole:c}){let u=Ml(i);return r=>u(r,{environment:n,role:c})}s(cre,"makeBoundLogin");var Ko;function PE(){if(Ko)return Ko;try{let i=(0,HI.existsSync)(`${To()}/checksum.config.ts`)?"checksum.config.ts":(0,HI.existsSync)(`${To()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return WI(Zoe(`${To()}/${i}`))}catch{console.warn("Could not find checksum config file, will run with defaults")}return WI()}s(PE,"loadChecksumConfig");function WI(i={}){let n={apiKey:"",runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1,skipTestsWithKnownBugs:!0},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,consecutiveActionDelay:100,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return i.options?.useChecksumAI?.visualComparison===void 0&&i.options?.useChecksumAI?.assertions&&(i.options.useChecksumAI.visualComparison=!0),Ko=ore(n,i),process.env.CHECKSUM_API_URL&&(Ko.apiURL=process.env.CHECKSUM_API_URL),_e.testRun.disableAutoRecovery&&Ko.options&&(Ko.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),_e.testRun.disableHostReports&&Ko.options&&(Ko.options.hostReports=!1),Ko.options&&(_e.testRun.disableTimeMachine&&(Ko.options.disableTimeMachine=!0),_e.testRun.disableRrwebRecording&&(Ko.options.disableRrwebRecording=!0)),Ko}s(WI,"getChecksumConfig");var za="Checksum failed connecting to the server";var tBt=require("@playwright/test");async function lre(i){await i.body?.cancel().catch(()=>{})}s(lre,"drainBody");var pje="http://127.0.0.1";async function WQ(i,n){let c=n.fetchImpl??globalThis.fetch;try{let u=await c(`${pje}:${n.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(n.timeoutMs)});return await lre(u),u.ok?!0:(n.onError?.(new Error(`monitor rejected message with status ${u.status}`)),!1)}catch(u){return n.onError?.(u),!1}}s(WQ,"postToMonitor");async function GQ(i,n){return await WQ(i,n)?!0:n.attempts<=1?!1:(await hje(n.retryDelayMs),GQ(i,{...n,attempts:n.attempts-1}))}s(GQ,"postToMonitorWithRetry");function hje(i){return new Promise(n=>{setTimeout(n,i)})}s(hje,"sleep");var GI={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:6e4,min:5e3,max:6e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function gje(i,n,c,u){if(i===void 0||i.trim()==="")return n;let r=Number(i);return Number.isInteger(r)?Math.min(u,Math.max(c,r)):n}s(gje,"clampEnvInt");var Aje=[["cliHardCapMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function yje(i){let n={...i},c=[];for(let[u,r,f]of Aje)for(let p of r){let d=Math.floor(n[u]*f);n[p]>d&&(c.push(`${GI[p].env} (${n[p]}ms) exceeds its bound under ${GI[u].env} (${n[u]}ms); using ${d}ms`),n[p]=d)}return{tunables:n,warnings:c}}s(yje,"coerceScopeHierarchy");function vje(i){let n={};for(let c of Object.keys(GI)){let u=GI[c];n[c]=gje(i[u.env],u.fallback,u.min,u.max)}return n.resumableChunkBytes=Math.max(1,Math.floor(n.resumableChunkBytes/262144))*262144,yje(n)}s(vje,"resolveUploadTunablesDetailed");function JQ(i){return vje(i).tunables}s(JQ,"resolveUploadTunables");var V_t=JQ({});var bje=4,sre=3,mje=500,JI=class i{constructor(n){this.workerInfo=n;this.hasMonitor=!1;i.monitorAgentPort?this.hasMonitor=!0:he("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}static{s(this,"TestRunMonitorBridge")}static{this.monitorAgentHost="http://localhost"}static{this.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT}static{this.playwrightConfigSent=!1}static{this.tunables=JQ(process.env)}addAsset(n){this.signalUpload(n,["trace","har","rrweb-recording"].includes(n.type))}addChecksumTestMetadata(n){let c={type:"checksumTestMetadata",payload:n};this.sendMessage(c)}addTestInfo(n,c,u=!1){this.sendMessage({type:"testInfo",payload:{checksumTestId:n,pwTestId:c,usingChecksumTestIdPlaceholder:u}})}addSingleTestStats(n,c){this.sendMessage({type:"testStats",payload:{passed:n,healed:c}})}sendPlaywrightConfig(){if(i.playwrightConfigSent)return;let n=this.buildPlaywrightConfig();this.sendMessage({type:"playwrightConfig",payload:n}),i.playwrightConfigSent=!0}buildPlaywrightConfig(){let{use:n,testDir:c,testMatch:u,testIgnore:r,timeout:f,outputDir:p,retries:d}=this.workerInfo.project,{reporter:h,configFile:o,projects:a}=this.workerInfo.config,e=Object.keys(a).filter(t=>[n,c,u,r,f,p,d].includes(t)).reduce((t,l)=>({...t,[l]:a[Number(l)]}),{});return{reporter:h,...o!==void 0?{configFile:o}:{},filteredProjects:e,use:n,testDir:c,testMatch:u,testIgnore:r,timeout:f,outputDir:p,retries:d}}sendMessage(n){return this.hasMonitor&&i.monitorAgentPort?WQ(n,{port:i.monitorAgentPort,timeoutMs:i.tunables.ipcTimeoutMs,onError:s(c=>he("Failed to send message to test run monitor",n,c),"onError")}):void 0}async signalUpload(n,c=!1){let u=i.monitorAgentPort;if(!this.hasMonitor||!u)return;let r={type:"asset",payload:n,watch:c},f;await GQ(r,{port:u,timeoutMs:i.tunables.ipcTimeoutMs*bje,attempts:sre,retryDelayMs:mje,onError:s(d=>{f=d,he("Failed to register asset with test run monitor",r,d)},"onError")})||ky("asset_registration_failed",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:"error",asset_type:n.type,asset_path:n.path,attempts:sre,error:Pd(f)})}};var ure=require("@playwright/test"),fre=require("puppeteer-extra-plugin"),dre=require("module");var qI=(0,dre.createRequire)(__filename),$I=class i{constructor(n){this.options=n;this.importPluginPackages()}static{s(this,"StealthProvider")}importPluginPackages(){i.pw??=qI("playwright-extra"),i.StealthPlugin??=qI("puppeteer-extra-plugin-stealth")}static createFreshInstance(){try{let{addExtra:n}=qI("playwright-extra");return n(i.pw.chromium)}catch(n){throw console.error("[StealthProvider] Error creating fresh instance:",n),n}}buildChromiumWithPlugins(n){let{project:c}=this.options,u=c.use.userAgent,r=c.use.playwrightExtra??[],f=i.StealthPlugin();if(r.push(f),this.isCustomUserAgent(u)){f.enabledEvasions.delete("user-agent-override");let h=qI("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:u});r.push(h)}let p=n??i.pw.chromium;return r.forEach((d,h)=>{try{!(d instanceof fre.PuppeteerExtraPlugin)&&d!==f&&console.warn(`Plugin at index ${h} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),p.use(d)}catch(o){console.warn(o)}}),p}isCustomUserAgent(n){return n?!Object.values(ure.devices).some(c=>n===c.userAgent):!1}};function pre(i,n){return{testSuiteRunId:n,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}s(pre,"createDefaultTestSuiteRunInfo");var Are=require("crypto");var dBt=require("@playwright/test");var bBt=require("@playwright/test");function hre(i,n){return Reflect.get(i,n)}s(hre,"readDynamicProperty");var VI=class i{constructor(n){this.context=n;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++i.instanceCounter,this.proxy=this.createContextProxy()}static{s(this,"ChecksumBrowserContext")}static{this.instanceCounter=0}static{this.guidCounter=0}static makeContext(n){return new i(n).proxy}_rawContext(){return this.context}setTestAssets(n){this._testAssets=n,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let n=await this.context.newPage();return this.makePage(n)}async makePage(n){if(n._isChecksumPage===!0)return n;if(n.isClosed())throw new Error("Cannot initialize closed page");let c=this.getPageGuid(n),u=this.getPageByGuid(c);if(u)return u;let r=this._pagesInProgress.get(c);if(r)return r;let f=this._createPageInstance(n);this._pagesInProgress.set(c,f);try{let p=await f;return this._pagesInProgress.delete(c),this.addPage(p),p}catch(p){throw this._pagesInProgress.delete(c),p}}addPage(n){let c=this.getPageGuid(n);this._pages[c]=n,n.once("close",()=>{this.removePage(c)})}removePage(n){this._pages[n]&&delete this._pages[n]}async _createPageInstance(n){if(n.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await UI.init(n,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(c){throw new Error(`Failed to initialize RuntimePage: ${c instanceof Error?c.message:String(c)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}createContextProxy(){return new Proxy(this,{get:s(function(c,u){return c.getContextMethod(u)},"get")})}setupPageListener(){this.context.on("page",async n=>{try{if(n.isClosed())return;await this.makePage(n)}catch(c){let u=c instanceof Error?c.message:String(c);if(u.includes("Page has already been closed")||u.includes("Target page, context or browser has been closed"))return;throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",c),c}})}getPageGuid(n){let c=this.pageGuidMap.get(n);return c||(c=`page@checksumctx_${this.instanceId}_${++i.guidCounter}`,this.pageGuidMap.set(n,c)),c}getPageByGuid(n){return this._pages[n]}getAllPages(){return Object.values(this._pages)}getContextMethod(n){if(n in this){let u=hre(this,n);return typeof u=="function"?u.bind(this):u}let c=hre(this.context,n);return typeof c=="function"?c.bind(this.context):c}pages(){return this.getAllPages()}getPage(n){let c=this.getAllPages(),u=c[n];if(!u)throw new Error(`Page with index ${n} not found. Total pages: ${c.length}`);return u}};var qQ={},yre=s((i,n,c={},u=!1)=>{let{environments:r}=n,f=r?.find(d=>d.default),p=i.extend({baseURL:f?.baseURL,bypassCSP:!0,permissions:s(async({},d,h)=>{await d(h.project.use.permissions)},"permissions"),proxy:s(async({proxy:d},h)=>{d?await h({...d,bypass:"127.0.0.1,localhost"}):await h(d)},"proxy"),browser:s(async({browser:d,launchOptions:h},o,a)=>{let e=s(()=>(a.project.use.playwrightExtra||[]).some(g=>g.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),t=s(async()=>{let g=await(await new $I({project:a.project}).buildChromiumWithPlugins()).launch(h);await o(g)},"launchBrowserWithStealthPlugin");_e.useRemoteDebugging.enabled&&e()?await t():await o(d)},"browser"),launchOptions:s(async({launchOptions:d},h)=>{let o=d?.args?[...d.args]:[],a=s(e=>{o.includes(e)||o.push(e)},"pushArg");c.useMockData&&a("--disable-web-security"),_e.bypassProxyForLocalhost&&a("--proxy-bypass-list=localhost,127.0.0.1"),_e.useRemoteDebugging.enabled&&a(`--remote-debugging-port=${_e.useRemoteDebugging.port}`),await h({...d,args:o})},"launchOptions"),variableStore:s(async({},d)=>{let h=new tf;await d(h)},"variableStore"),vs:s(async({variableStore:d},h)=>{await h(d)},"vs"),variablesStore:s(async({variableStore:d},h)=>{await h(d)},"variablesStore"),testRunAnalytics:s(async({},d,h)=>{let o=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),pre("playwright-run-version-unknown",(0,Are.randomUUID)())}})(),a=gre(h)??"",e=Vo.getTestRunInstance({...o,checksumTestId:a},process.env.CHECKSUM_ISOLATED_MODE==="true",h);await d(e)},"testRunAnalytics"),monitorBridge:[async({},d,h)=>{let o=new JI(h);await d(o)},{scope:"worker"}],context:s(async({context:d,monitorBridge:h,variableStore:o,testRunAnalytics:a},e,t)=>{let l=VI.makeContext(d);l.setTestAssets({testRunAnalytics:a,monitorBridge:h,variableStore:o,testInfo:t,checksumTestId:gre(t),test:p,config:n,isReplMode:u}),await e(l),l.cleanup()},"context"),page:s(async({page:d,context:h},o,a)=>{let e=await h.makePage(d);Object.defineProperty(e.constructor,"name",{value:"Page"}),await o(e),e&&typeof e.onTestComplete=="function"&&await e.onTestComplete(a.status==="passed"),e&&typeof e.shutdown=="function"&&await e.shutdown()},"page")});return{test:p,defineChecksumTest:Eje}},"createChecksumTestExtension"),Eje=s((i,n,c)=>{let r=(new Error().stack?.split(`
|
|
323
|
+
`,f),f}}s(dje,"proceedWithLogin");function Ml(i){let{config:n,folder:c,throwIfAuthFailed:u}=i,r=fje(c);return async(f,{role:p,environment:d}={})=>{let{envName:h,role:o}=jQ({...d!==void 0?{envName:d}:{},...p!==void 0?{role:p}:{}}),{environment:a,user:e}=HQ(n,{...o!==void 0?{role:o}:{},...h!==void 0?{environment:h}:{}},i.throwIfEnvInfoInvalid);if(u&&!e)throw new Error("Could not find user credentials matching the provided role and/or environment");await dje(f,r,{environment:a,user:e,config:n})}}s(Ml,"makeUnboundLogin");function cre(i,{environmentName:n,userRole:c}){let u=Ml(i);return r=>u(r,{environment:n,role:c})}s(cre,"makeBoundLogin");var Ko;function PE(){if(Ko)return Ko;try{let i=(0,HI.existsSync)(`${To()}/checksum.config.ts`)?"checksum.config.ts":(0,HI.existsSync)(`${To()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return WI(Zoe(`${To()}/${i}`))}catch{console.warn("Could not find checksum config file, will run with defaults")}return WI()}s(PE,"loadChecksumConfig");function WI(i={}){let n={apiKey:"",runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1,skipTestsWithKnownBugs:!0},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,consecutiveActionDelay:100,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return i.options?.useChecksumAI?.visualComparison===void 0&&i.options?.useChecksumAI?.assertions&&(i.options.useChecksumAI.visualComparison=!0),Ko=ore(n,i),process.env.CHECKSUM_API_URL&&(Ko.apiURL=process.env.CHECKSUM_API_URL),_e.testRun.disableAutoRecovery&&Ko.options&&(Ko.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),_e.testRun.disableHostReports&&Ko.options&&(Ko.options.hostReports=!1),Ko.options&&(_e.testRun.disableTimeMachine&&(Ko.options.disableTimeMachine=!0),_e.testRun.disableRrwebRecording&&(Ko.options.disableRrwebRecording=!0)),Ko}s(WI,"getChecksumConfig");var za="Checksum failed connecting to the server";var tBt=require("@playwright/test");async function lre(i){await i.body?.cancel().catch(()=>{})}s(lre,"drainBody");var pje="http://127.0.0.1";async function WQ(i,n){let c=n.fetchImpl??globalThis.fetch;try{let u=await c(`${pje}:${n.port}/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(n.timeoutMs)});return await lre(u),u.ok?!0:(n.onError?.(new Error(`monitor rejected message with status ${u.status}`)),!1)}catch(u){return n.onError?.(u),!1}}s(WQ,"postToMonitor");async function GQ(i,n){return await WQ(i,n)?!0:n.attempts<=1?!1:(await hje(n.retryDelayMs),GQ(i,{...n,attempts:n.attempts-1}))}s(GQ,"postToMonitorWithRetry");function hje(i){return new Promise(n=>{setTimeout(n,i)})}s(hje,"sleep");var GI={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function gje(i,n,c,u){if(i===void 0||i.trim()==="")return n;let r=Number(i);return Number.isInteger(r)?Math.min(u,Math.max(c,r)):n}s(gje,"clampEnvInt");var Aje=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function yje(i){let n={...i},c=[];for(let[u,r,f]of Aje)for(let p of r){let d=Math.floor(n[u]*f);n[p]>d&&(c.push(`${GI[p].env} (${n[p]}ms) exceeds its bound under ${GI[u].env} (${n[u]}ms); using ${d}ms`),n[p]=d)}return{tunables:n,warnings:c}}s(yje,"coerceScopeHierarchy");function vje(i){let n={};for(let c of Object.keys(GI)){let u=GI[c];n[c]=gje(i[u.env],u.fallback,u.min,u.max)}return n.resumableChunkBytes=Math.max(1,Math.floor(n.resumableChunkBytes/262144))*262144,yje(n)}s(vje,"resolveUploadTunablesDetailed");function JQ(i){return vje(i).tunables}s(JQ,"resolveUploadTunables");var V_t=JQ({});var bje=4,sre=3,mje=500,JI=class i{constructor(n){this.workerInfo=n;this.hasMonitor=!1;i.monitorAgentPort?this.hasMonitor=!0:he("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}static{s(this,"TestRunMonitorBridge")}static{this.monitorAgentHost="http://localhost"}static{this.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT}static{this.playwrightConfigSent=!1}static{this.tunables=JQ(process.env)}addAsset(n){this.signalUpload(n,["trace","har","rrweb-recording"].includes(n.type))}addChecksumTestMetadata(n){let c={type:"checksumTestMetadata",payload:n};this.sendMessage(c)}addTestInfo(n,c,u=!1){this.sendMessage({type:"testInfo",payload:{checksumTestId:n,pwTestId:c,usingChecksumTestIdPlaceholder:u}})}addSingleTestStats(n,c){this.sendMessage({type:"testStats",payload:{passed:n,healed:c}})}sendPlaywrightConfig(){if(i.playwrightConfigSent)return;let n=this.buildPlaywrightConfig();this.sendMessage({type:"playwrightConfig",payload:n}),i.playwrightConfigSent=!0}buildPlaywrightConfig(){let{use:n,testDir:c,testMatch:u,testIgnore:r,timeout:f,outputDir:p,retries:d}=this.workerInfo.project,{reporter:h,configFile:o,projects:a}=this.workerInfo.config,e=Object.keys(a).filter(t=>[n,c,u,r,f,p,d].includes(t)).reduce((t,l)=>({...t,[l]:a[Number(l)]}),{});return{reporter:h,...o!==void 0?{configFile:o}:{},filteredProjects:e,use:n,testDir:c,testMatch:u,testIgnore:r,timeout:f,outputDir:p,retries:d}}sendMessage(n){return this.hasMonitor&&i.monitorAgentPort?WQ(n,{port:i.monitorAgentPort,timeoutMs:i.tunables.ipcTimeoutMs,onError:s(c=>he("Failed to send message to test run monitor",n,c),"onError")}):void 0}async signalUpload(n,c=!1){let u=i.monitorAgentPort;if(!this.hasMonitor||!u)return;let r={type:"asset",payload:n,watch:c},f;await GQ(r,{port:u,timeoutMs:i.tunables.ipcTimeoutMs*bje,attempts:sre,retryDelayMs:mje,onError:s(d=>{f=d,he("Failed to register asset with test run monitor",r,d)},"onError")})||ky("asset_registration_failed",{test_suite_run_id:process.env.CHECKSUM_TEST_SUITE_ID,outcome:"error",asset_type:n.type,asset_path:n.path,attempts:sre,error:Pd(f)})}};var ure=require("@playwright/test"),fre=require("puppeteer-extra-plugin"),dre=require("module");var qI=(0,dre.createRequire)(__filename),$I=class i{constructor(n){this.options=n;this.importPluginPackages()}static{s(this,"StealthProvider")}importPluginPackages(){i.pw??=qI("playwright-extra"),i.StealthPlugin??=qI("puppeteer-extra-plugin-stealth")}static createFreshInstance(){try{let{addExtra:n}=qI("playwright-extra");return n(i.pw.chromium)}catch(n){throw console.error("[StealthProvider] Error creating fresh instance:",n),n}}buildChromiumWithPlugins(n){let{project:c}=this.options,u=c.use.userAgent,r=c.use.playwrightExtra??[],f=i.StealthPlugin();if(r.push(f),this.isCustomUserAgent(u)){f.enabledEvasions.delete("user-agent-override");let h=qI("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:u});r.push(h)}let p=n??i.pw.chromium;return r.forEach((d,h)=>{try{!(d instanceof fre.PuppeteerExtraPlugin)&&d!==f&&console.warn(`Plugin at index ${h} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),p.use(d)}catch(o){console.warn(o)}}),p}isCustomUserAgent(n){return n?!Object.values(ure.devices).some(c=>n===c.userAgent):!1}};function pre(i,n){return{testSuiteRunId:n,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}s(pre,"createDefaultTestSuiteRunInfo");var Are=require("crypto");var dBt=require("@playwright/test");var bBt=require("@playwright/test");function hre(i,n){return Reflect.get(i,n)}s(hre,"readDynamicProperty");var VI=class i{constructor(n){this.context=n;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++i.instanceCounter,this.proxy=this.createContextProxy()}static{s(this,"ChecksumBrowserContext")}static{this.instanceCounter=0}static{this.guidCounter=0}static makeContext(n){return new i(n).proxy}_rawContext(){return this.context}setTestAssets(n){this._testAssets=n,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let n=await this.context.newPage();return this.makePage(n)}async makePage(n){if(n._isChecksumPage===!0)return n;if(n.isClosed())throw new Error("Cannot initialize closed page");let c=this.getPageGuid(n),u=this.getPageByGuid(c);if(u)return u;let r=this._pagesInProgress.get(c);if(r)return r;let f=this._createPageInstance(n);this._pagesInProgress.set(c,f);try{let p=await f;return this._pagesInProgress.delete(c),this.addPage(p),p}catch(p){throw this._pagesInProgress.delete(c),p}}addPage(n){let c=this.getPageGuid(n);this._pages[c]=n,n.once("close",()=>{this.removePage(c)})}removePage(n){this._pages[n]&&delete this._pages[n]}async _createPageInstance(n){if(n.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await UI.init(n,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(c){throw new Error(`Failed to initialize RuntimePage: ${c instanceof Error?c.message:String(c)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}createContextProxy(){return new Proxy(this,{get:s(function(c,u){return c.getContextMethod(u)},"get")})}setupPageListener(){this.context.on("page",async n=>{try{if(n.isClosed())return;await this.makePage(n)}catch(c){let u=c instanceof Error?c.message:String(c);if(u.includes("Page has already been closed")||u.includes("Target page, context or browser has been closed"))return;throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",c),c}})}getPageGuid(n){let c=this.pageGuidMap.get(n);return c||(c=`page@checksumctx_${this.instanceId}_${++i.guidCounter}`,this.pageGuidMap.set(n,c)),c}getPageByGuid(n){return this._pages[n]}getAllPages(){return Object.values(this._pages)}getContextMethod(n){if(n in this){let u=hre(this,n);return typeof u=="function"?u.bind(this):u}let c=hre(this.context,n);return typeof c=="function"?c.bind(this.context):c}pages(){return this.getAllPages()}getPage(n){let c=this.getAllPages(),u=c[n];if(!u)throw new Error(`Page with index ${n} not found. Total pages: ${c.length}`);return u}};var qQ={},yre=s((i,n,c={},u=!1)=>{let{environments:r}=n,f=r?.find(d=>d.default),p=i.extend({baseURL:f?.baseURL,bypassCSP:!0,permissions:s(async({},d,h)=>{await d(h.project.use.permissions)},"permissions"),proxy:s(async({proxy:d},h)=>{d?await h({...d,bypass:"127.0.0.1,localhost"}):await h(d)},"proxy"),browser:s(async({browser:d,launchOptions:h},o,a)=>{let e=s(()=>(a.project.use.playwrightExtra||[]).some(g=>g.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),t=s(async()=>{let g=await(await new $I({project:a.project}).buildChromiumWithPlugins()).launch(h);await o(g)},"launchBrowserWithStealthPlugin");_e.useRemoteDebugging.enabled&&e()?await t():await o(d)},"browser"),launchOptions:s(async({launchOptions:d},h)=>{let o=d?.args?[...d.args]:[],a=s(e=>{o.includes(e)||o.push(e)},"pushArg");c.useMockData&&a("--disable-web-security"),_e.bypassProxyForLocalhost&&a("--proxy-bypass-list=localhost,127.0.0.1"),_e.useRemoteDebugging.enabled&&a(`--remote-debugging-port=${_e.useRemoteDebugging.port}`),await h({...d,args:o})},"launchOptions"),variableStore:s(async({},d)=>{let h=new tf;await d(h)},"variableStore"),vs:s(async({variableStore:d},h)=>{await h(d)},"vs"),variablesStore:s(async({variableStore:d},h)=>{await h(d)},"variablesStore"),testRunAnalytics:s(async({},d,h)=>{let o=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),pre("playwright-run-version-unknown",(0,Are.randomUUID)())}})(),a=gre(h)??"",e=Vo.getTestRunInstance({...o,checksumTestId:a},process.env.CHECKSUM_ISOLATED_MODE==="true",h);await d(e)},"testRunAnalytics"),monitorBridge:[async({},d,h)=>{let o=new JI(h);await d(o)},{scope:"worker"}],context:s(async({context:d,monitorBridge:h,variableStore:o,testRunAnalytics:a},e,t)=>{let l=VI.makeContext(d);l.setTestAssets({testRunAnalytics:a,monitorBridge:h,variableStore:o,testInfo:t,checksumTestId:gre(t),test:p,config:n,isReplMode:u}),await e(l),l.cleanup()},"context"),page:s(async({page:d,context:h},o,a)=>{let e=await h.makePage(d);Object.defineProperty(e.constructor,"name",{value:"Page"}),await o(e),e&&typeof e.onTestComplete=="function"&&await e.onTestComplete(a.status==="passed"),e&&typeof e.shutdown=="function"&&await e.shutdown()},"page")});return{test:p,defineChecksumTest:Eje}},"createChecksumTestExtension"),Eje=s((i,n,c)=>{let r=(new Error().stack?.split(`
|
|
324
324
|
`)??[]).find(f=>f.includes(".checksum.spec.ts"));if(!r)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return qQ[r]=n,i},"defineChecksumTest");function gre(i){let{file:n,line:c}=i,u=Object.keys(qQ).filter(f=>f.trim().includes(n.trim()));if(!u.length)return;let r=4;for(let f=0;f<r;f++)for(let p of u){let d;try{d=parseInt(p.split(":").reverse()[1]??"")}catch{continue}if(d-f===c)return qQ[p]}}s(gre,"getCurrentTestIdFromMapping");var XBt=require("@playwright/test");var UBt=require("@playwright/test");var Ije=["toMatchSnapshot"],Oje=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],vre=[...Oje,...Ije];var zI=class{constructor(n,c,u=!1,r=!1,f={}){this.page=n;this.soft=u;this.skipAutoRecovery=r;this.configuration=f;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=s(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(c)}static{s(this,"ExpectCallProxyHandler")}setThought(n){n&&(this.checksumAIThought=this.page.addNewThought(n,"assertion"),this.useChecksumAIOptions=this.page.getRuntimeOptions()?.useChecksumAI,this.useChecksumAIOptions?.assertions&&(this.page.setAIFallback(n,"assertion"),this.fallbackEnabled=!0))}get(n,c,u){if(typeof c!="string")return Reflect.get(n,c);if(c==="checksumAI")return f=>(this.setThought(f),u);if(c==="withChecksumAI"||typeof Reflect.get(n,c)=="function"){let f=c==="withChecksumAI"?this.withChecksumAIMatcher:Reflect.get(n,c);return(...p)=>vre.includes(c)?f.call(n,...p):this.checksumAIThought?this.executeMatcherWithinStep(f,n,...p):this.executeMatcher(f,n,...p)}let r=Reflect.get(n,c);return new Proxy(r,this)}findNestedErrors(n,c){n.error&&n.infectParentStepsWithError&&c.push(n.error);for(let u of n.steps)this.findNestedErrors(u,c)}async callMatcher(n,c,...u){this.beforeMatcherCall();let r=n.call(c,...u),f=r instanceof Promise?await r:r;if(this.step){let p=[];if(this.step.error?p.push(this.step.error):this.findNestedErrors(this.step,p),p.length)throw p[0]}return f}executeMatcherWithinStep(n,c,...u){let r=this.checksumAIThought;if(!r)throw new Error("ExpectCallProxyHandler: checksumAIThought is not set");return this.page.step(r.thought,()=>this.callMatcher(n,c,...u).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:s(f=>this.step=f,"obtainStep")}).catch(f=>{if(!this.soft&&!(this.withChecksumAI&&f.message===za))throw f}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(n,c,...u){try{return await this.callMatcher(n,c,...u)}catch(r){await this.onMatcherFailure(r);return}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(n){return!(!this.fallbackEnabled||Reflect.get(n,"matcherResult")?.name==="toHaveScreenshot"&&!this.useChecksumAIOptions?.visualComparison)}async onMatcherFailure(n){if(!this.shouldInitiateFallback(n))throw he("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:this.checksumAIThought?.thought??"",error:n.message,matcher:n.matcherResult?.name}),n;if(Jb()){if(he("[onMatcherFailure] assertion failed inside a locator handler, skipping fallback"),this.soft)return;throw n}if(he("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought?.thought),this.skipAutoRecovery){if(this.soft)return;throw n}try{await this.page.initiateFallbackSequence({type:"assertion",error:n,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(c){if(this.soft)return;throw c}throw this.soft=!0,n}};var YI=class i{constructor(n,c={}){this.page=n;this.configuration=c}static{s(this,"ExpectProxyHandler")}get(n,c){if(c==="setPage")return r=>{this.page=r};if(c==="extend")return(...r)=>{let f=n.extend(...r);return new Proxy(f,this)};if(c==="configure")return r=>{let f=n.configure(r);return new Proxy(f,new i(this.page,{...this.configuration,...r}))};if(c==="soft")return(...r)=>{let f=this.manipulateArgsAndExtractThought(r),p=n.soft(...r);return new Proxy(p,this.makeExpectCallProxyHandler(f,!0))};if(c==="poll")return(...r)=>{let f=this.manipulateArgsAndExtractThought(r),p=n.poll(...r);return new Proxy(p,this.makeExpectCallProxyHandler(f))};if(c==="skipAutoRecovery")return new Proxy(()=>{},{apply:s((f,p,d)=>{let h=this.manipulateArgsAndExtractThought(d),o=n.apply(p,d);return new Proxy(o,this.makeExpectCallProxyHandler(h,void 0,!0))},"apply"),get:s((f,p)=>{let d=new Proxy(n,new i(this.page,{...this.configuration,skipAutoRecovery:!0}));return Reflect.get(d,p)},"get")});let u=Reflect.get(n,c);return u instanceof Function?u.bind(n):u}apply(n,c,u){let r=this.manipulateArgsAndExtractThought(u),f=n.apply(c,u);return new Proxy(f,this.makeExpectCallProxyHandler(r))}makeExpectCallProxyHandler(n,c,u){if(!this.page)throw new Error("ExpectProxyHandler: page is not set");return new zI(this.page,n,c===!0?!0:this.configuration?.soft,u===!0?!0:this.configuration?.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(n){let c,u=n[1];if(typeof u=="string")c=u,n[1]=void 0;else if(u!==null&&typeof u=="object"){let r=u;if(r.checksumAI===!1){r.checksumAI=void 0;return}r.checksumAI&&typeof r.checksumAI=="string"?(c=r.checksumAI,r.checksumAI=void 0):r.message&&(c=r.message,r.message=void 0)}return c}};var KI=class i{constructor(n){this.expect=n;this.proxy=new Proxy(this.expect,new YI)}static{s(this,"ChecksumExpect")}static init(n){return new i(n).proxy}};var bre=require("@playwright/test");function wje(i,n=PE()){let{options:c,apiKey:u,environments:r,defaultEnvironmentName:f}=n,p=r?.find(g=>g.default);if(f&&(p=r?.find(g=>g.name===f)),!p)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!p.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!p.users?.find(g=>g.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!u)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let h=process.env.CHECKSUM_REPL==="true",{test:o,defineChecksumTest:a}=yre(i??bre.test,n,c,h),e=KI.init(o.expect),t=Cje();o._checksum={expect:e,checksumAI:t},h&&(o.beforeEach(async()=>{o.setTimeout(0)}),o.afterEach(async()=>{for(;;)await ze(1e3)}));let l=s(({name:g,userRole:A})=>{let{envName:y,role:v}=jQ({...g!==void 0?{envName:g}:{},...A!==void 0?{role:A}:{}}),{environment:w,user:E}=HQ(n,{...y!==void 0?{environment:y}:{},...v!==void 0?{role:v}:{}},!0),S=cre({config:n,throwIfEnvInfoInvalid:!0},{environmentName:w.name,userRole:E.role});return{environment:w,user:E,login:S}},"getEnvironment");return{test:o,expect:e,login:Ml({config:n}),defineChecksumTest:a,getEnvironment:l,checksumAI:t}}s(wje,"init");var $Q=s(i=>new Proxy(i,{apply:s(function(c,u,r){let f={...c.options,...r[2]};return c.page.checksumAI(r[0],r[1],f)},"apply"),get:s(function(c,u){return u==="withDialog"?(c.options.withDialog=!0,$Q(i)):u==="skipAutoRecovery"?(c.options.skipAutoRecovery=!0,$Q(i)):c[u]},"get"),set:s(function(c,u,r){return u!=="page"?!1:(c[u]=r,!!r)},"set")}),"makeChecksumAIProxy"),Cje=s(()=>{let i=s(function(){},"func");return i.page=void 0,i.options={withDialog:!1,skipAutoRecovery:!1},$Q(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,getChecksumConfig,getLogin,init});
|
|
325
325
|
/*! Bundled license information:
|
|
326
326
|
|
package/package.json
CHANGED