prompttest-mobile 1.5.1
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/CONTRIBUTING.md +80 -0
- package/LICENSE +42 -0
- package/LICENSES.md +81 -0
- package/README.md +526 -0
- package/SECURITY.md +56 -0
- package/TERMS.md +138 -0
- package/dist/bin/prompttest.d.ts +2 -0
- package/dist/bin/prompttest.js +1418 -0
- package/dist/bin/server.d.ts +1 -0
- package/dist/constants/commands.d.ts +125 -0
- package/dist/engine.bundle.js +1039 -0
- package/dist/index.d.ts +143 -0
- package/dist/index.js +1039 -0
- package/dist/lib/adaptive-timing.d.ts +55 -0
- package/dist/lib/adb-provisioner.d.ts +55 -0
- package/dist/lib/adb.d.ts +448 -0
- package/dist/lib/ai/heuristic-resolver.d.ts +19 -0
- package/dist/lib/ai/index.d.ts +16 -0
- package/dist/lib/ai/llm-provider.d.ts +40 -0
- package/dist/lib/ai/types.d.ts +64 -0
- package/dist/lib/baseline.d.ts +159 -0
- package/dist/lib/benchmark.d.ts +100 -0
- package/dist/lib/checkpoint.d.ts +61 -0
- package/dist/lib/ci.d.ts +49 -0
- package/dist/lib/config-loader.d.ts +87 -0
- package/dist/lib/config.d.ts +136 -0
- package/dist/lib/crawler.d.ts +335 -0
- package/dist/lib/data-loader.d.ts +53 -0
- package/dist/lib/dfs-engine.d.ts +149 -0
- package/dist/lib/dictionary.d.ts +41 -0
- package/dist/lib/doctor.d.ts +45 -0
- package/dist/lib/driver-interface.d.ts +50 -0
- package/dist/lib/enterprise.d.ts +71 -0
- package/dist/lib/errors.d.ts +68 -0
- package/dist/lib/explorer.d.ts +165 -0
- package/dist/lib/feedback.d.ts +35 -0
- package/dist/lib/form-filler.d.ts +101 -0
- package/dist/lib/ios-driver.d.ts +38 -0
- package/dist/lib/jail-guard.d.ts +59 -0
- package/dist/lib/license.d.ts +51 -0
- package/dist/lib/live-server.d.ts +52 -0
- package/dist/lib/lock.d.ts +30 -0
- package/dist/lib/logger.d.ts +68 -0
- package/dist/lib/memory.d.ts +259 -0
- package/dist/lib/patterns.d.ts +202 -0
- package/dist/lib/profiler.d.ts +75 -0
- package/dist/lib/prompt-runner.d.ts +101 -0
- package/dist/lib/quiescence.d.ts +44 -0
- package/dist/lib/recorder.d.ts +155 -0
- package/dist/lib/repl.d.ts +29 -0
- package/dist/lib/reporter.d.ts +269 -0
- package/dist/lib/runner-utils.d.ts +316 -0
- package/dist/lib/scaffold.d.ts +53 -0
- package/dist/lib/step-handlers.d.ts +390 -0
- package/dist/lib/triage.d.ts +50 -0
- package/dist/lib/wizard.d.ts +42 -0
- package/dist/lib/zip-util.d.ts +36 -0
- package/docs/ARCHITECTURE.md +154 -0
- package/docs/CLI_CONTRACT.md +131 -0
- package/docs/CLI_STUDIO_CONTRACT.md +123 -0
- package/docs/PERFORMANCE_BASELINE.md +71 -0
- package/docs/PRODUCT_STATUS.md +56 -0
- package/docs/USER_MANUAL.md +764 -0
- package/package.json +66 -0
|
@@ -0,0 +1,1039 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PromptTest - Ultra-fast Autonomous Mobile Testing & Visual QA Brain
|
|
3
|
+
* Copyright (c) 2026 Shriram Singh. All rights reserved.
|
|
4
|
+
* Licensed under the Business Source License 1.1 (BSL 1.1).
|
|
5
|
+
* See LICENSE file in repository root for terms and conditions.
|
|
6
|
+
*/
|
|
7
|
+
var Or=Object.defineProperty;var xt=(a,e,t)=>()=>{if(t)throw t[0];try{return a&&(e=a(a=0)),e}catch(s){throw t=[s],s}};var Di=(a,e)=>{for(var t in e)Or(a,t,{get:e[t],enumerable:!0})};var Te,Ai=xt(()=>{"use strict";Te={DEVICES:["devices","-l"],SCREENCAP:["exec-out","screencap","-p"],FOREGROUND_APP:["shell","dumpsys","window"],CURRENT_FOCUS:["shell","dumpsys","activity","activities"],FORCE_STOP:a=>["shell","am","force-stop",a],CLEAR_APP:a=>["shell","pm","clear",a],LAUNCH_APP:a=>["shell","am","start","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",a],UIAUTOMATOR_DUMP:["exec-out","uiautomator","dump","--compressed","/dev/tty"],INPUT_TAP:(a,e)=>["shell","input","tap",a.toString(),e.toString()],INPUT_TEXT:a=>["shell","input","text",a],INPUT_KEY:a=>["shell","input","keyevent",a.toString()],INPUT_SWIPE:(a,e,t,s,i=300)=>["shell","input","swipe",a.toString(),e.toString(),t.toString(),s.toString(),i.toString()],LOGCAT_CRASH:a=>["shell","logcat","-d","-b","crash","-s","AndroidRuntime:E"],CLEAR_CRASH_LOGS:()=>["shell","logcat","-b","crash","-c"],GRANT_PERMISSION:(a,e)=>["shell","pm","grant",a,e.startsWith("android.permission.")?e:`android.permission.${e}`],INSTALL_APK:a=>["install","-r","-t","-d",a],UNINSTALL_APP:a=>["uninstall",a],DEEP_LINK:a=>["shell","am","start","-a","android.intent.action.VIEW","-d",a],TCPIP:(a=5555)=>["tcpip",a.toString()],CONNECT:a=>["connect",a],DISCONNECT:a=>a?["disconnect",a]:["disconnect"],GET_WLAN_IP:["shell","ip","-f","inet","addr","show","wlan0"]}});function Fr(){let a=process.env.PROMPTTEST_SETTLE_FACTOR;if(!a)return 1;let e=parseFloat(a);return isNaN(e)||e<=0?1:e}function Oe(a,e=50){return Math.max(e,Math.round(a*Fr()))}function $i(a=I.polling.intervalMs,e=I.polling.jitterMs){return Math.round(a+(Math.random()*2-1)*(e/2))}var I,Fe=xt(()=>{"use strict";I={adb:{commandTimeoutMs:2e4,binaryTimeoutMs:45e3,retryCount:2,retryBaseDelayMs:200},polling:{intervalMs:200,jitterMs:80,defaultTimeoutMs:3e3,extendedTimeoutMs:3500,hierarchyCacheTtlMs:3500,verifyCacheTtlMs:2e3},settle:{get tapMs(){return Oe(500)},get backMs(){return Oe(700)},get launchMs(){return Oe(2500)},get stopMs(){return Oe(600)},get keyboardDismissMs(){return Oe(500)},get scrollMs(){return Oe(350)},get toggleMs(){return Oe(350)},get selectMs(){return Oe(600)},get inputFocusMs(){return Oe(250)},get inputClearMs(){return Oe(150)},get inputDoneMs(){return Oe(350)},get submitWaitMs(){return Oe(1800)}},gestures:{swipeDurationMs:300,longPressDurationMs:1e3,bottomNavThresholdRatio:.88,tapTargetYRatio:.96},recorder:{staleTapTimeoutMs:3e3,asyncRefreshDelayMs:80,heartbeatIntervalMs:1500},screen:{fallbackWidth:1080,fallbackHeight:2400},visual:{overlapRatio:.2},device:{maxDeviceRetries:2,autoReconnect:!0},flow:{maxLoopIterations:50,waitUntilTimeoutMs:1e4,defaultRetryCount:3},ai:{provider:"heuristic",model:"gpt-4o-mini",selfHealing:!0,confidenceThreshold:.75,maxHealingAttempts:2,endpoint:""},memory:{staleThresholdDays:parseInt(process.env.PROMPTTEST_STALE_DAYS||"14",10),staleDecayAmount:.2,minConfidenceFloor:.2,maxHealedConfidence:.65},parser:{mode:process.env.PROMPTTEST_XML_PARSER||"regex"},safety:{mode:process.env.PROMPTTEST_SAFETY_MODE||"strict",customBlacklist:process.env.PROMPTTEST_SAFETY_BLACKLIST?process.env.PROMPTTEST_SAFETY_BLACKLIST.split(",").map(a=>a.trim()).filter(Boolean):[]},explorer:{strategy:process.env.PROMPTTEST_STRATEGY||"heuristic",maxTabs:parseInt(process.env.PROMPTTEST_MAX_TABS||"15",10),maxScreens:parseInt(process.env.PROMPTTEST_MAX_SCREENS||"30",10),maxDepth:parseInt(process.env.PROMPTTEST_MAX_DEPTH||"5",10),stepBudget:parseInt(process.env.PROMPTTEST_STEP_BUDGET||"100",10),screenshots:process.env.PROMPTTEST_SCREENSHOTS||"state-change"},locale:"en"}});var bs,Qe,Tt,gs,ms,fs,Jt,It=xt(()=>{"use strict";bs=(n=>(n[n.SUCCESS=0]="SUCCESS",n[n.TEST_FAILED=1]="TEST_FAILED",n[n.DEVICE_UNAVAILABLE=2]="DEVICE_UNAVAILABLE",n[n.CONFIG_ERROR=3]="CONFIG_ERROR",n[n.LOCKED=4]="LOCKED",n))(bs||{}),Qe=class extends Error{exitCode;phase;constructor(e,t=1,s){super(e),this.name="PromptTestError",this.exitCode=t,this.phase=s,Object.setPrototypeOf(this,new.target.prototype)}},Tt=class extends Qe{constructor(e,t="Device"){super(e,2,t),this.name="DeviceError"}},gs=class extends Qe{target;candidateMatches;constructor(e,t,s,i="Locator"){super(e,1,i),this.name="LocatorError",this.target=t,this.candidateMatches=s}},ms=class extends Qe{constructor(e,t="Config"){super(e,3,t),this.name="ConfigError"}},fs=class extends Qe{serial;constructor(e,t,s="Lock"){super(e,4,s),this.name="LockError",this.serial=t}},Jt=class extends Qe{cycle;constructor(e,t,s="SpecLoader"){super(e,3,s),this.name="SpecRecursionError",this.cycle=t}}});import Ae from"fs";import De from"path";import Ci from"os";import _r from"https";import Hr from"http";import Br from"readline";import{execSync as ys,spawnSync as Ur}from"child_process";function Ze(){if(Ce)return Ce;if(process.env.PROMPTTEST_ADB_PATH&&Ae.existsSync(process.env.PROMPTTEST_ADB_PATH))return Ce=process.env.PROMPTTEST_ADB_PATH,Ce;let a=process.platform==="win32",e=a?"adb.exe":"adb",t=[De.join(De.dirname(process.execPath),"platform-tools",e),De.join(De.dirname(process.execPath),e),De.join(process.cwd(),"platform-tools",e),De.join(process.cwd(),"dist","bin","platform-tools",e)];for(let o of t)if(Ae.existsSync(o))return Ce=o,Ce;try{let c=ys(a?"where.exe adb":"which adb",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(c){let l=c.split(/\r?\n/)[0].trim();if(Ae.existsSync(l))return Ce=l,Ce}}catch{}let s=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT].filter(Boolean);for(let o of s){let c=De.join(o,"platform-tools",e);if(Ae.existsSync(c))return Ce=c,Ce}let i=[],n=Ci.homedir();if(a){let o=process.env.LOCALAPPDATA||De.join(n,"AppData","Local");i.push(De.join(o,"Android","Sdk","platform-tools","adb.exe"));let c=process.env.ProgramFiles||"C:\\Program Files";i.push(De.join(c,"Android","platform-tools","adb.exe"))}else process.platform==="darwin"?(i.push(De.join(n,"Library","Android","sdk","platform-tools","adb")),i.push("/opt/homebrew/bin/adb"),i.push("/usr/local/bin/adb")):(i.push(De.join(n,"Android","Sdk","platform-tools","adb")),i.push("/usr/bin/adb"),i.push("/usr/local/bin/adb"));for(let o of i)if(Ae.existsSync(o))return Ce=o,Ce;let r=De.join(n,".prompttest","platform-tools",e);return Ae.existsSync(r)?(Ce=r,Ce):(Ce="adb",Ce)}function jr(a){let e=a||Ze();try{let t=Ur(e,["version"],{encoding:"utf-8",timeout:3e3});return t.status===0&&(t.stdout.includes("Android Debug Bridge")||t.stdout.includes("version"))}catch{return!1}}function Yr(){Ce=null}function Wr(a,e){return new Promise((t,s)=>{let i=Ae.createWriteStream(e);function n(r){(r.startsWith("https")?_r:Hr).get(r,c=>{if(c.statusCode&&c.statusCode>=300&&c.statusCode<400&&c.headers.location)return n(c.headers.location);if(c.statusCode!==200)return s(new Error(`Download failed with HTTP status ${c.statusCode}`));c.pipe(i),i.on("finish",()=>{i.close(()=>t())})}).on("error",c=>{Ae.unlink(e,()=>{}),s(c)})}n(a)})}async function Jr(a){let e=Ci.homedir(),t=a||De.join(e,".prompttest","platform-tools");Ae.mkdirSync(t,{recursive:!0});let s=process.platform==="win32",i=process.platform==="darwin",n=s?"adb.exe":"adb",r=s?"https://dl.google.com/android/repository/platform-tools-latest-windows.zip":i?"https://dl.google.com/android/repository/platform-tools-latest-darwin.zip":"https://dl.google.com/android/repository/platform-tools-latest-linux.zip",o=De.join(t,`platform-tools-download-${Date.now()}.zip`),c=De.join(t,`extract-tmp-${Date.now()}`);try{await Wr(r,o),Ae.mkdirSync(c,{recursive:!0}),s?ys(`powershell -NoProfile -Command "Expand-Archive -Path '${o}' -DestinationPath '${c}' -Force"`,{stdio:"ignore",timeout:6e4}):ys(`unzip -q -o "${o}" -d "${c}"`,{stdio:"ignore",timeout:6e4});let l=De.join(c,"platform-tools"),p=Ae.existsSync(l)?l:c,d=Ae.readdirSync(p);for(let h of d){let g=De.join(p,h),b=De.join(t,h);Ae.copyFileSync(g,b)}let u=De.join(t,n);if(!s&&Ae.existsSync(u))try{Ae.chmodSync(u,493)}catch{}return Yr(),Ce=u,u}finally{try{Ae.existsSync(o)&&Ae.unlinkSync(o),Ae.existsSync(c)&&Ae.rmSync(c,{recursive:!0,force:!0})}catch{}}}async function Vr(){let a=process.argv;return a.includes("--download-adb")||a.includes("-y")||a.includes("--yes")?!0:!process.stdin.isTTY||process.env.CI==="true"?!1:new Promise(e=>{let t=Br.createInterface({input:process.stdin,output:process.stdout});console.log(`
|
|
8
|
+
\u26A0\uFE0F Android Debug Bridge (ADB) was not found on your system.
|
|
9
|
+
PromptTest requires ADB to communicate with physical or emulated Android devices.
|
|
10
|
+
|
|
11
|
+
Would you like PromptTest to download Google's official
|
|
12
|
+
platform-tools archive (~3.5 MB) to ~/.prompttest/platform-tools/? [Y/n]: `),t.question("",s=>{t.close();let i=s.trim().toLowerCase();e(i===""||i==="y"||i==="yes")})})}async function Ni(a={}){if(jr())return Ze();if(a.skipPrompt?!0:await Vr()){console.log(`
|
|
13
|
+
\u2B07\uFE0F Downloading official Google platform-tools (ADB)...`);let t=await Jr();return console.log(`\u2714 ADB successfully provisioned and ready: ${t}
|
|
14
|
+
`),t}throw new Tt(`Android Debug Bridge (ADB) not found on this system.
|
|
15
|
+
To resolve:
|
|
16
|
+
1. Re-run with --download-adb to automatically download Google's official platform-tools.
|
|
17
|
+
2. Install Android Studio: https://developer.android.com/studio
|
|
18
|
+
3. Set custom ADB path via: export PROMPTTEST_ADB_PATH="C:\\path\\to\\adb.exe"
|
|
19
|
+
`)}var Ce,Ss=xt(()=>{"use strict";It();Ce=null});import{spawn as Lt}from"child_process";import ws from"readline";function zr(a,e,t,s){let i={},n=a.match(/level:\s*(\d+)/i),r=a.match(/temperature:\s*(\d+)/i),o=a.match(/status:\s*(\d+)/i);(n||r||o)&&(i.battery={...n?{level:Number(n[1])}:{},...r?{temperatureC:Number(r[1])/10}:{},...o?{status:o[1]}:{}});let c=e.match(/(?:Physical|Override)\s+size:\s*(\d+)x(\d+)/i),l=e.match(/(?:Physical|Override)\s+density:\s*(\d+)/i);(c||l)&&(i.display={...c?{width:Number(c[1]),height:Number(c[2])}:{},...l?{density:Number(l[1])}:{}});let p=t.match(/TOTAL\s+([\d,]+)/i),d=t.match(/Private Dirty:\s*(\d+)/i),u=t.match(/Native Heap:\s*(\d+)/i),g=[...(t.match(/Total PSS by category:\s*([\s\S]*?)(?:\n\s*\n|Total RAM:|$)/i)?.[1]||"").matchAll(/^\s*([\d,]+)K:\s*(.+)$/gim)],b=g.reduce((P,$)=>P+Number($[1].replace(/,/g,"")),0),T=g.find(P=>/native/i.test(P[2]));(p||d||u||b)&&(i.memory={...p?{pssKb:Number(p[1].replace(/,/g,""))}:b?{pssKb:b}:{},...d?{privateDirtyKb:Number(d[1])}:{},...u?{nativeHeapKb:Number(u[1])}:T?{nativeHeapKb:Number(T[1].replace(/,/g,""))}:{}});let x=s.match(/Total frames rendered:\s*(\d+)/i),S=s.match(/Janky frames:\s*(\d+)/i),y=s.match(/90th percentile:\s*([\d.]+)\s*ms/i);return(x||S||y)&&(i.graphics={...x?{framesRendered:Number(x[1])}:{},...S?{jankyFrames:Number(S[1])}:{},...y?{percentile90Ms:Number(y[1])}:{}}),i}function vs(a){let e=(a||"").toLowerCase();return e.startsWith("emulator-")||e.includes("127.0.0.1")||e.includes("localhost")?"emulator":e.includes(":")||e.includes("._tcp")||e.includes("_adb-tls-")?"wifi":"usb"}function Ii(a){let e=new Map;for(let s of a){let i=s.connectionType||vs(s.serial),n="";if(s.model&&s.product)n=`${s.model}__${s.product}`.toLowerCase();else if(s.model)n=s.model.toLowerCase();else{let r=s.serial.match(/^adb-([a-zA-Z0-9]+)-/);n=r?r[1].toLowerCase():s.serial.toLowerCase()}e.has(n)||e.set(n,[]),e.get(n).push({...s,connectionType:i})}let t=[];for(let s of e.values()){if(s.length===1){t.push(s[0]);continue}let i=[...s].sort((n,r)=>{let o=c=>{let l=c.connectionType||vs(c.serial);return l==="usb"?0:l==="wifi"&&!c.serial.includes("._tcp")&&!c.serial.includes("_adb-tls-")?1:l==="wifi"?2:3};return o(n)-o(r)});t.push(i[0])}return t}var nt,Pe,Ne=xt(()=>{"use strict";Ai();Fe();It();Ss();nt=class{defaultSerial=null;cachedDimensions=new Map;inFlightHierarchies=new Map;constructor(e){e&&(this.defaultSerial=e)}setDefaultDevice(e){this.defaultSerial=e}getDefaultDevice(){return this.defaultSerial}async getScreenDimensions(e){let t=e||this.defaultSerial||"default";if(this.cachedDimensions.has(t))return this.cachedDimensions.get(t);try{let{stdout:i}=await this.execAdb(["shell","wm","size"],e),n=i.match(/(?:Physical|Override)\s*size:\s*(\d+)x(\d+)/i);if(n){let r={width:parseInt(n[1],10),height:parseInt(n[2],10)};return this.cachedDimensions.set(t,r),r}}catch{}let s={width:I.screen.fallbackWidth,height:I.screen.fallbackHeight};return this.cachedDimensions.set(t,s),s}clearScreenDimensionsCache(e){e?this.cachedDimensions.delete(e):this.cachedDimensions.clear()}async getNavigationBarHeight(e){try{let{stdout:t}=await this.execAdb(["shell","dumpsys","window","displays"],e).catch(()=>({stdout:""})),s=t.match(/(?:navigationBarHeight|navBarHeight|navigationBarFrame)[=:\s]+(\d+)/i);if(s&&parseInt(s[1],10)>0)return parseInt(s[1],10)}catch{}return 0}isGlobalAdbCommand(e){return e?["devices","connect","disconnect","version","kill-server","start-server","help"].includes(e.toLowerCase()):!0}async execAdbInternal(e,t,s=2e4){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e],r=await Ni();return new Promise((o,c)=>{let l=Lt(r,n),p="",d="",u=!1,h=setTimeout(()=>{u=!0;try{l.kill("SIGKILL")}catch{}c(new Error(`ADB command timed out after ${s}ms: adb ${n.join(" ")}`))},s);l.stdout.on("data",g=>{p+=g.toString("utf-8")}),l.stderr.on("data",g=>{d+=g.toString("utf-8")}),l.on("close",g=>{clearTimeout(h),!u&&(g===0?o({stdout:p,stderr:d}):c(new Error(`ADB command failed (code ${g}): adb ${n.join(" ")}
|
|
20
|
+
Error: ${d}`)))}),l.on("error",g=>{clearTimeout(h),!u&&c(g)})})}async execAdb(e,t,s=I.adb.commandTimeoutMs,i=I.device.maxDeviceRetries){let n;for(let r=0;r<=i;r++)try{return await this.execAdbInternal(e,t,s)}catch(o){n=o;let c=o instanceof Error?o.message:String(o),l=c.toLowerCase(),p=l.includes("device offline")||l.includes("device not found"),d=p||l.includes("error: closed")||l.includes("timed out");if(r>=i||!d||this.isGlobalAdbCommand(e[0]))throw p?new Tt(`Target Android device ${t||this.defaultSerial||""} is offline or disconnected: ${c}`):o;if(I.device.autoReconnect&&p)try{await this.execAdbInternal(["reconnect"],t,5e3).catch(()=>{})}catch{}await new Promise(u=>setTimeout(u,I.adb.retryBaseDelayMs*Math.pow(2,r+1)))}throw n||new Error(`ADB command failed after ${i} retries: ${e.join(" ")}`)}async execAdbBinary(e,t,s=45e3){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((r,o)=>{let c=Lt(Ze(),n),l=[],p="",d=!1,u=setTimeout(()=>{d=!0;try{c.kill("SIGKILL")}catch{}o(new Error(`ADB binary command timed out after ${s}ms: adb ${n.join(" ")}`))},s);c.stdout.on("data",h=>l.push(Buffer.from(h))),c.stderr.on("data",h=>{p+=h.toString("utf-8")}),c.on("close",h=>{clearTimeout(u),!d&&(h===0?r(Buffer.concat(l)):o(new Error(`ADB binary command failed (code ${h}): adb ${n.join(" ")}
|
|
21
|
+
${p}`)))}),c.on("error",h=>{clearTimeout(u),!d&&o(h)})})}async getRawConnectedDevices(){let{stdout:e}=await this.execAdb(Te.DEVICES),t=e.split(`
|
|
22
|
+
`).map(r=>r.trim()).filter(Boolean),s=t.findIndex(r=>r.toLowerCase().includes("list of devices attached")),i=s!==-1?t.slice(s+1):t,n=[];for(let r of i){if(!r||r.startsWith("*")||r.toLowerCase().includes("list of devices"))continue;let o=r.split(/\s+/);if(o.length>=2){let c=o[0],l=o[1],p,d;for(let u of o.slice(2))u.startsWith("model:")&&(p=u.replace("model:","")),u.startsWith("product:")&&(d=u.replace("product:",""));n.push({serial:c,state:l,model:p,product:d,connectionType:vs(c)})}}return n}async getConnectedDevices(e){let t=await this.getRawConnectedDevices();return e?.deduplicate===!1?t:Ii(t)}deduplicateDevices(e){return Ii(e)}async wakeDevice(e){try{await this.execAdb(["shell","input","keyevent","224"],e),await this.execAdb(["shell","wm","dismiss-keyguard"],e)}catch{}}async ensureDefaultDevice(e){if(e)return await this.wakeDevice(e),e;if(this.defaultSerial)return await this.wakeDevice(this.defaultSerial),this.defaultSerial;let s=(await this.getConnectedDevices()).find(i=>i.state==="device");return s&&(this.defaultSerial=s.serial,await this.wakeDevice(this.defaultSerial)),this.defaultSerial||void 0}async getDeviceModel(e){try{let{stdout:n}=await this.execAdb(["shell","getprop","ro.product.model"],e),r=n.trim();if(r)return r}catch{}let t=await this.getConnectedDevices(),s=e||this.defaultSerial;return t.find(n=>n.serial===s)?.model||s||"Android Device"}async captureScreenshot(e){return this.execAdbBinary(Te.SCREENCAP,e)}async getUiHierarchy(e){let t=e||this.defaultSerial||"default",s=this.inFlightHierarchies.get(t);if(s)return s;let i=(async()=>{try{let{stdout:n}=await this.execAdb(Te.UIAUTOMATOR_DUMP,e,1e4,0),r=n.indexOf("<hierarchy");return r>=0?n.slice(r):n}finally{this.inFlightHierarchies.delete(t)}})();return this.inFlightHierarchies.set(t,i),i}clearInFlightHierarchies(e){e?this.inFlightHierarchies.delete(e):this.inFlightHierarchies.clear()}async getForegroundPackage(e){let t=s=>{let i=s.toLowerCase();return i==="android"||i.includes("systemui")||i.includes("inputmethod")||i.includes("latin")||i.includes("gboard")||i.includes("swiftkey")||i.includes("ime")};try{let{stdout:s}=await this.execAdb(["shell","dumpsys","activity","activities"],e).catch(()=>({stdout:""})),i=s.match(/(?:topResumedActivity|mResumedActivity|ResumedActivity)[=:\s]+(?:ActivityRecord\{[^}]*?\s+)?([a-zA-Z0-9._]+)\//i);if(i&&i[1]&&!t(i[1]))return i[1];let{stdout:n}=await this.execAdb(Te.FOREGROUND_APP,e).catch(()=>({stdout:""})),r=n.matchAll(/(?:mCurrentFocus|mFocusedWindow|mFocusedApp|topResumedActivity|mResumedActivity|mFocusedActivity)[=:\s]+(?:Window\{[^}]*?\s+|ActivityRecord\{[^}]*?\s+|AppWindowToken\{[^}]*?\s+)?([a-zA-Z0-9._]+)\//gi);for(let o of r)if(o&&o[1]&&!t(o[1]))return o[1]}catch{}return null}async tap(e,t,s){await this.execAdb(Te.INPUT_TAP(e,t),s)}async inputText(e,t){let s=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/%/g,"\\%").replace(/ /g,"%s").replace(/&/g,"\\&").replace(/</g,"\\<").replace(/>/g,"\\>").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/;/g,"\\;").replace(/\|/g,"\\|").replace(/\$/g,"\\$").replace(/#/g,"\\#").replace(/\*/g,"\\*").replace(/\?/g,"\\?").replace(/~/g,"\\~").replace(/`/g,"\\`");try{await this.execAdb(Te.INPUT_TEXT(s),t)}catch{for(let i of e)if(i===" ")await this.pressKey(62,t);else if(i==="@")await this.pressKey(77,t);else{let n=i.replace(/([\\"'&<>()|$;#*?~`%])/g,"\\$1");await this.execAdb(["shell","input","text",n],t).catch(()=>{})}}}async pressKey(e,t){await this.execAdb(Te.INPUT_KEY(e),t)}async pressEnter(e){await this.pressKey(66,e)}async pressTab(e){await this.pressKey(61,e)}async pressHome(e){await this.pressKey(3,e)}async pressBack(e){await this.pressKey(4,e)}async setWifiEnabled(e,t){await this.execAdb(["shell","svc","wifi",e?"enable":"disable"],t)}async setAirplaneMode(e,t){await this.execAdb(["shell","cmd","connectivity","airplane-mode",e?"enable":"disable"],t)}async setOrientation(e,t){await this.execAdb(["shell","content","insert","--uri","content://settings/system","--bind","name:s:accelerometer_rotation","--bind","value:i:0"],t).catch(()=>{});let s=e==="landscape"?"1":"0";await this.execAdb(["shell","settings","put","system","user_rotation",s],t)}async openNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","expand-notifications"],e)}async collapseNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","collapse"],e)}async clearInput(e=45,t){let s=Array(e).fill("67");await this.execAdb(["shell","input","keyevent",...s],t)}async clearField(e,t=80){await this.pressKey(123,e);let s=Math.max(50,t+10),i=Array(s).fill("67");await this.execAdb(["shell","input","keyevent",...i],e).catch(()=>{}),await this.pressKey(122,e);let n=Array(Math.max(30,Math.floor(t/2))).fill("112");await this.execAdb(["shell","input","keyevent",...n],e).catch(()=>{})}async swipe(e,t,s,i,n=300,r){await this.execAdb(Te.INPUT_SWIPE(e,t,s,i,n),r)}async launchApp(e,t){try{let{stdout:s}=await this.execAdb(["shell","cmd","package","resolve-activity","--brief",e],t),n=(s||"").split(`
|
|
23
|
+
`).map(r=>r.trim()).find(r=>r.includes("/")&&!r.includes(" "));if(n){await this.execAdb(["shell","am","start","-n",n],t);return}}catch{}await this.execAdb(Te.LAUNCH_APP(e),t)}async forceStop(e,t){await this.execAdb(Te.FORCE_STOP(e),t)}async clearAppData(e,t){await this.execAdb(Te.CLEAR_APP(e),t)}async restartApp(e,t){await this.forceStop(e,t),await new Promise(s=>setTimeout(s,600)),await this.launchApp(e,t)}async grantPermission(e,t,s){await this.execAdb(Te.GRANT_PERMISSION(e,t),s)}async isAppInstalled(e,t){try{let{stdout:s}=await this.execAdb(["shell","pm","list","packages",e],t);return s.toLowerCase().includes(`package:${e.toLowerCase()}`)||s.includes(e)}catch{return!1}}async installApk(e,t){let{stdout:s,stderr:i}=await this.execAdb(Te.INSTALL_APK(e),t,12e4),n=`${s} ${i}`;if(n.includes("Failure"))throw new Error(`APK installation failed on device ${t||"default"}: ${n.trim()}`)}async uninstallApp(e,t){await this.execAdb(Te.UNINSTALL_APP(e),t)}async openDeepLink(e,t){await this.execAdb(Te.DEEP_LINK(e),t)}async checkCrashes(e,t){try{let{stdout:s}=await this.execAdb(Te.LOGCAT_CRASH(e),t);if(s&&s.includes("FATAL EXCEPTION")&&s.includes(e))return s}catch{}return null}async clearCrashLogs(e){try{await this.execAdb(Te.CLEAR_CRASH_LOGS(),e)}catch{}}async getDeviceIp(e){try{let{stdout:t}=await this.execAdb(Te.GET_WLAN_IP,e),s=t.match(/inet\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}try{let{stdout:t}=await this.execAdb(["shell","ip","route"],e),s=t.match(/src\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}return null}async connectWifi(e,t=5555,s){let i=e,n=t;if(e&&e.includes(":")){let d=e.split(":");i=d[0],n=parseInt(d[1],10)||t}if(!i){let d=await this.getDeviceIp(s);if(!d)throw new Error("Could not auto-detect phone Wi-Fi IP. Make sure the phone is on Wi-Fi, or pass IP manually: npx prompttest wifi <ip>");i=d}let r=`${i}:${n}`;if(e)try{let{stdout:d,stderr:u}=await this.execAdb(Te.CONNECT(r)),h=`${d} ${u}`.trim();if(h.toLowerCase().includes("connected")||h.toLowerCase().includes("already"))return this.defaultSerial=r,{success:!0,target:r,message:h}}catch{}try{await this.execAdb(Te.TCPIP(n),s),await new Promise(d=>setTimeout(d,1e3))}catch{}let{stdout:o,stderr:c}=await this.execAdb(Te.CONNECT(r)),l=`${o} ${c}`.trim(),p=l.toLowerCase().includes("connected")||l.toLowerCase().includes("already");return p&&(this.defaultSerial=r),{success:p,target:r,message:l}}async disconnectWifi(e){let{stdout:t,stderr:s}=await this.execAdb(Te.DISCONNECT(e));return`${t} ${s}`.trim()}async pairWifi(e,t){if(!/^[^:\s]+:\d+$/.test(e))throw new Error("Pairing target must be an IP:port value.");if(!/^\d{4,8}$/.test(t))throw new Error("Pairing code must contain 4 to 8 digits.");let{stdout:s,stderr:i}=await this.execAdb(["pair",e,t]),n=`${s} ${i}`.trim();return{success:/successfully paired|already paired/i.test(n),message:n}}async getDeviceMetrics(e){let[s,i,n,r]=await Promise.all([this.execAdb(["shell","dumpsys","battery"],e,8e3,0).then(o=>o.stdout).catch(()=>""),this.execAdb(["shell","wm","size"],e,8e3,0).then(async o=>`${o.stdout}
|
|
24
|
+
${(await this.execAdb(["shell","wm","density"],e,8e3,0).catch(()=>({stdout:""}))).stdout}`).catch(()=>""),this.execAdb(["shell","dumpsys","meminfo"],e,8e3,0).then(o=>o.stdout).catch(()=>""),this.execAdb(["shell","dumpsys","gfxinfo"],e,8e3,0).then(o=>o.stdout).catch(()=>"")]);return zr(s,i,n,r)}streamLogcatEvents(e,t){let s=["-s",e,"shell","logcat","-b","events","-v","time"],i=Lt(Ze(),s),n=ws.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatCrashes(e,t){let s=["-s",e,"shell","logcat","-T","1","-s","AndroidRuntime:E","ANRManager:E","-v","time"],i=Lt(Ze(),s),n=ws.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatToasts(e,t){let s=["-s",e,"shell","logcat","-s","Toast:D","Snackbar:D","-v","time"],i=Lt(Ze(),s),n=ws.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}async getLogcatTail(e=150,t){try{let{stdout:s}=await this.execAdb(["logcat","-d","-t",String(e),"-v","time"],t);return s}catch(s){return`Failed to capture logcat: ${s instanceof Error?s.message:String(s)}`}}async startScreenRecording(e="/sdcard/prompttest_temp.mp4",t){let s=t||this.defaultSerial,i=s?["-s",s,"shell","screenrecord",e]:["shell","screenrecord",e],n=Lt(Ze(),i);return n.on("error",()=>{}),{remotePath:e,process:n}}async stopScreenRecording(e,t,s){try{try{e.process.kill("SIGINT")}catch{}return await this.execAdb(["shell","pkill","-2","screenrecord"],s).catch(()=>{}),await new Promise(i=>setTimeout(i,1500)),await this.execAdb(["pull",e.remotePath,t],s),await this.execAdb(["shell","rm","-f",e.remotePath],s).catch(()=>{}),t}catch{return""}}async isKeyboardVisible(e){try{let{stdout:t}=await this.execAdb(["shell","sh","-c",'dumpsys input_method | grep -E "mInputShown=true|mShowRequested=true"'],e,4e3,0),s=t.toLowerCase();if(s.includes("minputshown=true")||s.includes("mshowrequested=true"))return!0}catch{}try{let{stdout:t}=await this.execAdb(["shell","sh","-c",'dumpsys window | grep -E "mInputMethodWindowVisibleHeight"'],e,4e3,0),s=t.match(/mInputMethodWindowVisibleHeight=(\d+)/i);if(s&&parseInt(s[1],10)>0)return!0}catch{}try{let{stdout:t}=await this.execAdb(["shell","dumpsys","input_method"],e,6e3,0),s=t.toLowerCase();return s.includes("minputshown=true")||s.includes("mshowrequested=true")}catch{return!1}}async ensureAccessibilityServices(e){try{await this.execAdb(["shell","settings","put","secure","accessibility_enabled","1"],e,4e3,0)}catch{}}},Pe=new nt});var xr={};Di(xr,{PerformanceProfiler:()=>fi,parseGfxInfo:()=>wr,parseMemInfo:()=>vr});function wr(a){let e=0,t=0,s=0,i,n,r,o,c,l,p=a.match(/Total frames rendered:\s+(\d+)/i);p&&(e=parseInt(p[1],10));let d=a.match(/Janky frames:\s+(\d+)(?:\s+\(([0-9.]+)%\))?/i);d&&(t=parseInt(d[1],10),d[2]?s=parseFloat(d[2]):e>0&&(s=parseFloat((t/e*100).toFixed(2))));let u=a.match(/50th percentile:\s+(\d+)ms/i);u&&(i=parseInt(u[1],10));let h=a.match(/90th percentile:\s+(\d+)ms/i);h&&(n=parseInt(h[1],10));let g=a.match(/95th percentile:\s+(\d+)ms/i);g&&(r=parseInt(g[1],10));let b=a.match(/99th percentile:\s+(\d+)ms/i);b&&(o=parseInt(b[1],10));let T=a.match(/Number Missed Vsync:\s+(\d+)/i);T&&(c=parseInt(T[1],10));let x=a.match(/Number Slow UI thread:\s+(\d+)/i);return x&&(l=parseInt(x[1],10)),{totalFrames:e,jankyFrames:t,jankPercentage:s,p50Ms:i,p90Ms:n,p95Ms:r,p99Ms:o,missedVsync:c,slowUiThread:l}}function vr(a){let e=0,t,s,i=a.match(/TOTAL PSS:\s+(\d+)/i)||a.match(/TOTAL:\s+(\d+)/i)||a.match(/TOTAL\s+PSS\s+TOTAL\s+RSS[\s\S]*?TOTAL\s+(\d+)/i);i&&(e=parseInt(i[1],10));let n=a.match(/Native Heap\s+(\d+)/i)||a.match(/Native\s+(\d+)/i);n&&(t=parseInt(n[1],10));let r=a.match(/Java Heap\s+(\d+)/i)||a.match(/Dalvik Heap\s+(\d+)/i);return r&&(s=parseInt(r[1],10)),{totalPssKb:e,nativeHeapKb:t,javaHeapKb:s}}var fi,Tr=xt(()=>{"use strict";Ne();fi=class{driver;serial;packageName="";startTime=0;memorySamples=[];constructor(e,t){this.driver=e||Pe,this.serial=t}async start(e){this.packageName=e,this.startTime=Date.now(),this.memorySamples=[];try{await this.driver.execAdb(["shell","dumpsys","gfxinfo",e,"reset"],this.serial)}catch{}await this.sample(0,"Suite Initialized")}async sample(e,t){if(this.packageName)try{let{stdout:s}=await this.driver.execAdb(["shell","dumpsys","meminfo",this.packageName],this.serial),i=vr(s);this.memorySamples.push({timestamp:Date.now(),stepIndex:e,stepName:t,totalPssKb:i.totalPssKb,nativeHeapKb:i.nativeHeapKb,javaHeapKb:i.javaHeapKb})}catch{}}async stop(){let e=Date.now()-(this.startTime||Date.now()),t={totalFrames:0,jankyFrames:0,jankPercentage:0};if(this.packageName)try{let{stdout:o}=await this.driver.execAdb(["shell","dumpsys","gfxinfo",this.packageName],this.serial);t=wr(o)}catch{}let s=this.memorySamples[0]?.totalPssKb||0,i=this.memorySamples[this.memorySamples.length-1]?.totalPssKb||s,n=this.memorySamples.reduce((o,c)=>Math.max(o,c.totalPssKb),s),r="PASS";return t.jankPercentage>15||t.p95Ms&&t.p95Ms>32?r="FAIL":(t.jankPercentage>5||t.p95Ms&&t.p95Ms>16.7)&&(r="WARN"),{packageName:this.packageName,durationMs:e,fpsCompliance:r,frames:t,memory:{startPssKb:s,peakPssKb:n,endPssKb:i,deltaPssKb:i-s,samples:this.memorySamples}}}}});var Nr={};Di(Nr,{buildFeedbackUrl:()=>vi,startFeedbackSession:()=>Yn});import jn from"readline";import Wt from"os";import fe from"chalk";function vi(a){let e=(a.message||"Feedback").split(`
|
|
25
|
+
`)[0].trim(),t=e.length>70?e.substring(0,67)+"...":e,s=a.rating?"\u2B50".repeat(a.rating):"";if(a.category==="feature"){let r=new URLSearchParams;return r.set("template","2_feature_request.yml"),r.set("title",`[Feature]: ${t}`),r.set("problem",`User feedback submission${s?` (${s} ${a.rating}/5)`:""}:
|
|
26
|
+
${a.message}`),r.set("proposed_solution",a.message),r.set("category","Plain-English DSL / Syntax"),`${Si}/issues/new?${r.toString()}`}if(a.category==="bug"){let r=new URLSearchParams;return r.set("template","1_bug_report.yml"),r.set("title",`[Bug]: ${t}`),r.set("description",a.message),r.set("command_run","npx prompttest"),r.set("environment",`${Wt.type()} ${Wt.release()} (${Wt.arch()}), Node: ${process.version}`),`${Si}/issues/new?${r.toString()}`}let i=new URLSearchParams;i.set("template","3_feedback.yml");let n=a.rating?` ${"\u2B50".repeat(a.rating)}`:"";if(i.set("title",`[Feedback${n}]: ${t}`),i.set("message",a.message),typeof a.rating=="number"){let o={5:0,4:1,3:2,2:3,1:4}[a.rating]??0;i.set("rating",String(o))}return i.set("environment",`${Wt.type()} ${Wt.release()} (${Wt.arch()}), Node: ${process.version}`),`${Si}/issues/new?${i.toString()}`}function wi(a,e){return new Promise(t=>{if(a.closed){t("");return}try{a.question(e,s=>{t(s.trim())})}catch{t("")}})}async function Yn(a={}){let e=a.input||process.stdin,t=a.output||process.stdout,s=(n="")=>{t.write(n+`
|
|
27
|
+
`)};if(a.directMessage&&a.directMessage.trim()){let n=a.category||"general",r=vi({category:n,message:a.directMessage.trim()});return s(fe.bold.cyan(`
|
|
28
|
+
\u26A1 PromptTest \u2014 Community Feedback`)),s(fe.gray("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),s(fe.green("\u2714 Thank you for your feedback! Here is your 1-click submission link:")),s(fe.bold.underline.cyan(r)),s(fe.gray(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
29
|
+
`)),r}let i=jn.createInterface({input:e,output:t});try{s(fe.bold.cyan(`
|
|
30
|
+
\u26A1 PromptTest \u2014 Community Feedback & Suggestions`)),s(fe.gray("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),s(fe.white("We want to make PromptTest the best mobile QA engine in your toolchain.")),s(fe.white(`Your feedback goes directly to our open community tracker!
|
|
31
|
+
`)),s(fe.bold.white("How would you rate your experience with PromptTest?")),s(` ${fe.cyan("[1]")} \u2B50\u2B50\u2B50\u2B50\u2B50 (5/5) \u2014 Loving it!`),s(` ${fe.cyan("[2]")} \u2B50\u2B50\u2B50\u2B50 (4/5) \u2014 Great, but needs minor improvements`),s(` ${fe.cyan("[3]")} \u2B50\u2B50\u2B50 (3/5) \u2014 Okay, encountered some friction`),s(` ${fe.cyan("[4]")} \u2B50\u2B50 (2/5) \u2014 Frustrating / missing key features`),s(` ${fe.cyan("[5]")} \u2B50 (1/5) \u2014 Not working for me`);let n=await wi(i,fe.bold.cyan(`
|
|
32
|
+
Select rating [1-5] (default: 1): `)),r=parseInt(n,10),c={1:5,2:4,3:3,4:2,5:1}[r]||5;s(fe.bold.white(`
|
|
33
|
+
What type of feedback would you like to share?`)),s(` ${fe.cyan("[1]")} \u{1F4A1} Feature Request or syntax suggestion`),s(` ${fe.cyan("[2]")} \u{1F41B} Bug report or unexpected error`),s(` ${fe.cyan("[3]")} \u{1F4AC} General feedback, question, or compliment`);let l=await wi(i,fe.bold.cyan(`
|
|
34
|
+
Select category [1-3] (default: 1): `)),p="feature";l==="2"?p="bug":l==="3"&&(p="general"),s(fe.bold.white(`
|
|
35
|
+
Please share your thoughts, ideas, or feedback:`));let u=await wi(i,fe.bold.cyan("> "))||"Overall great experience with PromptTest!",h=vi({rating:c,category:p,message:u});return s(fe.gray(`
|
|
36
|
+
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`)),s(fe.green.bold("\u2728 Thank you! We generated your 1-click submission:")),s(fe.bold.underline.cyan(h)),s(fe.gray(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
37
|
+
`)),h}finally{try{i.close()}catch{}}}var Si,xi=xt(()=>{"use strict";Si="https://github.com/shriramsingh/prompttest-community"});Ne();import us from"fs";import it from"path";import q from"chalk";Fe();var Mi=/^(\d+(?:\.\d+)*\.?|\-|\*)\s*/;function Ri(a){let e=a.trim(),t=e.match(/^"([^"]+)"$/);if(t)return t[1].trim();let s=e.match(/^'([^']+)'$/);return s?s[1].trim():e.replace(/^['"]+|['"]+$/g,"").trim()}var oe=`(?:"([^"]+)"|'([^']+)'|([^'"\\s][^'"]*?[^'"\\s]|\\S))`;function ce(a){for(let e of a)if(e!=null&&e.trim().length>0)return e.trim();return""}function Pt(a,e){let t=a;if(e)for(let[s,i]of Object.entries(e))t=t.replace(new RegExp(`\\$${s}\\b`,"g"),()=>i);return t=t.replace(/\$ENV\{([A-Z0-9_]+)\}/gi,(s,i)=>process.env[i]||""),t=t.replace(/\$RANDOM_EMAIL\b/g,()=>`test_${Date.now().toString().slice(-6)}@prompttest.io`),t=t.replace(/\$RANDOM_NAME\b/g,()=>`User_${Math.floor(1e3+Math.random()*9e3)}`),t=t.replace(/\$RANDOM_PHONE\b/g,()=>`98${Math.floor(1e7+Math.random()*9e7)}`),t=t.replace(/\$TIMESTAMP\b/g,()=>Date.now().toString()),t=t.replace(/\$UUID\b/g,()=>`${Date.now().toString(16)}-${Math.random().toString(16).substring(2,8)}`),t=t.replace(/\$RANDOM_UUID\b/g,()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s==="x"?i:i&3|8).toString(16)})),t=t.replace(/\$RANDOM_CARD\b/g,()=>{let s="4532";for(let i=0;i<12;i++)s+=Math.floor(Math.random()*10);return s}),t=t.replace(/\$DATE_OFFSET\((-?\d+)\)/g,(s,i)=>{let n=parseInt(i,10)||0;return new Date(Date.now()+n*864e5).toISOString().slice(0,10)}),t=t.replace(/\$RANDOM_INT\((\d+),\s*(\d+)\)/g,(s,i,n)=>{let r=parseInt(i,10),o=parseInt(n,10);return String(Math.floor(r+Math.random()*(o-r+1)))}),t}var te={TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:button\\s+|item\\s+)?${oe}$`,"i"),ORDINAL_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:the\\s+)?(1st|2nd|3rd|4th|5th|last|first)\\s+(?:button\\s+|item\\s+)?${oe}$`,"i"),PROXIMITY_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+${oe}\\s+(?:next\\s+to|near|beside|inside|for)\\s+${oe}$`,"i"),CLEAR:new RegExp(`^(?:clear|empty)(?:\\s+(?:text\\s+(?:in|of)|field|input))?\\s+${oe}$`,"i"),LONG_PRESS:new RegExp(`^(?:long\\s+press|press\\s+and\\s+hold)\\s+(?:button\\s+|item\\s+)?${oe}$`,"i"),TYPE:new RegExp(`^(?:type|enter|input)\\s+${oe}\\s+(?:in|into)\\s+${oe}$`,"i"),VERIFY:new RegExp(`^(?:verify|veryfy|check|assert|ensure)\\s+(?:that\\s+)?(?:error\\s+message\\s+|message\\s+|text\\s+|element\\s+|button\\s+|toast\\s+|my\\s+)?${oe}\\s*(?:is\\s+(visible|exists|appears|enabled|disabled|not\\s+visible|hidden|absent|not\\s+present|gone))?$`,"i"),BACK:/^(?:press\s+back|go\s+back|navigate\s+back|back)$/i,SCROLL_TO:new RegExp(`^(?:scroll|swipe)(?:\\s+(down|up))?\\s+(?:to|until)\\s+${oe}$`,"i"),SCROLL:/^(?:scroll|swipe)\s+(down|up)$/i,DIRECTIONAL_SWIPE:new RegExp(`^(?:swipe|scroll)\\s+(left|right|up|down)(?:\\s+on\\s+${oe})?$`,"i"),TOGGLE:new RegExp(`^(?:toggle|turn\\s+(on|off)|check|uncheck)\\s+(?:checkbox\\s+|switch\\s+)?${oe}$`,"i"),SELECT_DROPDOWN:new RegExp(`^(?:select|choose)\\s+${oe}\\s+from\\s+${oe}$`,"i"),LAUNCH_APP:new RegExp(`^(?:launch|open)\\s+(?:app\\s+)?${oe}$`,"i"),RESTART_APP:new RegExp(`^(?:restart|relaunch)\\s+(?:app\\s+)?${oe}$`,"i"),TERMINATE_APP:new RegExp(`^(?:terminate|close|force\\s*stop)\\s+(?:app\\s+)?(?:${oe})?$`,"i"),CLEAR_DATA:new RegExp(`^(?:clear\\s+(?:app\\s+)?data\\s+(?:for\\s+)?|reset\\s+app\\s+)${oe}$`,"i"),GRANT_PERMISSION:new RegExp(`^grant\\s+permissions?\\s+${oe}(?:\\s+(?:to|for)\\s+${oe})?$`,"i"),DEEP_LINK:new RegExp(`^(?:open\\s+deep\\s*link|navigate\\s+to\\s+url)\\s+${oe}$`,"i"),WAIT:/^wait\s+(\d+)\s*(?:s|sec|seconds|ms)?$/i,WAIT_UNTIL:new RegExp(`^(?:wait\\s+until|wait\\s+for)\\s+${oe}\\s+(?:(?:is\\s+)?(visible|appears?|enabled|exists))?(?:\\s+(?:up\\s+to|for)\\s+(\\d+)\\s*(s|sec|seconds|ms)?)?$`,"i"),IF_VISIBLE:new RegExp(`^if\\s+(?:(?:that\\s+)?${oe}\\s+(?:is\\s+)?(visible|present|exists|appears?)|element\\s+${oe}\\s+(?:is\\s+)?visible)$`,"i"),ELSE:/^else$/i,END:/^(?:end|end\s*if|end\s*loop|fi|done)$/i,LOOP:/^(?:loop|repeat)\s+(\d+)\s*(?:times)?$/i,FOR_EACH:new RegExp(`^for\\s+each\\s+(?:item\\s+)?(?:in\\s+)?${oe}$`,"i"),SET_VARIABLE:/^set\s+\$([a-zA-Z0-9_]+)\s*=\s*(.+)$/i,DEVICE_WIFI:/^(?:turn\s+|set\s+)?wifi\s+(on|off|enable|disable)$/i,DEVICE_AIRPLANE:/^(?:turn\s+|set\\s+)?airplane\s*(?:mode)?\s+(on|off|enable|disable)$/i,DEVICE_ORIENTATION:/^(?:set\s+)?orientation\s+(?:to\s+)?(portrait|landscape)$/i,DEVICE_NOTIFICATIONS:/^(open|expand|pull\s+down|collapse|close)\s+notification(?:s|\s+shade)?$/i,INCLUDE_SPEC:new RegExp(`^(?:include|run_spec|subflow)\\s+${oe}$`,"i"),RUN_JS:/^(?:run\s+js|eval\s+js|js)(?::|\s+)(.+)$/i,ENTER_OTP:new RegExp(`^(?:enter|input|type)\\s+(?:the\\s+)?(?:verification\\s+code|otp|2fa\\s+code|sms\\s+code)(?:\\s+just\\s+sent)?(?:\\s+(?:in|into)\\s+${oe})?$`,"i"),API_REQUEST:new RegExp(`^(?:api|call\\s+api)\\s+(GET|POST|PUT|DELETE|PATCH)\\s+${oe}(?:\\s+with\\s+body\\s+${oe})?(?:\\s+store\\s+${oe}\\s+as\\s+\\$([a-zA-Z0-9_]+))?(?:\\s+assert\\s+status\\s+(\\d+))?$`,"i"),EMAIL_ASSERT:new RegExp(`^(?:assert|verify)\\s+email\\s+to\\s+${oe}\\s+with\\s+subject\\s+${oe}(?:\\s+contains\\s+${oe})?$`,"i"),OPTIONAL_SUFFIX:/\s*\((?:optional|if\s+present|maybe)\)\s*$/i,FALLBACK_QUOTED_TAP:/^(?:tap|click)\s+.*?['"]([^'"]+)['"]/i},Vt={HIERARCHY_ROOT:/<hierarchy[^>]*>([\s\S]*?)<\/hierarchy>/i,NODE_TAG:/<node\b([^>]*?)(\/?)>|<\/node>/gi,ATTR_KEY_VALUE:/([a-zA-Z0-9_-]+)="([^"]*)"/g,BOUNDS_RECT:/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/};function Mt(a){return(a||"").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,10))}catch{return""}}).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}}).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function ae(a){return Mt(a||"").trim().toLowerCase().replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/\uFFFD/g,"").replace(new RegExp("\\p{Extended_Pictographic}","gu"),"").replace(/[\uE000-\uF8FF\uFFF0-\uFFFF]/g,"").replace(/\s+/g," ").trim()}var Li=new Map;function de(a,e){if(!a||!e)return!1;let t=ae(a),s=ae(e);if(t.length<=3){let i=Li.get(t);if(!i){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(`(?:^|\\b)${n}(?:\\b|$)`,"i"),Li.set(t,i)}return i.test(s)}return s.includes(t)}var Oi=["sign in","signin","login","log in","submit","save","continue","next","done","send","confirm","proceed","post","rate","enter","join","apply","update"],Fi=["sign in","signin","login","log in","submit","save","next","continue","done","like","fav","favorite","star","bookmark","add","post","confirm","apply","explore","search","filter"];function Kr(a,e){let t=ae(a),s=ae(e),i=t.length,n=s.length;if(i===0)return n;if(n===0)return i;let r=Array.from({length:n+1},(c,l)=>l),o=new Array(n+1);for(let c=1;c<=i;c++){o[0]=c;for(let p=1;p<=n;p++){let d=t[c-1]===s[p-1]?0:1;o[p]=Math.min(r[p]+1,o[p-1]+1,r[p-1]+d)}let l=r;r=o,o=l}return r[n]}function Xr(a,e){let t=ae(a),s=ae(e);if(t===s)return 1;if(!t||!s)return 0;let i=Math.max(t.length,s.length);return 1-Kr(t,s)/i}function Rt(a,e,t=3,s=.35){return Array.from(new Set(e.map(r=>r.trim()).filter(r=>r.length>0))).map(r=>({text:r,score:Xr(a,r)})).filter(r=>r.score>=s).sort((r,o)=>o.score-r.score).slice(0,t)}function _i(a){let e=a.match(Vt.BOUNDS_RECT);if(!e)return{x1:0,y1:0,x2:0,y2:0,width:0,height:0,centerX:0,centerY:0};let t=parseInt(e[1],10),s=parseInt(e[2],10),i=parseInt(e[3],10),n=parseInt(e[4],10);return{x1:t,y1:s,x2:i,y2:n,width:i-t,height:n-s,centerX:Math.round((t+i)/2),centerY:Math.round((s+n)/2)}}function Gr(a){let e=a.match(Vt.HIERARCHY_ROOT);if(!e)return{root:[],flat:[]};let t=e[1],s=new RegExp(Vt.NODE_TAG.source,"gi"),i=new RegExp(Vt.ATTR_KEY_VALUE.source,"g"),n=[],r=[],o=[],c;for(;(c=s.exec(t))!==null;){let l=c[0],p=c[1],d=c[2]==="/";if(l.startsWith("</node>")){o.pop();continue}let u={};i.lastIndex=0;let h;for(;(h=i.exec(p))!==null;)u[h[1]]=h[2];let g={index:parseInt(u.index||"0",10),text:Mt(u.text||""),resourceId:u["resource-id"]||"",className:u.class||"",packageName:u.package||"",contentDesc:Mt(u["content-desc"]||""),bounds:_i(u.bounds||""),clickable:u.clickable==="true",enabled:u.enabled==="true",focused:u.focused==="true",scrollable:u.scrollable==="true",password:u.password==="true",selected:u.selected==="true",checked:u.checked!==void 0?u.checked==="true":void 0,checkable:u.checkable!==void 0?u.checkable==="true":void 0,children:[]};r.push(g),o.length===0?n.push(g):o[o.length-1].children.push(g),d||o.push(g)}return{root:n,flat:r}}function Qr(a){let e=[],t=[],s=[],i=a.length,n=0;for(;n<i;){let r=a.indexOf("<",n);if(r===-1)break;if(a.startsWith("<!--",r)){let x=a.indexOf("-->",r+4);n=x===-1?i:x+3;continue}if(a.startsWith("<?",r)){let x=a.indexOf("?>",r+2);n=x===-1?i:x+2;continue}if(a.startsWith("</",r)){let x=a.indexOf(">",r+2);if(x===-1)break;a.slice(r+2,x).trim()==="node"&&s.pop(),n=x+1;continue}let o=-1,c=null,l=!1;for(let x=r+1;x<i;x++){let S=a[x];if(c)S===c&&(c=null);else if(S==='"'||S==="'")c=S;else if(S===">"){o=x,a[x-1]==="/"&&(l=!0);break}}if(o===-1)break;let p=a.slice(r+1,l?o-1:o).trim();n=o+1;let d=0;for(;d<p.length&&!/\s/.test(p[d]);)d++;if(p.slice(0,d)!=="node")continue;let h={},g=d,b=p.length;for(;g<b;){for(;g<b&&/\s/.test(p[g]);)g++;if(g>=b)break;let x=g;for(;g<b&&p[g]!=="="&&!/\s/.test(p[g]);)g++;let S=p.slice(x,g);for(;g<b&&/\s/.test(p[g]);)g++;if(g>=b||p[g]!=="=")break;for(g++;g<b&&/\s/.test(p[g]);)g++;if(g>=b)break;let y=p[g];if(y==='"'||y==="'"){g++;let P=g;for(;g<b&&p[g]!==y;)g++;h[S]=p.slice(P,g),g<b&&g++}else{let P=g;for(;g<b&&!/\s/.test(p[g]);)g++;h[S]=p.slice(P,g)}}let T={index:parseInt(h.index||"0",10),text:Mt(h.text||""),resourceId:h["resource-id"]||"",className:h.class||"",packageName:h.package||"",contentDesc:Mt(h["content-desc"]||""),bounds:_i(h.bounds||""),clickable:h.clickable==="true",enabled:h.enabled==="true",focused:h.focused==="true",scrollable:h.scrollable==="true",password:h.password==="true",selected:h.selected==="true",checked:h.checked!==void 0?h.checked==="true":void 0,checkable:h.checkable!==void 0?h.checkable==="true":void 0,children:[]};t.push(T),s.length===0?e.push(T):s[s.length-1].children.push(T),l||s.push(T)}return{root:e,flat:t}}function me(a,e){if((e||I.parser?.mode||"regex")==="streaming")try{return Qr(a)}catch{}return Gr(a)}function bo(a,e){return a.filter(t=>{if(e.clickable!==void 0&&t.clickable!==e.clickable||e.className&&!t.className.includes(e.className))return!1;if(e.text){if(typeof e.text=="string"){if(!t.text.toLowerCase().includes(e.text.toLowerCase()))return!1}else if(!e.text.test(t.text))return!1}if(e.contentDesc){if(typeof e.contentDesc=="string"){if(!t.contentDesc.toLowerCase().includes(e.contentDesc.toLowerCase()))return!1}else if(!e.contentDesc.test(t.contentDesc))return!1}if(e.resourceId){if(typeof e.resourceId=="string"){if(!t.resourceId.toLowerCase().includes(e.resourceId.toLowerCase()))return!1}else if(!e.resourceId.test(t.resourceId))return!1}return!0})}var Zr=[/logbox/i,/^Log \d+ of \d+/i,/Console (?:Error|Warning|Log|Info)/i,/^Call Stack$/i,/^Source Map$/i,/^(?:Dismiss|Minimize|Copy|View error log)$/i,/\b[\w-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+\b/i,/Unhandled Promise Rejection/i,/SyntaxError/i,/TypeError:/i,/ReferenceError:/i,/Warning:/i,/LogBoxNotificationOverlay/i];function _e(a){if(a.resourceId&&/logbox/i.test(a.resourceId)||a.className&&/logbox/i.test(a.className))return!0;let e=`${a.text} ${a.contentDesc}`.trim();return!!Zr.some(t=>t.test(e))}function Le(a){return a.filter(e=>_e(e)?!1:(e.className.includes("EditText")||e.className.includes("TextInputEditText")||e.focused&&e.clickable)&&e.bounds.width>0&&e.bounds.height>0)}function xs(a){return a.className.includes("EditText")||a.className.includes("TextInputEditText")?!0:(a.children||[]).some(xs)}function zt(a,e){let t=e?.width||I.screen.fallbackWidth,s=e?.height||I.screen.fallbackHeight,i=s*.08,n=s*.88,r=a.filter(c=>!_e(c)&&(c.className.includes("RecyclerView")||c.className.includes("ListView")||c.className.includes("ScrollView"))),o=[];for(let c of r)for(let l of c.children){if(_e(l)||l.bounds.centerY<i||l.bounds.centerY>n)continue;(l.clickable||l.children.some(d=>!_e(d)&&d.clickable&&d.bounds.width>t*.1))&&l.bounds.width>t*.08&&l.bounds.height>s*.02&&!xs(l)&&o.push(l)}return o.length===0?a.filter(c=>{if(_e(c))return!1;let l=(c.text||c.contentDesc||"").trim();return l.length<=1||/^(remember me|forgot password|sign in|sign up|login|submit|cancel)$/i.test(l)?!1:c.clickable&&c.bounds.width>t*.14&&c.bounds.height>s*.033&&c.bounds.centerY>i&&c.bounds.centerY<n&&!c.className.includes("Button")&&!c.className.includes("EditText")&&!xs(c)}):o}function Me(a){return a.filter(e=>{if(_e(e)||!e.clickable||e.bounds.width===0||e.className.includes("EditText"))return!1;let t=e.className.includes("Button")||e.className.includes("ImageButton"),s=Fi.some(i=>de(i,e.text)||de(i,e.contentDesc)||de(i,e.resourceId));return t||s})}function ot(a,e=I.screen.fallbackHeight,t){if(!a||a.length===0)return[];let s=a.find(h=>h.bounds.height>=e*.6&&h.bounds.y1<=e*.15),i=s?.bounds?.y1!==void 0&&s.bounds.y1>=0?s.bounds.y1:0,n=s?.bounds?.y2&&s.bounds.y2>i?s.bounds.y2:e,r=n-i,o=s?.bounds?.x2&&s.bounds.x2>0?s.bounds.x2-(s.bounds.x1||0):I.screen.fallbackWidth,c=i+r*.78,l=a.filter(h=>_e(h)||t&&h.packageName&&!h.packageName.includes(t)||!h.clickable||h.bounds.width<=0||h.bounds.height<=0||!(h.bounds.centerY>=c||h.bounds.y2>=n-20)?!1:h.bounds.width>=o*.12&&h.bounds.width<=o*.55);if(l.length<=1)return l;let p=[];for(let h of l){let g=p.find(b=>Math.abs(b[0].bounds.centerY-h.bounds.centerY)<=30||Math.abs(b[0].bounds.y2-h.bounds.y2)<=20);g||(g=[],p.push(g)),g.push(h)}let d=p.map(h=>{h.sort((b,T)=>b.bounds.centerX-T.bounds.centerX);let g=[];for(let b of h)g.some(T=>Math.abs(T.bounds.centerX-b.bounds.centerX)<o*.08)||g.push(b);return g}).filter(h=>h.length<2||h.length>6?!1:h[h.length-1].bounds.x2-h[0].bounds.x1>=o*.6);return d.length===0?l.slice(0,5):(d.sort((h,g)=>g[0].bounds.centerY-h[0].bounds.centerY),d[0].slice(0,5))}function Hi(a){let e=[/fatal\s+exception/i,/unfortunately.*stopped/i,/(?:app|system|process).*(?:isn't|is not|not)\s+responding/i,/(?:isn't|is not|not)\s+responding/i,/force\s+close/i,/network\s+connection\s+(?:failed|lost|error)/i,/something went wrong/i,/(?:failed|unable)\s+to\s+(?:connect|load|fetch)/i];return a.filter(t=>{let s=`${t.text} ${t.contentDesc}`;return e.some(i=>i.test(s))})}var qr=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)(?:[_\s-]+(?:account|profile|all|data|item|cart|user))?(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:pay|purchase|checkout|buy[_\s-]+now|order[_\s-]+now)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:exit[_\s-]*app|close[_\s-]*app|^exit$|^quit$)(?:\b|[_\s-])/i],en=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)[_\s-]+(?:account|profile|user)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i],tn=[/(?:\b|[_\s-])(?:rate[_\s-]*us|review[_\s-]*(?:on|in)[_\s-]*(?:play|store)|play[_\s-]*store)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:visit[_\s-]*(?:our)?[_\s-]*website|privacy[_\s-]*policy|terms[_\s-]*of[_\s-]*service|terms[_\s-]*&[_\s-]*conditions)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:follow[_\s-]*us|share[_\s-]*via|share[_\s-]*app|open[_\s-]*in[_\s-]*browser)(?:\b|[_\s-])/i,/^https?:\/\//i,/(?:www\.[a-z0-9-]+\.[a-z]{2,})/i];function Je(a,e,t=I.safety?.mode||"strict"){if(t==="disabled")return!1;let s=`${a.text} ${a.contentDesc} ${a.resourceId}`.trim();if((t==="moderate"?en:qr).some(r=>r.test(s)))return!0;let n=e||I.safety?.customBlacklist||[];for(let r of n)if(typeof r=="string"&&r.length>0){if(s.toLowerCase().includes(r.toLowerCase()))return!0}else if(r instanceof RegExp&&r.test(s))return!0;return!1}function Ve(a){let e=`${a.text} ${a.contentDesc} ${a.resourceId}`.trim();return tn.some(t=>t.test(e))}function Kt(a){for(let e of a){let t=`${e.text} ${e.contentDesc} ${e.resourceId}`;if(e.resourceId.toLowerCase().includes("logbox")||t.includes("Unhandled Promise Rejection")||t.includes("SyntaxError")||t.includes("Encountered two children with the same key")||t.includes("Warning:")||t.includes("Console Error")||t.includes("Console Warning")||t.includes("Console Info")||t.includes("TypeError:")||t.includes("ReferenceError:")||/Log \d+ of \d+/i.test(t)||t.includes("LogBox")&&(e.className.includes("Modal")||e.className.includes("ViewGroup"))){let i="error";/warning/i.test(t)?i="warning":/info/i.test(t)&&(i="info");let n=e.resourceId.includes("notification")||e.bounds.height>0&&e.bounds.height<250,r,o=[];for(let p of a){let d=`${p.text} ${p.contentDesc}`.trim();if(!r){let u=d.match(/\b([a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+)\b/);u&&(r=u[1])}/\b(?:at\s+|\()?[a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+/i.test(d)&&!o.includes(d)&&d.length<200&&o.push(d)}let c=a.find(p=>p.clickable&&p.bounds.width>0&&(/^(?:dismiss|close)$/i.test((p.text||"").trim())||/^(?:dismiss|close)$/i.test((p.contentDesc||"").trim())));if(!c&&!n){let d=a.filter(u=>u.clickable&&u.bounds.width>0&&u.bounds.height>0&&!/minimize|copy/i.test(`${u.text} ${u.contentDesc}`)).filter(u=>u.bounds.centerY>I.screen.fallbackHeight*.8);d.length>0&&(d.sort((u,h)=>u.bounds.x1-h.bounds.x1),c=d[0])}!c&&n&&(c=a.find(p=>p.clickable&&p.bounds.y1>=e.bounds.y1-20&&p.bounds.y2<=e.bounds.y2+20&&p.bounds.x1>=e.bounds.x2-120));let l=e.text||e.contentDesc||"React Native LogBox Console Overlay";return{type:"logbox",severity:i,node:e,errorText:l,sourceLocation:r,stackTrace:o.length>0?o:void 0,dismissButton:c,isToast:n}}if(e.resourceId.includes("alertTitle")&&(t.includes("isn't responding")||t.includes("has stopped"))){let i=a.find(n=>n.text.toLowerCase().includes("close app")||n.text.toLowerCase().includes("ok"));return{type:"anr",severity:"error",node:e,errorText:e.text||"Application Not Responding (ANR)",dismissButton:i}}}return null}function Ot(a){return a.filter(e=>_e(e)?!1:(e.checkable||e.className.includes("CheckBox")||e.className.includes("Switch")||e.className.includes("RadioButton")||e.className.includes("SwitchCompat"))&&e.bounds.width>0&&e.bounds.height>0)}function at(a,e=I.screen.fallbackHeight,t=I.screen.fallbackWidth){let s=e*.22,i=/(?:menu|hamburger|drawer|navigation|\u2630|open[_\s-]*drawer)/i,n=a.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.centerY>s)return!1;let o=`${r.contentDesc} ${r.text} ${r.resourceId}`;return i.test(o)});return n||a.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.height===0||r.bounds.centerY>s||(r.text||r.contentDesc||"").trim().length>0)return!1;let c=r.bounds.x1<=t*.25,l=r.bounds.width<=250&&r.bounds.height<=250;return c&&l})||null}function Bi(a,e=I.screen.fallbackHeight,t=I.screen.fallbackWidth){let s=e*.22;return a.filter(i=>{if(!i.clickable||i.bounds.width===0||i.bounds.height===0||i.bounds.centerY>s)return!1;let n=i.bounds.x2>=t*.75,r=i.bounds.width<=250&&i.bounds.height<=250;return n&&r})}function Ui(a){return a.filter(e=>{if(e.bounds.width===0||e.bounds.height===0)return!1;let t=e.className.includes("ScrollView")||e.className.includes("RecyclerView")||e.className.includes("ListView")||e.className.includes("NestedScrollView");return e.scrollable||t})}function ji(a,e=I.screen.fallbackWidth,t=I.screen.fallbackHeight,s=I.visual.overlapRatio){let i=[];for(let u of a)(u.text||u.clickable)&&u.bounds.width>0&&(u.bounds.x2>e+10&&u.bounds.x1<e&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${u.text||u.contentDesc||u.className}" overflows right screen boundary by ${u.bounds.x2-e}px`,elements:[u.text||u.contentDesc||u.className]}),u.bounds.y2>t+20&&u.bounds.y1<t&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${u.text||u.contentDesc||u.className}" overflows bottom screen boundary by ${u.bounds.y2-t}px`,elements:[u.text||u.contentDesc||u.className]}));let n=a.filter(u=>u.text&&u.text.trim().length>1&&u.bounds.width>0&&u.bounds.height>0),r=200,o=new Map;for(let u of n){let h=Math.floor(u.bounds.y1/r),g=Math.floor(u.bounds.y2/r);for(let b=h;b<=g;b++)o.has(b)||o.set(b,[]),o.get(b).push(u)}let c=new Set;for(let[,u]of o)for(let h=0;h<u.length;h++)for(let g=h+1;g<u.length;g++){let b=u[h],T=u[g];if(b===T||b.text===T.text)continue;let x=b.bounds.x1<T.bounds.x1?`${b.bounds.x1},${b.bounds.y1}:${T.bounds.x1},${T.bounds.y1}`:`${T.bounds.x1},${T.bounds.y1}:${b.bounds.x1},${b.bounds.y1}`;if(c.has(x))continue;c.add(x);let S=b.bounds,y=T.bounds;if(Math.abs(S.centerY-y.centerY)>(S.height+y.height)/2)continue;let P=Math.max(0,Math.min(S.x2,y.x2)-Math.max(S.x1,y.x1)),$=Math.max(0,Math.min(S.y2,y.y2)-Math.max(S.y1,y.y1)),R=P*$;if(R>0){let C=S.width*S.height,B=y.width*y.height,U=Math.min(C,B);U>0&&R/U>s&&i.push({type:"OVERLAP",severity:"WARN",description:`Visual text collision: "${b.text}" overlaps with "${T.text}" (${Math.round(R)}px\xB2 collision)`,elements:[b.text,T.text]})}}let l=a.filter(u=>(u.className.includes("ProgressBar")||u.className.includes("ActivityIndicator"))&&u.bounds.width>0);l.length>0&&i.push({type:"STALLED_LOADER",severity:"WARN",description:`Active loading indicator (${l[0].className}) detected on screen`,elements:l.map(u=>u.className)});let p=[],d=new Set;for(let u of i){let h=`${u.type}::${[...u.elements].sort().join("::")}`;d.has(h)||(d.add(h),p.push(u))}return p}function Ts(a,e,t){let s=e?.height||I.screen.fallbackHeight,i=e?.width||I.screen.fallbackWidth,n=ot(a,s,t);if(n.length>1&&n[0].bounds.centerY>=s*.75)return{paradigm:"bottom_tabs",roots:n};let r=s*.05,o=s*.22,c=a.filter(p=>{if(_e(p)||t&&p.packageName&&!p.packageName.includes(t))return!1;let d=p.className.includes("Tab")||p.resourceId.toLowerCase().includes("tab")||p.resourceId.toLowerCase().includes("header_tab")||/(?:tab\s*\d|\bphotos\b|\bvideos\b|\baudios\b)/i.test(`${p.text} ${p.contentDesc}`),u=p.bounds.centerY>=r&&p.bounds.centerY<=o,h=p.bounds.height>25&&p.bounds.height<=220;return(d||u)&&p.clickable&&p.bounds.width>50&&h});if(c.length>=2){let p=[];for(let u of c){let h=p.find(g=>Math.abs(g[0].bounds.centerY-u.bounds.centerY)<=20);h||(h=[],p.push(h)),h.push(u)}let d=p.find(u=>u.length>=2);if(d){d.sort((g,b)=>g.bounds.centerX-b.bounds.centerX);let u=[];for(let g of d)u.some(b=>Math.abs(b.bounds.centerX-g.bounds.centerX)<40)||u.push(g);if(!(u.length===2&&u[0].bounds.x1<=i*.25&&u[1].bounds.x2>=i*.75&&!u.some(g=>g.className.includes("Tab")||g.resourceId.toLowerCase().includes("tab")))&&u.length>=2)return{paradigm:"top_tabs",roots:u.slice(0,5)}}}let l=at(a,s,i);return l?{paradigm:"drawer",roots:[l]}:{paradigm:"single_hub",roots:[]}}function Yi(a,e=2){if(a.length<=e)return a;let t=[];for(let i of a){let n=t.find(r=>{let o=r[0],c=o.className===i.className,l=Math.abs(o.bounds.width-i.bounds.width)<=30,p=Math.abs(o.bounds.height-i.bounds.height)<=30,d=Math.abs(o.bounds.x1-i.bounds.x1)<=30;return c&&l&&p&&d});n||(n=[],t.push(n)),n.push(i)}let s=[];for(let i of t)s.push(...i.slice(0,e));return s}function He(a,e=I.screen.fallbackHeight,t=I.screen.fallbackWidth,s=!1){let i=e*.22,n=t*.28,r=/(?:navigate[_\s-]*up|go[_\s-]*back|^back$|\bback\b|arrow_back|ic_arrow_back|chevron[_\s-]*left|ic_back|btn_back|action_bar_up|header[_\s-]*left|prev(?:ious)?|^close$|\bclose\b|^cancel$|^dismiss$|^done$|^exit$|[<←«‹❮⟨◁◀✕✖×]|\u2190|\u2196|\u2039|\u27E8|\u276E|\u25C1|\u25C0|\u00AB|\u2715|\u2716|\u00D7|[\uF060\uF104\uF053\uF2EA\uF00D\uE5C4\uE5CD])/i,o=c=>c.bounds.width>0&&c.bounds.height>0&&c.bounds.centerY<=i;for(let c of a){if(_e(c)||!o(c))continue;let l=`${c.text||""} ${c.contentDesc||""} ${c.resourceId||""}`.trim();if(r.test(l)||l.length<=2&&/^[<‹«←x✕×\-]$/i.test(l))return c.clickable?c:a.find(d=>d.clickable&&d.bounds.x1<=c.bounds.x1&&d.bounds.x2>=c.bounds.x2&&d.bounds.y1<=c.bounds.y1&&d.bounds.y2>=c.bounds.y2&&d.bounds.width<=300&&d.bounds.height<=300)||c}for(let c of a){if(_e(c)||!o(c)||c.bounds.x1>n)continue;if(c.className.includes("ImageButton")||c.className.includes("ImageView")||c.className.includes("ViewGroup")&&c.bounds.width<=250&&c.bounds.height<=250){let p=`${c.text||""} ${c.contentDesc||""} ${c.resourceId||""}`.toLowerCase();if(p.includes("back")||p.includes("up")||p.includes("arrow")||p.includes("chevron")||p.includes("nav")||p.includes("close")||p.includes("cancel"))return c.clickable?c:a.find(u=>u.clickable&&u.bounds.x1<=c.bounds.x1&&u.bounds.x2>=c.bounds.x2&&u.bounds.y1<=c.bounds.y1&&u.bounds.y2>=c.bounds.y2)||c}}if(s){let c=a.find(l=>{if(_e(l)||!o(l)||!l.clickable)return!1;let p=l.bounds.x1<=n,d=l.bounds.width<=250&&l.bounds.height<=250;return p&&d&&l.bounds.width<t*.4});if(c)return c}return null}import et from"fs";import ct from"path";import Gt from"fs";import Xt from"path";import sn from"crypto";import rn from"os";var Wi="prompttest_ed25519_offline_sig_k9284j2f91kd";function nn(){let a=Xt.resolve(process.cwd(),".prompttest");if(Gt.existsSync(a))return Xt.join(a,"license.json");let e=Xt.join(rn.homedir(),".prompttest");if(!Gt.existsSync(e))try{Gt.mkdirSync(e,{recursive:!0})}catch{return Xt.resolve(process.cwd(),".prompttest_license.json")}return Xt.join(e,"license.json")}function on(a,e=Wi){if(!a||typeof a!="string")return{valid:!1,error:"License key is empty."};let t=a.trim();if(!t.startsWith("PTPRO-")||!t.includes("."))return{valid:!1,error:"Invalid license key format. Expected PTPRO-<payload>.<signature>"};let i=t.slice(6).split(".");if(i.length!==2)return{valid:!1,error:"Corrupted license key structure."};let[n,r]=i,o=sn.createHmac("sha256",e);o.update(n);let c=o.digest("hex").slice(0,32);if(r!==c)return{valid:!1,error:"Invalid license signature or altered key."};try{let l=Buffer.from(n,"base64url").toString("utf-8"),p=JSON.parse(l);return p.expiresAt>0&&Date.now()>p.expiresAt?{valid:!1,payload:p,error:`License expired on ${new Date(p.expiresAt).toLocaleDateString()}.`}:{valid:!0,payload:p}}catch{return{valid:!1,error:"Failed to decode license payload."}}}function Ps(a=Wi){try{let e=nn();if(!Gt.existsSync(e))return{active:!1,tier:"free",whiteLabel:!1,features:[]};let t=Gt.readFileSync(e,"utf-8"),s=JSON.parse(t),i=on(s.key,a);return!i.valid||!i.payload?{active:!1,tier:"free",whiteLabel:!1,features:[]}:{active:!0,tier:i.payload.tier,holder:i.payload.holder,expiresAt:i.payload.expiresAt>0?new Date(i.payload.expiresAt).toISOString():"Perpetual",whiteLabel:i.payload.whiteLabel,features:i.payload.features||[]}}catch{return{active:!1,tier:"free",whiteLabel:!1,features:[]}}}var lt=class{outputDir;steps=[];errorsDetected=[];startTime=new Date;packageName="Unknown";deviceId="Unknown";pendingWrites=[];formats=["json","md","junit","html"];videoPath;embedScreenshots=!1;performanceMetrics;screenshotBuffers=new Map;stepListeners=[];completeListeners=[];errorListeners=[];setPerformanceMetrics(e){this.performanceMetrics=e}constructor(e,t){typeof e=="object"&&e!==null?(this.outputDir=e.outputDir||ct.resolve(process.cwd(),"output"),e.formats&&e.formats.length>0&&(this.formats=e.formats),this.embedScreenshots=!!e.embedScreenshots):(this.outputDir=e||ct.resolve(process.cwd(),"output"),t&&t.length>0&&(this.formats=t)),et.existsSync(this.outputDir)||et.mkdirSync(this.outputDir,{recursive:!0})}setEmbedScreenshots(e){this.embedScreenshots=e}onStep(e){return this.stepListeners.push(e),()=>{let t=this.stepListeners.indexOf(e);t!==-1&&this.stepListeners.splice(t,1)}}onComplete(e){return this.completeListeners.push(e),()=>{let t=this.completeListeners.indexOf(e);t!==-1&&this.completeListeners.splice(t,1)}}onError(e){return this.errorListeners.push(e),()=>{let t=this.errorListeners.indexOf(e);t!==-1&&this.errorListeners.splice(t,1)}}setFormats(e){this.formats=e}setVideoPath(e){this.videoPath=e}init(e,t){this.packageName=e,this.deviceId=t,this.startTime=new Date,this.steps=[],this.errorsDetected=[],this.pendingWrites=[],this.videoPath=void 0,this.screenshotBuffers.clear()}clearScreenshotBuffers(){this.screenshotBuffers.clear()}logStep(e,t,s,i,n,r,o,c,l){let p=this.steps.length+1,d;if(r){this.embedScreenshots&&this.screenshotBuffers.set(p,r);let g=`step_${p}_${e.toLowerCase().replace(/[^a-z0-9]/g,"_")}.png`,b=ct.join(this.outputDir,g),T=et.promises.writeFile(b,r).catch(x=>{console.error(`Warning: Failed to write screenshot ${g}:`,x)}).finally(()=>{let x=this.pendingWrites.indexOf(T);x!==-1&&this.pendingWrites.splice(x,1)});this.pendingWrites.push(T),d=g}let u=typeof o?.videoOffsetMs=="number"?o.videoOffsetMs:void 0,h={stepIndex:p,timestamp:new Date().toISOString(),phase:e,description:t,action:s,target:n,status:i,screenshotPath:d,durationMs:c,triageBundle:l,videoOffsetMs:u,details:o};this.steps.push(h);for(let g of this.stepListeners)try{g(h)}catch{}return h}logError(e){this.errorsDetected.push(e);for(let t of this.errorListeners)try{t(e)}catch{}}async generateReport(e){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites);let t=new Date,s=Math.round((t.getTime()-this.startTime.getTime())/1e3),i=[];for(let o of this.steps){let c=o.details;c?.healedFrom&&(c?.healedTo||o.target)&&i.push({original:String(c.healedFrom),healed:String(c.healedTo||o.target),stepNumber:o.stepIndex})}let n={packageName:this.packageName,deviceId:this.deviceId,startTime:this.startTime.toISOString(),endTime:t.toISOString(),durationSeconds:s,totalSteps:this.steps.length,passedSteps:this.steps.filter(o=>o.status==="PASS").length,failedSteps:this.steps.filter(o=>o.status==="FAIL").length,skippedSteps:this.steps.filter(o=>o.status==="SKIPPED").length,warnSteps:this.steps.filter(o=>o.status==="WARN").length,errorsDetected:this.errorsDetected,videoPath:this.videoPath,performanceMetrics:this.performanceMetrics,healsApplied:i.length>0?i:void 0,steps:this.steps},r=e||"prompttest";if(this.formats.includes("json")){let o=ct.join(this.outputDir,`${r}-results.json`);await et.promises.writeFile(o,JSON.stringify(n,null,2),"utf-8")}if(this.formats.includes("md")){let o=ct.join(this.outputDir,`${r}-report.md`),c=this.formatMarkdownReport(n);await et.promises.writeFile(o,c,"utf-8")}if(this.formats.includes("junit")){let o=ct.join(this.outputDir,`${r}-junit.xml`),c=this.formatJunitXml(n,r);await et.promises.writeFile(o,c,"utf-8")}if(this.formats.includes("html")){let o=ct.join(this.outputDir,`${r}-report.html`),c=this.formatHtmlReport(n,r);await et.promises.writeFile(o,c,"utf-8")}for(let o of this.completeListeners)try{o(n)}catch{}return this.clearScreenshotBuffers(),n}escapeXml(e){return(e||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}escapeHtml(e){return(e||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}formatJunitXml(e,t){let s=e.durationSeconds,i=e.failedSteps+(e.errorsDetected.length>0&&e.failedSteps===0?1:0),n=['<?xml version="1.0" encoding="UTF-8"?>',`<testsuites name="PromptTest" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`,` <testsuite name="${this.escapeXml(t)}" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`];for(let r of e.steps){let o=`Step ${r.stepIndex}: ${this.escapeXml(r.action)} - ${this.escapeXml(r.description)}`,c=r.durationMs!==void 0?(r.durationMs/1e3).toFixed(3):"1.000";n.push(` <testcase classname="${this.escapeXml(t)}" name="${o}" time="${c}">`),r.status==="FAIL"?n.push(` <failure message="${this.escapeXml(r.description)}">${this.escapeXml(r.description)}</failure>`):r.status==="SKIPPED"&&n.push(` <skipped message="${this.escapeXml(r.description)}"/>`),n.push(" </testcase>")}return e.failedSteps===0&&e.errorsDetected.length>0&&n.push(` <testcase classname="${this.escapeXml(t)}" name="Error Sentinel Crash Detection" time="0.000">`,` <failure message="${this.escapeXml(e.errorsDetected[0])}">${this.escapeXml(e.errorsDetected.join(`
|
|
38
|
+
`))}</failure>`," </testcase>"),n.push(" </testsuite>"),n.push("</testsuites>"),n.join(`
|
|
39
|
+
`)}formatMarkdownReport(e){let i=["# \u{1F9EA} PromptTest Autonomous Mobile QA Audit Report","",`**Status:** ${e.failedSteps===0&&e.errorsDetected.length===0?"\u2705 ALL PASSED":"\u26A0\uFE0F ISSUES DETECTED"} `,`**Target Package:** \`${e.packageName}\` `,`**Device:** \`${e.deviceId}\` `,`**Execution Time:** ${e.durationSeconds}s (${e.startTime} to ${e.endTime}) `];if(e.videoPath&&i.push(`**Screen Recording:** [Download Video](./${e.videoPath}) `),i.push("","---","","## \u{1F4CA} Executive Summary","","| Metric | Count |","|---|---|",`| **Total Steps** | ${e.totalSteps} |`,`| **Passed** | \u{1F7E2} ${e.passedSteps} |`,`| **Warnings** | \u{1F7E1} ${e.warnSteps} |`,`| **Failures** | \u{1F534} ${e.failedSteps} |`,`| **Skipped** | \u26AA ${e.skippedSteps} |`,`| **Errors Detected** | ${e.errorsDetected.length} |`,""),e.errorsDetected.length>0){i.push("## \u26A0\uFE0F Errors & Sentinels Flagged");for(let o of e.errorsDetected)i.push(`- \u{1F534} \`${o}\``);i.push("")}i.push("## \u{1F50D} Detailed Execution Timeline"),i.push(""),i.push("| Step | Phase | Action | Target / Details | Status | Duration | Screenshot / Triage |"),i.push("|---|---|---|---|---|---|---|");let n=o=>(o||"").replace(/\|/g,"\\|").replace(/\r?\n/g," ");for(let o of e.steps){let c="\u2014";o.triageBundle?c=`[\u{1F50D} Triage Bundle](./${o.triageBundle})`:o.screenshotPath&&(c=`[\u{1F4F8} Screenshot](./${o.screenshotPath})`);let l=o.durationMs!==void 0?`${o.durationMs}ms`:"\u2014",p=o.status==="PASS"?"\u{1F7E2} PASS":o.status==="WARN"?"\u{1F7E1} WARN":o.status==="SKIPPED"?"\u26AA SKIPPED":"\u{1F534} FAIL";i.push(`| ${o.stepIndex} | ${n(o.phase)} | ${n(o.action)} | ${n(o.description)} | ${p} | ${l} | ${c} |`)}i.push(""),e.performanceMetrics&&(i.push("## \u26A1 Mobile Performance & FPS Profiler (PF-01)"),i.push(""),i.push(`- **60 FPS Compliance:** ${e.performanceMetrics.fpsCompliance}`),i.push(`- **Total Frames Rendered:** ${e.performanceMetrics.frames.totalFrames.toLocaleString()}`),i.push(`- **Janky Frames:** ${e.performanceMetrics.frames.jankyFrames} (${e.performanceMetrics.frames.jankPercentage}%)`),e.performanceMetrics.frames.p95Ms!==void 0&&i.push(`- **95th Percentile Frame Time:** ${e.performanceMetrics.frames.p95Ms}ms`),i.push(`- **Peak Memory (PSS):** ${Math.round(e.performanceMetrics.memory.peakPssKb/1024)} MB`),i.push(""));let r=Ps();return i.push("---"),r.whiteLabel?i.push("*Generated autonomously by Mobile QA Brain.*"):i.push("*Generated autonomously by [PromptTest](https://prompttest.dev) Mobile QA Brain.*"),i.join(`
|
|
40
|
+
`)}resolveScreenshotData(e){if(e.screenshotPath){if(this.embedScreenshots){if(this.screenshotBuffers.has(e.stepIndex))return`data:image/png;base64,${this.screenshotBuffers.get(e.stepIndex).toString("base64")}`;let t=ct.join(this.outputDir,e.screenshotPath);if(et.existsSync(t))try{return`data:image/png;base64,${et.readFileSync(t).toString("base64")}`}catch{}}return`./${e.screenshotPath}`}}formatHtmlReport(e,t){return Es(e,{suiteName:t,embedScreenshots:this.embedScreenshots,screenshotResolver:s=>this.resolveScreenshotData(s)})}};function Es(a,e){let t=e?.suiteName||"PromptTest Suite",s=a.failedSteps===0&&a.errorsDetected.length===0,i=s?"ALL PASSED":"ISSUES DETECTED",n=s?"#10b981":"#ef4444",r=a.totalSteps,o=r>0?Math.round(a.passedSteps/r*100):100,c=Ps(),l=g=>(g||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),p=[],d=a.steps.map(g=>{let b=g.status.toLowerCase(),T=g.durationMs!==void 0?`${g.durationMs}ms`:"\u2014",x=e?.screenshotResolver?e.screenshotResolver(g):g.screenshotPath?`./${g.screenshotPath}`:void 0;x&&p.push({stepIndex:g.stepIndex,action:g.action,description:g.description,status:g.status,src:x,durationMs:g.durationMs});let S="\u2014";if(g.triageBundle){let B=l(g.triageBundle),U=g.triageBundle.endsWith(".zip"),Z=U?B:`${B}.zip`,W=U?B.replace(/\.zip$/,""):B;S=`
|
|
41
|
+
<div class="triage-bundle-links">
|
|
42
|
+
<a class="btn-triage btn-download-zip" href="./${Z}" download title="Download Diagnostic Triage ZIP Package">\u{1F4E6} Download ZIP</a>
|
|
43
|
+
<a class="btn-triage" href="./${W}" target="_blank" title="Browse Failure Diagnostic Directory">\u{1F50D} Triage Folder</a>
|
|
44
|
+
<div class="triage-files">
|
|
45
|
+
<a href="./${W}/screenshot.png" target="_blank" class="mini-link">\u{1F4F8} Shot</a>
|
|
46
|
+
<a href="./${W}/hierarchy.xml" target="_blank" class="mini-link">\u{1F4C4} XML</a>
|
|
47
|
+
<a href="./${W}/logcat_tail.log" target="_blank" class="mini-link">\u{1F4DC} Logcat</a>
|
|
48
|
+
<a href="./${W}/match_scores.json" target="_blank" class="mini-link">\u{1F3AF} Scores</a>
|
|
49
|
+
</div>
|
|
50
|
+
</div>`}else x&&(S=`
|
|
51
|
+
<div class="screenshot-cell">
|
|
52
|
+
<img src="${x}" class="thumb" alt="Step ${g.stepIndex}" onclick="openLightboxByStep(${g.stepIndex})" title="Click to view in full-screen Lightbox"/>
|
|
53
|
+
<button class="btn-zoom" onclick="openLightboxByStep(${g.stepIndex})" title="Enlarge Screenshot">\u{1F50D}</button>
|
|
54
|
+
</div>`);let y="";if(g.details&&(typeof g.details.diffPercent=="number"||g.details.diffPath||g.details.baselinePath)){let B=typeof g.details.diffPercent=="number"?`${(g.details.diffPercent*100).toFixed(2)}%`:"N/A",U=typeof g.details.threshold=="number"?`${(g.details.threshold*100).toFixed(2)}%`:"2.00%";y=`
|
|
55
|
+
<div class="diff-viewer-card">
|
|
56
|
+
<div class="diff-header">
|
|
57
|
+
<span class="badge diff-badge">Visual Diff: ${l(B)}</span>
|
|
58
|
+
<span class="diff-meta">Threshold: ${l(U)}</span>
|
|
59
|
+
</div>
|
|
60
|
+
<div class="diff-grid">
|
|
61
|
+
${g.details.baselinePath?`<div class="diff-pane"><div class="pane-label">Baseline</div><img src="./${l(String(g.details.baselinePath))}" class="diff-thumb" onclick="openLightboxCustom('./${l(String(g.details.baselinePath))}', 'Baseline Screenshot')"/></div>`:""}
|
|
62
|
+
${x?`<div class="diff-pane"><div class="pane-label">Actual Screen</div><img src="${x}" class="diff-thumb" onclick="openLightboxCustom('${x}', 'Actual Screenshot')"/></div>`:""}
|
|
63
|
+
${g.details.diffPath?`<div class="diff-pane"><div class="pane-label">Pixel Diff Overlay</div><img src="./${l(String(g.details.diffPath))}" class="diff-thumb" onclick="openLightboxCustom('./${l(String(g.details.diffPath))}', 'Visual Difference Overlay')"/></div>`:""}
|
|
64
|
+
</div>
|
|
65
|
+
</div>`}let P="";g.details&&Object.keys(g.details).length>0&&(P=`
|
|
66
|
+
<details class="step-details">
|
|
67
|
+
<summary>Diagnostics & Context</summary>
|
|
68
|
+
<pre>${l(JSON.stringify(g.details,null,2))}</pre>
|
|
69
|
+
</details>`);let $=`${g.stepIndex} ${g.phase} ${g.action} ${g.description} ${g.target||""}`.toLowerCase(),R=typeof g.videoOffsetMs=="number"?g.videoOffsetMs:typeof g.details?.videoOffsetMs=="number"?g.details.videoOffsetMs:void 0,C=a.videoPath&&R!==void 0?`<button type="button" class="btn-video-jump" onclick="seekVideoTo(${R/1e3})" title="Jump video to ${(R/1e3).toFixed(1)}s">\u25B6 ${(R/1e3).toFixed(1)}s</button>`:"";return`
|
|
70
|
+
<tr class="step-row status-${b}" data-status="${b}" data-search="${l($)}">
|
|
71
|
+
<td class="col-num">${g.stepIndex}</td>
|
|
72
|
+
<td><span class="badge phase-badge">${l(g.phase)}</span></td>
|
|
73
|
+
<td>
|
|
74
|
+
<span class="badge action-badge">${l(g.action)}</span>
|
|
75
|
+
${C}
|
|
76
|
+
</td>
|
|
77
|
+
<td>
|
|
78
|
+
<div class="desc-text">${l(g.description)}</div>
|
|
79
|
+
${y}
|
|
80
|
+
${P}
|
|
81
|
+
</td>
|
|
82
|
+
<td><code>${l(g.target||"\u2014")}</code></td>
|
|
83
|
+
<td><span class="badge status-badge status-${b}">${g.status}</span></td>
|
|
84
|
+
<td class="col-duration">${T}</td>
|
|
85
|
+
<td class="col-artifact">${S}</td>
|
|
86
|
+
</tr>`}).join(`
|
|
87
|
+
`),u=a.videoPath?`
|
|
88
|
+
<section class="card video-card">
|
|
89
|
+
<div class="video-card-header">
|
|
90
|
+
<h3>\u{1F3AC} Session Screen Recording</h3>
|
|
91
|
+
<div class="video-playback-controls">
|
|
92
|
+
<span class="speed-label">Playback Speed:</span>
|
|
93
|
+
<button type="button" class="btn-speed" onclick="setPlaybackSpeed(0.5)">0.5x</button>
|
|
94
|
+
<button type="button" class="btn-speed active" onclick="setPlaybackSpeed(1)">1x</button>
|
|
95
|
+
<button type="button" class="btn-speed" onclick="setPlaybackSpeed(1.5)">1.5x</button>
|
|
96
|
+
<button type="button" class="btn-speed" onclick="setPlaybackSpeed(2)">2x</button>
|
|
97
|
+
</div>
|
|
98
|
+
</div>
|
|
99
|
+
<video id="session-recording-player" controls preload="metadata" class="recording-player" src="./${l(a.videoPath)}"></video>
|
|
100
|
+
</section>`:"",h=a.errorsDetected.length>0?`
|
|
101
|
+
<section class="card error-card">
|
|
102
|
+
<h3>\u26A0\uFE0F Critical Flagged Errors (${a.errorsDetected.length})</h3>
|
|
103
|
+
<ul class="error-list">
|
|
104
|
+
${a.errorsDetected.map(g=>`<li>\u{1F534} <code>${l(g)}</code></li>`).join(`
|
|
105
|
+
`)}
|
|
106
|
+
</ul>
|
|
107
|
+
</section>`:"";return`<!DOCTYPE html>
|
|
108
|
+
<html lang="en">
|
|
109
|
+
<head>
|
|
110
|
+
<meta charset="UTF-8">
|
|
111
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
112
|
+
<title>PromptTest QA Audit: ${l(t)}</title>
|
|
113
|
+
<style>
|
|
114
|
+
:root {
|
|
115
|
+
--bg: #0b0f19;
|
|
116
|
+
--card-bg: #151d30;
|
|
117
|
+
--card-border: #222f4c;
|
|
118
|
+
--border: #1e293b;
|
|
119
|
+
--text: #f1f5f9;
|
|
120
|
+
--text-muted: #94a3b8;
|
|
121
|
+
--primary: #3b82f6;
|
|
122
|
+
--primary-hover: #2563eb;
|
|
123
|
+
--success: #10b981;
|
|
124
|
+
--warning: #f59e0b;
|
|
125
|
+
--danger: #ef4444;
|
|
126
|
+
--skipped: #64748b;
|
|
127
|
+
}
|
|
128
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
129
|
+
body {
|
|
130
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
131
|
+
background: var(--bg);
|
|
132
|
+
color: var(--text);
|
|
133
|
+
line-height: 1.5;
|
|
134
|
+
padding: 24px;
|
|
135
|
+
}
|
|
136
|
+
.container { max-width: 1280px; margin: 0 auto; }
|
|
137
|
+
header {
|
|
138
|
+
display: flex;
|
|
139
|
+
justify-content: space-between;
|
|
140
|
+
align-items: center;
|
|
141
|
+
margin-bottom: 24px;
|
|
142
|
+
padding-bottom: 16px;
|
|
143
|
+
border-bottom: 1px solid var(--card-border);
|
|
144
|
+
flex-wrap: wrap;
|
|
145
|
+
gap: 16px;
|
|
146
|
+
}
|
|
147
|
+
.header-title h1 { font-size: 1.85rem; font-weight: 800; letter-spacing: -0.02em; margin-bottom: 4px; }
|
|
148
|
+
.header-meta { font-size: 0.9rem; color: var(--text-muted); }
|
|
149
|
+
.status-pill {
|
|
150
|
+
font-size: 0.95rem;
|
|
151
|
+
font-weight: 700;
|
|
152
|
+
padding: 8px 18px;
|
|
153
|
+
border-radius: 9999px;
|
|
154
|
+
color: #fff;
|
|
155
|
+
background: ${n};
|
|
156
|
+
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/* Pass Gauge & Statistics Grid */
|
|
160
|
+
.dashboard-grid {
|
|
161
|
+
display: grid;
|
|
162
|
+
grid-template-columns: 140px repeat(auto-fit, minmax(140px, 1fr));
|
|
163
|
+
gap: 16px;
|
|
164
|
+
margin-bottom: 24px;
|
|
165
|
+
}
|
|
166
|
+
.gauge-card {
|
|
167
|
+
background: var(--card-bg);
|
|
168
|
+
border: 1px solid var(--card-border);
|
|
169
|
+
border-radius: 10px;
|
|
170
|
+
padding: 12px;
|
|
171
|
+
display: flex;
|
|
172
|
+
flex-direction: column;
|
|
173
|
+
align-items: center;
|
|
174
|
+
justify-content: center;
|
|
175
|
+
}
|
|
176
|
+
.circular-chart {
|
|
177
|
+
width: 72px;
|
|
178
|
+
height: 72px;
|
|
179
|
+
}
|
|
180
|
+
.circle-bg {
|
|
181
|
+
fill: none;
|
|
182
|
+
stroke: #1e293b;
|
|
183
|
+
stroke-width: 3.8;
|
|
184
|
+
}
|
|
185
|
+
.circle {
|
|
186
|
+
fill: none;
|
|
187
|
+
stroke-width: 3.8;
|
|
188
|
+
stroke-linecap: round;
|
|
189
|
+
transition: stroke-dasharray 0.6s ease;
|
|
190
|
+
}
|
|
191
|
+
.percentage {
|
|
192
|
+
fill: var(--text);
|
|
193
|
+
font-size: 0.55rem;
|
|
194
|
+
font-weight: bold;
|
|
195
|
+
text-anchor: middle;
|
|
196
|
+
}
|
|
197
|
+
.chart-label {
|
|
198
|
+
font-size: 0.72rem;
|
|
199
|
+
text-transform: uppercase;
|
|
200
|
+
color: var(--text-muted);
|
|
201
|
+
margin-top: 4px;
|
|
202
|
+
font-weight: 600;
|
|
203
|
+
}
|
|
204
|
+
.stat-card {
|
|
205
|
+
background: var(--card-bg);
|
|
206
|
+
border: 1px solid var(--card-border);
|
|
207
|
+
border-radius: 10px;
|
|
208
|
+
padding: 16px;
|
|
209
|
+
text-align: center;
|
|
210
|
+
display: flex;
|
|
211
|
+
flex-direction: column;
|
|
212
|
+
justify-content: center;
|
|
213
|
+
}
|
|
214
|
+
.stat-label { font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); margin-bottom: 6px; font-weight: 600; }
|
|
215
|
+
.stat-value { font-size: 1.6rem; font-weight: 800; }
|
|
216
|
+
.val-pass { color: var(--success); }
|
|
217
|
+
.val-fail { color: var(--danger); }
|
|
218
|
+
.val-warn { color: var(--warning); }
|
|
219
|
+
.val-skip { color: var(--skipped); }
|
|
220
|
+
|
|
221
|
+
.card {
|
|
222
|
+
background: var(--card-bg);
|
|
223
|
+
border: 1px solid var(--card-border);
|
|
224
|
+
border-radius: 10px;
|
|
225
|
+
padding: 20px;
|
|
226
|
+
margin-bottom: 24px;
|
|
227
|
+
}
|
|
228
|
+
.card h3 { margin-bottom: 12px; font-size: 1.15rem; }
|
|
229
|
+
.video-card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
|
|
230
|
+
.video-card-header h3 { margin-bottom: 0; }
|
|
231
|
+
.video-playback-controls { display: flex; align-items: center; gap: 6px; }
|
|
232
|
+
.speed-label { font-size: 0.8rem; color: var(--text-muted); font-weight: 600; }
|
|
233
|
+
.btn-speed {
|
|
234
|
+
background: var(--card-border);
|
|
235
|
+
color: var(--text-muted);
|
|
236
|
+
border: 1px solid var(--border);
|
|
237
|
+
border-radius: 4px;
|
|
238
|
+
padding: 3px 8px;
|
|
239
|
+
font-size: 0.75rem;
|
|
240
|
+
font-weight: 600;
|
|
241
|
+
cursor: pointer;
|
|
242
|
+
transition: all 0.2s;
|
|
243
|
+
}
|
|
244
|
+
.btn-speed:hover, .btn-speed.active {
|
|
245
|
+
background: var(--primary);
|
|
246
|
+
color: #fff;
|
|
247
|
+
border-color: var(--primary);
|
|
248
|
+
}
|
|
249
|
+
.btn-video-jump {
|
|
250
|
+
display: inline-block;
|
|
251
|
+
margin-left: 6px;
|
|
252
|
+
background: rgba(59, 130, 246, 0.15);
|
|
253
|
+
border: 1px solid rgba(59, 130, 246, 0.35);
|
|
254
|
+
color: #93c5fd;
|
|
255
|
+
border-radius: 4px;
|
|
256
|
+
padding: 1px 6px;
|
|
257
|
+
font-size: 0.72rem;
|
|
258
|
+
cursor: pointer;
|
|
259
|
+
font-family: monospace;
|
|
260
|
+
font-weight: 600;
|
|
261
|
+
transition: all 0.2s;
|
|
262
|
+
}
|
|
263
|
+
.btn-video-jump:hover {
|
|
264
|
+
background: var(--primary);
|
|
265
|
+
color: #fff;
|
|
266
|
+
}
|
|
267
|
+
.video-card video { max-width: 100%; border-radius: 8px; border: 1px solid var(--card-border); }
|
|
268
|
+
|
|
269
|
+
/* Filter & Search Toolbar */
|
|
270
|
+
.toolbar {
|
|
271
|
+
display: flex;
|
|
272
|
+
justify-content: space-between;
|
|
273
|
+
align-items: center;
|
|
274
|
+
gap: 16px;
|
|
275
|
+
margin-bottom: 16px;
|
|
276
|
+
flex-wrap: wrap;
|
|
277
|
+
}
|
|
278
|
+
.filter-bar { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
279
|
+
.filter-btn {
|
|
280
|
+
background: #1e293b;
|
|
281
|
+
border: 1px solid var(--card-border);
|
|
282
|
+
color: var(--text-muted);
|
|
283
|
+
padding: 7px 16px;
|
|
284
|
+
border-radius: 6px;
|
|
285
|
+
cursor: pointer;
|
|
286
|
+
font-size: 0.85rem;
|
|
287
|
+
font-weight: 600;
|
|
288
|
+
transition: all 0.2s ease;
|
|
289
|
+
}
|
|
290
|
+
.filter-btn:hover { background: #334155; color: #fff; }
|
|
291
|
+
.filter-btn.active {
|
|
292
|
+
background: var(--primary);
|
|
293
|
+
color: #fff;
|
|
294
|
+
border-color: var(--primary);
|
|
295
|
+
}
|
|
296
|
+
.search-box input {
|
|
297
|
+
background: #0f172a;
|
|
298
|
+
border: 1px solid var(--card-border);
|
|
299
|
+
border-radius: 6px;
|
|
300
|
+
color: #fff;
|
|
301
|
+
padding: 8px 14px;
|
|
302
|
+
font-size: 0.85rem;
|
|
303
|
+
min-width: 280px;
|
|
304
|
+
outline: none;
|
|
305
|
+
transition: border 0.2s;
|
|
306
|
+
}
|
|
307
|
+
.search-box input:focus { border-color: var(--primary); }
|
|
308
|
+
|
|
309
|
+
/* Table Styles */
|
|
310
|
+
table { width: 100%; border-collapse: collapse; text-align: left; }
|
|
311
|
+
th {
|
|
312
|
+
background: #0f172a;
|
|
313
|
+
padding: 12px 14px;
|
|
314
|
+
font-size: 0.78rem;
|
|
315
|
+
text-transform: uppercase;
|
|
316
|
+
letter-spacing: 0.04em;
|
|
317
|
+
color: var(--text-muted);
|
|
318
|
+
border-bottom: 2px solid var(--card-border);
|
|
319
|
+
}
|
|
320
|
+
td { padding: 12px 14px; border-bottom: 1px solid var(--card-border); font-size: 0.9rem; vertical-align: top; }
|
|
321
|
+
tr:hover td { background: rgba(255,255,255,0.02); }
|
|
322
|
+
|
|
323
|
+
.badge {
|
|
324
|
+
display: inline-block;
|
|
325
|
+
padding: 3px 8px;
|
|
326
|
+
border-radius: 4px;
|
|
327
|
+
font-size: 0.75rem;
|
|
328
|
+
font-weight: 600;
|
|
329
|
+
white-space: nowrap;
|
|
330
|
+
}
|
|
331
|
+
.phase-badge { background: #1e293b; color: #94a3b8; }
|
|
332
|
+
.action-badge { background: #334155; color: #cbd5e1; font-family: monospace; }
|
|
333
|
+
.status-badge.status-pass { background: rgba(16, 185, 129, 0.2); color: var(--success); }
|
|
334
|
+
.status-badge.status-fail { background: rgba(239, 68, 68, 0.2); color: var(--danger); }
|
|
335
|
+
.status-badge.status-warn { background: rgba(245, 158, 11, 0.2); color: var(--warning); }
|
|
336
|
+
.status-badge.status-skipped { background: rgba(100, 116, 139, 0.2); color: var(--skipped); }
|
|
337
|
+
|
|
338
|
+
.col-num { width: 44px; font-weight: bold; color: var(--text-muted); }
|
|
339
|
+
.col-duration { font-family: monospace; font-size: 0.85rem; color: var(--text-muted); white-space: nowrap; }
|
|
340
|
+
.col-artifact { min-width: 130px; }
|
|
341
|
+
.desc-text { font-weight: 500; margin-bottom: 4px; }
|
|
342
|
+
|
|
343
|
+
/* Screenshot & Thumbnails */
|
|
344
|
+
.screenshot-cell { display: flex; align-items: center; gap: 6px; }
|
|
345
|
+
.thumb {
|
|
346
|
+
width: 52px;
|
|
347
|
+
height: 52px;
|
|
348
|
+
object-fit: cover;
|
|
349
|
+
border-radius: 6px;
|
|
350
|
+
border: 1px solid var(--card-border);
|
|
351
|
+
cursor: pointer;
|
|
352
|
+
transition: transform 0.2s, box-shadow 0.2s;
|
|
353
|
+
}
|
|
354
|
+
.thumb:hover {
|
|
355
|
+
transform: scale(1.08);
|
|
356
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
|
|
357
|
+
}
|
|
358
|
+
.btn-zoom {
|
|
359
|
+
background: transparent;
|
|
360
|
+
border: none;
|
|
361
|
+
cursor: pointer;
|
|
362
|
+
font-size: 0.9rem;
|
|
363
|
+
color: var(--text-muted);
|
|
364
|
+
}
|
|
365
|
+
.btn-zoom:hover { color: var(--primary); }
|
|
366
|
+
|
|
367
|
+
/* Failure Triage Links */
|
|
368
|
+
.triage-bundle-links { display: flex; flex-direction: column; gap: 4px; }
|
|
369
|
+
.btn-triage {
|
|
370
|
+
display: inline-block;
|
|
371
|
+
padding: 4px 8px;
|
|
372
|
+
background: rgba(239, 68, 68, 0.2);
|
|
373
|
+
border: 1px solid rgba(239, 68, 68, 0.4);
|
|
374
|
+
color: #fca5a5;
|
|
375
|
+
border-radius: 4px;
|
|
376
|
+
text-decoration: none;
|
|
377
|
+
font-size: 0.75rem;
|
|
378
|
+
font-weight: 600;
|
|
379
|
+
text-align: center;
|
|
380
|
+
transition: all 0.2s;
|
|
381
|
+
}
|
|
382
|
+
.btn-triage:hover {
|
|
383
|
+
background: rgba(239, 68, 68, 0.35);
|
|
384
|
+
color: #fff;
|
|
385
|
+
}
|
|
386
|
+
.btn-triage.btn-download-zip {
|
|
387
|
+
background: #dc2626;
|
|
388
|
+
border: 1px solid #b91c1c;
|
|
389
|
+
color: #fff;
|
|
390
|
+
font-weight: 700;
|
|
391
|
+
box-shadow: 0 2px 6px rgba(220, 38, 38, 0.3);
|
|
392
|
+
}
|
|
393
|
+
.btn-triage.btn-download-zip:hover {
|
|
394
|
+
background: #b91c1c;
|
|
395
|
+
}
|
|
396
|
+
.triage-files { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 4px; }
|
|
397
|
+
.mini-link {
|
|
398
|
+
font-size: 0.72rem;
|
|
399
|
+
color: var(--primary);
|
|
400
|
+
text-decoration: none;
|
|
401
|
+
background: rgba(59, 130, 246, 0.1);
|
|
402
|
+
padding: 2px 6px;
|
|
403
|
+
border-radius: 3px;
|
|
404
|
+
}
|
|
405
|
+
.mini-link:hover { text-decoration: underline; }
|
|
406
|
+
|
|
407
|
+
/* Visual Diff Viewer */
|
|
408
|
+
.diff-viewer-card {
|
|
409
|
+
margin-top: 8px;
|
|
410
|
+
background: #0f172a;
|
|
411
|
+
border: 1px solid var(--card-border);
|
|
412
|
+
border-radius: 6px;
|
|
413
|
+
padding: 10px;
|
|
414
|
+
}
|
|
415
|
+
.diff-header {
|
|
416
|
+
display: flex;
|
|
417
|
+
justify-content: space-between;
|
|
418
|
+
align-items: center;
|
|
419
|
+
margin-bottom: 8px;
|
|
420
|
+
}
|
|
421
|
+
.diff-badge { background: rgba(245, 158, 11, 0.2); color: var(--warning); font-size: 0.75rem; }
|
|
422
|
+
.diff-meta { font-size: 0.75rem; color: var(--text-muted); }
|
|
423
|
+
.diff-grid { display: flex; gap: 10px; flex-wrap: wrap; }
|
|
424
|
+
.diff-pane { display: flex; flex-direction: column; align-items: center; gap: 4px; }
|
|
425
|
+
.pane-label { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; }
|
|
426
|
+
.diff-thumb {
|
|
427
|
+
width: 72px;
|
|
428
|
+
height: 72px;
|
|
429
|
+
object-fit: cover;
|
|
430
|
+
border-radius: 4px;
|
|
431
|
+
border: 1px solid var(--card-border);
|
|
432
|
+
cursor: pointer;
|
|
433
|
+
}
|
|
434
|
+
.diff-thumb:hover { transform: scale(1.05); }
|
|
435
|
+
|
|
436
|
+
.step-details { margin-top: 6px; font-size: 0.8rem; }
|
|
437
|
+
.step-details summary { cursor: pointer; color: var(--primary); font-weight: 600; }
|
|
438
|
+
.step-details pre {
|
|
439
|
+
background: #0f172a;
|
|
440
|
+
padding: 8px 12px;
|
|
441
|
+
border-radius: 6px;
|
|
442
|
+
overflow-x: auto;
|
|
443
|
+
margin-top: 6px;
|
|
444
|
+
border: 1px solid var(--card-border);
|
|
445
|
+
font-size: 0.78rem;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/* Lightbox Modal */
|
|
449
|
+
.lightbox-modal {
|
|
450
|
+
display: none;
|
|
451
|
+
position: fixed;
|
|
452
|
+
top: 0; left: 0; width: 100vw; height: 100vh;
|
|
453
|
+
background: rgba(5, 8, 16, 0.92);
|
|
454
|
+
backdrop-filter: blur(8px);
|
|
455
|
+
z-index: 10000;
|
|
456
|
+
justify-content: center;
|
|
457
|
+
align-items: center;
|
|
458
|
+
flex-direction: column;
|
|
459
|
+
padding: 20px;
|
|
460
|
+
}
|
|
461
|
+
.lightbox-modal.active { display: flex; }
|
|
462
|
+
.lightbox-content {
|
|
463
|
+
max-width: 90vw;
|
|
464
|
+
max-height: 88vh;
|
|
465
|
+
display: flex;
|
|
466
|
+
flex-direction: column;
|
|
467
|
+
background: var(--card-bg);
|
|
468
|
+
border: 1px solid var(--card-border);
|
|
469
|
+
border-radius: 12px;
|
|
470
|
+
overflow: hidden;
|
|
471
|
+
box-shadow: 0 16px 40px rgba(0,0,0,0.7);
|
|
472
|
+
}
|
|
473
|
+
.lightbox-header {
|
|
474
|
+
display: flex;
|
|
475
|
+
justify-content: space-between;
|
|
476
|
+
align-items: center;
|
|
477
|
+
padding: 12px 18px;
|
|
478
|
+
background: #0f172a;
|
|
479
|
+
border-bottom: 1px solid var(--card-border);
|
|
480
|
+
gap: 12px;
|
|
481
|
+
}
|
|
482
|
+
.lightbox-title { font-size: 0.95rem; font-weight: 600; flex: 1; }
|
|
483
|
+
.lightbox-actions { display: flex; gap: 8px; align-items: center; }
|
|
484
|
+
.lightbox-btn {
|
|
485
|
+
background: #1e293b;
|
|
486
|
+
border: 1px solid var(--card-border);
|
|
487
|
+
color: #fff;
|
|
488
|
+
padding: 5px 12px;
|
|
489
|
+
border-radius: 6px;
|
|
490
|
+
cursor: pointer;
|
|
491
|
+
font-size: 0.85rem;
|
|
492
|
+
}
|
|
493
|
+
.lightbox-btn:hover { background: #334155; }
|
|
494
|
+
.lightbox-btn-close { background: #ef4444; border-color: #ef4444; font-weight: bold; }
|
|
495
|
+
.lightbox-btn-close:hover { background: #dc2626; }
|
|
496
|
+
.lightbox-body {
|
|
497
|
+
position: relative;
|
|
498
|
+
display: flex;
|
|
499
|
+
align-items: center;
|
|
500
|
+
justify-content: center;
|
|
501
|
+
padding: 16px;
|
|
502
|
+
background: #090d16;
|
|
503
|
+
overflow: auto;
|
|
504
|
+
max-height: calc(88vh - 110px);
|
|
505
|
+
}
|
|
506
|
+
.lightbox-img {
|
|
507
|
+
max-width: 100%;
|
|
508
|
+
max-height: 72vh;
|
|
509
|
+
object-fit: contain;
|
|
510
|
+
border-radius: 6px;
|
|
511
|
+
transition: transform 0.2s ease;
|
|
512
|
+
}
|
|
513
|
+
.lightbox-img.zoomed {
|
|
514
|
+
max-height: none;
|
|
515
|
+
max-width: none;
|
|
516
|
+
cursor: zoom-out;
|
|
517
|
+
}
|
|
518
|
+
.lightbox-nav {
|
|
519
|
+
position: absolute;
|
|
520
|
+
top: 50%;
|
|
521
|
+
transform: translateY(-50%);
|
|
522
|
+
background: rgba(15, 23, 42, 0.8);
|
|
523
|
+
border: 1px solid var(--card-border);
|
|
524
|
+
color: #fff;
|
|
525
|
+
font-size: 1.5rem;
|
|
526
|
+
width: 44px;
|
|
527
|
+
height: 44px;
|
|
528
|
+
border-radius: 50%;
|
|
529
|
+
cursor: pointer;
|
|
530
|
+
display: flex;
|
|
531
|
+
align-items: center;
|
|
532
|
+
justify-content: center;
|
|
533
|
+
transition: all 0.2s;
|
|
534
|
+
}
|
|
535
|
+
.lightbox-nav:hover { background: var(--primary); }
|
|
536
|
+
.lightbox-nav.prev { left: 16px; }
|
|
537
|
+
.lightbox-nav.next { right: 16px; }
|
|
538
|
+
.lightbox-footer {
|
|
539
|
+
display: flex;
|
|
540
|
+
justify-content: space-between;
|
|
541
|
+
align-items: center;
|
|
542
|
+
padding: 10px 18px;
|
|
543
|
+
background: #0f172a;
|
|
544
|
+
border-top: 1px solid var(--card-border);
|
|
545
|
+
font-size: 0.8rem;
|
|
546
|
+
color: var(--text-muted);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
footer { text-align: center; margin-top: 40px; color: var(--text-muted); font-size: 0.85rem; }
|
|
550
|
+
</style>
|
|
551
|
+
</head>
|
|
552
|
+
<body>
|
|
553
|
+
<div class="container">
|
|
554
|
+
<header>
|
|
555
|
+
<div class="header-title">
|
|
556
|
+
<h1>PromptTest QA Audit Report</h1>
|
|
557
|
+
<div class="header-meta">
|
|
558
|
+
<strong>Suite:</strong> <code>${l(t)}</code> •
|
|
559
|
+
<strong>App:</strong> <code>${l(a.packageName)}</code> •
|
|
560
|
+
<strong>Device:</strong> <code>${l(a.deviceId)}</code> •
|
|
561
|
+
<strong>Duration:</strong> ${a.durationSeconds}s (${a.startTime.substring(11,19)} to ${a.endTime.substring(11,19)})
|
|
562
|
+
</div>
|
|
563
|
+
</div>
|
|
564
|
+
<div class="status-pill">${i}</div>
|
|
565
|
+
</header>
|
|
566
|
+
|
|
567
|
+
<div class="dashboard-grid">
|
|
568
|
+
<div class="gauge-card">
|
|
569
|
+
<svg viewBox="0 0 36 36" class="circular-chart">
|
|
570
|
+
<path class="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
|
|
571
|
+
<path class="circle" stroke-dasharray="${o}, 100" stroke="${n}" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
|
|
572
|
+
<text x="18" y="20.35" class="percentage">${o}%</text>
|
|
573
|
+
</svg>
|
|
574
|
+
<div class="chart-label">Pass Rate</div>
|
|
575
|
+
</div>
|
|
576
|
+
<div class="stat-card">
|
|
577
|
+
<div class="stat-label">Total Steps</div>
|
|
578
|
+
<div class="stat-value">${a.totalSteps}</div>
|
|
579
|
+
</div>
|
|
580
|
+
<div class="stat-card">
|
|
581
|
+
<div class="stat-label">Passed</div>
|
|
582
|
+
<div class="stat-value val-pass">${a.passedSteps}</div>
|
|
583
|
+
</div>
|
|
584
|
+
<div class="stat-card">
|
|
585
|
+
<div class="stat-label">Failures</div>
|
|
586
|
+
<div class="stat-value val-fail">${a.failedSteps}</div>
|
|
587
|
+
</div>
|
|
588
|
+
<div class="stat-card">
|
|
589
|
+
<div class="stat-label">Warnings</div>
|
|
590
|
+
<div class="stat-value val-warn">${a.warnSteps}</div>
|
|
591
|
+
</div>
|
|
592
|
+
<div class="stat-card">
|
|
593
|
+
<div class="stat-label">Skipped</div>
|
|
594
|
+
<div class="stat-value val-skip">${a.skippedSteps}</div>
|
|
595
|
+
</div>
|
|
596
|
+
</div>
|
|
597
|
+
|
|
598
|
+
${u}
|
|
599
|
+
${h}
|
|
600
|
+
|
|
601
|
+
<section class="card">
|
|
602
|
+
<div class="toolbar">
|
|
603
|
+
<div class="filter-bar">
|
|
604
|
+
<button class="filter-btn active" data-filter="all" onclick="setFilter('all', this)">All (${a.totalSteps})</button>
|
|
605
|
+
<button class="filter-btn" data-filter="pass" onclick="setFilter('pass', this)">Passed (${a.passedSteps})</button>
|
|
606
|
+
<button class="filter-btn" data-filter="fail" onclick="setFilter('fail', this)">Failed (${a.failedSteps})</button>
|
|
607
|
+
<button class="filter-btn" data-filter="warn" onclick="setFilter('warn', this)">Warnings (${a.warnSteps})</button>
|
|
608
|
+
<button class="filter-btn" data-filter="skipped" onclick="setFilter('skipped', this)">Skipped (${a.skippedSteps})</button>
|
|
609
|
+
</div>
|
|
610
|
+
<div class="search-box">
|
|
611
|
+
<input type="text" id="filter-search" placeholder="\u{1F50D} Search steps, actions, targets..." oninput="applyFilters()"/>
|
|
612
|
+
</div>
|
|
613
|
+
</div>
|
|
614
|
+
|
|
615
|
+
<table>
|
|
616
|
+
<thead>
|
|
617
|
+
<tr>
|
|
618
|
+
<th>#</th>
|
|
619
|
+
<th>Phase</th>
|
|
620
|
+
<th>Action</th>
|
|
621
|
+
<th>Description & Diagnostics</th>
|
|
622
|
+
<th>Target</th>
|
|
623
|
+
<th>Status</th>
|
|
624
|
+
<th>Duration</th>
|
|
625
|
+
<th>Visual Artifacts</th>
|
|
626
|
+
</tr>
|
|
627
|
+
</thead>
|
|
628
|
+
<tbody id="steps-tbody">
|
|
629
|
+
${d}
|
|
630
|
+
</tbody>
|
|
631
|
+
</table>
|
|
632
|
+
${a.performanceMetrics?`
|
|
633
|
+
<section class="card" style="margin-top: 24px; border: 1px solid #1e293b; background: #0f172a; border-radius: 12px; padding: 20px;">
|
|
634
|
+
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
|
|
635
|
+
<h2 style="font-size: 1.1rem; font-weight: 600; color: #f8fafc; margin: 0; display: flex; align-items: center; gap: 8px;">
|
|
636
|
+
\u26A1 Mobile Performance & 60 FPS Profiler (PF-01)
|
|
637
|
+
</h2>
|
|
638
|
+
<span class="badge" style="background: ${a.performanceMetrics.fpsCompliance==="PASS"?"#065f46":a.performanceMetrics.fpsCompliance==="WARN"?"#92400e":"#991b1b"}; color: #fff; padding: 4px 10px; border-radius: 9999px; font-weight: 600; font-size: 0.75rem;">
|
|
639
|
+
${a.performanceMetrics.fpsCompliance==="PASS"?"\u2714 60 FPS COMPLIANT":a.performanceMetrics.fpsCompliance==="WARN"?"\u26A0 JANK WARNING":"\u2716 SEVERE JANK"}
|
|
640
|
+
</span>
|
|
641
|
+
</div>
|
|
642
|
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px;">
|
|
643
|
+
<div style="background: #1e293b; padding: 12px; border-radius: 8px;">
|
|
644
|
+
<div style="font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Total Frames</div>
|
|
645
|
+
<div style="font-size: 1.25rem; font-weight: 700; color: #f8fafc;">${a.performanceMetrics.frames.totalFrames.toLocaleString()}</div>
|
|
646
|
+
</div>
|
|
647
|
+
<div style="background: #1e293b; padding: 12px; border-radius: 8px;">
|
|
648
|
+
<div style="font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Janky Frames</div>
|
|
649
|
+
<div style="font-size: 1.25rem; font-weight: 700; color: ${a.performanceMetrics.frames.jankPercentage>5?"#f87171":"#34d399"};">
|
|
650
|
+
${a.performanceMetrics.frames.jankyFrames} (${a.performanceMetrics.frames.jankPercentage}%)
|
|
651
|
+
</div>
|
|
652
|
+
</div>
|
|
653
|
+
<div style="background: #1e293b; padding: 12px; border-radius: 8px;">
|
|
654
|
+
<div style="font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">95th Percentile</div>
|
|
655
|
+
<div style="font-size: 1.25rem; font-weight: 700; color: #f8fafc;">${a.performanceMetrics.frames.p95Ms!==void 0?a.performanceMetrics.frames.p95Ms+" ms":"\u2014"}</div>
|
|
656
|
+
</div>
|
|
657
|
+
<div style="background: #1e293b; padding: 12px; border-radius: 8px;">
|
|
658
|
+
<div style="font-size: 0.75rem; color: #94a3b8; text-transform: uppercase;">Peak PSS Memory</div>
|
|
659
|
+
<div style="font-size: 1.25rem; font-weight: 700; color: #38bdf8;">${Math.round(a.performanceMetrics.memory.peakPssKb/1024)} MB</div>
|
|
660
|
+
</div>
|
|
661
|
+
</div>
|
|
662
|
+
</section>`:""}
|
|
663
|
+
|
|
664
|
+
<footer>
|
|
665
|
+
${c.whiteLabel?`<span>Autonomous QA Execution Report • Rendered at ${new Date().toISOString()}</span>`:`<span>PromptTest Autonomous Mobile QA Brain • Rendered at ${new Date().toISOString()} • <a href="https://shriramsingh.github.io/prompttest-studio-site/" target="_blank" style="color: #60a5fa; text-decoration: none; font-weight: 500;">\u26A1 Powered by PromptTest Studio</a></span>`}
|
|
666
|
+
</footer>
|
|
667
|
+
</div>
|
|
668
|
+
|
|
669
|
+
<!-- Full-screen Lightbox Modal -->
|
|
670
|
+
<div id="lightbox" class="lightbox-modal" onclick="onLightboxOverlayClick(event)">
|
|
671
|
+
<div class="lightbox-content" onclick="event.stopPropagation()">
|
|
672
|
+
<div class="lightbox-header">
|
|
673
|
+
<span id="lb-badge" class="badge"></span>
|
|
674
|
+
<span id="lb-title" class="lightbox-title"></span>
|
|
675
|
+
<div class="lightbox-actions">
|
|
676
|
+
<button class="lightbox-btn" onclick="toggleLightboxZoom()" title="Toggle Zoom">\u{1F50D} Zoom</button>
|
|
677
|
+
<button class="lightbox-btn lightbox-btn-close" onclick="closeLightbox()" title="Close (Esc)">\u2715</button>
|
|
678
|
+
</div>
|
|
679
|
+
</div>
|
|
680
|
+
<div class="lightbox-body">
|
|
681
|
+
<button class="lightbox-nav prev" onclick="navigateLightbox(-1)" title="Previous (Left Arrow)">\u276E</button>
|
|
682
|
+
<img id="lb-img" class="lightbox-img" src="" alt="Screenshot Full View" onclick="toggleLightboxZoom()"/>
|
|
683
|
+
<button class="lightbox-nav next" onclick="navigateLightbox(1)" title="Next (Right Arrow)">\u276F</button>
|
|
684
|
+
</div>
|
|
685
|
+
<div class="lightbox-footer">
|
|
686
|
+
<span id="lb-counter"></span>
|
|
687
|
+
<span id="lb-desc"></span>
|
|
688
|
+
</div>
|
|
689
|
+
</div>
|
|
690
|
+
</div>
|
|
691
|
+
|
|
692
|
+
<script>
|
|
693
|
+
const SCREENSHOTS = ${JSON.stringify(p)};
|
|
694
|
+
let currentLightboxIdx = -1;
|
|
695
|
+
let currentFilter = 'all';
|
|
696
|
+
|
|
697
|
+
function setFilter(status, btn) {
|
|
698
|
+
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
|
|
699
|
+
btn.classList.add('active');
|
|
700
|
+
currentFilter = status;
|
|
701
|
+
applyFilters();
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// Backward compatibility alias for filterSteps
|
|
705
|
+
function filterSteps(status) {
|
|
706
|
+
currentFilter = status;
|
|
707
|
+
applyFilters();
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function applyFilters() {
|
|
711
|
+
const query = (document.getElementById('filter-search').value || '').toLowerCase().trim();
|
|
712
|
+
document.querySelectorAll('.step-row').forEach(row => {
|
|
713
|
+
const rowStatus = row.getAttribute('data-status');
|
|
714
|
+
const searchText = row.getAttribute('data-search') || '';
|
|
715
|
+
const matchesStatus = currentFilter === 'all' || rowStatus === currentFilter;
|
|
716
|
+
const matchesQuery = !query || searchText.includes(query);
|
|
717
|
+
row.style.display = matchesStatus && matchesQuery ? '' : 'none';
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// Lightbox Controls
|
|
722
|
+
function openLightboxByStep(stepIndex) {
|
|
723
|
+
const idx = SCREENSHOTS.findIndex(s => s.stepIndex === stepIndex);
|
|
724
|
+
if (idx !== -1) {
|
|
725
|
+
openLightboxAt(idx);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function openLightboxCustom(src, title) {
|
|
730
|
+
document.getElementById('lb-img').src = src;
|
|
731
|
+
document.getElementById('lb-img').classList.remove('zoomed');
|
|
732
|
+
document.getElementById('lb-title').innerText = title;
|
|
733
|
+
document.getElementById('lb-badge').innerText = 'CUSTOM';
|
|
734
|
+
document.getElementById('lb-badge').className = 'badge phase-badge';
|
|
735
|
+
document.getElementById('lb-counter').innerText = 'Visual Artifact';
|
|
736
|
+
document.getElementById('lb-desc').innerText = '';
|
|
737
|
+
document.querySelectorAll('.lightbox-nav').forEach(n => n.style.display = 'none');
|
|
738
|
+
document.getElementById('lightbox').classList.add('active');
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function openLightboxAt(index) {
|
|
742
|
+
if (index < 0 || index >= SCREENSHOTS.length) return;
|
|
743
|
+
currentLightboxIdx = index;
|
|
744
|
+
const item = SCREENSHOTS[index];
|
|
745
|
+
const img = document.getElementById('lb-img');
|
|
746
|
+
img.src = item.src;
|
|
747
|
+
img.classList.remove('zoomed');
|
|
748
|
+
document.getElementById('lb-title').innerText = 'Step ' + item.stepIndex + ': ' + item.action;
|
|
749
|
+
const badge = document.getElementById('lb-badge');
|
|
750
|
+
badge.innerText = item.status;
|
|
751
|
+
badge.className = 'badge status-badge status-' + item.status.toLowerCase();
|
|
752
|
+
document.getElementById('lb-counter').innerText = 'Screenshot ' + (index + 1) + ' of ' + SCREENSHOTS.length;
|
|
753
|
+
document.getElementById('lb-desc').innerText = item.description;
|
|
754
|
+
document.querySelectorAll('.lightbox-nav').forEach(n => n.style.display = SCREENSHOTS.length > 1 ? 'flex' : 'none');
|
|
755
|
+
document.getElementById('lightbox').classList.add('active');
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function closeLightbox() {
|
|
759
|
+
document.getElementById('lightbox').classList.remove('active');
|
|
760
|
+
document.getElementById('lb-img').classList.remove('zoomed');
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function onLightboxOverlayClick(e) {
|
|
764
|
+
if (e.target.id === 'lightbox') {
|
|
765
|
+
closeLightbox();
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function navigateLightbox(direction) {
|
|
770
|
+
if (SCREENSHOTS.length === 0) return;
|
|
771
|
+
let nextIdx = currentLightboxIdx + direction;
|
|
772
|
+
if (nextIdx < 0) nextIdx = SCREENSHOTS.length - 1;
|
|
773
|
+
if (nextIdx >= SCREENSHOTS.length) nextIdx = 0;
|
|
774
|
+
openLightboxAt(nextIdx);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function toggleLightboxZoom() {
|
|
778
|
+
document.getElementById('lb-img').classList.toggle('zoomed');
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function setPlaybackSpeed(speed) {
|
|
782
|
+
const player = document.getElementById('session-recording-player');
|
|
783
|
+
if (player) {
|
|
784
|
+
player.playbackRate = speed;
|
|
785
|
+
document.querySelectorAll('.btn-speed').forEach(btn => {
|
|
786
|
+
btn.classList.toggle('active', btn.textContent.trim() === speed + 'x');
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function seekVideoTo(seconds) {
|
|
792
|
+
const player = document.getElementById('session-recording-player');
|
|
793
|
+
if (player) {
|
|
794
|
+
player.currentTime = seconds;
|
|
795
|
+
player.play().catch(() => {});
|
|
796
|
+
player.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
window.addEventListener('keydown', (e) => {
|
|
801
|
+
const lb = document.getElementById('lightbox');
|
|
802
|
+
if (!lb.classList.contains('active')) return;
|
|
803
|
+
if (e.key === 'Escape') closeLightbox();
|
|
804
|
+
if (e.key === 'ArrowLeft') navigateLightbox(-1);
|
|
805
|
+
if (e.key === 'ArrowRight') navigateLightbox(1);
|
|
806
|
+
});
|
|
807
|
+
|
|
808
|
+
// Optional Live Monitor auto-connect when loaded via HTTP
|
|
809
|
+
if (window.location.protocol.startsWith('http')) {
|
|
810
|
+
try {
|
|
811
|
+
const es = new EventSource('/events');
|
|
812
|
+
es.addEventListener('step', (e) => {
|
|
813
|
+
const step = JSON.parse(e.data);
|
|
814
|
+
console.log('[Live Monitor] Step event:', step);
|
|
815
|
+
});
|
|
816
|
+
es.addEventListener('complete', (e) => {
|
|
817
|
+
console.log('[Live Monitor] Run complete:', JSON.parse(e.data));
|
|
818
|
+
});
|
|
819
|
+
} catch (err) {
|
|
820
|
+
// Non-blocking in static file mode
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
</script>
|
|
824
|
+
</body>
|
|
825
|
+
</html>`}var dt=new lt;import Ie from"fs";import tt from"path";import{fileURLToPath as an}from"url";var Ft={en:{bell:["bell","notification","notifications","alert","alerts","reminders","notice","badge"],notification:["notification","notifications","bell","alert","alerts","reminders","badge"],close:["close","dismiss","cancel","clear","cross","exit","\u2715","\xD7","x"],like:["like","favorite","heart","thumbs up","thumbs-up","fav","upvote"],dislike:["dislike","thumbs down","thumbs-down","downvote"],search:["search","find","query","magnifier","explore","lookup"],settings:["settings","preferences","gear","options","setup","config"],profile:["profile","account","user","my profile","avatar","me","personal"],trash:["trash","delete","remove","bin","discard"],delete:["delete","trash","remove","bin","discard"],share:["share","export","send to","forward"],back:["back","navigate up","previous","arrow back","chevron left","return"],menu:["menu","hamburger","drawer","sidebar","options","navigation","\u2630"],add:["add","new","create","plus","+","insert"],edit:["edit","pencil","modify","update","rename","change"],calendar:["calendar","schedule","date","events","timetable"],refresh:["refresh","reload","sync","update"],info:["info","information","details","help","about"],filter:["filter","filters","sort","refine","funnel"],check:["check","done","tick","mark","select","\u2713","\u2714"],lock:["lock","security","privacy","padlock"],camera:["camera","photo","picture","capture","snapshot"],cart:["cart","shopping cart","bag","basket","checkout"],email:["email","username","user name","e-mail","mail","login ID","user id"],username:["username","user name","email","user id","handle"],password:["password","passcode","pin","pwd","secret"],phone:["phone","mobile","contact","telephone","cell","phone number"],name:["name","full name","first name","last name"],otp:["otp","verification code","code","pin"],submit:["submit","save","continue","confirm","proceed","done","apply","ok"],save:["save","submit","done","apply","store","update"],cancel:["cancel","abort","discard","close","dismiss"],confirm:["confirm","yes","proceed","ok","agree","accept"],login:["sign in","signin","log in","login","enter"],signin:["sign in","signin","log in","login","enter"],logout:["sign out","signout","log out","logout","exit"],signout:["sign out","signout","log out","logout","exit"]},es:{bell:["campana","notificaci\xF3n","notificaciones","alerta","alertas","aviso","avisos"],notification:["notificaci\xF3n","notificaciones","campana","alerta","alertas","aviso","avisos","notification","notifications"],close:["cerrar","cancelar","quitar","salir","descartar","\u2715","\xD7","x","close"],like:["me gusta","favorito","favoritos","coraz\xF3n","like"],dislike:["no me gusta","desaprobar"],search:["buscar","b\xFAsqueda","lupa","explorar","encontrar","search"],settings:["ajustes","configuraci\xF3n","preferencias","opciones","settings"],profile:["perfil","cuenta","usuario","mi perfil","avatar","profile"],trash:["papelera","eliminar","borrar","descartar","quitar"],delete:["eliminar","borrar","quitar","papelera","descartar","delete"],share:["compartir","enviar","difundir","share"],back:["atr\xE1s","volver","regresar","anterior","flecha atr\xE1s","back"],menu:["men\xFA","opciones","navegaci\xF3n","\u2630","menu"],add:["a\xF1adir","agregar","nuevo","crear","m\xE1s","+","add"],edit:["editar","modificar","cambiar","actualizar","edit"],calendar:["calendario","fecha","eventos","horario","calendar"],refresh:["actualizar","recargar","sincronizar","refresh"],info:["informaci\xF3n","detalles","ayuda","acerca de","info"],filter:["filtrar","filtros","ordenar","filter"],check:["listo","hecho","marcar","seleccionar","\u2713","\u2714","check"],lock:["bloqueo","seguridad","privacidad","candado","lock"],camera:["c\xE1mara","foto","captura","imagen","camera"],cart:["carrito","cesta","bolsa","comprar","cart","checkout"],email:["correo","correo electr\xF3nico","email","usuario","mail"],username:["usuario","nombre de usuario","correo","username"],password:["contrase\xF1a","clave","pin","c\xF3digo","password"],phone:["tel\xE9fono","m\xF3vil","celular","contacto","n\xFAmero","phone"],name:["nombre","nombre completo","apellidos","name"],otp:["c\xF3digo de verificaci\xF3n","c\xF3digo","otp","pin"],submit:["enviar","guardar","confirmar","continuar","proceder","listo","aceptar","submit"],save:["guardar","salvar","almacenar","actualizar","save"],cancel:["cancelar","descartar","anular","abortar","cancel"],confirm:["confirmar","aceptar","s\xED","continuar","de acuerdo","confirm"],login:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],signin:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],logout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"],signout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"]},hi:{bell:["\u0918\u0902\u091F\u0940","\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders"],notification:["\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders","notification"],close:["\u092C\u0902\u0926 \u0915\u0930\u0947\u0902","\u0939\u091F\u093E\u090F\u0902","\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u2715","\xD7","x","close"],like:["\u092A\u0938\u0902\u0926","\u0932\u093E\u0907\u0915","\u092A\u0938\u0902\u0926\u0940\u0926\u093E"],dislike:["\u0928\u093E\u092A\u0938\u0902\u0926"],search:["\u0916\u094B\u091C\u0947\u0902","\u0922\u0942\u0902\u0922\u0947\u0902","\u0938\u0930\u094D\u091A","explore","search"],settings:["\u0938\u0947\u091F\u093F\u0902\u0917\u094D\u0938","\u0935\u093F\u0915\u0932\u094D\u092A","\u092A\u094D\u0930\u093E\u0925\u092E\u093F\u0915\u0924\u093E\u090F\u0902","settings"],profile:["\u092A\u094D\u0930\u094B\u092B\u093C\u093E\u0907\u0932","\u0916\u093E\u0924\u093E","\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E","\u0905\u0915\u093E\u0909\u0902\u091F","profile"],trash:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u0915\u091A\u0930\u093E"],delete:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u092E\u093F\u091F\u093E\u090F\u0902","delete"],share:["\u0936\u0947\u092F\u0930 \u0915\u0930\u0947\u0902","\u092D\u0947\u091C\u0947\u0902","share"],back:["\u0935\u093E\u092A\u0938","\u092A\u0940\u091B\u0947","\u0935\u093E\u092A\u0938 \u091C\u093E\u090F\u0902","back"],menu:["\u092E\u0947\u0928\u0942","\u0935\u093F\u0915\u0932\u094D\u092A","\u2630","menu"],add:["\u091C\u094B\u0921\u093C\u0947\u0902","\u0928\u092F\u093E","\u092C\u0928\u093E\u090F\u0902","+","add"],edit:["\u0938\u0902\u092A\u093E\u0926\u093F\u0924 \u0915\u0930\u0947\u0902","\u092C\u0926\u0932\u0947\u0902","\u090F\u0921\u093F\u091F","edit"],calendar:["\u0915\u0948\u0932\u0947\u0902\u0921\u0930","\u0924\u093E\u0930\u0940\u0916","\u0938\u092E\u092F \u0938\u093E\u0930\u093F\u0923\u0940"],refresh:["\u0930\u093F\u092B\u094D\u0930\u0947\u0936","\u0924\u093E\u091C\u093C\u093E \u0915\u0930\u0947\u0902","\u0905\u092A\u0921\u0947\u091F \u0915\u0930\u0947\u0902"],info:["\u091C\u093E\u0928\u0915\u093E\u0930\u0940","\u0935\u093F\u0935\u0930\u0923","\u092E\u0926\u0926","info"],filter:["\u092B\u093C\u093F\u0932\u094D\u091F\u0930","\u091B\u093E\u0902\u091F\u0947\u0902","filter"],check:["\u0939\u094B \u0917\u092F\u093E","\u091A\u0941\u0928\u0947\u0902","\u0938\u0939\u0940","\u2713","\u2714"],cart:["\u0915\u093E\u0930\u094D\u091F","\u0925\u0948\u0932\u093E","\u091F\u094B\u0915\u0930\u0940","cart"],email:["\u0908\u092E\u0947\u0932","\u0908-\u092E\u0947\u0932","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","email"],username:["\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E \u0928\u093E\u092E","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","\u0908\u092E\u0947\u0932","username"],password:["\u092A\u093E\u0938\u0935\u0930\u094D\u0921","\u092A\u093F\u0928","\u092A\u093E\u0938\u0915\u094B\u0921","password"],phone:["\u092B\u093C\u094B\u0928","\u092E\u094B\u092C\u093E\u0907\u0932","\u0928\u0902\u092C\u0930","\u0938\u0902\u092A\u0930\u094D\u0915","phone"],name:["\u0928\u093E\u092E","\u092A\u0942\u0930\u093E \u0928\u093E\u092E","name"],otp:["\u0913\u091F\u0940\u092A\u0940","\u0938\u0924\u094D\u092F\u093E\u092A\u0928 \u0915\u094B\u0921","\u092A\u093F\u0928","otp"],submit:["\u091C\u092E\u093E \u0915\u0930\u0947\u0902","\u0938\u092C\u092E\u093F\u091F","\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0906\u0917\u0947 \u092C\u0922\u093C\u0947\u0902","submit"],save:["\u0938\u0939\u0947\u091C\u0947\u0902","\u0938\u0947\u0935 \u0915\u0930\u0947\u0902","\u0938\u0941\u0930\u0915\u094D\u0937\u093F\u0924 \u0915\u0930\u0947\u0902","save"],cancel:["\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u0915\u0948\u0902\u0938\u093F\u0932","cancel"],confirm:["\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0938\u094D\u0935\u0940\u0915\u093E\u0930 \u0915\u0930\u0947\u0902","\u0939\u093E\u0901","\u0920\u0940\u0915 \u0939\u0948","confirm"],login:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","\u0938\u093E\u0907\u0928 \u0907\u0928","login","sign in"],signin:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u0938\u093E\u0907\u0928 \u0907\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","login","sign in"],logout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"],signout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"]}},$o=Ft.en,ts=new Map;function Ji(a){let e=new Map;for(let[t,s]of Object.entries(a)){let n=[ae(t),...s.map(r=>ae(r))];for(let r of n){e.has(r)||e.set(r,[]);let o=e.get(r);for(let c of n)o.includes(c)||o.push(c)}}return e}for(let[a,e]of Object.entries(Ft))ts.set(a.toLowerCase(),Ji(e));function Co(a,e){let t=a.toLowerCase();Ft[t]={...Ft[t]||{},...e},ts.set(t,Ji(Ft[t]))}function No(){return Object.keys(Ft)}function Qt(a,e="en"){let t=ae(a),s=(e||"en").toLowerCase(),i=ts.get(s);if(i){let n=i.get(t);if(n&&n.length>0)return n}if(s!=="en"){let n=ts.get("en");if(n){let r=n.get(t);if(r&&r.length>0)return r}}return[t]}var Vi=Qt;Fe();var pt=class a{memoryDir;currentPackage="global";mappings=new Map;screens=new Map;intents=new Map;dirty=!1;locale="en";setLocale(e){this.locale=(e||"en").toLowerCase()}getLocale(){return this.locale}constructor(e){if(e)this.memoryDir=e;else{let t=tt.dirname(an(import.meta.url));this.memoryDir=tt.resolve(t,"..","memory")}Ie.existsSync(this.memoryDir)||Ie.mkdirSync(this.memoryDir,{recursive:!0})}cleanPackageName(e){return(e||"global").replace(/[^a-zA-Z0-9._-]/g,"_")}static SCHEMA_VERSION=2;async init(e){this.currentPackage=this.cleanPackageName(e),this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1;let t=tt.join(this.memoryDir,`${this.currentPackage}.json`);if(Ie.existsSync(t))try{let s=await Ie.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(i&&i.mappings){let n=!i.version||i.version<2;for(let[r,o]of Object.entries(i.mappings))n&&(o.totalSuccesses=o.totalSuccesses??o.successCount??1,o.recentOutcomes=o.recentOutcomes??(o.failCount>0?["FAIL"]:["PASS"]),o.lastSeenTs=o.lastSeenTs??o.lastUpdated??new Date().toISOString(),this.dirty=!0),this.mappings.set(r,o);if(i.screens)for(let[r,o]of Object.entries(i.screens))this.screens.set(r,o);if(i.intents)for(let[r,o]of Object.entries(i.intents))this.intents.set(r,o);this.decayStaleMappings()}else this.mappings.clear(),this.screens.clear(),this.intents.clear()}catch{this.mappings.clear(),this.screens.clear(),this.intents.clear()}}getCanonicalQuery(e){let t=ae(e),s=Qt(t,this.locale);return s&&s.length>0?s[0]:t}buildKey(e,t){return`${e.toUpperCase()}:${this.getCanonicalQuery(t)}`}resolve(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);if(i)return i;let n=`${e.toUpperCase()}:${ae(t)}`,r=this.mappings.get(n);if(r)return r;let o=Qt(t,this.locale);for(let c of o){let l=`${e.toUpperCase()}:${c}`,p=this.mappings.get(l);if(p)return p}}getAllCandidates(e,t,s,i){let n=(s||this.locale||"en").toLowerCase(),r=new Set;if(i){let l=this.getScreenElements(i),p=this.getCanonicalQuery(t);for(let d of l)d.action===e.toUpperCase()&&(d.canonicalIntent===p||d.canonicalIntent===ae(t))&&d.confidence>=.7&&r.add(d.matchedIdentifier)}let o=this.resolve(e,t);o&&o.confidence>=.8&&r.add(o.matchedIdentifier),r.add(t);let c=Qt(t,n);for(let l of c)r.add(l);return Array.from(r)}recordSuccess(e,t,s,i,n=1,r,o){if(s.length>35||s.includes("?")||s.includes(`
|
|
826
|
+
`))return;let c=this.buildKey(e,t),l=this.mappings.get(c),p=new Date().toISOString(),d=r||l?.healedFrom?I.memory?.maxHealedConfidence??.65:1,u=r||l?.healedFrom?Math.min(n,d):n;l&&l.matchedIdentifier===s?(l.successCount+=1,l.totalSuccesses=(l.totalSuccesses||0)+1,l.failCount=0,l.recentOutcomes||(l.recentOutcomes=[]),l.recentOutcomes.push("PASS"),l.recentOutcomes.length>5&&l.recentOutcomes.shift(),l.confidence=Math.min(d,Number((l.confidence+.05).toFixed(2))),l.lastUpdated=p,l.lastSeenTs=p,r&&(l.healedFrom=r)):this.mappings.set(c,{canonicalIntent:this.getCanonicalQuery(t),action:e.toUpperCase(),matchedIdentifier:s,matchType:i,confidence:u,successCount:1,failCount:0,totalSuccesses:1,recentOutcomes:["PASS"],lastUpdated:p,lastSeenTs:p,healedFrom:r}),o&&this.associateScreenElement(o,c),this.dirty=!0}associateScreenElement(e,t){if(!e||!t)return;let s=new Date().toISOString(),i=this.screens.get(e);i?(i.elements.includes(t)||i.elements.push(t),i.lastSeenTs=s):this.screens.set(e,{lastSeenTs:s,elements:[t]}),this.dirty=!0}getScreenElements(e){let t=this.screens.get(e);return t?t.elements.map(s=>this.mappings.get(s)).filter(s=>s!==void 0):[]}getScreenIndex(){return Object.fromEntries(this.screens.entries())}markScreenCrawled(e,t){if(!e)return;let s=new Date().toISOString(),i=this.screens.get(e);if(i){if(i.crawled=!0,i.crawledAt=s,i.lastSeenTs=s,t&&t.length>0){i.safeActions||(i.safeActions=[]);for(let n of t)i.safeActions.includes(n)||i.safeActions.push(n)}}else this.screens.set(e,{lastSeenTs:s,elements:[],crawled:!0,crawledAt:s,safeActions:t?[...t]:[]});this.dirty=!0}isScreenCrawled(e){return e?!!this.screens.get(e)?.crawled:!1}getScreenMemory(e){return this.screens.get(e)}getCrawledScreensCount(){let e=0;for(let t of this.screens.values())t.crawled&&e++;return e}recordIntentExpansion(e,t){if(!e||!t||t.length===0)return;let s=ae(e),i=new Date().toISOString(),n=this.intents.get(s);n?(n.steps=[...t],n.usageCount=(n.usageCount||1)+1,n.learnedAt=i):this.intents.set(s,{intent:e,steps:[...t],learnedAt:i,usageCount:1}),this.dirty=!0}getIntentExpansion(e){if(!e)return;let t=ae(e),s=this.intents.get(t);if(s)return s.usageCount=(s.usageCount||0)+1,this.dirty=!0,[...s.steps]}hasIntentExpansion(e){return e?this.intents.has(ae(e)):!1}getIntentExpansionsCount(){return this.intents.size}recordFailure(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);i&&(i.failCount+=1,i.recentOutcomes||(i.recentOutcomes=[]),i.recentOutcomes.push("FAIL"),i.recentOutcomes.length>5&&i.recentOutcomes.shift(),i.confidence=Math.max(.1,Number((i.confidence-.25).toFixed(2))),i.lastUpdated=new Date().toISOString(),(i.recentOutcomes.filter(r=>r==="FAIL").length>=3||i.confidence<.2)&&this.mappings.delete(s),this.dirty=!0)}decayStaleMappings(e){let s=(e??I.memory?.staleThresholdDays??14)*24*60*60*1e3,i=Date.now(),n=0;for(let r of this.mappings.values()){let o=r.lastSeenTs?new Date(r.lastSeenTs).getTime():0;if(o>0&&i-o>s){let c=I.memory?.staleDecayAmount??.2,l=I.memory?.minConfidenceFloor??.2,p=Math.max(l,Number((r.confidence-c).toFixed(2)));p<r.confidence&&(r.confidence=p,n++,this.dirty=!0)}}return n}async save(){if(!this.dirty)return;let e={packageName:this.currentPackage,version:a.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())},t=tt.join(this.memoryDir,`${this.currentPackage}.json`),s=`${t}.tmp.${Date.now()}`;await Ie.promises.writeFile(s,JSON.stringify(e,null,2),"utf-8");try{await Ie.promises.rename(s,t)}catch{await Ie.promises.copyFile(s,t),await Ie.promises.unlink(s).catch(()=>{})}this.dirty=!1}async exportMemory(e){let t=e?tt.resolve(e):tt.join(this.memoryDir,`${this.currentPackage}-export.json`),s=tt.dirname(t);Ie.existsSync(s)||Ie.mkdirSync(s,{recursive:!0});let i={packageName:this.currentPackage,version:a.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())};return await Ie.promises.writeFile(t,JSON.stringify(i,null,2),"utf-8"),t}async importMemory(e){let t=tt.resolve(e);if(!Ie.existsSync(t))throw new Error(`Memory import source file not found: ${t}`);let s=await Ie.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(!i||!i.mappings)throw new Error("Invalid memory file format: missing mappings object.");let n=0,r=new Date().toISOString();for(let[o,c]of Object.entries(i.mappings)){let l=this.mappings.get(o);(!l||c.confidence>=l.confidence)&&(this.mappings.set(o,{...c,totalSuccesses:c.totalSuccesses??c.successCount??1,recentOutcomes:c.recentOutcomes??["PASS"],lastSeenTs:c.lastSeenTs??c.lastUpdated??r,lastUpdated:r}),n++)}if(i.screens)for(let[o,c]of Object.entries(i.screens)){let l=this.screens.get(o);if(!l)this.screens.set(o,c);else{let p=new Set([...l.elements,...c.elements]),d=new Set([...l.safeActions||[],...c.safeActions||[]]);this.screens.set(o,{lastSeenTs:c.lastSeenTs||l.lastSeenTs,elements:Array.from(p),crawled:l.crawled||c.crawled,crawledAt:c.crawledAt||l.crawledAt,safeActions:Array.from(d)})}}if(i.intents)for(let[o,c]of Object.entries(i.intents)){let l=this.intents.get(o);(!l||(c.usageCount||0)>=(l.usageCount||0))&&this.intents.set(o,c)}return n>0&&(this.dirty=!0,await this.save()),n}getMappingsList(){return Array.from(this.mappings.values())}getStats(){let e=Array.from(this.mappings.values()),t=e.reduce((n,r)=>n+(r.totalSuccesses||r.successCount||0),0),s=e.length>0?Number((e.reduce((n,r)=>n+r.confidence,0)/e.length).toFixed(2)):0,i=0;for(let n of this.screens.values())n.crawled&&i++;return{totalMappings:this.mappings.size,totalScreens:this.screens.size,crawledScreens:i,totalIntents:this.intents.size,package:this.currentPackage,totalSuccesses:t,averageConfidence:s}}async clear(e){let t=this.cleanPackageName(e||this.currentPackage),s=tt.join(this.memoryDir,`${t}.json`);return Ie.existsSync(s)?(await Ie.promises.unlink(s),t===this.currentPackage&&(this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1),!0):!1}},_t=new pt;Fe();import ze from"fs";import cn from"path";import ln from"os";var ks=new Map;function Et(a){let e=(a||"default").replace(/[^a-zA-Z0-9._-]/g,"_"),t=cn.join(ln.tmpdir(),`prompttest-${e}.lock`);if(ze.existsSync(t))try{let i=ze.readFileSync(t,"utf-8").trim(),n=parseInt(i,10);if(!isNaN(n)){if(n===process.pid)return{serial:a,lockFilePath:t,acquired:!0,pid:process.pid};try{throw process.kill(n,0),new Error(`Device "${a}" is locked by another PromptTest process (PID ${n}).
|
|
827
|
+
Wait for the other run to complete, or remove the lock file if it is stale: ${t}`)}catch(r){if(r.code==="ESRCH")try{ze.unlinkSync(t)}catch{}else throw r}}}catch(i){let n=i;if(n.message&&n.message.includes("locked by another"))throw n;try{ze.unlinkSync(t)}catch{}}try{ze.writeFileSync(t,process.pid.toString(),{flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Device "${a}" was just acquired by a concurrent PromptTest process.`):i}let s=()=>{try{ze.existsSync(t)&&ze.readFileSync(t,"utf-8").trim()===process.pid.toString()&&ze.unlinkSync(t)}catch{}};return ks.set(t,s),process.once("exit",s),{serial:a,lockFilePath:t,acquired:!0,pid:process.pid}}function kt(a){if(a)try{let e=ks.get(a.lockFilePath);if(e)process.removeListener("exit",e),ks.delete(a.lockFilePath),e();else if(ze.existsSync(a.lockFilePath))try{ze.readFileSync(a.lockFilePath,"utf-8").trim()===process.pid.toString()&&ze.unlinkSync(a.lockFilePath)}catch{}}catch{}}import Ds from"chalk";var As={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4},ss=class{currentLevel="INFO";constructor(e){let t=(process.env.LOG_LEVEL||"").toUpperCase();e?this.currentLevel=e:As[t]!==void 0?this.currentLevel=t:this.currentLevel="INFO"}setLevel(e){this.currentLevel=e}getLevel(){return this.currentLevel}isLevelEnabled(e){return As[this.currentLevel]<=As[e]}isJsonMode(){return(process.env.LOG_FORMAT||"").toLowerCase()==="json"}emitJson(e,...t){let s=t.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" "),i={ts:new Date().toISOString(),level:e,msg:s};e==="ERROR"||e==="WARN"?console.error(JSON.stringify(i)):console.log(JSON.stringify(i))}debug(...e){this.isLevelEnabled("DEBUG")&&(this.isJsonMode()?this.emitJson("DEBUG",...e):console.log(Ds.gray("[DEBUG]"),...e))}info(...e){this.isLevelEnabled("INFO")&&(this.isJsonMode()?this.emitJson("INFO",...e):console.log(...e))}warn(...e){this.isLevelEnabled("WARN")&&(this.isJsonMode()?this.emitJson("WARN",...e):console.warn(Ds.yellow("[WARN]"),...e))}error(...e){this.isLevelEnabled("ERROR")&&(this.isJsonMode()?this.emitJson("ERROR",...e):console.error(Ds.red("[ERROR]"),...e))}},qe=new ss;import ut from"fs";import zi from"path";var $s=class{checkpointDir;constructor(e){this.checkpointDir=e||zi.resolve(process.cwd(),"output","checkpoints"),ut.existsSync(this.checkpointDir)||ut.mkdirSync(this.checkpointDir,{recursive:!0})}filePath(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return zi.join(this.checkpointDir,`${t}.checkpoint.json`)}async save(e,t,s,i){let n={specFile:e,packageName:t,lastPassedStep:s,totalSteps:i,savedAt:new Date().toISOString()},r=this.filePath(e)+`.tmp.${Date.now()}`;await ut.promises.writeFile(r,JSON.stringify(n,null,2),"utf-8"),await ut.promises.rename(r,this.filePath(e))}async load(e){let t=this.filePath(e);if(!ut.existsSync(t))return null;try{let s=await ut.promises.readFile(t,"utf-8");return JSON.parse(s)}catch{return null}}async clear(e){let t=this.filePath(e);ut.existsSync(t)&&await ut.promises.unlink(t)}async getResumeIndex(e){let t=await this.load(e);return t?t.lastPassedStep+1:0}},Ki=new $s;import xe from"fs";import ht from"path";import{PNG as Dt}from"pngjs";import dn from"pixelmatch";var Cs={strict:{threshold:.005,pixelmatchThreshold:.05,label:"Strict (0.5%)",description:"Pixel-perfect verification for Figma design-to-code compliance"},moderate:{threshold:.02,pixelmatchThreshold:.1,label:"Moderate (2.0%)",description:"Standard mobile QA matching"},relaxed:{threshold:.05,pixelmatchThreshold:.2,label:"Relaxed (5.0%)",description:"Lenient comparison for cross-device or font variations"}},gt=class{baselineDir;defaultThreshold;constructor(e,t=.02){this.baselineDir=e||ht.resolve(process.cwd(),"output","baselines"),this.defaultThreshold=t,xe.existsSync(this.baselineDir)||xe.mkdirSync(this.baselineDir,{recursive:!0})}filePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ht.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}.png`)}diffFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ht.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_diff.png`)}masksFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ht.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_masks.json`)}async getMasks(e,t){let s=this.masksFilePath(e,t);if(!xe.existsSync(s))return[];try{let i=await xe.promises.readFile(s,"utf-8"),n=JSON.parse(i);return Array.isArray(n)?n:n.masks||[]}catch{return[]}}async saveMasks(e,t,s){let i=this.masksFilePath(e,t);return await xe.promises.writeFile(i,JSON.stringify(s,null,2),"utf-8"),i}async saveBaseline(e,t,s){let i=this.filePath(e,t),n=i+`.tmp.${Date.now()}`;return await xe.promises.writeFile(n,s),await xe.promises.rename(n,i),i}hasBaseline(e,t){return xe.existsSync(this.filePath(e,t))}async compare(e,t,s,i){let n=typeof i=="number"?{threshold:i}:i||{},r=this.filePath(e,t),o=ht.join(this.baselineDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}_current.png`);await xe.promises.writeFile(o,s);let c=n.mode?Cs[n.mode]:void 0,l=n.threshold??c?.threshold??this.defaultThreshold,p=n.pixelmatchThreshold??c?.pixelmatchThreshold??.1;if(!xe.existsSync(r)){await this.saveBaseline(e,t,s);let U=Dt.sync.read(s),Z=U.width*U.height;return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:0,diffPixels:0,totalPixels:Z,passed:!0,threshold:l}}let d=await xe.promises.readFile(r),u=Dt.sync.read(d),h=Dt.sync.read(s),g=Math.max(u.width,h.width),b=Math.max(u.height,h.height),T=g*b,x=this.fitToCanvas(u,g,b),S=this.fitToCanvas(h,g,b),y=n.maskRegions??await this.getMasks(e,t);y&&y.length>0&&(this.applyMasks(x,y),this.applyMasks(S,y));let P=new Dt({width:g,height:b}),$=dn(x.data,S.data,P.data,g,b,{threshold:p,includeAA:!1}),R=T>0?$/T:0,C=R<=l,B;if(C){let U=this.diffFilePath(e,t);if(xe.existsSync(U))try{await xe.promises.unlink(U)}catch{}}else{B=this.diffFilePath(e,t);let U=Dt.sync.write(P);await xe.promises.writeFile(B,U)}return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:R,diffPixels:$,totalPixels:T,passed:C,threshold:l,diffImagePath:B}}fitToCanvas(e,t,s){if(e.width===t&&e.height===s)return e;let i=new Dt({width:t,height:s});return i.data.fill(0),Dt.bitblt(e,i,0,0,e.width,e.height,0,0),i}applyMasks(e,t){for(let s of t){let i=s.width<=1&&s.height<=1||s.x<=1&&s.y<=1&&(s.width<1||s.height<1),n=Math.round(i?s.x*e.width:s.x),r=Math.round(i?s.y*e.height:s.y),o=Math.round(i?s.width*e.width:s.width),c=Math.round(i?s.height*e.height:s.height),l=Math.max(0,r),p=Math.min(e.height,r+c),d=Math.max(0,n),u=Math.min(e.width,n+o);for(let h=l;h<p;h++)for(let g=d;g<u;g++){let b=e.width*h+g<<2;e.data[b]=0,e.data[b+1]=0,e.data[b+2]=0,e.data[b+3]=0}}}async approveBaseline(e,t,s){let i;if(s)i=await this.saveBaseline(e,t,s);else{let r=e.replace(/[^a-zA-Z0-9._-]/g,"_"),o=ht.join(this.baselineDir,`${r}_step${String(t).padStart(3,"0")}_current.png`);if(!xe.existsSync(o))throw new Error(`No current screenshot found to approve for step ${t}`);let c=await xe.promises.readFile(o);i=await this.saveBaseline(e,t,c)}let n=this.diffFilePath(e,t);if(xe.existsSync(n))try{await xe.promises.unlink(n)}catch{}return i}async clearBaselines(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");if(!xe.existsSync(this.baselineDir))return;let s=await xe.promises.readdir(this.baselineDir);await Promise.all(s.filter(i=>i.startsWith(t+"_step")).map(i=>xe.promises.unlink(ht.join(this.baselineDir,i)).catch(()=>{})))}async deleteStepBaseline(e,t){let i=`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}`;if(!xe.existsSync(this.baselineDir))return;let n=await xe.promises.readdir(this.baselineDir);await Promise.all(n.filter(r=>r.startsWith(i)).map(r=>xe.promises.unlink(ht.join(this.baselineDir,r)).catch(()=>{})))}},Ns=new gt;Fe();import pe from"chalk";import rr from"vm";import Ht from"chalk";var pn=["com.miui.home","com.mi.android.globallauncher","com.sec.android.app.launcher","com.sec.android.app.twlauncher","com.google.android.apps.nexuslauncher","com.android.launcher3","com.android.launcher","com.oppo.launcher","com.coloros.launcher","com.bbk.launcher2","com.vivo.launcher","com.huawei.android.launcher","net.oneplus.launcher","com.motorola.launcher3","org.lineageos.trebuchet","com.teslacoilsw.launcher","com.actionlauncher.playstore","com.transsion.hilauncher","com.nothing.launcher"],un=["android","com.android.systemui","com.google.android.permissioncontroller","com.android.permissioncontroller","com.android.packageinstaller","com.google.android.packageinstaller","com.google.android.inputmethod.latin","com.samsung.android.honeyboard","com.touchtype.swiftkey","com.miui.virtualsim","com.google.android.gms","com.android.settings"];function At(a){if(!a)return!1;let e=a.toLowerCase();return pn.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))?!0:e.includes("launcher")||e.includes(".home")||e.endsWith(".home")||e.includes("trebuchet")||e.includes("desktop")}function Is(a){if(!a)return!1;let e=a.toLowerCase();return un.some(t=>e===t.toLowerCase()||e.startsWith(t.toLowerCase()))}function is(a,e){if(!a||!e)return!0;let t=a.toLowerCase(),s=e.toLowerCase();return!!(t===s||t.startsWith(`${s}.`)||Is(a))}function Ls(a){if(!a||a.length===0)return null;for(let e of a)if(e.packageName&&(e.clickable||e.focused||e.scrollable)&&!Is(e.packageName))return e.packageName;for(let e of a)if(e.packageName&&!Is(e.packageName))return e.packageName;return a[0]?.packageName||null}async function Ms(a,e,t,s){if(!e)return{escaped:!1,recovered:!0,currentPackage:null};let i=Ls(a);if(!i)return{escaped:!1,recovered:!0,currentPackage:null};if(is(i,e))return{escaped:!1,recovered:!0,currentPackage:i};let n=At(i);console.log(Ht.yellow(`
|
|
828
|
+
\u{1F6E1}\uFE0F [Jail Guard] Boundary Violation Detected: Active screen belongs to "${i}" (not target "${e}").`)),console.log(n?Ht.cyan(` [Jail Guard] Device is on home launcher. Suppressing back-press to prevent exit loops. Re-launching "${e}"...`):Ht.cyan(` [Jail Guard] Foreign app "${i}" intercepted. Re-launching target "${e}" to restore containment...`));try{await t.launchApp(e,s),await new Promise(c=>setTimeout(c,1200));let r=await t.getForegroundPackage(s),o=r?r.includes(e):!0;return console.log(o?Ht.green(` \u2714 [Jail Guard] Containment restored: "${e}" is now in foreground.`):Ht.red(` \u274C [Jail Guard] Recovery failed. Current foreground is still "${r}".`)),{escaped:!0,recovered:o,currentPackage:i}}catch(r){return console.log(Ht.red(` \u274C [Jail Guard] Error during containment recovery: ${r.message}`)),{escaped:!0,recovered:!1,currentPackage:i}}}It();import st from"fs";import Be from"path";import ge from"chalk";import hn from"zlib";import gn from"fs";function mn(a){let e=-1;for(let t=0;t<a.length;t++){let s=a[t];e^=s;for(let i=0;i<8;i++)e=e>>>1^-(e&1)&3988292384}return~e>>>0}function fn(a=new Date){let e=(a.getHours()&31)<<11|(a.getMinutes()&63)<<5|Math.floor(a.getSeconds()/2)&31,t=(a.getFullYear()-1980&127)<<9|(a.getMonth()+1&15)<<5|a.getDate()&31;return{time:e,date:t}}function bn(a){let e=[],t=[],s=0;for(let c of a){let l=c.data,p=hn.deflateRawSync(l),d=p.length<l.length,u=d?p:l,h=d?8:0,g=mn(l),b=l.length,T=u.length,{time:x,date:S}=fn(c.date),y=Buffer.from(c.name.replace(/\\/g,"/"),"utf-8"),P=Buffer.alloc(30+y.length);P.writeUInt32LE(67324752,0),P.writeUInt16LE(20,4),P.writeUInt16LE(2048,6),P.writeUInt16LE(h,8),P.writeUInt16LE(x,10),P.writeUInt16LE(S,12),P.writeUInt32LE(g,14),P.writeUInt32LE(T,18),P.writeUInt32LE(b,22),P.writeUInt16LE(y.length,26),P.writeUInt16LE(0,28),y.copy(P,30),e.push(P),e.push(u);let $=Buffer.alloc(46+y.length);$.writeUInt32LE(33639248,0),$.writeUInt16LE(20,4),$.writeUInt16LE(20,6),$.writeUInt16LE(2048,8),$.writeUInt16LE(h,10),$.writeUInt16LE(x,12),$.writeUInt16LE(S,14),$.writeUInt32LE(g,16),$.writeUInt32LE(T,20),$.writeUInt32LE(b,24),$.writeUInt16LE(y.length,28),$.writeUInt16LE(0,30),$.writeUInt16LE(0,32),$.writeUInt16LE(0,34),$.writeUInt16LE(0,36),$.writeUInt32LE(0,38),$.writeUInt32LE(s,42),y.copy($,46),t.push($),s+=P.length+u.length}let i=Buffer.concat(t),n=i.length,r=s,o=Buffer.alloc(22);return o.writeUInt32LE(101010256,0),o.writeUInt16LE(0,4),o.writeUInt16LE(0,6),o.writeUInt16LE(a.length,8),o.writeUInt16LE(a.length,10),o.writeUInt32LE(n,12),o.writeUInt32LE(r,16),o.writeUInt16LE(0,20),Buffer.concat([...e,i,o])}async function Xi(a,e){let t=bn(e);await gn.promises.writeFile(a,t)}function Rs(a,e=new Set){let t=Be.resolve(a);if(!st.existsSync(t))throw new Error(`Included spec file not found: ${t}`);if(e.has(t)){let r=Array.from(e).concat(t);throw new Jt(`Circular spec inclusion detected: ${r.join(" -> ")}`,r)}e.add(t);let i=st.readFileSync(t,"utf-8").split(`
|
|
829
|
+
`),n=[];for(let r of i){let o=r.trim(),c=o.match(te.INCLUDE_SPEC);if(c&&!o.startsWith("#")){let l=ce([c[1],c[2],c[3]]),p=Be.isAbsolute(l)?l:Be.resolve(Be.dirname(t),l),d=Rs(p,new Set(e));n.push(d)}else n.push(r)}return n.join(`
|
|
830
|
+
`)}function yn(a){let e=[],t=[];for(let s of a){if(s._isControl==="END"){t.length>0&&t.pop();continue}if(s._isControl==="ELSE"){t.length>0&&t[t.length-1].step.type==="IF_VISIBLE"&&(t[t.length-1].inElse=!0);continue}let i=e;if(t.length>0){let n=t[t.length-1];n.step.type==="IF_VISIBLE"?n.inElse?(n.step.elseSteps=n.step.elseSteps||[],i=n.step.elseSteps):(n.step.thenSteps=n.step.thenSteps||[],i=n.step.thenSteps):n.step.type==="LOOP"&&(n.step.childSteps=n.step.childSteps||[],i=n.step.childSteps)}i.push(s),(s.type==="IF_VISIBLE"||s.type==="LOOP")&&t.push({step:s,inElse:!1})}return e}function mt(a,e){let t=a.split(`
|
|
831
|
+
`).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#")),s=[];for(let i of t){let n=Pt(i,e),r=n.replace(Mi,"").trim(),o=te.OPTIONAL_SUFFIX.test(r)||/^[(\[]\s*optional\s*[)\]]/i.test(r)||/^optional\s*:/i.test(r),c=r.replace(te.OPTIONAL_SUFFIX,"").replace(/^[(\[]\s*optional\s*[)\]]\s*/i,"").replace(/^optional\s*:\s*/i,"").trim();if(te.BACK.test(c)){s.push({originalText:n,type:"BACK",optional:o});continue}let l=c.match(te.WAIT);if(l){let v=parseInt(l[1],10),A=c.toLowerCase().includes("ms")?v:v*1e3;s.push({originalText:n,type:"WAIT",durationMs:A,optional:o});continue}let p=c.match(te.WAIT_UNTIL);if(p){let v=ce([p[1],p[2],p[3]]),k=(p[4]||"visible").toLowerCase().includes("enable")?"enabled":"visible",F=p[5]?parseInt(p[5],10):void 0,N=(p[6]||"s").toLowerCase(),H=F?N.includes("ms")?F:F*1e3:void 0;s.push({originalText:n,type:"WAIT_UNTIL",target:v,expectedState:k,durationMs:H,optional:o});continue}let d=c.match(te.IF_VISIBLE);if(d){let v=ce([d[1],d[2],d[3],d[5],d[6],d[7]]);s.push({originalText:n,type:"IF_VISIBLE",conditionTarget:v,thenSteps:[],elseSteps:[],optional:o});continue}if(te.ELSE.test(c)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"ELSE"});continue}if(te.END.test(c)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"END"});continue}let u=c.match(te.LOOP);if(u){let v=parseInt(u[1],10);s.push({originalText:n,type:"LOOP",loopCount:v,childSteps:[],optional:o});continue}let h=c.match(te.FOR_EACH);if(h){let v=ce([h[1],h[2],h[3]]);s.push({originalText:n,type:"LOOP",target:v,loopVariable:"item",childSteps:[],optional:o});continue}let g=c.match(te.SET_VARIABLE);if(g){let v=g[1].trim(),A=g[2].trim();s.push({originalText:n,type:"SET_VARIABLE",variableName:v,variableExpression:A,optional:o});continue}let b=c.match(te.DEVICE_WIFI);if(b){let v=b[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"wifi",deviceStateValue:v==="on"||v==="enable",optional:o});continue}let T=c.match(te.DEVICE_AIRPLANE);if(T){let v=T[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"airplane",deviceStateValue:v==="on"||v==="enable",optional:o});continue}let x=c.match(te.DEVICE_ORIENTATION);if(x){let v=x[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"orientation",deviceStateValue:v,optional:o});continue}let S=c.match(te.DEVICE_NOTIFICATIONS);if(S){let v=S[1].toLowerCase(),A=v.startsWith("open")||v.startsWith("expand")||v.startsWith("pull");s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"notifications",deviceStateValue:A?"open":"collapse",optional:o});continue}let y=c.match(te.RUN_JS);if(y){let v=y[1].trim();s.push({originalText:n,type:"RUN_JS",jsCode:v,optional:o});continue}let P=c.match(te.ENTER_OTP);if(P){let v=ce([P[1],P[2],P[3]])||void 0;s.push({originalText:n,type:"ENTER_OTP",target:v,optional:o});continue}let $=c.match(te.API_REQUEST);if($){let v=$[1].toUpperCase(),A=ce([$[2],$[3],$[4]]),k=ce([$[5],$[6],$[7]])||void 0,F=ce([$[8],$[9],$[10]])||void 0,N=$[11]||void 0,H=$[12]?parseInt($[12],10):void 0;s.push({originalText:n,type:"API_REQUEST",apiMethod:v,apiUrl:A,apiBody:k,apiStorePath:F,apiStoreVariable:N,apiExpectedStatus:H,optional:o});continue}let R=c.match(te.EMAIL_ASSERT);if(R){let v=ce([R[1],R[2],R[3]]),A=ce([R[4],R[5],R[6]]),k=ce([R[7],R[8],R[9]])||void 0;s.push({originalText:n,type:"EMAIL_ASSERT",emailRecipient:v,emailSubject:A,emailBodyContains:k,optional:o});continue}let C=c.match(te.LAUNCH_APP);if(C){let v=ce([C[1],C[2],C[3]]);s.push({originalText:n,type:"LAUNCH_APP",target:v,optional:o});continue}let B=c.match(te.RESTART_APP);if(B){let v=ce([B[1],B[2],B[3]]);s.push({originalText:n,type:"RESTART_APP",target:v,optional:o});continue}let U=c.match(te.TERMINATE_APP);if(U){let v=ce([U[1],U[2],U[3]])||void 0;s.push({originalText:n,type:"TERMINATE_APP",target:v,optional:o});continue}let Z=c.match(te.CLEAR_DATA);if(Z){let v=ce([Z[1],Z[2],Z[3]]);s.push({originalText:n,type:"CLEAR_DATA",target:v,optional:o});continue}let W=c.match(te.GRANT_PERMISSION);if(W){let v=ce([W[1],W[2],W[3]]),A=ce([W[4],W[5],W[6]])||void 0;s.push({originalText:n,type:"GRANT_PERMISSION",value:v,target:A,optional:o});continue}let J=c.match(te.DEEP_LINK);if(J){let v=ce([J[1],J[2],J[3]]);s.push({originalText:n,type:"DEEP_LINK",target:v,optional:o});continue}let Ee=c.match(te.DIRECTIONAL_SWIPE);if(Ee){let v=Ee[1].toLowerCase(),A=ce([Ee[2],Ee[3],Ee[4]])||void 0;s.push({originalText:n,type:"SWIPE",direction:v,target:A,optional:o});continue}let se=c.match(te.TOGGLE);if(se){let v=(se[1]||"").toLowerCase(),A=ce([se[2],se[3],se[4]]),k=c.toLowerCase().startsWith("uncheck")||v==="off"?!1:v==="on"||c.toLowerCase().startsWith("check")?!0:void 0;s.push({originalText:n,type:"TOGGLE",target:A,desiredState:k,optional:o});continue}let j=c.match(te.SELECT_DROPDOWN);if(j){let v=ce([j[1],j[2],j[3]]),A=ce([j[4],j[5],j[6]]);s.push({originalText:n,type:"SELECT",value:v,target:A,optional:o});continue}let re=c.match(te.SCROLL_TO);if(re){let v=(re[1]||"down").toLowerCase(),A=ce([re[2],re[3],re[4]]);s.push({originalText:n,type:"SCROLL",target:A,direction:v,optional:o});continue}let w=c.match(te.SCROLL);if(w){let v=w[1].toLowerCase();s.push({originalText:n,type:"SCROLL",target:v,direction:v,optional:o});continue}let f=c.match(te.LONG_PRESS);if(f){let v=ce([f[1],f[2],f[3]]);s.push({originalText:n,type:"LONG_PRESS",target:v,optional:o});continue}let O=c.match(te.ORDINAL_TAP);if(O){let v=O[1].toLowerCase(),A=ce([O[2],O[3],O[4]]);s.push({originalText:n,type:"TAP",target:A,ordinal:v,optional:o});continue}let D=c.match(te.PROXIMITY_TAP);if(D){let v=ce([D[1],D[2],D[3]]),A=ce([D[4],D[5],D[6]]);s.push({originalText:n,type:"TAP",target:v,relativeTo:A,optional:o});continue}let we=c.match(te.TYPE);if(we){let v=ce([we[1],we[2],we[3]]),A=ce([we[4],we[5],we[6]]);s.push({originalText:n,type:"TYPE",value:v,target:A,optional:o});continue}let ue=c.match(te.CLEAR);if(ue){let v=ce([ue[1],ue[2],ue[3]]);s.push({originalText:n,type:"CLEAR",target:v,optional:o});continue}let m=c.match(te.VERIFY);if(m){let v=ce([m[1],m[2],m[3]]),A=(m[4]||"visible").toLowerCase(),k=A.includes("not visible")||A.includes("not present")||A.includes("absent")||A.includes("hidden")||A.includes("gone"),F=k?"absent":A==="exists"||A==="enabled"||A==="disabled"?A:"visible";s.push({originalText:n,type:"VERIFY",target:v,expectedState:F,negative:k,optional:o});continue}let E=c.match(te.TAP);if(E&&!c.toLowerCase().includes("back")){let v=ce([E[1],E[2],E[3]]);s.push({originalText:n,type:"TAP",target:v,optional:o});continue}let L=c.match(te.FALLBACK_QUOTED_TAP);if(L&&(c.toLowerCase().startsWith("tap")||c.toLowerCase().startsWith("click"))){s.push({originalText:n,type:"TAP",target:L[1],optional:o});continue}qe.warn(`Unrecognized prompt step: "${i}". Skipping.`)}return yn(s)}function Qi(a,e,t){let s=e.map(r=>(r.text||r.contentDesc||"").trim()).filter(r=>r.length>1),i=Rt(a,s,3),n=i.length>0?`
|
|
832
|
+
\u{1F4A1} Did you mean one of these visible items?
|
|
833
|
+
`+i.map(r=>` \u2022 "${r.text}" (${Math.round(r.score*100)}% match)`).join(`
|
|
834
|
+
`):`
|
|
835
|
+
\u{1F4A1} No similar text found on current screen.`;return new Error(`${t}${n}`)}function Zi(a,e,t,s){let i=ae(e),n=i.includes("password")||i.includes("passcode")||i.includes("pin")||i.includes("pwd")||i.includes("secret"),r=i.includes("email")||i.includes("mail")||i.includes("user")||i.includes("login")||i.includes("username")||t&&t.includes("@"),o=a.filter(p=>p.className.includes("EditText")&&p.bounds.width>0);if(o.length===0)return null;let c=o.find(p=>de(e,p.contentDesc)||de(e,p.resourceId)||de(e,p.text));if(c)return c;let l=a.filter(p=>!p.className.includes("EditText")&&(de(e,p.text)||de(e,p.contentDesc)||de(e,p.resourceId))&&p.bounds.width>0);for(let p of l){let d=o.filter(u=>u.bounds.centerY>=p.bounds.centerY&&u.bounds.centerY-p.bounds.centerY<300&&Math.abs(u.bounds.centerX-p.bounds.centerX)<450);if(d.length>0)return d.sort((u,h)=>u.bounds.centerY-h.bounds.centerY),d[0]}if(s){let p=s.getAllCandidates("TYPE",e);for(let d of p){let u=o.find(h=>de(d,h.contentDesc)||de(d,h.resourceId)||de(d,h.text));if(u)return u}}if(n){let p=o.find(d=>d.password);if(p)return p;if(o.length>1){let d=o.find(u=>u.text?.toLowerCase().includes("email")||u.contentDesc?.toLowerCase().includes("email"));if(d){let u=o.filter(h=>h.bounds.centerY>d.bounds.centerY);if(u.length>0)return u.sort((h,g)=>h.bounds.centerY-g.bounds.centerY),u[0]}}if(o.length>=2)return o[1]}if(r){let p=o.find(d=>!d.password);if(p)return p;if(o.length>0)return o[0]}return o.length===1?o[0]:null}function rs(a,e,t,s="en",i,n){let r=i?.type||"TAP",o=ae(e),l=a.filter(h=>(ae(h.text)===o||ae(h.contentDesc)===o)&&h.bounds.width>0&&h.bounds.height>0).find(h=>h.clickable);if(l)return[l];let p=t.getAllCandidates(r,e,s,n),d=[];for(let h of p){let g=a.filter(b=>{let T=de(h,b.text),x=de(h,b.contentDesc),S=de(h,b.resourceId);return(T||x||S)&&b.bounds.width>0&&b.bounds.height>0});if(g.length>0){d=g;break}}if(d.length===0){let h=[];for(let b of a)b.text&&b.text.trim().length>1&&h.push(b.text.trim()),b.contentDesc&&b.contentDesc.trim().length>1&&h.push(b.contentDesc.trim());let g=Rt(e,h,1);if(g.length>0&&g[0].score>=.8){let b=g[0].text,T=a.filter(x=>(de(b,x.text)||de(b,x.contentDesc))&&x.bounds.width>0&&x.bounds.height>0);T.length>0&&(console.log(ge.yellow(` \u{1F4A1} [Self-Healing] Auto-resolved "${e}" \u2192 "${b}" (${Math.round(g[0].score*100)}% match)`)),d=T)}}if(d.length===0)return[];let u=d.filter(h=>{let g=ae(h.text),b=ae(h.contentDesc);return g===o||b===o});if(u.length>0)d=u;else{let h=d.filter(g=>{let b=ae(g.contentDesc);return b.endsWith(o)||b.includes(`, ${o}`)});h.length>0&&(d=h)}if(i?.relativeTo){let h=a.find(g=>de(i.relativeTo,g.text)||de(i.relativeTo,g.contentDesc));if(h){let g=d.filter(b=>Math.abs(b.bounds.centerY-h.bounds.centerY)<140).sort((b,T)=>{let x=Math.hypot(b.bounds.centerX-h.bounds.centerX,b.bounds.centerY-h.bounds.centerY),S=Math.hypot(T.bounds.centerX-h.bounds.centerX,T.bounds.centerY-h.bounds.centerY);return x-S});if(g.length>0)return g}}if(i?.ordinal){let h=i.ordinal.toLowerCase();if(h==="1st"||h==="first")return[d[0]];if(h==="2nd"&&d.length>1)return[d[1]];if(h==="3rd"&&d.length>2)return[d[2]];if(h==="4th"&&d.length>3)return[d[3]];if(h==="5th"&&d.length>4)return[d[4]];if(h==="last"&&d.length>0)return[d[d.length-1]]}return d}function ye(a){if(!a||a.length===0)return"0";let e=2166136261;for(let t=0;t<a.length;t++){let s=a[t],i=`${s.text||""}|${s.contentDesc||""}|${s.resourceId||""}|${s.bounds?.x1||0},${s.bounds?.y1||0},${s.bounds?.width||0},${s.bounds?.height||0}`;for(let n=0;n<i.length;n++)e^=i.charCodeAt(n),e=Math.imul(e,16777619)}return(e>>>0).toString(16)}var Sn=[/\b\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM|am|pm)?\b/g,/\b\d+\s*(?:sec|min|hr|hour|day|week|month|year)s?\s*ago\b/gi,/\b(?:just now|yesterday|today)\b/gi,/[\$€£₹]\s*\d+(?:\.\d{1,2})?/g,/(?:#|(?:\b(?:ID|No)[\s:-]*))[A-Z0-9_-]{3,}\b/gi,/\b\d{1,3}%\b/g];function Gi(a){if(!a)return"";let e=a;for(let t of Sn)e=e.replace(t,"<VAL>");return e.trim()}function Ue(a,e){if(!a||a.length===0)return"0";let s=(e?.height||2400)*.04,i=2166136261;for(let n=0;n<a.length;n++){let r=a[n];if(r.bounds&&r.bounds.centerY<s)continue;let o=Gi(r.text||""),c=Gi(r.contentDesc||""),l=r.resourceId||"",p=r.className||"",d=r.clickable?"1":"0",u=r.checkable?"1":"0",h=Math.round((r.bounds?.x1||0)/50),g=Math.round((r.bounds?.y1||0)/50),b=Math.round((r.bounds?.width||0)/50),T=Math.round((r.bounds?.height||0)/50),x=`${p}|${l}|${o}|${c}|${d}|${u}|${h},${g},${b},${T}`;for(let S=0;S<x.length;S++)i^=x.charCodeAt(S),i=Math.imul(i,16777619)}return(i>>>0).toString(16)}function ha(a,e){let t=ye(a),s=ye(e);return{hasChanged:t!==s,previousHash:t,currentHash:s,nodeCountDelta:e.length-a.length}}function qi(a){let e=new Set;if(!a)return e;let t=a.split(",").map(s=>s.trim()).filter(Boolean);for(let s of t)if(s.includes("-")){let[i,n]=s.split("-").map(c=>c.trim()),r=parseInt(i,10),o=parseInt(n,10);if(!isNaN(r)&&!isNaN(o)){let[c,l]=r<=o?[r,o]:[o,r];for(let p=c;p<=l;p++)e.add(p)}}else{let i=parseInt(s,10);isNaN(i)||e.add(i)}return e}function er(a){let e=new Set,t=a.split(`
|
|
836
|
+
`);for(let s of t){let i=s.trim();if(!i.startsWith("#"))continue;let n=i.match(/#\s*@tags?:\s*(.+)/i);if(n){n[1].split(",").map(o=>o.trim().toLowerCase()).filter(Boolean).forEach(o=>e.add(o));continue}let r=i.match(/#\s*@([a-zA-Z0-9_-]+)/);r&&r[1].toLowerCase()!=="tags"&&r[1].toLowerCase()!=="tag"&&e.add(r[1].toLowerCase())}return Array.from(e)}function tr(a){let e=["",ge.bold.cyan(`\u{1F4CB} Parsed Test Steps (${a.length} total):`),ge.gray("\u250C\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),ge.gray("\u2502")+` ${ge.bold("#".padEnd(3))} `+ge.gray("\u2502")+` ${ge.bold("Type".padEnd(14))} `+ge.gray("\u2502")+` ${ge.bold("Target".padEnd(28))} `+ge.gray("\u2502")+` ${ge.bold("Value / Detail".padEnd(30))} `+ge.gray("\u2502")+` ${ge.bold("Optional".padEnd(8))} `+ge.gray("\u2502"),ge.gray("\u251C\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")];return a.forEach((t,s)=>{let i=`${s+1}`.padEnd(3),n=t.type.padEnd(14),r=(t.target||t.conditionTarget||"\u2014").slice(0,28).padEnd(28),o=(t.value||(t.durationMs?`${t.durationMs}ms`:t.expectedState)||"\u2014").slice(0,30).padEnd(30),c=(t.optional?"Yes":"No").padEnd(8);e.push(ge.gray("\u2502")+` ${ge.white(i)} `+ge.gray("\u2502")+` ${ge.cyan(n)} `+ge.gray("\u2502")+` ${ge.yellow(r)} `+ge.gray("\u2502")+` ${ge.white(o)} `+ge.gray("\u2502")+` ${ge.gray(c)} `+ge.gray("\u2502"))}),e.push(ge.gray(`\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
837
|
+
`)),e.join(`
|
|
838
|
+
`)}function ns(a,e,t=[],s="SKIPPED",i="Validation"){let n=new Date().toISOString(),r=s==="PASS";return{packageName:a||"none",deviceId:e||"none",startTime:n,endTime:n,durationSeconds:0,totalSteps:t.length,passedSteps:r?t.length:0,failedSteps:0,skippedSteps:r?0:t.length,warnSteps:0,errorsDetected:[],steps:t.map((o,c)=>({stepIndex:c+1,timestamp:n,phase:i,description:o.originalText,action:o.type,target:o.target,status:s,durationMs:0}))}}function ga(a,e){return a&&(e&&/password|passwd|pin\b|secret|token|api[_-]?key|auth|credential/i.test(e)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":a)}async function sr(a){let{outputDir:e,specName:t,currentSpecName:s,stepNum:i,step:n,error:r,stepStartTime:o,startTime:c,errorShot:l,lastHierarchy:p,driver:d,serial:u}=a;try{let h=`${t}_step_${i}`,g=Be.join(e,"failures",h);st.existsSync(g)||st.mkdirSync(g,{recursive:!0}),l&&await st.promises.writeFile(Be.join(g,"screenshot.png"),l);let b=p?.xml||await d.getUiHierarchy(u).catch(()=>"");b&&await st.promises.writeFile(Be.join(g,"hierarchy.xml"),b,"utf-8");let T=await d.getLogcatTail(150,u);await st.promises.writeFile(Be.join(g,"logcat_tail.log"),T,"utf-8");let x=p?.flat||[],S=n.target&&x.length>0?Rt(n.target,x.map(B=>B.text||B.contentDesc||"").filter(Boolean)):[];await st.promises.writeFile(Be.join(g,"match_scores.json"),JSON.stringify(S,null,2),"utf-8");let y={specName:s,stepNumber:i,stepType:n.type,target:n.target||n.value,error:r.message,timestamp:new Date().toISOString(),videoOffsetMs:Math.max(0,o-c)};await st.promises.writeFile(Be.join(g,"manifest.json"),JSON.stringify(y,null,2),"utf-8");let P=[{name:"manifest.json",data:Buffer.from(JSON.stringify(y,null,2),"utf-8")},{name:"logcat_tail.log",data:Buffer.from(T,"utf-8")},{name:"match_scores.json",data:Buffer.from(JSON.stringify(S,null,2),"utf-8")}];b&&P.push({name:"hierarchy.xml",data:Buffer.from(b,"utf-8")}),l&&P.push({name:"screenshot.png",data:l});let $=`${h}.zip`,R=Be.join(e,"failures",$);await Xi(R,P);let C=Be.join("failures",$).replace(/\\/g,"/");return console.log(ge.red(` \u{1F4C1} Failure Triage ZIP Bundle generated at: output/${C}`)),C}catch{return}}var wn=["ProgressBar","CircularProgressIndicator","LinearProgressIndicator","ContentLoadingProgressBar","LoadingView","ActivityIndicator"],vn=/(?:loading|spinner|shimmer|skeleton|progress[-_]?bar|refreshing)/i,ir=/^(?:loading|please wait|fetching|authenticating|syncing|processing)\.{0,3}$/i;function Os(a){if(!a||a.length===0)return{loading:!1};for(let e of a){if(e.className&&wn.some(t=>e.className.includes(t)))return{loading:!0,reason:`Active widget <${e.className}>`};if(e.resourceId&&vn.test(e.resourceId))return{loading:!0,reason:`Loading resource ID "${e.resourceId}"`};if(e.contentDesc&&ir.test(e.contentDesc.trim()))return{loading:!0,reason:`Loading description "${e.contentDesc}"`};if(e.text&&ir.test(e.text.trim()))return{loading:!0,reason:`Loading status text "${e.text}"`}}return{loading:!1}}async function Fs(a,e=4500,t=150){let s=Date.now(),i="",n=0,r=[];for(;Date.now()-s<e;){a.setLastHierarchy(null);let{flat:o}=await a.getCleanHierarchy(a.serial);if(r=o,Os(o).loading){n=0,i="",await new Promise(u=>setTimeout(u,220));continue}let l=ye(o);if(l===i&&l!=="0"){if(n++,n>=1)return{settled:!0,durationMs:Date.now()-s,finalHash:l,flat:r}}else n=0,i=l;let p=Date.now()-s,d=e-p;if(d<=0)break;await new Promise(u=>setTimeout(u,Math.min(t,d)))}return{settled:!1,durationMs:Date.now()-s,finalHash:i||(r.length>0?ye(r):"0"),flat:r}}function ne(a){return new Promise(e=>setTimeout(e,a))}function xn(a){let e=a.screenDimensions.height,t=a.navBarHeight>0?e-a.navBarHeight:e,s=a.navBarHeight>0?t*.94:e*I.gestures.bottomNavThresholdRatio;return{effectiveHeight:t,bottomThreshold:s}}var _s=class{type="TAP";async execute(e,t){let s=e.target,{width:i,height:n}=t.screenDimensions,r=Math.round(i*.5),{flat:o,matched:c}=await t.waitForTarget(s,t.serial,I.polling.defaultTimeoutMs,e);if(c.length===0&&t.upcomingSteps&&t.upcomingSteps.length>0&&!o.some($=>$.password===!0||$.className.includes("EditText")&&o.some(R=>R.text?.toLowerCase().includes("password")))){let $=t.upcomingSteps.findIndex(C=>C.type==="VERIFY"&&C.target&&t.matchNodes(o,C.target,C).length>0);if($!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[$].target}"`,skipCount:$};let R=t.upcomingSteps.findIndex(C=>C.type==="TAP"&&C.target&&t.matchNodes(o,C.target,C).length>0);if(R!==-1)return{fastForwarded:!0,reason:`Upcoming action "${t.upcomingSteps[R].target}" is directly actionable`,skipCount:R}}if(c.length===0){await t.driver.swipe(r,Math.round(n*.75),r,Math.round(n*.35),300,t.serial),await ne(350),t.setLastHierarchy(null);let P=await t.waitForTarget(s,t.serial,2e3,e);o=P.flat,c=P.matched}if(c.length===0)throw t.buildDiagnosticError(s,o,`Element matching "${s}" not found on current screen.`);let l=c.find(P=>P.clickable)||c[0];if(t.targetPackage&&!is(l.packageName,t.targetPackage))throw console.log(pe.red(` \u{1F6A8} [Jail Guard] Blocked Tap on foreign package "${l.packageName}". Target is "${t.targetPackage}".`)),await Ms(o,t.targetPackage,t.driver,t.serial),new Error(`Security Boundary Violation: Refused to tap element belonging to foreign application "${l.packageName}". Containment enforced.`);if(await t.ensureInViewport(l,t.serial)){let P=await t.waitForTarget(s,t.serial,1500,e);P.matched.length>0&&(o=P.flat,c=P.matched,l=c.find($=>$.clickable)||c[0])}let d=l.bounds.centerX,{effectiveHeight:u}=xn(t),h=l.bounds.centerY;if(l.bounds.y2>u&&(h=Math.min(Math.round((l.bounds.y1+u)/2),u-15)),h=Math.min(h,l.bounds.y2-2),h=Math.max(h,l.bounds.y1+2),h>n*.5&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(pe.gray(` [Keyboard] Target occluded by soft keyboard (Y=${h} > ${Math.round(n*.5)}). Dismissing...`)),await t.driver.pressBack(t.serial),await ne(300),t.setLastHierarchy(null))}catch{}let g=Ue(o,t.screenDimensions),b=l.contentDesc||l.text||l.resourceId;console.log(pe.gray(` [Tap Target] (${d}, ${h}) for "${b||s}"`));let T=t.lastHierarchy?.hash;await t.driver.tap(d,h,t.serial),t.setLastHierarchy(null);let x=t.upcomingSteps&&t.upcomingSteps[0],S=x?.target?t.matchNodes(o,x.target,x).length>0:!1;if(x&&!S&&(x.type==="VERIFY"||x.type==="TAP")){let P=await Fs(t,4500),R=Ue(P.flat,t.screenDimensions)!==g,C=x.target?t.matchNodes(P.flat,x.target,x).length>0:!1;if(!R&&!C&&t.matchNodes(P.flat,s,e).length>0)throw new Error(`Navigation failed: Tap on "${s}" did not transition away from the current screen. Next expected element "${x.target}" is not visible.`)}else await ne(I.settle.tapMs);b&&ae(b)!==ae(s)&&t.memory.recordSuccess("TAP",s,b,l.contentDesc?"contentDesc":l.text?"text":"resourceId",1,void 0,T)}},Hs=class{type="LONG_PRESS";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,I.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Element matching "${s}" not found for long-press.`);let r=n[0];if(await t.ensureInViewport(r,t.serial)){let c=await t.waitForTarget(s,t.serial,1500,e);c.matched.length>0&&(r=c.matched[0])}await t.driver.swipe(r.bounds.centerX,r.bounds.centerY,r.bounds.centerX,r.bounds.centerY,I.gestures.longPressDurationMs,t.serial),await ne(300),t.setLastHierarchy(null)}},os=class{type="TYPE";async execute(e,t){let s=e.target,i=e.value??"",n=[],r=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<I.polling.hierarchyCacheTtlMs){let d=t.findTargetInputField(t.lastHierarchy.flat,s,i);d&&(n=t.lastHierarchy.flat,r=d)}if(r||(n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i)),!r){let d=Date.now();for(;Date.now()-d<2e3&&(await ne(200),n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i),!r););}if(!r&&t.upcomingSteps&&t.upcomingSteps.length>0&&!n.some(u=>u.className.includes("EditText"))){let u=t.upcomingSteps.findIndex(h=>h.type==="VERIFY"&&h.target&&t.matchNodes(n,h.target,h).length>0);if(u!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[u].target}" and form is completed`,skipCount:u}}if(!r)throw t.buildDiagnosticError(s,n,`Input field matching "${s}" not found.`);if(t.targetPackage&&!is(r.packageName,t.targetPackage))throw console.log(pe.red(` \u{1F6A8} [Jail Guard] Blocked Type on foreign package "${r.packageName}". Target is "${t.targetPackage}".`)),await Ms(n,t.targetPackage,t.driver,t.serial),new Error(`Security Boundary Violation: Refused to type into element belonging to foreign application "${r.packageName}". Containment enforced.`);if(r.text&&r.text===i){console.log(pe.gray(` [Input Field] Already contains desired value "${i}". Skipping typing.`));return}if(await t.ensureInViewport(r,t.serial)){n=(await t.getCleanHierarchy(t.serial)).flat;let u=t.findTargetInputField(n,s,i);u&&(r=u)}let{height:c}=t.screenDimensions;if(r.bounds.centerY>c*.5&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(pe.gray(" [Keyboard] Input field occluded by soft keyboard. Dismissing before focus...")),await t.driver.pressBack(t.serial),await ne(300),t.setLastHierarchy(null))}catch{}let l=t.lastHierarchy?.hash;await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await ne(I.settle.inputFocusMs),await t.driver.clearField(t.serial),await ne(I.settle.inputClearMs),await t.driver.inputText(i,t.serial),await ne(I.settle.inputDoneMs),t.setLastHierarchy(null);let p=r.contentDesc||r.resourceId;p&&ae(p)!==ae(s)&&t.memory.recordSuccess("TYPE",s,p,r.contentDesc?"contentDesc":"resourceId",1,void 0,l)}},Bs=class{type="CLEAR";async execute(e,t){let s=e.target,i=[],n=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<I.polling.hierarchyCacheTtlMs&&(n=t.findTargetInputField(t.lastHierarchy.flat,s),n&&(i=t.lastHierarchy.flat)),n||(i=(await t.getCleanHierarchy(t.serial)).flat,n=t.findTargetInputField(i,s)),!n){let o=t.matchNodes(i,s,e);o.length>0&&(n=o[0])}if(!n)throw t.buildDiagnosticError(s,i,`Input field matching "${s}" not found to clear.`);await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await ne(300);let r=t.driver;r.clearField?await r.clearField(t.serial):r.clearInput&&await r.clearInput(50,t.serial),await ne(200),t.setLastHierarchy(null)}},Us=class{type="VERIFY";async execute(e,t){let s=e.target,i=e.expectedState||"visible";if(e.negative===!0||i==="absent"||i==="hidden"){let u=await t.getCleanHierarchy(t.serial);if(t.matchNodes(u.flat,s,e).length>0)throw new Error(`Negative assertion failed: "${s}" was expected to be NOT visible, but is present on screen.`);return}let{width:r,height:o}=t.screenDimensions,c=Math.round(r*.5),l=!1,p=[],d;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<I.polling.verifyCacheTtlMs&&(d=t.matchNodes(t.lastHierarchy.flat,s,e)[0],d&&(p=t.lastHierarchy.flat,l=!0,t.lastHierarchy.timestamp=Date.now())),!l){p=(await t.getCleanHierarchy(t.serial)).flat,d=t.matchNodes(p,s,e)[0],d?l=!0:Os(p).loading&&(console.log(pe.cyan(" \u23F3 [Quiescence] Loading indicator detected in Verify. Waiting for screen to settle...")),p=(await Fs(t,4500)).flat,d=t.matchNodes(p,s,e)[0],d&&(l=!0));let h=Date.now();for(;!l&&Date.now()-h<I.polling.extendedTimeoutMs;){if(p=(await t.getCleanHierarchy(t.serial)).flat,d=t.matchNodes(p,s,e)[0],d){l=!0,t.lastHierarchy&&(t.lastHierarchy.timestamp=Date.now()),await ne(400);break}await ne(200)}}if(l||(await t.driver.swipe(c,Math.round(o*.75),c,Math.round(o*.35),300,t.serial),await ne(400),p=(await t.getCleanHierarchy(t.serial)).flat,d=t.matchNodes(p,s,e)[0],d&&(l=!0)),!l){if(t.upcomingSteps&&t.upcomingSteps.length>0&&!p.some(h=>h.password===!0||h.className.includes("EditText")&&p.some(g=>g.text?.toLowerCase().includes("password")))){let h=t.upcomingSteps.findIndex(g=>g.type==="VERIFY"&&g.target&&t.matchNodes(p,g.target,g).length>0);if(h!==-1)return{fastForwarded:!0,reason:`Screen is already on "${t.upcomingSteps[h].target}"`,skipCount:h}}throw await t.driver.swipe(c,Math.round(o*.35),c,Math.round(o*.75),300,t.serial),await ne(300),t.buildDiagnosticError(s,p,`Verification assertion failed: "${s}" is not visible on screen.`)}if(d&&i==="disabled"&&d.enabled)throw new Error(`State assertion failed: "${s}" was expected to be DISABLED, but is enabled.`);if(d&&i==="enabled"&&!d.enabled)throw new Error(`State assertion failed: "${s}" was expected to be ENABLED, but is disabled.`)}},js=class{type="BACK";async execute(e,t){let{flat:s}=await t.getCleanHierarchy(t.serial),i=Ls(s);if(i&&At(i)){console.log(pe.yellow(` \u{1F6E1}\uFE0F [Jail Guard] Device is already on launcher (${i}). Suppressing Back press to prevent app exit loop.`)),t.targetPackage&&await t.driver.launchApp(t.targetPackage,t.serial);return}await t.driver.pressKey(4,t.serial),await ne(I.settle.backMs),t.setLastHierarchy(null)}},Ys=class{type="SCROLL";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5);if(e.target&&e.target!=="up"&&e.target!=="down"){let o=e.target,c=e.direction||"down",l=!1;for(let p=0;p<5;p++){let{flat:d}=await t.getCleanHierarchy(t.serial),u=t.matchNodes(d,o,e);if(u.length>0){await t.ensureInViewport(u[0],t.serial),l=!0;break}c==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await ne(I.settle.scrollMs),t.setLastHierarchy(null)}if(!l){let{flat:p}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(o,p,`Element "${o}" not found after scrolling ${e.direction||"down"}.`)}}else e.target==="up"||e.direction==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await ne(I.settle.scrollMs),t.setLastHierarchy(null)}},Ws=class{type="SWIPE";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5),r=e.direction||"left";if(e.target){let{matched:d}=await t.waitForTarget(e.target,t.serial,2500,e);if(d.length>0){let u=d[0],h=r==="left"?u.bounds.x2-40:r==="right"?u.bounds.x1+40:u.bounds.centerX,g=r==="left"?u.bounds.x1+40:r==="right"?u.bounds.x2-40:u.bounds.centerX,b=r==="up"?u.bounds.y2-40:r==="down"?u.bounds.y1+40:u.bounds.centerY,T=r==="up"?u.bounds.y1+40:r==="down"?u.bounds.y2-40:u.bounds.centerY;await t.driver.swipe(h,b,g,T,I.gestures.swipeDurationMs,t.serial),await ne(400),t.setLastHierarchy(null);return}}let o=r==="left"?Math.round(s*.8):r==="right"?Math.round(s*.2):n,c=r==="left"?Math.round(s*.2):r==="right"?Math.round(s*.8):n,l=Math.round(r==="up"?i*.75:r==="down"?i*.35:i*.5),p=Math.round(r==="up"?i*.35:r==="down"?i*.75:i*.5);await t.driver.swipe(o,l,c,p,I.gestures.swipeDurationMs,t.serial),await ne(400),t.setLastHierarchy(null)}},Js=class{type="TOGGLE";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,I.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Toggle element matching "${s}" not found.`);let r=n.find(c=>c.clickable)||n[0];if(await t.ensureInViewport(r,t.serial)){let c=await t.waitForTarget(s,t.serial,1500,e);c.matched.length>0&&(r=c.matched.find(l=>l.clickable)||c.matched[0])}if(e.desiredState!==void 0&&r.checked!==void 0&&r.checked===e.desiredState){console.log(pe.gray(` [Toggle] "${s}" is already in desired state (${e.desiredState?"ON":"OFF"}).`));return}await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await ne(I.settle.toggleMs),t.setLastHierarchy(null)}},Vs=class{type="SELECT";async execute(e,t){let s=e.target,i=e.value,{flat:n,matched:r}=await t.waitForTarget(s,t.serial,I.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,n,`Dropdown / picker element matching "${s}" not found.`);let o=r.find(p=>p.clickable)||r[0];await t.driver.tap(o.bounds.centerX,o.bounds.centerY,t.serial),await ne(I.settle.selectMs),t.setLastHierarchy(null);let c=await t.waitForTarget(i,t.serial,I.polling.defaultTimeoutMs);if(c.matched.length===0)throw t.buildDiagnosticError(i,c.flat,`Dropdown option "${i}" not found.`);let l=c.matched[0];await t.driver.tap(l.bounds.centerX,l.bounds.centerY,t.serial),await ne(400),t.setLastHierarchy(null)}},zs=class{type="LAUNCH_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to launch app.");t.targetPackage=s,await t.driver.launchApp(s,t.serial),await ne(I.settle.launchMs),t.setLastHierarchy(null)}},Ks=class{type="RESTART_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to restart app.");t.targetPackage=s,await t.driver.restartApp(s,t.serial),await ne(I.settle.launchMs),t.setLastHierarchy(null)}},Xs=class{type="TERMINATE_APP";async execute(e,t){let s=e.target||await t.driver.getForegroundPackage(t.serial);s&&await t.driver.forceStop(s,t.serial),await ne(I.settle.stopMs),t.setLastHierarchy(null)}},Gs=class{type="CLEAR_DATA";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to clear data.");await t.driver.clearAppData(s,t.serial),await ne(1e3),t.setLastHierarchy(null)}},Qs=class{type="GRANT_PERMISSION";async execute(e,t){let s=e.value,i=e.target||await t.driver.getForegroundPackage(t.serial);if(!i)throw new Error("Foreground package not detected for grant permission.");await t.driver.grantPermission(i,s,t.serial),await ne(400)}},Zs=class{type="DEEP_LINK";async execute(e,t){let s=e.target;await t.driver.openDeepLink(s,t.serial),await ne(I.settle.launchMs),t.setLastHierarchy(null)}},qs=class{type="WAIT";async execute(e,t){await ne(e.durationMs||1e3)}},ei=class{type="IF_VISIBLE";async execute(e,t){let s=e.conditionTarget||e.target;if(!s)return;let i=!1;try{let{matched:n}=await t.waitForTarget(s,t.serial,1500,e);i=n.length>0}catch{i=!1}i?(console.log(pe.cyan(` [Conditional] Condition met: "${s}" is visible.`)),e.thenSteps&&e.thenSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.thenSteps,t)):(console.log(pe.gray(` [Conditional] Condition not met: "${s}" is not visible.`)),e.elseSteps&&e.elseSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.elseSteps,t))}},ti=class{type="LOOP";async execute(e,t){let s=I.flow?.maxLoopIterations||50,i=Math.min(e.loopCount||1,s),n=e.childSteps||[];if(!(n.length===0||!t.executeChildSteps)){console.log(pe.cyan(` [Loop] Starting loop iteration (1 to ${i})...`));for(let r=1;r<=i;r++){e.loopVariable&&t.variables.set(e.loopVariable,String(r)),t.loopStack.push({current:r,total:i,variable:e.loopVariable});try{await t.executeChildSteps(n,t)}finally{t.loopStack.pop()}}}}},si=class{type="WAIT_UNTIL";async execute(e,t){let s=e.target,i=e.durationMs||I.flow?.waitUntilTimeoutMs||1e4,n=e.expectedState||"visible";console.log(pe.gray(` [Wait Until] Waiting for "${s}" to be ${n} (up to ${i}ms)...`));let r=Date.now(),o=!1;for(;Date.now()-r<i;){try{let{matched:c}=await t.waitForTarget(s,t.serial,1e3,e);if(c.length>0){let l=c[0];if(n==="enabled"&&!l.enabled){await ne(250);continue}o=!0;break}}catch{}await ne(250)}if(!o){let{flat:c}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(s,c,`WaitUntil assertion failed: "${s}" did not become ${n} within ${i}ms.`)}}},ii=class{type="SET_VARIABLE";async execute(e,t){let s=e.variableName,i=e.variableExpression||"";i=Pt(i,Object.fromEntries(t.variables));let n=Ri(i);t.variables.set(s,n),console.log(pe.cyan(` [Variable] $${s} = "${n}"`))}},ri=class{type="DEVICE_STATE";async execute(e,t){let s=e.deviceAction,i=e.deviceStateValue;switch(s){case"wifi":{let n=i===!0||i==="on"||i==="enable";console.log(pe.cyan(` [Device] Setting Wi-Fi: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setWifiEnabled(n,t.serial);break}case"airplane":{let n=i===!0||i==="on"||i==="enable";console.log(pe.cyan(` [Device] Setting Airplane Mode: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setAirplaneMode(n,t.serial);break}case"orientation":{let n=i==="landscape"?"landscape":"portrait";console.log(pe.cyan(` [Device] Setting Orientation: ${n.toUpperCase()}`)),await t.driver.setOrientation(n,t.serial);break}case"notifications":{let n=i==="open"||i==="expand"||i===!0;console.log(pe.cyan(` [Device] ${n?"Expanding":"Collapsing"} Notification Shade`)),n?await t.driver.openNotificationShade(t.serial):await t.driver.collapseNotificationShade(t.serial);break}default:throw new Error(`Unsupported device action: ${s}`)}await ne(400),t.setLastHierarchy(null)}},ni=class{type="RUN_JS";async execute(e,t){let s=e.jsCode||e.value||"";if(!s)return;console.log(pe.cyan(" [JS Hook] Executing sandboxed JavaScript snippet..."));let i={vars:Object.fromEntries(t.variables),setVar:(r,o)=>{t.variables.set(r,String(o))},getVar:r=>t.variables.get(r),console:{log:(...r)=>console.log(pe.gray(" [JS Output]",...r)),error:(...r)=>console.error(pe.red(" [JS Error]",...r))}},n=rr.createContext(i);rr.runInContext(s,n,{timeout:3e3});for(let[r,o]of Object.entries(i.vars))t.variables.set(r,String(o))}},oi=class{type="ENTER_OTP";async execute(e,t){console.log(pe.cyan(" [OTP Capture] Detecting verification code..."));let s=null;if(process.env.PROMPTTEST_MOCK_OTP)s=process.env.PROMPTTEST_MOCK_OTP.trim(),console.log(pe.gray(` [OTP Capture] Captured code from environment: ${s}`));else try{let{stdout:i}=await t.driver.execAdb(["shell","logcat","-d","-t","200","-s","SMSDispatcher:V","SmsMessage:V","NotificationService:V","ActivityManager:I"],t.serial),n=i.match(/(?:code|otp|pin|verification)[^0-9\r\n]{0,35}(\d{4,8})\b/i)||i.match(/\b(\d{4,8})\s*(?:is your verification|is your otp)/i);n&&(s=n[1],console.log(pe.gray(` [OTP Capture] Captured code from logcat: ${s}`)))}catch{}if(s||(s="123456",console.log(pe.yellow(` [OTP Capture] No live code detected; using simulated OTP: ${s}`))),e.target){let i={originalText:`Type '${s}' into '${e.target}'`,type:"TYPE",target:e.target,value:s};return new os().execute(i,t)}else{let{flat:i}=await t.getCleanHierarchy(t.serial),n=t.findTargetInputField(i,"code",s)||i.find(r=>r.className.includes("EditText"));n?(await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await ne(250),await t.driver.inputText(s,t.serial)):await t.driver.inputText(s,t.serial)}}},ai=class{type="API_REQUEST";async execute(e,t){let s=e.apiMethod||"GET",i=e.apiUrl||"";if(!i)throw new Error("API_REQUEST requires a valid target URL.");console.log(pe.cyan(` [API Request] ${s} ${i}...`));let n={method:s,headers:{"Content-Type":"application/json",Accept:"application/json"}};e.apiBody&&(s==="POST"||s==="PUT"||s==="PATCH")&&(n.body=e.apiBody);let r=await fetch(i,n);if(e.apiExpectedStatus!==void 0){if(r.status!==e.apiExpectedStatus)throw new Error(`API status assertion failed for ${i}: expected HTTP ${e.apiExpectedStatus}, but received HTTP ${r.status}`);console.log(pe.green(` \u2714 API Status HTTP ${r.status} matched expectation.`))}if(e.apiStorePath&&e.apiStoreVariable)try{let o=await r.text(),c=JSON.parse(o),l=this.resolveJsonPath(c,e.apiStorePath);l!==void 0&&(t.variables.set(e.apiStoreVariable,String(l)),console.log(pe.cyan(` [Variable] $${e.apiStoreVariable} = "${l}" (from ${e.apiStorePath})`)))}catch(o){qe.warn(`Failed to parse JSON response for path extraction: ${o.message}`)}}resolveJsonPath(e,t){let s=t.replace(/^\$\.?/,"").split("."),i=e;for(let n of s){if(i==null||typeof i!="object")return;i=i[n]}return i}},ci=class{type="EMAIL_ASSERT";async execute(e,t){let s=e.emailRecipient||"",i=e.emailSubject||"";console.log(pe.cyan(` [Email Assertion] Checking email to "${s}" with subject "${i}"...`));let n=[];if(process.env.PROMPTTEST_MOCK_EMAILS)try{n=JSON.parse(process.env.PROMPTTEST_MOCK_EMAILS)}catch{n=[]}let r=n.find(o=>o.to.toLowerCase()===s.toLowerCase()&&o.subject.toLowerCase().includes(i.toLowerCase()));if(!r){if(n.length===0){if(!s.includes("@"))throw new Error(`Invalid email recipient address: "${s}"`);console.log(pe.yellow(" \u26A0 No mock inbox configured (PROMPTTEST_MOCK_EMAILS); simulated email check passed."));return}throw new Error(`Email assertion failed: No email to "${s}" with subject "${i}" found.`)}if(e.emailBodyContains&&r.body&&!r.body.includes(e.emailBodyContains))throw new Error(`Email body assertion failed: Expected email to contain "${e.emailBodyContains}", but content did not match.`);console.log(pe.green(" \u2714 Email verified successfully."))}},Tn=[new _s,new Hs,new os,new Bs,new Us,new js,new Ys,new Ws,new Js,new Vs,new zs,new Ks,new Xs,new Gs,new Qs,new Zs,new qs,new ei,new ti,new si,new ii,new ri,new ni,new oi,new ai,new ci],nr=new Map(Tn.map(a=>[a.type,a]));var $t=class{providerName="heuristic";async resolveIntent(e,t){let s=ae(e),i=s.includes("login")||s.includes("log in")||s.includes("sign in")||s.includes("signin");if(i&&(s.includes("student")||s.includes("learner")))return[{originalText:"Type 'student@coachconnect.com' into 'Email'",type:"TYPE",target:"Email",value:"student@coachconnect.com"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}];if(i&&(s.includes("teacher")||s.includes("coach")||s.includes("trainer")))return[{originalText:"Type 'teacher@coachconnect.com' into 'Email'",type:"TYPE",target:"Email",value:"teacher@coachconnect.com"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}];if(i&&s.includes("admin"))return[{originalText:"Type 'admin@coachconnect.com' into 'Email'",type:"TYPE",target:"Email",value:"admin@coachconnect.com"},{originalText:"Type 'AdminPass123!' into 'Password'",type:"TYPE",target:"Password",value:"AdminPass123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}];if(i)return[{originalText:"Type 'user@example.com' into 'Email'",type:"TYPE",target:"Email",value:"user@example.com"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}];if(s.includes("sign up with random user")||s.includes("register new user"))return[{originalText:"Type $RANDOM_NAME into 'Name'",type:"TYPE",target:"Name",value:"$RANDOM_NAME"},{originalText:"Type $RANDOM_EMAIL into 'Email'",type:"TYPE",target:"Email",value:"$RANDOM_EMAIL"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Create Account'",type:"TAP",target:"Create Account"}];if(s.includes("dismiss dialog")||s.includes("close modal")||s.includes("dismiss popup"))return[{originalText:"Tap 'Close'",type:"TAP",target:"Close",optional:!0},{originalText:"Tap 'Dismiss'",type:"TAP",target:"Dismiss",optional:!0},{originalText:"Press back",type:"BACK",optional:!0}];let n=e.match(/(?:login|sign\s*in)\s+(?:with\s+)?(?:user(?:name)?|email)?\s*["']([^"']+)["']\s*(?:and\s+)?(?:password|pass)?\s*["']([^"']+)["']/i);if(n){let o=n[1],c=n[2];return[{originalText:`Type "${o}" into "Email"`,type:"TYPE",target:"Email",value:o},{originalText:`Type "${c}" into "Password"`,type:"TYPE",target:"Password",value:c},{originalText:'Tap "Sign In"',type:"TAP",target:"Sign In"}]}let r=e.match(/search\s+(?:for\s+)?["']([^"']+)["']/i);if(r){let o=r[1];return[{originalText:'Tap "Search"',type:"TAP",target:"Search"},{originalText:`Type "${o}" into "Search"`,type:"TYPE",target:"Search",value:o},{originalText:'Tap "Search"',type:"TAP",target:"Search"}]}return s.includes("checkout")||s.includes("proceed to payment")?[{originalText:'Tap "Checkout"',type:"TAP",target:"Checkout"},{originalText:'Assert "Payment" is visible',type:"VERIFY",target:"Payment"}]:s.includes("logout")||s.includes("log out")||s.includes("sign out")?[{originalText:'Tap "Settings"',type:"TAP",target:"Settings",optional:!0},{originalText:'Tap "Log Out"',type:"TAP",target:"Log Out"},{originalText:'Tap "Confirm"',type:"TAP",target:"Confirm",optional:!0}]:null}async findSuggestions(e,t,s){let i=[],n=ae(e),r=new Set,o=Vi(e,s?.locale);for(let d of o){let u=t.find(h=>h.bounds.width>0&&h.bounds.height>0&&(de(d,h.text)||de(d,h.contentDesc)));if(u){let h=(u.text||u.contentDesc||d).trim();r.has(h)||(r.add(h),i.push({text:h,score:.9,node:u,strategy:"synonym",reason:`Direct synonym match for "${e}" via semantic dictionary`}))}}for(let d of t)if(d.resourceId&&d.bounds.width>0&&d.bounds.height>0&&d.resourceId.toLowerCase().split(/[:/_]/).some(g=>g===n||n.includes(g))){let g=(d.text||d.contentDesc||d.resourceId).trim();r.has(g)||(r.add(g),i.push({text:g,score:.85,node:d,strategy:"exact",reason:`Resource-ID segment matches target "${e}"`}))}let c=[];for(let d of t)d.bounds.width>0&&d.bounds.height>0&&(d.text&&d.text.trim().length>1&&c.push({text:d.text.trim(),node:d}),d.contentDesc&&d.contentDesc.trim().length>1&&c.push({text:d.contentDesc.trim(),node:d}));let l=Array.from(new Set(c.map(d=>d.text))),p=Rt(e,l,5);for(let d of p)if(d.score>=.7&&!r.has(d.text)){r.add(d.text);let u=c.find(h=>h.text===d.text)?.node;i.push({text:d.text,score:d.score,node:u,strategy:"fuzzy",reason:`String similarity match (${Math.round(d.score*100)}%)`})}return i.sort((d,u)=>u.score-d.score)}};var Bt=class{providerName="mock";mockIntents=new Map;mockSuggestions=new Map;constructor(){this.mockIntents.set("log in to account",[{originalText:"Type 'test@example.com' into 'Email'",type:"TYPE",target:"Email",value:"test@example.com"},{originalText:"Type 'Password123' into 'Password'",type:"TYPE",target:"Password",value:"Password123"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}])}setMockIntent(e,t){this.mockIntents.set(e.toLowerCase().trim(),t)}setMockSuggestion(e,t){this.mockSuggestions.set(e.toLowerCase().trim(),t)}async resolveIntent(e,t){let s=e.toLowerCase().trim();return this.mockIntents.has(s)?this.mockIntents.get(s):null}async findSuggestions(e,t,s){let i=e.toLowerCase().trim();return this.mockSuggestions.has(i)?this.mockSuggestions.get(i):new $t().findSuggestions(e,t)}},as=class{providerName;config;heuristicFallback;constructor(e){this.config=e,this.providerName=e.provider,this.heuristicFallback=new $t}async resolveIntent(e,t){if(this.config.provider==="mock")return new Bt().resolveIntent(e,t);try{let s=`You are a test automation engineer generating steps for PromptTest.
|
|
839
|
+
Convert the following high-level user intent into a concrete sequence of plain-English test steps.
|
|
840
|
+
Valid syntax examples:
|
|
841
|
+
- Tap 'Button Label'
|
|
842
|
+
- Type 'value' into 'Field Label'
|
|
843
|
+
- Verify 'Text' is visible
|
|
844
|
+
- Scroll down
|
|
845
|
+
- Press back
|
|
846
|
+
- Wait 1000
|
|
847
|
+
|
|
848
|
+
User Intent: "${e}"
|
|
849
|
+
|
|
850
|
+
Return ONLY a JSON array of plain strings representing each step, e.g.:
|
|
851
|
+
["Type 'user@test.com' into 'Email'", "Tap 'Next'"]`,i=await this.callLlm(s);if(!i)return this.heuristicFallback.resolveIntent(e,t);let n=i.match(/\[[\s\S]*\]/);return n?JSON.parse(n[0]).map(c=>({originalText:c,type:c.startsWith("Tap")?"TAP":c.startsWith("Type")?"TYPE":"VERIFY"})):this.heuristicFallback.resolveIntent(e,t)}catch(s){return qe.warn(`LLM intent resolution failed (${s.message}), falling back to heuristic engine.`),this.heuristicFallback.resolveIntent(e,t)}}async findSuggestions(e,t,s){if(this.config.provider==="mock")return new Bt().findSuggestions(e,t,s);try{let i=t.filter(l=>l.bounds.width>0&&l.bounds.height>0&&(l.text||l.contentDesc)).map(l=>({text:l.text||l.contentDesc,id:l.resourceId||"",class:l.className.split(".").pop()})).slice(0,30),n=`A UI test failed because an element named "${e}" could not be found.
|
|
852
|
+
Here are the visible UI elements on the current Android screen:
|
|
853
|
+
${JSON.stringify(i,null,2)}
|
|
854
|
+
|
|
855
|
+
Identify the best matching replacement element for "${e}".
|
|
856
|
+
Respond ONLY with a JSON object in this format:
|
|
857
|
+
{"bestMatch": "Exact Text of Best Element", "confidence": 0.85, "reason": "Reason for match"}`,r=await this.callLlm(n);if(!r)return this.heuristicFallback.findSuggestions(e,t,s);let o=r.match(/\{[\s\S]*\}/);if(!o)return this.heuristicFallback.findSuggestions(e,t,s);let c=JSON.parse(o[0]);if(c.bestMatch){let l=t.find(p=>p.text===c.bestMatch||p.contentDesc===c.bestMatch);return[{text:c.bestMatch,score:typeof c.confidence=="number"?c.confidence:.85,node:l,strategy:"llm",reason:c.reason||"LLM semantic match"},...await this.heuristicFallback.findSuggestions(e,t,s)]}}catch(i){qe.warn(`LLM self-healing failed (${i.message}), using heuristic suggestions.`)}return this.heuristicFallback.findSuggestions(e,t,s)}async callLlm(e){let t=this.config.timeoutMs||8e3,s=new AbortController,i=setTimeout(()=>s.abort(),t);try{if(this.config.provider==="openai"){let n=this.config.apiKey||process.env.OPENAI_API_KEY;if(!n)throw new Error("OPENAI_API_KEY is not set");let r=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:this.config.model||"gpt-4o-mini",messages:[{role:"user",content:e}],temperature:.1}),signal:s.signal});if(!r.ok)throw new Error(`OpenAI HTTP ${r.status}: ${await r.text()}`);return(await r.json()).choices?.[0]?.message?.content||null}if(this.config.provider==="anthropic"){let n=this.config.apiKey||process.env.ANTHROPIC_API_KEY;if(!n)throw new Error("ANTHROPIC_API_KEY is not set");let r=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.config.model||"claude-3-haiku-20240307",max_tokens:1024,messages:[{role:"user",content:e}]}),signal:s.signal});if(!r.ok)throw new Error(`Anthropic HTTP ${r.status}: ${await r.text()}`);return(await r.json()).content?.[0]?.text||null}if(this.config.provider==="ollama"){let n=this.config.endpoint||process.env.OLLAMA_BASE_URL||"http://localhost:11434",r=await fetch(`${n.replace(/\/$/,"")}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.config.model||"llama3.2",messages:[{role:"user",content:e}],stream:!1}),signal:s.signal});if(!r.ok)throw new Error(`Ollama HTTP ${r.status}: ${await r.text()}`);return(await r.json()).message?.content||null}return null}finally{clearTimeout(i)}}};Fe();function li(a){let e=a?.provider||I.ai.provider;if(e==="heuristic")return new $t;if(e==="mock")return new Bt;let t={provider:e,model:a?.model||I.ai.model,endpoint:a?.endpoint||I.ai.endpoint};return new as(t)}import or from"fs";import di from"path";var Ut=class{static extractDataDirective(e,t=process.cwd()){let s=e.split(`
|
|
858
|
+
`),i="",n=-1;for(let p=0;p<s.length;p++){let d=s[p].trim();if(d.startsWith("#!data")||d.startsWith("#! data")){i=d,n=p;break}}if(n===-1)return null;let r=i.replace(/^#!\s*data\s*/,"").trim(),o=[],c="inline";if(r.startsWith("[")||r.startsWith("{"))try{let p=JSON.parse(r);o=Array.isArray(p)?p.map(d=>this.stringifyObject(d)):[this.stringifyObject(p)]}catch(p){throw new Error(`Failed to parse inline #!data JSON directive: ${p.message}`)}else{let p=r.replace(/^['"]+|['"]+$/g,"").trim(),d=di.isAbsolute(p)?p:di.resolve(t,p);c=d,o=this.loadFromFile(d)}let l=[...s];return l.splice(n,1),{directive:i,source:c,cleanedSpec:l.join(`
|
|
859
|
+
`),rows:o}}static loadFromFile(e){if(!or.existsSync(e))throw new Error(`Data file not found: ${e}`);let t=or.readFileSync(e,"utf-8");return di.extname(e).toLowerCase()===".json"?this.parseJson(t):this.parseCsv(t)}static parseJson(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(s=>this.stringifyObject(s)):[this.stringifyObject(t)]}catch(t){throw new Error(`Invalid JSON data file format: ${t.message}`)}}static parseCsv(e){let t=this.splitCsvLines(e);if(t.length<2)return[];let s=this.parseCsvRow(t[0]).map(n=>n.trim().replace(/^['"]+|['"]+$/g,"")),i=[];for(let n=1;n<t.length;n++){if(!t[n].trim())continue;let o=this.parseCsvRow(t[n]),c={};for(let l=0;l<s.length;l++){let p=s[l];c[p]=o[l]!==void 0?o[l].trim():""}i.push(c)}return i}static filterRows(e,t){if(!t)return e;let s=[...e];if(t.onlyRow!==void 0&&t.onlyRow>0){let i=t.onlyRow-1;if(i<s.length)return[s[i]];throw new Error(`Requested --only-row=${t.onlyRow}, but dataset only contains ${s.length} row(s).`)}if(t.iterations!==void 0&&t.iterations>0){if(t.iterations<=s.length)return s.slice(0,t.iterations);let i=[];for(let n=0;n<t.iterations;n++)i.push(s[n%s.length]);return i}return s}static parseCsvRow(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='"',n++):i=!i:r===","&&!i?(t.push(s),s=""):s+=r}return t.push(s),t}static splitCsvLines(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='""',n++):(i=!i,s+=r):(r===`
|
|
860
|
+
`||r==="\r")&&!i?(r==="\r"&&e[n+1]===`
|
|
861
|
+
`&&n++,s.trim().length>0&&t.push(s),s=""):s+=r}return s.trim().length>0&&t.push(s),t}static stringifyObject(e){if(!e||typeof e!="object")return{};let t={};for(let[s,i]of Object.entries(e))t[s]=i!=null?String(i):"";return t}};import Cn from"http";import Q from"fs";import X from"path";import br from"os";import{fileURLToPath as Nn}from"url";Ne();Ne();Ss();import ke from"fs";import Se from"path";import Y from"chalk";Fe();import{spawn as Pn}from"child_process";import ar from"readline";import{createRequire as En}from"module";var kn=En(import.meta.url),pi="1.1.0";try{pi=kn("../../package.json").version||"1.1.0"}catch{}var ft=class{onStep;driver;deviceLock=null;isRecording=!1;recordedSteps=[];existingSteps=[];existingFileHeader=[];lastHierarchyFlat=[];lastScreenTitle="";visitedScreens=[];targetPackage=null;isAppendMode=!1;resolvedOutputPath="";resolvedReportPath="";activeInput=null;geteventProcess=null;isRefreshingHierarchy=!1;targetSerial="";touchMaxX=I.screen.fallbackWidth;touchMaxY=I.screen.fallbackHeight;displayWidth=I.screen.fallbackWidth;displayHeight=I.screen.fallbackHeight;activeTouchX=-1;activeTouchY=-1;touchDownTime=0;isTouchActive=!1;isSwipeGesture=!1;lastHierarchyTimestamp=0;lastTapTimestamp=0;lastRecordedTapTarget="";inFlightTapQueue=[];inputDebounceTimer=null;logcatEventProcess=null;logcatCrashProcess=null;hierarchyCacheTime=0;hierarchyStale=!0;lastScrollTimestamp=0;lastScrollDirection="";currentScreenName="";sessionScreenSections=[];sessionStartTime=0;screenshotDir="";screenshotCounter=0;crashDetected=!1;lastScreenTransitionTime=0;constructor(e){this.driver=e||Pe}flushToDisk(){if(this.resolvedOutputPath)try{this.saveSpec(this.resolvedOutputPath)}catch{}if(this.resolvedReportPath)try{this.saveReport(this.resolvedReportPath)}catch{}}appendStep(e,t){if(this.recordedSteps[this.recordedSteps.length-1]!==e){this.recordedSteps.push(e),this.flushToDisk(),t&&console.log(t);try{this.onStep?.(e)}catch{}}}extractBrandSlug(e){if(!e)return"app";let t=new Set(["com","org","net","io","in","co","uk","de","fr","us","ai","dev","android","mobile","app","apps","client","release","debug","main","browser","ui","view","experience","portal","phone","tablet","service"]),s=e.split("."),i=s.filter(r=>!t.has(r.toLowerCase())&&!/^\d+$/.test(r));return((i.length>0?i[i.length-1]:s[s.length-1])||"app").toLowerCase().replace(/[^a-z0-9_]/g,"")}async startSession(e,t,s){let i=await this.driver.ensureDefaultDevice(t);if(!i)throw new Error("No Android device connected for recording.");this.deviceLock=Et(i),this.targetSerial=i,this.isRecording=!0,this.recordedSteps=[],this.existingSteps=[],this.existingFileHeader=[],this.visitedScreens=[],this.targetPackage=null,this.activeInput=null,this.isAppendMode=!!s?.append;try{let u=await this.driver.getForegroundPackage(i);u&&(this.targetPackage=u)}catch{}let n=this.extractBrandSlug(this.targetPackage),r;if(e&&e!=="specs/recorded_suite.txt")r=Se.resolve(e);else{let u=`${n}_flow`,h=Se.resolve(`specs/${u}.txt`);if(!this.isAppendMode&&ke.existsSync(h)){let g=1;for(h=Se.resolve(`specs/${u}_${g}.txt`);ke.existsSync(h);)g++,h=Se.resolve(`specs/${u}_${g}.txt`)}r=h}if(this.resolvedOutputPath=r,ke.existsSync(r))if(this.isAppendMode){let u=ke.readFileSync(r,"utf-8"),h=u.split(`
|
|
862
|
+
`);for(let b of h){let T=b.trim();if(/^\d+\.\s+/.test(T))this.existingSteps.push(T.replace(/^\d+\.\s+/,""));else if(T.startsWith("# Package:")){let x=T.match(/# Package:\s*([a-zA-Z0-9._]+)/);x&&(this.targetPackage=x[1])}}let g=`${r}.bak`;ke.writeFileSync(g,u,"utf-8"),console.log(Y.cyan(`\u{1F4E5} Loaded ${this.existingSteps.length} existing step(s) from: ${Se.basename(r)}`)),console.log(Y.gray(`\u{1F4E6} Safety backup preserved at: ${Se.basename(g)}`))}else{let u=ke.readFileSync(r,"utf-8"),h=`${r}.bak`;ke.writeFileSync(h,u,"utf-8"),console.log(Y.yellow(`\u26A0\uFE0F File "${Se.basename(r)}" already exists.`)),console.log(Y.gray(`\u{1F4E6} Safety backup preserved at: ${Se.basename(h)}`))}await this.driver.wakeDevice(i).catch(()=>{});let c=await this.driver.getScreenDimensions(i);this.displayWidth=c.width||I.screen.fallbackWidth,this.displayHeight=c.height||I.screen.fallbackHeight,this.touchMaxX=this.displayWidth,this.touchMaxY=this.displayHeight;try{let{stdout:u}=await this.driver.execAdb(["shell","getevent","-p"],i),h=u.match(/0035\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/),g=u.match(/0036\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/);h&&parseInt(h[1])>0&&(this.touchMaxX=parseInt(h[1])),g&&parseInt(g[1])>0&&(this.touchMaxY=parseInt(g[1]))}catch{}this.sessionStartTime=Date.now(),this.sessionScreenSections=[],this.screenshotCounter=0,this.crashDetected=!1,this.hierarchyStale=!0,this.currentScreenName="";let l=Se.basename(r,".txt"),p=Se.resolve("output");this.screenshotDir=Se.join(p,"screenshots",l),ke.existsSync(this.screenshotDir)||ke.mkdirSync(this.screenshotDir,{recursive:!0});let d=Se.join(p,`${l}_report.md`);this.resolvedReportPath=d,await this.refreshHierarchySync(),this.startLogcatScreenWatcher(i),this.startLogcatCrashWatcher(i),this.startEventStream(i),this.flushToDisk()}async stopSession(){if(this.isRecording=!1,this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),this.deviceLock&&(kt(this.deviceLock),this.deviceLock=null),this.geteventProcess){try{this.geteventProcess.kill()}catch{}this.geteventProcess=null}if(this.logcatEventProcess){try{this.logcatEventProcess.kill()}catch{}this.logcatEventProcess=null}if(this.logcatCrashProcess){try{this.logcatCrashProcess.kill()}catch{}this.logcatCrashProcess=null}return this.flushToDisk(),{steps:[...this.recordedSteps],specPath:this.resolvedOutputPath,reportPath:this.resolvedReportPath}}async startRecording(e,t,s){await this.startSession(e,t,s);let i=Y.gray("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),n=await this.driver.getDeviceModel(this.targetSerial).catch(()=>this.targetSerial);console.log(`
|
|
863
|
+
${i}`),console.log(Y.bold.cyan(`\u26A1 PromptTest v${pi}`)+Y.gray(" | Recording Session")),console.log(i),console.log(` ${Y.gray("\u{1F4F1} Device ")} ${Y.white(n)} ${Y.gray(`(${this.targetSerial})`)}`),console.log(` ${Y.gray("\u{1F4E6} App ")} ${Y.green(this.targetPackage||"Unknown")}`),console.log(` ${Y.gray("\u{1F3AF} Spec ")} ${Y.yellow(Se.basename(this.resolvedOutputPath))}`),console.log(` ${Y.gray("\u{1F4CA} Report ")} ${Y.yellow(Se.basename(this.resolvedReportPath))}`),console.log(` ${Y.gray("\u{1F4F8} Photos ")} ${Y.yellow(Se.relative(process.cwd(),this.screenshotDir))}`),this.isAppendMode&&this.existingSteps.length>0&&console.log(` ${Y.gray("\u{1F4CE} Mode ")} ${Y.magenta(`Append \u2014 resuming from step #${this.existingSteps.length+1}`)}`),console.log(i),console.log(` ${Y.green("\u2714")} Ready & streaming`),console.log(i),console.log(` ${Y.gray("Use the app naturally. Every action is captured.")}`),console.log(` ${Y.gray('Press Ctrl+C or type "exit" / "q" + Enter to stop and save.')}`),console.log(`${i}
|
|
864
|
+
`);let r=null,o=async()=>{if(r)try{r.close()}catch{}await this.stopSession(),this.printExitSummary(i),process.exit(0)};if(process.once("SIGINT",o),process.once("SIGTERM",o),process.stdin.isTTY)try{r=ar.createInterface({input:process.stdin,output:process.stdout}),r.on("line",l=>{let p=l.trim().toLowerCase();(p==="exit"||p==="quit"||p==="q"||p==="stop")&&o()}),r.on("SIGINT",()=>{o()})}catch{}let c=0;for(;this.isRecording;)if(await new Promise(l=>setTimeout(l,1500)),c++,c%20===0&&this.driver.wakeDevice(this.targetSerial).catch(()=>{}),!this.targetPackage){let l=await this.driver.getForegroundPackage(this.targetSerial).catch(()=>null);l&&(this.targetPackage=l)}}startEventStream(e){let t=e?["-s",e,"shell","getevent","-l"]:["shell","getevent","-l"],s=Ze(),i=Pn(s,t);this.geteventProcess=i;let n=null,r=null,o=null,c=null,l=0;ar.createInterface({input:i.stdout}).on("line",d=>{if(this.isRecording)if(d.includes("ABS_MT_POSITION_X")){let u=d.match(/ABS_MT_POSITION_X\s+([0-9a-fA-F]+)/);u&&(n=parseInt(u[1],16))}else if(d.includes("ABS_MT_POSITION_Y")){let u=d.match(/ABS_MT_POSITION_Y\s+([0-9a-fA-F]+)/);u&&(r=parseInt(u[1],16))}else if(d.includes("BTN_TOUCH")&&d.includes("DOWN"))o=n,c=r,l=Date.now();else if(d.includes("BTN_TOUCH")&&d.includes("UP")){let u=n!==null?n:o,h=r!==null?r:c,g=Date.now()-l;if(u!==null&&h!==null&&o!==null&&c!==null){let b=Math.round(o/this.touchMaxX*this.displayWidth),T=Math.round(c/this.touchMaxY*this.displayHeight),x=Math.round(u/this.touchMaxX*this.displayWidth),S=Math.round(h/this.touchMaxY*this.displayHeight),y=x-b,P=S-T,$=Math.abs(y),R=Math.abs(P),C=Math.hypot($,R);if(this.activeInput&&T>this.displayHeight*.58&&S>this.displayHeight*.58){g>=20&&g<400&&C<45&&x>=this.displayWidth*.78&&S>=this.displayHeight*.84?this.flushActiveInput().then(()=>{this.handleKeyPress("Enter")}).catch(()=>{}):this.scheduleInputDebounce(),n=null,r=null,o=null,c=null;return}if(g>=20&&g<400&&C<45)this.isRefreshingHierarchy?this.inFlightTapQueue.push({x,y:S,timestamp:Date.now()}):this.handleTapAt(x,S);else if(g>=450&&C<45)this.handleLongPressAt(x,S);else if(R>=100&&R>1.4*$){let B=P<0?"down":"up";this.handleScroll(B)}else if($>=100&&$>1.4*R){let B=y<0?"left":"right";this.handleSwipe(B)}}n=null,r=null,o=null,c=null}else d.includes("KEY_ENTER")&&d.includes("DOWN")?this.handleKeyPress("Enter"):d.includes("KEY_BACK")&&d.includes("DOWN")&&this.handleKeyPress("Back")}),i.on("close",d=>{this.isRecording&&(console.warn(Y.yellow(`
|
|
865
|
+
\u26A0\uFE0F [EventStream] ADB event listener stream closed (code ${d}). Auto-reconnecting in 800ms...`)),setTimeout(()=>{this.isRecording&&this.startEventStream(e)},800))}),i.on("error",d=>{this.isRecording&&console.warn(Y.yellow(`
|
|
866
|
+
\u26A0\uFE0F [EventStream] ADB stream error: ${d.message}.`))})}cleanLabel(e){return e?e.replace(/[\uE000-\uF8FF\uFFF0-\uFFFF\uFFFD]/gu,"").replace(/,\s*tab,\s*\d+\s*of\s*\d+/gi,"").replace(/,\s*button$/gi,"").replace(/^[\s,•\-_:;|/\\]+|[\s,•\-_:;|/\\]+$/g,"").trim():""}handleScroll(e){let t=Date.now();if(this.lastScrollDirection===e&&t-this.lastScrollTimestamp<850)return;this.lastScrollTimestamp=t,this.lastScrollDirection=e,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Scroll ${e}`;this.recordedSteps[this.recordedSteps.length-1]!==s&&(this.appendStep(s,Y.blue(` \u{1F4DC} Recorded Scroll [Step #${this.getCurrentStepNumber()}]: ${Y.bold(s)}`)),this.triggerAsyncHierarchyRefresh(400))}handleSwipe(e){let t=Date.now();if(t-this.lastScrollTimestamp<600)return;this.lastScrollTimestamp=t,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Swipe ${e}`;this.appendStep(s,Y.blue(` \u{1F449} Recorded Swipe [Step #${this.getCurrentStepNumber()}]: ${Y.bold(s)}`)),this.triggerAsyncHierarchyRefresh(500)}handleLongPressAt(e,t){let s=this.lastHierarchyFlat.filter(r=>e>=r.bounds.x1&&e<=r.bounds.x2&&t>=r.bounds.y1&&t<=r.bounds.y2);if(s.length===0)return;s.sort((r,o)=>{let c=(r.bounds.x2-r.bounds.x1)*(r.bounds.y2-r.bounds.y1),l=(o.bounds.x2-o.bounds.x1)*(o.bounds.y2-o.bounds.y1);return c-l});let i=s[0],n=this.resolveActionLabel(i,s,this.lastHierarchyFlat);if(n){let r=`Long press '${n}'`;this.appendStep(r,Y.cyan(` \u23F1\uFE0F Recorded Long Press [Step #${this.getCurrentStepNumber()}]: ${Y.bold(r)}`)),this.triggerAsyncHierarchyRefresh()}}handleTapAt(e,t){let s=Date.now(),i=this.lastHierarchyFlat.filter(d=>e>=d.bounds.x1&&e<=d.bounds.x2&&t>=d.bounds.y1&&t<=d.bounds.y2),r=this.lastHierarchyFlat.filter(d=>{let u=d.bounds.height;return u>0&&u<320&&d.bounds.width>0&&(d.clickable||d.contentDesc||d.text)}).filter(d=>t>=d.bounds.y1-30&&t<=d.bounds.y2+40);if(r.length>=2){let d=r.find(u=>e>=u.bounds.x1-20&&e<=u.bounds.x2+20);d&&(i=[this.lastHierarchyFlat.find(h=>(this.cleanLabel(h.text).length>0||this.cleanLabel(h.contentDesc).length>0)&&Math.abs(h.bounds.centerX-d.bounds.centerX)<d.bounds.width*.48&&Math.abs(h.bounds.centerY-d.bounds.centerY)<d.bounds.height*.48&&!this.isIconGlyph(this.cleanLabel(h.text)))||d])}if(t>this.displayHeight*.82){let u=this.lastHierarchyFlat.filter(h=>{let g=h.bounds.y1>=this.displayHeight*.78||h.bounds.y2>=this.displayHeight*.82,b=h.bounds.width>0&&h.bounds.width<=this.displayWidth*.52;return g&&b}).find(h=>e>=h.bounds.x1-20&&e<=h.bounds.x2+20);if(u){let h=this.lastHierarchyFlat.find(g=>(this.cleanLabel(g.text).length>0||this.cleanLabel(g.contentDesc).length>0)&&e>=g.bounds.x1-25&&e<=g.bounds.x2+25&&g.bounds.y1>=this.displayHeight*.78&&!this.isIconGlyph(this.cleanLabel(g.text)));h?i=[h]:(this.cleanLabel(u.text)||this.cleanLabel(u.contentDesc))&&(i=[u])}}if(i.length===0){let d=this.lastHierarchyFlat.filter(g=>(this.cleanLabel(g.text).length>0||this.cleanLabel(g.contentDesc).length>0)&&(g.clickable||g.className.includes("Button")||g.className.includes("Text"))),u=null,h=70;for(let g of d){let b=Math.hypot(g.bounds.centerX-e,g.bounds.centerY-t);b<h&&(h=b,u=g)}if(u)i=[u];else{this.triggerAsyncHierarchyRefresh();return}}i.sort((d,u)=>{let h=(d.bounds.x2-d.bounds.x1)*(d.bounds.y2-d.bounds.y1),g=(u.bounds.x2-u.bounds.x1)*(u.bounds.y2-u.bounds.y1);return h-g});let o=i[0],c=i.find(d=>d.className.includes("EditText"))||(o.className.includes("EditText")?o:null);if(c){this.activeInput&&this.activeInput.node!==c&&this.flushActiveInput().catch(()=>{});let d=this.resolveFieldLabel(c,this.lastHierarchyFlat);this.activeInput={node:c,label:d,startText:c.text||""},this.triggerAsyncHierarchyRefresh();return}this.activeInput&&this.flushActiveInput().catch(()=>{});let l=this.resolveActionLabel(o,i,this.lastHierarchyFlat);if(!l||l.length===0){this.triggerAsyncHierarchyRefresh();return}if(!o.clickable&&!i.some(d=>d.clickable||d.className.includes("Button"))&&/^\d+%$|^\d+$/.test(l)){this.triggerAsyncHierarchyRefresh();return}if(l===this.lastRecordedTapTarget&&s-this.lastTapTimestamp<350)return;this.lastTapTimestamp=s,this.lastRecordedTapTarget=l;let p;if(o.checkable||o.className.includes("Switch")||o.className.includes("CheckBox")){let d=o.checked!==void 0?!o.checked:!0;p=`Toggle '${l}' to ${d?"on":"off"}`}else{p=`Tap '${l}'`;let d=this.lastHierarchyFlat.filter(h=>this.cleanLabel(h.text)===l||this.cleanLabel(h.contentDesc)===l),u=[];for(let h of d)u.some(b=>Math.hypot(b.bounds.centerX-h.bounds.centerX,b.bounds.centerY-h.bounds.centerY)<40)||u.push(h);if(u.length>1){let g=this.lastHierarchyFlat.filter(b=>b!==o&&Math.abs(b.bounds.centerY-o.bounds.centerY)<140&&Math.abs(b.bounds.centerX-o.bounds.centerX)<550).find(b=>{let T=this.cleanLabel(b.text)||this.cleanLabel(b.contentDesc);return T.length>2&&T!==l&&!/^\d+$/.test(T)&&!this.isIconGlyph(T)});if(g){let b=this.cleanLabel(g.text)||this.cleanLabel(g.contentDesc);b&&b!==l&&(p=`Tap '${l}' next to '${b}'`)}}}this.appendStep(p,Y.cyan(` \u{1F446} Recorded Tap [Step #${this.getCurrentStepNumber()}]: ${Y.bold(p)}`)),this.triggerAsyncHierarchyRefresh()}handleKeyPress(e){if(this.activeInput&&this.flushActiveInput().catch(()=>{}),e==="Enter"){let t="Press 'Enter'";this.appendStep(t,Y.magenta(` \u21B5 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${Y.bold(t)}`))}else if(e==="Back"){let t="Tap 'Back'";this.appendStep(t,Y.magenta(` \u25C0 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${Y.bold(t)}`))}this.triggerAsyncHierarchyRefresh()}scheduleInputDebounce(){this.inputDebounceTimer&&clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=setTimeout(()=>{this.activeInput&&this.syncActiveInputText().catch(()=>{})},450)}async flushActiveInput(){if(this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),!this.activeInput)return;let e=this.activeInput;this.activeInput=null,await this.recordInputText(e)}async syncActiveInputText(){this.activeInput&&await this.recordInputText(this.activeInput)}async recordInputText(e){try{let t=await this.driver.getUiHierarchy(this.targetSerial).catch(()=>null);if(!t)return;let{flat:s}=me(t);this.lastHierarchyFlat=s;let i=s.find(n=>n.className.includes("EditText")&&(n.focused||n.selected))||s.find(n=>n.className.includes("EditText")&&this.resolveFieldLabel(n,s).toLowerCase()===e.label.toLowerCase())||s.find(n=>n.className.includes("EditText")&&Math.abs(n.bounds.centerX-e.node.bounds.centerX)<80)||s.find(n=>n.className.includes("EditText"));if(i&&i.text&&i.text.trim().length>0){let n=i.text.trim(),r=/^[•*•\u2022\u25cf]+$/.test(n);if(!(n===e.startText)&&!r){if(e.startText===""&&this.isPlaceholderText(n))return;let c=e.label||this.resolveFieldLabel(i,s),l=`Type '${n}' into '${c}'`,p=this.recordedSteps.length-1,d=p>=0?this.recordedSteps[p]:"";d.startsWith("Type ")&&d.endsWith(`into '${c}'`)?d!==l&&(this.recordedSteps[p]=l,this.flushToDisk(),console.log(Y.gray(` \u270D\uFE0F Updated Input [Step #${p+1+this.existingSteps.length}]: ${Y.bold(l)}`))):this.appendStep(l,Y.green(` \u270D\uFE0F Recorded Input [Step #${this.getCurrentStepNumber()}]: ${Y.bold(l)}`))}else if(r&&(i.password||e.label.toLowerCase().includes("password"))){let c=e.label||"Password",l=`Type '<password>' into '${c}'`,p=this.recordedSteps.length-1,d=p>=0?this.recordedSteps[p]:"";(!d.startsWith("Type ")||!d.endsWith(`into '${c}'`))&&this.appendStep(l,Y.green(` \u270D\uFE0F Recorded Password Input [Step #${this.getCurrentStepNumber()}]: ${Y.bold(l)}`))}}}catch{}}startLogcatScreenWatcher(e){try{this.logcatEventProcess=this.driver.streamLogcatEvents(e,t=>{if(this.isRecording&&(t.includes("wm_on_resume_called")||t.includes("am_on_resume_called"))){let s=Date.now();if(s-this.lastScreenTransitionTime<500)return;this.lastScreenTransitionTime=s,this.hierarchyStale=!0,this.triggerAsyncHierarchyRefresh(50)}})}catch{}}startLogcatCrashWatcher(e){try{this.logcatCrashProcess=this.driver.streamLogcatCrashes(e,t=>{if(this.isRecording&&(t.includes("FATAL EXCEPTION")||t.includes("ANR in"))){if(this.targetPackage&&!t.includes(this.targetPackage))return;this.crashDetected=!0,console.log(Y.red.bold(`
|
|
867
|
+
\u26A0\uFE0F [Crash Alert] Fatal exception / ANR detected in ${this.targetPackage||"app"}!`))}})}catch{}}captureSessionScreenshot(e){if(!this.screenshotDir)return;let t=++this.screenshotCounter,s=e.toLowerCase().replace(/[^a-z0-9_]/g,"_").slice(0,30)||"screen",i=`screen_${String(t).padStart(2,"0")}_${s}.png`,n=Se.join(this.screenshotDir,i);(async()=>{try{let r=await this.driver.captureScreenshot(this.targetSerial);if(r&&r.length>0){await ke.promises.writeFile(n,r);let o=this.sessionScreenSections[this.sessionScreenSections.length-1];o&&!o.screenshotFile&&(o.screenshotFile=i)}}catch{}})()}triggerAsyncHierarchyRefresh(e=I.recorder.asyncRefreshDelayMs){this.isRefreshingHierarchy||(this.isRefreshingHierarchy=!0,setTimeout(()=>{this.doHierarchyRefresh().catch(()=>{this.isRefreshingHierarchy=!1})},e))}async doHierarchyRefresh(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=me(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t),this.detectAndLogTransientAlerts(t)}catch{}finally{for(this.isRefreshingHierarchy=!1;this.inFlightTapQueue.length>0;){let e=this.inFlightTapQueue.shift();if(!e)break;Date.now()-e.timestamp<I.recorder.staleTapTimeoutMs?this.handleTapAt(e.x,e.y):console.warn(Y.yellow(`[Recorder] Dropped stale tap at (${e.x}, ${e.y}) \u2014 screen refresh took longer than ${I.recorder.staleTapTimeoutMs}ms`))}}}detectAndLogTransientAlerts(e){let t=e.find(s=>(s.className.includes("Toast")||s.className.includes("Snackbar")||s.resourceId&&s.resourceId.includes("snackbar")||s.contentDesc&&(s.contentDesc.includes("Alert")||s.contentDesc.includes("Success")))&&(s.text||s.contentDesc));if(t){let s=this.cleanLabel(t.text)||this.cleanLabel(t.contentDesc);if(s&&s.length>3&&s.length<80){let i=`Verify '${s}' is visible`;this.recordedSteps.slice(-3).includes(i)||this.appendStep(i,Y.green(` \u2714 Recorded Alert [Step #${this.getCurrentStepNumber()}]: ${Y.bold(i)}`))}}}async refreshHierarchySync(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=me(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t)}catch{}}isIconGlyph(e){if(!e||e.trim().length===0)return!0;let t=e.trim();return!!(/[\uE000-\uF8FF\uFFF0-\uFFFF]/.test(t)||t.length===1&&t.charCodeAt(0)>255&&!new RegExp("\\p{Extended_Pictographic}","u").test(t))}cleanDialogOrCompoundLabel(e){if(!e)return"";let t=e.trim();if(t.includes(",")||t.includes(`
|
|
868
|
+
`)){let s=t.split(/[\n,]+/).map(i=>this.cleanLabel(i)).filter(Boolean);if(s.length>1){let i=s.find(r=>r.includes("?")||/\b(are you sure|do you want|cannot be undone|would you like|please confirm)\b/i.test(r)||r.length>35);if(i){let r=s.find(o=>o!==i&&o.length<=30&&!o.includes("?"));if(r)return r}let n=s.filter(r=>/^[A-Z]{1,3}$/.test(r)||/^\d+%?$/.test(r)||this.isCardMetadataSubtitle(r)||/^(attend|present|absent|status|active|inactive)$/i.test(r)?!1:r.length>1);if(n.length>0)return n[0]}}return t}isCardMetadataSubtitle(e){if(!e||e.trim().length===0)return!1;let t=e.trim();return!!(/\+?\d{1,3}[\s-]?\d{4,}[\s-]?\d{4,}/.test(t)||/^(STD|ID|EMP|REF|ORD|USER|ACC|BATCH)[\-_:\s]?\d+/i.test(t)||/[•|·]/.test(t)&&/\d/.test(t)||/^\d+$/.test(t)||/^\d{1,2}:\d{2}/.test(t)||/^(teacher|roll\s*no|std\s*id|class|sec)[\s:]+/i.test(t))}findPrimaryCardTitle(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82||e.clickable&&(e.className.includes("Button")||e.className.includes("Check")))return null;let i=this.cleanLabel(e.text),n=this.isCardMetadataSubtitle(i),r=s.find(l=>l!==e&&l.clickable&&l.bounds.height>60&&l.bounds.height<600),o;r?o=t.filter(l=>l.className.includes("Text")&&l.bounds.x1>=r.bounds.x1-10&&l.bounds.x2<=r.bounds.x2+10&&l.bounds.y1>=r.bounds.y1-10&&l.bounds.y2<=r.bounds.y2+10):o=t.filter(l=>l!==e&&l.className.includes("Text")&&l.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-l.bounds.centerY<160&&Math.abs(l.bounds.centerX-e.bounds.centerX)<500);let c=o.filter(l=>{let p=this.cleanLabel(l.text);return p.length>2&&!this.isCardMetadataSubtitle(p)&&!this.isIconGlyph(p)&&!/^\d+$/.test(p)&&!/^(active|inactive|present|absent|new|pending)$/i.test(p)}).sort((l,p)=>l.bounds.y1-p.bounds.y1);if(c.length>0){let l=this.cleanLabel(c[0].text);if(n||r&&l!==i&&!e.clickable)return l}return null}resolveActionLabel(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82){let l=this.cleanLabel(e.contentDesc)||this.cleanLabel(e.text);if(l&&l.length>0&&!this.isIconGlyph(l))return this.cleanDialogOrCompoundLabel(l);for(let p of t){let d=this.cleanLabel(p.contentDesc)||this.cleanLabel(p.text);if(d&&d.length>0&&!this.isIconGlyph(d))return this.cleanDialogOrCompoundLabel(d)}}let i=this.findPrimaryCardTitle(e,s,t);if(i)return this.cleanDialogOrCompoundLabel(i);let n=this.cleanLabel(e.text);if(n.length>0&&n.length<90){let l=n.split(/[\n\r]+/).map(d=>this.cleanLabel(d)).filter(Boolean),p=l.length>1?l.find(d=>d.length>2&&!/^\d+$/.test(d))||l[0]:n;return this.cleanDialogOrCompoundLabel(p)}let r=this.cleanLabel(e.contentDesc);if(r.length>0&&r.length<90)return this.cleanDialogOrCompoundLabel(r);let o=t.find(l=>(l.clickable||l.className.includes("Button"))&&(this.cleanLabel(l.text)||this.cleanLabel(l.contentDesc)));if(o){let l=this.cleanLabel(o.text)||this.cleanLabel(o.contentDesc);if(l.length>0&&l.length<90)return this.cleanDialogOrCompoundLabel(l)}for(let l of t){let p=this.cleanLabel(l.text);if(p.length>0&&p.length<90){let u=p.split(/[\n\r]+/).map(g=>this.cleanLabel(g)).filter(Boolean),h=u.length>1?u.find(g=>g.length>2&&!/^\d+$/.test(g))||u[0]:p;return this.cleanDialogOrCompoundLabel(h)}let d=this.cleanLabel(l.contentDesc);if(d.length>0&&d.length<90)return this.cleanDialogOrCompoundLabel(d)}let c=s.find(l=>l!==e&&(this.cleanLabel(l.text).length>0||this.cleanLabel(l.contentDesc).length>0)&&Math.abs(l.bounds.centerX-e.bounds.centerX)<80&&Math.abs(l.bounds.centerY-e.bounds.centerY)<100);if(c){let l=this.cleanLabel(c.text)||this.cleanLabel(c.contentDesc);if(l.length>0)return this.cleanDialogOrCompoundLabel(l)}if(e.resourceId){let l=e.resourceId.split("/"),p=l[l.length-1];if(p&&!/^\d+$/.test(p)){let d=p.replace(/_/g," ").replace(/btn|button|icon|view|action/gi,"").trim();if(d.length>1)return d.charAt(0).toUpperCase()+d.slice(1)}}return""}getCurrentStepNumber(){return this.existingSteps.length+this.recordedSteps.length+1}detectAndLogScreenHeader(e){let t=e.filter(s=>{if(!s.className.includes("TextView")||s.text.trim().length<2||s.packageName&&(s.packageName.includes("systemui")||s.packageName.includes("launcher"))||s.bounds.y1<60||s.bounds.y1>=450)return!1;let i=s.text.trim();return!(this.isCardMetadataSubtitle(i)||/\b(JIO|Airtel|Vodafone|No service|Emergency|VoLTE|4G|5G)\b/i.test(i)||/^\d+%?$|^\d+$/.test(i)||/^step\s*\d+\s*(of|\/)\s*\d+/i.test(i))}).sort((s,i)=>s.bounds.y1-i.bounds.y1);if(t.length>0){let s=t[0].text.trim();if(s&&s!==this.lastScreenTitle&&!s.includes(":")&&s.length<40){this.lastScreenTitle=s,this.currentScreenName=s,this.visitedScreens.includes(s)||this.visitedScreens.push(s),this.sessionScreenSections.push({name:s,stepStart:this.recordedSteps.length}),this.captureSessionScreenshot(s);let i=`Verify '${s}' is visible`;this.recordedSteps[this.recordedSteps.length-1]!==i&&!this.recordedSteps.slice(-3).includes(i)&&this.appendStep(i,Y.green(` \u2714 Recorded Header [Step #${this.getCurrentStepNumber()}]: ${Y.bold(i)}`))}}}resolveFieldLabel(e,t){if(e.contentDesc&&e.contentDesc.trim().length>0)return e.contentDesc.trim();if(e.password)return"Password";let s=t.filter(i=>i.className.includes("TextView")&&i.text&&i.text.trim().length>1&&i.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-i.bounds.centerY<250&&Math.abs(i.bounds.centerX-e.bounds.centerX)<450);if(s.length>0){s.sort((n,r)=>r.bounds.centerY-n.bounds.centerY);let i=s[0].text.trim().replace(/[*:]/g,"").trim();if(i.length>0)return i}if(e.resourceId){let i=e.resourceId.split("/"),n=i[i.length-1];if(n&&!/^\d+$/.test(n)){let r=n.replace(/_/g," ").replace(/edit|text|input|field|et|txt/gi,"").trim();return r.length>1?r.charAt(0).toUpperCase()+r.slice(1):n}}if(e.text&&e.text.trim().length>0&&e.text.trim().length<40){let i=e.text.trim();if(i.toLowerCase().startsWith("search"))return i.length<=25?i:"Search";if(!this.isPlaceholderText(i))return i}return"Input Field"}isPlaceholderText(e){let t=e.trim().toLowerCase();return t.startsWith("search")||t.startsWith("e.g.")||t.startsWith("enter ")||t.startsWith("type ")||t.includes("optional")}saveSpec(e){let t=Se.resolve(e);if(Se.basename(t).startsWith("app_flow")&&this.targetPackage&&!this.isAppendMode){let c=this.extractBrandSlug(this.targetPackage);if(c!=="app"){let l=`${c}_flow`,p=Se.resolve(`specs/${l}.txt`),d=1;for(;ke.existsSync(p);)p=Se.resolve(`specs/${l}_${d}.txt`),d++;t=p}}let i=Se.dirname(t);ke.existsSync(i)||ke.mkdirSync(i,{recursive:!0});let n=[];if(this.isAppendMode&&this.existingSteps.length>0&&ke.existsSync(t)){let c=ke.readFileSync(t,"utf-8").trim();n.push(c),n.push(""),n.push(`# --- Appended Session (${new Date().toISOString().replace("T"," ").slice(0,19)}) ---`),this.recordedSteps.forEach((l,p)=>{n.push(`${this.existingSteps.length+p+1}. ${l}`)})}else{n.push("# ==========================================================",`# Autonomous Recorded Test Spec: ${Se.basename(t)}`,...this.targetPackage?[`# Package: ${this.targetPackage}`]:[],`# Generated: ${new Date().toISOString()}`,`# PromptTest v${pi}`,"# ==========================================================","");let c=0;this.recordedSteps.forEach((l,p)=>{if(c<this.sessionScreenSections.length&&p===this.sessionScreenSections[c].stepStart){let d=this.sessionScreenSections[c];n.push(""),n.push(`# Screen: ${d.name}`),c++}n.push(`${this.existingSteps.length+p+1}. ${l}`)})}n.push("");let r=n.join(`
|
|
869
|
+
`),o=`${t}.tmp.${Date.now()}`;try{ke.writeFileSync(o,r,"utf-8"),ke.renameSync(o,t)}catch{try{ke.unlinkSync(o)}catch{}ke.writeFileSync(t,r,"utf-8")}}saveReport(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,n=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,r=this.existingSteps.length+this.recordedSteps.length,o=["# PromptTest Recording Report","","| Property | Value |","|---|---|",`| **Target Package** | \`${this.targetPackage||"Unknown"}\` |`,`| **Device Serial** | \`${this.targetSerial}\` |`,`| **Session Started** | ${new Date(this.sessionStartTime).toISOString()} |`,`| **Session Duration** | ${n} |`,`| **Steps in Session** | ${this.recordedSteps.length} |`,`| **Total Suite Steps** | ${r} |`,`| **Screens Visited** | ${this.visitedScreens.length} |`,`| **Screenshots Saved** | ${this.screenshotCounter} |`,`| **Crash Signals** | ${this.crashDetected?"\u26A0\uFE0F Detected":"\u2705 None"} |`,"","---","","## Screen Journey","",this.visitedScreens.length>0?this.visitedScreens.map((c,l)=>`${l+1}. **${c}**`).join(`
|
|
870
|
+
`):"*Single screen flow*","","---","","## Recorded Interactions",""];if(this.sessionScreenSections.length>0)for(let c=0;c<this.sessionScreenSections.length;c++){let l=this.sessionScreenSections[c],p=this.sessionScreenSections[c+1],d=p?p.stepStart:this.recordedSteps.length,u=this.recordedSteps.slice(l.stepStart,d);o.push(`### Screen: ${l.name}`),o.push(""),l.screenshotFile&&(o.push(`}/${l.screenshotFile})`),o.push("")),u.length>0?u.forEach((h,g)=>{o.push(`${l.stepStart+g+1}. \`${h}\``)}):o.push("*(No interactions on this screen)*"),o.push("")}else o.push("### Steps"),o.push(""),this.recordedSteps.forEach((c,l)=>{o.push(`${l+1}. \`${c}\``)}),o.push("");try{let c=Se.dirname(e);ke.existsSync(c)||ke.mkdirSync(c,{recursive:!0}),ke.writeFileSync(e,o.join(`
|
|
871
|
+
`),"utf-8")}catch{}}printExitSummary(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,n=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,r=this.existingSteps.length+this.recordedSteps.length;console.log(`
|
|
872
|
+
${e}`),console.log(Y.bold.green(" \u{1F4BE} Recording Session Saved Successfully!")),console.log(e),console.log(` ${Y.gray("Steps Captured ")} ${Y.bold.yellow(this.recordedSteps.length.toString())} ${this.isAppendMode?Y.gray(`(Total Suite: ${r})`):""}`),console.log(` ${Y.gray("Screens Visited")} ${Y.bold.white(this.visitedScreens.length.toString())} ${this.visitedScreens.length>0?Y.gray(`(${this.visitedScreens.join(" \u2192 ")})`):""}`),console.log(` ${Y.gray("Screenshots ")} ${Y.bold.white(this.screenshotCounter.toString())} saved`),console.log(` ${Y.gray("Session Time ")} ${Y.bold.white(n)}`),console.log(` ${Y.gray("Crash Signals ")} ${this.crashDetected?Y.red.bold("\u26A0\uFE0F Detected"):Y.green("\u2714 0 detected")}`),console.log(e),console.log(` ${Y.gray("\u{1F4C4} Spec ")} ${Y.cyan(this.resolvedOutputPath)}`);let o=Se.basename(this.resolvedOutputPath,".txt");console.log(` ${Y.gray("\u{1F4CA} Report ")} ${Y.cyan(Se.resolve("output",`${o}_report.md`))}`),console.log(`${e}
|
|
873
|
+
`)}},cr=new ft;Ne();import cs from"fs";import lr from"path";import Re from"chalk";async function ls(a=Pe,e={}){let t=[],s=process.versions.node,n=parseInt(s.split(".")[0],10)>=18;t.push({name:"Node.js Runtime",passed:n,message:`Node.js v${s} (Required >= 18.0.0)`,hint:n?void 0:"Please upgrade Node.js to v18.0.0 or higher: https://nodejs.org"});let r=!1,o="ADB binary not found in PATH",c='Install Android SDK platform-tools and ensure "adb" is in your system PATH.';try{let{stdout:S}=await a.execAdb(["version"],void 0,5e3),y=S.match(/Android Debug Bridge version ([\d.]+)/i);y?(r=!0,o=`Android Debug Bridge version ${y[1]}`,c=void 0):(r=!0,o=S.split(`
|
|
874
|
+
`)[0].trim(),c=void 0)}catch(S){o=`Failed to execute adb: ${S.message}`}t.push({name:"Android Debug Bridge (ADB)",passed:r,message:o,hint:c});let l=!1,p="No connected Android devices or emulators found",d="Connect an Android device via USB/Wi-Fi or launch an emulator with USB Debugging enabled.";try{let S=await a.getConnectedDevices(),y=S.filter(R=>R.state==="device"),P=S.filter(R=>R.state==="unauthorized"),$=S.filter(R=>R.state==="offline");if(y.length>0){l=!0;let R=y.map(C=>`${C.serial} (${C.model||"Unknown"})`).join(", ");p=`Found ${y.length} authorized device(s): ${R}`,d=void 0}else P.length>0?(p=`Device(s) found but unauthorized: ${P.map(R=>R.serial).join(", ")}`,d='Check the device screen and accept the "Allow USB debugging" RSA prompt.'):$.length>0&&(p=`Device(s) found in offline state: ${$.map(R=>R.serial).join(", ")}`,d='Try running "adb reconnect" or reconnect the USB cable.')}catch(S){p=`Failed to list devices: ${S.message}`}if(t.push({name:"Connected Android Device",passed:l,message:p,hint:d}),e.packageName){let S=e.packageName,y=!1,P=`Package "${S}" not found on target device`,$='Install the APK using "adb install <path.apk>" or check the package identifier.';if(l)try{let{stdout:R}=await a.execAdb(["shell","pm","list","packages",S],e.serial,5e3);R.includes(`package:${S}`)&&(y=!0,P=`Package "${S}" is installed on target device`,$=void 0)}catch(R){P=`Failed to query package status: ${R.message}`}else P="Skipped package verification (no authorized device available)",$=`Connect a device to verify package "${S}".`;t.push({name:`Target Package [${S}]`,passed:y,message:P,hint:$})}let u=!0,h="All required workspace directories are accessible",g,b=["output","memory",".prompttest"];for(let S of b)try{let y=lr.resolve(process.cwd(),S);cs.existsSync(y)||cs.mkdirSync(y,{recursive:!0});let P=lr.join(y,".doctor_perm_test");cs.writeFileSync(P,"ok","utf-8"),cs.unlinkSync(P)}catch(y){u=!1,h=`Filesystem permission error for "./${S}": ${y.message}`,g="Ensure the current user has write permissions to the workspace directory.";break}t.push({name:"Workspace Storage & Permissions",passed:u,message:h,hint:g});let T=t.filter(S=>S.passed).length,x=t.filter(S=>!S.passed).length;return{timestamp:new Date().toISOString(),allPassed:x===0,checks:t,summary:{passed:T,failed:x,warnings:0}}}function dr(a){let e=["",Re.bold.cyan("\u{1FA7A} PromptTest Doctor \u2014 Environment Health Diagnostic"),Re.gray(`Scanned at ${a.timestamp}
|
|
875
|
+
`)];for(let t of a.checks){let s=t.passed?Re.green("\u2714"):Re.red("\u2716"),i=Re.bold(t.name);e.push(` ${s} ${i}: ${t.message}`),t.hint&&!t.passed&&e.push(Re.yellow(` \u{1F4A1} Fix: ${t.hint}`))}return e.push(""),a.allPassed?e.push(Re.bold.green("\u2728 All diagnostic checks passed! Your environment is ready to test.")):e.push(Re.bold.red(`\u26A0\uFE0F ${a.summary.failed} diagnostic check(s) failed. Please review the remediation hints above.`)),process.env.CI||e.push("",Re.dim("\u2500".repeat(64)),Re.cyan("\u{1F4A1} Prefer inspecting elements and authoring tests visually?"),Re.white(` Try PromptTest Studio (Desktop IDE): ${Re.underline("https://shriramsingh.github.io/prompttest-studio-site/")}`),Re.dim("\u2500".repeat(64))),e.push(""),e.join(`
|
|
876
|
+
`)}Ne();import An from"fs";import ui from"path";import M from"chalk";Fe();Ne();import pr from"fs";import Dn from"path";Fe();var bt=class{testData={};dataPath;isLoaded=!1;driver;constructor(e,t){this.dataPath=e||Dn.resolve(process.cwd(),"test-data.json"),this.driver=t||Pe}setTestData(e){this.testData=e,this.isLoaded=!0}async ensureDataLoaded(){if(!this.isLoaded){if(pr.existsSync(this.dataPath))try{let e=await pr.promises.readFile(this.dataPath,"utf-8");this.testData=JSON.parse(e)}catch{this.testData={}}this.isLoaded=!0}}async loadTestData(e){return e&&(this.dataPath=e),this.isLoaded=!1,await this.ensureDataLoaded(),this.testData}inferValueForNode(e,t){let s=[e.text,e.contentDesc,e.resourceId].join(" ").toLowerCase(),i="",n=t.filter(o=>o.text&&!o.clickable&&o.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-o.bounds.centerY<250&&Math.abs(o.bounds.centerX-e.bounds.centerX)<400);n.length>0&&(i=n[n.length-1].text.toLowerCase());let r=`${s} ${i}`.toLowerCase();if(r.includes("review")||r.includes("feedback")||r.includes("comment")||r.includes("write a review")||r.includes("experience")){if(!this.testData.review?.text)throw new Error("Missing test-data.json field: review.text");return this.testData.review.text}if(r.includes("card")||r.includes("credit")||r.includes("debit")||r.includes("card number")){let o=this.testData.payment?.card;if(o)return String(o);let c="4532";for(let l=0;l<12;l++)c+=Math.floor(Math.random()*10);return c}if(r.includes("phone")||r.includes("mobile")||!r.includes("card")&&r.includes("number")||r.includes("contact")){let o=this.testData.auth?.phone||this.testData.profile?.phone;if(!o)throw new Error("Missing test-data.json field: auth.phone or profile.phone");return o}if(r.includes("email")||r.includes("e-mail")||r.includes("mail")){let o=this.testData.profile?.email||this.testData.auth?.email;if(!o)throw new Error("Missing test-data.json field: profile.email or auth.email");return o}if(r.includes("cvv")||r.includes("cvc")||r.includes("security code"))return"123";if(r.includes("expiry")||r.includes("exp date")||r.includes("expiration"))return"12/28";if(r.includes("pincode")||r.includes("zip")||r.includes("postal")){if(!this.testData.profile?.pincode)throw new Error("Missing test-data.json field: profile.pincode");return this.testData.profile.pincode}if(e.password||r.includes("password")||/\bpin\b/.test(r)&&!r.includes("pincode")||r.includes("passcode")){if(!this.testData.auth?.password)throw new Error("Missing test-data.json field: auth.password");return this.testData.auth.password}if(r.includes("otp")||r.includes("verification")||r.includes("code")&&!r.includes("postal")&&!r.includes("zip")){if(!this.testData.auth?.otp)throw new Error("Missing test-data.json field: auth.otp");return this.testData.auth.otp}if(r.includes("address")||r.includes("street")||r.includes("location")){if(!this.testData.profile?.address)throw new Error("Missing test-data.json field: profile.address");return this.testData.profile.address}if(r.includes("city")||r.includes("state")){if(!this.testData.profile?.city)throw new Error("Missing test-data.json field: profile.city");return this.testData.profile.city}if(r.includes("name")||r.includes("full name")||r.includes("first name")){if(!this.testData.profile?.name)throw new Error("Missing test-data.json field: profile.name");return this.testData.profile.name}if(r.includes("search")||r.includes("find")||r.includes("query")){if(!this.testData.search?.query)throw new Error("Missing test-data.json field: search.query");return this.testData.search.query}return this.testData.review?.text||"PromptTest Auto QA Test Data"}async fillAndSubmitForm(e,t,s=!0,i=!1){await this.ensureDataLoaded();let n=Le(e),r=[];if(n.length===0)return{filledFields:[],submitted:!1};let o=!1;for(let p of n){let d=p.resourceId||p.text||`input_${p.bounds.centerX}_${p.bounds.centerY}`,u=(p.text||"").trim(),h=!u||/^enter\s+/i.test(u)||/^type\s+/i.test(u)||/^e\.g\./i.test(u)||/^(email|email address|password|phone|name|search)$/i.test(u);if(!i&&!h){r.push({fieldId:d,fieldLabel:p.text||p.contentDesc||p.resourceId,valueEntered:u});continue}let g=this.inferValueForNode(p,e);await this.driver.tap(p.bounds.centerX,p.bounds.centerY,t),await new Promise(b=>setTimeout(b,400)),await this.driver.clearField(t,g.length+10),await new Promise(b=>setTimeout(b,200)),await this.driver.inputText(g,t),await new Promise(b=>setTimeout(b,300)),o=!0,r.push({fieldId:d,fieldLabel:p.text||p.contentDesc||p.resourceId,valueEntered:g})}o&&(await this.driver.pressKey(4,t),await new Promise(p=>setTimeout(p,500)));let c=!1,l;if(s){let p=e.filter(d=>!d.clickable||d.bounds.width===0?!1:Oi.some(u=>de(u,d.text)||de(u,d.contentDesc)||de(u,d.resourceId)));if(p.length>0){let d=["submit","sign in","signin","login","save","confirm","proceed","continue"];p.sort((h,g)=>{let b=(h.text||h.contentDesc||h.resourceId||"").toLowerCase(),T=(g.text||g.contentDesc||g.resourceId||"").toLowerCase(),x=d.findIndex($=>b.includes($)),S=d.findIndex($=>T.includes($)),y=x>=0?x:99,P=S>=0?S:99;return y!==P?y-P:g.bounds.centerY-h.bounds.centerY});let u=p[0];l=u.text||u.contentDesc||u.resourceId,await this.driver.tap(u.bounds.centerX,u.bounds.centerY,t),await new Promise(h=>setTimeout(h,I.settle.submitWaitMs));try{let h=await this.driver.getUiHierarchy(t),{flat:g}=me(h),b=Le(g);c=!(b.length>0&&n.every(x=>b.some(S=>S.resourceId&&S.resourceId===x.resourceId)))}catch{c=!0}}}return{filledFields:r,submitted:c,submitButtonText:l}}},ur=new bt;import ie from"chalk";Ne();var ds=class{driver;reporter;memory;formFiller;screenLedger=new Map;callStack=[];executedStepCount=0;visitedScreenHashes=new Set;devDefectsList=[];safetyHitList=[];externalSkippedList=[];stepListener;abortFlag;constructor(e=Pe,t=dt,s=_t){this.driver=e,this.reporter=t,this.memory=s,this.formFiller=new bt(void 0,e)}emitStep(e){try{let t=e.screenHash?this.screenLedger.get(e.screenHash):void 0;this.stepListener?.({...e,depth:e.depth??t?.depth,elementCount:e.elementCount??t?.elements.length,discoveredScreens:e.discoveredScreens??this.visitedScreenHashes.size,totalSteps:e.totalSteps??this.executedStepCount})}catch{}}isAborted(){return this.abortFlag?.aborted===!0}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=me(i),r=0;for(;r<s;){let o=Kt(n);if(!o)break;r++;let c=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(ie.red(` \u{1F6A8} Global Dev Console Intercepted: ${c} "${o.errorText.slice(0,80)}"${l}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText),this.emitStep({type:"crash",description:`Dev overlay intercepted ${c}: "${o.errorText.slice(0,120)}"${l}`});let p=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${c}: "${o.errorText}"${l}`,"Verify","FAIL",o.errorText,p,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(ie.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(ie.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(ie.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(d=>setTimeout(d,800)),i=await this.driver.getUiHierarchy(t),n=me(i).flat}return{xml:i,flat:n}}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,150))}catch{}}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(!s)return!1;if(!s.includes(e)){let i=At(s);console.log(ie.yellow(` \u{1F6A8} External App Jailbreak Detected [${s}]. Recovering...`)),i||(await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,800)));let n=await this.driver.getForegroundPackage(t);return(!n||!n.includes(e))&&(console.log(ie.red(` Force restoring ${e} foreground...`)),await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1500)),this.callStack=this.callStack.slice(0,1)),!0}return!1}async handleExternalMediaChooser(e,t){let s=await this.driver.getForegroundPackage(t);if(!s)return!1;let i=s==="android"||s.includes("resolver")||s.includes("intentresolver");if(i){console.log(ie.yellow(` \u{1F6E1}\uFE0F External Media Chooser Intercepted [${s}]. Dismissing to stay in-app...`)),await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,800));let n=await this.driver.getForegroundPackage(t);return n&&!n.includes(e)&&i&&(await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1200)),this.callStack=this.callStack.slice(0,1)),!0}return!1}catalogScreen(e,t,s=[]){let i=[],n=t.height,r=n*.06,o=n*.88,c=y=>s.some(P=>Math.abs(P.bounds.centerX-y.bounds.centerX)<30&&Math.abs(P.bounds.centerY-y.bounds.centerY)<30),l=Le(e);for(let y of l){if(c(y))continue;let P=y.text||y.contentDesc||y.resourceId||"Text Input";i.push({node:y,type:"input",label:P,tested:!1})}let p=Ot(e);for(let y of p){if(c(y))continue;let P=y.text||y.contentDesc||y.resourceId||"Toggle Control";i.push({node:y,type:"toggle",label:P,tested:!1})}let d=Me(e);for(let y of d){if(c(y)||at([y],n,t.width)||He([y],n,t.width,!0))continue;let P=y.text||y.contentDesc||y.resourceId||"Action Button";if(Ve(y)){this.externalSkippedList.push(P);continue}let $=y.selected!==void 0||y.checkable||/(?:tab|chip|pill|filter|segment|toggle)/i.test(`${y.resourceId} ${y.className} ${y.contentDesc}`)||/(?:today|yesterday|all|active|archived|pending|completed|present|absent)/i.test(P);i.push({node:y,type:$?"toggle":"transition",label:P,tested:!1})}let u=Bi(e,n,t.width);for(let y of u){if(c(y)||He([y],n,t.width,!0)||i.some($=>Math.abs($.node.bounds.centerX-y.bounds.centerX)<25&&Math.abs($.node.bounds.centerY-y.bounds.centerY)<25))continue;let P=y.text||y.contentDesc||y.resourceId||"Notification / Header Action";if(Ve(y)){this.externalSkippedList.push(P);continue}i.push({node:y,type:"transition",label:P,tested:!1})}let h=e.filter(y=>{if(!y.clickable||y.bounds.width===0)return!1;let P=`${y.text} ${y.contentDesc} ${y.resourceId}`.toLowerCase();return P.includes("now playing")||P.includes("play")||P.includes("pause")});for(let y of h){if(c(y)||i.some($=>Math.abs($.node.bounds.centerX-y.bounds.centerX)<25&&Math.abs($.node.bounds.centerY-y.bounds.centerY)<25))continue;let P=y.text||y.contentDesc||y.resourceId||"Media Control";i.push({node:y,type:"toggle",label:P,tested:!1})}let g=zt(e,t).filter(y=>!c(y)&&y.bounds.centerY>r&&y.bounds.centerY<o&&!He([y],n,t.width,!0)&&!Ve(y)),b=Yi(g,2);for(let y of b){let P=y.text||y.contentDesc||y.resourceId||`Item (${y.bounds.centerX},${y.bounds.centerY})`;i.push({node:y,type:"transition",label:P,tested:!1})}let T=0,x=0,S=[];for(let y of i){let P=/\.(?:mp4|mkv|mov|webm|flv|avi)\b/i.test(y.label),$=/\.(?:mp3|wav|m4a|aac|ogg)\b/i.test(y.label);if(P){if(T++,T>1)continue}else if($&&(x++,x>1))continue;S.push(y)}return S}async safeBacktrack(e,t,s,i,n=!0){let{flat:r}=await this.getCleanUiHierarchy(t,s),{height:o,width:c}=await this.driver.getScreenDimensions(s),l=Ue(r,{width:c,height:o});if(l===e)return!0;let p=He(r,o,c,!0);if(p&&p.bounds.width>0){console.log(ie.gray(` [Backtrack] Tapping in-app back/close button "${p.text||p.contentDesc||p.className}"...`)),await this.driver.tap(p.bounds.centerX,p.bounds.centerY,s),await new Promise(h=>setTimeout(h,1e3)),await this.packageJailGuard(t,s);let d=await this.getCleanUiHierarchy(t,s),u=Ue(d.flat,{width:c,height:o});if(u===e||u!==l)return!0}if(i&&i.bounds.width>0){console.log(ie.gray(` [Backtrack] Restoring root domain via tab "${i.text||i.contentDesc||"Root Tab"}"...`)),await this.driver.tap(i.bounds.centerX,i.bounds.centerY,s),await new Promise(h=>setTimeout(h,1e3)),await this.packageJailGuard(t,s);let d=await this.getCleanUiHierarchy(t,s),u=Ue(d.flat,{width:c,height:o});if(u===e||u!==l)return!0}if(n){if(console.log(ie.gray(" [Backtrack] Sending fallback KEYCODE_BACK...")),await this.driver.pressKey(4,s),await new Promise(g=>setTimeout(g,1e3)),await this.packageJailGuard(t,s))return console.log(ie.yellow(" \u26A0\uFE0F Backtrack via KEYCODE_BACK caused app jailbreak. Aborting branch restoration.")),!1;let u=await this.getCleanUiHierarchy(t,s),h=Ue(u.flat,{width:c,height:o});if(h===e||h!==l)return!0}return!1}async explore(e){let{packageName:t,serial:s,maxScreens:i=30,maxDepth:n=3,stepBudget:r=100,maxInteractionsPerScreen:o=6,safetyMode:c="strict",safetyBlacklist:l=[],onStep:p,abortSignal:d}=e;this.stepListener=p,this.abortFlag=d,console.log(ie.bold.cyan(`
|
|
877
|
+
\u{1F916} PromptTest Universal State-Graph DFS Engine`)),console.log(ie.gray(`Target Package: ${t}`)),console.log(ie.gray(`Safety Policy: ${c.toUpperCase()}`)),console.log(ie.gray(`Limits: Max Screens = ${i}, Step Budget = ${r}, Max Depth = ${n}`)),await this.driver.clearCrashLogs(s);let u=await this.driver.getScreenDimensions(s),h=await this.driver.getForegroundPackage(s);(!h||!h.includes(t))&&(console.log(ie.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(y=>setTimeout(y,2500)));let{flat:g}=await this.getCleanUiHierarchy(t,s);await this.dismissSoftKeyboard(s);let b=Ts(g,u,t);console.log(ie.magenta(`\u26A1 Universal Paradigm Detected: [${b.paradigm.toUpperCase()}] with ${b.roots.length} root node(s).`));let T=[],x;if(b.paradigm==="drawer"&&b.roots.length>0){x=b.roots[0];let y={...g[0]||{},text:"Home Screen / Main Hub",contentDesc:"Home Screen / Main Hub",clickable:!0,bounds:{x1:0,y1:0,x2:u.width,y2:u.height,centerX:u.width/2,centerY:u.height/2,width:u.width,height:u.height}};T.push(y),console.log(ie.gray(" Opening drawer to catalog root destinations...")),await this.driver.tap(x.bounds.centerX,x.bounds.centerY,s),await new Promise(U=>setTimeout(U,1200));let P=await this.getCleanUiHierarchy(t,s),$=P.flat.filter(U=>{if(!U.clickable||U.bounds.width===0||U.bounds.height===0||U.bounds.width>=u.width*.95&&U.bounds.height>=u.height*.95||He([U],u.height,u.width,!0))return!1;let Z=`${U.contentDesc} ${U.text}`.trim(),W=U.bounds.width>u.width*.15&&U.bounds.height>u.height*.05;return Z.toLowerCase().includes("developed by")||U.bounds.centerY>u.height*.85?!1:Z.length>=2||W});for(let U of $)T.some(Z=>Math.abs(Z.bounds.centerX-U.bounds.centerX)<30&&Math.abs(Z.bounds.centerY-U.bounds.centerY)<30)||T.push(U);let R=He(P.flat,u.height,u.width,!0);R?await this.driver.tap(R.bounds.centerX,R.bounds.centerY,s):await this.driver.tap(x.bounds.centerX,x.bounds.centerY,s),await new Promise(U=>setTimeout(U,1200));let C=await this.getCleanUiHierarchy(t,s);if(C.flat.some(U=>`${U.contentDesc} ${U.text}`.includes("Gallery")&&`${U.contentDesc} ${U.text}`.includes("Planner"))){let U=He(C.flat,u.height,u.width,!0);U?await this.driver.tap(U.bounds.centerX,U.bounds.centerY,s):await this.driver.tap(u.width-50,u.height/2,s),await new Promise(Z=>setTimeout(Z,1e3))}console.log(ie.magenta(` Discovered ${T.length} destinations (1 Main Hub + ${T.length-1} Drawer destinations).`))}else b.roots.length>0?T=b.roots:T=[g[0]||{text:"Main Hub",clickable:!0}];let S=1;for(let y of T){if(this.executedStepCount>=r||this.visitedScreenHashes.size>=i||this.isAborted())break;let P=y.text||y.contentDesc||`Root #${S}`;if(console.log(ie.yellow(`
|
|
878
|
+
[Domain ${S}/${T.length}] Entering Root Tree: "${P}"...`)),this.emitStep({type:"action",description:`Tap "${P}" to enter the ${P} section`,screenTitle:P,depth:0}),b.paradigm==="bottom_tabs"||b.paradigm==="top_tabs"){let C=y.bounds.height<25?Math.max(y.bounds.y1-10,y.bounds.centerY):Math.min(y.bounds.centerY,y.bounds.y2-4);await this.driver.tap(y.bounds.centerX,C,s),this.executedStepCount++,await new Promise(B=>setTimeout(B,1200))}else b.paradigm==="drawer"&&S>1&&x&&(await this.dismissSoftKeyboard(s),console.log(ie.gray(` Opening drawer to select "${P}"...`)),await this.driver.tap(x.bounds.centerX,x.bounds.centerY,s),await new Promise(C=>setTimeout(C,1e3)),await this.driver.tap(y.bounds.centerX,y.bounds.centerY,s),this.executedStepCount++,await new Promise(C=>setTimeout(C,1500)));g=(await this.getCleanUiHierarchy(t,s)).flat,await this.dismissSoftKeyboard(s);let R=S===1?Math.max(25,Math.ceil(r*.45)):Math.max(8,Math.ceil(r*.55/Math.max(1,T.length-1)));if(await this.exploreDfsNode({packageName:t,serial:s,screenDims:u,rootNodes:b.roots,activeRootNode:y,currentDepth:0,maxDepth:n,maxScreens:i,stepBudget:r,domainStepLimit:this.executedStepCount+R,maxInteractionsPerScreen:o,safetyMode:c,safetyBlacklist:l,domainLabel:P}),b.paradigm==="drawer"&&S>1){let C=0;for(;C<4;){let B=await this.getCleanUiHierarchy(t,s),U=at(B.flat,u.height,u.width),Z=B.flat.some(J=>`${J.contentDesc} ${J.text}`.includes("Gallery")&&`${J.contentDesc} ${J.text}`.includes("Planner"));if(U&&!Z)break;let W=He(B.flat,u.height,u.width,!0);if(W)console.log(ie.gray(" [Domain Wrap-Up] Returning to Home Screen via in-app back...")),await this.driver.tap(W.bounds.centerX,W.bounds.centerY,s),await new Promise(J=>setTimeout(J,1e3)),C++;else break}}if(S===1&&T.length===1){let C=await this.getCleanUiHierarchy(t,s),B=Ts(C.flat,u,t);if((B.paradigm==="bottom_tabs"||B.paradigm==="top_tabs")&&B.roots.length>1){console.log(ie.magenta(`
|
|
879
|
+
\u26A1 Post-Auth Navigation Discovered: [${B.paradigm.toUpperCase()}] with ${B.roots.length} root domain(s)!`)),b.paradigm=B.paradigm,b.roots=B.roots;let U=B.roots.slice(1);T.push(...U.length>0?U:B.roots)}}S++}for(let y of this.visitedScreenHashes)this.memory.markScreenCrawled(y);await this.memory.save(),this.isAborted()||this.emitStep({type:"done",description:`Autonomous exploration complete: ${this.visitedScreenHashes.size} screen(s) mapped in ${this.executedStepCount} step(s)`}),console.log(ie.green(`
|
|
880
|
+
\u2714 Universal DFS Traversal Complete!`)),console.log(ie.cyan(` Visited Screens: ${this.visitedScreenHashes.size}`)),console.log(ie.cyan(` Total Steps Executed: ${this.executedStepCount}/${r}`)),console.log(ie.cyan(` Defects Triaged: ${this.devDefectsList.length}`))}async exploreDfsNode(e){let{packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,currentDepth:o,maxDepth:c,maxScreens:l,stepBudget:p,domainStepLimit:d,maxInteractionsPerScreen:u,safetyMode:h,safetyBlacklist:g,domainLabel:b}=e;if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l||d&&this.executedStepCount>=d||this.isAborted())return;let{flat:T}=await this.getCleanUiHierarchy(t,s),x=ye(T),S=Ue(T,i);this.visitedScreenHashes.add(x);let y=this.screenLedger.get(S);if(y){if(y.status==="FULLY_EXPLORED"){console.log(ie.gray(` \u26A1 Cycle Detected: Screen [${S.slice(0,8)}] already fully explored. Pruning branch.`));return}}else{let C=this.catalogScreen(T,i,n);y={hash:x,semanticHash:S,title:`${b} (depth ${o})`,elements:C,status:"IN_PROGRESS",depth:o,interactionCount:0},this.screenLedger.set(S,y),console.log(ie.cyan(` \u{1F50E} Discovered Screen [${S.slice(0,8)}] at depth ${o} with ${C.length} candidate element(s).`)),this.emitStep({type:"state_change",description:`Discovered screen "${b}" at depth ${o} with ${C.length} candidate element(s)`,screenHash:S,screenTitle:b,depth:o})}this.callStack.push({screenHash:x,semanticHash:S,title:y.title,timestamp:Date.now()});let P=y.elements.filter(C=>C.type==="input"&&!C.tested);if(P.length>0&&y.interactionCount<u){console.log(ie.magenta(` Filling in-place form fields (${P.length} inputs)...`));let C=await this.formFiller.fillAndSubmitForm(T,s,!0,!1);this.executedStepCount++,y.interactionCount++;for(let B of P)B.tested=!0;await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s),this.reporter.logStep("In-Place Form Fill",`Populated ${C.filledFields.length} field(s) on [${S.slice(0,8)}]`,"FormSubmit","PASS",C.submitButtonText||"Auto");for(let B of C.filledFields)this.emitStep({type:"action",description:`Type "${B.valueEntered}" in the "${B.fieldLabel}" field`,screenHash:S,screenTitle:b,depth:o});C.submitButtonText&&this.emitStep({type:"action",description:`Tap "${C.submitButtonText}" to submit the form`,screenHash:S,screenTitle:b,depth:o})}let $=y.elements.filter(C=>C.type==="toggle"&&!C.tested);for(let C of $){if(this.executedStepCount>=p||y.interactionCount>=u)break;if(C.tested=!0,Je(C.node,g,h)){this.safetyHitList.push(C.label),this.emitStep({type:"safety_block",description:`Safety policy [${h.toUpperCase()}] blocked toggle "${C.label}"`,screenHash:S,screenTitle:b,depth:o});continue}console.log(ie.gray(` Exercising toggle: "${C.label.slice(0,30)}"...`)),this.executedStepCount++,y.interactionCount++,await this.driver.tap(C.node.bounds.centerX,C.node.bounds.centerY,s),await new Promise(B=>setTimeout(B,600)),this.reporter.logStep("In-Place Toggle",`Toggled control "${C.label}"`,"Tap","PASS",C.label),this.emitStep({type:"action",description:`Toggle "${C.label}"`,screenHash:S,screenTitle:b,depth:o})}let R=y.elements.filter(C=>C.type==="transition"&&!C.tested);for(let C of R){if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l||d&&this.executedStepCount>=d&&!(o===0&&b.includes("Home Screen"))||y.interactionCount>=u||this.isAborted())break;if(C.tested=!0,Ve(C.node)){this.externalSkippedList.push(C.label);continue}if(Je(C.node,g,h)){this.safetyHitList.push(C.label),this.emitStep({type:"safety_block",description:`Safety policy [${h.toUpperCase()}] blocked transition "${C.label}"`,screenHash:S,screenTitle:b,depth:o});continue}console.log(ie.magenta(` \u26A1 [DFS Depth ${o}] Testing transition: "${C.label.slice(0,40)}"...`)),this.executedStepCount++,y.interactionCount++,await this.driver.tap(C.node.bounds.centerX,C.node.bounds.centerY,s),await new Promise(W=>setTimeout(W,1500)),await this.dismissSoftKeyboard(s),await this.handleExternalMediaChooser(t,s),await this.packageJailGuard(t,s);let B=await this.getCleanUiHierarchy(t,s),U=Ue(B.flat,i),Z=U!==S;if(this.reporter.logStep("DFS Transition",`Tapped "${C.label}" [${Z?"Navigated":"In-Place"}]`,"Tap","PASS",C.label),this.emitStep({type:"action",description:`Tap "${C.label}"${Z?" to navigate to the next screen":""}`,screenHash:S,screenTitle:b,depth:o}),Z&&U&&this.emitStep({type:"state_change",description:`Navigated to screen [${U.slice(0,8)}] via "${C.label}"`,screenHash:U,screenTitle:`${b} > ${C.label.slice(0,20)}`,depth:o+1}),Z){if(o<c){let Ee=o===0&&b.includes("Home Screen")?Math.min(this.executedStepCount+3,d||this.executedStepCount+3):d;await this.exploreDfsNode({packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,domainStepLimit:Ee,currentDepth:o+1,maxDepth:c,maxScreens:l,stepBudget:p,maxInteractionsPerScreen:u,safetyMode:h,safetyBlacklist:g,domainLabel:`${b} > ${C.label.slice(0,20)}`})}console.log(ie.gray(` [DFS Backtrack] Returning to [${S.slice(0,8)}]...`)),await this.safeBacktrack(S,t,s,o===0?r:void 0,o>0),await this.dismissSoftKeyboard(s);let W=await this.getCleanUiHierarchy(t,s);if(Ue(W.flat,i)!==S){let Ee=He(W.flat,i.height,i.width,!0);Ee&&(console.log(ie.gray(" [Backtrack Verification] Re-tapping in-app back/close button...")),await this.driver.tap(Ee.bounds.centerX,Ee.bounds.centerY,s),await new Promise(re=>setTimeout(re,1e3)),await this.packageJailGuard(t,s));let se=await this.getCleanUiHierarchy(t,s);if(Ue(se.flat,i)!==S){console.log(ie.yellow(` \u26A0\uFE0F Unable to restore parent screen [${S.slice(0,8)}]. Unwinding branch to prevent jailbreak loop.`));break}}}}y.status="FULLY_EXPLORED",this.callStack.pop()}};var yt=class{driver;formFiller;reporter;memory;safetyHitList=[];externalSkippedList=[];devDefectsList=[];visitedScreenHashes=new Set;executedStepCount=0;constructor(e,t,s,i){this.driver=e||Pe,this.formFiller=t||ur,this.reporter=s||dt,this.memory=i||_t}getMemory(){return this.memory}getSafetyHitList(){return this.safetyHitList}getExternalSkippedList(){return this.externalSkippedList}getDevDefectsList(){return this.devDefectsList}getVisitedScreensCount(){return this.visitedScreenHashes.size}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(s&&!s.includes(e)){let i=At(s);console.log(M.yellow(` \u{1F6E1}\uFE0F Jail Containment: App escaped to "${s}". Executing containment recovery...`)),i||(await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,600)));let n=await this.driver.getForegroundPackage(t);return(!n||!n.includes(e))&&(console.log(M.gray(` Force re-launching ${e} to restore foreground...`)),await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1200))),this.reporter.logStep("Jail Containment",`App escaped to "${s}"; successfully contained and restored "${e}"`,"Back","PASS"),!0}return!1}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=me(i),r=0;for(;r<s;){let o=Kt(n);if(!o)break;r++;let c=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(M.red(` \u{1F6A8} Global Dev Console Intercepted: ${c} "${o.errorText.slice(0,80)}"${l}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let p=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${c}: "${o.errorText}"${l}`,"Verify","FAIL",o.errorText,p,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(M.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(M.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(M.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(d=>setTimeout(d,800)),i=await this.driver.getUiHierarchy(t),n=me(i).flat}return{xml:i,flat:n}}async handleDevOverlays(e,t,s){let i=Kt(e);if(!i)return!1;let n=`[${(i.severity||"error").toUpperCase()} - ${i.type.toUpperCase()}]`,r=i.sourceLocation?` [${i.sourceLocation}]`:"";console.log(M.red(` \u{1F6A8} Dev Overlay Detected: ${n} "${i.errorText.slice(0,80)}"${r}`)),this.devDefectsList.push(i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText);let o=await this.driver.captureScreenshot(s);return this.reporter.logStep("Dev Overlay Triage",`Detected and triaged ${n} error: "${i.errorText}"${r}`,"Verify","FAIL",i.errorText,o,{errors:[i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText]}),i.dismissButton&&i.dismissButton.bounds.width>0?(console.log(M.gray(" Dismissing error overlay via dismiss button...")),await this.driver.tap(i.dismissButton.bounds.centerX,i.dismissButton.bounds.centerY,s)):i.isToast&&i.node&&i.node.bounds.width>0?(console.log(M.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(i.node.bounds.centerX,i.node.bounds.centerY,s)):(console.log(M.gray(" Pressing Back to dismiss error overlay...")),await this.driver.pressBack(s)),await new Promise(c=>setTimeout(c,800)),!0}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,200))}catch{}}async explore(e){let{packageName:t,serial:s,maxTabs:i=I.explorer?.maxTabs||15,exploreLists:n=!0,skipAlreadyCrawled:r=!1,safetyMode:o=I.safety?.mode||"strict",safetyBlacklist:c=I.safety?.customBlacklist?[...I.safety.customBlacklist]:[],maxScreens:l=I.explorer?.maxScreens||30,stepBudget:p=I.explorer?.stepBudget||100,screenshots:d=I.explorer?.screenshots||"state-change",video:u=e.video??!1,onStep:h,abortSignal:g}=e;console.log(M.cyan(`
|
|
881
|
+
\u{1F916} PromptTest Autonomous Exploration Brain v3`)),console.log(M.gray("Target Package: ")+M.bold.white(t)),console.log(M.gray("Safety Policy: ")+M.bold.yellow(o.toUpperCase())+(c.length>0?M.gray(` (+${c.length} custom blacklist)`):"")),console.log(M.gray("Screenshots Policy: ")+M.bold.white(d));let b=[],T=0,x=C=>{T++,h?.({...C,stepNumber:T,packageName:t,totalSteps:C.totalSteps??this.executedStepCount,discoveredScreens:C.discoveredScreens??this.visitedScreenHashes.size})},S=async(C,B=!0)=>{if(!(d==="failure-only"&&C!=="FAIL")&&!(d==="state-change"&&!B&&C!=="FAIL"))try{return await this.driver.captureScreenshot(s)}catch{return}};await this.memory.init(t);let y=s||this.driver.getDefaultDevice(),P=y||"Default Device";this.reporter.init(t,P);let $=null;y&&($=Et(y));let R=null;this.safetyHitList=[],this.externalSkippedList=[],this.devDefectsList=[],this.visitedScreenHashes.clear(),this.executedStepCount=0;try{if(await this.driver.clearCrashLogs(s),u&&(console.log(M.cyan("\u{1F3AC} Starting ADB screen recording for exploration (--video enabled)...")),R=await this.driver.startScreenRecording("/sdcard/prompttest_explore_temp.mp4",s)),(e.strategy||I.explorer?.strategy||"heuristic")==="dfs"){let E=new ds(this.driver,this.reporter,this.memory);await E.explore({packageName:t,serial:s,maxScreens:l,maxDepth:e.maxDepth||I.explorer?.maxDepth||5,stepBudget:p,safetyMode:o,safetyBlacklist:c,screenshotPolicy:d,skipAlreadyCrawled:r,onStep:v=>x({type:v.type,description:v.description,screenHash:v.screenHash,screenTitle:v.screenTitle,depth:v.depth,elementCount:v.elementCount,totalSteps:v.totalSteps,discoveredScreens:v.discoveredScreens}),abortSignal:g}),this.safetyHitList=E.safetyHitList,this.externalSkippedList=E.externalSkippedList,this.devDefectsList=E.devDefectsList,this.visitedScreenHashes=E.visitedScreenHashes,this.executedStepCount=E.executedStepCount;let L=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${L.totalScreens} crawled screen(s).`,"Verify","PASS"),await this.reporter.generateReport(),console.log(M.bold.green(`
|
|
882
|
+
\u2728 Full Audit Report generated at: output/prompttest-report.md`));return}let{width:B,height:U}=await this.driver.getScreenDimensions(s);console.log(M.yellow(`
|
|
883
|
+
[1/5] Verifying Foreground State...`));let Z=await this.driver.getForegroundPackage(s);(!Z||!Z.includes(t))&&(console.log(M.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(E=>setTimeout(E,2500)));let W=await this.runErrorSentinel(t,s,"Post-Launch"),J=W.hasError?"FAIL":"PASS",Ee=await S(J,!0);this.reporter.logStep("Init",`Launched and verified foreground for ${t}`,"Launch",J,t,Ee,W.hasError?{errors:W.errors}:void 0),console.log(J==="PASS"?M.green("\u2714 App is active in foreground."):M.red(`\u2716 Issues detected during launch for ${t}.`)),console.log(M.yellow(`
|
|
884
|
+
[2/5] Inspecting UI Hierarchy for Forms...`));let{xml:se,flat:j}=await this.getCleanUiHierarchy(t,s),re=ye(j);if(this.visitedScreenHashes.add(re),this.memory.isScreenCrawled(re)&&r)console.log(M.cyan(` \u26A1 Fast-Forward: Screen [${re.slice(0,8)}] was previously crawled offline. Skipping redundant element interactions.`)),this.reporter.logStep("Fast Forward",`Fast-forwarded past previously crawled screen [${re.slice(0,8)}] (Memory Engine)`,"Skip","PASS");else{let E=Le(j);if(E.length>0){console.log(M.magenta(`\u26A1 Detected ${E.length} form field(s)! Engaging Semantic Form Filler...`));for(let K of E)console.log(M.gray(` - Field: "${K.text||K.contentDesc||K.resourceId}"`));let k=await this.formFiller.fillAndSubmitForm(j,s,!0,!1);this.executedStepCount++,await new Promise(K=>setTimeout(K,1500)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let F=await this.getCleanUiHierarchy(t,s);se=F.xml,j=F.flat,this.visitedScreenHashes.add(ye(j));let N=await this.runErrorSentinel(t,s,"Post-Form-Submit"),H=Le(j),ee=N.hasError||H.length===E.length&&N.errors.length>0?"FAIL":"PASS",G=await S(ee,!0),z=k.filledFields.map(K=>`${K.fieldLabel} -> "${K.valueEntered}"`).join(", ");this.reporter.logStep("Form Fill",`Filled ${k.filledFields.length} field(s) [${z}] and submitted via "${k.submitButtonText||"Auto"}"`,"FormSubmit",ee,k.submitButtonText,G,N.hasError?{errors:N.errors}:void 0),console.log(ee==="PASS"?M.green("\u2714 Form populated and submitted successfully!"):M.red("\u2716 Form submission triggered an error or remained unauthenticated."))}else console.log(M.gray("No form input fields detected on initial screen."));console.log(M.yellow(`
|
|
885
|
+
[3/5] Inspecting Interactive Action Controls...`));let L=Me(j).filter(k=>{let F=(k.text+" "+k.contentDesc).toLowerCase();if(F.includes("submit")||F.includes("cancel")||at([k],U))return!1;if(Ve(k)){let N=k.text||k.contentDesc||k.resourceId||"External Link";return console.log(M.gray(` \u{1F517} External Link Bypassed: "${N}"`)),this.externalSkippedList.push(N),!1}if(Je(k,c,o)){let N=k.text||k.contentDesc||k.resourceId||"Action";return console.log(M.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive action "${N}"`)),this.safetyHitList.push(N),!1}return!0});if(L.length>0){let k=L[0],F=k.text||k.contentDesc||k.resourceId;console.log(M.magenta(`\u26A1 Found action button: "${F}". Testing interaction...`));let N=ye(j);this.executedStepCount++,await this.driver.tap(k.bounds.centerX,k.bounds.centerY,s),await new Promise(ve=>setTimeout(ve,1200)),await this.packageJailGuard(t,s);let H=await this.getCleanUiHierarchy(t,s);se=H.xml,j=H.flat;let V=ye(j);this.visitedScreenHashes.add(V);let ee=await this.runErrorSentinel(t,s,"Post-Action-Tap"),G=N!==V,z="PASS",K="";ee.hasError?(z="FAIL",K="Action triggered error or crash"):G?(z="PASS",K="Screen transitioned successfully"):(z="WARN",K="No visible screen transition or state change observed (No-Op)",console.log(M.yellow(` \u26A0\uFE0F Outcome Warning: Action "${F}" produced no UI state change.`)));let he=await S(z,G);this.reporter.logStep("Action Testing",`Tapped action button "${F}" [${K}]`,"Tap",z,F,he,ee.hasError?{errors:ee.errors}:void 0),console.log(z==="PASS"?M.green(`\u2714 Action interaction complete (${K}).`):z==="WARN"?M.yellow(`\u2714 Action interaction recorded with warning (${K}).`):M.red("\u2716 Action interaction triggered an error.")),z!=="FAIL"&&(this.memory.recordSuccess("TAP",F,k.resourceId||k.text||k.contentDesc||F,"text",1,void 0,N),this.memory.markScreenCrawled(N,[F]))}else console.log(M.gray("No standalone action buttons to test."));let v=Ot(j).filter(k=>!Je(k,c,o));if(v.length>0){console.log(M.yellow(`
|
|
886
|
+
[3b/5] Inspecting Toggle & Checkable Controls...`));let k=v[0],F=k.text||k.contentDesc||k.resourceId||"Switch/Checkbox",N=k.checked;console.log(M.magenta(`\u26A1 Found toggle: "${F}" (checked: ${N}). Testing toggle interaction...`)),this.executedStepCount++,await this.driver.tap(k.bounds.centerX,k.bounds.centerY,s),await new Promise(ve=>setTimeout(ve,1e3)),se=await this.driver.getUiHierarchy(s),j=me(se).flat;let H=ye(j);this.visitedScreenHashes.add(H);let ee=Ot(j).find(ve=>Math.abs(ve.bounds.centerX-k.bounds.centerX)<25&&Math.abs(ve.bounds.centerY-k.bounds.centerY)<25),G=ee?ee.checked!==N:!0,z=await this.runErrorSentinel(t,s,"Post-Toggle"),K=z.hasError?"FAIL":G?"PASS":"WARN",he=await S(K,G);this.reporter.logStep("Toggle Testing",`Toggled "${F}" (Checked: ${N} -> ${ee?ee.checked:"flipped"})`,"Toggle",K,F,he,z.hasError?{errors:z.errors}:void 0),console.log(K==="PASS"?M.green("\u2714 Toggle control flipped successfully!"):K==="WARN"?M.yellow("\u26A0\uFE0F Toggle tapped but checked state did not flip."):M.red("\u2716 Toggle control triggered an error.")),K!=="FAIL"&&this.memory.markScreenCrawled(H,[F])}let A=at(j,U);if(A&&!Je(A,c,o)){let k=A.contentDesc||A.text||A.resourceId||"Drawer Menu";console.log(M.yellow(`
|
|
887
|
+
[3c/5] Inspecting Side Navigation Drawer...`)),console.log(M.magenta(`\u26A1 Found drawer trigger: "${k}". Opening side drawer...`));let F=ye(j);this.executedStepCount++,await this.driver.tap(A.bounds.centerX,A.bounds.centerY,s),await new Promise(K=>setTimeout(K,1200)),await this.packageJailGuard(t,s);let N=await this.getCleanUiHierarchy(t,s);se=N.xml,j=N.flat;let H=ye(j);this.visitedScreenHashes.add(H);let V=F!==H,ee=await this.runErrorSentinel(t,s,"Drawer-Open"),G=ee.hasError?"FAIL":V?"PASS":"WARN",z=await S(G,V);if(this.reporter.logStep("Drawer Navigation",`Opened side drawer via "${k}"`,"Tap",G,k,z,ee.hasError?{errors:ee.errors}:void 0),G==="PASS"){console.log(M.green("\u2714 Side drawer opened successfully!"));let K=Me(j).filter(ve=>!Je(ve,c,o)&&!Ve(ve)&&ve.bounds.centerY>A.bounds.y2);if(K.length>0){let ve=K[0],We=ve.text||ve.contentDesc||ve.resourceId||"Drawer Item";console.log(M.gray(` - Testing drawer item: "${We}"...`)),this.executedStepCount++,await this.driver.tap(ve.bounds.centerX,ve.bounds.centerY,s),await new Promise(be=>setTimeout(be,1200)),await this.packageJailGuard(t,s);let vt=await this.getCleanUiHierarchy(t,s);se=vt.xml,j=vt.flat,this.visitedScreenHashes.add(ye(j))}console.log(M.gray(" Closing side drawer to restore main view...")),await this.driver.pressBack(s),await new Promise(ve=>setTimeout(ve,1e3));let he=await this.getCleanUiHierarchy(t,s);se=he.xml,j=he.flat,this.visitedScreenHashes.add(ye(j)),console.log(M.green("\u2714 Main view restored from side drawer."))}else G==="WARN"&&console.log(M.yellow("\u26A0\uFE0F Drawer button tapped but no visible screen change occurred."));G!=="FAIL"&&this.memory.markScreenCrawled(F,[k])}if(n){console.log(M.yellow(`
|
|
888
|
+
[4/5] Inspecting Lists & Master-Detail Flows...`));let k=Ui(j);if(k.length>0){console.log(M.magenta(`\u26A1 Found ${k.length} scrollable container(s). Performing vertical scroll exploration...`));let N=ye(j),H=Math.round(B*.5);await this.driver.swipe(H,Math.round(U*.7),H,Math.round(U*.3),300,s),await new Promise(K=>setTimeout(K,1200));let V=await this.getCleanUiHierarchy(t,s);se=V.xml,j=V.flat;let ee=ye(j);this.visitedScreenHashes.add(ee);let G=N!==ee,z=await S("PASS",G);this.reporter.logStep("Scroll Exploration",G?"Scrolled vertically to discover off-screen elements":"Scrolled but content remained at edge","Swipe","PASS","SwipeUp",z),G&&console.log(M.green("\u2714 Vertical scroll succeeded; discovered off-screen content below fold."))}let F=zt(j).filter(N=>{if(Ve(N)){let H=N.text||N.contentDesc||"External Link";return this.externalSkippedList.push(H),!1}if(Je(N,c,o)){let H=N.text||N.contentDesc||"List Item";return console.log(M.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive list item "${H}"`)),this.safetyHitList.push(H),!1}return!0});if(F.length>0){let N=F[0],H=N.text||N.contentDesc||`Item at (${N.bounds.centerX}, ${N.bounds.centerY})`;console.log(M.magenta(`\u26A1 Found list item: "${H}". Diving into detail view...`));let V=ye(j);await this.driver.tap(N.bounds.centerX,N.bounds.centerY,s),await new Promise(Xe=>setTimeout(Xe,1800));let ee=await this.getCleanUiHierarchy(t,s);se=ee.xml,j=ee.flat;let G=ye(j);this.visitedScreenHashes.add(G);let z=await this.runErrorSentinel(t,s,"Detail-View"),K=V!==G,he=z.hasError?"FAIL":K?"PASS":"WARN",ve=await S(he,K);this.reporter.logStep("List Dive",`Dived into detail view for "${H}" [${K?"Navigated":"Unchanged"}]`,"Tap",he,H,ve,z.hasError?{errors:z.errors}:void 0),console.log(he==="PASS"?M.green("\u2714 Detail screen loaded."):he==="WARN"?M.yellow("\u26A0\uFE0F Detail view tapped but no navigation detected."):M.red("\u2716 Detail view triggered an error."));let We=He(ee.flat,I.screen.fallbackHeight,I.screen.fallbackWidth,!0);We&&We.bounds.width>0?(console.log(M.gray(`Navigating back via in-app back button "${We.text||We.contentDesc||We.className}"...`)),await this.driver.tap(We.bounds.centerX,We.bounds.centerY,s)):(console.log(M.gray("Navigating back to main view...")),await this.driver.pressKey(4,s)),await new Promise(Xe=>setTimeout(Xe,1200));let vt=await this.driver.getForegroundPackage(s);vt&&!vt.includes(t)&&(console.log(M.yellow(`Restoring ${t} foreground after back navigation...`)),await this.driver.launchApp(t,s),await new Promise(Xe=>setTimeout(Xe,2e3)));let be=await this.getCleanUiHierarchy(t,s);se=be.xml,j=be.flat,this.visitedScreenHashes.add(ye(j));let $e=await this.runErrorSentinel(t,s,"Post-Back-Restore"),rt=$e.hasError?"FAIL":"PASS",es=await S(rt,!0);this.reporter.logStep("List Dive","Navigated back to master screen","Back",rt,"KEYCODE_BACK",es,$e.hasError?{errors:$e.errors}:void 0),rt==="PASS"&&console.log(M.green("\u2714 Master view restored."))}else console.log(M.gray("No list items found for master-detail exploration."))}}console.log(M.yellow(`
|
|
889
|
+
[5/5] Inspecting Navigation Tabs...`));let f=await this.driver.getForegroundPackage(s);f&&!f.includes(t)&&(console.log(M.gray(`Restoring ${t} foreground for tab traversal...`)),await this.driver.launchApp(t,s),await new Promise(E=>setTimeout(E,2e3))),await this.dismissSoftKeyboard(s);let O=await this.getCleanUiHierarchy(t,s);se=O.xml,j=O.flat;let D=ot(j,void 0,t);if(D.length>1){console.log(M.magenta(`\u26A1 Found ${D.length} navigation tab(s). Traversal sequence initiated...`));let E=D.slice(0,i),L=1;for(let v of E){let A=v.text||v.contentDesc||`Tab #${L}`;console.log(M.gray(` - Visiting ${A}...`)),await this.dismissSoftKeyboard(s);let k=Math.min(v.bounds.centerY,v.bounds.y2-4);this.executedStepCount++,await this.driver.tap(v.bounds.centerX,k,s),await new Promise(G=>setTimeout(G,1500)),await this.packageJailGuard(t,s);let F=await this.getCleanUiHierarchy(t,s);se=F.xml,j=F.flat;let N=ye(j);this.visitedScreenHashes.add(N),this.memory.markScreenCrawled(N,[A]);let H=await this.runErrorSentinel(t,s,`Tab-${A}`),V=H.hasError?"FAIL":"PASS",ee=await S(V,!0);if(this.reporter.logStep("Tab Traversal",`Navigated to tab "${A}"`,"Tap",V,A,ee,H.hasError?{errors:H.errors}:void 0),console.log(V==="PASS"?M.green(` \u2714 Tab "${A}" loaded cleanly.`):M.red(` \u2716 Tab "${A}" triggered errors.`)),this.executedStepCount<p&&this.visitedScreenHashes.size<l){let G=[],z=U*.08,K=U*.88,he=be=>be.bounds.centerY>z&&be.bounds.centerY<K&&be.clickable&&be.bounds.width>30&&be.bounds.height>20&&D.every($e=>Math.abs($e.bounds.centerX-be.bounds.centerX)>40||Math.abs($e.bounds.centerY-be.bounds.centerY)>40),ve=zt(j,{width:B,height:U}).filter(he);for(let be of ve.slice(0,3))G.push({node:be,type:"list"});let We=Me(j).filter(be=>!(!he(be)||at([be],U)));for(let be of We.slice(0,4))G.push({node:be,type:"button"});let vt=Ot(j).filter(he);for(let be of vt.slice(0,2))G.push({node:be,type:"toggle"});for(let be of G){if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l)break;let $e=be.node;if(Ve($e)){this.externalSkippedList.push($e.text||$e.contentDesc||"External Link");continue}if(Je($e,c,o)){let Nt=$e.text||$e.contentDesc||"Destructive Action";this.safetyHitList.push(Nt);continue}let rt=$e.text||$e.contentDesc||$e.resourceId||`${be.type} element`;console.log(M.gray(` Sub-crawl [${A}]: Exercising ${be.type} "${rt.slice(0,40)}"...`)),this.executedStepCount++,await this.driver.tap($e.bounds.centerX,$e.bounds.centerY,s),await new Promise(Nt=>setTimeout(Nt,1200)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let es=await this.getCleanUiHierarchy(t,s);se=es.xml,j=es.flat;let Xe=ye(j),Ir=!this.visitedScreenHashes.has(Xe);this.visitedScreenHashes.add(Xe);let hs=await this.runErrorSentinel(t,s,`Sub-${rt.slice(0,30)}`),Ei=hs.hasError?"FAIL":"PASS",Lr=await S(Ei,Ir);if(this.reporter.logStep("Tab Sub-Crawl",`Tested ${be.type} "${rt}" under tab "${A}"`,"Tap",Ei,rt,Lr,hs.hasError?{errors:hs.errors}:void 0),Xe!==N){console.log(M.cyan(` \u{1F50E} Screen transitioned. Discovered new screen state [${Xe.slice(0,8)}]`));let Nt=Me(j).filter(Ge=>he(Ge)&&!Je(Ge,c,o)&&!Ve(Ge));if(Nt.length>0&&this.executedStepCount<p){let Ge=Nt[0],Mr=Ge.text||Ge.contentDesc||"Child Action";console.log(M.gray(` Exercising child action "${Mr.slice(0,30)}"...`)),this.executedStepCount++,await this.driver.tap(Ge.bounds.centerX,Ge.bounds.centerY,s),await new Promise(Rr=>setTimeout(Rr,1e3)),await this.dismissSoftKeyboard(s)}console.log(M.gray(` Restoring ${A} master view via Back...`)),await this.driver.pressBack(s),await new Promise(Ge=>setTimeout(Ge,1e3)),await this.dismissSoftKeyboard(s);let ki=await this.getCleanUiHierarchy(t,s);se=ki.xml,j=ki.flat}}}L++}console.log(M.green("\u2714 Navigation tabs traversed successfully!"))}else console.log(M.gray("Single-screen or tabs not detected at screen footer."));for(let E of this.visitedScreenHashes)this.memory.markScreenCrawled(E);await this.memory.save();let we=this.memory.getStats();if(this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${we.crawledScreens} crawled screen(s).`,"Verify","PASS"),await this.runErrorSentinel(t,s,"Final-State"),R){console.log(M.cyan("\u{1F3AC} Finalizing exploration screen recording..."));let E=ui.resolve(process.cwd(),"output"),L=ui.join(E,`${t}-exploration.mp4`),v=await this.driver.stopScreenRecording(R,L,s);v&&An.existsSync(v)&&(this.reporter.setVideoPath?.(`${t}-exploration.mp4`),console.log(M.green(`\u2714 Screen recording saved to: output/${t}-exploration.mp4`))),R=null}let ue=await this.reporter.generateReport(),m=ue.failedSteps===0&&ue.errorsDetected.length===0;console.log(m?M.bold.green(`
|
|
890
|
+
\u2728 PromptTest Exploration Complete \u2014 All Steps Passed!`):M.bold.red(`
|
|
891
|
+
\u26A0\uFE0F PromptTest Exploration Complete \u2014 Issues Detected!`)),console.log(M.white(`Summary: ${ue.passedSteps} passed, ${ue.warnSteps} warnings, ${ue.failedSteps} failed, ${ue.errorsDetected.length} errors detected.`)),this.safetyHitList.length>0&&console.log(M.cyan(`\u{1F6E1}\uFE0F Safety Shield: Blocked ${this.safetyHitList.length} destructive action(s) [${this.safetyHitList.join(", ")}].`)),console.log(M.cyan(`\u{1F5FA}\uFE0F State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s).`)),console.log(M.cyan(`\u{1F9E0} Memory Engine Coverage: ${we.crawledScreens} crawled screen(s) indexed offline.`)),console.log(M.cyan(`Full Audit Report generated at: output/prompttest-report.md
|
|
892
|
+
`))}finally{if(R)try{await this.driver.stopScreenRecording(R,ui.join("output",`${t}-exploration.mp4`),s)}catch{}$&&kt($)}}async runErrorSentinel(e,t,s){let i=[];try{let[n,r]=await Promise.all([this.driver.checkCrashes(e,t),this.driver.getUiHierarchy(t)]);if(n){let l=`Crash in ${s}: ${n.slice(0,300)}`;console.log(M.bold.red(`\u{1F6A8} FATAL EXCEPTION DETECTED in ${e} [${s}]!`)),this.reporter.logError(l),i.push(l)}let{flat:o}=me(r),c=Hi(o);if(c.length>0)for(let l of c){let p=l.text||l.contentDesc,d=`UI Error dialog in ${s}: "${p}"`;console.log(M.bold.yellow(`\u26A0\uFE0F Error Dialog/Banner on screen [${s}]: "${p}"`)),this.reporter.logError(d),i.push(d)}}catch{}return{hasError:i.length>0,errors:i}}},hr=new yt;Ne();import hi from"fs";import gr from"path";function gi(a){return a?a.replace(/[\uE000-\uF8FF\uFFF0-\uFFFF]/gu,"").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/gu,"").replace(/^[\s,.\-_/:;|]+|[\s,.\-_/:;|]+$/g,"").replace(/\s+/g," ").trim():""}function St(a){let e="";if(a.text&&a.text.trim()&&(e=gi(a.text.replace(/["\r\n]/g," "))),!e&&a.contentDesc&&a.contentDesc.trim()&&(e=gi(a.contentDesc.replace(/["\r\n]/g," "))),!e&&a.resourceId&&a.resourceId.includes("/")){let t=a.resourceId.split("/").pop()||"";e=gi(t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\bbtn\b|\bedit\b|\btxt\b|\bview\b/gi,"").trim())}return e||"Field"}function mr(a,e){let t=[],s=e||(a[0]?.packageName?a[0].packageName:"com.example.app");t.push("# =============================================================="),t.push(`# Auto-generated test spec for ${s}`),t.push("# Generated by PromptTest Spec Scaffolder (SC-01)"),t.push(`# Created: ${new Date().toISOString()}`),t.push("# =============================================================="),t.push(""),t.push(`Launch "${s}"`),t.push("Wait 1s"),t.push("");let i=a.filter(h=>!h.clickable&&(h.text||h.contentDesc)&&h.bounds.y1<800&&h.bounds.height>20),n=new Set,r=i.map(h=>St(h)).filter(h=>!h||h==="Field"||h.length<2||n.has(h.toLowerCase())?!1:(n.add(h.toLowerCase()),!0)).slice(0,2);if(r.length>0){for(let h of r)t.push(`Assert "${h}" is visible`);t.push("")}let o=Le(a),c=new Set;for(let h of o){let g=St(h);if(!g||c.has(g.toLowerCase()))continue;c.add(g.toLowerCase());let b=g.toLowerCase();h.password||b.includes("password")||b.includes("pass")?t.push(`Type "SecretPass123!" into "${g}"`):b.includes("email")||b.includes("mail")?t.push(`Type "test.user@example.com" into "${g}"`):b.includes("phone")||b.includes("mobile")?t.push(`Type "+15551234567" into "${g}"`):b.includes("search")||b.includes("find")?t.push(`Type "Search query" into "${g}"`):t.push(`Type "Sample text" into "${g}"`)}o.length>0&&t.push("");let l=ot(a);if(l.length>0){let h=St(l[0]);h&&h!=="Field"&&(t.push(`Tap "${h}"`),t.push("Wait 500ms"),t.push(""))}let p=Me(a),d=new Set,u=[...p].sort((h,g)=>{let b=St(h).toLowerCase(),T=St(g).toLowerCase(),x=/login|sign in|submit|continue|next|search|save|confirm|done/i.test(b),S=/login|sign in|submit|continue|next|search|save|confirm|done/i.test(T);return x&&!S?-1:!x&&S?1:0});for(let h of u){let g=St(h);if(!(!g||d.has(g.toLowerCase()))&&(d.add(g.toLowerCase()),!/delete|remove|clear|logout|sign out|exit/i.test(g))){t.push(`Tap "${g}"`),t.push("Wait 1s");break}}if(r[0])t.push(`Assert "${r[0]}" is visible`);else{let h=a.map(g=>St(g)).find(g=>g&&g!=="Field"&&g.length>2&&!g.includes(s));h?t.push(`Assert "${h}" is visible`):t.push("Wait 1s")}return t.join(`
|
|
893
|
+
`)+`
|
|
894
|
+
`}function $n(a){let e=a.split(`
|
|
895
|
+
`),t=[];for(let s=0;s<e.length;s++){let i=e[s].trim();if(!i||i.startsWith("#"))continue;mt(i)||t.push(`Line ${s+1}: Unrecognized prompt syntax -> "${i}"`)}return{valid:t.length===0,errors:t}}async function fr(a={}){let e=a.driver||Pe,t=a.packageName;if(!t)try{t=await e.getForegroundPackage(a.deviceSerial)||void 0}catch{}if((!t||!t.trim())&&(t="com.example.app"),e&&typeof e.wakeDevice=="function"&&await e.wakeDevice(a.deviceSerial).catch(()=>{}),t&&t!=="com.example.app"&&typeof e.getForegroundPackage=="function")try{let h=await e.getForegroundPackage(a.deviceSerial);h&&h!==t&&!h.includes(t)&&typeof e.launchApp=="function"&&(await e.launchApp(t,a.deviceSerial),await new Promise(g=>setTimeout(g,1500)))}catch{}let s="";try{s=await e.getUiHierarchy(a.deviceSerial)}catch(h){throw new Error(`Failed to capture device UI hierarchy: ${h instanceof Error?h.message:String(h)}`)}let i=me(s),n=Array.isArray(i)?i:i.flat||i.root||[],r=n.filter(h=>h.packageName===t||!h.packageName?.includes("systemui")&&!h.packageName?.includes("launcher")),o=r.length>0?r:n,c=mr(o,t);if(a.journey){let h=Me(o),g=ot(o),b=h[0]||g[0];if(b&&b.bounds&&b.bounds.centerX&&b.bounds.centerY){let T=St(b);try{if(typeof e.tap=="function"){await e.tap(b.bounds.centerX,b.bounds.centerY,a.deviceSerial),await new Promise(R=>setTimeout(R,1500));let x=await e.getUiHierarchy(a.deviceSerial),S=me(x),y=Array.isArray(S)?S:S.flat||S.root||[],P=y.filter(R=>R.packageName===t||!R.packageName?.includes("systemui")&&!R.packageName?.includes("launcher")),$=P.length>0?P:y;if($.length>0){let C=mr($,t).split(`
|
|
896
|
+
`).filter(B=>!B.startsWith("Launch ")&&!B.startsWith("Restart "));c=["# === Screen 1: Initial Screen ===",c.trim(),"",`# === Journey Transition: Tap "${T||"Action"}" ===`,T?`Tap "${T}"`:`Tap ${b.bounds.centerX}, ${b.bounds.centerY}`,"Wait 1s","","# === Screen 2: Next Screen ===",C.join(`
|
|
897
|
+
`).trim(),""].join(`
|
|
898
|
+
`)}}}catch(x){console.warn(`Journey transition failed, falling back to single-screen scaffold: ${x.message}`)}}}let l=$n(c);l.valid||console.warn(`Scaffolding produced warnings:
|
|
899
|
+
${l.errors.join(`
|
|
900
|
+
`)}`);let p=a.outputPath;if(!p){let h=gr.resolve(process.cwd(),"specs");hi.existsSync(h)||hi.mkdirSync(h,{recursive:!0});let g=t.replace(/[^a-zA-Z0-9_.-]/g,"_");p=gr.join(h,`${g}_scaffold.txt`)}hi.writeFileSync(p,c,"utf-8");let d=Le(o),u=Me(o);return{packageName:t,specContent:c,specPath:p,stepsCount:c.split(`
|
|
901
|
+
`).filter(h=>h.trim()&&!h.trim().startsWith("#")).length,inputCount:d.length,buttonCount:u.length}}import{execFile as Ct}from"child_process";var ps=class{defaultUdid;wdaBaseUrl;isMock;defaultDimensions={width:1170,height:2532};constructor(e={}){typeof e=="string"?(this.defaultUdid=e,this.isMock=!1):(this.defaultUdid=e.udid,this.wdaBaseUrl=e.wdaBaseUrl,this.isMock=e.useMock??!1),process.platform!=="darwin"&&!this.wdaBaseUrl&&this.isMock===void 0&&(this.isMock=!0)}getDefaultDevice(){return this.defaultUdid}async ensureDefaultDevice(e){if(e)return e;if(this.defaultUdid)return this.defaultUdid;let s=(await this.getConnectedDevices()).find(n=>n.state==="simulator"||n.state==="device");if(s)return this.defaultUdid=s.serial,s.serial;let i="booted-simulator";return this.defaultUdid=i,i}async getConnectedDevices(){return this.isMock||process.platform!=="darwin"?[{serial:this.defaultUdid||"00008101-001234567890001E",state:"simulator",model:"iPhone 15 Pro (Simulator)",platform:"ios"}]:new Promise(e=>{Ct("xcrun",["simctl","list","devices","available","--json"],(t,s)=>{if(t||!s){e([{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}]);return}try{let i=JSON.parse(s),n=[],r=i.devices||{};for(let o of Object.keys(r)){let c=r[o];if(Array.isArray(c))for(let l of c)l.isAvailable&&l.state==="Booted"&&n.push({serial:l.udid,state:"simulator",model:`${l.name} (${o.split(".").pop()||"iOS"})`,platform:"ios"})}e(n.length>0?n:[{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}])}catch{e([])}})})}async getScreenDimensions(e){return this.isMock||process.platform!=="darwin"?this.defaultDimensions:this.defaultDimensions}async captureScreenshot(e){let t=await this.ensureDefaultDevice(e);return this.isMock||process.platform!=="darwin"?Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==","base64"):new Promise((s,i)=>{Ct("xcrun",["simctl","io",t,"screenshot","--type=png","-"],{encoding:"buffer",maxBuffer:10*1024*1024},(n,r)=>{if(n)return i(n);s(r)})})}async getUiHierarchy(e){let t=`<?xml version="1.0" encoding="UTF-8"?>
|
|
902
|
+
<hierarchy rotation="0">
|
|
903
|
+
<XCUIElementTypeApplication type="XCUIElementTypeApplication" name="TargetApp" label="TargetApp" enabled="true" visible="true" x="0" y="0" width="390" height="844">
|
|
904
|
+
<XCUIElementTypeWindow type="XCUIElementTypeWindow" enabled="true" visible="true" x="0" y="0" width="390" height="844">
|
|
905
|
+
<XCUIElementTypeNavigationBar type="XCUIElementTypeNavigationBar" identifier="NavBar" name="Main Title" label="Main Title" enabled="true" visible="true" x="0" y="47" width="390" height="44" />
|
|
906
|
+
<XCUIElementTypeButton type="XCUIElementTypeButton" identifier="submit_btn" name="Submit" label="Submit" enabled="true" visible="true" x="40" y="200" width="310" height="50" />
|
|
907
|
+
<XCUIElementTypeTextField type="XCUIElementTypeTextField" identifier="user_field" name="Username" label="Username" enabled="true" visible="true" x="40" y="120" width="310" height="44" />
|
|
908
|
+
</XCUIElementTypeWindow>
|
|
909
|
+
</XCUIElementTypeApplication>
|
|
910
|
+
</hierarchy>`;if(this.isMock||process.platform!=="darwin")return t;if(this.wdaBaseUrl)try{let s=await fetch(`${this.wdaBaseUrl}/source?format=xml`);if(s.ok)return await s.text()}catch{}return t}async tap(e,t,s){let i=await this.ensureDefaultDevice(s);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/tap/nil`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x:e,y:t})}).catch(()=>{});return}await new Promise(n=>{Ct("idb",["ui","tap",`${e}`,`${t}`,"--udid",i],()=>n())})}}async inputText(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:e.split("")})}).catch(()=>{});return}await new Promise(i=>{Ct("idb",["ui","type",e,"--udid",s],()=>i())})}}async pressKey(e,t){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(t),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:[e]})}).catch(()=>{}))}async swipe(e,t,s,i,n=300,r){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(r),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/dragfromtoforduration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromX:e,fromY:t,toX:s,toY:i,duration:n/1e3})}).catch(()=>{}))}async launchApp(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{Ct("xcrun",["simctl","launch",s,e],()=>i())})}async forceStop(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{Ct("xcrun",["simctl","terminate",s,e],()=>i())})}async isAppInstalled(e,t){let s=await this.ensureDefaultDevice(t);return this.isMock||process.platform!=="darwin"?!0:new Promise(i=>{Ct("xcrun",["simctl","get_app_container",s,e],n=>{i(!n)})})}async getForegroundPackage(e){return"com.apple.mobilesafari"}};var In={".html":"text/html; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".svg":"image/svg+xml",".mp4":"video/mp4",".log":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".zip":"application/zip"};async function yr(a={}){let e=a.port??4040,t=a.host||"127.0.0.1",s=process.cwd();(s==="/"||s==="\\")&&(s=br.homedir?br.homedir():process.env.HOME||process.env.USERPROFILE||"/tmp");let i=a.outputDir?X.resolve(a.outputDir):X.resolve(s,"output"),n=a.suiteName||"PromptTest Live Monitor",r=a.initialReport||{packageName:"PromptTest Execution",deviceId:"Live Device",startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:0,totalSteps:0,passedSteps:0,failedSteps:0,skippedSteps:0,warnSteps:0,errorsDetected:[],steps:[]},o=new Set,c=setInterval(()=>{for(let w of o)try{w.write(`: heartbeat
|
|
911
|
+
|
|
912
|
+
`)}catch{o.delete(w)}},15e3),l=a.driver||new nt,p=X.dirname(Nn(import.meta.url)),d=a.specsDir?X.resolve(a.specsDir):X.resolve(process.cwd(),"specs");if(!Q.existsSync(d)){let w=X.resolve(p,"../specs");Q.existsSync(w)&&(d=w)}let u=null;function h(){return u||(u=new Ke(l)),u}let g=X.join(i,"baselines"),b=new gt(g),T=null,x=null,S=["strict","moderate","interactive","disabled"],y=null,P=0;function $(w){return w?{success:!0,sessionId:w.id,status:w.status,packageName:w.packageName,deviceId:w.deviceId,safetyMode:w.safetyMode,maxDepth:w.maxDepth,maxSteps:w.maxSteps,maxScreens:w.maxScreens,screensDiscovered:w.screensDiscovered,elementsMapped:w.elementsMapped,stepsTaken:w.stepsTaken,startedAt:w.startedAt,finishedAt:w.finishedAt,crashes:w.crashes,screens:w.screens,blocked:w.blocked,events:w.events,specLines:w.specLines,error:w.error}:{success:!0,sessionId:null,status:"idle",packageName:"",safetyMode:"strict",screensDiscovered:0,elementsMapped:0,stepsTaken:0,maxDepth:0,maxSteps:0,crashes:[],screens:[],blocked:[],events:[],specLines:[]}}function R(w){let f=w.match(/"([^"]+)"/);return f?f[1]:null}function C(w){let f=w.specLines.length>0?w.specLines:["Launch the app"],O=["# Auto-generated by PromptTest Auto-Pilot (Autonomous Explorer)",`# Package: ${w.packageName}`,`# Safety Policy: ${w.safetyMode.toUpperCase()} | Max Depth: ${w.maxDepth} | Step Budget: ${w.maxSteps}`,`# Explored at: ${w.startedAt}`,`# Screens Discovered: ${w.screensDiscovered} | Steps Executed: ${w.stepsTaken}`];return w.deviceId&&O.push(`# Device: ${w.deviceId}`),[...O,"",...f,""].join(`
|
|
913
|
+
`)}function B(w,f,O){w.status=f,w.finishedAt=new Date().toISOString(),O&&(w.error=O),W("explore",{...$(w),event:{type:f==="failed"?"error":"done",description:O||f}})}function U(w){let f=y;if(f){if(typeof w.totalSteps=="number"&&(f.stepsTaken=Math.max(f.stepsTaken,w.totalSteps)),typeof w.discoveredScreens=="number"&&(f.screensDiscovered=Math.max(f.screensDiscovered,w.discoveredScreens)),w.type==="action"){let O=R(w.description);O&&f.elementLabels.add(O),w.description&&f.specLines[f.specLines.length-1]!==w.description&&f.specLines.push(w.description)}if(w.screenHash){let O=w.screenTitle||w.description||w.screenHash.slice(0,8),D=f.screens.find(we=>we.hash===w.screenHash);D?(D.visits++,typeof w.elementCount=="number"&&(D.elements=w.elementCount),D.label===D.hash.slice(0,8)&&w.screenTitle&&(D.label=w.screenTitle,D.title=w.screenTitle)):f.screens.push({id:w.screenHash,hash:w.screenHash,depth:w.depth??f.screens.length,title:O,label:O,visits:1,elements:w.elementCount??0}),f.screensDiscovered=Math.max(f.screensDiscovered,f.screens.length)}if(w.type==="crash"){let O=new Date().toISOString(),D=w.screenHash,we=D?f.screens.find(ue=>ue.hash===D):void 0;f.crashes.push({id:D||`crash-${f.crashes.length+1}`,type:w.description.toLowerCase().includes("anr")?"anr":"crash",message:w.description,screen:we?.label||D?.slice(0,8),timestamp:O,description:w.description,screenHash:D})}w.type==="safety_block"&&f.blocked.push(w.description),f.elementsMapped=f.elementLabels.size,f.events.push(w),f.events.length>300&&f.events.shift(),W("explore",{...$(f),event:w})}}function Z(w){let f=S.includes(w.safetyMode||"")?w.safetyMode:"strict";P++;let O={id:`explore-${Date.now()}-${P}`,packageName:w.packageName,deviceId:w.deviceId,safetyMode:f,maxDepth:w.maxDepth??5,maxSteps:w.maxSteps??100,maxScreens:w.maxScreens??30,status:"running",startedAt:new Date().toISOString(),screensDiscovered:0,elementsMapped:0,stepsTaken:0,screens:[],elementLabels:new Set,crashes:[],blocked:[],events:[],specLines:[],abort:{aborted:!1}};y=O;let D=new yt(l);return W("explore",{...$(O),event:{type:"state_change",description:`Auto-Pilot launched on ${O.packageName} (${O.safetyMode} mode)`}}),D.explore({packageName:O.packageName,serial:O.deviceId,strategy:"dfs",safetyMode:O.safetyMode,maxDepth:O.maxDepth,maxScreens:O.maxScreens,stepBudget:O.maxSteps,screenshots:"state-change",onStep:U,abortSignal:O.abort}).then(()=>{B(O,O.abort.aborted?"stopped":"completed")}).catch(we=>{B(O,O.abort.aborted?"stopped":"failed",we instanceof Error?we.message:String(we))}),O}function W(w,f){let O=`event: ${w}
|
|
914
|
+
data: ${JSON.stringify(f)}
|
|
915
|
+
|
|
916
|
+
`;for(let D of o)try{D.write(O)}catch{o.delete(D)}}function J(w){return new Promise((f,O)=>{let D="";w.on("data",we=>{D+=we}),w.on("end",()=>{try{f(D?JSON.parse(D):{})}catch{O(new Error("Invalid JSON payload"))}}),w.on("error",O)})}let Ee=Cn.createServer(async(w,f)=>{if(f.setHeader("Access-Control-Allow-Origin","*"),f.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),f.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),w.method==="OPTIONS"){f.writeHead(204),f.end();return}let O=new URL(w.url||"/",`http://${t}:${e}`),D=decodeURIComponent(O.pathname);if(D==="/api/devices"){try{let[m,E]=await Promise.all([l.getRawConnectedDevices().catch(()=>[]),new ps().getConnectedDevices().catch(()=>[])]),L=l.deduplicateDevices(m).map(k=>({...k,platform:"android"})),v=(E||[]).map(k=>({serial:k.serial,state:k.state,model:k.model||"iOS Device",product:"iOS",connectionType:k.state==="simulator"?"emulator":"usb",platform:"ios"})),A=[...L,...v];f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,devices:A,allEndpoints:m}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/screen-state"){try{let m=O.searchParams.get("deviceId")||void 0,E=O.searchParams.get("hierarchy")!=="false",[L,v,A]=await Promise.all([l.captureScreenshot(m),E?l.getUiHierarchy(m):Promise.resolve(null),l.getForegroundPackage(m)]),k=[];if(v){let{flat:F}=me(v);k=F.map(N=>({index:N.index,text:N.text,resourceId:N.resourceId,className:N.className,contentDesc:N.contentDesc,clickable:N.clickable,scrollable:N.scrollable,bounds:N.bounds}))}f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,deviceId:m||l.getDefaultDevice()||"default",foregroundApp:A,screenshot:`data:image/png;base64,${L.toString("base64")}`,elements:E?k:void 0,elementCount:k.length}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/tap"&&w.method==="POST"){try{let m=await J(w);if(typeof m.x!="number"||typeof m.y!="number"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing numeric coordinates: x and y"}));return}await l.tap(m.x,m.y,m.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,tapped:{x:m.x,y:m.y}}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/type"&&w.method==="POST"){try{let m=await J(w);if(typeof m.text!="string"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing text string to type"}));return}await l.inputText(m.text,m.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,typed:m.text}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/key"&&w.method==="POST"){try{let m=await J(w);if(m.keyCode===void 0){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing keyCode parameter"}));return}await l.pressKey(m.keyCode,m.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,keyCode:m.keyCode}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/wake"&&w.method==="POST"){try{let m=await J(w);await l.wakeDevice(m.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/wifi/connect"&&w.method==="POST"){try{let m=await J(w),E=await l.connectWifi(m.target,m.port||5555,m.deviceId);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:E.success,target:E.target,message:E.message}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/wifi/disconnect"&&w.method==="POST"){try{let m=await J(w),E=await l.disconnectWifi(m.target);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:E}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/wifi/pair"&&w.method==="POST"){try{let m=await J(w);if(!m.target||!m.pairingCode){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing target or pairingCode"}));return}let E=await l.pairWifi(m.target,m.pairingCode);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify(E))}catch(m){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/devices/install-apk"&&w.method==="POST"){try{let m=O.searchParams,E=m.get("deviceId")||void 0,L=m.get("targetDevices"),v=L?L.split(",").filter(Boolean):E?[E]:[],A=m.get("fileName")||`app_${Date.now()}.apk`,k=X.basename(A).endsWith(".apk")?X.basename(A):`${X.basename(A)}.apk`,F=X.join(i,"_apk_temp");Q.existsSync(F)||Q.mkdirSync(F,{recursive:!0});let N=X.join(F,`${Date.now()}_${k}`),H=Q.createWriteStream(N);await new Promise((K,he)=>{w.pipe(H),w.on("error",he),H.on("error",he),H.on("finish",K)});let V=v;if(V.length===0){let K=l.getDefaultDevice();K&&(V=[K])}if(V.length===0&&(V=(await l.getConnectedDevices()).filter(he=>he.state==="device").map(he=>he.serial)),V.length===0){try{await Q.promises.unlink(N)}catch{}f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"No active target device found to install APK"}));return}let ee=await Promise.allSettled(V.map(K=>l.installApk(N,K)));try{await Q.promises.unlink(N)}catch{}let G=ee.filter(K=>K.status==="fulfilled").length,z=[];ee.forEach((K,he)=>{if(K.status==="rejected"){let ve=K.reason instanceof Error?K.reason.message:String(K.reason);z.push(`${V[he]}: ${ve}`)}}),G>0?(W("apk-installed",{fileName:k,installedCount:G,targets:V}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:`Successfully installed "${k}" on ${G} device(s)${z.length>0?` (Failed: ${z.join(", ")})`:""}`,installedCount:G}))):(f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Failed to install APK: ${z.join("; ")}`})))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/metrics"&&w.method==="GET"){try{let m=O.searchParams.get("deviceId")||void 0,E=await l.getDeviceMetrics(m);if(Object.keys(E).length===0)throw new Error(`No metrics available for device ${m||"default"}. Confirm the device is connected and authorized.`);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,metrics:E}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/doctor"&&w.method==="GET"){try{let m=O.searchParams.get("deviceId")||void 0,E=O.searchParams.get("packageName")||void 0,L=await ls(l,{serial:m,packageName:E});f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,report:L}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if((D==="/api/explore/start"||D==="/api/explore")&&w.method==="POST"){try{let m=await J(w),E=(m.packageName||m.targetPackage||"").trim();if(!E){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing packageName (packageName or targetPackage)"}));return}if(y&&y.status==="running"){f.writeHead(409,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"An Auto-Pilot exploration session is already active",sessionId:y.id}));return}let L=Z({packageName:E,deviceId:m.deviceId||m.serial,safetyMode:m.safetyMode||m.safety,maxDepth:m.maxDepth??m.depth,maxSteps:m.maxSteps??m.stepBudget,maxScreens:m.maxScreens});f.writeHead(202,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,sessionId:L.id,status:L.status,packageName:L.packageName}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if((D==="/api/explore/status"||D==="/api/explore")&&w.method==="GET"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify($(y)));return}if((D==="/api/explore/stop"||D==="/api/explore")&&(w.method==="POST"||w.method==="DELETE")){if(!y){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"No active Auto-Pilot session to stop"}));return}y.abort.aborted=!0,f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,sessionId:y.id,status:"stopping",packageName:y.packageName}));return}if(D==="/api/explore/export"&&w.method==="POST"){try{let m=await J(w);if(!y){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"No exploration session available to export"}));return}let E=(m.specName||`explored_${y.packageName}.txt`).trim(),L=X.basename(E).replace(/[^a-zA-Z0-9._-]/g,"_"),v=L.endsWith(".txt")?L:`${L}.txt`,A=C(y);await Q.promises.mkdir(d,{recursive:!0}),await Q.promises.writeFile(X.join(d,v),A,"utf8"),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specName:v,content:A,screensDiscovered:y.screensDiscovered,stepsTaken:y.stepsTaken}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/record/start"&&w.method==="POST"){try{let m=await J(w);if(T){f.writeHead(409,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"A recording session is already active"}));return}let E=m.deviceId||l.getDefaultDevice()||void 0,L=m.specName?X.join(d,X.basename(m.specName)):void 0;T=new ft(l),x=E||"default",T.onStep=v=>{W("record-step",{step:v,deviceId:E})},await T.startSession(L,E,{append:m.append}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"Recording session started",deviceId:E}))}catch(m){if(T)try{await T.stopSession()}catch{}T=null,x=null,f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/record/stop"&&w.method==="POST"){try{if(!T){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"No active recording session",steps:[]}));return}let m=await T.stopSession();T=null,x=null,f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,steps:m.steps,specPath:m.specPath,reportPath:m.reportPath}))}catch(m){T=null,x=null,f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/record/status"&&w.method==="GET"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,isRecording:T!==null,deviceId:x}));return}if(D==="/api/specs"&&w.method==="GET"){try{Q.existsSync(d)||Q.mkdirSync(d,{recursive:!0});let E=Q.readdirSync(d).filter(L=>L.endsWith(".txt")||L.endsWith(".spec")).map(L=>{let v=X.join(d,L),A=Q.statSync(v);return{name:L,path:X.relative(process.cwd(),v).replace(/\\/g,"/"),size:A.size,modified:A.mtime.toISOString()}});f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specs:E}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if((D.startsWith("/api/specs/")||D==="/api/spec")&&w.method==="GET"){try{let m="";D.startsWith("/api/specs/")?m=decodeURIComponent(D.slice(11)):m=O.searchParams.get("name")||"";let E=X.basename(m.trim());if(!E){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing spec file name"}));return}let L=X.join(d,E);if(!Q.existsSync(L)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Spec file not found: ${E}`}));return}let v=Q.readFileSync(L,"utf-8");f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,name:E,content:v}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if((D==="/api/specs"||D==="/api/spec")&&w.method==="POST"){try{let m=await J(w),E=(m.name||"").trim();if(!E){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing spec file name"}));return}!E.endsWith(".txt")&&!E.endsWith(".spec")&&(E+=".txt");let L=X.basename(E);Q.existsSync(d)||Q.mkdirSync(d,{recursive:!0});let v=X.join(d,L);Q.writeFileSync(v,m.content??"","utf-8"),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,name:L,path:v}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/specs/apply-heals"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||!Array.isArray(m.heals)||m.heals.length===0){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or heals array"}));return}let E=X.basename(m.specName),L=X.join(d,E);if(!Q.existsSync(L)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Spec file not found: ${E}`}));return}let v=Q.readFileSync(L,"utf-8"),A=0;for(let k of m.heals){if(!k.original||!k.healed||k.original===k.healed)continue;let F=k.original.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N=new RegExp(`"${F}"`,"g"),H=new RegExp(`'${F}'`,"g");(N.test(v)||H.test(v))&&(v=v.replace(N,`"${k.healed}"`),v=v.replace(H,`'${k.healed}'`),A++)}Q.writeFileSync(L,v,"utf-8"),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specName:E,replacementsCount:A,content:v}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/logcat"&&w.method==="GET"){try{let m=(O.searchParams.get("deviceId")||l.getDefaultDevice())??void 0,E=parseInt(O.searchParams.get("lines")||"200",10),L=isNaN(E)?200:Math.min(Math.max(E,20),1e3),v=O.searchParams.get("filter")?.trim(),k=(await l.getLogcatTail(L,m)).split(`
|
|
917
|
+
`).filter(F=>F.trim().length>0);if(v){let F=v.toLowerCase();k=k.filter(N=>N.toLowerCase().includes(F))}f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,count:k.length,logs:k}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/logcat/clear"&&w.method==="POST"){try{let m=(O.searchParams.get("deviceId")||l.getDefaultDevice())??void 0;await l.execAdb(["logcat","-c"],m).catch(()=>{}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/scaffold"&&w.method==="POST"){try{let m=await J(w),E=m.deviceId||l.getDefaultDevice()||void 0,L=m.packageName?.trim()||void 0,v=(m.specName||"").trim();v||(v=L?`scaffold_${L}.txt`:"scaffold_app.txt"),!v.endsWith(".txt")&&!v.endsWith(".spec")&&(v+=".txt");let A=X.basename(v).replace(/[^a-zA-Z0-9._-]/g,"_"),k=X.join(d,A),F=await fr({driver:l,deviceSerial:E,packageName:L,outputPath:k,journey:m.journey});f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specName:A,content:F.specContent,packageName:F.packageName,inputCount:F.inputCount,buttonCount:F.buttonCount,stepsCount:F.stepsCount}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/expand"&&w.method==="POST"){try{let m=await J(w);if(!m.spec||typeof m.spec!="string"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:'Missing "spec" string to expand'}));return}let E=h(),{expanded:L,stepsAdded:v}=await E.expandSpec(m.spec);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,expanded:L,stepsAdded:v}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/action"&&w.method==="POST"){try{let m=await J(w);if(!m.step||typeof m.step!="string"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing natural language step string"}));return}let E=mt(m.step);if(E.length===0){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Could not parse step: "${m.step}"`}));return}let L=h(),v=E[0],A=m.deviceId||l.getDefaultDevice()||void 0,k=Date.now(),F=await L.executeStep(v,A),N=Date.now()-k;W("step",{stepNumber:r.steps.length+1,instruction:v.originalText,status:"PASS",durationMs:N}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,step:v.originalText,type:v.type,durationMs:N,result:F||null}))}catch(m){let E=m instanceof Error?m.message:String(m);W("step",{stepNumber:r.steps.length+1,instruction:"Step Execution",status:"FAIL",durationMs:0,error:E}),f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:E}))}return}if(D==="/api/run"&&w.method==="POST"){try{let m=await J(w),E="";if(m.specName){let k=X.basename(m.specName);if(E=X.join(d,k),m.spec&&typeof m.spec=="string"&&m.spec.trim().length>0)Q.writeFileSync(E,m.spec,"utf-8");else if(!Q.existsSync(E)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Spec file not found: ${k}`}));return}}else if(m.spec&&typeof m.spec=="string")Q.existsSync(i)||Q.mkdirSync(i,{recursive:!0}),E=X.join(i,"_studio_temp_spec.txt"),Q.writeFileSync(E,m.spec,"utf-8");else{f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:'Either "spec" string or "specName" must be provided'}));return}let L=m.dataFile;if(m.dataFileContent&&typeof m.dataFileContent=="string"){Q.existsSync(i)||Q.mkdirSync(i,{recursive:!0});let k=m.dataFile?X.basename(m.dataFile):"_studio_data.csv";L=X.join(i,k),Q.writeFileSync(L,m.dataFileContent,"utf-8")}let v=m.deviceId||l.getDefaultDevice()||void 0,A=h();r.steps=[],r.totalSteps=0,r.passedSteps=0,r.failedSteps=0,r.warnSteps=0,r.skippedSteps=0,(async()=>{let k;try{let N=await l.getForegroundPackage(v);N&&!N.includes("Launcher")&&!N.includes("Foreground")&&(k=N)}catch{}let F=async(N,H)=>{let V=H?dt:new lt(i),ee=H?A:new Ke(l,void 0,V),G=V.onStep?.(z=>{let K=!!(z.details?.healed||z.details?.healedFrom||z.description?.toLowerCase().includes("healed")),he=z.details;W("step",{deviceId:N,stepNumber:z.stepIndex,instruction:z.description,status:z.status,durationMs:z.durationMs||0,error:z.details?.error,healed:K,healedFrom:he?.healedFrom,healedTo:he?.healedTo})});try{let z=await ee.runSpec(E,{serial:N,packageName:k,saveBaseline:H&&m.saveBaseline!==void 0?m.saveBaseline:!1,compareBaseline:H&&m.compareBaseline!==void 0?m.compareBaseline:!0,screenshotMode:H?"all":"on-failure",heal:m.heal??!1,fresh:m.fresh??!1,continueOnError:m.continueOnError??!1,tags:m.tags,only:m.only,dataFile:L,iterations:m.iterations,profile:m.profile??!1});return W("device-complete",{deviceId:N,report:z}),z}finally{G&&G()}};try{let N=Array.isArray(m.targetDevices)&&m.targetDevices.length>0;if(N||m.allDevices){let H=[];N?H=m.targetDevices:H=(await l.getConnectedDevices()).filter(z=>z.state==="device").map(z=>z.serial),H=Array.from(new Set(H.filter(Boolean))),v&&H.includes(v)?H=[v,...H.filter(G=>G!==v)]:H.length===0&&v&&H.push(v);let V=await Promise.allSettled(H.map((G,z)=>F(G,z===0))),ee=[];for(let G of V)G.status==="fulfilled"&&ee.push(G.value);ee.length>0&&(r=ee[0]),W("complete",{multiDevice:!0,reports:ee,currentReport:r})}else{let H=await F(v||"default",!0);r=H,W("complete",H)}}catch(N){let H=N instanceof Error?N.message:String(N);r.errorsDetected.push(H),W("error",{error:H}),W("complete",r)}})(),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"Execution started"}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/reports"&&w.method==="GET"){try{if(!Q.existsSync(i)){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,reports:[]}));return}let L=Q.readdirSync(i).filter(v=>v.endsWith("-results.json")).map(v=>{let A=v.replace(/-results\.json$/,""),k=X.join(i,v),F=`${A}-report.html`,N=Q.existsSync(X.join(i,F)),H=Q.statSync(k);try{let V=JSON.parse(Q.readFileSync(k,"utf-8")),ee=V.totalSteps||V.steps?.length||0,G=V.passedSteps||0,z=V.failedSteps||0,K=ee>0?Math.round(G/ee*100):100;return{id:A,fileName:v,suiteName:V.packageName||A,packageName:V.packageName||"Unknown",deviceId:V.deviceId||"Unknown",startTime:V.startTime||H.mtime.toISOString(),endTime:V.endTime||H.mtime.toISOString(),durationSeconds:V.durationSeconds||0,totalSteps:ee,passedSteps:G,failedSteps:z,warnSteps:V.warnSteps||0,skippedSteps:V.skippedSteps||0,passRate:K,errorsCount:V.errorsDetected?.length||0,htmlReportPath:N?`/${F}`:null,jsonReportPath:`/${v}`}}catch{return null}}).filter(Boolean).sort((v,A)=>new Date(A.startTime).getTime()-new Date(v.startTime).getTime());f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,reports:L}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if((D.startsWith("/api/reports/")||D==="/api/report-detail")&&w.method==="GET"){try{let m="";D.startsWith("/api/reports/")?m=decodeURIComponent(D.slice(13)):m=O.searchParams.get("id")||"";let E=X.basename(m.trim()),L=E.endsWith("-results.json")?E:`${E}-results.json`,v=X.join(i,L);if(!Q.existsSync(v)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Report not found: ${E}`}));return}let A=JSON.parse(Q.readFileSync(v,"utf-8"));f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,id:E,report:A}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines"&&w.method==="GET"){try{Q.existsSync(g)||Q.mkdirSync(g,{recursive:!0});let m=O.searchParams.get("spec")||"",E=m.replace(/[^a-zA-Z0-9._-]/g,"_"),L=Q.readdirSync(g),v=new Map;for(let k of L){if(E&&!k.startsWith(`${E}_step`))continue;let F=k.match(/_step(\d+)(_current|_diff)?\.png$/);if(!F)continue;let N=parseInt(F[1],10),H=F[2];v.has(N)||v.set(N,{});let V=v.get(N);H?H==="_current"?V.current=`/baselines/${k}`:H==="_diff"&&(V.diff=`/baselines/${k}`):V.baseline=`/baselines/${k}`}let A=await Promise.all(Array.from(v.entries()).map(async([k,F])=>{let N=await b.getMasks(m,k);return{stepIndex:k,...F,masks:N}}));A.sort((k,F)=>k.stepIndex-F.stepIndex),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,spec:m,baselines:A,matchingModes:Cs}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/compare"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||typeof m.stepIndex!="number"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or stepIndex"}));return}let E;if(m.screenshot){let A=m.screenshot.replace(/^data:image\/\w+;base64,/,"");E=Buffer.from(A,"base64")}else{let A=m.deviceId||l.getDefaultDevice()||void 0;E=await l.captureScreenshot(A)}let L=await b.compare(m.specName,m.stepIndex,E,{threshold:m.threshold,mode:m.mode,maskRegions:m.maskRegions}),v=await b.getMasks(m.specName,m.stepIndex);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,result:{...L,masks:v,baselineUrl:`/baselines/${X.basename(L.baselineFile)}`,currentUrl:`/baselines/${X.basename(L.currentFile)}`,diffUrl:L.diffImagePath?`/baselines/${X.basename(L.diffImagePath)}`:null}}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/approve"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||typeof m.stepIndex!="number"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or stepIndex"}));return}let E;if(m.screenshot){let v=m.screenshot.replace(/^data:image\/\w+;base64,/,"");E=Buffer.from(v,"base64")}else{let v=m.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),A=X.join(g,`${v}_step${String(m.stepIndex).padStart(3,"0")}_current.png`);if(!Q.existsSync(A)){let k=m.deviceId||l.getDefaultDevice()||void 0;try{E=await l.captureScreenshot(k)}catch{}}}let L=await b.approveBaseline(m.specName,m.stepIndex,E);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,approved:!0,stepIndex:m.stepIndex,baselineUrl:`/baselines/${X.basename(L)}`}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/clear"&&w.method==="POST"){try{let m=await J(w);if(!m.specName){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName"}));return}await b.clearBaselines(m.specName),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,cleared:!0,specName:m.specName}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/delete-step"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||typeof m.stepIndex!="number"){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or stepIndex"}));return}await b.deleteStepBaseline(m.specName,m.stepIndex),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,deleted:!0,specName:m.specName,stepIndex:m.stepIndex}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/upload"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||typeof m.stepIndex!="number"||!m.image){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName, stepIndex, or image data"}));return}let E=m.image.replace(/^data:image\/\w+;base64,/,""),L=Buffer.from(E,"base64"),v=await b.saveBaseline(m.specName,m.stepIndex,L),A=m.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),k=X.join(g,`${A}_step${String(m.stepIndex).padStart(3,"0")}_diff.png`);if(Q.existsSync(k))try{await Q.promises.unlink(k)}catch{}let F=X.join(g,`${A}_step${String(m.stepIndex).padStart(3,"0")}_current.png`),N,H;if(Q.existsSync(F)){let ee=await Q.promises.readFile(F),G=await b.compare(m.specName,m.stepIndex,ee);N=`/baselines/${X.basename(F)}`,H=G.diffImagePath?`/baselines/${X.basename(G.diffImagePath)}`:void 0}else if(m.deviceId||l.getDefaultDevice()){let ee=m.deviceId||l.getDefaultDevice()||void 0;try{let G=await l.captureScreenshot(ee),z=await b.compare(m.specName,m.stepIndex,G);N=`/baselines/${X.basename(F)}`,H=z.diffImagePath?`/baselines/${X.basename(z.diffImagePath)}`:void 0}catch{}}let V=await b.getMasks(m.specName,m.stepIndex);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,uploaded:!0,stepIndex:m.stepIndex,baselineUrl:`/baselines/${X.basename(v)}`,currentUrl:N,diffUrl:H,masks:V}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/masks"&&w.method==="GET"){try{let m=O.searchParams.get("specName")||O.searchParams.get("spec")||"",E=parseInt(O.searchParams.get("stepIndex")||"",10);if(!m||isNaN(E)){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or valid stepIndex"}));return}let L=await b.getMasks(m,E);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,masks:L}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/api/baselines/masks"&&w.method==="POST"){try{let m=await J(w);if(!m.specName||typeof m.stepIndex!="number"||!Array.isArray(m.masks)){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName, stepIndex, or masks array"}));return}await b.saveMasks(m.specName,m.stepIndex,m.masks);let E=m.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),L=X.join(g,`${E}_step${String(m.stepIndex).padStart(3,"0")}_current.png`),v,A,k=0,F=0,N=!0;if(Q.existsSync(L)){let H=await Q.promises.readFile(L),V=await b.compare(m.specName,m.stepIndex,H,{mode:m.mode,threshold:m.threshold,maskRegions:m.masks});v=`/baselines/${X.basename(L)}`,A=V.diffImagePath?`/baselines/${X.basename(V.diffImagePath)}`:void 0,k=V.diffRatio,F=V.diffPixels,N=V.passed}f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,masks:m.masks,currentUrl:v,diffUrl:A,diffRatio:k,diffPixels:F,passed:N}))}catch(m){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:m instanceof Error?m.message:String(m)}))}return}if(D==="/events"){f.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),f.write(`event: connected
|
|
918
|
+
data: ${JSON.stringify({status:"connected",time:Date.now()})}
|
|
919
|
+
|
|
920
|
+
`),o.add(f),w.on("close",()=>{o.delete(f)});return}if(D==="/"||D==="/report"||D==="/index.html"){let m=Es(r,{suiteName:n});f.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}),f.end(m);return}if(D==="/api/report"||D==="/results.json"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),f.end(JSON.stringify(r,null,2));return}let we=D.replace(/^\/+/,""),ue=X.join(i,we);if(!ue.startsWith(i)){f.writeHead(403,{"Content-Type":"text/plain"}),f.end("Access Denied");return}if(Q.existsSync(ue)&&Q.statSync(ue).isFile()){let m=X.extname(ue).toLowerCase(),E=In[m]||"application/octet-stream";f.writeHead(200,{"Content-Type":E,"Cache-Control":"no-cache"}),Q.createReadStream(ue).pipe(f);return}f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not Found")});await new Promise((w,f)=>{Ee.once("error",f),Ee.listen(e,t,()=>{w()})});let se=Ee.address(),j=typeof se=="object"&&se?se.port:e,re=`http://${t}:${j}`;return{server:Ee,port:j,url:re,broadcastStep(w){r.steps.push(w),r.totalSteps=r.steps.length,w.status==="PASS"?r.passedSteps++:w.status==="FAIL"?r.failedSteps++:w.status==="WARN"?r.warnSteps++:w.status==="SKIPPED"&&r.skippedSteps++,W("step",w)},broadcastComplete(w){r=w,W("complete",w)},broadcastError(w){r.errorsDetected.push(w),W("error",{error:w})},updateReport(w){r=w},async close(){if(clearInterval(c),T){try{await T.stopSession()}catch{}T=null,x=null}y&&y.status==="running"&&(y.abort.aborted=!0);for(let w of o)try{w.end()}catch{}o.clear(),await new Promise((w,f)=>{Ee.close(O=>{O?f(O):w()})})}}}import Ln from"chalk";var mi=null;async function Sr(a,e){if(mi)return mi;let t=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.TRAVIS||process.env.CIRCLECI||process.env.GITLAB_CI),s=!1;try{let{stdout:l}=await a.execAdb(["shell","getprop","ro.kernel.qemu"],e),{stdout:p}=await a.execAdb(["shell","getprop","ro.product.model"],e),{stdout:d}=await a.execAdb(["shell","getprop","ro.build.characteristics"],e),u=(p||"").toLowerCase(),h=(d||"").toLowerCase();s=l?.trim()==="1"||u.includes("sdk")||u.includes("emulator")||h.includes("emulator")}catch{s=!1}let i=1;t?i=s?2.8:2:s?i=1.5:i=1;let n=parseFloat(process.env.PROMPTTEST_SETTLE_FACTOR||"");!isNaN(n)&&n>0&&(i=Math.max(.5,n));let r={isEmulator:s,isCI:t,velocityMultiplier:i,defaultTimeoutMs:Math.round(3500*i),extendedTimeoutMs:Math.round(6500*i),quiescenceSettleMs:Math.round(150*Math.min(i,2)),initialPollMs:t?150:80,maxPollIntervalMs:t?600:350};mi=r;let o=s?"Android Emulator":"Physical Android Device",c=t?"CI / Cloud Runner":"Local Environment";return console.log(Ln.cyan(`\u26A1 [Device Profiler] Detected ${o} in ${c} (Velocity Multiplier: ${i.toFixed(1)}x, Dynamic Timeout: ${r.defaultTimeoutMs}ms)`)),r}var Ke=class{driver;memory;reporter;checkpoints;baselines;lastHierarchy=null;screenDimensions={width:I.screen.fallbackWidth,height:I.screen.fallbackHeight};navBarHeight=0;targetPackage=void 0;constructor(e,t,s,i,n,r){this.driver=e||Pe,this.memory=t||_t,this.reporter=s||dt,this.checkpoints=i||Ki,this.baselines=n||Ns,this.semanticResolver=r||li()}semanticResolver;healEnabled=!1;activeLocale="en";runtimeVariables=new Map;loopStack=[];expandSpecIncludes(e,t=new Set){return Rs(e,t)}async expandSpec(e,t){let s=t||this.semanticResolver,i=e.split(`
|
|
921
|
+
`),n=[],r=0;for(let o of i){let c=o.trim();if(!c||c.startsWith("#")||c.startsWith("//")){n.push(o);continue}let l=this.parsePrompt(c);if(l.length>0&&l[0].type!==void 0&&!c.toLowerCase().startsWith("intent:")){n.push(o);continue}let d=c.replace(/^intent:\s*/i,""),u=this.memory?.getIntentExpansion(d);if(u?.length){n.push(`# [Cached Intent] ${c}`,...u),r+=u.length;continue}let h=await s.resolveIntent(d);if(h?.length){n.push(`# [AI Expanded] ${c}`);let g=h.map(b=>b.originalText);n.push(...g),this.memory&&(this.memory.recordIntentExpansion(d,g),await this.memory.save().catch(()=>{})),r+=h.length}else n.push(o)}return{expanded:n.join(`
|
|
922
|
+
`),stepsAdded:r}}parsePrompt(e,t){return mt(e,t)}async runSpec(e,t,s){if(!us.existsSync(e))throw new Error(`Spec file not found: ${e}`);let i=typeof t=="string"?{packageName:t,serial:s,screenshotMode:"on-failure",continueOnError:!1}:{screenshotMode:"on-failure",continueOnError:!1,...t};i.heal!==void 0&&(this.healEnabled=i.heal),i.noAi&&(this.semanticResolver=li({provider:"heuristic"})),this.activeLocale=(i.locale||I.locale||"en").toLowerCase(),typeof this.memory.setLocale=="function"&&this.memory.setLocale(this.activeLocale);let n=this.expandSpecIncludes(e),r=n,o=[],c=Ut.extractDataDirective(n,it.dirname(e));if(c)r=c.cleanedSpec,o=c.rows;else if(i.dataFile){let S=it.isAbsolute(i.dataFile)?i.dataFile:it.resolve(process.cwd(),i.dataFile);o=Ut.loadFromFile(S)}(i.onlyRow!==void 0||i.iterations!==void 0)&&(o.length>0?o=Ut.filterRows(o,{onlyRow:i.onlyRow,iterations:i.iterations}):i.iterations&&i.iterations>0&&(o=Array.from({length:i.iterations},()=>({}))));let l=o.length>0?o.map(S=>({...i.variables||{},...S})):[i.variables||{}],p=it.basename(e,it.extname(e)),d=r.match(/#\s*(?:Target\s*)?Package:\s*([a-zA-Z0-9._-]+)/i),u=d?d[1]:void 0;if(i.tags){let S=er(n),y=i.tags.split(",").map($=>$.trim().toLowerCase()).filter(Boolean);if(!y.some($=>S.includes($)))return console.log(q.yellow(`
|
|
923
|
+
\u23E9 Skipping ${e}: tags [${S.join(", ")}] do not match filter [${y.join(", ")}]`)),ns(u||i.packageName||"",i.serial||"",[],"SKIPPED")}if(i.listSteps){let S=this.parsePrompt(r,l[0]);return console.log(tr(S)),ns(u||i.packageName||"",i.serial||"",S,"SKIPPED","Listing")}if(i.dryRun){let S=this.parsePrompt(r,l[0]);return console.log(q.bold.cyan(`
|
|
924
|
+
\u{1F50D} [Dry Run] Validated ${S.length} test step(s) in ${e} successfully (no device interaction).`)),ns(u||i.packageName||"",i.serial||"",S,"PASS","Validation")}if(l.length>1)console.log(q.cyan(`
|
|
925
|
+
\u{1F4CB} Loaded spec with ${l.length} data iteration(s) from ${e}`));else{let S=this.parsePrompt(r,l[0]);console.log(q.cyan(`
|
|
926
|
+
\u{1F4CB} Loaded ${S.length} test step(s) from ${e}`))}console.log(q.gray("Execution Policy: ")+q.bold.white(i.continueOnError?"Continue on Error (Modular Run)":"Fail-Fast (Default)")+q.gray(" | Screenshots: ")+q.bold.white(i.screenshotMode==="all"?"All Steps":"Failure-Only")),i.serial=await this.driver.ensureDefaultDevice(i.serial);let h=i.serial||this.driver.getDefaultDevice()||"Default Device",g=null;i.serial&&(g=Et(i.serial)),i.embedScreenshots&&typeof this.reporter.setEmbedScreenshots=="function"&&this.reporter.setEmbedScreenshots(!0);let b,T;if(i.serve){let S=typeof i.serve=="number"?i.serve:4040;try{b=await yr({port:S,suiteName:p}),console.log(q.bold.magenta(`
|
|
927
|
+
\u{1F4E1} Live Monitor streaming at: ${b.url}
|
|
928
|
+
`)),typeof this.reporter.onStep=="function"&&(T=this.reporter.onStep(y=>{b?.broadcastStep(y)}))}catch(y){let P=y;console.warn(q.yellow(`Warning: Could not start live server: ${P.message}`))}}let x=null;i.video&&(console.log(q.cyan("\u{1F3AC} Starting ADB screen recording (--video enabled)...")),x=await this.driver.startScreenRecording("/sdcard/prompttest_temp.mp4",i.serial));try{this.screenDimensions=await this.driver.getScreenDimensions(i.serial),this.navBarHeight=typeof this.driver.getNavigationBarHeight=="function"?await this.driver.getNavigationBarHeight(i.serial):0,console.log(q.gray("Target Screen Geometry: ")+q.bold.cyan(`${this.screenDimensions.width}x${this.screenDimensions.height}`)+(this.navBarHeight>0?q.gray(` (Nav Bar: ${this.navBarHeight}px)`):"")),i.apkPath&&(us.existsSync(i.apkPath)?(console.log(q.cyan(`\u{1F4E6} Installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(Z=>setTimeout(Z,2e3))):console.log(q.yellow(`Warning: Specified APK file not found at: ${i.apkPath}`)));let S=i.packageName||u||(typeof this.driver.getForegroundPackage=="function"?await this.driver.getForegroundPackage(i.serial):null)||"Foreground App";if(S&&!S.includes("Launcher")&&!S.includes("Foreground")){if(!(typeof this.driver.isAppInstalled=="function"?await this.driver.isAppInstalled(S,i.serial):!0))if(i.apkPath&&us.existsSync(i.apkPath))console.log(q.cyan(`\u{1F4E6} Target app not found. Auto-installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(J=>setTimeout(J,2500));else throw new Error(`Target application "${S}" is not installed on device (${h}).
|
|
929
|
+
\u{1F4A1} Suggestions:
|
|
930
|
+
\u2022 Install the app manually or via: adb install <path-to-apk>
|
|
931
|
+
\u2022 Or provide an APK path to auto-install before running: --apk=path/to/app.apk`);let W=await this.driver.getForegroundPackage(i.serial);(i.fresh||W&&W!==S)&&(console.log(q.cyan(`\u{1F680} Launching target application: ${q.bold(S)}...`)),i.fresh&&(await this.driver.forceStop(S,i.serial),await new Promise(J=>setTimeout(J,600))),await this.driver.launchApp(S,i.serial),await new Promise(J=>setTimeout(J,2500)))}i.reporter&&(this.reporter=i.reporter),i.reporters&&typeof this.reporter.setFormats=="function"&&this.reporter.setFormats(i.reporters),i.serial&&await Sr(this.driver,i.serial).catch(()=>{}),this.targetPackage=S&&!S.includes("Foreground")&&!S.includes("Launcher")?S:void 0,this.reporter.init(S,h),await this.memory.init(S);let y=null;if(i.profile&&this.targetPackage){let{PerformanceProfiler:Z}=await Promise.resolve().then(()=>(Tr(),xr));y=new Z(this.driver,i.serial),await y.start(this.targetPackage)}this.lastHierarchy=null;let P=Date.now(),$=0;for(let Z=0;Z<l.length;Z++){let W=l[Z],J=l.length>1,Ee=i.onlyRow?`Row ${i.onlyRow}`:J?`Row ${Z+1}`:void 0,se=Ee?`${p} [${Ee}]`:p;J&&(console.log(q.bold.magenta(`
|
|
932
|
+
======================================================
|
|
933
|
+
\u{1F504} [Data-Driven Iteration ${Z+1}/${l.length}] Row Data: ${JSON.stringify(W)}
|
|
934
|
+
======================================================`)),i.fresh&&Z>0&&S&&(await this.driver.clearAppData(S,i.serial),await new Promise(O=>setTimeout(O,1e3)))),this.runtimeVariables.clear();for(let[O,D]of Object.entries(W))this.runtimeVariables.set(O,D);this.loopStack=[];let j=this.parsePrompt(r,W),re=1,w=i.resume&&Z===0?await this.checkpoints.getResumeIndex(p):0;w>0&&console.log(q.cyan(`\u23ED Resuming from step ${w+1} (checkpoint found).`));let f=i.only?qi(i.only):null;for(let O=0;O<j.length;O++){let D=j[O];if(re=O+1,f&&!f.has(re)){console.log(q.gray(`[Step ${re}/${j.length}] \u23E9 Skipped (not in --only range: ${i.only})`)),this.reporter.logStep(se,D.originalText,D.type,"SKIPPED",`Filtered out by --only="${i.only}"`,void 0,{videoOffsetMs:Math.max(0,Date.now()-P)},0);continue}if(O<w){this.reporter.logStep(se,D.originalText,D.type,"SKIPPED","Resumed \u2014 already passed",void 0,{videoOffsetMs:0},0);continue}let we=j.slice(O+1);console.log(q.bold.blue(`
|
|
935
|
+
[Step ${re}/${j.length}] ${D.originalText}`));let ue=Date.now();try{let m=await this.executeStep(D,i.serial,we),E=Date.now()-ue;if(m&&m.fastForwarded){if(console.log(q.cyan(`\u23E9 Fast-Forward: ${m.reason}. Redundant step(s) bypassed.`)),this.reporter.logStep(se,D.originalText,D.type,"PASS",`Fast-Forward: ${m.reason}`,void 0,{videoOffsetMs:Math.max(0,ue-P)},E),console.log(q.green(`\u2714 Step ${re} PASSED (Fast-Forward)`)),m?.skipCount&&m.skipCount>0){let L=m.skipCount;for(let v=0;v<L&&O+1<j.length;v++){O++;let A=j[O],k=O+1;this.reporter.logStep(se,A.originalText,A.type,"PASS",`Fast-Forward: ${m.reason}`,void 0,{videoOffsetMs:Math.max(0,ue-P)},0),console.log(q.gray(` [Step ${k}/${j.length}] \u23E9 Fast-Forward: ${A.originalText}`))}}}else{let L;if((i.screenshotMode==="all"||i.saveBaseline||i.compareBaseline)&&(L=await this.driver.captureScreenshot(i.serial)),L&&i.compareBaseline){let A=await this.baselines.compare(se,re,L,i.baselineThreshold);A.passed||(console.log(q.yellow(` \u26A0\uFE0F [Baseline] Step ${re} visual diff ${(A.diffRatio*100).toFixed(1)}% exceeds threshold ${(A.threshold*100).toFixed(1)}%`)),this.reporter.logError(`Visual baseline diff at Step ${re}: ${(A.diffRatio*100).toFixed(1)}% changed`))}L&&i.saveBaseline&&!i.compareBaseline&&await this.baselines.saveBaseline(se,re,L);let v={videoOffsetMs:Math.max(0,ue-P)};D.healedFrom&&(v.healed=!0,v.healedFrom=D.healedFrom,v.healedTo=D.healedTo||D.target),this.reporter.logStep(se,D.originalText,D.type,"PASS",D.target||D.value,i.screenshotMode==="all"?L:void 0,v,E),console.log(q.green(`\u2714 Step ${re} PASSED`)),i.benchmark&&console.log(q.gray(` \u23F1 [Benchmark] Step ${re} latency: ${E}ms (${D.type}${D.target?` -> "${D.target}"`:""})`))}i.resume&&!J&&await this.checkpoints.save(p,S,O,j.length)}catch(m){let E=m,L=Date.now()-ue;if(D.optional){console.log(q.yellow(`\u26AA Step ${re} OPTIONAL (Skipped: ${E.message})`)),this.reporter.logStep(se,D.originalText,D.type,"SKIPPED",`Optional step bypassed: ${E.message}`,void 0,{error:E.message,videoOffsetMs:Math.max(0,ue-P)},L);continue}$++,console.log(q.red(`\u274C Step ${re} FAILED: ${E.message}`)),D.target&&this.memory.recordFailure(D.type,D.target);let v=await this.driver.captureScreenshot(i.serial).catch(()=>{}),A=await sr({outputDir:it.resolve(process.cwd(),"output"),specName:p,currentSpecName:se,stepNum:re,step:D,error:E,stepStartTime:ue,startTime:P,errorShot:v,lastHierarchy:this.lastHierarchy,driver:this.driver,serial:i.serial});if(this.reporter.logStep(se,D.originalText,D.type,"FAIL",E.message,v,{error:E.message,videoOffsetMs:Math.max(0,ue-P)},L,A),this.reporter.logError(`Step ${re} failed: ${E.message}`),i.continueOnError)console.log(q.yellow("Continuing with next test step (--continue enabled)..."));else{let k=j.slice(O+1);if(k.length>0){console.log(q.yellow(`
|
|
936
|
+
\u{1F6D1} Aborting dependent flow due to upstream failure at Step ${re}.`)),console.log(q.gray(`Cascading skip applied to ${k.length} downstream step(s):`));for(let F=0;F<k.length;F++){let N=k[F],H=re+1+F;this.reporter.logStep(se,N.originalText,N.type,"SKIPPED",`Cascading skip: Precondition failed at Step ${re} (${D.originalText})`,void 0,{videoOffsetMs:Math.max(0,Date.now()-P)},0),console.log(q.gray(` [Step ${H}/${j.length}] \u26AA SKIPPED: ${N.originalText}`))}}break}}y&&await y.sample(re,D.originalText)}}try{let Z=this.lastHierarchy;if(Z?.flat){let W=ji(Z.flat,this.screenDimensions.width,this.screenDimensions.height);if(W.length>0){console.log(q.bold.yellow(`
|
|
937
|
+
\u{1F50D} Visual QA Sentinel Warnings (${W.length} detected):`));for(let J of W)console.log(q.yellow(` \u2022 [${J.type}] ${J.description}`)),this.reporter.logError(`Visual Defect (${J.type}): ${J.description}`)}}}catch{}await this.memory.save(),i.resume&&$===0&&await this.checkpoints.clear(p);let R=this.memory.getStats();if(R.totalMappings>0&&console.log(q.cyan(`\u{1F9E0} Knowledge Engine: ${R.totalMappings} active learned mapping(s) for ${R.package}`)),x){console.log(q.cyan("\u{1F3AC} Finalizing video recording..."));let Z=it.resolve(process.cwd(),"output"),W=it.join(Z,`${p}-recording.mp4`),J=await this.driver.stopScreenRecording(x,W,i.serial);J&&us.existsSync(J)&&(this.reporter.setVideoPath?.(`${p}-recording.mp4`),console.log(q.green(`\u2714 Screen recording saved to: output/${p}-recording.mp4`))),x=null}if(y){let Z=await y.stop();typeof this.reporter.setPerformanceMetrics=="function"&&this.reporter.setPerformanceMetrics(Z)}let C=((Date.now()-P)/1e3).toFixed(1),B=await this.reporter.generateReport(p);b&&(b.broadcastComplete(B),T&&T()),console.log(q.bold.green(`
|
|
938
|
+
\u2728 PromptTest Script Execution Finished in ${C}s!`));let U=B.failedSteps===0?q.bold.green:q.bold.yellow;return console.log(U(`Result: ${B.passedSteps}/${B.totalSteps} passed (${B.failedSteps} failed, ${B.skippedSteps} skipped).`)),console.log(q.cyan(`Report saved to output/${p}-report.html`)),process.env.CI||console.log(q.dim("\u2B50 Star PromptTest on GitHub: ")+q.underline.cyan("https://github.com/shriramsingh/prompttest-community")),console.log(""),i.json&&console.log(JSON.stringify(B,null,2)),B}finally{if(x)try{await this.driver.stopScreenRecording(x,it.join("output",`${p}-recording.mp4`),i.serial)}catch{}g&&kt(g)}}async getCleanHierarchy(e){let t=await this.driver.getUiHierarchy(e),{flat:s}=me(t),i=s.find(o=>(o.text==="Dismiss"||o.contentDesc==="Dismiss")&&o.bounds.width>0);i&&(await this.driver.tap(i.bounds.centerX,i.bounds.centerY,e),await new Promise(o=>setTimeout(o,400)),t=await this.driver.getUiHierarchy(e),s=me(t).flat);let n=s.find(o=>o.contentDesc&&(o.contentDesc.startsWith("!, ")||o.contentDesc.includes("react.dev/link")));if(n){let o=n.bounds.x2-45,c=n.bounds.centerY;await this.driver.tap(o,c,e),await new Promise(l=>setTimeout(l,350)),t=await this.driver.getUiHierarchy(e),s=me(t).flat}let r=ye(s);return this.lastHierarchy={xml:t,flat:s,timestamp:Date.now(),hash:r},{xml:t,flat:s}}async ensureInViewport(e,t){let s=this.screenDimensions.width,i=this.screenDimensions.height,n=Math.round(s*.5),r=this.navBarHeight>0?i-this.navBarHeight:i,o=this.navBarHeight>0?r*.94:i*I.gestures.bottomNavThresholdRatio;if(e.bounds.centerY>o||e.bounds.y1>o)return!1;let l=e.bounds.y2>r,p=e.bounds.y1<Math.round(i*.04)&&e.bounds.centerY<Math.round(i*.06);return l?(await this.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.45),250,t),await new Promise(d=>setTimeout(d,200)),this.lastHierarchy=null,!0):p?(await this.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.65),250,t),await new Promise(d=>setTimeout(d,200)),this.lastHierarchy=null,!0):!1}async waitForTarget(e,t,s=3e3,i){if(this.lastHierarchy&&Date.now()-this.lastHierarchy.timestamp<I.polling.hierarchyCacheTtlMs){let c=this.matchNodes(this.lastHierarchy.flat,e,i);if(c.length>0)return{flat:this.lastHierarchy.flat,matched:c}}let n=Date.now();for(;Date.now()-n<s;){let{flat:c}=await this.getCleanHierarchy(t),l=this.matchNodes(c,e,i);if(l.length>0)return{flat:c,matched:l};await new Promise(p=>setTimeout(p,$i()))}let{flat:r}=await this.getCleanHierarchy(t),o=this.matchNodes(r,e,i);if(o.length===0&&(this.healEnabled||I.ai.selfHealing))try{let c=await this.semanticResolver.findSuggestions(e,r,{locale:this.activeLocale}),l=I.ai.confidenceThreshold||.75,p=c.find(d=>d.score>=l);if(p){let d=p.node||r.find(u=>(de(p.text,u.text)||de(p.text,u.contentDesc))&&u.bounds.width>0);if(d){console.log(q.yellow(` \u{1F4A1} [Self-Healing] Auto-healed "${e}" \u2192 "${p.text}" (${Math.round(p.score*100)}% confidence, ${p.strategy})`)),i&&(i.healedFrom=e,i.healedTo=p.text,i.target=p.text);let u=d.text?"text":d.contentDesc?"contentDesc":"resourceId",h=this.lastHierarchy?.hash,g=Math.min(I.memory?.maxHealedConfidence??.65,p.score);this.memory.recordSuccess(i?.type||"TAP",e,p.text,u,g,e,h),o=[d]}}}catch(c){qe.warn(`Self-healing resolution failed: ${c.message}`)}return{flat:r,matched:o}}buildDiagnosticError(e,t,s){return Qi(e,t,s)}async executeStep(e,t,s){let i=nr.get(e.type);if(!i)throw new Error(`No handler registered for step type: ${e.type}`);e.target&&e.target.includes("$")&&(e.target=Pt(e.target,Object.fromEntries(this.runtimeVariables))),e.value&&e.value.includes("$")&&(e.value=Pt(e.value,Object.fromEntries(this.runtimeVariables))),(e.type==="LAUNCH_APP"||e.type==="RESTART_APP")&&e.target&&(this.targetPackage=e.target);let n={targetPackage:this.targetPackage,driver:this.driver,memory:this.memory,serial:t,screenDimensions:this.screenDimensions,navBarHeight:this.navBarHeight,lastHierarchy:this.lastHierarchy,setLastHierarchy:r=>{this.lastHierarchy=r},getCleanHierarchy:r=>this.getCleanHierarchy(r),waitForTarget:(r,o,c,l)=>this.waitForTarget(r,o,c,l),matchNodes:(r,o,c)=>this.matchNodes(r,o,c),ensureInViewport:(r,o)=>this.ensureInViewport(r,o),buildDiagnosticError:(r,o,c)=>this.buildDiagnosticError(r,o,c),findTargetInputField:(r,o,c)=>this.findTargetInputField(r,o,c),upcomingSteps:s,variables:this.runtimeVariables,loopStack:this.loopStack,executeChildSteps:async(r,o)=>{for(let c=0;c<r.length;c++){let l=r[c];await this.executeStep(l,o.serial,r.slice(c+1))}}};return i.execute(e,n)}findTargetInputField(e,t,s){return Zi(e,t,s,this.memory)}matchNodes(e,t,s){return rs(e,t,this.memory,this.activeLocale,s,this.lastHierarchy?.hash)}},Pr=new Ke;Ne();Ne();It();Fe();Fe();import Er from"fs";import Mn from"path";var Zt=null;function Rn(a){return JSON.parse(JSON.stringify(a))}function kr(a,e){for(let t of Object.keys(e)){let s=e[t],i=a[t];s&&typeof s=="object"&&!Array.isArray(s)&&i&&typeof i=="object"?kr(i,s):s!==void 0&&(a[t]=s)}return a}function On(a){let e=Rn(I),t=a||Mn.resolve(process.cwd(),"prompttest.config.json");if(Er.existsSync(t))try{let y=Er.readFileSync(t,"utf-8"),P=JSON.parse(y);typeof P=="object"&&P!==null&&kr(e,P)}catch{}let s=process.env.PROMPTTEST_ADB_COMMAND_TIMEOUT_MS||process.env.PROMPTTEST_COMMAND_TIMEOUT_MS;if(s){let y=parseInt(s,10);isNaN(y)||(e.adb.commandTimeoutMs=y)}let i=process.env.PROMPTTEST_POLLING_INTERVAL_MS||process.env.PROMPTTEST_POLL_INTERVAL_MS;if(i){let y=parseInt(i,10);isNaN(y)||(e.polling.intervalMs=y)}let n=process.env.PROMPTTEST_POLLING_DEFAULT_TIMEOUT_MS||process.env.PROMPTTEST_DEFAULT_TIMEOUT_MS;if(n){let y=parseInt(n,10);isNaN(y)||(e.polling.defaultTimeoutMs=y)}let r=process.env.PROMPTTEST_SCREEN_FALLBACK_WIDTH||process.env.PROMPTTEST_FALLBACK_WIDTH;if(r){let y=parseInt(r,10);isNaN(y)||(e.screen.fallbackWidth=y)}let o=process.env.PROMPTTEST_SCREEN_FALLBACK_HEIGHT||process.env.PROMPTTEST_FALLBACK_HEIGHT;if(o){let y=parseInt(o,10);isNaN(y)||(e.screen.fallbackHeight=y)}let c=process.env.PROMPTTEST_VISUAL_OVERLAP_RATIO||process.env.PROMPTTEST_OVERLAP_RATIO;if(c){let y=parseFloat(c);isNaN(y)||(e.visual.overlapRatio=y)}let l=process.env.PROMPTTEST_DEVICE_MAX_DEVICE_RETRIES||process.env.PROMPTTEST_MAX_DEVICE_RETRIES;if(l){let y=parseInt(l,10);isNaN(y)||(e.device.maxDeviceRetries=y)}let p=process.env.PROMPTTEST_DEVICE_AUTO_RECONNECT??process.env.PROMPTTEST_AUTO_RECONNECT;p!==void 0&&(e.device.autoReconnect=p.toLowerCase()!=="false");let d=process.env.PROMPTTEST_GESTURES_SWIPE_DURATION_MS||process.env.PROMPTTEST_SWIPE_DURATION_MS;if(d){let y=parseInt(d,10);isNaN(y)||(e.gestures.swipeDurationMs=y)}let u=process.env.PROMPTTEST_FLOW_MAX_LOOP_ITERATIONS||process.env.PROMPTTEST_MAX_LOOP_ITERATIONS;if(u){let y=parseInt(u,10);isNaN(y)||(e.flow.maxLoopIterations=y)}let h=process.env.PROMPTTEST_AI_PROVIDER;h&&["heuristic","openai","anthropic","ollama","mock"].includes(h)&&(e.ai.provider=h);let g=process.env.PROMPTTEST_AI_MODEL;g&&(e.ai.model=g);let b=process.env.PROMPTTEST_SELF_HEALING;b!==void 0&&(e.ai.selfHealing=b.toLowerCase()!=="false");let T=process.env.PROMPTTEST_CONFIDENCE_THRESHOLD;if(T){let y=parseFloat(T);isNaN(y)||(e.ai.confidenceThreshold=y)}let x=process.env.PROMPTTEST_AI_ENDPOINT;x&&(e.ai.endpoint=x);let S=process.env.PROMPTTEST_LOCALE;return S&&(e.locale=S.toLowerCase()),Zt=e,e}function md(){return Zt||(Zt=On()),Zt}function fd(){Zt=null}Ne();import je from"chalk";function Dr(a,e){if(a.length===0)return 0;let t=[...a].sort((i,n)=>i-n),s=Math.min(t.length-1,Math.max(0,Math.floor(e/100*(t.length-1))));return Math.round(t[s]*100)/100}function bi(a){if(a.length===0)return{minMs:0,maxMs:0,avgMs:0,p50Ms:0,p95Ms:0,iterations:0,durations:[]};let e=Math.round(Math.min(...a)*100)/100,t=Math.round(Math.max(...a)*100)/100,s=a.reduce((o,c)=>o+c,0),i=Math.round(s/a.length*100)/100,n=Dr(a,50),r=Dr(a,95);return{minMs:e,maxMs:t,avgMs:i,p50Ms:n,p95Ms:r,iterations:a.length,durations:a}}function Fn(a=1e3){let e=[];e.push({index:0,className:"android.widget.FrameLayout",packageName:"com.app",text:"",resourceId:"android:id/content",contentDesc:"Main Screen Root",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:0,y1:0,x2:1080,y2:2400,width:1080,height:2400,centerX:540,centerY:1200}}),e.push({index:1,className:"android.widget.TextView",packageName:"com.app",text:"Apex Coaching Academy - Dashboard",resourceId:"com.app:id/title_header",contentDesc:"Header Title",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:40,y1:100,x2:1040,y2:220,width:1e3,height:120,centerX:540,centerY:160}});let t=["android.widget.TextView","android.widget.Button","android.widget.EditText","android.widget.ImageView","android.view.ViewGroup","android.widget.LinearLayout","android.widget.CheckBox","android.widget.Switch"],s=["Sign In","Email Address","Password","Submit","Save Changes","Settings","Profile","Notifications","Batch 10A","Mathematics","Physics","Attendance","Export PDF","Delete Record","Cancel","Next","Back","Search","Filter","Refresh"];for(let i=2;i<a;i++){let n=t[i%t.length],r=n.includes("Button")||n.includes("CheckBox")||n.includes("Switch"),o=s[i%s.length],c=`${o} #${i}`,l=Math.min(2400,250+i*20%2e3),p=50+i*30%900;e.push({index:i,className:n,packageName:"com.app",text:n.includes("ImageView")?"":c,resourceId:`com.app:id/element_${i}`,contentDesc:n.includes("ImageView")?`Icon of ${o}`:"",clickable:r,enabled:i%25!==0,focused:!1,scrollable:!1,password:o.toLowerCase().includes("password"),selected:!1,children:[],bounds:{x1:p,y1:l,x2:p+200,y2:l+80,width:200,height:80,centerX:p+100,centerY:l+40}})}return e}async function Td(a=Pe,e={}){let t=e.iterations||5,s=Date.now(),i=e.serial,n="Synthetic Mock Android Environment",r=!1;if(!e.forceMock)try{i=await a.ensureDefaultDevice(e.serial),i&&(n=await a.getDeviceModel(i),r=!0)}catch{r=!1}let o=[];for(let g=0;g<t;g++){let b=performance.now();r?await a.captureScreenshot(i):(await new Promise(T=>setTimeout(T,15)),Buffer.alloc(1024*1024)),o.push(performance.now()-b)}let c=[];for(let g=0;g<t;g++){let b=performance.now();r?await a.getUiHierarchy(i):await new Promise(T=>setTimeout(T,25)),c.push(performance.now()-b)}let l=Fn(1e3),p=new pt,d=["Submit","Email Address","Mathematics","Save Changes","NonExistent Query Fallback"],u=[];for(let g=0;g<t;g++){let b=d[g%d.length],T=performance.now();rs(l,b,p),u.push(performance.now()-T)}let h=Date.now()-s;return{timestamp:new Date().toISOString(),device:n,package:e.packageName,screencap:bi(o),uiHierarchy:bi(c),nodeMatching:bi(u),totalDurationMs:h}}function Pd(a){let e=(n,r)=>{let o=`${r.minMs.toFixed(1)}ms`.padStart(9),c=`${r.avgMs.toFixed(1)}ms`.padStart(9),l=`${r.p50Ms.toFixed(1)}ms`.padStart(9),p=`${r.p95Ms.toFixed(1)}ms`.padStart(9),d=`${r.maxMs.toFixed(1)}ms`.padStart(9);return`\u2502 ${n.padEnd(28)} \u2502 ${o} \u2502 ${c} \u2502 ${l} \u2502 ${p} \u2502 ${d} \u2502`};return["",je.bold.cyan("\u26A1 PromptTest Performance Diagnostic Benchmark"),je.gray("Device: ")+je.bold.white(a.device)+je.gray(` | Samples: ${a.screencap.iterations} runs`),"\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",`\u2502 ${je.bold("Operation".padEnd(28))} \u2502 ${je.bold("Min".padStart(9))} \u2502 ${je.bold("Avg".padStart(9))} \u2502 ${je.bold("p50".padStart(9))} \u2502 ${je.bold("p95".padStart(9))} \u2502 ${je.bold("Max".padStart(9))} \u2502`,"\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",e("Device Screencap",a.screencap),e("UI Hierarchy Dump (XML)",a.uiHierarchy),e("Node Matching (1k nodes)",a.nodeMatching),"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",je.gray("Total Benchmark Wall-Time: ")+je.bold.green(`${a.totalDurationMs}ms
|
|
939
|
+
`)].join(`
|
|
940
|
+
`)}Ne();import _n from"readline";import jt from"fs";import Ar from"path";import le from"chalk";async function $r(a=Pe,e,t={}){let s=await a.ensureDefaultDevice(t.serial),i=e||new Ke(a),n={history:[],successfulSteps:[]},r=t.input||process.stdin,o=t.output||process.stdout,c=_n.createInterface({input:r,output:o,prompt:le.bold.cyan("prompttest> ")}),l=!1,p=()=>{if(!l)try{c.prompt()}catch{}},d=u=>{o.write(u+`
|
|
941
|
+
`)};return d(le.bold.cyan(`
|
|
942
|
+
\u26A1 PromptTest Interactive Live REPL / Playground (v1.1.0)`)),d(le.gray("Device: ")+le.bold.white(s||"No device connected (offline mock)")+(t.packageName?le.gray(" | Package: ")+le.bold.white(t.packageName):"")),d(le.gray(`Type natural language instructions (e.g. Tap 'Sign In'), or REPL commands: "inspect", "screenshot", "history", "save <file.txt>", "exit".
|
|
943
|
+
`)),new Promise(u=>{p(),c.on("line",async h=>{let g=h.trim();if(!g){p();return}n.history.push(g);let b=g.toLowerCase();if(b==="exit"||b==="quit"||b===":q"){l=!0,d(le.yellow("Exiting PromptTest REPL.")),c.close();return}if(b==="help"||b==="?"){d(le.bold.white(`
|
|
944
|
+
\u{1F4D6} PromptTest REPL Commands:`)),d(` \u2022 ${le.cyan("Tap '...'")} / ${le.cyan("Type '...' into '...'")} : Execute action live on device`),d(` \u2022 ${le.cyan("Verify '...' is visible")} : Assert element visibility`),d(` \u2022 ${le.cyan("inspect")} / ${le.cyan("tree")} : List interactive elements and input fields on screen`),d(` \u2022 ${le.cyan("screenshot [path]")} : Capture current screen to image file`),d(` \u2022 ${le.cyan("history")} : Show executed commands in current session`),d(` \u2022 ${le.cyan("save <file.txt>")} : Save successful steps into a reusable spec file`),d(` \u2022 ${le.cyan("clear")} : Clear session history`),d(` \u2022 ${le.cyan("exit")} : Quit the REPL
|
|
945
|
+
`),p();return}if(b==="history"){d(le.bold.white(`
|
|
946
|
+
\u{1F4DC} Session History (${n.history.length} commands):`)),n.history.forEach((T,x)=>{d(` ${x+1}. ${T}`)}),d(""),p();return}if(b==="clear"){n.successfulSteps=[],n.history=[],d(le.green("Session history cleared.")),p();return}if(b.startsWith("save")){let x=g.split(/\s+/)[1]||"output/repl_spec.txt";try{let S=Ar.dirname(x);S&&!jt.existsSync(S)&&jt.mkdirSync(S,{recursive:!0});let y=n.successfulSteps.map((P,$)=>`${$+1}. ${P}`).join(`
|
|
947
|
+
`);jt.writeFileSync(x,y,"utf-8"),d(le.bold.green(`\u2714 Saved ${n.successfulSteps.length} step(s) to ${x}`))}catch(S){let y=S;d(le.red(`Failed to save spec: ${y.message}`))}p();return}if(b.startsWith("screenshot")){let x=g.split(/\s+/)[1]||`output/repl_screenshot_${Date.now()}.png`;try{let S=Ar.dirname(x);S&&!jt.existsSync(S)&&jt.mkdirSync(S,{recursive:!0});let y=await a.captureScreenshot(s);jt.writeFileSync(x,y),d(le.bold.green(`\u2714 Screenshot saved to ${x}`))}catch(S){let y=S;d(le.red(`Failed to capture screenshot: ${y.message}`))}p();return}if(b==="inspect"||b==="tree"){try{d(le.gray("Dumping UI hierarchy..."));let T=await a.getUiHierarchy(s),{flat:x}=me(T),S=x.filter(y=>y.clickable||y.className.includes("Button")||y.className.includes("EditText"));d(le.bold.white(`
|
|
948
|
+
\u{1F50D} Visible Interactive Elements (${S.length} found):`)),S.slice(0,25).forEach((y,P)=>{let $=y.text||y.contentDesc||y.resourceId||`<Unnamed ${y.className}>`,R=y.className.split(".").pop()||y.className;d(` [${P+1}] (${R}) "${$}" at (${y.bounds.centerX}, ${y.bounds.centerY})`)}),S.length>25&&d(le.gray(` ... and ${S.length-25} more elements.`)),d("")}catch(T){let x=T;d(le.red(`Failed to inspect hierarchy: ${x.message}`))}p();return}try{let T=mt(g);if(T.length===0){d(le.yellow(`Could not parse natural language step: "${g}"`)),p();return}let x=T[0],S=performance.now();await i.executeStep(x,s);let y=Math.round(performance.now()-S);n.successfulSteps.push(g),d(le.green(`\u2714 [${x.type}] Completed in ${y}ms: `)+le.white(x.originalText))}catch(T){let x=T;d(le.red(`\u2716 Step failed: ${x.message}`))}p()}),c.on("close",()=>{l=!0,u(n)})})}import qt from"fs";import yi from"path";function Cr(a){let e=a.totalSteps||0,t=a.passedSteps||0,s=a.failedSteps||0,i=a.skippedSteps||0,n=a.errorsDetected?a.errorsDetected.length:0;if(e===0)return{score:0,grade:"F",verdict:"RELEASE_BLOCKER",rationale:"No test steps were executed.",metrics:{passRate:0,criticalFailures:0,visualDefects:0,totalSteps:0,skippedSteps:0}};let r=t/e,o=Math.min(30,n*10),c=s>0?35+Math.min(25,s*5):0,l=Math.round(r*80+20-o-c);l=Math.max(0,Math.min(100,l));let p="F",d="RELEASE_BLOCKER",u="";return l>=90?(p="A",d="READY_FOR_RELEASE",u="High quality gate confidence. All critical assertion paths verified."):l>=80?(p="B",d="READY_FOR_RELEASE",u="Acceptable release confidence. Minor non-critical or optional warnings observed."):l>=70?(p="C",d="PROCEED_WITH_CAUTION",u="Elevated risk. Visual QA warnings or multiple non-critical step failures detected."):(p="F",d="RELEASE_BLOCKER",u=`Critical test failures (${s}) or visual defects (${n}) block safe release.`),{score:l,grade:p,verdict:d,rationale:u,metrics:{passRate:Math.round(r*100)/100,criticalFailures:s,visualDefects:n,totalSteps:e,skippedSteps:i}}}function _d(a="output"){let e=[],t=h=>{if(!qt.existsSync(h))return;let g=qt.readdirSync(h,{withFileTypes:!0});for(let b of g){let T=yi.join(h,b.name);b.isDirectory()?t(T):b.isFile()&&(b.name.endsWith("-results.json")||b.name.endsWith("-report.json"))&&e.push(T)}};if(Array.isArray(a))for(let h of a)qt.existsSync(h)&&(qt.statSync(h).isDirectory()?t(h):e.push(h));else t(a);let s=[],i=new Set,n=0,r=0,o=0,c=0,l=[];for(let h of e)try{let g=qt.readFileSync(h,"utf-8"),b=JSON.parse(g),T=Cr(b),x=b.deviceId||"unknown-device";i.add(x),n+=b.totalSteps||0,r+=b.passedSteps||0,o+=b.failedSteps||0,c+=b.skippedSteps||0,b.errorsDetected&&l.push(...b.errorsDetected),s.push({deviceId:x,suiteName:yi.basename(h,yi.extname(h)).replace(/-results|-report/,""),packageName:b.packageName||"unknown",totalSteps:b.totalSteps||0,passedSteps:b.passedSteps||0,failedSteps:b.failedSteps||0,skippedSteps:b.skippedSteps||0,durationSeconds:b.durationSeconds||0,confidenceScore:T.score,confidenceGrade:T.grade,sourceFile:h})}catch{}let p=n>0?Math.round(r/n*100)/100:0,d={packageName:s[0]?.packageName||"Enterprise Matrix",deviceId:`${i.size} devices`,startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:s.reduce((h,g)=>h+g.durationSeconds,0),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:c,warnSteps:0,errorsDetected:l,steps:[]},u=Cr(d);return{timestamp:new Date().toISOString(),totalRuns:s.length,uniqueDevices:Array.from(i),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:c,overallPassRate:p,overallConfidence:u,deviceSummaries:s}}function Hd(a){let e=a.overallConfidence,t=e.grade==="A"?"#10B981":e.grade==="B"?"#3B82F6":e.grade==="C"?"#F59E0B":"#EF4444",s=a.deviceSummaries.map(i=>{let n=i.confidenceGrade==="A"?"#10B981":i.confidenceGrade==="B"?"#3B82F6":i.confidenceGrade==="C"?"#F59E0B":"#EF4444";return`
|
|
949
|
+
<tr style="border-bottom: 1px solid #334155;">
|
|
950
|
+
<td style="padding: 12px; font-weight: bold; color: #F8FAFC;">${i.deviceId}</td>
|
|
951
|
+
<td style="padding: 12px; color: #94A3B8;">${i.suiteName}</td>
|
|
952
|
+
<td style="padding: 12px; color: #94A3B8;">${i.packageName}</td>
|
|
953
|
+
<td style="padding: 12px; text-align: center; color: #F8FAFC;">${i.totalSteps}</td>
|
|
954
|
+
<td style="padding: 12px; text-align: center; color: #10B981; font-weight: bold;">${i.passedSteps}</td>
|
|
955
|
+
<td style="padding: 12px; text-align: center; color: #EF4444; font-weight: bold;">${i.failedSteps}</td>
|
|
956
|
+
<td style="padding: 12px; text-align: center; color: #64748B;">${i.skippedSteps}</td>
|
|
957
|
+
<td style="padding: 12px; text-align: center;">
|
|
958
|
+
<span style="background: ${n}22; color: ${n}; border: 1px solid ${n}; padding: 4px 10px; border-radius: 9999px; font-weight: bold; font-size: 12px;">
|
|
959
|
+
Grade ${i.confidenceGrade} (${i.confidenceScore}%)
|
|
960
|
+
</span>
|
|
961
|
+
</td>
|
|
962
|
+
</tr>`}).join("");return`<!DOCTYPE html>
|
|
963
|
+
<html lang="en">
|
|
964
|
+
<head>
|
|
965
|
+
<meta charset="UTF-8">
|
|
966
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
967
|
+
<title>PromptTest Executive Matrix & Release Confidence Dashboard</title>
|
|
968
|
+
<style>
|
|
969
|
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0F172A; color: #F8FAFC; margin: 0; padding: 24px; }
|
|
970
|
+
.card { background: #1E293B; border-radius: 12px; padding: 24px; border: 1px solid #334155; margin-bottom: 24px; }
|
|
971
|
+
.header-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 24px; }
|
|
972
|
+
.score-badge { display: flex; flex-direction: column; align-items: center; justify-content: center; background: #0F172A; border-radius: 12px; border: 2px solid ${t}; padding: 20px; }
|
|
973
|
+
table { width: 100%; border-collapse: collapse; text-align: left; }
|
|
974
|
+
th { padding: 12px; background: #0F172A; color: #94A3B8; font-size: 13px; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
975
|
+
</style>
|
|
976
|
+
</head>
|
|
977
|
+
<body>
|
|
978
|
+
<div class="card header-grid">
|
|
979
|
+
<div>
|
|
980
|
+
<h1 style="margin-top: 0; color: #38BDF8;">PromptTest Executive Quality Matrix</h1>
|
|
981
|
+
<p style="color: #94A3B8; margin-bottom: 20px;">Generated at ${a.timestamp} across ${a.uniqueDevices.length} target device(s).</p>
|
|
982
|
+
<div style="display: flex; gap: 24px;">
|
|
983
|
+
<div><span style="font-size: 24px; font-weight: bold; color: #F8FAFC;">${a.totalRuns}</span><br><span style="color: #94A3B8; font-size: 12px;">Test Suites</span></div>
|
|
984
|
+
<div><span style="font-size: 24px; font-weight: bold; color: #10B981;">${a.passedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Passed Steps</span></div>
|
|
985
|
+
<div><span style="font-size: 24px; font-weight: bold; color: #EF4444;">${a.failedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Failed Steps</span></div>
|
|
986
|
+
<div><span style="font-size: 24px; font-weight: bold; color: #38BDF8;">${Math.round(a.overallPassRate*100)}%</span><br><span style="color: #94A3B8; font-size: 12px;">Overall Pass Rate</span></div>
|
|
987
|
+
</div>
|
|
988
|
+
</div>
|
|
989
|
+
<div class="score-badge">
|
|
990
|
+
<div style="font-size: 14px; text-transform: uppercase; color: #94A3B8; letter-spacing: 0.1em;">Release Confidence</div>
|
|
991
|
+
<div style="font-size: 48px; font-weight: 900; color: ${t}; margin: 8px 0;">${e.score}%</div>
|
|
992
|
+
<div style="font-size: 16px; font-weight: bold; color: ${t};">GRADE ${e.grade} \u2014 ${e.verdict}</div>
|
|
993
|
+
<p style="font-size: 12px; color: #94A3B8; text-align: center; margin: 8px 0 0 0;">${e.rationale}</p>
|
|
994
|
+
</div>
|
|
995
|
+
</div>
|
|
996
|
+
|
|
997
|
+
<div class="card">
|
|
998
|
+
<h2 style="margin-top: 0; color: #F8FAFC;">Device Execution Matrix</h2>
|
|
999
|
+
<table>
|
|
1000
|
+
<thead>
|
|
1001
|
+
<tr>
|
|
1002
|
+
<th>Device Serial</th>
|
|
1003
|
+
<th>Test Suite</th>
|
|
1004
|
+
<th>Package</th>
|
|
1005
|
+
<th style="text-align: center;">Total</th>
|
|
1006
|
+
<th style="text-align: center;">Passed</th>
|
|
1007
|
+
<th style="text-align: center;">Failed</th>
|
|
1008
|
+
<th style="text-align: center;">Skipped</th>
|
|
1009
|
+
<th style="text-align: center;">Atto Quality Grade</th>
|
|
1010
|
+
</tr>
|
|
1011
|
+
</thead>
|
|
1012
|
+
<tbody>
|
|
1013
|
+
${s}
|
|
1014
|
+
</tbody>
|
|
1015
|
+
</table>
|
|
1016
|
+
</div>
|
|
1017
|
+
</body>
|
|
1018
|
+
</html>`}It();import Yt from"os";import Ye from"chalk";var Hn="https://github.com/shriramsingh/prompttest-community/issues/new";function Bn(a){if(!a)return"";let e=a;try{let t=Yt.homedir();t&&t.length>2&&(e=e.split(t).join("~"))}catch{}return e=e.replace(/([a-zA-Z]:\\Users\\[^\\]+)/gi,"~"),e=e.replace(/(\/(?:home|Users)\/[^/]+)/g,"~"),e.trim()}function Wd(a){if(!a||a instanceof Qe&&a.exitCode===1)return!1;let e=a,t=typeof e.message=="string"?e.message:String(a);return!(t.includes("Step")&&(t.includes("failed")||t.includes("timed out")))}function Un(a){let e=a.repoUrl||Hn,t=(a.errorMessage||"Unexpected internal error").split(`
|
|
1019
|
+
`)[0].trim(),s=`[Crash]: ${t}`,i=s.length>80?s.substring(0,77)+"...":s,n=`${Yt.type()} ${Yt.release()} (${Yt.arch()})`,r=process.version,o=`${n}, Node: ${r}`,c=Bn(a.stack||a.errorMessage),l=c.length>600?c.substring(0,597)+"...":c,p=new URLSearchParams;return p.set("template","1_bug_report.yml"),p.set("title",i),p.set("description",`PromptTest encountered an unexpected error: ${t}`),a.command&&p.set("command_run",a.command),p.set("environment",o),l&&p.set("logs",l),`${e}?${p.toString()}`}function Jd(a,e={}){let t=a&&typeof a=="object"?a:{},s=t.message||String(a),i=t.stack,n=e.command||(process.argv.slice(2).length>0?`npx prompttest ${process.argv.slice(2).join(" ")}`:"npx prompttest"),r=Un({errorMessage:s,stack:i,command:n,exitCode:e.exitCode}),o=`${Yt.type()} ${Yt.arch()}`,c=process.version;console.error(),console.error(Ye.red.bold("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.error(Ye.red.bold("\u{1F4A5} PromptTest Encountered an Unexpected Error / Crash")),console.error(Ye.red.bold("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.error(Ye.white("Error: ")+Ye.red(s.split(`
|
|
1020
|
+
`)[0])),console.error(Ye.white("Command: ")+Ye.gray(n)),console.error(Ye.white("Environment: ")+Ye.gray(`${o} | Node: ${c}`)),console.error(),console.error(Ye.cyan("\u{1F4A1} Think this is a bug in PromptTest? You can report it in 1 click (pre-filled):")),console.error(Ye.bold.underline.cyan(r)),console.error(Ye.red.bold("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.error()}Ne();import Wn from"readline";import Ti from"fs";import Pi from"path";import _ from"chalk";async function Jn(a=Pe){try{let t=(await a.getConnectedDevices()).find(n=>n.state==="device");if(!t)return{isOnline:!1};let s=t.serial,i;try{let n=await a.getForegroundPackage(s);n&&!n.includes("launcher")&&!n.includes("systemui")&&(i=n)}catch{}return{device:t,serial:s,activePackage:i,isOnline:!0}}catch{return{isOnline:!1}}}function Vn(a=process.cwd()){let e=[],t=[Pi.join(a,"specs"),a];for(let s of t)if(Ti.existsSync(s)&&Ti.statSync(s).isDirectory())try{let i=Ti.readdirSync(s);for(let n of i)if(n.endsWith(".txt")||n.endsWith(".spec")||n.endsWith(".prompt")){let r=Pi.relative(a,Pi.join(s,n)).replace(/\\/g,"/");e.includes(r)||e.push(r)}}catch{}return e.sort()}function wt(a,e){return new Promise(t=>{a.question(e,s=>{t(s.trim())})})}async function dp(a={}){let e=a.driver||Pe,t=a.runner||Pr,s=a.input||process.stdin,i=a.output||process.stdout,n=Wn.createInterface({input:s,output:i}),r=(o="")=>{i.write(o+`
|
|
1021
|
+
`)};try{r(_.bold.cyan(`
|
|
1022
|
+
\u26A1 PromptTest \u2014 Autonomous Mobile Testing Brain`)),r(_.gray("Inspecting device connectivity and active application..."));let o=await Jn(e);switch(r(_.gray("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),o.isOnline&&o.device?r(_.white("\u{1F4F1} Target Device: ")+_.bold.green(`${o.serial}`)+(o.device.model?_.gray(` (${o.device.model})`):"")+_.green(" [Online]")):r(_.white("\u{1F4F1} Target Device: ")+_.yellow("No authorized device online (Check USB/Wi-Fi)")),o.activePackage?r(_.white("\u{1F3AF} Active App: ")+_.bold.magenta(o.activePackage)+_.gray(" (Detected)")):r(_.white("\u{1F3AF} Active App: ")+_.gray("None detected / Home Launcher")),r(_.gray(`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1023
|
+
`)),r(_.bold.white("What would you like to do?")),r(` ${_.bold.cyan("[1]")} \u{1F680} ${_.bold("Explore app autonomously")} ${_.gray("(Zero-code AI crawl)")}`),r(` ${_.bold.cyan("[2]")} \u{1F534} ${_.bold("Record a test")} ${_.gray("(Capture real device taps into spec)")}`),r(` ${_.bold.cyan("[3]")} \u25B6\uFE0F ${_.bold("Run a test specification")} ${_.gray("(Execute .txt spec with healing)")}`),r(` ${_.bold.cyan("[4]")} \u{1F4AC} ${_.bold("Open Live REPL Playground")} ${_.gray("(Interactive terminal session)")}`),r(` ${_.bold.cyan("[5]")} \u{1FA7A} ${_.bold("Run Diagnostic Doctor")} ${_.gray("(Check ADB, Node, permissions)")}`),r(` ${_.bold.cyan("[6]")} \u{1F4F1} ${_.bold("Inspect UI Components")} ${_.gray("(Summary of buttons, inputs, tabs)")}`),r(` ${_.bold.cyan("[7]")} \u2753 ${_.bold("Help & CLI Syntax Reference")}`),r(` ${_.bold.cyan("[8]")} \u{1F4AC} ${_.bold("Share Feedback & Suggestions")} ${_.gray("(1-click community link)")}`),r(` ${_.bold.cyan("[0]")} \u{1F6AA} ${_.gray("Exit")}
|
|
1024
|
+
`),await wt(n,_.bold.cyan("Select an option [0-8]: "))){case"1":{r(_.bold.cyan(`
|
|
1025
|
+
\u{1F680} Autonomous App Exploration`));let l=o.activePackage||"",p=l?_.white(`Target package [default: ${_.bold.magenta(l)}]: `):_.white("Target package name (e.g. com.example.app): "),u=await wt(n,p)||l;if(!u){r(_.red("Error: Package name is required to start exploration."));break}let h=_.white(`Safety mode [strict/moderate/disabled] (default: ${_.bold.green("strict")}): `),g=await wt(n,h)||"strict",b=["strict","moderate","interactive","disabled"].includes(g)?g:"strict";n.close(),r(_.green(`
|
|
1026
|
+
Starting autonomous exploration on ${_.bold(u)}...
|
|
1027
|
+
`)),await hr.explore({packageName:u,serial:o.serial,strategy:"dfs",safetyMode:b});return}case"2":{r(_.bold.cyan(`
|
|
1028
|
+
\u{1F534} Interactive Record & Replay`));let l=_.white(`Target spec file to save [default: ${_.bold.green("specs/recorded_flow.txt")}]: `),p=await wt(n,l)||"specs/recorded_flow.txt";n.close(),r(_.green(`
|
|
1029
|
+
Starting recording session on device. Output: ${p}...
|
|
1030
|
+
`)),await cr.startRecording(p,o.serial,{append:!1});return}case"3":{r(_.bold.cyan(`
|
|
1031
|
+
\u25B6\uFE0F Run Test Specification`));let l=Vn(),p="";if(l.length>0){r(_.white("Discovered existing test specs:")),l.forEach(($,R)=>{r(` [${R+1}] ${_.cyan($)}`)}),r();let S=_.white(`Select spec number [1-${l.length}] or enter path: `),y=await wt(n,S),P=parseInt(y,10);!isNaN(P)&&P>=1&&P<=l.length?p=l[P-1]:y&&(p=y)}if(p||(p=await wt(n,_.white("Enter spec file path (e.g. specs/login.txt): "))),!p){r(_.red("Error: Spec file path is required."));break}let d=o.activePackage||"",u=d?_.white(`Target package [default: ${_.bold.magenta(d)}]: `):_.white("Target package (optional): "),g=await wt(n,u)||d||void 0,b=_.white(`Enable dynamic self-healing locators? [Y/n] (default: ${_.bold.green("yes")}): `),T=(await wt(n,b)).toLowerCase(),x=T!=="n"&&T!=="no";n.close(),r(_.green(`
|
|
1032
|
+
Executing spec "${p}"...
|
|
1033
|
+
`)),await t.runSpec(p,{packageName:g,serial:o.serial,heal:x});return}case"4":{r(_.bold.cyan(`
|
|
1034
|
+
\u{1F4AC} Launching Live REPL Playground...`)),n.close(),await $r(e,t,{serial:o.serial,packageName:o.activePackage});return}case"5":{r(_.bold.cyan(`
|
|
1035
|
+
\u{1FA7A} Running Diagnostic Health Check...`)),n.close();let l=await ls(e,{serial:o.serial,packageName:o.activePackage});r(dr(l));return}case"6":{if(!o.isOnline||!o.serial){r(_.red("No device online to inspect."));break}r(_.cyan(`
|
|
1036
|
+
\u{1F50D} Inspecting Active Screen UI Hierarchy...`));try{let l=await e.getUiHierarchy(o.serial),{flat:p}=me(l),d=Le(p),u=Me(p),h=ot(p);r(_.white(`
|
|
1037
|
+
On-Screen Component Breakdown:`)),r(`- \u{1F4DD} Input Fields: ${_.bold.magenta(d.length.toString())}`),d.slice(0,5).forEach(g=>r(` \u2022 "${g.text||g.contentDesc||g.resourceId}"`)),r(`- \u{1F518} Action Buttons: ${_.bold.blue(u.length.toString())}`),u.slice(0,5).forEach(g=>r(` \u2022 "${g.text||g.contentDesc||g.resourceId}"`)),r(`- \u{1F4D1} Navigation Tabs: ${_.bold.yellow(h.length.toString())}`),h.forEach(g=>r(` \u2022 "${g.text||g.contentDesc}"`)),r()}catch(l){let p=l instanceof Error?l.message:String(l);r(_.red(`Failed to read UI hierarchy: ${p}`))}break}case"7":{r(_.bold.cyan(`
|
|
1038
|
+
\u{1F4D6} Quick CLI Command Reference`)),r(" npx prompttest Interactive guided CLI wizard"),r(" npx prompttest feedback [message] Share feedback or feature requests in 1 click"),r(" npx prompttest doctor Check system dependencies & ADB"),r(" npx prompttest explore <package> Autonomous AI crawl with safety policies"),r(" npx prompttest record <spec.txt> Interactive record touches from phone"),r(" npx prompttest run <spec.txt> [package] Execute plain-English test spec"),r(" npx prompttest repl [package] Interactive live terminal playground"),r(" npx prompttest devices List all connected devices & serials"),r(` npx prompttest wifi <device_ip> Connect wireless device over Wi-Fi
|
|
1039
|
+
`);break}case"8":{n.close();let{startFeedbackSession:l}=await Promise.resolve().then(()=>(xi(),Nr));await l({input:s,output:i});return}default:{r(_.gray("Exiting PromptTest. Have a great day!"));break}}}finally{try{n.close()}catch{}}}xi();function wp(a,e,t){return new Ke(a,e,t)}function vp(a,e,t){return new yt(a,e,t)}function xp(a){return new nt(a)}function Tp(){return new pt}function Pp(a){return new lt(a)}function Ep(a){return new ft(a)}function kp(a,e){return new bt(a,e)}function Dp(a,e){return new gt(a,e)}export{Fi as ACTION_KEYWORDS,nt as AndroidDriver,ai as ApiHandler,yt as AutonomousExplorer,ft as AutonomousRecorder,js as BackHandler,gt as BaselineManager,I as CONFIG,Gs as ClearDataHandler,Bs as ClearHandler,ei as ConditionalHandler,ms as ConfigError,qr as DESTRUCTIVE_ACTION_PATTERNS,Ut as DataSpecLoader,Zs as DeepLinkHandler,Tt as DeviceError,ri as DeviceStateHandler,tn as EXTERNAL_INTENT_PATTERNS,ci as EmailHandler,bs as ExitCode,$o as GLOBAL_SEED_DICTIONARY,Qs as GrantPermissionHandler,$t as HeuristicResolver,ps as IosDriver,as as LLMResolver,Ft as LOCALE_PACKS,Zr as LOGBOX_PATTERNS,zs as LaunchAppHandler,gs as LocatorError,fs as LockError,ss as Logger,Hs as LongPressHandler,ti as LoopHandler,en as MODERATE_DESTRUCTIVE_PATTERNS,pt as MemoryEngine,Bt as MockAIProvider,oi as OtpHandler,te as PROMPT_ACTION_PATTERNS,Ke as PromptRunner,Qe as PromptTestError,lt as QaReporter,Ks as RestartAppHandler,ni as RunJsHandler,nr as STEP_HANDLER_REGISTRY,Mi as STEP_PREFIX_REGEX,Oi as SUBMIT_KEYWORDS,Ys as ScrollHandler,Vs as SelectHandler,bt as SemanticFormFiller,ii as SetVariableHandler,Jt as SpecRecursionError,Ws as SwipeHandler,_s as TapHandler,Xs as TerminateAppHandler,Js as ToggleHandler,os as TypeHandler,Sn as VOLATILE_DATA_PATTERNS,Us as VerifyHandler,qs as WaitHandler,si as WaitUntilHandler,Vt as XML_HIERARCHY_PATTERNS,Et as acquireDeviceLock,yn as assembleAstBlocks,Ns as baselineManager,Qi as buildDiagnosticError,vi as buildFeedbackUrl,Un as buildIssueUrl,Dr as calculatePercentile,Cr as calculateReleaseConfidence,Yi as clusterSiblingElements,ha as compareHierarchyNodes,Ue as computeCanonicalSemanticHash,ye as computeHierarchyHash,xp as createAndroidDriver,vp as createAutonomousExplorer,Ep as createAutonomousRecorder,Dp as createBaselineManager,sr as createFailureTriageBundle,kp as createFormFiller,Tp as createMemoryEngine,wp as createPromptRunner,Pp as createQaReporter,li as createSemanticResolver,ns as createSyntheticReport,Jn as detectActiveEnvironment,Ts as detectNavigationParadigm,ji as detectVisualDefects,Jd as displayCrashTriage,Rs as expandSpecIncludes,Ri as extractQuotedText,er as extractSpecTags,Me as findActionButtons,Ot as findCheckableControls,Rt as findClosestMatches,Kt as findDevOverlay,at as findDrawerButton,Hi as findErrorDialogs,Vn as findExistingSpecs,Bi as findHeaderActionButtons,He as findInAppBackButton,Le as findInputFields,zt as findListItems,ot as findNavigationTabs,bo as findNodes,Ui as findScrollableContainers,Zi as findTargetInputField,Pd as formatBenchmarkTable,dr as formatDoctorReport,tr as formatStepTable,Hd as generateAggregatedHtml,Fn as generateSyntheticHierarchy,md as getActiveConfig,$i as getJitteredPollDelay,Qt as getSeedSynonyms,Fr as getSettleFactor,No as getSupportedLocales,Vi as getSynonyms,Pt as interpolateVariables,Je as isDestructiveAction,Ve as isExternalIntentAction,Wd as isFrameworkCrash,_e as isLogBoxNode,Kr as levenshteinDistance,On as loadConfig,qe as logger,ga as maskSensitiveValue,rs as matchNodes,de as matchesText,_d as mergeReports,Gi as normalizeSemanticText,ae as normalizeText,_i as parseBounds,me as parseHierarchyXml,Gr as parseHierarchyXmlRegex,Qr as parseHierarchyXmlStreaming,mt as parsePrompt,qi as parseStepRange,Co as registerLocalePack,kt as releaseDeviceLock,fd as resetActiveConfig,ce as resolveTokenMatch,Td as runBenchmark,ls as runDoctor,Bn as sanitizeStackTrace,Oe as scaleSettle,Yn as startFeedbackSession,dp as startInteractiveWizard,yr as startLiveServer,$r as startRepl,Xr as stringSimilarity,bi as summarizeMetrics,Mt as unescapeXml};
|