@checksum-ai/runtime 1.1.33 → 1.1.34
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/checksumlib.js +109 -69
- package/cli.js +2 -2
- package/index.js +51 -51
- package/package.json +1 -1
- package/vtg-build/asset-manifest.json +3 -3
- package/vtg-build/index.html +1 -1
- package/vtg-build/static/js/main.bbf3ab67.js +103 -0
- package/vtg-build/static/js/main.bbf3ab67.js.LICENSE.txt +118 -0
- package/vtg-build/static/js/main.bbf3ab67.js.map +1 -0
package/checksumlib.js
CHANGED
|
@@ -9714,9 +9714,6 @@
|
|
|
9714
9714
|
this.restoreNodeAttributes(node2, removedAttributes);
|
|
9715
9715
|
const result2 = await this.getElementWindowPlaywright(node2).$(selector);
|
|
9716
9716
|
if (result2 !== node2) {
|
|
9717
|
-
console.log(
|
|
9718
|
-
`Selector ${selector} is not valid, trying to generate new one`
|
|
9719
|
-
);
|
|
9720
9717
|
({ selector, locator } = await this.safeGetSelectorAndLocator(
|
|
9721
9718
|
nodeHTML
|
|
9722
9719
|
));
|
|
@@ -29390,8 +29387,9 @@
|
|
|
29390
29387
|
var SessionReplayer = class {
|
|
29391
29388
|
constructor(config = {}) {
|
|
29392
29389
|
this.events = [];
|
|
29393
|
-
this.
|
|
29390
|
+
this.numberOfCastedEvents = 0;
|
|
29394
29391
|
this.isLive = true;
|
|
29392
|
+
this.liveEvents = [];
|
|
29395
29393
|
// private currentTraveledTimestamp: number = undefined;
|
|
29396
29394
|
this.currentTraveledNumberOfEvents = void 0;
|
|
29397
29395
|
this.config = {
|
|
@@ -29420,8 +29418,8 @@
|
|
|
29420
29418
|
this.events = [...this.events, ...sortedNewEvents];
|
|
29421
29419
|
const promise = new Promise((resolve2) => {
|
|
29422
29420
|
this.onEventCast = (event) => {
|
|
29423
|
-
this.
|
|
29424
|
-
if (this.
|
|
29421
|
+
this.numberOfCastedEvents++;
|
|
29422
|
+
if (this.numberOfCastedEvents === this.events.length) {
|
|
29425
29423
|
this.onEventCast = void 0;
|
|
29426
29424
|
resolve2();
|
|
29427
29425
|
}
|
|
@@ -29438,6 +29436,20 @@
|
|
|
29438
29436
|
this.getOriginalTimestamp = /* @__PURE__ */ __name((event) => {
|
|
29439
29437
|
return event.originalTimestamp ?? event.timestamp;
|
|
29440
29438
|
}, "getOriginalTimestamp");
|
|
29439
|
+
this.trimEventsToLastCheckout = /* @__PURE__ */ __name((events) => {
|
|
29440
|
+
const lastCheckoutEventIndex = events.reduce(
|
|
29441
|
+
(lastCheckoutEventIndex2, event, index2) => {
|
|
29442
|
+
return event.isCheckout && event.type === EventType.Meta ? index2 : lastCheckoutEventIndex2;
|
|
29443
|
+
},
|
|
29444
|
+
void 0
|
|
29445
|
+
);
|
|
29446
|
+
let trimmedEvents = events;
|
|
29447
|
+
if (lastCheckoutEventIndex !== void 0) {
|
|
29448
|
+
trimmedEvents = events.slice(lastCheckoutEventIndex);
|
|
29449
|
+
}
|
|
29450
|
+
const castedEvents = lastCheckoutEventIndex !== void 0 ? this.liveEvents.slice(0, lastCheckoutEventIndex) : [];
|
|
29451
|
+
return { trimmedEvents, castedEvents, lastCheckoutEventIndex };
|
|
29452
|
+
}, "trimEventsToLastCheckout");
|
|
29441
29453
|
this.getNodeById = /* @__PURE__ */ __name((id) => {
|
|
29442
29454
|
return this.replayer.getMirror().getNode(id);
|
|
29443
29455
|
}, "getNodeById");
|
|
@@ -29445,36 +29457,49 @@
|
|
|
29445
29457
|
return this.replayer.getMirror().getMeta(node2);
|
|
29446
29458
|
}, "getMeta");
|
|
29447
29459
|
this.config = { ...this.config, ...config };
|
|
29460
|
+
this.goBackWithEvents = this.goBackWithEvents_native;
|
|
29448
29461
|
}
|
|
29449
29462
|
static {
|
|
29450
29463
|
__name(this, "SessionReplayer");
|
|
29451
29464
|
}
|
|
29452
|
-
|
|
29453
|
-
this.startOptions = options;
|
|
29454
|
-
const {
|
|
29455
|
-
firstEventTimestamp,
|
|
29456
|
-
speed = 8,
|
|
29457
|
-
useTimestampCompression = true
|
|
29458
|
-
} = options;
|
|
29465
|
+
makeReplayerConfig(live, { speed = 8 } = {}) {
|
|
29459
29466
|
const playerConfig = {
|
|
29460
29467
|
mouseTail: false,
|
|
29461
29468
|
pauseAnimation: false,
|
|
29462
29469
|
speed,
|
|
29463
29470
|
triggerFocus: true,
|
|
29464
29471
|
UNSAFE_replayCanvas: true,
|
|
29465
|
-
liveMode:
|
|
29472
|
+
liveMode: live,
|
|
29466
29473
|
showDebug: false,
|
|
29467
|
-
skipInactive: true
|
|
29474
|
+
skipInactive: true,
|
|
29475
|
+
inactivePeriodThreshold: 100
|
|
29468
29476
|
};
|
|
29469
29477
|
if (this.config.root) {
|
|
29470
29478
|
playerConfig.root = this.config.root;
|
|
29471
29479
|
}
|
|
29472
|
-
|
|
29480
|
+
return playerConfig;
|
|
29481
|
+
}
|
|
29482
|
+
makeReplayer(events, live, { speed = 8 } = {}) {
|
|
29483
|
+
this.replayer = new Replayer(
|
|
29484
|
+
events,
|
|
29485
|
+
this.makeReplayerConfig(live, { speed })
|
|
29486
|
+
);
|
|
29473
29487
|
if (this.config.enableInteract) {
|
|
29474
29488
|
this.replayer.enableInteract();
|
|
29475
29489
|
} else {
|
|
29476
29490
|
this.replayer.disableInteract();
|
|
29477
29491
|
}
|
|
29492
|
+
}
|
|
29493
|
+
start(options, castedEvents = []) {
|
|
29494
|
+
this.startOptions = options;
|
|
29495
|
+
const {
|
|
29496
|
+
firstEventTimestamp,
|
|
29497
|
+
speed = 8,
|
|
29498
|
+
useTimestampCompression = true
|
|
29499
|
+
} = options;
|
|
29500
|
+
this.events = castedEvents;
|
|
29501
|
+
this.numberOfCastedEvents = castedEvents.length;
|
|
29502
|
+
this.makeReplayer([], true, { speed });
|
|
29478
29503
|
this.useTimestampCompression = useTimestampCompression;
|
|
29479
29504
|
this.replayer.startLive(
|
|
29480
29505
|
this.useTimestampCompression ? Date.now() : firstEventTimestamp
|
|
@@ -29485,20 +29510,23 @@
|
|
|
29485
29510
|
}
|
|
29486
29511
|
});
|
|
29487
29512
|
}
|
|
29488
|
-
|
|
29489
|
-
|
|
29490
|
-
|
|
29491
|
-
|
|
29492
|
-
|
|
29493
|
-
|
|
29494
|
-
|
|
29495
|
-
|
|
29496
|
-
|
|
29497
|
-
|
|
29498
|
-
|
|
29499
|
-
|
|
29500
|
-
|
|
29501
|
-
|
|
29513
|
+
async goLive(sleepAfter = 1e3) {
|
|
29514
|
+
if (this.isLive) {
|
|
29515
|
+
return;
|
|
29516
|
+
}
|
|
29517
|
+
this.stop();
|
|
29518
|
+
this.currentTraveledNumberOfEvents = void 0;
|
|
29519
|
+
const { trimmedEvents, castedEvents } = this.trimEventsToLastCheckout(
|
|
29520
|
+
this.liveEvents
|
|
29521
|
+
);
|
|
29522
|
+
this.start(this.startOptions, castedEvents);
|
|
29523
|
+
this.isLive = true;
|
|
29524
|
+
await this.fastForward(trimmedEvents);
|
|
29525
|
+
if (sleepAfter) {
|
|
29526
|
+
await (0, import_await_sleep3.default)(sleepAfter);
|
|
29527
|
+
}
|
|
29528
|
+
}
|
|
29529
|
+
async goBackWithEvents_native(getEvents2, { sleepAfter = 1e3 }) {
|
|
29502
29530
|
if (this.isLive) {
|
|
29503
29531
|
this.liveEvents = this.events;
|
|
29504
29532
|
}
|
|
@@ -29506,38 +29534,65 @@
|
|
|
29506
29534
|
if (events.length === this.currentTraveledNumberOfEvents) {
|
|
29507
29535
|
return;
|
|
29508
29536
|
}
|
|
29509
|
-
const lastCheckoutEventIndex = events.reduce(
|
|
29510
|
-
(lastCheckoutEventIndex2, event, index2) => {
|
|
29511
|
-
return event.isCheckout && event.type === EventType.Meta ? index2 : lastCheckoutEventIndex2;
|
|
29512
|
-
},
|
|
29513
|
-
void 0
|
|
29514
|
-
);
|
|
29515
|
-
if (lastCheckoutEventIndex !== void 0) {
|
|
29516
|
-
console.log(
|
|
29517
|
-
"lastCheckoutEventIndex:",
|
|
29518
|
-
lastCheckoutEventIndex,
|
|
29519
|
-
"number of events to render:",
|
|
29520
|
-
events.length - lastCheckoutEventIndex
|
|
29521
|
-
);
|
|
29522
|
-
events.splice(lastCheckoutEventIndex);
|
|
29523
|
-
}
|
|
29524
29537
|
this.stop();
|
|
29525
29538
|
this.events = [];
|
|
29526
|
-
this.
|
|
29527
|
-
this.start(this.startOptions);
|
|
29539
|
+
this.numberOfCastedEvents = 0;
|
|
29528
29540
|
this.isLive = false;
|
|
29529
29541
|
this.currentTraveledNumberOfEvents = events.length;
|
|
29530
|
-
|
|
29542
|
+
const { trimmedEvents } = this.trimEventsToLastCheckout(events);
|
|
29543
|
+
this.makeReplayer(trimmedEvents, false, { speed: 360 });
|
|
29544
|
+
this.replayer.play(trimmedEvents[trimmedEvents.length - 1].timestamp);
|
|
29531
29545
|
if (sleepAfter) {
|
|
29532
29546
|
await (0, import_await_sleep3.default)(sleepAfter);
|
|
29533
29547
|
}
|
|
29534
29548
|
}
|
|
29535
|
-
async
|
|
29536
|
-
|
|
29537
|
-
|
|
29538
|
-
|
|
29539
|
-
|
|
29540
|
-
|
|
29549
|
+
async goBackWithEvents_native2(getEvents2, { sleepAfter = 1e3 }) {
|
|
29550
|
+
try {
|
|
29551
|
+
const events = getEvents2();
|
|
29552
|
+
const targetTimestamp = events[events.length - 1]?.timestamp ?? 0;
|
|
29553
|
+
const getTimeForPause = /* @__PURE__ */ __name(() => {
|
|
29554
|
+
return targetTimestamp - (this.events[0].timestamp ?? 0);
|
|
29555
|
+
}, "getTimeForPause");
|
|
29556
|
+
if (!this.isLive && targetTimestamp <= this.events[this.events.length - 1].timestamp) {
|
|
29557
|
+
const timeForPause2 = getTimeForPause();
|
|
29558
|
+
this.replayer.pause(timeForPause2);
|
|
29559
|
+
return;
|
|
29560
|
+
}
|
|
29561
|
+
if (this.isLive) {
|
|
29562
|
+
this.liveEvents = this.events;
|
|
29563
|
+
}
|
|
29564
|
+
this.stop();
|
|
29565
|
+
this.events = this.liveEvents;
|
|
29566
|
+
this.numberOfCastedEvents = this.liveEvents.length;
|
|
29567
|
+
this.isLive = false;
|
|
29568
|
+
this.makeReplayer(this.events, false, { speed: 360 });
|
|
29569
|
+
const timeForPause = getTimeForPause();
|
|
29570
|
+
this.replayer.pause(timeForPause);
|
|
29571
|
+
} finally {
|
|
29572
|
+
if (sleepAfter) {
|
|
29573
|
+
await (0, import_await_sleep3.default)(sleepAfter);
|
|
29574
|
+
}
|
|
29575
|
+
}
|
|
29576
|
+
}
|
|
29577
|
+
async goBackWithEvents_FFwd(getEvents2, { sleepAfter = 1e3 }) {
|
|
29578
|
+
if (this.isLive) {
|
|
29579
|
+
this.liveEvents = this.events;
|
|
29580
|
+
}
|
|
29581
|
+
const events = getEvents2();
|
|
29582
|
+
if (events.length === this.currentTraveledNumberOfEvents) {
|
|
29583
|
+
return;
|
|
29584
|
+
}
|
|
29585
|
+
this.currentTraveledNumberOfEvents = events.length;
|
|
29586
|
+
this.stop();
|
|
29587
|
+
const { trimmedEvents, castedEvents } = this.trimEventsToLastCheckout(
|
|
29588
|
+
this.liveEvents
|
|
29589
|
+
);
|
|
29590
|
+
this.start(this.startOptions, castedEvents);
|
|
29591
|
+
this.isLive = false;
|
|
29592
|
+
await this.fastForward(trimmedEvents, true);
|
|
29593
|
+
if (sleepAfter) {
|
|
29594
|
+
await (0, import_await_sleep3.default)(sleepAfter);
|
|
29595
|
+
}
|
|
29541
29596
|
}
|
|
29542
29597
|
async goBack(timestamp, {
|
|
29543
29598
|
sleepAfter = 1e3,
|
|
@@ -29577,21 +29632,6 @@
|
|
|
29577
29632
|
sleepAfter
|
|
29578
29633
|
});
|
|
29579
29634
|
}
|
|
29580
|
-
async goLive(sleepAfter = 1e3) {
|
|
29581
|
-
if (this.isLive) {
|
|
29582
|
-
return;
|
|
29583
|
-
}
|
|
29584
|
-
this.stop();
|
|
29585
|
-
this.currentTraveledNumberOfEvents = void 0;
|
|
29586
|
-
this.events = [];
|
|
29587
|
-
this.castedEvents = [];
|
|
29588
|
-
this.start(this.startOptions);
|
|
29589
|
-
this.isLive = true;
|
|
29590
|
-
await this.fastForward(this.liveEvents);
|
|
29591
|
-
if (sleepAfter) {
|
|
29592
|
-
await (0, import_await_sleep3.default)(sleepAfter);
|
|
29593
|
-
}
|
|
29594
|
-
}
|
|
29595
29635
|
getLastEventTimestamps() {
|
|
29596
29636
|
const lastEvent = this.events[this.events.length - 1];
|
|
29597
29637
|
return {
|
package/cli.js
CHANGED
|
@@ -127,7 +127,7 @@ show-report [options] [report] show HTML report
|
|
|
127
127
|
`);i.splice(5,0," --cksm-config=<config> Checksum configuration in JSON format").join(`
|
|
128
128
|
`),console.log(i.join(`
|
|
129
129
|
`))}catch(r){console.log("Error",r.message)}break;case"show-report":try{let i=(await this.getCmdOutput("npx playwright show-report --help")).replace(/npx playwright/g,"yarn checksum");console.log(i)}catch(r){console.log("Error",r.message)}break;case"generate":console.log("Not implemented yet");break}}};n(rg,"CLIHelp");var js=rg;var ig=class ig extends hr{constructor(t,r=!1){super(t,r)}async run(){let r=`npx playwright show-report ${this.getNonChecksumArgs().join(" ")}`;try{await this.execCmd(r)}catch(i){console.log("Error showing report",i.message)}}};n(ig,"CLIShowReport");var Fu=ig;var yt=require("fs"),_i=require("path");var ng=class ng extends hr{constructor(t,r=!1){super(t,r)}run(){console.log("Creating Checksum directory and necessary files to run your tests");try{this.findProjectRoot()}catch(s){console.log(s.message),process.exit(1)}let t=(0,_i.join)(process.cwd(),Fl);if((0,yt.existsSync)(t)||(0,yt.mkdirSync)(t),!(0,yt.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");let r=(0,yt.existsSync)((0,_i.join)(t,"checksum.config.ts"));zb({isInit:!r}).forEach(s=>{let l=(0,_i.join)(t,s);(0,yt.existsSync)(l)||(0,yt.copyFileSync)((0,_i.join)(this.getChecksumRootOrigin(),s),l)});let i=(0,_i.join)(t,".gitignore.example"),a=(0,_i.join)(t,".gitignore");(0,yt.existsSync)(i)&&!(0,yt.existsSync)(a)&&((0,yt.copyFileSync)(i,a),(0,yt.unlinkSync)(i)),this.validateAuthExists(),(0,yt.mkdirSync)((0,_i.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(s=>{(0,yt.mkdirSync)((0,_i.join)(t,"test-data",s),{recursive:!0})})}};n(ng,"CLIInstall");var Ru=ng;var ay=require("crypto");var Us=At(require("path")),Zr=At(require("fs"));function ag(e,t){let r=e.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);if(!r||r.length!==3)throw new Error("Invalid base64 string");let i=r[1],a=r[2],s=Buffer.from(a,"base64");return{name:t,type:i,buffer:s,size:s.length}}n(ag,"base64ToFile");function og(e,t,r=null){let i=ag(e,t),a=r??Us.default.join(__dirname,"..","uploads");Zr.default.existsSync(a)||Zr.default.mkdirSync(a,{recursive:!0});let s=Us.default.join(a,t);return Zr.default.writeFileSync(s,i.buffer),console.log(`File written successfully: ${s}`),s}n(og,"writeBase64ToFile");function k_(e,t){if(!Zr.default.existsSync(e)){console.error("The folder does not exist.");return}let r=t;function i(a,s){Zr.default.lstatSync(a).isDirectory()?(Zr.default.existsSync(s)||Zr.default.mkdirSync(s),Zr.default.readdirSync(a).forEach(l=>{let u=Us.default.join(a,l),d=Us.default.join(s,l);i(u,d)})):Zr.default.copyFileSync(a,s)}n(i,"copyRecursiveSync"),i(e,r),console.log(`Backup created: ${r}`)}n(k_,"copyFolderWithBackupSuffix");function __(e){return/^(?!\.{1,2}$)(?!.*[\\/:*?"<>|])[\S ]{1,255}$/.test(e)}n(__,"isValidFolderName");var sg=require("crypto");var cg=class cg{constructor(t,r,i,a,s,l,u,d){this.config=t;this.checksumRoot=r;this.pageInteractor=i;this.apiService=a;this.userStoryService=s;this.actionsManager=l;this.testAssetsManager=u;this.webDriver=d;this.executeAction=n(async(t,r={valueChanged:!1,playMode:!1})=>{try{return t.selector=void 0,t.executed=!1,r.playMode||(t.timestamp=Date.now()),t.eventCode==="login"?await this.performLogin(t.login):await this.pageInteractor.performAction(t,{useLocator:!0,timeout:r.timeout,monitorFlashingHTML:!1}),r.playMode||this.actionsManager.onActionExecuted(t,{parentAction:r.parentAction}),t}catch(i){throw console.error(i),new Error(i)}},"executeAction")}async uploadFiles(t){let r=t.map(({data:i,fileName:a},s)=>ag(i,a));await Promise.all(r.map(async i=>{let a=await this.getUploadFileSignedUrl({fileName:i.name,contentType:i.type});await this.apiService.putFile(a,i)})),t.forEach(({data:i,fileName:a},s)=>{og(i,a);let l=`${this.testAssetsManager.getLocalAutoSavePath()}/files`;og(i,a,l)})}async getUploadFileSignedUrl(t){if(!this.userStoryService.hasTestGenerationData()){console.log("No generationBatchId, can't upload");return}let r=await this.apiService.post("test-generation/get-upload-file-signed-url",{...t,batchId:this.userStoryService.getTestGenerationData().generationBatchId}),{url:i}=await r.json();return i}async login(t,{role:r,environment:i}){await Ym({config:this.config,folder:this.checksumRoot,throwIfEnvInfoInvalid:!0})(t,{role:r,environment:i}),this.didLogin=!0}async performLogin({role:t,environment:r}){await Cu(this.webDriver.page,this.webDriver.liveMainFrame,async i=>{await this.login(i,{role:t,environment:r})})}async getLastTimestamps(){return await this.webDriver.tmFrame.evaluate(()=>window.checksum.timeMachine.getLastEventTimestamps())}async addInitialLoginAction(){let t=await this.getLastTimestamps();this.actionsManager.addAction({description:"Log into application",eventCode:"login",id:(0,sg.randomUUID)(),login:{role:this.userStoryService.getStory().environment.userRole,environment:this.userStoryService.getStory().environment.name},timestamp:t.timestamp})}async addStartURLNavigationAction(){var i;let t=await this.getLastTimestamps(),r=(i=this.userStoryService.getStory())==null?void 0:i.url;r&&this.actionsManager.addAction({description:"Navigate to start URL",eventCode:"navigation",id:(0,sg.randomUUID)(),fillValue:r,timestamp:t.timestamp})}hasLoggedIn(){return this.didLogin}};n(cg,"VtgActionsService");var Mu=cg;var lg=class lg{constructor(t,r={},i=!0){this.requests=[];this.watcherConfig={minimumWaitTime:250,maximumWaitTime:1e4,followingRequestsWaitTime:250};this.resolved=!0;this.hasMinimumWaitTimePassed=!1;this.useLog=!1;this.logStack=[];this.resolve=n(()=>{this.resolved||(this.resolved=!0,clearTimeout(this.minimumWaitTimer),clearTimeout(this.maximumWaitTimer),clearTimeout(this.followingRequestWaitTimeoutId),this.loadResolve({totalTime:Date.now()-this.startTS,logs:this.logStack,pendingRequests:this.requests.length,totalRequests:this.observedRequestsCount}))},"resolve");this.watcherConfig={...this.watcherConfig,...r},this.initListeners(t),this.useLog=i}initListeners(t){t.on("request",r=>{var i;this.hasMinimumWaitTimePassed||(i=this.watcherConfig.whitelist)!=null&&i.length&&!this.watcherConfig.whitelist.some(a=>a.test(r.url()))||(this.useLog&&this.logStack.push(`${r.method()} ${r.url().substring(0,60)}`),this.requests.push(r),this.observedRequestsCount+=1)}),t.on("response",r=>{this.requests=this.requests.filter(i=>i!==r.request()),this.hasMinimumWaitTimePassed&&(this.requests.length||(clearTimeout(this.followingRequestWaitTimeoutId),this.followingRequestWaitTimeoutId=setTimeout(()=>{this.requests.length||this.resolve()},this.watcherConfig.followingRequestsWaitTime)))})}async wait(){return new Promise(t=>{this.loadResolve=t,this.resolved=!1,this.minimumWaitTimer=setTimeout(()=>{this.hasMinimumWaitTimePassed=!0,this.requests.length||this.resolve()},this.watcherConfig.minimumWaitTime),this.maximumWaitTimer=setTimeout(this.resolve,this.watcherConfig.maximumWaitTime)})}startListening(){this.requests=[],this.startTS=Date.now(),this.hasMinimumWaitTimePassed=!1,this.observedRequestsCount=0,this.useLog&&(this.logStack=[])}};n(lg,"NetworkWatcher");var Ou=lg;var A_=require("crypto");var vq=n(e=>({...e.fillValue&&{value:e.fillValue},...e.selector&&{selector:e.selector},type:s_[e.eventCode],id:e.id,files:[]}),"webPageActionToNextAction"),ug=class ug{constructor(t,r,i){this.actionsManager=t;this.apiService=r;this.userStoryService=i}clear(){this.remoteSessionId=void 0}async init({retriesLeft:t=3,keepActionsWithoutDescription:r=!1,lastActionId:i=void 0}={}){let{goal:a,instructions:s}=this.userStoryService.getStory(),l=this.actionsManager.actions??[];if(i){let f=l.findIndex(({id:h})=>h===i);f===-1&&console.log(`[init] No action with id ${i} was found in executed actions`),l=l.slice(0,f+1)}r||(l=l.filter(f=>!!f.description));let u={previous:l.map(f=>({thought:f.description,action:vq(f)}))},d={type:"test-generation",storyTitle:a,storyInstructions:s,testId:void 0,testSuiteId:void 0,thoughtsAndActions:u};try{let f=await this.apiService.post("ai-fallback/init",{data:d});this.remoteSessionId=await f.text()}catch(f){if(console.error(f),await Ce(2e3),t>0)return this.init({retriesLeft:t-1,keepActionsWithoutDescription:r});throw f}}};n(ug,"VtgAiSessionBaseService");var Ua=ug;var pg=class pg extends Ua{constructor(r,i,a,s,l,u){super(s,l,u);this.webDriver=r;this.pageInteractor=i;this.actionsService=a;this.actionsManager=s;this.apiService=l;this.userStoryService=u;this.previousActionFailed=!1;this.currentChecksumId="0";this.executeAction=n(async(r,i={valueChanged:!1,playMode:!1})=>{await this.webDriver.clearHighlights(),this.previousActionFailed=!1;let a;try{let s=new Ou(this.webDriver.liveMainFrame.page());s.startListening(),a=await this.actionsService.executeAction(r),await s.wait(),await Ce(2e3)}catch(s){throw this.previousActionFailed=!0,console.error(s),new Error(s)}return i.valueChanged&&await this.init(),a},"executeAction")}async init({keepActionsWithoutDescription:r}={keepActionsWithoutDescription:!0}){return this.clear(),super.init({keepActionsWithoutDescription:r})}clear(){super.clear(),this.previousActionFailed=!1,this.currentChecksumId="0"}async iterate({guidance:r}={}){await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1);let{reducedHTML:i,flashingHTML:a,elementsForNodeInterpretation:s,currentChecksumId:l}=await this.webDriver.evaluateWithChecksum(async({appRules:d,currentChecksumId:f})=>window.checksum.testGenerator.reduceHTML(d,{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:f}),{appRules:{appSpecificInteractableElementsSelectors:[]},currentChecksumId:this.currentChecksumId});this.currentChecksumId=l;let u=await this.getNextAction({reducedHTML:i,flashingHTML:a,elementsForNodeInterpretation:s,guidance:r});try{let f={...await this.pageInteractor.translateActionResponseToAgentPotentialAction(u),id:(0,A_.randomUUID)(),timestamp:Date.now()};return await this.webDriver.highlightElementByLocator(this.pageInteractor.makeLocator(f.selector,f.parentFramesSelectors),f.clickOffset,"10px solid rgba(255,0,0,1)"),f}catch(d){console.error("error in ai iterate",d)}}async stop(){}async getNextAction({reducedHTML:r,flashingHTML:i,elementsForNodeInterpretation:a,guidance:s}){let l={reduction:{reducedHTML:r,flashingHTML:i,elementsForNodeInterpretation:a},currentURL:this.webDriver.liveMainFrame.url(),previousActionOverview:{success:!this.previousActionFailed,userCorrection:s}};try{return await(await this.apiService.post("ai-fallback/iterate",{sessionId:this.remoteSessionId,iterationData:l})).json()}catch(u){throw console.error(u),u}}};n(pg,"VtgAITestGenerationService");var Lu=pg;var fg=class fg{constructor(t){this.config=t;this.baseURL=t.apiURL+"/client-api/runtime"}getBaseURL(){return this.baseURL}post(t,r){return fetch(`${this.baseURL}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}putFile(t,r){return fetch(t,{method:"PUT",headers:{"Content-Type":r.type},body:r})}};n(fg,"VtgCloudAPIService");var Du=fg;var xq="withChecksumAI()",Bu=n(e=>e.matcher.startsWith("toHaveURL")||e.matcher.startsWith("not.toHaveURL")||e.matcher.startsWith(xq),"isPageLevelAssertion"),ore=["navigation","get_more_items","wait","switch_tab"],C_=n(e=>{let{assertions:t,smartAssertion:r}=e;return[...t??[],...r?[r]:[]].filter(i=>i.isSelected)},"getSelectedAssertions"),dg=n(e=>e.matcher==="toBeHidden()","isAssertionOnElementFromPreviousState"),hg=n(e=>!e.locator||e.locator==="page"?"page":`page.${e.locator.replace(/^page/,"")}`,"getLocator"),qu=n(e=>{let t=n(a=>a?a.replaceAll(/\\/g,"\\\\").replaceAll(/"/g,'\\"').replaceAll(`
|
|
130
|
-
`,"\\n"):"","escapeString"),r=e.thought?`, "${t(e.thought)}"`:"";return`${`await expect(${hg(e)}${r})`}.${e.matcher}`},"generateAssertionCode"),mg=n(e=>e.includes("page.frameLocator('iframe')")||e.includes('page.frameLocator("iframe")')?e:e.replace("page.","page.frameLocator('iframe')."),"addTimeMachineFrameLocator");var za=class za{constructor(t=void 0){this.appRules=t}generateAssertionCode(t){return qu(t)}static getOppositeMatcherClause(t){if(t.startsWith("not."))return t.replace(/^not\./,"");let r=[...za.OPPOSITE_MATCHERS.keys()].find(a=>t.startsWith(a));if(!r)return`not.${t}`;let i=za.OPPOSITE_MATCHERS.get(r);return t.replace(r,i)}};n(za,"AssertionCodeGenerator"),za.OPPOSITE_MATCHERS=new Map([["toBeDisabled","toBeEnabled"],["toBeEnabled","toBeDisabled"],["toBeVisible","toBeHidden"],["toBeHidden","toBeVisible"]]);var Nu=za;var Ji=require("@playwright/test"),Rg=At(K_());var Fg=class Fg{constructor(t){this.options=t;this.harData={methodIndex:{GET:0,POST:0,PUT:0,DELETE:0}};this.interceptors={recordHar:this.harInterceptor.bind(this),completeOriginHeader:this.completeOriginHeaderInterceptor.bind(this)};this.intercept=n(async(t,r,i)=>{let a=[],s=n(l=>{if(l)switch(l.type){case"abort":return t.abort(l.errorCode);case"fulfill":return t.fulfill(l.fulfillOptions);default:case"continue":a.push(l)}},"processResult");for(let[l,u]of Object.entries(this.interceptors))if(this.options[l]){let d=s(await u(t,r,i));if(d)return d}return this.applyContinueResults(t,a)},"intercept")}setOptions(t){this.options=t}mergeOptions(t){this.options={...this.options,...t}}applyContinueResults(t,r){let i=r.filter(s=>!!s),a={};return i.forEach(s=>{s.options&&(s.options.headers&&(a.headers={...a.headers,...s.options.headers}),s.options.method&&(a.method=s.options.method),s.options.postData&&(a.postData=s.options.postData),s.options.url&&(a.url=s.options.url))}),t.continue(a)}async harInterceptor(t){let r=t.request().headers(),i=t.request().method();return r["Checksum-Id"]=(++this.harData.methodIndex[i]).toString(),{options:{headers:r}}}async completeOriginHeaderInterceptor(t,r,{page:i}){let a=t.request().headers();if(!a.Origin){try{let s=new URL(i.url()).origin;a.Origin=s}catch{}return{options:{headers:a}}}}};n(Fg,"RouteInterceptors");var Hu=Fg;var Mg=class Mg{constructor(t={},r={}){this.browserConfig={devtools:!1,executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH??void 0};this.options={fullScreenResolution:!1,defaultTimeout:3e4,defaultNavigationTimeout:3e4,disableWebSecurity:!0};this.contextClosePromise=void 0;this.eventListeners=[];this.lastSnapshot={selector:void 0,eventCode:void 0};this.snapshotTimeout=3e4;this.cacheScript=!1;this.pagesIndexToGuid={};this.framesMessageBroker=new qs;this.onRequestFinished=n(async t=>{try{let r=await t.response();if(!r.ok())return;let i=t.resourceType(),a=t.url(),s=n(async()=>{try{return await r.text()}catch{try{return await(await fetch(a)).text()}catch{return}}},"getBody");if(["document","script","stylesheet"].includes(i))try{let l=await s();if(!l)return;let u={url:a,source:l,type:i};await this.forEachEventListener(d=>{var f;return(f=d.onWebDriverResourceLoaded)==null?void 0:f.call(d,u)})}catch(l){console.error("[WebDriver] requestfinished event handler error",i,a,l)}}catch(r){console.error("[WebDriver] requestfinished event handler error",r)}},"onRequestFinished");this.onFrameNavigated=n(async t=>{let r=n(async i=>{await this.forEachEventListener(a=>{var s;return(s=a.onWebDriverFrameNavigated)==null?void 0:s.call(a,t,i)})},"notifyFrameNavigated");await r(!1),await this.injectedScriptManager.onFrameNavigated(t),await r(!0)},"onFrameNavigated");this.tracing=!1;this.tracingChunk=!1;this.chunkIndex=0;var i;if(this.options={...this.options,...t},this.browserConfig={...this.browserConfig,...r},this.injectedScriptManager=new Bs(this.options),this.browserConfig.args||(this.browserConfig.args=[]),this.options.disableWebSecurity&&this.browserConfig.args.push("--disable-web-security"),this.options.allowFileAccess&&this.browserConfig.args.push("--allow-file-access-from-files"),this.browserConfig.args.push("--disable-site-isolation-trials"),this.browserConfig.args.push("--allow-running-insecure-content"),this.options.forceHeadless&&(this.browserConfig.headless=!0,this.browserConfig.devtools=!1),this.options.useProxy)if((i=this.options.webProxy)!=null&&i.server){console.log("[WebDriver] using proxy");let{server:a,username:s,password:l}=this.options.webProxy;this.browserConfig.proxy={server:a,username:s,password:l},this.browserConfig.args.push("--proxy-bypass-list=localhost,127.0.0.1")}else console.error("[WebDriver] useProxy=true but proxy not configured");this.routeInterceptor=new Hu({completeOriginHeader:this.options.completeOriginHeader,recordHar:this.options.recordHAR})}async prepare({storageState:t,baseURL:r}={}){if(await this.shutdown(),this.options.useStealth){let a=require("puppeteer-extra-plugin-stealth");Rg.chromium.use(a()),this.browser=await Rg.chromium.launch(this.browserConfig)}else this.browser=await Ji.chromium.launch(this.browserConfig);let i={};return i.bypassCSP=!0,i.ignoreHTTPSErrors=!0,i.baseURL=r??this.options.baseURL,this.options.timezoneId&&(i.timezoneId=this.options.timezoneId),this.options.fullScreenResolution?i.viewport={width:1280,height:720}:this.options.hostWindowViewport&&(i.viewport=null),t&&(i.storageState=t),this.context=await this.browser.newContext(i),this.options.defaultTimeout&&this.context.setDefaultTimeout(this.options.defaultTimeout),this.options.defaultNavigationTimeout&&this.context.setDefaultNavigationTimeout(this.options.defaultNavigationTimeout),this.context.on("page",async a=>{await this.onNewPage(a),await this.onFrameNavigated(a.mainFrame()),a.on("framenavigated",this.onFrameNavigated)}),this.context.on("close",async()=>{this.contextClosePromise=this.forEachEventListener(a=>{var s;return(s=a.onWebDriverContextClose)==null?void 0:s.call(a)})}),this.activePage=await this.context.newPage(),this.originalPage=this.activePage,this.options.trackLoadedResources&&this.page.on("requestfinished",this.onRequestFinished),this.options.useCDPSession&&(this.cdpSession=await this.context.newCDPSession(this.page)),!0}get frameMsgBroker(){return this.framesMessageBroker}async onNewPage(t){try{await(t==null?void 0:t.route("**/*",async(r,i)=>this.routeInterceptor.intercept(r,i,{page:t})))}catch(r){console.error("[WebDriver] onPage error",r)}}switchActivePage(t){let r=this.context.pages().find(i=>pt(i)===t);return!r||r.isClosed()?(console.error(`[WebDriver] Page with guid ${t} not found or has been closed.`),!1):(this.previousPage=this.activePage,this.activePage=r,!0)}getDefaultTimeout(){return this.options.defaultTimeout}getDefaultNavigationTimeout(){return this.options.defaultNavigationTimeout}async addHARMockAPIRecordings(t){if(!this.activePage){console.warn("[addHARMockAPIRecordings] Active page is not set, skipping HAR recording.");return}await this.activePage.routeFromHAR(t,{url:/^(?!.*\.(js|mjs|ts|jsx|tsx|css|jpg|jpeg|png|gif|svg|webp|heif|heic|raw|cr2|nef|arw|bmp|tiff|tif|ico|woff|woff2|ttf|otf|doc|docx|pdf|ws|wasm|mp3|wav|aac|flac|mp4|avi|mov|wmv|flv|zip|rar|7z|tar\.gz|xml|html|py|java|cpp|xls|xlsx|ppt|pptx|gif)$)/i,update:!0,updateMode:"minimal"})}forEachEventListener(t){return Promise.all(this.eventListeners.map(async r=>{try{await t(r)}catch(i){console.log("WebDriver/forEachEventListener exception",i)}}))}registerEventListener(t){this.eventListeners.push(t)}async getScript(){async function t(r){let{exec:i}=require("child_process");return new Promise((a,s)=>{i(r,l=>{l?(console.log("error executing cmd, ",l),s(l)):a()})})}switch(n(t,"execCmd"),this.options.scriptSource){case"file":return this.options.scriptFile;case"url":if(this.cacheScript)return this.options.scriptFile;try{return await t(`curl -o ${this.options.scriptFile} '${this.options.scriptURL}'`),this.options.scriptFile}catch(r){console.log("[web-driver] Failed fetching frontend script",r)}break}}async startJSCoverageTracking(){return await this.page.coverage.startJSCoverage(),[];return await this.cdpSession.send("Debugger.enable"),await this.cdpSession.send("Profiler.enable"),await this.cdpSession.send("Profiler.startPreciseCoverage",{callCount:!1,detailed:!0}),this.getCurrentJSCoverage()}stopJSCoverageTracking(){return this.page.coverage.stopJSCoverage()}async getCurrentJSCoverage(){let t=await this.page.coverage.stopJSCoverage();return await this.page.coverage.startJSCoverage(),t;return(await this.cdpSession.send("Profiler.takePreciseCoverage")).result}async startCSSCoverageTracking(){return await this.cdpSession.send("DOM.enable"),await this.cdpSession.send("CSS.enable"),await this.cdpSession.send("CSS.startRuleUsageTracking"),this.getCurrentCSSCoverage()}async getCurrentCSSCoverage(){return(await this.cdpSession.send("CSS.takeCoverageDelta")).coverage}getCDPSession(){return this.cdpSession}async navigate(t){return this.page.goto(t)}async setViewportSize(t,r){return this.page.setViewportSize({width:t,height:r})}async getStorageState(){return this.page.context().storageState()}async shutdown(){try{this.page&&(await this.page.close(),this.activePage=void 0),this.context&&(await this.context.close(),this.context=void 0),this.browser&&(await this.browser.close(),this.browser=void 0)}catch(t){console.warn("[WebDriver] shutdown error",t)}}async wrapWithBrowserLogs(t,{disabled:r=!1,onErrorOnly:i=!1}={}){if(r)return t();let a=[],s=n(d=>{a.push(d.text())},"log");this.page.on("console",s);let l,u;try{u=await t()}catch(d){l=d}if(this.page.off("console",s),(!i||l)&&console.log("browser console messages:",a),l)throw l;return u}async takeElementSnapshot(t,r,i={},a={}){if(t===this.lastSnapshot.selector&&r===this.lastSnapshot.eventCode)return{};if(!t)return{};try{let{snapshot:s,elementLocator:l}=await this.takeSnapshot(t,a,{frameLocatorSelector:i.frameLocatorSelector});return this.lastSnapshot={selector:t,eventCode:r},{snapshot:s,elementLocator:l}}catch(s){return console.error("takeElementSnapshot error",s),{}}}getScreenshotTimeout(t=!1){return t?this.snapshotTimeout:this.snapshotTimeout+5e3}async takePageSnapshot(t){let r=this.page.screenshot({...t,timeout:this.getScreenshotTimeout()});return await Promise.race([r,Ce(this.getScreenshotTimeout(!0))])}async takeSnapshot(t,r,{frameLocatorSelector:i}={}){let a=i?this.page.frameLocator(i).locator(t):this.page.locator(t),s=a.screenshot({...r,timeout:this.getScreenshotTimeout()});return{snapshot:await Promise.race([s,Ce(this.getScreenshotTimeout(!0))]),elementLocator:a}}async getCurrentURL(){return this.page.url()}async getClientScreenResolution(){return await this.page.evaluate(async()=>({width:window.screen.width,height:window.screen.height}))}async awaitContextClose(){return this.contextClosePromise||await Ce(100),this.contextClosePromise}get page(){return this.activePage}getPage(){return this.activePage}startPlaywrightTrace(){return this.tracing=!0,this.context.tracing.start({name:"trace",screenshots:!0,snapshots:!0})}startPlaywrightTraceChunk(){return this.tracingChunk=!0,this.context.tracing.startChunk({name:`trace-chunk-${this.chunkIndex}`})}stopPlaywrightTraceChunk(t){return this.tracingChunk=!1,this.context.tracing.stopChunk({path:`${t.replace(".zip",`.${this.chunkIndex++}.zip`)}`})}stopPlaywrightTrace(t){return this.tracing=!1,this.context.tracing.stop({path:t})}isTracing(){return this.tracing}isTracingChunk(){return this.tracingChunk}};n(Mg,"WebDriver");var $u=Mg;var Gs=require("jsdom");var Og=class Og{constructor(t){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new Gs.JSDOM(t),this.process()}process(){this.expandedChecksumIdsReducedDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize());let t=n(l=>{l.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(d=>{d.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),r=n((l,u)=>u.window.document.body.querySelectorAll(`[${l}]`).forEach(d=>d.removeAttribute(l)),"removeAttributeFromAllElements"),i=n(l=>r("checksuminteractable",l),"removeChecksumInteractableAttribute"),a=n(l=>r("checksumid",l),"removeChecksumIdAttribute"),s=n(l=>r("rrwebid",l),"removeRrwebIdAttribute");t(this.reducedHTMLDom),i(this.expandedChecksumIdsReducedDom),i(this.reducedHTMLDom),i(this.rrwebIdsReducedDom),s(this.expandedChecksumIdsReducedDom),s(this.reducedHTMLDom),a(this.rrwebIdsReducedDom)}getDOMForType(t){switch(t){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(t){return await t(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(t){this.activeDOMType=t}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(t){return this.getDOMForType(t).serialize()}get raw(){return this.rawReducedHTMLDom}};n(Og,"ReducedHTMLDOM");var Gu=Og;var Lg=class Lg{constructor(t,r,i,a,s={logPerformance:!1}){this.timeMachine=t;this.actionsManager=r;this.apiService=i;this.remoteSessionId=a;this.options=s;this.currentChecksumId="0"}rewriteLastActionThought(t){throw new Error("Method not implemented.")}async generatePromptData(t,r,i){if(this.promptData)return{...this.promptData,assertionsData:r};let a=this.getActionTimestamps(t,i);if(!a)return;let s=await this.getReducedHTMLForTimestamp(a.before),l=await this.getReducedHTMLForTimestamp(a.after);return this.promptData={reduction:{reducedHTML:l,flashingHTML:[]},currentURL:"",previousReducedHTML:s,previousURL:"",actionId:t,assertionsData:r},this.promptData}async callApi(t,r,i,a){let s=Date.now(),l=await this.generatePromptData(r,i,a);if(this.logPerformance(`- Generated prompt data for ${t}`,s),!l)return;s=Date.now();let u=await this.apiService.post(`assertions/${t}`,{sessionId:this.remoteSessionId,data:l});if(!u.ok){console.error(`Request for assertion generation ${t} failed with status ${u.status}`);return}let d=await u.json();return this.logPerformance(`- Received response for assertion generation ${t}`,s),d}async generateAssertions(t,r){try{let i=await this.callApi("generate",t,void 0,r);if(i)return i.timestamps=this.getActionTimestamps(t,r),i}catch(i){throw console.error(i),i}}async refactoringAssertions(t){try{return await this.callApi("refactor",t.actionId,t)}catch(r){throw console.error(r),r}}async filteringAssertions(t){try{return await this.callApi("filter",t.actionId,t)}catch(r){throw console.error(r),r}}async getReducedHTMLWithRetries(t,{retriesLeft:r=3,retryWaitMS:i=1e3}={}){try{let{reducedHTML:a,currentChecksumId:s}=await t.evaluate(async l=>{var u,d;return(d=(u=window==null?void 0:window.checksum)==null?void 0:u.testGenerator)==null?void 0:d.reduceHTML({},l)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0});return this.currentChecksumId=s,{reducedHTML:a}}catch(a){if(r>0)return await Ce(i),this.getReducedHTMLWithRetries(t,{retriesLeft:r-1,retryWaitMS:i});throw a}}async getReducedHTMLForTimestamp(t){return this.timeMachine.executeTask(async r=>{let i="",a=await this.getReducedHTMLWithRetries(r);return i=a==null?void 0:a.reducedHTML,new Gu(i).getRrwebIdsReducedDomString()},t,{name:"getReducedHTMLForTimestamp"})}getVariables(){return[]}getVariablesString(t){return""}getActionTimestamps(t,r){let i=this.actionsManager.actions,a=i.findIndex(u=>u.id===t);if(a===-1){console.log(`[init] No action with id ${t} was found in executed actions`);return}let s=i[a],l=i[a+1];return{before:s.timestamp,after:(l==null?void 0:l.timestamp)??r}}logPerformance(t,r){this.options.logPerformance&&console.log(`${t} in`,Date.now()-r,"ms")}};n(Lg,"AssertionsAgent");var Vu=Lg;var nie=Ji.expect.configure({timeout:500}),_VtgAiAssertionsService=class _VtgAiAssertionsService extends Ua{constructor(t,r,i,a,s,l={logPerformance:!1}){super(t,r,i);this.actionsManager=t;this.apiService=r;this.userStoryService=i;this.timeMachine=a;this.webDriver=s;this.options=l;this.activeRemoteSessionIdByActionId=new Map}async init({retriesLeft:t=3,keepActionsWithoutDescription:r=!1,lastActionId:i=void 0}={}){await super.init({retriesLeft:t,keepActionsWithoutDescription:r,lastActionId:i}),this.activeRemoteSessionIdByActionId.set(i,this.remoteSessionId)}async generateAiAssertions({action:t,aiAssertionsGenerationStartedAt:r}){this.options.logPerformance&&console.log(`generateAiAssertions for action ${t.id}`);let i=n(async(a=[],s=!1)=>{let l=a.map((u,d)=>({...u,id:(Date.now()+d).toString()}));return await this.webDriver.page.evaluate(({assertions:u,actionId:d,error:f})=>{window.vtg.onAIAssertionsGenerated(d,u,f)},{assertions:l,actionId:t.id,error:s}),l.forEach(u=>{this.actionsManager.addOrUpdateAssertionByActionId(t.id,u)}),l},"sendResultToVTG");if(this.isRunning(t.id))return console.log("Already generating assertions for this action"),i();try{let a=Date.now();if(await this.init({keepActionsWithoutDescription:!0,lastActionId:t.id}),this.logPerformance(`init for action ${t.id}`,a),!this.isRunning(t.id))return i();let s=new Vu(this.timeMachine,this.actionsManager,this.apiService,this.remoteSessionId),l=await this.generateAssertions(s,t.id,r);if(!l||!this.isRunning(t.id))return i();if(l.assertions.length===0){let{smartAssertion:u}=l;return u?(u.isSelected=!0,i([u])):i()}return xt.vtg.aiAssertions.allowRefactoring&&(l=await this.refactoringAssertions(s,l)),!this.isRunning(t.id)||(l=await this.filteringAssertions(s,l),!this.isRunning(t.id))?i():(this.logPerformance(`---------------- Overall - Generated assertions for action ${t.id} in`,a),i(C_(l)))}catch(a){return console.error("Error in AI assertions generation",a),i([],!0)}finally{this.activeRemoteSessionIdByActionId.delete(t.id)}}stopGenerateAiAssertions({action:t}){this.activeRemoteSessionIdByActionId.delete(t.id)}isRunning(t){return this.activeRemoteSessionIdByActionId.has(t)}async generateAssertions(t,r,i=void 0){let a=Date.now(),s=a,l=await t.generateAssertions(r,i);if(this.logPerformance(`- generateAssertions for action ${r}`,a),!!l)return a=Date.now(),await this.setSelectionDataForAssertions(l),this.logPerformance(`- setSelectionData for action ${r}`,a),a=Date.now(),await this.validateAssertions(l.assertions,l.timestamps,t),this.logPerformance(`- validate assertions for action ${r}`,a),this.logPerformance(`Overall - Generated assertions for action ${r}`,s),l}async refactoringAssertions(t,r){let i=Date.now(),a=i;try{this.options.logPerformance&&console.log(`Refactoring assertions for action ${r.actionId}`),r=await t.refactoringAssertions(r),this.logPerformance(`- refactoringAssertions for action ${r.actionId}`,i),i=Date.now(),await this.validateAssertions(r.assertions,r.timestamps,t),this.logPerformance(`- validate assertions after refactoring for action ${r.actionId}`,i),this.logPerformance(`Overall - Refactored assertions for action ${r.actionId}`,a)}catch(s){console.error("[refactoringAssertions] Error in assertions refactoring",s)}return r}async filteringAssertions(t,r){try{let i=Date.now();this.options.logPerformance&&console.log(`Filtering assertions for action ${r.actionId}`);let a=await t.filteringAssertions(r);return this.logPerformance(`Overall - filteringAssertions for action ${r.actionId}`,i),a}catch(i){console.error("[filteringAssertions] Error in assertions filtering",i)}}async executeAssertion(assertion,timeMachine,agent){let variablesString=agent.getVariablesString(!0),page=timeMachine,executeMatcherCode=`
|
|
130
|
+
`,"\\n"):"","escapeString"),r=e.thought?`, "${t(e.thought)}"`:"";return`${`await expect(${hg(e)}${r})`}.${e.matcher}`},"generateAssertionCode"),mg=n(e=>e.includes("page.frameLocator('iframe')")||e.includes('page.frameLocator("iframe")')?e:e.replace("page.","page.frameLocator('iframe')."),"addTimeMachineFrameLocator");var za=class za{constructor(t=void 0){this.appRules=t}generateAssertionCode(t){return qu(t)}static getOppositeMatcherClause(t){if(t.startsWith("not."))return t.replace(/^not\./,"");let r=[...za.OPPOSITE_MATCHERS.keys()].find(a=>t.startsWith(a));if(!r)return`not.${t}`;let i=za.OPPOSITE_MATCHERS.get(r);return t.replace(r,i)}};n(za,"AssertionCodeGenerator"),za.OPPOSITE_MATCHERS=new Map([["toBeDisabled","toBeEnabled"],["toBeEnabled","toBeDisabled"],["toBeVisible","toBeHidden"],["toBeHidden","toBeVisible"]]);var Nu=za;var Ji=require("@playwright/test"),Rg=At(K_());var Fg=class Fg{constructor(t){this.options=t;this.harData={methodIndex:{GET:0,POST:0,PUT:0,DELETE:0}};this.interceptors={recordHar:this.harInterceptor.bind(this),completeOriginHeader:this.completeOriginHeaderInterceptor.bind(this)};this.intercept=n(async(t,r,i)=>{let a=[],s=n(l=>{if(l)switch(l.type){case"abort":return t.abort(l.errorCode);case"fulfill":return t.fulfill(l.fulfillOptions);default:case"continue":a.push(l)}},"processResult");for(let[l,u]of Object.entries(this.interceptors))if(this.options[l]){let d=s(await u(t,r,i));if(d)return d}return this.applyContinueResults(t,a)},"intercept")}setOptions(t){this.options=t}mergeOptions(t){this.options={...this.options,...t}}applyContinueResults(t,r){let i=r.filter(s=>!!s),a={};return i.forEach(s=>{s.options&&(s.options.headers&&(a.headers={...a.headers,...s.options.headers}),s.options.method&&(a.method=s.options.method),s.options.postData&&(a.postData=s.options.postData),s.options.url&&(a.url=s.options.url))}),t.continue(a)}async harInterceptor(t){let r=t.request().headers(),i=t.request().method();return r["Checksum-Id"]=(++this.harData.methodIndex[i]).toString(),{options:{headers:r}}}async completeOriginHeaderInterceptor(t,r,{page:i}){let a=t.request().headers();if(!a.Origin){try{let s=new URL(i.url()).origin;a.Origin=s}catch{}return{options:{headers:a}}}}};n(Fg,"RouteInterceptors");var Hu=Fg;var Mg=class Mg{constructor(t={},r={}){this.browserConfig={devtools:!1,executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH??void 0};this.options={fullScreenResolution:!1,defaultTimeout:3e4,defaultNavigationTimeout:3e4,disableWebSecurity:!0};this.contextClosePromise=void 0;this.eventListeners=[];this.lastSnapshot={selector:void 0,eventCode:void 0};this.snapshotTimeout=3e4;this.cacheScript=!1;this.pagesIndexToGuid={};this.framesMessageBroker=new qs;this.onRequestFinished=n(async t=>{try{let r=await t.response();if(!r.ok())return;let i=t.resourceType(),a=t.url(),s=n(async()=>{try{return await r.text()}catch{try{return await(await fetch(a)).text()}catch{return}}},"getBody");if(["document","script","stylesheet"].includes(i))try{let l=await s();if(!l)return;let u={url:a,source:l,type:i};await this.forEachEventListener(d=>{var f;return(f=d.onWebDriverResourceLoaded)==null?void 0:f.call(d,u)})}catch(l){console.error("[WebDriver] requestfinished event handler error",i,a,l)}}catch(r){console.error("[WebDriver] requestfinished event handler error",r)}},"onRequestFinished");this.onFrameNavigated=n(async t=>{let r=n(async i=>{await this.forEachEventListener(a=>{var s;return(s=a.onWebDriverFrameNavigated)==null?void 0:s.call(a,t,i)})},"notifyFrameNavigated");await r(!1),await this.injectedScriptManager.onFrameNavigated(t),await r(!0)},"onFrameNavigated");this.tracing=!1;this.tracingChunk=!1;this.chunkIndex=0;var i;if(this.options={...this.options,...t},this.browserConfig={...this.browserConfig,...r},this.injectedScriptManager=new Bs(this.options),this.browserConfig.args||(this.browserConfig.args=[]),this.options.disableWebSecurity&&this.browserConfig.args.push("--disable-web-security"),this.options.allowFileAccess&&this.browserConfig.args.push("--allow-file-access-from-files"),this.browserConfig.args.push("--disable-site-isolation-trials"),this.browserConfig.args.push("--allow-running-insecure-content"),this.options.forceHeadless&&(this.browserConfig.headless=!0,this.browserConfig.devtools=!1),this.options.useProxy)if((i=this.options.webProxy)!=null&&i.server){console.log("[WebDriver] using proxy");let{server:a,username:s,password:l}=this.options.webProxy;this.browserConfig.proxy={server:a,username:s,password:l},this.browserConfig.args.push("--proxy-bypass-list=localhost,127.0.0.1")}else console.error("[WebDriver] useProxy=true but proxy not configured");this.routeInterceptor=new Hu({completeOriginHeader:this.options.completeOriginHeader,recordHar:this.options.recordHAR})}async prepare({storageState:t,baseURL:r}={}){if(await this.shutdown(),this.options.useStealth){let a=require("puppeteer-extra-plugin-stealth");Rg.chromium.use(a()),this.browser=await Rg.chromium.launch(this.browserConfig)}else this.browser=await Ji.chromium.launch(this.browserConfig);let i={};return i.bypassCSP=!0,i.ignoreHTTPSErrors=!0,i.baseURL=r??this.options.baseURL,this.options.timezoneId&&(i.timezoneId=this.options.timezoneId),this.options.fullScreenResolution?i.viewport={width:1280,height:720}:this.options.hostWindowViewport&&(i.viewport=null),t&&(i.storageState=t),this.context=await this.browser.newContext(i),this.options.defaultTimeout&&this.context.setDefaultTimeout(this.options.defaultTimeout),this.options.defaultNavigationTimeout&&this.context.setDefaultNavigationTimeout(this.options.defaultNavigationTimeout),this.context.on("page",async a=>{await this.onNewPage(a),await this.onFrameNavigated(a.mainFrame()),a.on("framenavigated",this.onFrameNavigated)}),this.context.on("close",async()=>{this.contextClosePromise=this.forEachEventListener(a=>{var s;return(s=a.onWebDriverContextClose)==null?void 0:s.call(a)})}),this.activePage=await this.context.newPage(),this.originalPage=this.activePage,this.options.trackLoadedResources&&this.page.on("requestfinished",this.onRequestFinished),this.options.useCDPSession&&(this.cdpSession=await this.context.newCDPSession(this.page)),!0}get frameMsgBroker(){return this.framesMessageBroker}async onNewPage(t){try{await(t==null?void 0:t.route("**/*",async(r,i)=>this.routeInterceptor.intercept(r,i,{page:t})))}catch(r){console.error("[WebDriver] onPage error",r)}}switchActivePage(t){let r=this.context.pages().find(i=>pt(i)===t);return!r||r.isClosed()?(console.error(`[WebDriver] Page with guid ${t} not found or has been closed.`),!1):(this.previousPage=this.activePage,this.activePage=r,!0)}getDefaultTimeout(){return this.options.defaultTimeout}getDefaultNavigationTimeout(){return this.options.defaultNavigationTimeout}async addHARMockAPIRecordings(t){if(!this.activePage){console.warn("[addHARMockAPIRecordings] Active page is not set, skipping HAR recording.");return}await this.activePage.routeFromHAR(t,{url:/^(?!.*\.(js|mjs|ts|jsx|tsx|css|jpg|jpeg|png|gif|svg|webp|heif|heic|raw|cr2|nef|arw|bmp|tiff|tif|ico|woff|woff2|ttf|otf|doc|docx|pdf|ws|wasm|mp3|wav|aac|flac|mp4|avi|mov|wmv|flv|zip|rar|7z|tar\.gz|xml|html|py|java|cpp|xls|xlsx|ppt|pptx|gif)$)/i,update:!0,updateMode:"minimal"})}forEachEventListener(t){return Promise.all(this.eventListeners.map(async r=>{try{await t(r)}catch(i){console.log("WebDriver/forEachEventListener exception",i)}}))}registerEventListener(t){this.eventListeners.push(t)}async getScript(){async function t(r){let{exec:i}=require("child_process");return new Promise((a,s)=>{i(r,l=>{l?(console.log("error executing cmd, ",l),s(l)):a()})})}switch(n(t,"execCmd"),this.options.scriptSource){case"file":return this.options.scriptFile;case"url":if(this.cacheScript)return this.options.scriptFile;try{return await t(`curl -o ${this.options.scriptFile} '${this.options.scriptURL}'`),this.options.scriptFile}catch(r){console.log("[web-driver] Failed fetching frontend script",r)}break}}async startJSCoverageTracking(){return await this.page.coverage.startJSCoverage(),[];return await this.cdpSession.send("Debugger.enable"),await this.cdpSession.send("Profiler.enable"),await this.cdpSession.send("Profiler.startPreciseCoverage",{callCount:!1,detailed:!0}),this.getCurrentJSCoverage()}stopJSCoverageTracking(){return this.page.coverage.stopJSCoverage()}async getCurrentJSCoverage(){let t=await this.page.coverage.stopJSCoverage();return await this.page.coverage.startJSCoverage(),t;return(await this.cdpSession.send("Profiler.takePreciseCoverage")).result}async startCSSCoverageTracking(){return await this.cdpSession.send("DOM.enable"),await this.cdpSession.send("CSS.enable"),await this.cdpSession.send("CSS.startRuleUsageTracking"),this.getCurrentCSSCoverage()}async getCurrentCSSCoverage(){return(await this.cdpSession.send("CSS.takeCoverageDelta")).coverage}getCDPSession(){return this.cdpSession}async navigate(t){return this.page.goto(t)}async setViewportSize(t,r){return this.page.setViewportSize({width:t,height:r})}async getStorageState(){return this.page.context().storageState()}async shutdown(){try{this.page&&(await this.page.close(),this.activePage=void 0),this.context&&(await this.context.close(),this.context=void 0),this.browser&&(await this.browser.close(),this.browser=void 0)}catch(t){console.warn("[WebDriver] shutdown error",t)}}async wrapWithBrowserLogs(t,{disabled:r=!1,onErrorOnly:i=!1}={}){if(r)return t();let a=[],s=n(d=>{a.push(d.text())},"log");this.page.on("console",s);let l,u;try{u=await t()}catch(d){l=d}if(this.page.off("console",s),(!i||l)&&console.log("browser console messages:",a),l)throw l;return u}async takeElementSnapshot(t,r,i={},a={}){if(t===this.lastSnapshot.selector&&r===this.lastSnapshot.eventCode)return{};if(!t)return{};try{let{snapshot:s,elementLocator:l}=await this.takeSnapshot(t,a,{frameLocatorSelector:i.frameLocatorSelector});return this.lastSnapshot={selector:t,eventCode:r},{snapshot:s,elementLocator:l}}catch(s){return console.error("takeElementSnapshot error",s),{}}}getScreenshotTimeout(t=!1){return t?this.snapshotTimeout:this.snapshotTimeout+5e3}async takePageSnapshot(t){let r=this.page.screenshot({...t,timeout:this.getScreenshotTimeout()});return await Promise.race([r,Ce(this.getScreenshotTimeout(!0))])}async takeSnapshot(t,r,{frameLocatorSelector:i}={}){let a=i?this.page.frameLocator(i).locator(t):this.page.locator(t),s=a.screenshot({...r,timeout:this.getScreenshotTimeout()});return{snapshot:await Promise.race([s,Ce(this.getScreenshotTimeout(!0))]),elementLocator:a}}async getCurrentURL(){return this.page.url()}async getClientScreenResolution(){return await this.page.evaluate(async()=>({width:window.screen.width,height:window.screen.height}))}async awaitContextClose(){return this.contextClosePromise||await Ce(100),this.contextClosePromise}get page(){return this.activePage}getPage(){return this.activePage}startPlaywrightTrace(){return this.tracing=!0,this.context.tracing.start({name:"trace",screenshots:!0,snapshots:!0})}startPlaywrightTraceChunk(){return this.tracingChunk=!0,this.context.tracing.startChunk({name:`trace-chunk-${this.chunkIndex}`})}stopPlaywrightTraceChunk(t){return this.tracingChunk=!1,this.context.tracing.stopChunk({path:`${t.replace(".zip",`.${this.chunkIndex++}.zip`)}`})}stopPlaywrightTrace(t){return this.tracing=!1,this.context.tracing.stop({path:t})}isTracing(){return this.tracing}isTracingChunk(){return this.tracingChunk}};n(Mg,"WebDriver");var $u=Mg;var Gs=require("jsdom");var Og=class Og{constructor(t){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new Gs.JSDOM(t),this.process()}process(){this.expandedChecksumIdsReducedDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new Gs.JSDOM(this.rawReducedHTMLDom.serialize());let t=n(l=>{l.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(d=>{d.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),r=n((l,u)=>u.window.document.body.querySelectorAll(`[${l}]`).forEach(d=>d.removeAttribute(l)),"removeAttributeFromAllElements"),i=n(l=>r("checksuminteractable",l),"removeChecksumInteractableAttribute"),a=n(l=>r("checksumid",l),"removeChecksumIdAttribute"),s=n(l=>r("rrwebid",l),"removeRrwebIdAttribute");t(this.reducedHTMLDom),i(this.expandedChecksumIdsReducedDom),i(this.reducedHTMLDom),i(this.rrwebIdsReducedDom),s(this.expandedChecksumIdsReducedDom),s(this.reducedHTMLDom),a(this.rrwebIdsReducedDom)}getDOMForType(t){switch(t){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(t){return await t(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(t){this.activeDOMType=t}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(t){return this.getDOMForType(t).serialize()}get raw(){return this.rawReducedHTMLDom}};n(Og,"ReducedHTMLDOM");var Gu=Og;var Lg=class Lg{constructor(t,r,i,a,s={logPerformance:!1}){this.timeMachine=t;this.actionsManager=r;this.apiService=i;this.remoteSessionId=a;this.options=s;this.currentChecksumId="0"}rewriteLastActionThought(t){throw new Error("Method not implemented.")}async generatePromptData(t,r,i){if(this.promptData)return{...this.promptData,assertionsData:r};let a=this.getActionTimestamps(t,i);if(!a)return;let s=await this.getReducedHTMLForTimestamp(a.before),l=await this.getReducedHTMLForTimestamp(a.after);return this.promptData={reduction:{reducedHTML:l,flashingHTML:[]},currentURL:"",previousReducedHTML:s,previousURL:"",actionId:t,assertionsData:r},this.promptData}async callApi(t,r,i,a){let s=Date.now(),l=await this.generatePromptData(r,i,a);if(this.logPerformance(`- Generated prompt data for ${t}`,s),!l)return;s=Date.now();let u=await this.apiService.post(`assertions/${t}`,{sessionId:this.remoteSessionId,data:l});if(!u.ok){console.error(`Request for assertion generation ${t} failed with status ${u.status}`);return}let d=await u.json();return this.logPerformance(`- Received response for assertion generation ${t}`,s),d}async generateAssertions(t,r){try{let i=await this.callApi("generate",t,void 0,r);if(i)return i.timestamps=this.getActionTimestamps(t,r),i}catch(i){throw console.error(i),i}}async refactoringAssertions(t){try{return await this.callApi("refactor",t.actionId,t)}catch(r){throw console.error(r),r}}async filteringAssertions(t){try{return await this.callApi("filter",t.actionId,t)}catch(r){throw console.error(r),r}}async getReducedHTMLWithRetries(t,{retriesLeft:r=3,retryWaitMS:i=1e3}={}){try{let{reducedHTML:a,currentChecksumId:s}=await t.evaluate(async l=>{var u,d;return(d=(u=window==null?void 0:window.checksum)==null?void 0:u.testGenerator)==null?void 0:d.reduceHTML({},l)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0});return this.currentChecksumId=s,{reducedHTML:a}}catch(a){if(r>0)return await Ce(i),this.getReducedHTMLWithRetries(t,{retriesLeft:r-1,retryWaitMS:i});throw a}}async getReducedHTMLForTimestamp(t){return this.timeMachine.executeTask(async r=>{let i="",a=await this.getReducedHTMLWithRetries(r);return i=a==null?void 0:a.reducedHTML,new Gu(i).getRrwebIdsReducedDomString()},t,{name:"getReducedHTMLForTimestamp"})}getVariables(){return[]}getVariablesString(t){return""}getActionTimestamps(t,r){let i=this.actionsManager.actions,a=i.findIndex(u=>u.id===t);if(a===-1){console.log(`[init] No action with id ${t} was found in executed actions`);return}let s=i[a],l=i[a+1];return{before:s.timestamp,after:(l==null?void 0:l.timestamp)??r}}logPerformance(t,r){this.options.logPerformance&&console.log(`${t} in`,Date.now()-r,"ms")}};n(Lg,"AssertionsAgent");var Vu=Lg;var nie=Ji.expect.configure({timeout:500}),_VtgAiAssertionsService=class _VtgAiAssertionsService extends Ua{constructor(t,r,i,a,s,l={logPerformance:!1}){super(t,r,i);this.actionsManager=t;this.apiService=r;this.userStoryService=i;this.timeMachine=a;this.webDriver=s;this.options=l;this.activeRemoteSessionIdByActionId=new Map}async init({retriesLeft:t=3,keepActionsWithoutDescription:r=!1,lastActionId:i=void 0}={}){await super.init({retriesLeft:t,keepActionsWithoutDescription:r,lastActionId:i}),this.activeRemoteSessionIdByActionId.set(i,this.remoteSessionId)}async generateAiAssertions({action:t,aiAssertionsGenerationStartedAt:r}){this.options.logPerformance&&console.log(`generateAiAssertions for action ${t.id}`);let i=n(async(a=[],s=!1)=>{let l=a.map((u,d)=>({...u,id:(Date.now()+d).toString()})).filter(u=>{var d;return!["withChecksumAI()","withChecksumAI"].includes(u.matcher)&&!((d=u.usedVariablesNames)!=null&&d.length)});return await this.webDriver.page.evaluate(({assertions:u,actionId:d,error:f})=>{window.vtg.onAIAssertionsGenerated(d,u,f)},{assertions:l,actionId:t.id,error:s}),l.forEach(u=>{this.actionsManager.addOrUpdateAssertionByActionId(t.id,u)}),l},"sendResultToVTG");if(this.isRunning(t.id))return console.log("Already generating assertions for this action"),i();try{let a=Date.now();if(await this.init({keepActionsWithoutDescription:!0,lastActionId:t.id}),this.logPerformance(`init for action ${t.id}`,a),!this.isRunning(t.id))return i();let s=new Vu(this.timeMachine,this.actionsManager,this.apiService,this.remoteSessionId),l=await this.generateAssertions(s,t.id,r);if(!l||!this.isRunning(t.id))return i();if(l.assertions.length===0){let{smartAssertion:u}=l;return u?(u.isSelected=!0,i([u])):i()}return xt.vtg.aiAssertions.allowRefactoring&&(l=await this.refactoringAssertions(s,l)),!this.isRunning(t.id)||(l=await this.filteringAssertions(s,l),!this.isRunning(t.id))?i():(this.logPerformance(`---------------- Overall - Generated assertions for action ${t.id} in`,a),i(C_(l)))}catch(a){return console.error("Error in AI assertions generation",a),i([],!0)}finally{this.activeRemoteSessionIdByActionId.delete(t.id)}}stopGenerateAiAssertions({action:t}){this.activeRemoteSessionIdByActionId.delete(t.id)}isRunning(t){return this.activeRemoteSessionIdByActionId.has(t)}async generateAssertions(t,r,i=void 0){let a=Date.now(),s=a,l=await t.generateAssertions(r,i);if(this.logPerformance(`- generateAssertions for action ${r}`,a),!!l)return a=Date.now(),await this.setSelectionDataForAssertions(l),this.logPerformance(`- setSelectionData for action ${r}`,a),a=Date.now(),await this.validateAssertions(l.assertions,l.timestamps,t),this.logPerformance(`- validate assertions for action ${r}`,a),this.logPerformance(`Overall - Generated assertions for action ${r}`,s),l}async refactoringAssertions(t,r){let i=Date.now(),a=i;try{this.options.logPerformance&&console.log(`Refactoring assertions for action ${r.actionId}`),r=await t.refactoringAssertions(r),this.logPerformance(`- refactoringAssertions for action ${r.actionId}`,i),i=Date.now(),await this.validateAssertions(r.assertions,r.timestamps,t),this.logPerformance(`- validate assertions after refactoring for action ${r.actionId}`,i),this.logPerformance(`Overall - Refactored assertions for action ${r.actionId}`,a)}catch(s){console.error("[refactoringAssertions] Error in assertions refactoring",s)}return r}async filteringAssertions(t,r){try{let i=Date.now();this.options.logPerformance&&console.log(`Filtering assertions for action ${r.actionId}`);let a=await t.filteringAssertions(r);return this.logPerformance(`Overall - filteringAssertions for action ${r.actionId}`,i),a}catch(i){console.error("[filteringAssertions] Error in assertions filtering",i)}}async executeAssertion(assertion,timeMachine,agent){let variablesString=agent.getVariablesString(!0),page=timeMachine,executeMatcherCode=`
|
|
131
131
|
(async () => {
|
|
132
132
|
${variablesString}
|
|
133
133
|
${mg(qu(assertion))}
|
|
@@ -137,7 +137,7 @@ show-report [options] [report] show HTML report
|
|
|
137
137
|
${variablesString}
|
|
138
138
|
return await ${mg(hg(assertion))}.all();
|
|
139
139
|
})()`;try{let result=await eval(getLocatorsScript);return result}catch(t){return console.error(`Error getting Locator[] for assertion with locator: ${locator}`,getLocatorsScript,t.message),[]}}async isLocatorMappedToCorrectRrwebId(t,r,i){if(Bu(t))return!0;let a=await this.getLocatorRrwebIds(t,r,i);return a.length!==1?!1:a[0]===t.rrwebid}async validateAssertions(t,r,i){let a=t.filter(s=>s.isValid===void 0&&!Bu(s));await this.executeValidationTasksOnState(a,r,i,{isPreviousState:!0}),a=a.filter(s=>s.isValid===void 0),await this.executeValidationTasksOnState(a,r,i,{isPreviousState:!1}),a.forEach(s=>{s.isValid??(s.isValid=!0)})}async setSelectionDataForAssertions(t){let r=n(s=>{var l;return(l=s.matcher)==null?void 0:l.startsWith("toBeHidden")},"shouldGetSelectionDataFromPreviousState"),[i,a]=t.assertions.reduce(([s,l],u)=>(r(u)?s.push(u):l.push(u),[s,l]),[[],[]]);await this.setSelectionDataForAssertionsInTimestamp(i,t.timestamps.before),await this.setSelectionDataForAssertionsInTimestamp(a,t.timestamps.after)}async setSelectionDataForAssertionsInTimestamp(t,r){if(!(!t||t.length===0))return this.timeMachine.executeTask(async i=>{await Promise.all(t.map(a=>this.setSelectionData(a,i)))},r)}async executeValidationTasksOnState(t,r,i,{isPreviousState:a}){let s=a?"validateAssertionOnPreviousState":"validateAssertionOnCurrentState",l=(a?this.validateAssertionOnPreviousState:this.validateAssertionOnCurrentState).bind(this),u=a?r.before:r.after;await this.timeMachine.executeTask(async d=>{await Promise.all(t.flatMap(f=>{let h=dg(f)===a,g=!f.locatorMappedToCorrectRrwebId&&h,x=this.validateLocatorMappedToCorrectRrwebId(f,d,i),w=l(f,d,i);return g?[x,w]:[w]}))},u,{name:s})}async setSelectionData(t,r){if(!(!t.rrwebid||t.locator))try{let i=await r.evaluate(a=>window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(a,{ignoredIframesSelectors:["iframe"],fromTimeMachine:!0}),parseInt(t.rrwebid,10));Object.assign(t,i,{locatorMappedToCorrectRrwebId:!0})}catch(i){t.locatorMappedToCorrectRrwebId=!1,this.handleAssertionValidityError(i,t,"invalid locator")}}logPerformance(t,r){this.options.logPerformance&&console.log(`${t} in`,Date.now()-r,"ms")}handleAssertionValidityError(t,r,i){console.error(t.message),r&&(r.isValid=!1,r.invalidReason=i)}};n(_VtgAiAssertionsService,"VtgAiAssertionsService");var Zu=_VtgAiAssertionsService;var Dg=class Dg{async run(t,{thought:r,matcher:i,id:a}){return{...await this.processAssertion(t,{thought:r,matcher:i}),id:a}}async processAssertion(t,{thought:r,matcher:i}){let a={...t};return{thought:r,selected:!0,locator:a.locator,matcher:i}}};n(Dg,"VisualAssertionsGenerator");var Ku=Dg;var _VtgAssertionsService=class _VtgAssertionsService{constructor(e,t){this.webDriver=e;this.actionsManager=t}async verifyOnLive({locator,matcher}){return this.verify({locator:eval("this.webDriver.liveMainFrame."+locator),matcher})}async verifyOnTimeMachine({locator,matcher}){try{return this.verify({locator:eval('this.webDriver.tmFrame.frameLocator("iframe").'+locator),matcher,expect:Ji.expect.configure({timeout:1e3})})}catch(e){return console.log(e),{success:!1,message:String(e)}}}async verify({locator:e,matcher:t,expect:r=Ji.expect}){try{let i=r(e),a=`async (expectCall) => expectCall.${t}`;return await(0,eval)(a)(i),{success:!0,message:"Assertion verified successfully!"}}catch(i){return{success:!1,message:String(i)}}}async saveOrUpdateAssertionForAction({actionId:e,locator:t,thought:r,matcher:i,id:a}){if(this.actionsManager.actions.findIndex(({id:u})=>u===e)===-1)throw new Error(`[generateAssertionForAction] No action with id ${e} was found in executed actions`);let l=await new Ku().run({locator:t},{thought:r,matcher:i,id:a});return this.actionsManager.addOrUpdateAssertionByActionId(e,l),l}};n(_VtgAssertionsService,"VtgAssertionsService");var Ju=_VtgAssertionsService;var Bg=class Bg{log(...t){console.log(...t)}logError(...t){console.error(...t)}};n(Bg,"TMPAgentLoggerConsole");var Ga=Bg;var qg=class qg{constructor(t,r,i=new Ga){this.promptAssets=t;this.apiService=r;this.logger=i}async runLLMFiltering(t=[],r,{useImage:i=!0,useVariables:a=!0}={}){try{let s={title:this.promptAssets.title,steps:this.promptAssets.steps,thought:this.promptAssets.thought,parentChainHTML:r,generatedLocators:t,...i&&this.promptAssets.image?this.promptAssets.image:{}};return await(await this.apiService.post("vtg/locators/filter",s)).json()}catch(s){this.logger.log("Error generating selector with LLM filtering",s.message);return}}async extractCompoundSelectionData(t){throw new Error("Method not implemented.")}async extractCSSKeyElements(t){t||(t=this.promptAssets.parentChainHTML);let r={title:this.promptAssets.title,steps:this.promptAssets.steps,thought:this.promptAssets.thought,parentChainHTML:t};try{return await(await this.apiService.post("vtg/locators/extract-css",r)).json()}catch(i){throw console.error(i),i}}};n(qg,"VTGSelectorGeneratorAPI");var Vs=qg;var Zq="variablesStore.",Ng=class Ng{constructor(t,r,i=async()=>null,a=new Ga){this.selectorGeneratorApi=t;this.variables=r;this.evaluateWithChecksum=i;this.logger=a}async generateSelectionForAction(t,r){var u;let{useCSSExtraction:i,useCompoundSelector:a,useVariables:s,useArbitrarySelector:l}=r;if(l&&!t.contextElements&&t.isPartOfListItem&&t.couldPickAnyListItem)try{this.logger.log("*** Will generate arbitrary selector");let d=await this.evaluateWithChecksum(async({checksumId:f})=>window.checksum.testGenerator.buildArbitraryListItem(f),{checksumId:t.action.checksumid});if(d)return d[0]}catch(d){console.error("Error generating arbitrary selector",d)}if(!a||!t.contextElements||!t.isPartOfListItem){let d=await this.generateWithLLMFiltering(t.action.checksumid,await this.generateLocatorsForElement(t.action.checksumid,{isPartOfListItem:t.isPartOfListItem,isForContextElement:!1,useCSSExtraction:i}),null,{isPartOfListItem:t.isPartOfListItem,useVariables:s});if(d)return t.isPartOfListItem&&!d.locator.endsWith(".first()")&&(d.selector+=" >> nth=0",d.locator+=".first()",(u=d.selectorWithVars)!=null&&u.length&&(d.selectorWithVars+=" >> nth=0",d.locatorWithVars+=".first()")),d}if(a&&t.contextElements){let d=await this.generateCompoundSelector(t.action.checksumid,t.isPartOfListItem);if(d)return{compoundSelector:d}}console.log("[SelectorGenerator] Failed to generate selection")}async generateWithLLMFiltering(t,r,i,{useImage:a=!0,useVariables:s=!0,isPartOfListItem:l=!1,isForContextElement:u=!1}={}){var d,f;try{if(this.logger.log("*** Will generate selector with LLM filtering"),l){let g=r.find(x=>x.isListSelector);if(g)return g}let h=r.length>1||s&&Object.keys(((d=this.variables)==null?void 0:d.keyValue)??{}).length>0?await this.selectorGeneratorApi.runLLMFiltering(r,i??await this.getParentChainHTML(t),{useImage:a,useVariables:s}):r;for(let g of h){let x=await this.testSelector(g,t,{testUniqueness:!(l||u),useVariables:s});if(this.logger.log(`Tested selector: ${g.selector}'
|
|
140
|
-
result:`,x),x!=null&&x.valid)return{...x,...s&&((f=g.variables)!=null&&f.length)?{selectorWithVars:g.selector,locatorWithVars:x.locatorWithVars}:{},alternateSelectors:h.filter(w=>w!==g).map(w=>w.selector)}}return}catch(h){this.logger.log("Error generating selector with LLM filtering",h.message);return}}async generateCompoundSelector(t,r){try{this.logger.log("*** Will generate compound selector");let i=await this.selectorGeneratorApi.extractCompoundSelectionData(t);return this.processContextElements(i,r)}catch(i){this.logger.log("Error generating compound selector",i);return}}async processContextElements(t,r){let i=await this.evaluateWithChecksum(async({contextElementsMetadata:s,isPartOfListItem:l})=>window.checksum.testGenerator.getCompoundSelector().filter(s,{isPartOfListItem:l}).map(({element:u,...d})=>d),{contextElementsMetadata:t,isPartOfListItem:r});if(console.log(`Filtered context elements: ${i.length}`),i.length<2){this.logger.log("<!> No context elements found besides target, skipping");return}let a;try{if(a=await this.evaluateWithChecksum(async({contextElements:s,isPartOfListItem:l})=>window.checksum.testGenerator.getCompoundSelector().generate(s,{isPartOfListItem:l}),{contextElements:i,isPartOfListItem:r}),!a){this.logger.log("Error generating compound selector metadata for context elements");return}this.logger.log(`Generated compound selector metadata for ${i.length} context elements (including target)`)}catch(s){this.logger.log("Error generating compound selector metadata for context elements",s.message)}try{this.logger.log("** Generating selectors for context elements");let s=[];await Promise.all(i.map(async d=>{if(d.selection.type==="content"){s.push({...d,selector:`internal:text="${d.selection.value}"`,locator:`getByText("${d.selection.value}")`});return}let f=await this.generateWithLLMFiltering(d.selection.checksumid,await this.generateLocatorsForElement(d.selection.checksumid,{isForContextElement:!0,useCSSExtraction:!1,isPartOfListItem:!1}),null,{useImage:!1,isForContextElement:!0});if(!f)throw new Error("Failed to generate selector for context element");s.push({...d,...f})}));let{targetSelection:l}=a,u=l.playwrightSelectors.length>0?l.playwrightSelectors[0]:{selector:l.cssSelectors[0]};if(!u.selector)throw new Error("Failed to get target relative selector");return this.logger.log("Generated customer facing compound selector - ",[...s.map(d=>d.selector),"target: "+u.selector]),{elements:s,targetRelativeSelector:u,metadata:a}}catch(s){this.logger.log("Error generating customer facing compound selector metadata for context elements",s)}}async testSelector(t,r,{testUniqueness:i=!0,useVariables:a=!0}={}){var s;try{return a=a&&!!((s=t.variables)!=null&&s.length),await this.evaluateWithChecksum(async({checksumId:u,selector:d,testVariables:f,testUniqueness:h})=>{try{return window.checksum.testGenerator.testElementSelector(d,u,f,h)}catch(g){console.log("Error testing selector",g)}},{checksumId:r,selector:a?this.implantVariablesValues(t):t.selector,testVariables:a?{selectorWithVars:t.selector,variablesCode:this.variables.code}:void 0,testUniqueness:i})}catch(l){return console.error("Error testing selector",l),{valid:!1}}}implantVariablesValues(t){var i;return(i=t.variables)!=null&&i.length?Object.entries(this.variables.keyValue).map(([a,s])=>[Zq+a,s]).filter(([a])=>t.variables.map(s=>s.name).includes(a)).reduce((a,[s,l])=>a.replace("${"+s+"}",l),t.selector):t.selector}async getParentChainHTML(t){try{return this.parentChainHTML||(this.parentChainHTML={}),this.parentChainHTML[t]||(this.parentChainHTML[t]=await this.evaluateWithChecksum(async({checksumId:r})=>window.checksum.testGenerator.getParentChainHTML(r),{checksumId:t})),this.parentChainHTML[t]}catch(r){throw this.logger.log("Error getting parent chain HTML",r),r}}async getExtractCSSKeyElements(t){try{let r=await this.getParentChainHTML(t);return this.selectorGeneratorApi.extractCSSKeyElements(r)}catch(r){return this.logger.log("Error generating prompt for CSS key elements",r),[]}}async generateLocatorsForElement(t,r={isPartOfListItem:!1,isForContextElement:!1,useCSSExtraction:!0}){try{console.log("Generating custom locators");let i=r.useCSSExtraction?await this.getExtractCSSKeyElements(t):[],a=await this.evaluateWithChecksum(async({checksumId:s,keyFeatures:l,...u})=>window.checksum.testGenerator.buildCustomPlaywrightSelectors(s,l,u),{checksumId:t,keyFeatures:i,...r});return this.logger.log("Generated locators for filtering (first is playwright's)",a),a}catch(i){throw this.logger.log("Error generating prompt for selectors",i),i}}};n(Ng,"SelectorGenerator");var Xu=Ng;var _VtgLocatorsService=class _VtgLocatorsService{constructor(e,t,r){this.webDriver=e;this.apiService=t;this.userStoryService=r}getStory(){return this.userStoryService.getStory()}async verifyLocatorOrSelector({type,value}){try{let elementLocator;switch(type){case"locator":try{elementLocator=eval(jb(value,'this.webDriver.tmFrame.frameLocator("iframe")'))}catch(e){throw new Error(e.message)}break;case"selector":elementLocator=this.webDriver.tmFrame.frameLocator("iframe").locator(value);break}if(!elementLocator)throw new Error(`Element for ${type} ${value} not found`);let selectorCount;try{selectorCount=await elementLocator.count()}catch(e){throw new Error("Could not evaluate element")}if(selectorCount===2){for(let e=0;e<2;e++)if(await elementLocator.nth(e).evaluate(r=>r.matches(".element-inspector-ignore")))return{success:!0}}if(selectorCount!==1)throw new Error(selectorCount===0?"No element found":`Strict mode: ${selectorCount} elements found`);return{success:!0}}catch(e){return{success:!1,message:String(e)}}}async generateCSSExtractionForLocator(e,t){let r={...this.getSelectorGeneratorBasePromptAssets(e),parentChainHTML:t};return new Vs(r,this.apiService).extractCSSKeyElements()}async runLLMFilteringForLocator(e,t,r,i){let a={...this.getSelectorGeneratorBasePromptAssets(e),parentChainHTML:t,generatedLocators:r,image:i};return new Xu(new Vs(a,this.apiService),null,this.webDriver.evaluateWithChecksum.bind(this.webDriver)).generateWithLLMFiltering(e.id,r,t,{useImage:!!i,useVariables:!1,isPartOfListItem:!1,isForContextElement:!1})}getSelectorGeneratorBasePromptAssets(e){try{let{goal:t,instructions:r}=this.getStory();return{title:t,steps:r,thought:e.description}}catch(t){return console.log("Failed getting base prompt assets",t),{title:"",steps:"",thought:e.description}}}};n(_VtgLocatorsService,"VtgLocatorsService");var Yu=_VtgLocatorsService;var J_=require("request"),ep=require("fs");var jg=class jg{constructor(t,r,i,a,s,l=console.log){this.apiBaseURL=t;this.apiKey=r;this.uploadTimeout=i;this.makeGetUploadUrlAPIPath=a;this.onOutstandingUpload=s;this.log=l}async uploadAsset(t){try{let{path:r}=t.info;if(this.log("Uploading file",r),await this.getSignedURLForUpload(t),!t.uploadURL){this.log("Error getting signed URL for asset",r),t.error=!0;return}let a=(0,ep.statSync)(r).size,s=(0,ep.createReadStream)(r),l=mt(new Promise((u,d)=>{var h;let f=(0,J_.put)(t.uploadURL,{body:s,headers:{"Content-Type":o_[t.info.type]??""}},(g,x)=>{g&&d(g),u(x)});(h=this.onOutstandingUpload)==null||h.call(this,{request:f,size:a})}),this.uploadTimeout);l.then(u=>{if(u.statusCode!==200)throw new Error("Upload failed");this.log("File uploaded successfully",r),t.complete=!0}).catch(u=>{this.log("Error uploading asset",r,u),t.error=!0}),t.response=l}catch{t.error=!0}}async getSignedURLForUpload(t){try{let r=t.info,i=await fetch(`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(t)}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(r)}),{url:a}=await i.json();t.uploadURL=a}catch(r){return this.log("Error getting signed URL for artifact",r),null}}};n(jg,"TestAssetUploader");var Qu=jg;var X_=At(Bm()),Bn=require("path"),Xi=require("fs");async function Y_(e,t){let r=await(0,Xi.readdirSync)(t);await Promise.all(r.map(async i=>{let a=(0,Bn.join)(t,i);if((await(0,Xi.statSync)(a)).isDirectory()){let l=e.folder(i);await Y_(l,a)}else{let l=await(0,Xi.readFileSync)(a);e.file(i,l)}}))}n(Y_,"addFolderToZip");async function Q_(e){try{let t=await(0,X_.loadAsync)("UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==",{base64:!0});await Y_(t,e);let r=await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"}),i=(0,Bn.join)((0,Bn.dirname)(e),`${(0,Bn.basename)(e)}.zip`);return(0,Xi.writeFileSync)(i,r),i}catch(t){return console.error("Error creating zip:",t),null}}n(Q_,"zipFolder");var qn=require("fs");var Ug=class Ug{constructor(t,r,i,a,s,l){this.config=t;this.userStoryService=r;this.apiService=i;this.actionsManager=a;this.testAssetsManager=s;this.actionsService=l}getLocalSavedData(t){try{let r=(0,qn.readFileSync)(`${this.testAssetsManager.getLocalSavePath()}/${t}/test.json`,"utf-8");return JSON.parse(r)}catch(r){return console.error(`Error reading or parsing JSON file: ${r}`),null}}async localSave(){let t={executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:this.config.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()};(0,qn.writeFileSync)(`${this.testAssetsManager.getAssetsFolderPath()}/test.json`,JSON.stringify(t,null,2)),(0,qn.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,JSON.stringify(t,null,2))}async localBackup(t){k_(this.testAssetsManager.getLocalAutoSavePath(),this.testAssetsManager.getLocalSaveAsPath(t))}getIsFolderAlreadyExistsInDrafts(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,qn.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){console.log("No test generation data, can't upload");return}let t=await this.userStoryService.createTestGeneration(),r=new Qu(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${t}/get-upload-url`),i=n(u=>({complete:!1,error:!1,response:void 0,info:u}),"buildUploadAsset"),a=i({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),s=i({type:"har",path:await Q_(this.testAssetsManager.getHarFolderPath())});await Promise.all([r.uploadAsset(a),r.uploadAsset(s)]);let l=this.actionsManager.actions.map(u=>({...u,parentFramesSelectors:u.parentFramesSelectors?u.parentFramesSelectors.filter(d=>d!=="iframe"):void 0}));await this.apiService.post(`test-generation/${t}/completed`,{actions:l})}catch(t){console.error("Failed to upload test",t)}}};n(Ug,"VtgStorageService");var tp=Ug;var Kq={goal:"Send email via outreach list",instructions:"Make sure to select a user from the list first",environment:{name:void 0,userRole:void 0}},zg=class zg{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var t;return!!((t=this.userStoryTestGeneration)!=null&&t.internalTestId)}setStoryInfo(t,r){this.story=t,this.userStoryTestGeneration=r}async fetchStory(t){if(xt.vtg.useFakeStory){console.log("Using fake flow data"),this.story=Kq;return}if(!t)throw new Error("no story id provided");let i=await(await this.apiService.post(`test-generation/info/${t}`)).json();console.log("Received flow data:",i);let{id:a,title:s,steps:l,startUrl:u,userRole:d,environment:f,internalTestId:h,generationBatchId:g}=i;this.userStoryTestGeneration={internalTestId:h,generationBatchId:g},this.story={id:a,goal:s,instructions:l,url:u,environment:{userRole:d,name:f}}}getEnvInfo(){return Qm(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration.testGenerationId=r,r}};n(zg,"VtgUserStoryService");var rp=zg;var Wg=class Wg{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}addOrUpdateAssertionByActionId(t,r){this.executedActions=this._executedActions.map(i=>{var a;return i.id===t?(a=i.assertions)!=null&&a.find(({id:l})=>l===r.id)?{...i,assertions:i.assertions.map(l=>l.id===r.id?Object.assign(l,r):l)}:{...i,assertions:[...i.assertions??[],r]}:i})}setStorageService(t){this.storageService=t}pushExecutedActionOrAddAfterParent(t,r={}){if(r.parentAction){let i=this._executedActions.findIndex(({id:a})=>a===r.parentAction.id);if(i!==-1){let a={...t,timestamp:this._executedActions[i].timestamp+1};this._executedActions=[...this._executedActions.slice(0,i+1),a,...this._executedActions.slice(i+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:i})=>i===t.id);r!==-1&&(this.executedActions=[...this._executedActions.slice(0,r),{...this._executedActions[r],...t},...this._executedActions.slice(r+1)])}deleteStep(t,r){r?this.executedActions=this._executedActions.map(i=>{if(i.id===t){let a=i.assertions.filter(({id:s})=>s!==r);return Object.assign(i,{assertions:a})}return i}):this.executedActions=this._executedActions.filter(({id:i})=>i!==t)}};n(Wg,"VtgActionsManager");var ip=Wg;var Xx=At(n4()),u4=At(require("net")),p4=At(ix()),f4=At(l4());var Yx=class Yx{constructor(t,r,i,a,s,l,u,d){this.actionsService=t;this.assertionsService=r;this.locatorsService=i;this.aiTestGenerationService=a;this.aiAssertionsService=s;this.actionsManager=l;this.storageService=u;this.settingsService=d}async start(){return this.app=(0,Xx.default)(),this.app.use((0,f4.default)()),this.app.use(p4.default.json({limit:"50mb"})),this.app.use(Xx.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),this.setupEndpoints(),new Promise(t=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),t()})})}setupEndpoints(){this.app.get("/api",async(t,r)=>{r.send("success")}),this.app.post("/api/test/upload",async(t,r)=>(await this.storageService.saveToCloud(),r.send("success"))),this.app.post("/api/test/local-save",async(t,r)=>{await this.storageService.localSave(),r.send("success")}),this.app.post("/api/test/verify-save-location",async(t,r)=>{try{let i=this.storageService.getIsFolderAlreadyExistsInDrafts(t.body.location);r.send({exists:i})}catch(i){r.status(400).send({error:i})}}),this.app.post("/api/test/backup",async(t,r)=>{t.body.backupFolderName&&!__(t.body.backupFolderName)?r.status(400).send({error:"Invalid folder name"}):(await this.storageService.localBackup(t.body.backupFolderName),r.send("success"))}),this.app.post("/api/ai/init",async(t,r)=>{await this.aiTestGenerationService.init(),r.send("success")}),this.app.post("/api/ai/iterate",async(t,r)=>{let i=t.body,a=await this.aiTestGenerationService.iterate(i);return a?r.status(200).json(a):r.status(400).send("no action generated")}),this.app.post("/api/ai/generate-assertions",async(t,r)=>{let i=t.body;this.aiAssertionsService.generateAiAssertions(i),r.status(200).send({success:!0})}),this.app.post("/api/ai/stop-generate-assertions",async(t,r)=>{let i=t.body;return await this.aiAssertionsService.stopGenerateAiAssertions(i),r.status(200).send("success")}),this.app.post("/ai/stop",async(t,r)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/selector/play",async(t,r)=>{let i=t.body;try{let a=await this.locatorsService.verifyLocatorOrSelector(i);return r.status(200).send(a)}catch(a){return r.status(400).send({error:a.message})}}),this.app.post("/api/assertion/verify/time-machine",async(t,r)=>{let i=t.body,a=await this.assertionsService.verifyOnTimeMachine(i);return r.status(200).send(a)}),this.app.post("/api/assertion/verify/live",async(t,r)=>{let i=t.body,a=await this.assertionsService.verifyOnLive(i),s=a.success?200:404;return r.status(s).send(a)}),this.app.post("/api/assertion/save",async(t,r)=>{let i=t.body;try{let a=await this.assertionsService.saveOrUpdateAssertionForAction(i);r.status(200).json(a)}catch(a){r.status(400).send({error:a.message})}}),this.app.post("/api/locators/generate/css",async(t,r)=>{let{action:i,parentChainHTML:a}=t.body;try{let s=await this.locatorsService.generateCSSExtractionForLocator(i,a);r.status(200).json(s)}catch(s){r.status(400).send({error:s.message})}}),this.app.post("/api/locators/filter",async(t,r)=>{let{action:i,parentChainHTML:a,generatedLocators:s,image:l}=t.body;try{let u=await this.locatorsService.runLLMFilteringForLocator(i,a,s,l);r.status(200).json(u)}catch(u){r.status(400).send({error:u.message})}}),this.app.post("/api/steps/execute",async(t,r)=>{let i=t.body,a=i.isAISuggestion?this.aiTestGenerationService.executeAction:this.actionsService.executeAction;try{let s=await a(i.action,i.options);return r.status(200).json(s)}catch(s){return r.status(404).send({error:s.message})}}),this.app.post("/api/upload-files",async(t,r)=>{try{await this.actionsService.uploadFiles(t.body.files)}catch(i){return r.status(500).send(i)}return r.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(t,r)=>{let i=t.body;return this.actionsManager.addManualActionsToExecuted(i.action),r.send("success")}),this.app.patch("/api/steps",async(t,r)=>{let i=t.body;return this.actionsManager.updateExecutedAction({...i.update,id:i.id}),r.send("success")}),this.app.put("/api/steps",async(t,r)=>{let i=t.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(i.action,i.options)}catch(a){return r.status(500).send(a)}return r.send("success")}),this.app.delete("/api/step",async(t,r)=>{let{assertionId:i,actionId:a}=t.body;try{this.actionsManager.deleteStep(a,i)}catch(s){return r.status(500).send(s)}return r.status(200).send({message:"Success!"})}),this.app.get("/api/settings",async(t,r)=>{let i=this.settingsService.getSettings();return r.status(200).send(i)}),this.app.post("/api/settings",async(t,r)=>(this.settingsService.updateSettings(t.body),r.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((t,r)=>{let i=u4.default.createServer();i.unref(),i.on("error",r),i.listen(0,()=>{let a=i.address().port;i.close(()=>{t(a)})})})}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}};n(Yx,"VtgExpressServer");var df=Yx;var hf=require("fs");var Qx=class Qx{constructor(t,r){this.projectRootDirectory=t;this.checksumRoot=r;this.localSaveFolderPath=`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,hf.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,hf.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(t){this.autoSaveFolderPath=`/auto-save/${t}`,(0,hf.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return this.localSaveFolderPath+this.autoSaveFolderPath}getLocalSaveAsPath(t){return t&&(this.currentSaveAsLocation=t),this.currentSaveAsLocation||(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};n(Qx,"VtgTestAssetsManager");var mf=Qx;var RZ={useCDPSession:!0,trackLoadedResources:!0},ey=class ey extends $u{constructor(r={},i={devtools:!1},a={}){super({...RZ,...r},i);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=n(async(r,i=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:i}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=n(async r=>{try{return await r.waitForFunction(()=>{var i;return!!((i=window.checksum)!=null&&i.testGenerator)}),r.evaluate(async({appSpecificRules:i,config:a,initModules:s})=>{window.checksum.testGenerator.init(i,a,s),i.hasGoals&&await window.checksum.goalTracker.init()},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(i){console.log("initInjectedScript exception",i)}},"initInjectedScript");this.settings={...this.settings,...a},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let i=await super.prepare(r);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),i}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,i,a=this.evaluateWithChecksumTargetFrame){let s=this.injectedScriptManager.getNavigationPromise(a);s&&await s;try{return a.evaluate(r,i)}catch(l){throw console.error("evaluateWithChecksum error",l,r.toString()),l}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async i=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(i),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(i=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(i),r)}async postRRwebEvents(r){return this.evaluateWithChecksum(i=>window.checksum.testGenerator.postRRwebEvents(i),r)}async getRRwebEvents(r=0){return this.evaluateWithChecksum(async({index:i})=>window.checksum.testGenerator.getRRwebEvents(i),{index:r})}async getGoals(){return await this.evaluateWithChecksum(async()=>window.checksum.goalTracker.getGoals())}async takeElementSnapshot(r,i,a={},s={}){try{let{snapshot:l,elementLocator:u}=await super.takeElementSnapshot(r,i,a);if(!l||!a.takeBodyScreenshot)return l?{snapshot:l}:{};await this.highlightElementByLocator(u,a.mousePosition);let d=await this.takePageSnapshot(s);return await this.clearHighlights(),{snapshot:l,bodySnapshot:d}}catch(l){return console.error("[ChecksumWebDriver] takeElementSnapshot error",l),{}}}async highlightElementByLocator(r,i,a="20px solid rgba(255,0,0,1)"){return this.evaluateWithChecksum(async([s,l,u])=>{window.checksum.testGenerator.highlightElement(s,{highlightStyle:{outline:l},mousePosition:u})},[await r.elementHandle(),a,i])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};n(ey,"ChecksumWebDriver");var gf=ey;var b4=require("fs"),w4=At(require("path"));var ty=require("fs");var ry=class ry{constructor(t,r=xt.vtg.localBuildPath){this.page=t;this.filePath=r;this.filePath=r}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await Ce(2e3)}catch(t){console.error("An error occurred:",t)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t=xt.vtg.appURL;await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(!xt.isDevMode)try{let t=await ty.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,i=t.replace(r,"$1=$2.$3static");await ty.promises.writeFile(this.filePath,i,"utf8"),console.log(`Successfully modified ${this.filePath}`)}catch(t){console.error(`Error processing file ${this.filePath}:`,t)}}};n(ry,"VtgFrontendLauncher");var vf=ry;var cn={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Mce={defaultMerge:cn.defaultMerge};function MZ(e,t){return t}n(MZ,"defaultMetaDataUpdater");function OZ(e,t){return e.filter(r=>r!==void 0)}n(OZ,"defaultFilterValues");var d4;(function(e){e[e.NOT=0]="NOT",e[e.RECORD=1]="RECORD",e[e.ARRAY=2]="ARRAY",e[e.SET=3]="SET",e[e.MAP=4]="MAP",e[e.OTHER=5]="OTHER"})(d4||(d4={}));function h4(e){return typeof e!="object"||e===null?0:Array.isArray(e)?2:BZ(e)?1:e instanceof Set?3:e instanceof Map?4:5}n(h4,"getObjectType");function LZ(e){let t=new Set;for(let r of e)for(let i of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(i);return t}n(LZ,"getKeys");function DZ(e,t){return typeof e=="object"&&Object.prototype.propertyIsEnumerable.call(e,t)}n(DZ,"objectHasProperty");function g4(e){var i;let t=0,r=(i=e[0])==null?void 0:i[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var a;do{if(r===void 0)return{done:!0,value:void 0};let s=r.next();if(s.done===!0){t+=1,r=(a=e[t])==null?void 0:a[Symbol.iterator]();continue}return{done:!1,value:s.value}}while(!0)}}}}}n(g4,"getIterableOfIterables");var m4=["[object Object]","[object Module]"];function BZ(e){if(!m4.includes(Object.prototype.toString.call(e)))return!1;let{constructor:t}=e;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!m4.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}n(BZ,"isRecord");function qZ(e,t,r){let i={};for(let a of LZ(e)){let s=[];for(let d of e)DZ(d,a)&&s.push(d[a]);if(s.length===0)continue;let l=t.metaDataUpdater(r,{key:a,parents:e}),u=x4(s,t,l);u!==cn.skip&&(a==="__proto__"?Object.defineProperty(i,a,{value:u,configurable:!0,enumerable:!0,writable:!0}):i[a]=u)}return i}n(qZ,"mergeRecords$1");function NZ(e){return e.flat()}n(NZ,"mergeArrays$1");function jZ(e){return new Set(g4(e))}n(jZ,"mergeSets$1");function UZ(e){return new Map(g4(e))}n(UZ,"mergeMaps$1");function zZ(e){return e.at(-1)}n(zZ,"mergeOthers$1");var xf={mergeRecords:qZ,mergeArrays:NZ,mergeSets:jZ,mergeMaps:UZ,mergeOthers:zZ};function v4(...e){return WZ({})(...e)}n(v4,"deepmerge");function WZ(e,t){let r=HZ(e,i);function i(...a){return x4(a,r,t)}return n(i,"customizedDeepmerge"),i}n(WZ,"deepmergeCustom");function HZ(e,t){return{defaultMergeFunctions:xf,mergeFunctions:{...xf,...Object.fromEntries(Object.entries(e).filter(([r,i])=>Object.hasOwn(xf,r)).map(([r,i])=>i===!1?[r,xf.mergeOthers]:[r,i]))},metaDataUpdater:e.metaDataUpdater??MZ,deepmerge:t,useImplicitDefaultMerging:e.enableImplicitDefaultMerging??!1,filterValues:e.filterValues===!1?void 0:e.filterValues??OZ,actions:cn}}n(HZ,"getUtils");function x4(e,t,r){var s;let i=((s=t.filterValues)==null?void 0:s.call(t,e,r))??e;if(i.length===0)return;if(i.length===1)return iy(i,t,r);let a=h4(i[0]);if(a!==0&&a!==5){for(let l=1;l<i.length;l++)if(h4(i[l])!==a)return iy(i,t,r)}switch(a){case 1:return $Z(i,t,r);case 2:return GZ(i,t,r);case 3:return VZ(i,t,r);case 4:return ZZ(i,t,r);default:return iy(i,t,r)}}n(x4,"mergeUnknowns");function $Z(e,t,r){let i=t.mergeFunctions.mergeRecords(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(e,t,r):i}n($Z,"mergeRecords");function GZ(e,t,r){let i=t.mergeFunctions.mergeArrays(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(e):i}n(GZ,"mergeArrays");function VZ(e,t,r){let i=t.mergeFunctions.mergeSets(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(e):i}n(VZ,"mergeSets");function ZZ(e,t,r){let i=t.mergeFunctions.mergeMaps(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(e):i}n(ZZ,"mergeMaps");function iy(e,t,r){let i=t.mergeFunctions.mergeOthers(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(e):i}n(iy,"mergeOthers");var KZ=!0,y4=void 0,bf=class bf extends gf{constructor(r={},i={devtools:!1},a={}){var s;super(r,i,bf.makeSettings(a));this.onLiveFrameCreated=n(async r=>{this.liveFrame=r,this.frameMsgBroker.register("live",this.liveFrame),this.setEvaluateWithChecksumTargetFrame(this.liveFrame),await this.injectedScriptManager.addTrackedFrame(this.liveFrame)},"onLiveFrameCreated");this.timeMachine=new Ln(this.frameMsgBroker,this.injectedScriptManager,{headless:((s=a==null?void 0:a.timeMachine)==null?void 0:s.headless)??!0})}static makeSettings(r={}){return v4({frontendTestGenerationConfig:{showFrontendLogs:xt.isDevMode,recordOptions:{...y4?{checkoutEveryNms:y4}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},r)}get liveMainFrame(){return this.liveFrame}get tmFrame(){return this.timeMachineFrame}getTimeMachine(){return this.timeMachine}async prepare(r={}){let i=await super.prepare(r);if(this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),await new vf(this.page).start(),this.timeMachineFrame=this.page.frames()[2],KZ){let a=await this.context.newPage();await this.onLiveFrameCreated(a.mainFrame())}else await this.interceptPageRequests(),await this.onLiveFrameCreated(this.page.frames()[1]);return await this.timeMachine.prepare(this.liveFrame,this.timeMachineFrame),await this.exposeFunctionsForVTG(),i}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async r=>{let i=this.liveFrame;if(!i){console.log("no live frame detected");return}try{return i.evaluate(a=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(a),r)}catch(a){console.error("Error getting frame window",a)}})}async navigate(r){return this.liveFrame.goto(r)}async getCurrentURL(){return this.liveFrame.url()}getInjectedScriptInitModules(r){return r===this.timeMachineFrame?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:r===this.liveFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(a){try{return await b4.promises.readFile(a,"utf8")}catch(s){return console.error(`Error reading file ${a}:`,s),null}}n(r,"readLocalFile");function i(a){switch(w4.extname(a).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}n(i,"getContentType"),await this.page.route("**/*",async a=>{try{let s=a.request().url();if(console.log("intercepted!",s),s.startsWith("file://")){let l=s.replace("file://",""),u=await r(l);u!==null?await a.fulfill({status:200,contentType:i(l),body:u}):await a.abort()}else{let l=0,u=5;for(;l<u;){let d=await a.fetch(),f=d.status();if(f>299&&f<400){l++;let h=d.headers().location;if(!h){console.warn("Redirect without Location header"),await a.abort();return}console.log(`Redirect ${l} to: ${h}`),a.request().url=()=>new URL(h,s).toString()}else{let h={};h["Access-Control-Allow-Origin"]="*",h["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",h["Access-Control-Allow-Headers"]="Content-Type, Authorization",await a.fulfill({response:d,headers:{...d.headers(),...h,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${u}) exceeded`),await a.abort()}}catch(s){console.warn("intercept error",s)}})}};n(bf,"ChecksumVTGWebDriver");var yf=bf;var _o=require("fs");var JZ=".settings.json",ny=class ny{constructor(t){this.checksumRoot=t;this._settings={autoLogin:!0,autoRunSteps:!0,autoGenerateAssertions:!0,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${JZ}`,this.initSettings()}getSettings(){return this._settings}updateSettings(t){this._settings=Object.assign(this._settings,t),this.writeSettingsData()}initSettings(){if(!(0,_o.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,_o.readFileSync)(this.settingsFilePath,"utf-8");this._settings=JSON.parse(t)}writeSettingsData(){(0,_o.writeFileSync)(this.settingsFilePath,JSON.stringify(this._settings,null,2))}};n(ny,"VtgSettingsService");var wf=ny;var oy=class oy extends hr{constructor(r,i=!1){super(r,i);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=n(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(r)}async run(){await this.init(),this.buildServices(),this.buildServer(),this.vtgMode==="edit"&&this.initEditModeServices(),this.vtgMode==="cloud"&&await this.initCloudModeServices(),await this.start()}async init(){await this.patchPlaywright(),this.loadChecksumData(),this.webDriver=this.buildWebDriver(),this.taskTimeMachine=new Ln(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!xt.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0}),this.pageInteractor=new Os(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.liveMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:console.log,logError:console.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0},new Ds(this.config)),this.testAssetsManager=new mf(this.projectRootDirectory,this.checksumRoot)}buildServices(){this.actionsManager=new ip,this.apiService=new Du(this.config),this.userStoryService=new rp(this.apiService,this.config),this.actionsService=new Mu(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver),this.assertionsService=new Ju(this.webDriver,this.actionsManager),this.locatorsService=new Yu(this.webDriver,this.apiService,this.userStoryService),this.aiTestGenerationService=new Lu(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new Zu(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new tp(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService),this.settingsService=new wf(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new df(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.actionsManager,this.storageService,this.settingsService)}initEditModeServices(){let r=this.storageService.getLocalSavedData(this.editLocationPath);this.setServicesData({actions:r.executedActions,story:r.story,testGenerationData:r.testGenerationData})}async initCloudModeServices(){let i=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),a=i.actionsDownloadSignedURL,s=await fetch(a,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);let u=(await s.json()).map((d,f)=>{var h;return{...d,id:(0,ay.randomUUID)(),assertions:(h=d.assertions)==null?void 0:h.map(g=>({...g,id:(0,ay.randomUUID)()}))}});this.setServicesData({actions:u,story:i.story,testGenerationData:i.testGenerationData})}setServicesData({actions:r,story:i,testGenerationData:a}){this.actionsManager.setActions(r),this.userStoryService.setStoryInfo(i,a),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=i.id}async start({createAssetsFolder:r=!0}={}){this.vtgMode==="start"&&await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:i}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:i.baseURL}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),await this.taskTimeMachine.prepare(this.webDriver.liveMainFrame),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let a=this.config.baseURL;this.webDriver.liveMainFrame?await this.webDriver.liveMainFrame.goto(a,{waitUntil:"domcontentloaded",timeout:0}):console.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction()),await this.webDriver.page.evaluate(({localSaveFolderPath:s,actions:l})=>{window.vtg.initClient(s,l)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions}),await new Promise(()=>{})}buildWebDriver(){return new yf({scriptSource:xt.checksumScript.source,scriptURL:xt.checksumScript.url,scriptFile:xt.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:this.config.baseURL,disableWebSecurity:!0,allowFileAccess:!0},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"}})}initVtgMode(r){let i=r.indexOf("--edit"),a=r.indexOf("--cloud");i!==-1&&(this.vtgMode="edit",this.editLocationPath=r.at(i+1)),a!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r.at(a+1)),this.vtgMode==="start"&&(this.storyId=r[0])}};n(oy,"VisualTestGenerator");var qc=oy;var sy=class sy{constructor(){}async execute(){let t=!!process.argv.find(i=>i==="--cksm-clidebug");t&&Xm(!0);let r=process.argv.slice(3);switch(process.argv.find(i=>i==="--help"||i==="-h")&&(await new js(r,t).run(process.argv[2]),process.exit(0)),process.argv[2]){case"init":new Ru(r,t).run();break;case"test":await new Iu(r,t).run();break;case"show-report":await new Fu(r,t).run();break;case"generate":try{await new qc(r,t).run()}catch(i){console.log("Error",i.message)}break;case"vtg":try{await new qc(r,t).run()}catch(i){console.log("Error",i.message)}break;default:await new js(r,t).run()}process.exit(0)}};n(sy,"CLIDispatcher");var Sf=sy;(async()=>await new Sf().execute())();
|
|
140
|
+
result:`,x),x!=null&&x.valid)return{...x,...s&&((f=g.variables)!=null&&f.length)?{selectorWithVars:g.selector,locatorWithVars:x.locatorWithVars}:{},alternateSelectors:h.filter(w=>w!==g).map(w=>w.selector)}}return}catch(h){this.logger.log("Error generating selector with LLM filtering",h.message);return}}async generateCompoundSelector(t,r){try{this.logger.log("*** Will generate compound selector");let i=await this.selectorGeneratorApi.extractCompoundSelectionData(t);return this.processContextElements(i,r)}catch(i){this.logger.log("Error generating compound selector",i);return}}async processContextElements(t,r){let i=await this.evaluateWithChecksum(async({contextElementsMetadata:s,isPartOfListItem:l})=>window.checksum.testGenerator.getCompoundSelector().filter(s,{isPartOfListItem:l}).map(({element:u,...d})=>d),{contextElementsMetadata:t,isPartOfListItem:r});if(console.log(`Filtered context elements: ${i.length}`),i.length<2){this.logger.log("<!> No context elements found besides target, skipping");return}let a;try{if(a=await this.evaluateWithChecksum(async({contextElements:s,isPartOfListItem:l})=>window.checksum.testGenerator.getCompoundSelector().generate(s,{isPartOfListItem:l}),{contextElements:i,isPartOfListItem:r}),!a){this.logger.log("Error generating compound selector metadata for context elements");return}this.logger.log(`Generated compound selector metadata for ${i.length} context elements (including target)`)}catch(s){this.logger.log("Error generating compound selector metadata for context elements",s.message)}try{this.logger.log("** Generating selectors for context elements");let s=[];await Promise.all(i.map(async d=>{if(d.selection.type==="content"){s.push({...d,selector:`internal:text="${d.selection.value}"`,locator:`getByText("${d.selection.value}")`});return}let f=await this.generateWithLLMFiltering(d.selection.checksumid,await this.generateLocatorsForElement(d.selection.checksumid,{isForContextElement:!0,useCSSExtraction:!1,isPartOfListItem:!1}),null,{useImage:!1,isForContextElement:!0});if(!f)throw new Error("Failed to generate selector for context element");s.push({...d,...f})}));let{targetSelection:l}=a,u=l.playwrightSelectors.length>0?l.playwrightSelectors[0]:{selector:l.cssSelectors[0]};if(!u.selector)throw new Error("Failed to get target relative selector");return this.logger.log("Generated customer facing compound selector - ",[...s.map(d=>d.selector),"target: "+u.selector]),{elements:s,targetRelativeSelector:u,metadata:a}}catch(s){this.logger.log("Error generating customer facing compound selector metadata for context elements",s)}}async testSelector(t,r,{testUniqueness:i=!0,useVariables:a=!0}={}){var s;try{return a=a&&!!((s=t.variables)!=null&&s.length),await this.evaluateWithChecksum(async({checksumId:u,selector:d,testVariables:f,testUniqueness:h})=>{try{return window.checksum.testGenerator.testElementSelector(d,u,f,h)}catch(g){console.log("Error testing selector",g)}},{checksumId:r,selector:a?this.implantVariablesValues(t):t.selector,testVariables:a?{selectorWithVars:t.selector,variablesCode:this.variables.code}:void 0,testUniqueness:i})}catch(l){return console.error("Error testing selector",l),{valid:!1}}}implantVariablesValues(t){var i;return(i=t.variables)!=null&&i.length?Object.entries(this.variables.keyValue).map(([a,s])=>[Zq+a,s]).filter(([a])=>t.variables.map(s=>s.name).includes(a)).reduce((a,[s,l])=>a.replace("${"+s+"}",l),t.selector):t.selector}async getParentChainHTML(t){try{return this.parentChainHTML||(this.parentChainHTML={}),this.parentChainHTML[t]||(this.parentChainHTML[t]=await this.evaluateWithChecksum(async({checksumId:r})=>window.checksum.testGenerator.getParentChainHTML(r),{checksumId:t})),this.parentChainHTML[t]}catch(r){throw this.logger.log("Error getting parent chain HTML",r),r}}async getExtractCSSKeyElements(t){try{let r=await this.getParentChainHTML(t);return this.selectorGeneratorApi.extractCSSKeyElements(r)}catch(r){return this.logger.log("Error generating prompt for CSS key elements",r),[]}}async generateLocatorsForElement(t,r={isPartOfListItem:!1,isForContextElement:!1,useCSSExtraction:!0}){try{console.log("Generating custom locators");let i=r.useCSSExtraction?await this.getExtractCSSKeyElements(t):[],a=await this.evaluateWithChecksum(async({checksumId:s,keyFeatures:l,...u})=>window.checksum.testGenerator.buildCustomPlaywrightSelectors(s,l,u),{checksumId:t,keyFeatures:i,...r});return this.logger.log("Generated locators for filtering (first is playwright's)",a),a}catch(i){throw this.logger.log("Error generating prompt for selectors",i),i}}};n(Ng,"SelectorGenerator");var Xu=Ng;var _VtgLocatorsService=class _VtgLocatorsService{constructor(e,t,r){this.webDriver=e;this.apiService=t;this.userStoryService=r}getStory(){return this.userStoryService.getStory()}async verifyLocatorOrSelector({type,value}){try{let elementLocator;switch(type){case"locator":try{elementLocator=eval(jb(value,'this.webDriver.tmFrame.frameLocator("iframe")'))}catch(e){throw new Error(e.message)}break;case"selector":elementLocator=this.webDriver.tmFrame.frameLocator("iframe").locator(value);break}if(!elementLocator)throw new Error(`Element for ${type} ${value} not found`);let selectorCount;try{selectorCount=await elementLocator.count()}catch(e){throw new Error("Could not evaluate element")}if(selectorCount===2){for(let e=0;e<2;e++)if(await elementLocator.nth(e).evaluate(r=>r.matches(".element-inspector-ignore")))return{success:!0}}if(selectorCount!==1)throw new Error(selectorCount===0?"No element found":`Strict mode: ${selectorCount} elements found`);return{success:!0}}catch(e){return{success:!1,message:String(e)}}}async generateCSSExtractionForLocator(e,t){let r={...this.getSelectorGeneratorBasePromptAssets(e),parentChainHTML:t};return new Vs(r,this.apiService).extractCSSKeyElements()}async runLLMFilteringForLocator(e,t,r,i){let a={...this.getSelectorGeneratorBasePromptAssets(e),parentChainHTML:t,generatedLocators:r,image:i};return new Xu(new Vs(a,this.apiService),null,this.webDriver.evaluateWithChecksum.bind(this.webDriver)).generateWithLLMFiltering(e.id,r,t,{useImage:!!i,useVariables:!1,isPartOfListItem:!1,isForContextElement:!1})}getSelectorGeneratorBasePromptAssets(e){try{let{goal:t,instructions:r}=this.getStory();return{title:t,steps:r,thought:e.description}}catch(t){return console.log("Failed getting base prompt assets",t),{title:"",steps:"",thought:e.description}}}};n(_VtgLocatorsService,"VtgLocatorsService");var Yu=_VtgLocatorsService;var J_=require("request"),ep=require("fs");var jg=class jg{constructor(t,r,i,a,s,l=console.log){this.apiBaseURL=t;this.apiKey=r;this.uploadTimeout=i;this.makeGetUploadUrlAPIPath=a;this.onOutstandingUpload=s;this.log=l}async uploadAsset(t){try{let{path:r}=t.info;if(this.log("Uploading file",r),await this.getSignedURLForUpload(t),!t.uploadURL){this.log("Error getting signed URL for asset",r),t.error=!0;return}let a=(0,ep.statSync)(r).size,s=(0,ep.createReadStream)(r),l=mt(new Promise((u,d)=>{var h;let f=(0,J_.put)(t.uploadURL,{body:s,headers:{"Content-Type":o_[t.info.type]??""}},(g,x)=>{g&&d(g),u(x)});(h=this.onOutstandingUpload)==null||h.call(this,{request:f,size:a})}),this.uploadTimeout);l.then(u=>{if(u.statusCode!==200)throw new Error("Upload failed");this.log("File uploaded successfully",r),t.complete=!0}).catch(u=>{this.log("Error uploading asset",r,u),t.error=!0}),t.response=l}catch{t.error=!0}}async getSignedURLForUpload(t){try{let r=t.info,i=await fetch(`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(t)}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(r)}),{url:a}=await i.json();t.uploadURL=a}catch(r){return this.log("Error getting signed URL for artifact",r),null}}};n(jg,"TestAssetUploader");var Qu=jg;var X_=At(Bm()),Bn=require("path"),Xi=require("fs");async function Y_(e,t){let r=await(0,Xi.readdirSync)(t);await Promise.all(r.map(async i=>{let a=(0,Bn.join)(t,i);if((await(0,Xi.statSync)(a)).isDirectory()){let l=e.folder(i);await Y_(l,a)}else{let l=await(0,Xi.readFileSync)(a);e.file(i,l)}}))}n(Y_,"addFolderToZip");async function Q_(e){try{let t=await(0,X_.loadAsync)("UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==",{base64:!0});await Y_(t,e);let r=await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"}),i=(0,Bn.join)((0,Bn.dirname)(e),`${(0,Bn.basename)(e)}.zip`);return(0,Xi.writeFileSync)(i,r),i}catch(t){return console.error("Error creating zip:",t),null}}n(Q_,"zipFolder");var qn=require("fs");var Ug=class Ug{constructor(t,r,i,a,s,l){this.config=t;this.userStoryService=r;this.apiService=i;this.actionsManager=a;this.testAssetsManager=s;this.actionsService=l}getLocalSavedData(t){try{let r=(0,qn.readFileSync)(`${this.testAssetsManager.getLocalSavePath()}/${t}/test.json`,"utf-8");return JSON.parse(r)}catch(r){return console.error(`Error reading or parsing JSON file: ${r}`),null}}async localSave(){let t={executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:this.config.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()};(0,qn.writeFileSync)(`${this.testAssetsManager.getAssetsFolderPath()}/test.json`,JSON.stringify(t,null,2)),(0,qn.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,JSON.stringify(t,null,2))}async localBackup(t){k_(this.testAssetsManager.getLocalAutoSavePath(),this.testAssetsManager.getLocalSaveAsPath(t))}getIsFolderAlreadyExistsInDrafts(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,qn.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){console.log("No test generation data, can't upload");return}let t=await this.userStoryService.createTestGeneration(),r=new Qu(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${t}/get-upload-url`),i=n(u=>({complete:!1,error:!1,response:void 0,info:u}),"buildUploadAsset"),a=i({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),s=i({type:"har",path:await Q_(this.testAssetsManager.getHarFolderPath())});await Promise.all([r.uploadAsset(a),r.uploadAsset(s)]);let l=this.actionsManager.actions.map(u=>({...u,parentFramesSelectors:u.parentFramesSelectors?u.parentFramesSelectors.filter(d=>d!=="iframe"):void 0}));await this.apiService.post(`test-generation/${t}/completed`,{actions:l})}catch(t){console.error("Failed to upload test",t)}}};n(Ug,"VtgStorageService");var tp=Ug;var Kq={goal:"Send email via outreach list",instructions:"Make sure to select a user from the list first",environment:{name:void 0,userRole:void 0}},zg=class zg{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var t;return!!((t=this.userStoryTestGeneration)!=null&&t.internalTestId)}setStoryInfo(t,r){this.story=t,this.userStoryTestGeneration=r}async fetchStory(t){if(xt.vtg.useFakeStory){console.log("Using fake flow data"),this.story=Kq;return}if(!t)throw new Error("no story id provided");let i=await(await this.apiService.post(`test-generation/info/${t}`)).json();if(!(i!=null&&i.id))throw new Error(`Story ${t} not found`);console.log("Received flow data:",i);let{id:a,title:s,steps:l,startUrl:u,userRole:d,environment:f,internalTestId:h,generationBatchId:g}=i;this.userStoryTestGeneration={internalTestId:h,generationBatchId:g},this.story={id:a,goal:s,instructions:l,url:u,environment:{userRole:d,name:f}}}getEnvInfo(){return Qm(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration.testGenerationId=r,r}};n(zg,"VtgUserStoryService");var rp=zg;var Wg=class Wg{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}addOrUpdateAssertionByActionId(t,r){this.executedActions=this._executedActions.map(i=>{var a;return i.id===t?(a=i.assertions)!=null&&a.find(({id:l})=>l===r.id)?{...i,assertions:i.assertions.map(l=>l.id===r.id?Object.assign(l,r):l)}:{...i,assertions:[...i.assertions??[],r]}:i})}setStorageService(t){this.storageService=t}pushExecutedActionOrAddAfterParent(t,r={}){if(r.parentAction){let i=this._executedActions.findIndex(({id:a})=>a===r.parentAction.id);if(i!==-1){let a={...t,timestamp:this._executedActions[i].timestamp+1};this._executedActions=[...this._executedActions.slice(0,i+1),a,...this._executedActions.slice(i+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:i})=>i===t.id);r!==-1&&(this.executedActions=[...this._executedActions.slice(0,r),{...this._executedActions[r],...t},...this._executedActions.slice(r+1)])}deleteStep(t,r){r?this.executedActions=this._executedActions.map(i=>{if(i.id===t){let a=i.assertions.filter(({id:s})=>s!==r);return Object.assign(i,{assertions:a})}return i}):this.executedActions=this._executedActions.filter(({id:i})=>i!==t)}};n(Wg,"VtgActionsManager");var ip=Wg;var Xx=At(n4()),u4=At(require("net")),p4=At(ix()),f4=At(l4());var Yx=class Yx{constructor(t,r,i,a,s,l,u,d){this.actionsService=t;this.assertionsService=r;this.locatorsService=i;this.aiTestGenerationService=a;this.aiAssertionsService=s;this.actionsManager=l;this.storageService=u;this.settingsService=d}async start(){return this.app=(0,Xx.default)(),this.app.use((0,f4.default)()),this.app.use(p4.default.json({limit:"50mb"})),this.app.use(Xx.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),this.setupEndpoints(),new Promise(t=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),t()})})}setupEndpoints(){this.app.get("/api",async(t,r)=>{r.send("success")}),this.app.post("/api/test/upload",async(t,r)=>(await this.storageService.saveToCloud(),r.send("success"))),this.app.post("/api/test/local-save",async(t,r)=>{await this.storageService.localSave(),r.send("success")}),this.app.post("/api/test/verify-save-location",async(t,r)=>{try{let i=this.storageService.getIsFolderAlreadyExistsInDrafts(t.body.location);r.send({exists:i})}catch(i){r.status(400).send({error:i})}}),this.app.post("/api/test/backup",async(t,r)=>{t.body.backupFolderName&&!__(t.body.backupFolderName)?r.status(400).send({error:"Invalid folder name"}):(await this.storageService.localBackup(t.body.backupFolderName),r.send("success"))}),this.app.post("/api/ai/init",async(t,r)=>{await this.aiTestGenerationService.init(),r.send("success")}),this.app.post("/api/ai/iterate",async(t,r)=>{let i=t.body,a=await this.aiTestGenerationService.iterate(i);return a?r.status(200).json(a):r.status(400).send("no action generated")}),this.app.post("/api/ai/generate-assertions",async(t,r)=>{let i=t.body;this.aiAssertionsService.generateAiAssertions(i),r.status(200).send({success:!0})}),this.app.post("/api/ai/stop-generate-assertions",async(t,r)=>{let i=t.body;return await this.aiAssertionsService.stopGenerateAiAssertions(i),r.status(200).send("success")}),this.app.post("/ai/stop",async(t,r)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/selector/play",async(t,r)=>{let i=t.body;try{let a=await this.locatorsService.verifyLocatorOrSelector(i);return r.status(200).send(a)}catch(a){return r.status(400).send({error:a.message})}}),this.app.post("/api/assertion/verify/time-machine",async(t,r)=>{let i=t.body,a=await this.assertionsService.verifyOnTimeMachine(i);return r.status(200).send(a)}),this.app.post("/api/assertion/verify/live",async(t,r)=>{let i=t.body,a=await this.assertionsService.verifyOnLive(i),s=a.success?200:404;return r.status(s).send(a)}),this.app.post("/api/assertion/save",async(t,r)=>{let i=t.body;try{let a=await this.assertionsService.saveOrUpdateAssertionForAction(i);r.status(200).json(a)}catch(a){r.status(400).send({error:a.message})}}),this.app.post("/api/locators/generate/css",async(t,r)=>{let{action:i,parentChainHTML:a}=t.body;try{let s=await this.locatorsService.generateCSSExtractionForLocator(i,a);r.status(200).json(s)}catch(s){r.status(400).send({error:s.message})}}),this.app.post("/api/locators/filter",async(t,r)=>{let{action:i,parentChainHTML:a,generatedLocators:s,image:l}=t.body;try{let u=await this.locatorsService.runLLMFilteringForLocator(i,a,s,l);r.status(200).json(u)}catch(u){r.status(400).send({error:u.message})}}),this.app.post("/api/steps/execute",async(t,r)=>{let i=t.body,a=i.isAISuggestion?this.aiTestGenerationService.executeAction:this.actionsService.executeAction;try{let s=await a(i.action,i.options);return r.status(200).json(s)}catch(s){return r.status(404).send({error:s.message})}}),this.app.post("/api/upload-files",async(t,r)=>{try{await this.actionsService.uploadFiles(t.body.files)}catch(i){return r.status(500).send(i)}return r.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(t,r)=>{let i=t.body;return this.actionsManager.addManualActionsToExecuted(i.action),r.send("success")}),this.app.patch("/api/steps",async(t,r)=>{let i=t.body;return this.actionsManager.updateExecutedAction({...i.update,id:i.id}),r.send("success")}),this.app.put("/api/steps",async(t,r)=>{let i=t.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(i.action,i.options)}catch(a){return r.status(500).send(a)}return r.send("success")}),this.app.delete("/api/step",async(t,r)=>{let{assertionId:i,actionId:a}=t.body;try{this.actionsManager.deleteStep(a,i)}catch(s){return r.status(500).send(s)}return r.status(200).send({message:"Success!"})}),this.app.get("/api/settings",async(t,r)=>{let i=this.settingsService.getSettings();return r.status(200).send(i)}),this.app.post("/api/settings",async(t,r)=>(this.settingsService.updateSettings(t.body),r.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((t,r)=>{let i=u4.default.createServer();i.unref(),i.on("error",r),i.listen(0,()=>{let a=i.address().port;i.close(()=>{t(a)})})})}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}};n(Yx,"VtgExpressServer");var df=Yx;var hf=require("fs");var Qx=class Qx{constructor(t,r){this.projectRootDirectory=t;this.checksumRoot=r;this.localSaveFolderPath=`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,hf.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,hf.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(t){this.autoSaveFolderPath=`/auto-save/${t}`,(0,hf.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return this.localSaveFolderPath+this.autoSaveFolderPath}getLocalSaveAsPath(t){return t&&(this.currentSaveAsLocation=t),this.currentSaveAsLocation||(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};n(Qx,"VtgTestAssetsManager");var mf=Qx;var RZ={useCDPSession:!0,trackLoadedResources:!0},ey=class ey extends $u{constructor(r={},i={devtools:!1},a={}){super({...RZ,...r},i);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=n(async(r,i=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:i}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=n(async r=>{try{return await r.waitForFunction(()=>{var i;return!!((i=window.checksum)!=null&&i.testGenerator)}),r.evaluate(async({appSpecificRules:i,config:a,initModules:s})=>{window.checksum.testGenerator.init(i,a,s),i.hasGoals&&await window.checksum.goalTracker.init()},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(i){console.log("initInjectedScript exception",i)}},"initInjectedScript");this.settings={...this.settings,...a},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let i=await super.prepare(r);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),i}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,i,a=this.evaluateWithChecksumTargetFrame){let s=this.injectedScriptManager.getNavigationPromise(a);s&&await s;try{return a.evaluate(r,i)}catch(l){throw console.error("evaluateWithChecksum error",l,r.toString()),l}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async i=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(i),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(i=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(i),r)}async postRRwebEvents(r){return this.evaluateWithChecksum(i=>window.checksum.testGenerator.postRRwebEvents(i),r)}async getRRwebEvents(r=0){return this.evaluateWithChecksum(async({index:i})=>window.checksum.testGenerator.getRRwebEvents(i),{index:r})}async getGoals(){return await this.evaluateWithChecksum(async()=>window.checksum.goalTracker.getGoals())}async takeElementSnapshot(r,i,a={},s={}){try{let{snapshot:l,elementLocator:u}=await super.takeElementSnapshot(r,i,a);if(!l||!a.takeBodyScreenshot)return l?{snapshot:l}:{};await this.highlightElementByLocator(u,a.mousePosition);let d=await this.takePageSnapshot(s);return await this.clearHighlights(),{snapshot:l,bodySnapshot:d}}catch(l){return console.error("[ChecksumWebDriver] takeElementSnapshot error",l),{}}}async highlightElementByLocator(r,i,a="20px solid rgba(255,0,0,1)"){return this.evaluateWithChecksum(async([s,l,u])=>{window.checksum.testGenerator.highlightElement(s,{highlightStyle:{outline:l},mousePosition:u})},[await r.elementHandle(),a,i])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};n(ey,"ChecksumWebDriver");var gf=ey;var b4=require("fs"),w4=At(require("path"));var ty=require("fs");var ry=class ry{constructor(t,r=xt.vtg.localBuildPath){this.page=t;this.filePath=r;this.filePath=r}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await Ce(2e3)}catch(t){console.error("An error occurred:",t)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t=xt.vtg.appURL;await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(!xt.isDevMode)try{let t=await ty.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,i=t.replace(r,"$1=$2.$3static");await ty.promises.writeFile(this.filePath,i,"utf8"),console.log(`Successfully modified ${this.filePath}`)}catch(t){console.error(`Error processing file ${this.filePath}:`,t)}}};n(ry,"VtgFrontendLauncher");var vf=ry;var cn={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Mce={defaultMerge:cn.defaultMerge};function MZ(e,t){return t}n(MZ,"defaultMetaDataUpdater");function OZ(e,t){return e.filter(r=>r!==void 0)}n(OZ,"defaultFilterValues");var d4;(function(e){e[e.NOT=0]="NOT",e[e.RECORD=1]="RECORD",e[e.ARRAY=2]="ARRAY",e[e.SET=3]="SET",e[e.MAP=4]="MAP",e[e.OTHER=5]="OTHER"})(d4||(d4={}));function h4(e){return typeof e!="object"||e===null?0:Array.isArray(e)?2:BZ(e)?1:e instanceof Set?3:e instanceof Map?4:5}n(h4,"getObjectType");function LZ(e){let t=new Set;for(let r of e)for(let i of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(i);return t}n(LZ,"getKeys");function DZ(e,t){return typeof e=="object"&&Object.prototype.propertyIsEnumerable.call(e,t)}n(DZ,"objectHasProperty");function g4(e){var i;let t=0,r=(i=e[0])==null?void 0:i[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var a;do{if(r===void 0)return{done:!0,value:void 0};let s=r.next();if(s.done===!0){t+=1,r=(a=e[t])==null?void 0:a[Symbol.iterator]();continue}return{done:!1,value:s.value}}while(!0)}}}}}n(g4,"getIterableOfIterables");var m4=["[object Object]","[object Module]"];function BZ(e){if(!m4.includes(Object.prototype.toString.call(e)))return!1;let{constructor:t}=e;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!m4.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}n(BZ,"isRecord");function qZ(e,t,r){let i={};for(let a of LZ(e)){let s=[];for(let d of e)DZ(d,a)&&s.push(d[a]);if(s.length===0)continue;let l=t.metaDataUpdater(r,{key:a,parents:e}),u=x4(s,t,l);u!==cn.skip&&(a==="__proto__"?Object.defineProperty(i,a,{value:u,configurable:!0,enumerable:!0,writable:!0}):i[a]=u)}return i}n(qZ,"mergeRecords$1");function NZ(e){return e.flat()}n(NZ,"mergeArrays$1");function jZ(e){return new Set(g4(e))}n(jZ,"mergeSets$1");function UZ(e){return new Map(g4(e))}n(UZ,"mergeMaps$1");function zZ(e){return e.at(-1)}n(zZ,"mergeOthers$1");var xf={mergeRecords:qZ,mergeArrays:NZ,mergeSets:jZ,mergeMaps:UZ,mergeOthers:zZ};function v4(...e){return WZ({})(...e)}n(v4,"deepmerge");function WZ(e,t){let r=HZ(e,i);function i(...a){return x4(a,r,t)}return n(i,"customizedDeepmerge"),i}n(WZ,"deepmergeCustom");function HZ(e,t){return{defaultMergeFunctions:xf,mergeFunctions:{...xf,...Object.fromEntries(Object.entries(e).filter(([r,i])=>Object.hasOwn(xf,r)).map(([r,i])=>i===!1?[r,xf.mergeOthers]:[r,i]))},metaDataUpdater:e.metaDataUpdater??MZ,deepmerge:t,useImplicitDefaultMerging:e.enableImplicitDefaultMerging??!1,filterValues:e.filterValues===!1?void 0:e.filterValues??OZ,actions:cn}}n(HZ,"getUtils");function x4(e,t,r){var s;let i=((s=t.filterValues)==null?void 0:s.call(t,e,r))??e;if(i.length===0)return;if(i.length===1)return iy(i,t,r);let a=h4(i[0]);if(a!==0&&a!==5){for(let l=1;l<i.length;l++)if(h4(i[l])!==a)return iy(i,t,r)}switch(a){case 1:return $Z(i,t,r);case 2:return GZ(i,t,r);case 3:return VZ(i,t,r);case 4:return ZZ(i,t,r);default:return iy(i,t,r)}}n(x4,"mergeUnknowns");function $Z(e,t,r){let i=t.mergeFunctions.mergeRecords(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(e,t,r):i}n($Z,"mergeRecords");function GZ(e,t,r){let i=t.mergeFunctions.mergeArrays(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(e):i}n(GZ,"mergeArrays");function VZ(e,t,r){let i=t.mergeFunctions.mergeSets(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(e):i}n(VZ,"mergeSets");function ZZ(e,t,r){let i=t.mergeFunctions.mergeMaps(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(e):i}n(ZZ,"mergeMaps");function iy(e,t,r){let i=t.mergeFunctions.mergeOthers(e,t,r);return i===cn.defaultMerge||t.useImplicitDefaultMerging&&i===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(e):i}n(iy,"mergeOthers");var KZ=!0,y4=5e3,bf=class bf extends gf{constructor(r={},i={devtools:!1},a={}){var s;super(r,i,bf.makeSettings(a));this.onLiveFrameCreated=n(async r=>{this.liveFrame=r,this.frameMsgBroker.register("live",this.liveFrame),this.setEvaluateWithChecksumTargetFrame(this.liveFrame),await this.injectedScriptManager.addTrackedFrame(this.liveFrame)},"onLiveFrameCreated");this.timeMachine=new Ln(this.frameMsgBroker,this.injectedScriptManager,{headless:((s=a==null?void 0:a.timeMachine)==null?void 0:s.headless)??!0})}static makeSettings(r={}){return v4({frontendTestGenerationConfig:{showFrontendLogs:xt.isDevMode,recordOptions:{...y4?{checkoutEveryNms:y4}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},r)}get liveMainFrame(){return this.liveFrame}get tmFrame(){return this.timeMachineFrame}getTimeMachine(){return this.timeMachine}async prepare(r={}){let i=await super.prepare(r);if(this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),await new vf(this.page).start(),this.timeMachineFrame=this.page.frames()[2],KZ){let a=await this.context.newPage();await this.onLiveFrameCreated(a.mainFrame())}else await this.interceptPageRequests(),await this.onLiveFrameCreated(this.page.frames()[1]);return await this.timeMachine.prepare(this.liveFrame,this.timeMachineFrame),await this.exposeFunctionsForVTG(),i}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async r=>{let i=this.liveFrame;if(!i){console.log("no live frame detected");return}try{return i.evaluate(a=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(a),r)}catch(a){console.error("Error getting frame window",a)}})}async navigate(r){return this.liveFrame.goto(r)}async getCurrentURL(){return this.liveFrame.url()}getInjectedScriptInitModules(r){return r===this.timeMachineFrame?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:r===this.liveFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(a){try{return await b4.promises.readFile(a,"utf8")}catch(s){return console.error(`Error reading file ${a}:`,s),null}}n(r,"readLocalFile");function i(a){switch(w4.extname(a).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}n(i,"getContentType"),await this.page.route("**/*",async a=>{try{let s=a.request().url();if(console.log("intercepted!",s),s.startsWith("file://")){let l=s.replace("file://",""),u=await r(l);u!==null?await a.fulfill({status:200,contentType:i(l),body:u}):await a.abort()}else{let l=0,u=5;for(;l<u;){let d=await a.fetch(),f=d.status();if(f>299&&f<400){l++;let h=d.headers().location;if(!h){console.warn("Redirect without Location header"),await a.abort();return}console.log(`Redirect ${l} to: ${h}`),a.request().url=()=>new URL(h,s).toString()}else{let h={};h["Access-Control-Allow-Origin"]="*",h["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",h["Access-Control-Allow-Headers"]="Content-Type, Authorization",await a.fulfill({response:d,headers:{...d.headers(),...h,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${u}) exceeded`),await a.abort()}}catch(s){console.warn("intercept error",s)}})}};n(bf,"ChecksumVTGWebDriver");var yf=bf;var _o=require("fs");var JZ=".settings.json",ny=class ny{constructor(t){this.checksumRoot=t;this._settings={autoLogin:!0,autoRunSteps:!0,autoGenerateAssertions:!0,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${JZ}`,this.initSettings()}getSettings(){return this._settings}updateSettings(t){this._settings=Object.assign(this._settings,t),this.writeSettingsData()}initSettings(){if(!(0,_o.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,_o.readFileSync)(this.settingsFilePath,"utf-8");this._settings=JSON.parse(t)}writeSettingsData(){(0,_o.writeFileSync)(this.settingsFilePath,JSON.stringify(this._settings,null,2))}};n(ny,"VtgSettingsService");var wf=ny;var oy=class oy extends hr{constructor(r,i=!1){super(r,i);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=n(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(r)}async run(){await this.init(),this.buildServices(),this.buildServer(),this.vtgMode==="edit"&&this.initEditModeServices(),this.vtgMode==="cloud"&&await this.initCloudModeServices(),await this.start()}async init(){await this.patchPlaywright(),this.loadChecksumData(),this.webDriver=this.buildWebDriver(),this.taskTimeMachine=new Ln(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!xt.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0}),this.pageInteractor=new Os(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.liveMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:console.log,logError:console.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0},new Ds(this.config)),this.testAssetsManager=new mf(this.projectRootDirectory,this.checksumRoot)}buildServices(){this.actionsManager=new ip,this.apiService=new Du(this.config),this.userStoryService=new rp(this.apiService,this.config),this.actionsService=new Mu(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver),this.assertionsService=new Ju(this.webDriver,this.actionsManager),this.locatorsService=new Yu(this.webDriver,this.apiService,this.userStoryService),this.aiTestGenerationService=new Lu(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new Zu(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new tp(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService),this.settingsService=new wf(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new df(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.actionsManager,this.storageService,this.settingsService)}initEditModeServices(){let r=this.storageService.getLocalSavedData(this.editLocationPath);this.setServicesData({actions:r.executedActions,story:r.story,testGenerationData:r.testGenerationData})}async initCloudModeServices(){let i=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),a=i.actionsDownloadSignedURL,s=await fetch(a,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`HTTP error! Status: ${s.status}`);let u=(await s.json()).map((d,f)=>{var h;return{...d,id:(0,ay.randomUUID)(),assertions:(h=d.assertions)==null?void 0:h.map(g=>({...g,id:(0,ay.randomUUID)()}))}});this.setServicesData({actions:u,story:i.story,testGenerationData:i.testGenerationData})}setServicesData({actions:r,story:i,testGenerationData:a}){this.actionsManager.setActions(r),this.userStoryService.setStoryInfo(i,a),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=i.id}async start({createAssetsFolder:r=!0}={}){this.vtgMode==="start"&&await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:i}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:i.baseURL}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),await this.taskTimeMachine.prepare(this.webDriver.liveMainFrame),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let a=this.config.baseURL;this.webDriver.liveMainFrame?await this.webDriver.liveMainFrame.goto(a,{waitUntil:"domcontentloaded",timeout:0}):console.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction()),await this.webDriver.page.evaluate(({localSaveFolderPath:s,actions:l})=>{window.vtg.initClient(s,l)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions}),await new Promise(()=>{})}buildWebDriver(){return new yf({scriptSource:xt.checksumScript.source,scriptURL:xt.checksumScript.url,scriptFile:xt.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:this.config.baseURL,disableWebSecurity:!0,allowFileAccess:!0},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"}})}initVtgMode(r){let i=r.indexOf("--edit"),a=r.indexOf("--cloud");i!==-1&&(this.vtgMode="edit",this.editLocationPath=r.at(i+1)),a!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r.at(a+1)),this.vtgMode==="start"&&(this.storyId=r[0])}};n(oy,"VisualTestGenerator");var qc=oy;var sy=class sy{constructor(){}async execute(){let t=!!process.argv.find(i=>i==="--cksm-clidebug");t&&Xm(!0);let r=process.argv.slice(3);switch(process.argv.find(i=>i==="--help"||i==="-h")&&(await new js(r,t).run(process.argv[2]),process.exit(0)),process.argv[2]){case"init":new Ru(r,t).run();break;case"test":await new Iu(r,t).run();break;case"show-report":await new Fu(r,t).run();break;case"generate":try{await new qc(r,t).run()}catch(i){console.log("Error",i.message)}break;case"vtg":try{await new qc(r,t).run()}catch(i){console.log("Error",i.message)}break;default:await new js(r,t).run()}process.exit(0)}};n(sy,"CLIDispatcher");var Sf=sy;(async()=>await new Sf().execute())();
|
|
141
141
|
/*! Bundled license information:
|
|
142
142
|
|
|
143
143
|
lodash/lodash.js:
|