prompttest 1.3.5 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +6 -0
- package/README.md +191 -41
- package/TERMS.md +138 -0
- package/dist/bin/prompttest.js +489 -230
- package/dist/bin/server.d.ts +1 -0
- package/dist/engine.bundle.js +1000 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +292 -154
- package/dist/lib/adaptive-timing.d.ts +55 -0
- package/dist/lib/adb-provisioner.d.ts +55 -0
- package/dist/lib/adb.d.ts +29 -0
- package/dist/lib/baseline.d.ts +52 -4
- package/dist/lib/dfs-engine.d.ts +43 -0
- package/dist/lib/explorer.d.ts +44 -0
- package/dist/lib/feedback.d.ts +35 -0
- package/dist/lib/jail-guard.d.ts +59 -0
- package/dist/lib/live-server.d.ts +5 -0
- package/dist/lib/prompt-runner.d.ts +1 -0
- package/dist/lib/quiescence.d.ts +44 -0
- package/dist/lib/recorder.d.ts +24 -0
- package/dist/lib/reporter.d.ts +2 -0
- package/dist/lib/step-handlers.d.ts +2 -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 +4 -4
- 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 +6 -7
- package/package.json +12 -3
package/dist/index.js
CHANGED
|
@@ -1,62 +1,107 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`).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(ae.LAUNCH_APP(e),t)}async forceStop(e,t){await this.execAdb(ae.FORCE_STOP(e),t)}async clearAppData(e,t){await this.execAdb(ae.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(ae.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){await this.execAdb(ae.INSTALL_APK(e),t)}async uninstallApp(e,t){await this.execAdb(ae.UNINSTALL_APP(e),t)}async openDeepLink(e,t){await this.execAdb(ae.DEEP_LINK(e),t)}async checkCrashes(e,t){try{let{stdout:s}=await this.execAdb(ae.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(ae.CLEAR_CRASH_LOGS(),e)}catch{}}async getDeviceIp(e){try{let{stdout:t}=await this.execAdb(ae.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 l=e.split(":");i=l[0],n=parseInt(l[1],10)||t}if(!i){let l=await this.getDeviceIp(s);if(!l)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=l}let r=`${i}:${n}`;if(e)try{let{stdout:l,stderr:h}=await this.execAdb(ae.CONNECT(r)),u=`${l} ${h}`.trim();if(u.toLowerCase().includes("connected")||u.toLowerCase().includes("already"))return this.defaultSerial=r,{success:!0,target:r,message:u}}catch{}try{await this.execAdb(ae.TCPIP(n),s),await new Promise(l=>setTimeout(l,1e3))}catch{}let{stdout:o,stderr:a}=await this.execAdb(ae.CONNECT(r)),d=`${o} ${a}`.trim(),c=d.toLowerCase().includes("connected")||d.toLowerCase().includes("already");return c&&(this.defaultSerial=r),{success:c,target:r,message:d}}async disconnectWifi(e){let{stdout:t,stderr:s}=await this.execAdb(ae.DISCONNECT(e));return`${t} ${s}`.trim()}streamLogcatEvents(e,t){let i=et("adb",["-s",e,"shell","logcat","-b","events","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatCrashes(e,t){let i=et("adb",["-s",e,"shell","logcat","-T","1","-s","AndroidRuntime:E","ANRManager:E","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatToasts(e,t){let i=et("adb",["-s",e,"shell","logcat","-s","Toast:D","Snackbar:D","-v","time"]),n=Bt.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,n=et("adb",s?["-s",s,"shell","screenrecord",e]:["shell","screenrecord",e]);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","dumpsys","input_method"],e,4e3,0);return t.includes("mInputShown=true")||t.includes("isInputViewShown=true")||t.includes("mHasSurface=true")}catch{return!1}}async ensureAccessibilityServices(e){try{await this.execAdb(["shell","settings","put","secure","accessibility_enabled","1"],e,4e3,0)}catch{}}},he=new tt;var Ls=/^(\d+(?:\.\d+)*\.?|\-|\*)\s*/;function Rs(p){let e=p.trim(),t=e.match(/^"([^"]+)"$/);if(t)return t[1].trim();let s=e.match(/^'([^']+)'$/);return s?s[1].trim():e.replace(/^['"]+|['"]+$/g,"").trim()}var V=`(?:"([^"]+)"|'([^']+)'|([^'"\\s][^'"]*?[^'"\\s]|\\S))`;function W(p){for(let e of p)if(e!=null&&e.trim().length>0)return e.trim();return""}function Xe(p,e){let t=p;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 O={TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:button\\s+|item\\s+)?${V}$`,"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+)?${V}$`,"i"),PROXIMITY_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+${V}\\s+(?:next\\s+to|near|beside|inside|for)\\s+${V}$`,"i"),CLEAR:new RegExp(`^(?:clear|empty)(?:\\s+(?:text\\s+(?:in|of)|field|input))?\\s+${V}$`,"i"),LONG_PRESS:new RegExp(`^(?:long\\s+press|press\\s+and\\s+hold)\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),TYPE:new RegExp(`^(?:type|enter|input)\\s+${V}\\s+(?:in|into)\\s+${V}$`,"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+)?${V}\\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+${V}$`,"i"),SCROLL:/^(?:scroll|swipe)\s+(down|up)$/i,DIRECTIONAL_SWIPE:new RegExp(`^(?:swipe|scroll)\\s+(left|right|up|down)(?:\\s+on\\s+${V})?$`,"i"),TOGGLE:new RegExp(`^(?:toggle|turn\\s+(on|off)|check|uncheck)\\s+(?:checkbox\\s+|switch\\s+)?${V}$`,"i"),SELECT_DROPDOWN:new RegExp(`^(?:select|choose)\\s+${V}\\s+from\\s+${V}$`,"i"),LAUNCH_APP:new RegExp(`^(?:launch|open)\\s+(?:app\\s+)?${V}$`,"i"),RESTART_APP:new RegExp(`^(?:restart|relaunch)\\s+(?:app\\s+)?${V}$`,"i"),TERMINATE_APP:new RegExp(`^(?:terminate|close|force\\s*stop)\\s+(?:app\\s+)?(?:${V})?$`,"i"),CLEAR_DATA:new RegExp(`^(?:clear\\s+(?:app\\s+)?data\\s+(?:for\\s+)?|reset\\s+app\\s+)${V}$`,"i"),GRANT_PERMISSION:new RegExp(`^grant\\s+permissions?\\s+${V}(?:\\s+(?:to|for)\\s+${V})?$`,"i"),DEEP_LINK:new RegExp(`^(?:open\\s+deep\\s*link|navigate\\s+to\\s+url)\\s+${V}$`,"i"),WAIT:/^wait\s+(\d+)\s*(?:s|sec|seconds|ms)?$/i,WAIT_UNTIL:new RegExp(`^(?:wait\\s+until|wait\\s+for)\\s+${V}\\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+)?${V}\\s+(?:is\\s+)?(visible|present|exists|appears?)|element\\s+${V}\\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+)?${V}$`,"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+${V}$`,"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+${V})?$`,"i"),API_REQUEST:new RegExp(`^(?:api|call\\s+api)\\s+(GET|POST|PUT|DELETE|PATCH)\\s+${V}(?:\\s+with\\s+body\\s+${V})?(?:\\s+store\\s+${V}\\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+${V}\\s+with\\s+subject\\s+${V}(?:\\s+contains\\s+${V})?$`,"i"),OPTIONAL_SUFFIX:/\s*\((?:optional|if\s+present|maybe)\)\s*$/i,FALLBACK_QUOTED_TAP:/^(?:tap|click)\s+.*?['"]([^'"]+)['"]/i},ft={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 st(p){return(p||"").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 X(p){return st(p||"").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 Is=new Map;function z(p,e){if(!p||!e)return!1;let t=X(p),s=X(e);if(t.length<=3){let i=Is.get(t);if(!i){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(`(?:^|\\b)${n}(?:\\b|$)`,"i"),Is.set(t,i)}return i.test(s)}return s.includes(t)}var Ns=["sign in","signin","login","log in","submit","save","continue","next","done","send","confirm","proceed","post","rate","enter","join","apply","update"],Ms=["sign in","signin","login","log in","submit","save","next","continue","done","like","fav","favorite","star","bookmark","add","post","confirm","apply","explore","search","filter"];function yi(p,e){let t=X(p),s=X(e),i=t.length,n=s.length;if(i===0)return n;if(n===0)return i;let r=Array.from({length:n+1},(a,d)=>d),o=new Array(n+1);for(let a=1;a<=i;a++){o[0]=a;for(let c=1;c<=n;c++){let l=t[a-1]===s[c-1]?0:1;o[c]=Math.min(r[c]+1,o[c-1]+1,r[c-1]+l)}let d=r;r=o,o=d}return r[n]}function Si(p,e){let t=X(p),s=X(e);if(t===s)return 1;if(!t||!s)return 0;let i=Math.max(t.length,s.length);return 1-yi(t,s)/i}function We(p,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:Si(p,r)})).filter(r=>r.score>=s).sort((r,o)=>o.score-r.score).slice(0,t)}function Fs(p){let e=p.match(ft.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 wi(p){let e=p.match(ft.HIERARCHY_ROOT);if(!e)return{root:[],flat:[]};let t=e[1],s=new RegExp(ft.NODE_TAG.source,"gi"),i=new RegExp(ft.ATTR_KEY_VALUE.source,"g"),n=[],r=[],o=[],a;for(;(a=s.exec(t))!==null;){let d=a[0],c=a[1],l=a[2]==="/";if(d.startsWith("</node>")){o.pop();continue}let h={};i.lastIndex=0;let u;for(;(u=i.exec(c))!==null;)h[u[1]]=u[2];let g={index:parseInt(h.index||"0",10),text:st(h.text||""),resourceId:h["resource-id"]||"",className:h.class||"",packageName:h.package||"",contentDesc:st(h["content-desc"]||""),bounds:Fs(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:[]};r.push(g),o.length===0?n.push(g):o[o.length-1].children.push(g),l||o.push(g)}return{root:n,flat:r}}function vi(p){let e=[],t=[],s=[],i=p.length,n=0;for(;n<i;){let r=p.indexOf("<",n);if(r===-1)break;if(p.startsWith("<!--",r)){let S=p.indexOf("-->",r+4);n=S===-1?i:S+3;continue}if(p.startsWith("<?",r)){let S=p.indexOf("?>",r+2);n=S===-1?i:S+2;continue}if(p.startsWith("</",r)){let S=p.indexOf(">",r+2);if(S===-1)break;p.slice(r+2,S).trim()==="node"&&s.pop(),n=S+1;continue}let o=-1,a=null,d=!1;for(let S=r+1;S<i;S++){let b=p[S];if(a)b===a&&(a=null);else if(b==='"'||b==="'")a=b;else if(b===">"){o=S,p[S-1]==="/"&&(d=!0);break}}if(o===-1)break;let c=p.slice(r+1,d?o-1:o).trim();n=o+1;let l=0;for(;l<c.length&&!/\s/.test(c[l]);)l++;if(c.slice(0,l)!=="node")continue;let u={},g=l,f=c.length;for(;g<f;){for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let S=g;for(;g<f&&c[g]!=="="&&!/\s/.test(c[g]);)g++;let b=c.slice(S,g);for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f||c[g]!=="=")break;for(g++;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let m=c[g];if(m==='"'||m==="'"){g++;let v=g;for(;g<f&&c[g]!==m;)g++;u[b]=c.slice(v,g),g<f&&g++}else{let v=g;for(;g<f&&!/\s/.test(c[g]);)g++;u[b]=c.slice(v,g)}}let y={index:parseInt(u.index||"0",10),text:st(u.text||""),resourceId:u["resource-id"]||"",className:u.class||"",packageName:u.package||"",contentDesc:st(u["content-desc"]||""),bounds:Fs(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:[]};t.push(y),s.length===0?e.push(y):s[s.length-1].children.push(y),d||s.push(y)}return{root:e,flat:t}}function ue(p,e){if((e||E.parser?.mode||"regex")==="streaming")try{return vi(p)}catch{}return wi(p)}function ir(p,e){return p.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 xi=[/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 Se(p){if(p.resourceId&&/logbox/i.test(p.resourceId)||p.className&&/logbox/i.test(p.className))return!0;let e=`${p.text} ${p.contentDesc}`.trim();return!!xi.some(t=>t.test(e))}function _e(p){return p.filter(e=>Se(e)?!1:(e.className.includes("EditText")||e.className.includes("TextInputEditText")||e.focused&&e.clickable)&&e.bounds.width>0&&e.bounds.height>0)}function Ht(p){return p.className.includes("EditText")||p.className.includes("TextInputEditText")?!0:(p.children||[]).some(Ht)}function bt(p,e){let t=e?.width||E.screen.fallbackWidth,s=e?.height||E.screen.fallbackHeight,i=s*.08,n=s*.88,r=p.filter(a=>!Se(a)&&(a.className.includes("RecyclerView")||a.className.includes("ListView")||a.className.includes("ScrollView"))),o=[];for(let a of r)for(let d of a.children){if(Se(d)||d.bounds.centerY<i||d.bounds.centerY>n)continue;(d.clickable||d.children.some(l=>!Se(l)&&l.clickable&&l.bounds.width>t*.1))&&d.bounds.width>t*.08&&d.bounds.height>s*.02&&!Ht(d)&&o.push(d)}return o.length===0?p.filter(a=>{if(Se(a))return!1;let d=(a.text||a.contentDesc||"").trim();return d.length<=1||/^(remember me|forgot password|sign in|sign up|login|submit|cancel)$/i.test(d)?!1:a.clickable&&a.bounds.width>t*.14&&a.bounds.height>s*.033&&a.bounds.centerY>i&&a.bounds.centerY<n&&!a.className.includes("Button")&&!a.className.includes("EditText")&&!Ht(a)}):o}function Ge(p){return p.filter(e=>{if(Se(e)||!e.clickable||e.bounds.width===0||e.className.includes("EditText"))return!1;let t=e.className.includes("Button")||e.className.includes("ImageButton"),s=Ms.some(i=>z(i,e.text)||z(i,e.contentDesc)||z(i,e.resourceId));return t||s})}function Ut(p,e=E.screen.fallbackHeight,t){if(!p||p.length===0)return[];let s=p.find(u=>u.bounds.height>=e*.6&&u.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):E.screen.fallbackWidth,a=i+r*.78,d=p.filter(u=>Se(u)||t&&u.packageName&&!u.packageName.includes(t)||!u.clickable||u.bounds.width<=0||u.bounds.height<=0||!(u.bounds.centerY>=a||u.bounds.y2>=n-20)?!1:u.bounds.width>=o*.12&&u.bounds.width<=o*.55);if(d.length<=1)return d;let c=[];for(let u of d){let g=c.find(f=>Math.abs(f[0].bounds.centerY-u.bounds.centerY)<=30||Math.abs(f[0].bounds.y2-u.bounds.y2)<=20);g||(g=[],c.push(g)),g.push(u)}let l=c.map(u=>{u.sort((f,y)=>f.bounds.centerX-y.bounds.centerX);let g=[];for(let f of u)g.some(y=>Math.abs(y.bounds.centerX-f.bounds.centerX)<o*.08)||g.push(f);return g}).filter(u=>u.length<2||u.length>6?!1:u[u.length-1].bounds.x2-u[0].bounds.x1>=o*.6);return l.length===0?d.slice(0,5):(l.sort((u,g)=>g[0].bounds.centerY-u[0].bounds.centerY),l[0].slice(0,5))}function _s(p){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 p.filter(t=>{let s=`${t.text} ${t.contentDesc}`;return e.some(i=>i.test(s))})}var Ti=[/(?:\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],Ei=[/(?:\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],Pi=[/(?:\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 Ee(p,e,t=E.safety?.mode||"strict"){if(t==="disabled")return!1;let s=`${p.text} ${p.contentDesc} ${p.resourceId}`.trim();if((t==="moderate"?Ei:Ti).some(r=>r.test(s)))return!0;let n=e||E.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 Pe(p){let e=`${p.text} ${p.contentDesc} ${p.resourceId}`.trim();return Pi.some(t=>t.test(e))}function yt(p){for(let e of p){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 c of p){let l=`${c.text} ${c.contentDesc}`.trim();if(!r){let h=l.match(/\b([a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+)\b/);h&&(r=h[1])}/\b(?:at\s+|\()?[a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+/i.test(l)&&!o.includes(l)&&l.length<200&&o.push(l)}let a=p.find(c=>c.clickable&&c.bounds.width>0&&(/^(?:dismiss|close)$/i.test((c.text||"").trim())||/^(?:dismiss|close)$/i.test((c.contentDesc||"").trim())));if(!a&&!n){let l=p.filter(h=>h.clickable&&h.bounds.width>0&&h.bounds.height>0&&!/minimize|copy/i.test(`${h.text} ${h.contentDesc}`)).filter(h=>h.bounds.centerY>E.screen.fallbackHeight*.8);l.length>0&&(l.sort((h,u)=>h.bounds.x1-u.bounds.x1),a=l[0])}!a&&n&&(a=p.find(c=>c.clickable&&c.bounds.y1>=e.bounds.y1-20&&c.bounds.y2<=e.bounds.y2+20&&c.bounds.x1>=e.bounds.x2-120));let d=e.text||e.contentDesc||"React Native LogBox Console Overlay";return{type:"logbox",severity:i,node:e,errorText:d,sourceLocation:r,stackTrace:o.length>0?o:void 0,dismissButton:a,isToast:n}}if(e.resourceId.includes("alertTitle")&&(t.includes("isn't responding")||t.includes("has stopped"))){let i=p.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 it(p){return p.filter(e=>Se(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 Oe(p,e=E.screen.fallbackHeight,t=E.screen.fallbackWidth){let s=e*.22,i=/(?:menu|hamburger|drawer|navigation|\u2630|open[_\s-]*drawer)/i,n=p.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||p.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 a=r.bounds.x1<=t*.25,d=r.bounds.width<=250&&r.bounds.height<=250;return a&&d})||null}function Os(p,e=E.screen.fallbackHeight,t=E.screen.fallbackWidth){let s=e*.22;return p.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 Bs(p){return p.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 Hs(p,e=E.screen.fallbackWidth,t=E.screen.fallbackHeight,s=E.visual.overlapRatio){let i=[];for(let h of p)(h.text||h.clickable)&&h.bounds.width>0&&(h.bounds.x2>e+10&&h.bounds.x1<e&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows right screen boundary by ${h.bounds.x2-e}px`,elements:[h.text||h.contentDesc||h.className]}),h.bounds.y2>t+20&&h.bounds.y1<t&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows bottom screen boundary by ${h.bounds.y2-t}px`,elements:[h.text||h.contentDesc||h.className]}));let n=p.filter(h=>h.text&&h.text.trim().length>1&&h.bounds.width>0&&h.bounds.height>0),r=200,o=new Map;for(let h of n){let u=Math.floor(h.bounds.y1/r),g=Math.floor(h.bounds.y2/r);for(let f=u;f<=g;f++)o.has(f)||o.set(f,[]),o.get(f).push(h)}let a=new Set;for(let[,h]of o)for(let u=0;u<h.length;u++)for(let g=u+1;g<h.length;g++){let f=h[u],y=h[g];if(f===y||f.text===y.text)continue;let S=f.bounds.x1<y.bounds.x1?`${f.bounds.x1},${f.bounds.y1}:${y.bounds.x1},${y.bounds.y1}`:`${y.bounds.x1},${y.bounds.y1}:${f.bounds.x1},${f.bounds.y1}`;if(a.has(S))continue;a.add(S);let b=f.bounds,m=y.bounds;if(Math.abs(b.centerY-m.centerY)>(b.height+m.height)/2)continue;let v=Math.max(0,Math.min(b.x2,m.x2)-Math.max(b.x1,m.x1)),x=Math.max(0,Math.min(b.y2,m.y2)-Math.max(b.y1,m.y1)),D=v*x;if(D>0){let w=b.width*b.height,A=m.width*m.height,B=Math.min(w,A);B>0&&D/B>s&&i.push({type:"OVERLAP",severity:"WARN",description:`Visual text collision: "${f.text}" overlaps with "${y.text}" (${Math.round(D)}px\xB2 collision)`,elements:[f.text,y.text]})}}let d=p.filter(h=>(h.className.includes("ProgressBar")||h.className.includes("ActivityIndicator"))&&h.bounds.width>0);d.length>0&&i.push({type:"STALLED_LOADER",severity:"WARN",description:`Active loading indicator (${d[0].className}) detected on screen`,elements:d.map(h=>h.className)});let c=[],l=new Set;for(let h of i){let u=`${h.type}::${[...h.elements].sort().join("::")}`;l.has(u)||(l.add(u),c.push(h))}return c}function Yt(p,e,t){let s=e?.height||E.screen.fallbackHeight,i=e?.width||E.screen.fallbackWidth,n=Ut(p,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,a=p.filter(c=>{if(Se(c)||t&&c.packageName&&!c.packageName.includes(t))return!1;let l=c.className.includes("Tab")||c.resourceId.toLowerCase().includes("tab")||c.resourceId.toLowerCase().includes("header_tab")||/(?:tab\s*\d|\bphotos\b|\bvideos\b|\baudios\b)/i.test(`${c.text} ${c.contentDesc}`),h=c.bounds.centerY>=r&&c.bounds.centerY<=o,u=c.bounds.height>25&&c.bounds.height<=220;return(l||h)&&c.clickable&&c.bounds.width>50&&u});if(a.length>=2){let c=[];for(let h of a){let u=c.find(g=>Math.abs(g[0].bounds.centerY-h.bounds.centerY)<=20);u||(u=[],c.push(u)),u.push(h)}let l=c.find(h=>h.length>=2);if(l){l.sort((g,f)=>g.bounds.centerX-f.bounds.centerX);let h=[];for(let g of l)h.some(f=>Math.abs(f.bounds.centerX-g.bounds.centerX)<40)||h.push(g);if(!(h.length===2&&h[0].bounds.x1<=i*.25&&h[1].bounds.x2>=i*.75&&!h.some(g=>g.className.includes("Tab")||g.resourceId.toLowerCase().includes("tab")))&&h.length>=2)return{paradigm:"top_tabs",roots:h.slice(0,5)}}}let d=Oe(p,s,i);return d?{paradigm:"drawer",roots:[d]}:{paradigm:"single_hub",roots:[]}}function Us(p,e=2){if(p.length<=e)return p;let t=[];for(let i of p){let n=t.find(r=>{let o=r[0],a=o.className===i.className,d=Math.abs(o.bounds.width-i.bounds.width)<=30,c=Math.abs(o.bounds.height-i.bounds.height)<=30,l=Math.abs(o.bounds.x1-i.bounds.x1)<=30;return a&&d&&c&&l});n||(n=[],t.push(n)),n.push(i)}let s=[];for(let i of t)s.push(...i.slice(0,e));return s}function we(p,e=E.screen.fallbackHeight,t=E.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=a=>a.bounds.width>0&&a.bounds.height>0&&a.bounds.centerY<=i;for(let a of p){if(Se(a)||!o(a))continue;let d=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.trim();if(r.test(d)||d.length<=2&&/^[<‹«←x✕×\-]$/i.test(d))return a.clickable?a:p.find(l=>l.clickable&&l.bounds.x1<=a.bounds.x1&&l.bounds.x2>=a.bounds.x2&&l.bounds.y1<=a.bounds.y1&&l.bounds.y2>=a.bounds.y2&&l.bounds.width<=300&&l.bounds.height<=300)||a}for(let a of p){if(Se(a)||!o(a)||a.bounds.x1>n)continue;if(a.className.includes("ImageButton")||a.className.includes("ImageView")||a.className.includes("ViewGroup")&&a.bounds.width<=250&&a.bounds.height<=250){let c=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.toLowerCase();if(c.includes("back")||c.includes("up")||c.includes("arrow")||c.includes("chevron")||c.includes("nav")||c.includes("close")||c.includes("cancel"))return a.clickable?a:p.find(h=>h.clickable&&h.bounds.x1<=a.bounds.x1&&h.bounds.x2>=a.bounds.x2&&h.bounds.y1<=a.bounds.y1&&h.bounds.y2>=a.bounds.y2)||a}}if(s){let a=p.find(d=>{if(Se(d)||!o(d)||!d.clickable)return!1;let c=d.bounds.x1<=n,l=d.bounds.width<=250&&d.bounds.height<=250;return c&&l&&d.bounds.width<t*.4});if(a)return a}return null}import Le from"fs";import Be from"path";var rt=class{outputDir;steps=[];errorsDetected=[];startTime=new Date;packageName="Unknown";deviceId="Unknown";pendingWrites=[];formats=["json","md","junit","html"];videoPath;embedScreenshots=!1;screenshotBuffers=new Map;stepListeners=[];completeListeners=[];errorListeners=[];constructor(e,t){typeof e=="object"&&e!==null?(this.outputDir=e.outputDir||Be.resolve(process.cwd(),"output"),e.formats&&e.formats.length>0&&(this.formats=e.formats),this.embedScreenshots=!!e.embedScreenshots):(this.outputDir=e||Be.resolve(process.cwd(),"output"),t&&t.length>0&&(this.formats=t)),Le.existsSync(this.outputDir)||Le.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,a,d){let c=this.steps.length+1,l;if(r){this.embedScreenshots&&this.screenshotBuffers.set(c,r);let u=`step_${c}_${e.toLowerCase().replace(/[^a-z0-9]/g,"_")}.png`,g=Be.join(this.outputDir,u),f=Le.promises.writeFile(g,r).catch(y=>{console.error(`Warning: Failed to write screenshot ${u}:`,y)}).finally(()=>{let y=this.pendingWrites.indexOf(f);y!==-1&&this.pendingWrites.splice(y,1)});this.pendingWrites.push(f),l=u}let h={stepIndex:c,timestamp:new Date().toISOString(),phase:e,description:t,action:s,target:n,status:i,screenshotPath:l,durationMs:a,triageBundle:d,details:o};this.steps.push(h);for(let u of this.stepListeners)try{u(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={packageName:this.packageName,deviceId:this.deviceId,startTime:this.startTime.toISOString(),endTime:t.toISOString(),durationSeconds:s,totalSteps:this.steps.length,passedSteps:this.steps.filter(r=>r.status==="PASS").length,failedSteps:this.steps.filter(r=>r.status==="FAIL").length,skippedSteps:this.steps.filter(r=>r.status==="SKIPPED").length,warnSteps:this.steps.filter(r=>r.status==="WARN").length,errorsDetected:this.errorsDetected,videoPath:this.videoPath,steps:this.steps},n=e||"prompttest";if(this.formats.includes("json")){let r=Be.join(this.outputDir,`${n}-results.json`);await Le.promises.writeFile(r,JSON.stringify(i,null,2),"utf-8")}if(this.formats.includes("md")){let r=Be.join(this.outputDir,`${n}-report.md`),o=this.formatMarkdownReport(i);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("junit")){let r=Be.join(this.outputDir,`${n}-junit.xml`),o=this.formatJunitXml(i,n);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("html")){let r=Be.join(this.outputDir,`${n}-report.html`),o=this.formatHtmlReport(i,n);await Le.promises.writeFile(r,o,"utf-8")}for(let r of this.completeListeners)try{r(i)}catch{}return this.clearScreenshotBuffers(),i}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)}`,a=r.durationMs!==void 0?(r.durationMs/1e3).toFixed(3):"1.000";n.push(` <testcase classname="${this.escapeXml(t)}" name="${o}" time="${a}">`),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(`
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`)
|
|
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 un=Object.defineProperty;var hn=(a,e,t)=>()=>{if(t)throw t[0];try{return a&&(e=a(a=0)),e}catch(s){throw t=[s],s}};var gn=(a,e)=>{for(var t in e)un(a,t,{get:e[t],enumerable:!0})};var an={};gn(an,{buildFeedbackUrl:()=>oi,startFeedbackSession:()=>mr});import gr from"readline";import Ft from"os";import me from"chalk";function oi(a){let e=(a.message||"Feedback").split(`
|
|
8
|
+
`)[0].trim(),t=e.length>70?e.substring(0,67)+"...":e,s=a.rating?"\u2B50".repeat(a.rating):"";if(a.category==="feature"){let n=new URLSearchParams;return n.set("template","2_feature_request.yml"),n.set("title",`[Feature]: ${t}`),n.set("problem",`User feedback submission${s?` (${s} ${a.rating}/5)`:""}:
|
|
9
|
+
${a.message}`),n.set("proposed_solution",a.message),n.set("category","Plain-English DSL / Syntax"),`${ni}/issues/new?${n.toString()}`}if(a.category==="bug"){let n=new URLSearchParams;return n.set("template","1_bug_report.yml"),n.set("title",`[Bug]: ${t}`),n.set("description",a.message),n.set("command_run","npx prompttest"),n.set("environment",`${Ft.type()} ${Ft.release()} (${Ft.arch()}), Node: ${process.version}`),`${ni}/issues/new?${n.toString()}`}let i=new URLSearchParams;i.set("template","3_feedback.yml");let r=a.rating?` ${"\u2B50".repeat(a.rating)}`:"";if(i.set("title",`[Feedback${r}]: ${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",`${Ft.type()} ${Ft.release()} (${Ft.arch()}), Node: ${process.version}`),`${ni}/issues/new?${i.toString()}`}function ri(a,e){return new Promise(t=>{if(a.closed){t("");return}try{a.question(e,s=>{t(s.trim())})}catch{t("")}})}async function mr(a={}){let e=a.input||process.stdin,t=a.output||process.stdout,s=(r="")=>{t.write(r+`
|
|
10
|
+
`)};if(a.directMessage&&a.directMessage.trim()){let r=a.category||"general",n=oi({category:r,message:a.directMessage.trim()});return s(me.bold.cyan(`
|
|
11
|
+
\u26A1 PromptTest \u2014 Community Feedback`)),s(me.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(me.green("\u2714 Thank you for your feedback! Here is your 1-click submission link:")),s(me.bold.underline.cyan(n)),s(me.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
|
|
12
|
+
`)),n}let i=gr.createInterface({input:e,output:t});try{s(me.bold.cyan(`
|
|
13
|
+
\u26A1 PromptTest \u2014 Community Feedback & Suggestions`)),s(me.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(me.white("We want to make PromptTest the best mobile QA engine in your toolchain.")),s(me.white(`Your feedback goes directly to our open community tracker!
|
|
14
|
+
`)),s(me.bold.white("How would you rate your experience with PromptTest?")),s(` ${me.cyan("[1]")} \u2B50\u2B50\u2B50\u2B50\u2B50 (5/5) \u2014 Loving it!`),s(` ${me.cyan("[2]")} \u2B50\u2B50\u2B50\u2B50 (4/5) \u2014 Great, but needs minor improvements`),s(` ${me.cyan("[3]")} \u2B50\u2B50\u2B50 (3/5) \u2014 Okay, encountered some friction`),s(` ${me.cyan("[4]")} \u2B50\u2B50 (2/5) \u2014 Frustrating / missing key features`),s(` ${me.cyan("[5]")} \u2B50 (1/5) \u2014 Not working for me`);let r=await ri(i,me.bold.cyan(`
|
|
15
|
+
Select rating [1-5] (default: 1): `)),n=parseInt(r,10),c={1:5,2:4,3:3,4:2,5:1}[n]||5;s(me.bold.white(`
|
|
16
|
+
What type of feedback would you like to share?`)),s(` ${me.cyan("[1]")} \u{1F4A1} Feature Request or syntax suggestion`),s(` ${me.cyan("[2]")} \u{1F41B} Bug report or unexpected error`),s(` ${me.cyan("[3]")} \u{1F4AC} General feedback, question, or compliment`);let l=await ri(i,me.bold.cyan(`
|
|
17
|
+
Select category [1-3] (default: 1): `)),p="feature";l==="2"?p="bug":l==="3"&&(p="general"),s(me.bold.white(`
|
|
18
|
+
Please share your thoughts, ideas, or feedback:`));let h=await ri(i,me.bold.cyan("> "))||"Overall great experience with PromptTest!",u=oi({rating:c,category:p,message:h});return s(me.gray(`
|
|
19
|
+
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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(me.green.bold("\u2728 Thank you! We generated your 1-click submission:")),s(me.bold.underline.cyan(u)),s(me.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
|
|
20
|
+
`)),u}finally{try{i.close()}catch{}}}var ni,ai=hn(()=>{"use strict";ni="https://github.com/shriramsingh/prompttest-community"});import Ye from"fs";import Ie from"path";import V from"chalk";import{spawn as Pt}from"child_process";import ds from"readline";var xe={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",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 mn(){let a=process.env.PROMPTTEST_SETTLE_FACTOR;if(!a)return 1;let e=parseFloat(a);return isNaN(e)||e<=0?1:e}function Le(a,e=50){return Math.max(e,Math.round(a*mn()))}var C={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 Le(500)},get backMs(){return Le(700)},get launchMs(){return Le(2500)},get stopMs(){return Le(600)},get keyboardDismissMs(){return Le(500)},get scrollMs(){return Le(350)},get toggleMs(){return Le(350)},get selectMs(){return Le(600)},get inputFocusMs(){return Le(250)},get inputClearMs(){return Le(150)},get inputDoneMs(){return Le(350)},get submitWaitMs(){return Le(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"};function ui(a=C.polling.intervalMs,e=C.polling.jitterMs){return Math.round(a+(Math.random()*2-1)*(e/2))}var cs=(r=>(r[r.SUCCESS=0]="SUCCESS",r[r.TEST_FAILED=1]="TEST_FAILED",r[r.DEVICE_UNAVAILABLE=2]="DEVICE_UNAVAILABLE",r[r.CONFIG_ERROR=3]="CONFIG_ERROR",r[r.LOCKED=4]="LOCKED",r))(cs||{}),Je=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)}},mt=class extends Je{constructor(e,t="Device"){super(e,2,t),this.name="DeviceError"}},rs=class extends Je{target;candidateMatches;constructor(e,t,s,i="Locator"){super(e,1,i),this.name="LocatorError",this.target=t,this.candidateMatches=s}},os=class extends Je{constructor(e,t="Config"){super(e,3,t),this.name="ConfigError"}},as=class extends Je{serial;constructor(e,t,s="Lock"){super(e,4,s),this.name="LockError",this.serial=t}},_t=class extends Je{cycle;constructor(e,t,s="SpecLoader"){super(e,3,s),this.name="SpecRecursionError",this.cycle=t}};import Pe from"fs";import Ee from"path";import hi from"os";import fn from"https";import bn from"http";import yn from"readline";import{execSync as ls,spawnSync as Sn}from"child_process";var Ce=null;function Xe(){if(Ce)return Ce;if(process.env.PROMPTTEST_ADB_PATH&&Pe.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=[Ee.join(Ee.dirname(process.execPath),"platform-tools",e),Ee.join(Ee.dirname(process.execPath),e),Ee.join(process.cwd(),"platform-tools",e),Ee.join(process.cwd(),"dist","bin","platform-tools",e)];for(let o of t)if(Pe.existsSync(o))return Ce=o,Ce;try{let c=ls(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(Pe.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=Ee.join(o,"platform-tools",e);if(Pe.existsSync(c))return Ce=c,Ce}let i=[],r=hi.homedir();if(a){let o=process.env.LOCALAPPDATA||Ee.join(r,"AppData","Local");i.push(Ee.join(o,"Android","Sdk","platform-tools","adb.exe"));let c=process.env.ProgramFiles||"C:\\Program Files";i.push(Ee.join(c,"Android","platform-tools","adb.exe"))}else process.platform==="darwin"?(i.push(Ee.join(r,"Library","Android","sdk","platform-tools","adb")),i.push("/opt/homebrew/bin/adb"),i.push("/usr/local/bin/adb")):(i.push(Ee.join(r,"Android","Sdk","platform-tools","adb")),i.push("/usr/bin/adb"),i.push("/usr/local/bin/adb"));for(let o of i)if(Pe.existsSync(o))return Ce=o,Ce;let n=Ee.join(r,".prompttest","platform-tools",e);return Pe.existsSync(n)?(Ce=n,Ce):(Ce="adb",Ce)}function wn(a){let e=a||Xe();try{let t=Sn(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 vn(){Ce=null}function xn(a,e){return new Promise((t,s)=>{let i=Pe.createWriteStream(e);function r(n){(n.startsWith("https")?fn:bn).get(n,c=>{if(c.statusCode&&c.statusCode>=300&&c.statusCode<400&&c.headers.location)return r(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=>{Pe.unlink(e,()=>{}),s(c)})}r(a)})}async function Tn(a){let e=hi.homedir(),t=a||Ee.join(e,".prompttest","platform-tools");Pe.mkdirSync(t,{recursive:!0});let s=process.platform==="win32",i=process.platform==="darwin",r=s?"adb.exe":"adb",n=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=Ee.join(t,`platform-tools-download-${Date.now()}.zip`),c=Ee.join(t,`extract-tmp-${Date.now()}`);try{await xn(n,o),Pe.mkdirSync(c,{recursive:!0}),s?ls(`powershell -NoProfile -Command "Expand-Archive -Path '${o}' -DestinationPath '${c}' -Force"`,{stdio:"ignore",timeout:6e4}):ls(`unzip -q -o "${o}" -d "${c}"`,{stdio:"ignore",timeout:6e4});let l=Ee.join(c,"platform-tools"),p=Pe.existsSync(l)?l:c,d=Pe.readdirSync(p);for(let u of d){let m=Ee.join(p,u),y=Ee.join(t,u);Pe.copyFileSync(m,y)}let h=Ee.join(t,r);if(!s&&Pe.existsSync(h))try{Pe.chmodSync(h,493)}catch{}return vn(),Ce=h,h}finally{try{Pe.existsSync(o)&&Pe.unlinkSync(o),Pe.existsSync(c)&&Pe.rmSync(c,{recursive:!0,force:!0})}catch{}}}async function En(){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=yn.createInterface({input:process.stdin,output:process.stdout});console.log(`
|
|
21
|
+
\u26A0\uFE0F Android Debug Bridge (ADB) was not found on your system.
|
|
22
|
+
PromptTest requires ADB to communicate with physical or emulated Android devices.
|
|
23
|
+
|
|
24
|
+
Would you like PromptTest to download Google's official
|
|
25
|
+
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 gi(a={}){if(wn())return Xe();if(a.skipPrompt?!0:await En()){console.log(`
|
|
26
|
+
\u2B07\uFE0F Downloading official Google platform-tools (ADB)...`);let t=await Tn();return console.log(`\u2714 ADB successfully provisioned and ready: ${t}
|
|
27
|
+
`),t}throw new mt(`Android Debug Bridge (ADB) not found on this system.
|
|
28
|
+
To resolve:
|
|
29
|
+
1. Re-run with --download-adb to automatically download Google's official platform-tools.
|
|
30
|
+
2. Install Android Studio: https://developer.android.com/studio
|
|
31
|
+
3. Set custom ADB path via: export PROMPTTEST_ADB_PATH="C:\\path\\to\\adb.exe"
|
|
32
|
+
`)}function Pn(a,e,t,s){let i={},r=a.match(/level:\s*(\d+)/i),n=a.match(/temperature:\s*(\d+)/i),o=a.match(/status:\s*(\d+)/i);(r||n||o)&&(i.battery={...r?{level:Number(r[1])}:{},...n?{temperatureC:Number(n[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),h=t.match(/Native Heap:\s*(\d+)/i),m=[...(t.match(/Total PSS by category:\s*([\s\S]*?)(?:\n\s*\n|Total RAM:|$)/i)?.[1]||"").matchAll(/^\s*([\d,]+)K:\s*(.+)$/gim)],y=m.reduce((E,D)=>E+Number(D[1].replace(/,/g,"")),0),v=m.find(E=>/native/i.test(E[2]));(p||d||h||y)&&(i.memory={...p?{pssKb:Number(p[1].replace(/,/g,""))}:y?{pssKb:y}:{},...d?{privateDirtyKb:Number(d[1])}:{},...h?{nativeHeapKb:Number(h[1])}:v?{nativeHeapKb:Number(v[1].replace(/,/g,""))}:{}});let T=s.match(/Total frames rendered:\s*(\d+)/i),S=s.match(/Janky frames:\s*(\d+)/i),b=s.match(/90th percentile:\s*([\d.]+)\s*ms/i);return(T||S||b)&&(i.graphics={...T?{framesRendered:Number(T[1])}:{},...S?{jankyFrames:Number(S[1])}:{},...b?{percentile90Ms:Number(b[1])}:{}}),i}var tt=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),r=i.match(/(?:Physical|Override)\s*size:\s*(\d+)x(\d+)/i);if(r){let n={width:parseInt(r[1],10),height:parseInt(r[2],10)};return this.cachedDimensions.set(t,n),n}}catch{}let s={width:C.screen.fallbackWidth,height:C.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 r=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e],n=await gi();return new Promise((o,c)=>{let l=Pt(n,r),p="",d="",h=!1,u=setTimeout(()=>{h=!0;try{l.kill("SIGKILL")}catch{}c(new Error(`ADB command timed out after ${s}ms: adb ${r.join(" ")}`))},s);l.stdout.on("data",m=>{p+=m.toString("utf-8")}),l.stderr.on("data",m=>{d+=m.toString("utf-8")}),l.on("close",m=>{clearTimeout(u),!h&&(m===0?o({stdout:p,stderr:d}):c(new Error(`ADB command failed (code ${m}): adb ${r.join(" ")}
|
|
33
|
+
Error: ${d}`)))}),l.on("error",m=>{clearTimeout(u),!h&&c(m)})})}async execAdb(e,t,s=C.adb.commandTimeoutMs,i=C.device.maxDeviceRetries){let r;for(let n=0;n<=i;n++)try{return await this.execAdbInternal(e,t,s)}catch(o){r=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(n>=i||!d||this.isGlobalAdbCommand(e[0]))throw p?new mt(`Target Android device ${t||this.defaultSerial||""} is offline or disconnected: ${c}`):o;if(C.device.autoReconnect&&p)try{await this.execAdbInternal(["reconnect"],t,5e3).catch(()=>{})}catch{}await new Promise(h=>setTimeout(h,C.adb.retryBaseDelayMs*Math.pow(2,n+1)))}throw r||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 r=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((n,o)=>{let c=Pt(Xe(),r),l=[],p="",d=!1,h=setTimeout(()=>{d=!0;try{c.kill("SIGKILL")}catch{}o(new Error(`ADB binary command timed out after ${s}ms: adb ${r.join(" ")}`))},s);c.stdout.on("data",u=>l.push(Buffer.from(u))),c.stderr.on("data",u=>{p+=u.toString("utf-8")}),c.on("close",u=>{clearTimeout(h),!d&&(u===0?n(Buffer.concat(l)):o(new Error(`ADB binary command failed (code ${u}): adb ${r.join(" ")}
|
|
34
|
+
${p}`)))}),c.on("error",u=>{clearTimeout(h),!d&&o(u)})})}async getConnectedDevices(){let{stdout:e}=await this.execAdb(xe.DEVICES),t=e.split(`
|
|
35
|
+
`).map(o=>o.trim()).filter(Boolean),s=t.findIndex(o=>o.toLowerCase().includes("list of devices attached")),i=s!==-1?t.slice(s+1):t,r=[];return r=(o=>{let c=[];for(let l of o){if(!l||l.startsWith("*")||l.toLowerCase().includes("list of devices"))continue;let p=l.split(/\s+/);if(p.length>=2){let d=p[0],h=p[1],u,m;for(let y of p.slice(2))y.startsWith("model:")&&(u=y.replace("model:","")),y.startsWith("product:")&&(m=y.replace("product:",""));c.push({serial:d,state:h,model:u,product:m})}}return c})(i),r}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:r}=await this.execAdb(["shell","getprop","ro.product.model"],e),n=r.trim();if(n)return n}catch{}let t=await this.getConnectedDevices(),s=e||this.defaultSerial;return t.find(r=>r.serial===s)?.model||s||"Android Device"}async captureScreenshot(e){return this.execAdbBinary(xe.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:r}=await this.execAdb(xe.UIAUTOMATOR_DUMP,e,1e4,0),n=r.indexOf("<hierarchy");return n>=0?r.slice(n):r}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:r}=await this.execAdb(xe.FOREGROUND_APP,e).catch(()=>({stdout:""})),n=r.matchAll(/(?:mCurrentFocus|mFocusedWindow|mFocusedApp|topResumedActivity|mResumedActivity|mFocusedActivity)[=:\s]+(?:Window\{[^}]*?\s+|ActivityRecord\{[^}]*?\s+|AppWindowToken\{[^}]*?\s+)?([a-zA-Z0-9._]+)\//gi);for(let o of n)if(o&&o[1]&&!t(o[1]))return o[1]}catch{}return null}async tap(e,t,s){await this.execAdb(xe.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(xe.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 r=i.replace(/([\\"'&<>()|$;#*?~`%])/g,"\\$1");await this.execAdb(["shell","input","text",r],t).catch(()=>{})}}}async pressKey(e,t){await this.execAdb(xe.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 r=Array(Math.max(30,Math.floor(t/2))).fill("112");await this.execAdb(["shell","input","keyevent",...r],e).catch(()=>{})}async swipe(e,t,s,i,r=300,n){await this.execAdb(xe.INPUT_SWIPE(e,t,s,i,r),n)}async launchApp(e,t){try{let{stdout:s}=await this.execAdb(["shell","cmd","package","resolve-activity","--brief",e],t),r=(s||"").split(`
|
|
36
|
+
`).map(n=>n.trim()).find(n=>n.includes("/")&&!n.includes(" "));if(r){await this.execAdb(["shell","am","start","-n",r],t);return}}catch{}await this.execAdb(xe.LAUNCH_APP(e),t)}async forceStop(e,t){await this.execAdb(xe.FORCE_STOP(e),t)}async clearAppData(e,t){await this.execAdb(xe.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(xe.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){await this.execAdb(xe.INSTALL_APK(e),t)}async uninstallApp(e,t){await this.execAdb(xe.UNINSTALL_APP(e),t)}async openDeepLink(e,t){await this.execAdb(xe.DEEP_LINK(e),t)}async checkCrashes(e,t){try{let{stdout:s}=await this.execAdb(xe.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(xe.CLEAR_CRASH_LOGS(),e)}catch{}}async getDeviceIp(e){try{let{stdout:t}=await this.execAdb(xe.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,r=t;if(e&&e.includes(":")){let d=e.split(":");i=d[0],r=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 n=`${i}:${r}`;if(e)try{let{stdout:d,stderr:h}=await this.execAdb(xe.CONNECT(n)),u=`${d} ${h}`.trim();if(u.toLowerCase().includes("connected")||u.toLowerCase().includes("already"))return this.defaultSerial=n,{success:!0,target:n,message:u}}catch{}try{await this.execAdb(xe.TCPIP(r),s),await new Promise(d=>setTimeout(d,1e3))}catch{}let{stdout:o,stderr:c}=await this.execAdb(xe.CONNECT(n)),l=`${o} ${c}`.trim(),p=l.toLowerCase().includes("connected")||l.toLowerCase().includes("already");return p&&(this.defaultSerial=n),{success:p,target:n,message:l}}async disconnectWifi(e){let{stdout:t,stderr:s}=await this.execAdb(xe.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]),r=`${s} ${i}`.trim();return{success:/successfully paired|already paired/i.test(r),message:r}}async getDeviceMetrics(e){let[s,i,r,n]=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}
|
|
37
|
+
${(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 Pn(s,i,r,n)}streamLogcatEvents(e,t){let s=["-s",e,"shell","logcat","-b","events","-v","time"],i=Pt(Xe(),s),r=ds.createInterface({input:i.stdout});return r.on("line",t),i.on("close",()=>{try{r.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=Pt(Xe(),s),r=ds.createInterface({input:i.stdout});return r.on("line",t),i.on("close",()=>{try{r.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatToasts(e,t){let s=["-s",e,"shell","logcat","-s","Toast:D","Snackbar:D","-v","time"],i=Pt(Xe(),s),r=ds.createInterface({input:i.stdout});return r.on("line",t),i.on("close",()=>{try{r.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],r=Pt(Xe(),i);return r.on("error",()=>{}),{remotePath:e,process:r}}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{}}},ke=new tt;var fi=/^(\d+(?:\.\d+)*\.?|\-|\*)\s*/;function bi(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 re=`(?:"([^"]+)"|'([^']+)'|([^'"\\s][^'"]*?[^'"\\s]|\\S))`;function ae(a){for(let e of a)if(e!=null&&e.trim().length>0)return e.trim();return""}function ft(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 r=parseInt(i,10)||0;return new Date(Date.now()+r*864e5).toISOString().slice(0,10)}),t=t.replace(/\$RANDOM_INT\((\d+),\s*(\d+)\)/g,(s,i,r)=>{let n=parseInt(i,10),o=parseInt(r,10);return String(Math.floor(n+Math.random()*(o-n+1)))}),t}var G={TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:button\\s+|item\\s+)?${re}$`,"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+)?${re}$`,"i"),PROXIMITY_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+${re}\\s+(?:next\\s+to|near|beside|inside|for)\\s+${re}$`,"i"),CLEAR:new RegExp(`^(?:clear|empty)(?:\\s+(?:text\\s+(?:in|of)|field|input))?\\s+${re}$`,"i"),LONG_PRESS:new RegExp(`^(?:long\\s+press|press\\s+and\\s+hold)\\s+(?:button\\s+|item\\s+)?${re}$`,"i"),TYPE:new RegExp(`^(?:type|enter|input)\\s+${re}\\s+(?:in|into)\\s+${re}$`,"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+)?${re}\\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+${re}$`,"i"),SCROLL:/^(?:scroll|swipe)\s+(down|up)$/i,DIRECTIONAL_SWIPE:new RegExp(`^(?:swipe|scroll)\\s+(left|right|up|down)(?:\\s+on\\s+${re})?$`,"i"),TOGGLE:new RegExp(`^(?:toggle|turn\\s+(on|off)|check|uncheck)\\s+(?:checkbox\\s+|switch\\s+)?${re}$`,"i"),SELECT_DROPDOWN:new RegExp(`^(?:select|choose)\\s+${re}\\s+from\\s+${re}$`,"i"),LAUNCH_APP:new RegExp(`^(?:launch|open)\\s+(?:app\\s+)?${re}$`,"i"),RESTART_APP:new RegExp(`^(?:restart|relaunch)\\s+(?:app\\s+)?${re}$`,"i"),TERMINATE_APP:new RegExp(`^(?:terminate|close|force\\s*stop)\\s+(?:app\\s+)?(?:${re})?$`,"i"),CLEAR_DATA:new RegExp(`^(?:clear\\s+(?:app\\s+)?data\\s+(?:for\\s+)?|reset\\s+app\\s+)${re}$`,"i"),GRANT_PERMISSION:new RegExp(`^grant\\s+permissions?\\s+${re}(?:\\s+(?:to|for)\\s+${re})?$`,"i"),DEEP_LINK:new RegExp(`^(?:open\\s+deep\\s*link|navigate\\s+to\\s+url)\\s+${re}$`,"i"),WAIT:/^wait\s+(\d+)\s*(?:s|sec|seconds|ms)?$/i,WAIT_UNTIL:new RegExp(`^(?:wait\\s+until|wait\\s+for)\\s+${re}\\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+)?${re}\\s+(?:is\\s+)?(visible|present|exists|appears?)|element\\s+${re}\\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+)?${re}$`,"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+${re}$`,"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+${re})?$`,"i"),API_REQUEST:new RegExp(`^(?:api|call\\s+api)\\s+(GET|POST|PUT|DELETE|PATCH)\\s+${re}(?:\\s+with\\s+body\\s+${re})?(?:\\s+store\\s+${re}\\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+${re}\\s+with\\s+subject\\s+${re}(?:\\s+contains\\s+${re})?$`,"i"),OPTIONAL_SUFFIX:/\s*\((?:optional|if\s+present|maybe)\)\s*$/i,FALLBACK_QUOTED_TAP:/^(?:tap|click)\s+.*?['"]([^'"]+)['"]/i},Ht={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 kt(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 oe(a){return kt(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 mi=new Map;function pe(a,e){if(!a||!e)return!1;let t=oe(a),s=oe(e);if(t.length<=3){let i=mi.get(t);if(!i){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(`(?:^|\\b)${r}(?:\\b|$)`,"i"),mi.set(t,i)}return i.test(s)}return s.includes(t)}var yi=["sign in","signin","login","log in","submit","save","continue","next","done","send","confirm","proceed","post","rate","enter","join","apply","update"],Si=["sign in","signin","login","log in","submit","save","next","continue","done","like","fav","favorite","star","bookmark","add","post","confirm","apply","explore","search","filter"];function kn(a,e){let t=oe(a),s=oe(e),i=t.length,r=s.length;if(i===0)return r;if(r===0)return i;let n=Array.from({length:r+1},(c,l)=>l),o=new Array(r+1);for(let c=1;c<=i;c++){o[0]=c;for(let p=1;p<=r;p++){let d=t[c-1]===s[p-1]?0:1;o[p]=Math.min(n[p]+1,o[p-1]+1,n[p-1]+d)}let l=n;n=o,o=l}return n[r]}function Dn(a,e){let t=oe(a),s=oe(e);if(t===s)return 1;if(!t||!s)return 0;let i=Math.max(t.length,s.length);return 1-kn(t,s)/i}function bt(a,e,t=3,s=.35){return Array.from(new Set(e.map(n=>n.trim()).filter(n=>n.length>0))).map(n=>({text:n,score:Dn(a,n)})).filter(n=>n.score>=s).sort((n,o)=>o.score-n.score).slice(0,t)}function wi(a){let e=a.match(Ht.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),r=parseInt(e[4],10);return{x1:t,y1:s,x2:i,y2:r,width:i-t,height:r-s,centerX:Math.round((t+i)/2),centerY:Math.round((s+r)/2)}}function An(a){let e=a.match(Ht.HIERARCHY_ROOT);if(!e)return{root:[],flat:[]};let t=e[1],s=new RegExp(Ht.NODE_TAG.source,"gi"),i=new RegExp(Ht.ATTR_KEY_VALUE.source,"g"),r=[],n=[],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 h={};i.lastIndex=0;let u;for(;(u=i.exec(p))!==null;)h[u[1]]=u[2];let m={index:parseInt(h.index||"0",10),text:kt(h.text||""),resourceId:h["resource-id"]||"",className:h.class||"",packageName:h.package||"",contentDesc:kt(h["content-desc"]||""),bounds:wi(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:[]};n.push(m),o.length===0?r.push(m):o[o.length-1].children.push(m),d||o.push(m)}return{root:r,flat:n}}function $n(a){let e=[],t=[],s=[],i=a.length,r=0;for(;r<i;){let n=a.indexOf("<",r);if(n===-1)break;if(a.startsWith("<!--",n)){let T=a.indexOf("-->",n+4);r=T===-1?i:T+3;continue}if(a.startsWith("<?",n)){let T=a.indexOf("?>",n+2);r=T===-1?i:T+2;continue}if(a.startsWith("</",n)){let T=a.indexOf(">",n+2);if(T===-1)break;a.slice(n+2,T).trim()==="node"&&s.pop(),r=T+1;continue}let o=-1,c=null,l=!1;for(let T=n+1;T<i;T++){let S=a[T];if(c)S===c&&(c=null);else if(S==='"'||S==="'")c=S;else if(S===">"){o=T,a[T-1]==="/"&&(l=!0);break}}if(o===-1)break;let p=a.slice(n+1,l?o-1:o).trim();r=o+1;let d=0;for(;d<p.length&&!/\s/.test(p[d]);)d++;if(p.slice(0,d)!=="node")continue;let u={},m=d,y=p.length;for(;m<y;){for(;m<y&&/\s/.test(p[m]);)m++;if(m>=y)break;let T=m;for(;m<y&&p[m]!=="="&&!/\s/.test(p[m]);)m++;let S=p.slice(T,m);for(;m<y&&/\s/.test(p[m]);)m++;if(m>=y||p[m]!=="=")break;for(m++;m<y&&/\s/.test(p[m]);)m++;if(m>=y)break;let b=p[m];if(b==='"'||b==="'"){m++;let E=m;for(;m<y&&p[m]!==b;)m++;u[S]=p.slice(E,m),m<y&&m++}else{let E=m;for(;m<y&&!/\s/.test(p[m]);)m++;u[S]=p.slice(E,m)}}let v={index:parseInt(u.index||"0",10),text:kt(u.text||""),resourceId:u["resource-id"]||"",className:u.class||"",packageName:u.package||"",contentDesc:kt(u["content-desc"]||""),bounds:wi(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:[]};t.push(v),s.length===0?e.push(v):s[s.length-1].children.push(v),l||s.push(v)}return{root:e,flat:t}}function we(a,e){if((e||C.parser?.mode||"regex")==="streaming")try{return $n(a)}catch{}return An(a)}function jr(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 Cn=[/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 Me(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!!Cn.some(t=>t.test(e))}function ze(a){return a.filter(e=>Me(e)?!1:(e.className.includes("EditText")||e.className.includes("TextInputEditText")||e.focused&&e.clickable)&&e.bounds.width>0&&e.bounds.height>0)}function ps(a){return a.className.includes("EditText")||a.className.includes("TextInputEditText")?!0:(a.children||[]).some(ps)}function Bt(a,e){let t=e?.width||C.screen.fallbackWidth,s=e?.height||C.screen.fallbackHeight,i=s*.08,r=s*.88,n=a.filter(c=>!Me(c)&&(c.className.includes("RecyclerView")||c.className.includes("ListView")||c.className.includes("ScrollView"))),o=[];for(let c of n)for(let l of c.children){if(Me(l)||l.bounds.centerY<i||l.bounds.centerY>r)continue;(l.clickable||l.children.some(d=>!Me(d)&&d.clickable&&d.bounds.width>t*.1))&&l.bounds.width>t*.08&&l.bounds.height>s*.02&&!ps(l)&&o.push(l)}return o.length===0?a.filter(c=>{if(Me(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<r&&!c.className.includes("Button")&&!c.className.includes("EditText")&&!ps(c)}):o}function Qe(a){return a.filter(e=>{if(Me(e)||!e.clickable||e.bounds.width===0||e.className.includes("EditText"))return!1;let t=e.className.includes("Button")||e.className.includes("ImageButton"),s=Si.some(i=>pe(i,e.text)||pe(i,e.contentDesc)||pe(i,e.resourceId));return t||s})}function Ut(a,e=C.screen.fallbackHeight,t){if(!a||a.length===0)return[];let s=a.find(u=>u.bounds.height>=e*.6&&u.bounds.y1<=e*.15),i=s?.bounds?.y1!==void 0&&s.bounds.y1>=0?s.bounds.y1:0,r=s?.bounds?.y2&&s.bounds.y2>i?s.bounds.y2:e,n=r-i,o=s?.bounds?.x2&&s.bounds.x2>0?s.bounds.x2-(s.bounds.x1||0):C.screen.fallbackWidth,c=i+n*.78,l=a.filter(u=>Me(u)||t&&u.packageName&&!u.packageName.includes(t)||!u.clickable||u.bounds.width<=0||u.bounds.height<=0||!(u.bounds.centerY>=c||u.bounds.y2>=r-20)?!1:u.bounds.width>=o*.12&&u.bounds.width<=o*.55);if(l.length<=1)return l;let p=[];for(let u of l){let m=p.find(y=>Math.abs(y[0].bounds.centerY-u.bounds.centerY)<=30||Math.abs(y[0].bounds.y2-u.bounds.y2)<=20);m||(m=[],p.push(m)),m.push(u)}let d=p.map(u=>{u.sort((y,v)=>y.bounds.centerX-v.bounds.centerX);let m=[];for(let y of u)m.some(v=>Math.abs(v.bounds.centerX-y.bounds.centerX)<o*.08)||m.push(y);return m}).filter(u=>u.length<2||u.length>6?!1:u[u.length-1].bounds.x2-u[0].bounds.x1>=o*.6);return d.length===0?l.slice(0,5):(d.sort((u,m)=>m[0].bounds.centerY-u[0].bounds.centerY),d[0].slice(0,5))}function vi(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 In=[/(?:\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],Nn=[/(?:\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],Ln=[/(?:\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 Be(a,e,t=C.safety?.mode||"strict"){if(t==="disabled")return!1;let s=`${a.text} ${a.contentDesc} ${a.resourceId}`.trim();if((t==="moderate"?Nn:In).some(n=>n.test(s)))return!0;let r=e||C.safety?.customBlacklist||[];for(let n of r)if(typeof n=="string"&&n.length>0){if(s.toLowerCase().includes(n.toLowerCase()))return!0}else if(n instanceof RegExp&&n.test(s))return!0;return!1}function Ue(a){let e=`${a.text} ${a.contentDesc} ${a.resourceId}`.trim();return Ln.some(t=>t.test(e))}function jt(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 r=e.resourceId.includes("notification")||e.bounds.height>0&&e.bounds.height<250,n,o=[];for(let p of a){let d=`${p.text} ${p.contentDesc}`.trim();if(!n){let h=d.match(/\b([a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+)\b/);h&&(n=h[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&&!r){let d=a.filter(h=>h.clickable&&h.bounds.width>0&&h.bounds.height>0&&!/minimize|copy/i.test(`${h.text} ${h.contentDesc}`)).filter(h=>h.bounds.centerY>C.screen.fallbackHeight*.8);d.length>0&&(d.sort((h,u)=>h.bounds.x1-u.bounds.x1),c=d[0])}!c&&r&&(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:n,stackTrace:o.length>0?o:void 0,dismissButton:c,isToast:r}}if(e.resourceId.includes("alertTitle")&&(t.includes("isn't responding")||t.includes("has stopped"))){let i=a.find(r=>r.text.toLowerCase().includes("close app")||r.text.toLowerCase().includes("ok"));return{type:"anr",severity:"error",node:e,errorText:e.text||"Application Not Responding (ANR)",dismissButton:i}}}return null}function Dt(a){return a.filter(e=>Me(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 st(a,e=C.screen.fallbackHeight,t=C.screen.fallbackWidth){let s=e*.22,i=/(?:menu|hamburger|drawer|navigation|\u2630|open[_\s-]*drawer)/i,r=a.find(n=>{if(!n.clickable||n.bounds.width===0||n.bounds.centerY>s)return!1;let o=`${n.contentDesc} ${n.text} ${n.resourceId}`;return i.test(o)});return r||a.find(n=>{if(!n.clickable||n.bounds.width===0||n.bounds.height===0||n.bounds.centerY>s||(n.text||n.contentDesc||"").trim().length>0)return!1;let c=n.bounds.x1<=t*.25,l=n.bounds.width<=250&&n.bounds.height<=250;return c&&l})||null}function xi(a,e=C.screen.fallbackHeight,t=C.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 r=i.bounds.x2>=t*.75,n=i.bounds.width<=250&&i.bounds.height<=250;return r&&n})}function Ti(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 Ei(a,e=C.screen.fallbackWidth,t=C.screen.fallbackHeight,s=C.visual.overlapRatio){let i=[];for(let h of a)(h.text||h.clickable)&&h.bounds.width>0&&(h.bounds.x2>e+10&&h.bounds.x1<e&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows right screen boundary by ${h.bounds.x2-e}px`,elements:[h.text||h.contentDesc||h.className]}),h.bounds.y2>t+20&&h.bounds.y1<t&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows bottom screen boundary by ${h.bounds.y2-t}px`,elements:[h.text||h.contentDesc||h.className]}));let r=a.filter(h=>h.text&&h.text.trim().length>1&&h.bounds.width>0&&h.bounds.height>0),n=200,o=new Map;for(let h of r){let u=Math.floor(h.bounds.y1/n),m=Math.floor(h.bounds.y2/n);for(let y=u;y<=m;y++)o.has(y)||o.set(y,[]),o.get(y).push(h)}let c=new Set;for(let[,h]of o)for(let u=0;u<h.length;u++)for(let m=u+1;m<h.length;m++){let y=h[u],v=h[m];if(y===v||y.text===v.text)continue;let T=y.bounds.x1<v.bounds.x1?`${y.bounds.x1},${y.bounds.y1}:${v.bounds.x1},${v.bounds.y1}`:`${v.bounds.x1},${v.bounds.y1}:${y.bounds.x1},${y.bounds.y1}`;if(c.has(T))continue;c.add(T);let S=y.bounds,b=v.bounds;if(Math.abs(S.centerY-b.centerY)>(S.height+b.height)/2)continue;let E=Math.max(0,Math.min(S.x2,b.x2)-Math.max(S.x1,b.x1)),D=Math.max(0,Math.min(S.y2,b.y2)-Math.max(S.y1,b.y1)),B=E*D;if(B>0){let k=S.width*S.height,j=b.width*b.height,M=Math.min(k,j);M>0&&B/M>s&&i.push({type:"OVERLAP",severity:"WARN",description:`Visual text collision: "${y.text}" overlaps with "${v.text}" (${Math.round(B)}px\xB2 collision)`,elements:[y.text,v.text]})}}let l=a.filter(h=>(h.className.includes("ProgressBar")||h.className.includes("ActivityIndicator"))&&h.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(h=>h.className)});let p=[],d=new Set;for(let h of i){let u=`${h.type}::${[...h.elements].sort().join("::")}`;d.has(u)||(d.add(u),p.push(h))}return p}function us(a,e,t){let s=e?.height||C.screen.fallbackHeight,i=e?.width||C.screen.fallbackWidth,r=Ut(a,s,t);if(r.length>1&&r[0].bounds.centerY>=s*.75)return{paradigm:"bottom_tabs",roots:r};let n=s*.05,o=s*.22,c=a.filter(p=>{if(Me(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}`),h=p.bounds.centerY>=n&&p.bounds.centerY<=o,u=p.bounds.height>25&&p.bounds.height<=220;return(d||h)&&p.clickable&&p.bounds.width>50&&u});if(c.length>=2){let p=[];for(let h of c){let u=p.find(m=>Math.abs(m[0].bounds.centerY-h.bounds.centerY)<=20);u||(u=[],p.push(u)),u.push(h)}let d=p.find(h=>h.length>=2);if(d){d.sort((m,y)=>m.bounds.centerX-y.bounds.centerX);let h=[];for(let m of d)h.some(y=>Math.abs(y.bounds.centerX-m.bounds.centerX)<40)||h.push(m);if(!(h.length===2&&h[0].bounds.x1<=i*.25&&h[1].bounds.x2>=i*.75&&!h.some(m=>m.className.includes("Tab")||m.resourceId.toLowerCase().includes("tab")))&&h.length>=2)return{paradigm:"top_tabs",roots:h.slice(0,5)}}}let l=st(a,s,i);return l?{paradigm:"drawer",roots:[l]}:{paradigm:"single_hub",roots:[]}}function Pi(a,e=2){if(a.length<=e)return a;let t=[];for(let i of a){let r=t.find(n=>{let o=n[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});r||(r=[],t.push(r)),r.push(i)}let s=[];for(let i of t)s.push(...i.slice(0,e));return s}function Re(a,e=C.screen.fallbackHeight,t=C.screen.fallbackWidth,s=!1){let i=e*.22,r=t*.28,n=/(?: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(Me(c)||!o(c))continue;let l=`${c.text||""} ${c.contentDesc||""} ${c.resourceId||""}`.trim();if(n.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(Me(c)||!o(c)||c.bounds.x1>r)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(h=>h.clickable&&h.bounds.x1<=c.bounds.x1&&h.bounds.x2>=c.bounds.x2&&h.bounds.y1<=c.bounds.y1&&h.bounds.y2>=c.bounds.y2)||c}}if(s){let c=a.find(l=>{if(Me(l)||!o(l)||!l.clickable)return!1;let p=l.bounds.x1<=r,d=l.bounds.width<=250&&l.bounds.height<=250;return p&&d&&l.bounds.width<t*.4});if(c)return c}return null}import Ze from"fs";import it from"path";var At=class{outputDir;steps=[];errorsDetected=[];startTime=new Date;packageName="Unknown";deviceId="Unknown";pendingWrites=[];formats=["json","md","junit","html"];videoPath;embedScreenshots=!1;screenshotBuffers=new Map;stepListeners=[];completeListeners=[];errorListeners=[];constructor(e,t){typeof e=="object"&&e!==null?(this.outputDir=e.outputDir||it.resolve(process.cwd(),"output"),e.formats&&e.formats.length>0&&(this.formats=e.formats),this.embedScreenshots=!!e.embedScreenshots):(this.outputDir=e||it.resolve(process.cwd(),"output"),t&&t.length>0&&(this.formats=t)),Ze.existsSync(this.outputDir)||Ze.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,r,n,o,c,l){let p=this.steps.length+1,d;if(n){this.embedScreenshots&&this.screenshotBuffers.set(p,n);let m=`step_${p}_${e.toLowerCase().replace(/[^a-z0-9]/g,"_")}.png`,y=it.join(this.outputDir,m),v=Ze.promises.writeFile(y,n).catch(T=>{console.error(`Warning: Failed to write screenshot ${m}:`,T)}).finally(()=>{let T=this.pendingWrites.indexOf(v);T!==-1&&this.pendingWrites.splice(T,1)});this.pendingWrites.push(v),d=m}let h=typeof o?.videoOffsetMs=="number"?o.videoOffsetMs:void 0,u={stepIndex:p,timestamp:new Date().toISOString(),phase:e,description:t,action:s,target:r,status:i,screenshotPath:d,durationMs:c,triageBundle:l,videoOffsetMs:h,details:o};this.steps.push(u);for(let m of this.stepListeners)try{m(u)}catch{}return u}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={packageName:this.packageName,deviceId:this.deviceId,startTime:this.startTime.toISOString(),endTime:t.toISOString(),durationSeconds:s,totalSteps:this.steps.length,passedSteps:this.steps.filter(n=>n.status==="PASS").length,failedSteps:this.steps.filter(n=>n.status==="FAIL").length,skippedSteps:this.steps.filter(n=>n.status==="SKIPPED").length,warnSteps:this.steps.filter(n=>n.status==="WARN").length,errorsDetected:this.errorsDetected,videoPath:this.videoPath,steps:this.steps},r=e||"prompttest";if(this.formats.includes("json")){let n=it.join(this.outputDir,`${r}-results.json`);await Ze.promises.writeFile(n,JSON.stringify(i,null,2),"utf-8")}if(this.formats.includes("md")){let n=it.join(this.outputDir,`${r}-report.md`),o=this.formatMarkdownReport(i);await Ze.promises.writeFile(n,o,"utf-8")}if(this.formats.includes("junit")){let n=it.join(this.outputDir,`${r}-junit.xml`),o=this.formatJunitXml(i,r);await Ze.promises.writeFile(n,o,"utf-8")}if(this.formats.includes("html")){let n=it.join(this.outputDir,`${r}-report.html`),o=this.formatHtmlReport(i,r);await Ze.promises.writeFile(n,o,"utf-8")}for(let n of this.completeListeners)try{n(i)}catch{}return this.clearScreenshotBuffers(),i}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),r=['<?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 n of e.steps){let o=`Step ${n.stepIndex}: ${this.escapeXml(n.action)} - ${this.escapeXml(n.description)}`,c=n.durationMs!==void 0?(n.durationMs/1e3).toFixed(3):"1.000";r.push(` <testcase classname="${this.escapeXml(t)}" name="${o}" time="${c}">`),n.status==="FAIL"?r.push(` <failure message="${this.escapeXml(n.description)}">${this.escapeXml(n.description)}</failure>`):n.status==="SKIPPED"&&r.push(` <skipped message="${this.escapeXml(n.description)}"/>`),r.push(" </testcase>")}return e.failedSteps===0&&e.errorsDetected.length>0&&r.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>"),r.push(" </testsuite>"),r.push("</testsuites>"),r.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 n of e.errorsDetected)i.push(`- \u{1F534} \`${n}\``);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 r=n=>(n||"").replace(/\|/g,"\\|").replace(/\r?\n/g," ");for(let n of e.steps){let o="\u2014";n.triageBundle?o=`[\u{1F50D} Triage Bundle](./${n.triageBundle})`:n.screenshotPath&&(o=`[\u{1F4F8} Screenshot](./${n.screenshotPath})`);let c=n.durationMs!==void 0?`${n.durationMs}ms`:"\u2014",l=n.status==="PASS"?"\u{1F7E2} PASS":n.status==="WARN"?"\u{1F7E1} WARN":n.status==="SKIPPED"?"\u26AA SKIPPED":"\u{1F534} FAIL";i.push(`| ${n.stepIndex} | ${r(n.phase)} | ${r(n.action)} | ${r(n.description)} | ${l} | ${c} | ${o} |`)}return i.push(""),i.push("---"),i.push("*Generated autonomously by PromptTest 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=it.join(this.outputDir,e.screenshotPath);if(Ze.existsSync(t))try{return`data:image/png;base64,${Ze.readFileSync(t).toString("base64")}`}catch{}}return`./${e.screenshotPath}`}}formatHtmlReport(e,t){return hs(e,{suiteName:t,embedScreenshots:this.embedScreenshots,screenshotResolver:s=>this.resolveScreenshotData(s)})}};function hs(a,e){let t=e?.suiteName||"PromptTest Suite",s=a.failedSteps===0&&a.errorsDetected.length===0,i=s?"ALL PASSED":"ISSUES DETECTED",r=s?"#10b981":"#ef4444",n=a.totalSteps,o=n>0?Math.round(a.passedSteps/n*100):100,c=u=>(u||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),l=[],p=a.steps.map(u=>{let m=u.status.toLowerCase(),y=u.durationMs!==void 0?`${u.durationMs}ms`:"\u2014",v=e?.screenshotResolver?e.screenshotResolver(u):u.screenshotPath?`./${u.screenshotPath}`:void 0;v&&l.push({stepIndex:u.stepIndex,action:u.action,description:u.description,status:u.status,src:v,durationMs:u.durationMs});let T="\u2014";if(u.triageBundle){let k=c(u.triageBundle),j=u.triageBundle.endsWith(".zip"),M=j?k:`${k}.zip`,J=j?k.replace(/\.zip$/,""):k;T=`
|
|
9
41
|
<div class="triage-bundle-links">
|
|
10
|
-
<a class="btn-triage" href="./${
|
|
42
|
+
<a class="btn-triage btn-download-zip" href="./${M}" download title="Download Diagnostic Triage ZIP Package">\u{1F4E6} Download ZIP</a>
|
|
43
|
+
<a class="btn-triage" href="./${J}" target="_blank" title="Browse Failure Diagnostic Directory">\u{1F50D} Triage Folder</a>
|
|
11
44
|
<div class="triage-files">
|
|
12
|
-
<a href="./${
|
|
13
|
-
<a href="./${
|
|
14
|
-
<a href="./${
|
|
15
|
-
<a href="./${
|
|
45
|
+
<a href="./${J}/screenshot.png" target="_blank" class="mini-link">\u{1F4F8} Shot</a>
|
|
46
|
+
<a href="./${J}/hierarchy.xml" target="_blank" class="mini-link">\u{1F4C4} XML</a>
|
|
47
|
+
<a href="./${J}/logcat_tail.log" target="_blank" class="mini-link">\u{1F4DC} Logcat</a>
|
|
48
|
+
<a href="./${J}/match_scores.json" target="_blank" class="mini-link">\u{1F3AF} Scores</a>
|
|
16
49
|
</div>
|
|
17
|
-
</div>`}else
|
|
50
|
+
</div>`}else v&&(T=`
|
|
18
51
|
<div class="screenshot-cell">
|
|
19
|
-
<img src="${
|
|
52
|
+
<img src="${v}" class="thumb" alt="Step ${u.stepIndex}" onclick="openLightboxByStep(${u.stepIndex})" title="Click to view in full-screen Lightbox"/>
|
|
20
53
|
<button class="btn-zoom" onclick="openLightboxByStep(${u.stepIndex})" title="Enlarge Screenshot">\u{1F50D}</button>
|
|
21
|
-
</div>`);let
|
|
54
|
+
</div>`);let S="";if(u.details&&(typeof u.details.diffPercent=="number"||u.details.diffPath||u.details.baselinePath)){let k=typeof u.details.diffPercent=="number"?`${(u.details.diffPercent*100).toFixed(2)}%`:"N/A",j=typeof u.details.threshold=="number"?`${(u.details.threshold*100).toFixed(2)}%`:"2.00%";S=`
|
|
22
55
|
<div class="diff-viewer-card">
|
|
23
56
|
<div class="diff-header">
|
|
24
|
-
<span class="badge diff-badge">Visual Diff: ${
|
|
25
|
-
<span class="diff-meta">Threshold: ${
|
|
57
|
+
<span class="badge diff-badge">Visual Diff: ${c(k)}</span>
|
|
58
|
+
<span class="diff-meta">Threshold: ${c(j)}</span>
|
|
26
59
|
</div>
|
|
27
60
|
<div class="diff-grid">
|
|
28
|
-
${u.details.baselinePath?`<div class="diff-pane"><div class="pane-label">Baseline</div><img src="./${
|
|
29
|
-
${
|
|
30
|
-
${u.details.diffPath?`<div class="diff-pane"><div class="pane-label">Pixel Diff Overlay</div><img src="./${
|
|
61
|
+
${u.details.baselinePath?`<div class="diff-pane"><div class="pane-label">Baseline</div><img src="./${c(String(u.details.baselinePath))}" class="diff-thumb" onclick="openLightboxCustom('./${c(String(u.details.baselinePath))}', 'Baseline Screenshot')"/></div>`:""}
|
|
62
|
+
${v?`<div class="diff-pane"><div class="pane-label">Actual Screen</div><img src="${v}" class="diff-thumb" onclick="openLightboxCustom('${v}', 'Actual Screenshot')"/></div>`:""}
|
|
63
|
+
${u.details.diffPath?`<div class="diff-pane"><div class="pane-label">Pixel Diff Overlay</div><img src="./${c(String(u.details.diffPath))}" class="diff-thumb" onclick="openLightboxCustom('./${c(String(u.details.diffPath))}', 'Visual Difference Overlay')"/></div>`:""}
|
|
31
64
|
</div>
|
|
32
|
-
</div>`}let
|
|
65
|
+
</div>`}let b="";u.details&&Object.keys(u.details).length>0&&(b=`
|
|
33
66
|
<details class="step-details">
|
|
34
67
|
<summary>Diagnostics & Context</summary>
|
|
35
|
-
<pre>${
|
|
36
|
-
</details>`);let
|
|
37
|
-
<tr class="step-row status-${
|
|
68
|
+
<pre>${c(JSON.stringify(u.details,null,2))}</pre>
|
|
69
|
+
</details>`);let E=`${u.stepIndex} ${u.phase} ${u.action} ${u.description} ${u.target||""}`.toLowerCase(),D=typeof u.videoOffsetMs=="number"?u.videoOffsetMs:typeof u.details?.videoOffsetMs=="number"?u.details.videoOffsetMs:void 0,B=a.videoPath&&D!==void 0?`<button type="button" class="btn-video-jump" onclick="seekVideoTo(${D/1e3})" title="Jump video to ${(D/1e3).toFixed(1)}s">\u25B6 ${(D/1e3).toFixed(1)}s</button>`:"";return`
|
|
70
|
+
<tr class="step-row status-${m}" data-status="${m}" data-search="${c(E)}">
|
|
38
71
|
<td class="col-num">${u.stepIndex}</td>
|
|
39
|
-
<td><span class="badge phase-badge">${
|
|
40
|
-
<td><span class="badge action-badge">${a(u.action)}</span></td>
|
|
72
|
+
<td><span class="badge phase-badge">${c(u.phase)}</span></td>
|
|
41
73
|
<td>
|
|
42
|
-
<
|
|
74
|
+
<span class="badge action-badge">${c(u.action)}</span>
|
|
75
|
+
${B}
|
|
76
|
+
</td>
|
|
77
|
+
<td>
|
|
78
|
+
<div class="desc-text">${c(u.description)}</div>
|
|
79
|
+
${S}
|
|
43
80
|
${b}
|
|
44
|
-
${m}
|
|
45
81
|
</td>
|
|
46
|
-
<td><code>${
|
|
47
|
-
<td><span class="badge status-badge status-${
|
|
48
|
-
<td class="col-duration">${
|
|
49
|
-
<td class="col-artifact">${
|
|
82
|
+
<td><code>${c(u.target||"\u2014")}</code></td>
|
|
83
|
+
<td><span class="badge status-badge status-${m}">${u.status}</span></td>
|
|
84
|
+
<td class="col-duration">${y}</td>
|
|
85
|
+
<td class="col-artifact">${T}</td>
|
|
50
86
|
</tr>`}).join(`
|
|
51
|
-
`),
|
|
87
|
+
`),d=a.videoPath?`
|
|
52
88
|
<section class="card video-card">
|
|
53
|
-
<
|
|
54
|
-
|
|
55
|
-
|
|
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="./${c(a.videoPath)}"></video>
|
|
100
|
+
</section>`:"",h=a.errorsDetected.length>0?`
|
|
56
101
|
<section class="card error-card">
|
|
57
|
-
<h3>\u26A0\uFE0F Critical Flagged Errors (${
|
|
102
|
+
<h3>\u26A0\uFE0F Critical Flagged Errors (${a.errorsDetected.length})</h3>
|
|
58
103
|
<ul class="error-list">
|
|
59
|
-
${
|
|
104
|
+
${a.errorsDetected.map(u=>`<li>\u{1F534} <code>${c(u)}</code></li>`).join(`
|
|
60
105
|
`)}
|
|
61
106
|
</ul>
|
|
62
107
|
</section>`:"";return`<!DOCTYPE html>
|
|
@@ -64,7 +109,7 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
64
109
|
<head>
|
|
65
110
|
<meta charset="UTF-8">
|
|
66
111
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
67
|
-
<title>PromptTest QA Audit: ${
|
|
112
|
+
<title>PromptTest QA Audit: ${c(t)}</title>
|
|
68
113
|
<style>
|
|
69
114
|
:root {
|
|
70
115
|
--bg: #0b0f19;
|
|
@@ -107,7 +152,7 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
107
152
|
padding: 8px 18px;
|
|
108
153
|
border-radius: 9999px;
|
|
109
154
|
color: #fff;
|
|
110
|
-
background: ${
|
|
155
|
+
background: ${r};
|
|
111
156
|
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4);
|
|
112
157
|
}
|
|
113
158
|
|
|
@@ -181,9 +226,44 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
181
226
|
margin-bottom: 24px;
|
|
182
227
|
}
|
|
183
228
|
.card h3 { margin-bottom: 12px; font-size: 1.15rem; }
|
|
184
|
-
.
|
|
185
|
-
.
|
|
186
|
-
.
|
|
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
|
+
}
|
|
187
267
|
.video-card video { max-width: 100%; border-radius: 8px; border: 1px solid var(--card-border); }
|
|
188
268
|
|
|
189
269
|
/* Filter & Search Toolbar */
|
|
@@ -289,13 +369,29 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
289
369
|
.btn-triage {
|
|
290
370
|
display: inline-block;
|
|
291
371
|
padding: 4px 8px;
|
|
292
|
-
background:
|
|
293
|
-
|
|
372
|
+
background: rgba(239, 68, 68, 0.2);
|
|
373
|
+
border: 1px solid rgba(239, 68, 68, 0.4);
|
|
374
|
+
color: #fca5a5;
|
|
294
375
|
border-radius: 4px;
|
|
295
376
|
text-decoration: none;
|
|
296
377
|
font-size: 0.75rem;
|
|
297
|
-
font-weight:
|
|
378
|
+
font-weight: 600;
|
|
298
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;
|
|
299
395
|
}
|
|
300
396
|
.triage-files { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 4px; }
|
|
301
397
|
.mini-link {
|
|
@@ -459,10 +555,10 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
459
555
|
<div class="header-title">
|
|
460
556
|
<h1>PromptTest QA Audit Report</h1>
|
|
461
557
|
<div class="header-meta">
|
|
462
|
-
<strong>Suite:</strong> <code>${
|
|
463
|
-
<strong>App:</strong> <code>${a
|
|
464
|
-
<strong>Device:</strong> <code>${a
|
|
465
|
-
<strong>Duration:</strong> ${
|
|
558
|
+
<strong>Suite:</strong> <code>${c(t)}</code> •
|
|
559
|
+
<strong>App:</strong> <code>${c(a.packageName)}</code> •
|
|
560
|
+
<strong>Device:</strong> <code>${c(a.deviceId)}</code> •
|
|
561
|
+
<strong>Duration:</strong> ${a.durationSeconds}s (${a.startTime.substring(11,19)} to ${a.endTime.substring(11,19)})
|
|
466
562
|
</div>
|
|
467
563
|
</div>
|
|
468
564
|
<div class="status-pill">${i}</div>
|
|
@@ -472,44 +568,44 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
472
568
|
<div class="gauge-card">
|
|
473
569
|
<svg viewBox="0 0 36 36" class="circular-chart">
|
|
474
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"/>
|
|
475
|
-
<path class="circle" stroke-dasharray="${o}, 100" stroke="${
|
|
571
|
+
<path class="circle" stroke-dasharray="${o}, 100" stroke="${r}" 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"/>
|
|
476
572
|
<text x="18" y="20.35" class="percentage">${o}%</text>
|
|
477
573
|
</svg>
|
|
478
574
|
<div class="chart-label">Pass Rate</div>
|
|
479
575
|
</div>
|
|
480
576
|
<div class="stat-card">
|
|
481
577
|
<div class="stat-label">Total Steps</div>
|
|
482
|
-
<div class="stat-value">${
|
|
578
|
+
<div class="stat-value">${a.totalSteps}</div>
|
|
483
579
|
</div>
|
|
484
580
|
<div class="stat-card">
|
|
485
581
|
<div class="stat-label">Passed</div>
|
|
486
|
-
<div class="stat-value val-pass">${
|
|
582
|
+
<div class="stat-value val-pass">${a.passedSteps}</div>
|
|
487
583
|
</div>
|
|
488
584
|
<div class="stat-card">
|
|
489
585
|
<div class="stat-label">Failures</div>
|
|
490
|
-
<div class="stat-value val-fail">${
|
|
586
|
+
<div class="stat-value val-fail">${a.failedSteps}</div>
|
|
491
587
|
</div>
|
|
492
588
|
<div class="stat-card">
|
|
493
589
|
<div class="stat-label">Warnings</div>
|
|
494
|
-
<div class="stat-value val-warn">${
|
|
590
|
+
<div class="stat-value val-warn">${a.warnSteps}</div>
|
|
495
591
|
</div>
|
|
496
592
|
<div class="stat-card">
|
|
497
593
|
<div class="stat-label">Skipped</div>
|
|
498
|
-
<div class="stat-value val-skip">${
|
|
594
|
+
<div class="stat-value val-skip">${a.skippedSteps}</div>
|
|
499
595
|
</div>
|
|
500
596
|
</div>
|
|
501
597
|
|
|
502
|
-
${
|
|
598
|
+
${d}
|
|
503
599
|
${h}
|
|
504
600
|
|
|
505
601
|
<section class="card">
|
|
506
602
|
<div class="toolbar">
|
|
507
603
|
<div class="filter-bar">
|
|
508
|
-
<button class="filter-btn active" data-filter="all" onclick="setFilter('all', this)">All (${
|
|
509
|
-
<button class="filter-btn" data-filter="pass" onclick="setFilter('pass', this)">Passed (${
|
|
510
|
-
<button class="filter-btn" data-filter="fail" onclick="setFilter('fail', this)">Failed (${
|
|
511
|
-
<button class="filter-btn" data-filter="warn" onclick="setFilter('warn', this)">Warnings (${
|
|
512
|
-
<button class="filter-btn" data-filter="skipped" onclick="setFilter('skipped', this)">Skipped (${
|
|
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>
|
|
513
609
|
</div>
|
|
514
610
|
<div class="search-box">
|
|
515
611
|
<input type="text" id="filter-search" placeholder="\u{1F50D} Search steps, actions, targets..." oninput="applyFilters()"/>
|
|
@@ -530,7 +626,7 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
530
626
|
</tr>
|
|
531
627
|
</thead>
|
|
532
628
|
<tbody id="steps-tbody">
|
|
533
|
-
${
|
|
629
|
+
${p}
|
|
534
630
|
</tbody>
|
|
535
631
|
</table>
|
|
536
632
|
</section>
|
|
@@ -564,7 +660,7 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
564
660
|
</div>
|
|
565
661
|
|
|
566
662
|
<script>
|
|
567
|
-
const SCREENSHOTS = ${JSON.stringify(
|
|
663
|
+
const SCREENSHOTS = ${JSON.stringify(l)};
|
|
568
664
|
let currentLightboxIdx = -1;
|
|
569
665
|
let currentFilter = 'all';
|
|
570
666
|
|
|
@@ -652,6 +748,25 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
652
748
|
document.getElementById('lb-img').classList.toggle('zoomed');
|
|
653
749
|
}
|
|
654
750
|
|
|
751
|
+
function setPlaybackSpeed(speed) {
|
|
752
|
+
const player = document.getElementById('session-recording-player');
|
|
753
|
+
if (player) {
|
|
754
|
+
player.playbackRate = speed;
|
|
755
|
+
document.querySelectorAll('.btn-speed').forEach(btn => {
|
|
756
|
+
btn.classList.toggle('active', btn.textContent.trim() === speed + 'x');
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
function seekVideoTo(seconds) {
|
|
762
|
+
const player = document.getElementById('session-recording-player');
|
|
763
|
+
if (player) {
|
|
764
|
+
player.currentTime = seconds;
|
|
765
|
+
player.play().catch(() => {});
|
|
766
|
+
player.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
655
770
|
window.addEventListener('keydown', (e) => {
|
|
656
771
|
const lb = document.getElementById('lightbox');
|
|
657
772
|
if (!lb.classList.contains('active')) return;
|
|
@@ -677,9 +792,20 @@ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevic
|
|
|
677
792
|
}
|
|
678
793
|
</script>
|
|
679
794
|
</body>
|
|
680
|
-
</html>`}var nt=new rt;import ge from"fs";import Re from"path";import{fileURLToPath as Di}from"url";var ot={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"]}},lr=ot.en,Et=new Map;function Ys(p){let e=new Map;for(let[t,s]of Object.entries(p)){let n=[X(t),...s.map(r=>X(r))];for(let r of n){e.has(r)||e.set(r,[]);let o=e.get(r);for(let a of n)o.includes(a)||o.push(a)}}return e}for(let[p,e]of Object.entries(ot))Et.set(p.toLowerCase(),Ys(e));function dr(p,e){let t=p.toLowerCase();ot[t]={...ot[t]||{},...e},Et.set(t,Ys(ot[t]))}function ur(){return Object.keys(ot)}function St(p,e="en"){let t=X(p),s=(e||"en").toLowerCase(),i=Et.get(s);if(i){let n=i.get(t);if(n&&n.length>0)return n}if(s!=="en"){let n=Et.get("en");if(n){let r=n.get(t);if(r&&r.length>0)return r}}return[t]}var js=St;var He=class p{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=Re.dirname(Di(import.meta.url));this.memoryDir=Re.resolve(t,"..","memory")}ge.existsSync(this.memoryDir)||ge.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=Re.join(this.memoryDir,`${this.currentPackage}.json`);if(ge.existsSync(t))try{let s=await ge.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=X(e),s=St(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()}:${X(t)}`,r=this.mappings.get(n);if(r)return r;let o=St(t,this.locale);for(let a of o){let d=`${e.toUpperCase()}:${a}`,c=this.mappings.get(d);if(c)return c}}getAllCandidates(e,t,s,i){let n=(s||this.locale||"en").toLowerCase(),r=new Set;if(i){let d=this.getScreenElements(i),c=this.getCanonicalQuery(t);for(let l of d)l.action===e.toUpperCase()&&(l.canonicalIntent===c||l.canonicalIntent===X(t))&&l.confidence>=.7&&r.add(l.matchedIdentifier)}let o=this.resolve(e,t);o&&o.confidence>=.8&&r.add(o.matchedIdentifier),r.add(t);let a=St(t,n);for(let d of a)r.add(d);return Array.from(r)}recordSuccess(e,t,s,i,n=1,r,o){if(s.length>35||s.includes("?")||s.includes(`
|
|
681
|
-
`))return;let
|
|
682
|
-
Wait for the other run to complete, or remove the lock file if it is stale: ${t}`)}catch(r){if(r.code==="ESRCH")try{De.unlinkSync(t)}catch{}else throw r}}}catch(i){let n=i;if(n.message&&n.message.includes("locked by another"))throw n;try{De.unlinkSync(t)}catch{}}try{De.writeFileSync(t,process.pid.toString(),{flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Device "${p}" was just acquired by a concurrent PromptTest process.`):i}let s=()=>{try{De.existsSync(t)&&De.readFileSync(t,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(t)}catch{}};return Vt.set(t,s),process.once("exit",s),{serial:p,lockFilePath:t,acquired:!0,pid:process.pid}}function ze(p){if(p)try{let e=Vt.get(p.lockFilePath);if(e)process.removeListener("exit",e),Vt.delete(p.lockFilePath),e();else if(De.existsSync(p.lockFilePath))try{De.readFileSync(p.lockFilePath,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(p.lockFilePath)}catch{}}catch{}}import Xt from"chalk";var Wt={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4},Pt=class{currentLevel="INFO";constructor(e){let t=(process.env.LOG_LEVEL||"").toUpperCase();e?this.currentLevel=e:Wt[t]!==void 0?this.currentLevel=t:this.currentLevel="INFO"}setLevel(e){this.currentLevel=e}getLevel(){return this.currentLevel}isLevelEnabled(e){return Wt[this.currentLevel]<=Wt[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(Xt.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(Xt.yellow("[WARN]"),...e))}error(...e){this.isLevelEnabled("ERROR")&&(this.isJsonMode()?this.emitJson("ERROR",...e):console.error(Xt.red("[ERROR]"),...e))}},ke=new Pt;import Ue from"fs";import Vs from"path";var Gt=class{checkpointDir;constructor(e){this.checkpointDir=e||Vs.resolve(process.cwd(),"output","checkpoints"),Ue.existsSync(this.checkpointDir)||Ue.mkdirSync(this.checkpointDir,{recursive:!0})}filePath(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Vs.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 Ue.promises.writeFile(r,JSON.stringify(n,null,2),"utf-8"),await Ue.promises.rename(r,this.filePath(e))}async load(e){let t=this.filePath(e);if(!Ue.existsSync(t))return null;try{let s=await Ue.promises.readFile(t,"utf-8");return JSON.parse(s)}catch{return null}}async clear(e){let t=this.filePath(e);Ue.existsSync(t)&&await Ue.promises.unlink(t)}async getResumeIndex(e){let t=await this.load(e);return t?t.lastPassedStep+1:0}},Xs=new Gt;import ve from"fs";import wt from"path";import{PNG as Je}from"pngjs";import ki from"pixelmatch";var ct=class{baselineDir;defaultThreshold;constructor(e,t=.02){this.baselineDir=e||wt.resolve(process.cwd(),"output","baselines"),this.defaultThreshold=t,ve.existsSync(this.baselineDir)||ve.mkdirSync(this.baselineDir,{recursive:!0})}filePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}.png`)}diffFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_diff.png`)}async saveBaseline(e,t,s){let i=this.filePath(e,t),n=i+`.tmp.${Date.now()}`;return await ve.promises.writeFile(n,s),await ve.promises.rename(n,i),i}hasBaseline(e,t){return ve.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=wt.join(this.baselineDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}_current.png`);await ve.promises.writeFile(o,s);let a=n.threshold??this.defaultThreshold;if(!ve.existsSync(r)){await this.saveBaseline(e,t,s);let w=Je.sync.read(s),A=w.width*w.height;return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:0,diffPixels:0,totalPixels:A,passed:!0,threshold:a}}let d=await ve.promises.readFile(r),c=Je.sync.read(d),l=Je.sync.read(s),h=Math.max(c.width,l.width),u=Math.max(c.height,l.height),g=h*u,f=this.fitToCanvas(c,h,u),y=this.fitToCanvas(l,h,u);n.maskRegions&&n.maskRegions.length>0&&(this.applyMasks(f,n.maskRegions),this.applyMasks(y,n.maskRegions));let S=new Je({width:h,height:u}),b=n.pixelmatchThreshold??.1,m=ki(f.data,y.data,S.data,h,u,{threshold:b,includeAA:!1}),v=g>0?m/g:0,x=v<=a,D;if(m>0){D=this.diffFilePath(e,t);let w=Je.sync.write(S);await ve.promises.writeFile(D,w)}return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:v,diffPixels:m,totalPixels:g,passed:x,threshold:a,diffImagePath:D}}fitToCanvas(e,t,s){if(e.width===t&&e.height===s)return e;let i=new Je({width:t,height:s});return i.data.fill(0),Je.bitblt(e,i,0,0,e.width,e.height,0,0),i}applyMasks(e,t){for(let s of t){let i=Math.min(e.width,s.x+s.width),n=Math.min(e.height,s.y+s.height);for(let r=Math.max(0,s.y);r<n;r++)for(let o=Math.max(0,s.x);o<i;o++){let a=e.width*r+o<<2;e.data[a]=0,e.data[a+1]=0,e.data[a+2]=0,e.data[a+3]=0}}}async clearBaselines(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");if(!ve.existsSync(this.baselineDir))return;let s=await ve.promises.readdir(this.baselineDir);await Promise.all(s.filter(i=>i.startsWith(t+"_step")).map(i=>ve.promises.unlink(wt.join(this.baselineDir,i)).catch(()=>{})))}},Kt=new ct;import se from"chalk";import Ws from"vm";function Y(p){return new Promise(e=>setTimeout(e,p))}function Ci(p){let e=p.screenDimensions.height,t=p.navBarHeight>0?e-p.navBarHeight:e,s=p.navBarHeight>0?t*.94:e*E.gestures.bottomNavThresholdRatio;return{effectiveHeight:t,bottomThreshold:s}}var zt=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:a}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(a.length===0&&t.upcomingSteps&&t.upcomingSteps.length>0&&!o.some(S=>S.password===!0||S.className.includes("EditText")&&o.some(b=>b.text?.toLowerCase().includes("password")))){let S=t.upcomingSteps.findIndex(m=>m.type==="VERIFY"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(S!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[S].target}"`,skipCount:S};let b=t.upcomingSteps.findIndex(m=>m.type==="TAP"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(b!==-1)return{fastForwarded:!0,reason:`Upcoming action "${t.upcomingSteps[b].target}" is directly actionable`,skipCount:b}}if(a.length===0){await t.driver.swipe(r,Math.round(n*.75),r,Math.round(n*.35),300,t.serial),await Y(350),t.setLastHierarchy(null);let y=await t.waitForTarget(s,t.serial,2e3,e);o=y.flat,a=y.matched}if(a.length===0)throw t.buildDiagnosticError(s,o,`Element matching "${s}" not found on current screen.`);let d=a.find(y=>y.clickable)||a[0];if(await t.ensureInViewport(d,t.serial)){let y=await t.waitForTarget(s,t.serial,1500,e);y.matched.length>0&&(o=y.flat,a=y.matched,d=a.find(S=>S.clickable)||a[0])}let l=d.bounds.centerX,{effectiveHeight:h}=Ci(t),u=d.bounds.centerY;if(d.bounds.y2>h&&(u=Math.min(Math.round((d.bounds.y1+h)/2),h-15)),u=Math.min(u,d.bounds.y2-2),u=Math.max(u,d.bounds.y1+2),u>n*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(` [Keyboard] Target occluded by soft keyboard (Y=${u} > ${Math.round(n*.6)}). Dismissing...`)),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let g=d.contentDesc||d.text||d.resourceId;console.log(se.gray(` [Tap Target] (${l}, ${u}) for "${g||s}"`));let f=t.lastHierarchy?.hash;await t.driver.tap(l,u,t.serial),await Y(E.settle.tapMs),t.setLastHierarchy(null),g&&X(g)!==X(s)&&t.memory.recordSuccess("TAP",s,g,d.contentDesc?"contentDesc":d.text?"text":"resourceId",1,void 0,f)}},Jt=class{type="LONG_PRESS";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,E.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 a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched[0])}await t.driver.swipe(r.bounds.centerX,r.bounds.centerY,r.bounds.centerX,r.bounds.centerY,E.gestures.longPressDurationMs,t.serial),await Y(300),t.setLastHierarchy(null)}},Dt=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<E.polling.hierarchyCacheTtlMs){let l=t.findTargetInputField(t.lastHierarchy.flat,s,i);l&&(n=t.lastHierarchy.flat,r=l)}if(r||(n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i)),!r){let l=Date.now();for(;Date.now()-l<2e3&&(await Y(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(h=>h.className.includes("EditText"))){let h=t.upcomingSteps.findIndex(u=>u.type==="VERIFY"&&u.target&&t.matchNodes(n,u.target,u).length>0);if(h!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[h].target}" and form is completed`,skipCount:h}}if(!r)throw t.buildDiagnosticError(s,n,`Input field matching "${s}" not found.`);if(r.text&&r.text===i){console.log(se.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 h=t.findTargetInputField(n,s,i);h&&(r=h)}let{height:a}=t.screenDimensions;if(r.bounds.centerY>a*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(" [Keyboard] Input field occluded by soft keyboard. Dismissing before focus...")),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let d=t.lastHierarchy?.hash;await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await Y(E.settle.inputFocusMs),await t.driver.clearField(t.serial),await Y(E.settle.inputClearMs),await t.driver.inputText(i,t.serial),await Y(E.settle.inputDoneMs),t.setLastHierarchy(null);let c=r.contentDesc||r.resourceId;c&&X(c)!==X(s)&&t.memory.recordSuccess("TYPE",s,c,r.contentDesc?"contentDesc":"resourceId",1,void 0,d)}},Qt=class{type="CLEAR";async execute(e,t){let s=e.target,i=[],n=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<E.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 Y(300);let r=t.driver;typeof r.clearField=="function"?await r.clearField(t.serial):typeof r.clearInput=="function"&&await r.clearInput(50,t.serial),await Y(200),t.setLastHierarchy(null)}},qt=class{type="VERIFY";async execute(e,t){let s=e.target,i=e.expectedState||"visible";if(e.negative===!0||i==="absent"||i==="hidden"){let h=await t.getCleanHierarchy(t.serial);if(t.matchNodes(h.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,a=Math.round(r*.5),d=!1,c=[],l;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<E.polling.verifyCacheTtlMs&&(l=t.matchNodes(t.lastHierarchy.flat,s,e)[0],l&&(c=t.lastHierarchy.flat,d=!0,t.lastHierarchy.timestamp=Date.now())),!d){let h=Date.now();for(;Date.now()-h<E.polling.extendedTimeoutMs;){if(c=(await t.getCleanHierarchy(t.serial)).flat,l=t.matchNodes(c,s,e)[0],l){d=!0,t.lastHierarchy&&(t.lastHierarchy.timestamp=Date.now()),await Y(400);break}await Y(200)}}if(d||(await t.driver.swipe(a,Math.round(o*.75),a,Math.round(o*.35),300,t.serial),await Y(400),c=(await t.getCleanHierarchy(t.serial)).flat,l=t.matchNodes(c,s,e)[0],l&&(d=!0)),!d){if(t.upcomingSteps&&t.upcomingSteps.length>0&&!c.some(u=>u.password===!0||u.className.includes("EditText")&&c.some(g=>g.text?.toLowerCase().includes("password")))){let u=t.upcomingSteps.findIndex(g=>g.type==="VERIFY"&&g.target&&t.matchNodes(c,g.target,g).length>0);if(u!==-1)return{fastForwarded:!0,reason:`Screen is already on "${t.upcomingSteps[u].target}"`,skipCount:u}}throw await t.driver.swipe(a,Math.round(o*.35),a,Math.round(o*.75),300,t.serial),await Y(300),t.buildDiagnosticError(s,c,`Verification assertion failed: "${s}" is not visible on screen.`)}if(l&&i==="disabled"&&l.enabled)throw new Error(`State assertion failed: "${s}" was expected to be DISABLED, but is enabled.`);if(l&&i==="enabled"&&!l.enabled)throw new Error(`State assertion failed: "${s}" was expected to be ENABLED, but is disabled.`)}},Zt=class{type="BACK";async execute(e,t){await t.driver.pressKey(4,t.serial),await Y(E.settle.backMs),t.setLastHierarchy(null)}},es=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,a=e.direction||"down",d=!1;for(let c=0;c<5;c++){let{flat:l}=await t.getCleanHierarchy(t.serial),h=t.matchNodes(l,o,e);if(h.length>0){await t.ensureInViewport(h[0],t.serial),d=!0;break}a==="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 Y(E.settle.scrollMs),t.setLastHierarchy(null)}if(!d){let{flat:c}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(o,c,`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 Y(E.settle.scrollMs),t.setLastHierarchy(null)}},ts=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:l}=await t.waitForTarget(e.target,t.serial,2500,e);if(l.length>0){let h=l[0],u=r==="left"?h.bounds.x2-40:r==="right"?h.bounds.x1+40:h.bounds.centerX,g=r==="left"?h.bounds.x1+40:r==="right"?h.bounds.x2-40:h.bounds.centerX,f=r==="up"?h.bounds.y2-40:r==="down"?h.bounds.y1+40:h.bounds.centerY,y=r==="up"?h.bounds.y1+40:r==="down"?h.bounds.y2-40:h.bounds.centerY;await t.driver.swipe(u,f,g,y,E.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null);return}}let o=r==="left"?Math.round(s*.8):r==="right"?Math.round(s*.2):n,a=r==="left"?Math.round(s*.2):r==="right"?Math.round(s*.8):n,d=Math.round(r==="up"?i*.75:r==="down"?i*.35:i*.5),c=Math.round(r==="up"?i*.35:r==="down"?i*.75:i*.5);await t.driver.swipe(o,d,a,c,E.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null)}},ss=class{type="TOGGLE";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Toggle element matching "${s}" not found.`);let r=n.find(a=>a.clickable)||n[0];if(await t.ensureInViewport(r,t.serial)){let a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched.find(d=>d.clickable)||a.matched[0])}if(e.desiredState!==void 0&&r.checked!==void 0&&r.checked===e.desiredState){console.log(se.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 Y(E.settle.toggleMs),t.setLastHierarchy(null)}},is=class{type="SELECT";async execute(e,t){let s=e.target,i=e.value,{flat:n,matched:r}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,n,`Dropdown / picker element matching "${s}" not found.`);let o=r.find(c=>c.clickable)||r[0];await t.driver.tap(o.bounds.centerX,o.bounds.centerY,t.serial),await Y(E.settle.selectMs),t.setLastHierarchy(null);let a=await t.waitForTarget(i,t.serial,E.polling.defaultTimeoutMs);if(a.matched.length===0)throw t.buildDiagnosticError(i,a.flat,`Dropdown option "${i}" not found.`);let d=a.matched[0];await t.driver.tap(d.bounds.centerX,d.bounds.centerY,t.serial),await Y(400),t.setLastHierarchy(null)}},rs=class{type="LAUNCH_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to launch app.");await t.driver.launchApp(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},ns=class{type="RESTART_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to restart app.");await t.driver.restartApp(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},os=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 Y(E.settle.stopMs),t.setLastHierarchy(null)}},as=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 Y(1e3),t.setLastHierarchy(null)}},cs=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 Y(400)}},ls=class{type="DEEP_LINK";async execute(e,t){let s=e.target;await t.driver.openDeepLink(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},ds=class{type="WAIT";async execute(e,t){await Y(e.durationMs||1e3)}},us=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(se.cyan(` [Conditional] Condition met: "${s}" is visible.`)),e.thenSteps&&e.thenSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.thenSteps,t)):(console.log(se.gray(` [Conditional] Condition not met: "${s}" is not visible.`)),e.elseSteps&&e.elseSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.elseSteps,t))}},ps=class{type="LOOP";async execute(e,t){let s=E.flow?.maxLoopIterations||50,i=Math.min(e.loopCount||1,s),n=e.childSteps||[];if(!(n.length===0||!t.executeChildSteps)){console.log(se.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()}}}}},hs=class{type="WAIT_UNTIL";async execute(e,t){let s=e.target,i=e.durationMs||E.flow?.waitUntilTimeoutMs||1e4,n=e.expectedState||"visible";console.log(se.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:a}=await t.waitForTarget(s,t.serial,1e3,e);if(a.length>0){let d=a[0];if(n==="enabled"&&!d.enabled){await Y(250);continue}o=!0;break}}catch{}await Y(250)}if(!o){let{flat:a}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(s,a,`WaitUntil assertion failed: "${s}" did not become ${n} within ${i}ms.`)}}},gs=class{type="SET_VARIABLE";async execute(e,t){let s=e.variableName,i=e.variableExpression||"";i=Xe(i,Object.fromEntries(t.variables));let n=Rs(i);t.variables.set(s,n),console.log(se.cyan(` [Variable] $${s} = "${n}"`))}},ms=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(se.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(se.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(se.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(se.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 Y(400),t.setLastHierarchy(null)}},fs=class{type="RUN_JS";async execute(e,t){let s=e.jsCode||e.value||"";if(!s)return;console.log(se.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(se.gray(" [JS Output]",...r)),error:(...r)=>console.error(se.red(" [JS Error]",...r))}},n=Ws.createContext(i);Ws.runInContext(s,n,{timeout:3e3});for(let[r,o]of Object.entries(i.vars))t.variables.set(r,String(o))}},bs=class{type="ENTER_OTP";async execute(e,t){console.log(se.cyan(" [OTP Capture] Detecting verification code..."));let s=null;if(process.env.PROMPTTEST_MOCK_OTP)s=process.env.PROMPTTEST_MOCK_OTP.trim(),console.log(se.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(se.gray(` [OTP Capture] Captured code from logcat: ${s}`)))}catch{}if(s||(s="123456",console.log(se.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 Dt().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 Y(250),await t.driver.inputText(s,t.serial)):await t.driver.inputText(s,t.serial)}}},ys=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(se.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(se.green(` \u2714 API Status HTTP ${r.status} matched expectation.`))}if(e.apiStorePath&&e.apiStoreVariable)try{let o=await r.text(),a=JSON.parse(o),d=this.resolveJsonPath(a,e.apiStorePath);d!==void 0&&(t.variables.set(e.apiStoreVariable,String(d)),console.log(se.cyan(` [Variable] $${e.apiStoreVariable} = "${d}" (from ${e.apiStorePath})`)))}catch(o){ke.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}},Ss=class{type="EMAIL_ASSERT";async execute(e,t){let s=e.emailRecipient||"",i=e.emailSubject||"";console.log(se.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(se.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(se.green(" \u2714 Email verified successfully."))}},Ii=[new zt,new Jt,new Dt,new Qt,new qt,new Zt,new es,new ts,new ss,new is,new rs,new ns,new os,new as,new cs,new ls,new ds,new us,new ps,new hs,new gs,new ms,new fs,new bs,new ys,new Ss],Gs=new Map(Ii.map(p=>[p.type,p]));var Qe=class{providerName="heuristic";async resolveIntent(e,t){let s=X(e);return(s.includes("login")||s.includes("log in")||s.includes("sign in")||s.includes("signin"))&&(s.includes("test user")||s.includes("default credentials")||s.includes("credentials"))?[{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"}]:s.includes("sign up with random user")||s.includes("register new user")?[{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"}]:s.includes("dismiss dialog")||s.includes("close modal")||s.includes("dismiss popup")?[{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}]:null}async findSuggestions(e,t,s){let i=[],n=X(e),r=new Set,o=js(e,s?.locale);for(let l of o){let h=t.find(u=>u.bounds.width>0&&u.bounds.height>0&&(z(l,u.text)||z(l,u.contentDesc)));if(h){let u=(h.text||h.contentDesc||l).trim();r.has(u)||(r.add(u),i.push({text:u,score:.9,node:h,strategy:"synonym",reason:`Direct synonym match for "${e}" via semantic dictionary`}))}}for(let l of t)if(l.resourceId&&l.bounds.width>0&&l.bounds.height>0&&l.resourceId.toLowerCase().split(/[:/_]/).some(g=>g===n||n.includes(g))){let g=(l.text||l.contentDesc||l.resourceId).trim();r.has(g)||(r.add(g),i.push({text:g,score:.85,node:l,strategy:"exact",reason:`Resource-ID segment matches target "${e}"`}))}let a=[];for(let l of t)l.bounds.width>0&&l.bounds.height>0&&(l.text&&l.text.trim().length>1&&a.push({text:l.text.trim(),node:l}),l.contentDesc&&l.contentDesc.trim().length>1&&a.push({text:l.contentDesc.trim(),node:l}));let d=Array.from(new Set(a.map(l=>l.text))),c=We(e,d,5);for(let l of c)if(l.score>=.7&&!r.has(l.text)){r.add(l.text);let h=a.find(u=>u.text===l.text)?.node;i.push({text:l.text,score:l.score,node:h,strategy:"fuzzy",reason:`String similarity match (${Math.round(l.score*100)}%)`})}return i.sort((l,h)=>h.score-l.score)}};var lt=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 Qe().findSuggestions(e,t)}},At=class{providerName;config;heuristicFallback;constructor(e){this.config=e,this.providerName=e.provider,this.heuristicFallback=new Qe}async resolveIntent(e,t){if(this.config.provider==="mock")return new lt().resolveIntent(e,t);try{let s=`You are a test automation engineer generating steps for PromptTest.
|
|
795
|
+
</html>`}var nt=new At;import Ne from"fs";import qe from"path";import{fileURLToPath as Mn}from"url";var $t={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"]}},zr=$t.en,Xt=new Map;function ki(a){let e=new Map;for(let[t,s]of Object.entries(a)){let r=[oe(t),...s.map(n=>oe(n))];for(let n of r){e.has(n)||e.set(n,[]);let o=e.get(n);for(let c of r)o.includes(c)||o.push(c)}}return e}for(let[a,e]of Object.entries($t))Xt.set(a.toLowerCase(),ki(e));function Gr(a,e){let t=a.toLowerCase();$t[t]={...$t[t]||{},...e},Xt.set(t,ki($t[t]))}function Kr(){return Object.keys($t)}function Yt(a,e="en"){let t=oe(a),s=(e||"en").toLowerCase(),i=Xt.get(s);if(i){let r=i.get(t);if(r&&r.length>0)return r}if(s!=="en"){let r=Xt.get("en");if(r){let n=r.get(t);if(n&&n.length>0)return n}}return[t]}var Di=Yt;var rt=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=qe.dirname(Mn(import.meta.url));this.memoryDir=qe.resolve(t,"..","memory")}Ne.existsSync(this.memoryDir)||Ne.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=qe.join(this.memoryDir,`${this.currentPackage}.json`);if(Ne.existsSync(t))try{let s=await Ne.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(i&&i.mappings){let r=!i.version||i.version<2;for(let[n,o]of Object.entries(i.mappings))r&&(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(n,o);if(i.screens)for(let[n,o]of Object.entries(i.screens))this.screens.set(n,o);if(i.intents)for(let[n,o]of Object.entries(i.intents))this.intents.set(n,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=oe(e),s=Yt(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 r=`${e.toUpperCase()}:${oe(t)}`,n=this.mappings.get(r);if(n)return n;let o=Yt(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 r=(s||this.locale||"en").toLowerCase(),n=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===oe(t))&&d.confidence>=.7&&n.add(d.matchedIdentifier)}let o=this.resolve(e,t);o&&o.confidence>=.8&&n.add(o.matchedIdentifier),n.add(t);let c=Yt(t,r);for(let l of c)n.add(l);return Array.from(n)}recordSuccess(e,t,s,i,r=1,n,o){if(s.length>35||s.includes("?")||s.includes(`
|
|
796
|
+
`))return;let c=this.buildKey(e,t),l=this.mappings.get(c),p=new Date().toISOString(),d=n||l?.healedFrom?C.memory?.maxHealedConfidence??.65:1,h=n||l?.healedFrom?Math.min(r,d):r;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,n&&(l.healedFrom=n)):this.mappings.set(c,{canonicalIntent:this.getCanonicalQuery(t),action:e.toUpperCase(),matchedIdentifier:s,matchType:i,confidence:h,successCount:1,failCount:0,totalSuccesses:1,recentOutcomes:["PASS"],lastUpdated:p,lastSeenTs:p,healedFrom:n}),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 r of t)i.safeActions.includes(r)||i.safeActions.push(r)}}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=oe(e),i=new Date().toISOString(),r=this.intents.get(s);r?(r.steps=[...t],r.usageCount=(r.usageCount||1)+1,r.learnedAt=i):this.intents.set(s,{intent:e,steps:[...t],learnedAt:i,usageCount:1}),this.dirty=!0}getIntentExpansion(e){if(!e)return;let t=oe(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(oe(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(n=>n==="FAIL").length>=3||i.confidence<.2)&&this.mappings.delete(s),this.dirty=!0)}decayStaleMappings(e){let s=(e??C.memory?.staleThresholdDays??14)*24*60*60*1e3,i=Date.now(),r=0;for(let n of this.mappings.values()){let o=n.lastSeenTs?new Date(n.lastSeenTs).getTime():0;if(o>0&&i-o>s){let c=C.memory?.staleDecayAmount??.2,l=C.memory?.minConfidenceFloor??.2,p=Math.max(l,Number((n.confidence-c).toFixed(2)));p<n.confidence&&(n.confidence=p,r++,this.dirty=!0)}}return r}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=qe.join(this.memoryDir,`${this.currentPackage}.json`),s=`${t}.tmp.${Date.now()}`;await Ne.promises.writeFile(s,JSON.stringify(e,null,2),"utf-8");try{await Ne.promises.rename(s,t)}catch{await Ne.promises.copyFile(s,t),await Ne.promises.unlink(s).catch(()=>{})}this.dirty=!1}async exportMemory(e){let t=e?qe.resolve(e):qe.join(this.memoryDir,`${this.currentPackage}-export.json`),s=qe.dirname(t);Ne.existsSync(s)||Ne.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 Ne.promises.writeFile(t,JSON.stringify(i,null,2),"utf-8"),t}async importMemory(e){let t=qe.resolve(e);if(!Ne.existsSync(t))throw new Error(`Memory import source file not found: ${t}`);let s=await Ne.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(!i||!i.mappings)throw new Error("Invalid memory file format: missing mappings object.");let r=0,n=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??n,lastUpdated:n}),r++)}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 r>0&&(this.dirty=!0,await this.save()),r}getMappingsList(){return Array.from(this.mappings.values())}getStats(){let e=Array.from(this.mappings.values()),t=e.reduce((r,n)=>r+(n.totalSuccesses||n.successCount||0),0),s=e.length>0?Number((e.reduce((r,n)=>r+n.confidence,0)/e.length).toFixed(2)):0,i=0;for(let r of this.screens.values())r.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=qe.join(this.memoryDir,`${t}.json`);return Ne.existsSync(s)?(await Ne.promises.unlink(s),t===this.currentPackage&&(this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1),!0):!1}},Ct=new rt;import je from"fs";import Rn from"path";import On from"os";var gs=new Map;function yt(a){let e=(a||"default").replace(/[^a-zA-Z0-9._-]/g,"_"),t=Rn.join(On.tmpdir(),`prompttest-${e}.lock`);if(je.existsSync(t))try{let i=je.readFileSync(t,"utf-8").trim(),r=parseInt(i,10);if(!isNaN(r)){if(r===process.pid)return{serial:a,lockFilePath:t,acquired:!0,pid:process.pid};try{throw process.kill(r,0),new Error(`Device "${a}" is locked by another PromptTest process (PID ${r}).
|
|
797
|
+
Wait for the other run to complete, or remove the lock file if it is stale: ${t}`)}catch(n){if(n.code==="ESRCH")try{je.unlinkSync(t)}catch{}else throw n}}}catch(i){let r=i;if(r.message&&r.message.includes("locked by another"))throw r;try{je.unlinkSync(t)}catch{}}try{je.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{je.existsSync(t)&&je.readFileSync(t,"utf-8").trim()===process.pid.toString()&&je.unlinkSync(t)}catch{}};return gs.set(t,s),process.once("exit",s),{serial:a,lockFilePath:t,acquired:!0,pid:process.pid}}function St(a){if(a)try{let e=gs.get(a.lockFilePath);if(e)process.removeListener("exit",e),gs.delete(a.lockFilePath),e();else if(je.existsSync(a.lockFilePath))try{je.readFileSync(a.lockFilePath,"utf-8").trim()===process.pid.toString()&&je.unlinkSync(a.lockFilePath)}catch{}}catch{}}import ms from"chalk";var fs={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4},zt=class{currentLevel="INFO";constructor(e){let t=(process.env.LOG_LEVEL||"").toUpperCase();e?this.currentLevel=e:fs[t]!==void 0?this.currentLevel=t:this.currentLevel="INFO"}setLevel(e){this.currentLevel=e}getLevel(){return this.currentLevel}isLevelEnabled(e){return fs[this.currentLevel]<=fs[e]}isJsonMode(){return(process.env.LOG_FORMAT||"").toLowerCase()==="json"}emitJson(e,...t){let s=t.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).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(ms.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(ms.yellow("[WARN]"),...e))}error(...e){this.isLevelEnabled("ERROR")&&(this.isJsonMode()?this.emitJson("ERROR",...e):console.error(ms.red("[ERROR]"),...e))}},Ge=new zt;import ot from"fs";import Ai from"path";var bs=class{checkpointDir;constructor(e){this.checkpointDir=e||Ai.resolve(process.cwd(),"output","checkpoints"),ot.existsSync(this.checkpointDir)||ot.mkdirSync(this.checkpointDir,{recursive:!0})}filePath(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Ai.join(this.checkpointDir,`${t}.checkpoint.json`)}async save(e,t,s,i){let r={specFile:e,packageName:t,lastPassedStep:s,totalSteps:i,savedAt:new Date().toISOString()},n=this.filePath(e)+`.tmp.${Date.now()}`;await ot.promises.writeFile(n,JSON.stringify(r,null,2),"utf-8"),await ot.promises.rename(n,this.filePath(e))}async load(e){let t=this.filePath(e);if(!ot.existsSync(t))return null;try{let s=await ot.promises.readFile(t,"utf-8");return JSON.parse(s)}catch{return null}}async clear(e){let t=this.filePath(e);ot.existsSync(t)&&await ot.promises.unlink(t)}async getResumeIndex(e){let t=await this.load(e);return t?t.lastPassedStep+1:0}},$i=new bs;import ve from"fs";import at from"path";import{PNG as wt}from"pngjs";import Fn from"pixelmatch";var ys={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"}},ct=class{baselineDir;defaultThreshold;constructor(e,t=.02){this.baselineDir=e||at.resolve(process.cwd(),"output","baselines"),this.defaultThreshold=t,ve.existsSync(this.baselineDir)||ve.mkdirSync(this.baselineDir,{recursive:!0})}filePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return at.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}.png`)}diffFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return at.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 at.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_masks.json`)}async getMasks(e,t){let s=this.masksFilePath(e,t);if(!ve.existsSync(s))return[];try{let i=await ve.promises.readFile(s,"utf-8"),r=JSON.parse(i);return Array.isArray(r)?r:r.masks||[]}catch{return[]}}async saveMasks(e,t,s){let i=this.masksFilePath(e,t);return await ve.promises.writeFile(i,JSON.stringify(s,null,2),"utf-8"),i}async saveBaseline(e,t,s){let i=this.filePath(e,t),r=i+`.tmp.${Date.now()}`;return await ve.promises.writeFile(r,s),await ve.promises.rename(r,i),i}hasBaseline(e,t){return ve.existsSync(this.filePath(e,t))}async compare(e,t,s,i){let r=typeof i=="number"?{threshold:i}:i||{},n=this.filePath(e,t),o=at.join(this.baselineDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}_current.png`);await ve.promises.writeFile(o,s);let c=r.mode?ys[r.mode]:void 0,l=r.threshold??c?.threshold??this.defaultThreshold,p=r.pixelmatchThreshold??c?.pixelmatchThreshold??.1;if(!ve.existsSync(n)){await this.saveBaseline(e,t,s);let M=wt.sync.read(s),J=M.width*M.height;return{stepName:`Step ${t}`,baselineFile:n,currentFile:o,diffRatio:0,diffPixels:0,totalPixels:J,passed:!0,threshold:l}}let d=await ve.promises.readFile(n),h=wt.sync.read(d),u=wt.sync.read(s),m=Math.max(h.width,u.width),y=Math.max(h.height,u.height),v=m*y,T=this.fitToCanvas(h,m,y),S=this.fitToCanvas(u,m,y),b=r.maskRegions??await this.getMasks(e,t);b&&b.length>0&&(this.applyMasks(T,b),this.applyMasks(S,b));let E=new wt({width:m,height:y}),D=Fn(T.data,S.data,E.data,m,y,{threshold:p,includeAA:!1}),B=v>0?D/v:0,k=B<=l,j;if(k){let M=this.diffFilePath(e,t);if(ve.existsSync(M))try{await ve.promises.unlink(M)}catch{}}else{j=this.diffFilePath(e,t);let M=wt.sync.write(E);await ve.promises.writeFile(j,M)}return{stepName:`Step ${t}`,baselineFile:n,currentFile:o,diffRatio:B,diffPixels:D,totalPixels:v,passed:k,threshold:l,diffImagePath:j}}fitToCanvas(e,t,s){if(e.width===t&&e.height===s)return e;let i=new wt({width:t,height:s});return i.data.fill(0),wt.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),r=Math.round(i?s.x*e.width:s.x),n=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,n),p=Math.min(e.height,n+c),d=Math.max(0,r),h=Math.min(e.width,r+o);for(let u=l;u<p;u++)for(let m=d;m<h;m++){let y=e.width*u+m<<2;e.data[y]=0,e.data[y+1]=0,e.data[y+2]=0,e.data[y+3]=0}}}async approveBaseline(e,t,s){let i;if(s)i=await this.saveBaseline(e,t,s);else{let n=e.replace(/[^a-zA-Z0-9._-]/g,"_"),o=at.join(this.baselineDir,`${n}_step${String(t).padStart(3,"0")}_current.png`);if(!ve.existsSync(o))throw new Error(`No current screenshot found to approve for step ${t}`);let c=await ve.promises.readFile(o);i=await this.saveBaseline(e,t,c)}let r=this.diffFilePath(e,t);if(ve.existsSync(r))try{await ve.promises.unlink(r)}catch{}return i}async clearBaselines(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");if(!ve.existsSync(this.baselineDir))return;let s=await ve.promises.readdir(this.baselineDir);await Promise.all(s.filter(i=>i.startsWith(t+"_step")).map(i=>ve.promises.unlink(at.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(!ve.existsSync(this.baselineDir))return;let r=await ve.promises.readdir(this.baselineDir);await Promise.all(r.filter(n=>n.startsWith(i)).map(n=>ve.promises.unlink(at.join(this.baselineDir,n)).catch(()=>{})))}},Ss=new ct;import ue from"chalk";import _i from"vm";import It from"chalk";var _n=["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"],Hn=["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 vt(a){if(!a)return!1;let e=a.toLowerCase();return _n.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 ws(a){if(!a)return!1;let e=a.toLowerCase();return Hn.some(t=>e===t.toLowerCase()||e.startsWith(t.toLowerCase()))}function Gt(a,e){if(!a||!e)return!0;let t=a.toLowerCase(),s=e.toLowerCase();return!!(t===s||t.startsWith(`${s}.`)||ws(a))}function vs(a){if(!a||a.length===0)return null;for(let e of a)if(e.packageName&&(e.clickable||e.focused||e.scrollable)&&!ws(e.packageName))return e.packageName;for(let e of a)if(e.packageName&&!ws(e.packageName))return e.packageName;return a[0]?.packageName||null}async function xs(a,e,t,s){if(!e)return{escaped:!1,recovered:!0,currentPackage:null};let i=vs(a);if(!i)return{escaped:!1,recovered:!0,currentPackage:null};if(Gt(i,e))return{escaped:!1,recovered:!0,currentPackage:i};let r=vt(i);console.log(It.yellow(`
|
|
798
|
+
\u{1F6E1}\uFE0F [Jail Guard] Boundary Violation Detected: Active screen belongs to "${i}" (not target "${e}").`)),console.log(r?It.cyan(` [Jail Guard] Device is on home launcher. Suppressing back-press to prevent exit loops. Re-launching "${e}"...`):It.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 n=await t.getForegroundPackage(s),o=n?n.includes(e):!0;return console.log(o?It.green(` \u2714 [Jail Guard] Containment restored: "${e}" is now in foreground.`):It.red(` \u274C [Jail Guard] Recovery failed. Current foreground is still "${n}".`)),{escaped:!0,recovered:o,currentPackage:i}}catch(n){return console.log(It.red(` \u274C [Jail Guard] Error during containment recovery: ${n.message}`)),{escaped:!0,recovered:!1,currentPackage:i}}}import Ci from"fs";import Kt from"path";import ge from"chalk";function Ts(a,e=new Set){let t=Kt.resolve(a);if(!Ci.existsSync(t))throw new Error(`Included spec file not found: ${t}`);if(e.has(t)){let n=Array.from(e).concat(t);throw new _t(`Circular spec inclusion detected: ${n.join(" -> ")}`,n)}e.add(t);let i=Ci.readFileSync(t,"utf-8").split(`
|
|
799
|
+
`),r=[];for(let n of i){let o=n.trim(),c=o.match(G.INCLUDE_SPEC);if(c&&!o.startsWith("#")){let l=ae([c[1],c[2],c[3]]),p=Kt.isAbsolute(l)?l:Kt.resolve(Kt.dirname(t),l),d=Ts(p,new Set(e));r.push(d)}else r.push(n)}return r.join(`
|
|
800
|
+
`)}function Bn(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 r=t[t.length-1];r.step.type==="IF_VISIBLE"?r.inElse?(r.step.elseSteps=r.step.elseSteps||[],i=r.step.elseSteps):(r.step.thenSteps=r.step.thenSteps||[],i=r.step.thenSteps):r.step.type==="LOOP"&&(r.step.childSteps=r.step.childSteps||[],i=r.step.childSteps)}i.push(s),(s.type==="IF_VISIBLE"||s.type==="LOOP")&&t.push({step:s,inElse:!1})}return e}function Nt(a,e){let t=a.split(`
|
|
801
|
+
`).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#")),s=[];for(let i of t){let r=ft(i,e),n=r.replace(fi,"").trim(),o=G.OPTIONAL_SUFFIX.test(n)||/^[(\[]\s*optional\s*[)\]]/i.test(n)||/^optional\s*:/i.test(n),c=n.replace(G.OPTIONAL_SUFFIX,"").replace(/^[(\[]\s*optional\s*[)\]]\s*/i,"").replace(/^optional\s*:\s*/i,"").trim();if(G.BACK.test(c)){s.push({originalText:r,type:"BACK",optional:o});continue}let l=c.match(G.WAIT);if(l){let x=parseInt(l[1],10),$=c.toLowerCase().includes("ms")?x:x*1e3;s.push({originalText:r,type:"WAIT",durationMs:$,optional:o});continue}let p=c.match(G.WAIT_UNTIL);if(p){let x=ae([p[1],p[2],p[3]]),A=(p[4]||"visible").toLowerCase().includes("enable")?"enabled":"visible",H=p[5]?parseInt(p[5],10):void 0,R=(p[6]||"s").toLowerCase(),W=H?R.includes("ms")?H:H*1e3:void 0;s.push({originalText:r,type:"WAIT_UNTIL",target:x,expectedState:A,durationMs:W,optional:o});continue}let d=c.match(G.IF_VISIBLE);if(d){let x=ae([d[1],d[2],d[3],d[5],d[6],d[7]]);s.push({originalText:r,type:"IF_VISIBLE",conditionTarget:x,thenSteps:[],elseSteps:[],optional:o});continue}if(G.ELSE.test(c)){s.push({originalText:r,type:"IF_VISIBLE",_isControl:"ELSE"});continue}if(G.END.test(c)){s.push({originalText:r,type:"IF_VISIBLE",_isControl:"END"});continue}let h=c.match(G.LOOP);if(h){let x=parseInt(h[1],10);s.push({originalText:r,type:"LOOP",loopCount:x,childSteps:[],optional:o});continue}let u=c.match(G.FOR_EACH);if(u){let x=ae([u[1],u[2],u[3]]);s.push({originalText:r,type:"LOOP",target:x,loopVariable:"item",childSteps:[],optional:o});continue}let m=c.match(G.SET_VARIABLE);if(m){let x=m[1].trim(),$=m[2].trim();s.push({originalText:r,type:"SET_VARIABLE",variableName:x,variableExpression:$,optional:o});continue}let y=c.match(G.DEVICE_WIFI);if(y){let x=y[1].toLowerCase();s.push({originalText:r,type:"DEVICE_STATE",deviceAction:"wifi",deviceStateValue:x==="on"||x==="enable",optional:o});continue}let v=c.match(G.DEVICE_AIRPLANE);if(v){let x=v[1].toLowerCase();s.push({originalText:r,type:"DEVICE_STATE",deviceAction:"airplane",deviceStateValue:x==="on"||x==="enable",optional:o});continue}let T=c.match(G.DEVICE_ORIENTATION);if(T){let x=T[1].toLowerCase();s.push({originalText:r,type:"DEVICE_STATE",deviceAction:"orientation",deviceStateValue:x,optional:o});continue}let S=c.match(G.DEVICE_NOTIFICATIONS);if(S){let x=S[1].toLowerCase(),$=x.startsWith("open")||x.startsWith("expand")||x.startsWith("pull");s.push({originalText:r,type:"DEVICE_STATE",deviceAction:"notifications",deviceStateValue:$?"open":"collapse",optional:o});continue}let b=c.match(G.RUN_JS);if(b){let x=b[1].trim();s.push({originalText:r,type:"RUN_JS",jsCode:x,optional:o});continue}let E=c.match(G.ENTER_OTP);if(E){let x=ae([E[1],E[2],E[3]])||void 0;s.push({originalText:r,type:"ENTER_OTP",target:x,optional:o});continue}let D=c.match(G.API_REQUEST);if(D){let x=D[1].toUpperCase(),$=ae([D[2],D[3],D[4]]),A=ae([D[5],D[6],D[7]])||void 0,H=ae([D[8],D[9],D[10]])||void 0,R=D[11]||void 0,W=D[12]?parseInt(D[12],10):void 0;s.push({originalText:r,type:"API_REQUEST",apiMethod:x,apiUrl:$,apiBody:A,apiStorePath:H,apiStoreVariable:R,apiExpectedStatus:W,optional:o});continue}let B=c.match(G.EMAIL_ASSERT);if(B){let x=ae([B[1],B[2],B[3]]),$=ae([B[4],B[5],B[6]]),A=ae([B[7],B[8],B[9]])||void 0;s.push({originalText:r,type:"EMAIL_ASSERT",emailRecipient:x,emailSubject:$,emailBodyContains:A,optional:o});continue}let k=c.match(G.LAUNCH_APP);if(k){let x=ae([k[1],k[2],k[3]]);s.push({originalText:r,type:"LAUNCH_APP",target:x,optional:o});continue}let j=c.match(G.RESTART_APP);if(j){let x=ae([j[1],j[2],j[3]]);s.push({originalText:r,type:"RESTART_APP",target:x,optional:o});continue}let M=c.match(G.TERMINATE_APP);if(M){let x=ae([M[1],M[2],M[3]])||void 0;s.push({originalText:r,type:"TERMINATE_APP",target:x,optional:o});continue}let J=c.match(G.CLEAR_DATA);if(J){let x=ae([J[1],J[2],J[3]]);s.push({originalText:r,type:"CLEAR_DATA",target:x,optional:o});continue}let Y=c.match(G.GRANT_PERMISSION);if(Y){let x=ae([Y[1],Y[2],Y[3]]),$=ae([Y[4],Y[5],Y[6]])||void 0;s.push({originalText:r,type:"GRANT_PERMISSION",value:x,target:$,optional:o});continue}let K=c.match(G.DEEP_LINK);if(K){let x=ae([K[1],K[2],K[3]]);s.push({originalText:r,type:"DEEP_LINK",target:x,optional:o});continue}let le=c.match(G.DIRECTIONAL_SWIPE);if(le){let x=le[1].toLowerCase(),$=ae([le[2],le[3],le[4]])||void 0;s.push({originalText:r,type:"SWIPE",direction:x,target:$,optional:o});continue}let Z=c.match(G.TOGGLE);if(Z){let x=(Z[1]||"").toLowerCase(),$=ae([Z[2],Z[3],Z[4]]),A=c.toLowerCase().startsWith("uncheck")||x==="off"?!1:x==="on"||c.toLowerCase().startsWith("check")?!0:void 0;s.push({originalText:r,type:"TOGGLE",target:$,desiredState:A,optional:o});continue}let _=c.match(G.SELECT_DROPDOWN);if(_){let x=ae([_[1],_[2],_[3]]),$=ae([_[4],_[5],_[6]]);s.push({originalText:r,type:"SELECT",value:x,target:$,optional:o});continue}let De=c.match(G.SCROLL_TO);if(De){let x=(De[1]||"down").toLowerCase(),$=ae([De[2],De[3],De[4]]);s.push({originalText:r,type:"SCROLL",target:$,direction:x,optional:o});continue}let w=c.match(G.SCROLL);if(w){let x=w[1].toLowerCase();s.push({originalText:r,type:"SCROLL",target:x,direction:x,optional:o});continue}let f=c.match(G.LONG_PRESS);if(f){let x=ae([f[1],f[2],f[3]]);s.push({originalText:r,type:"LONG_PRESS",target:x,optional:o});continue}let I=c.match(G.ORDINAL_TAP);if(I){let x=I[1].toLowerCase(),$=ae([I[2],I[3],I[4]]);s.push({originalText:r,type:"TAP",target:$,ordinal:x,optional:o});continue}let N=c.match(G.PROXIMITY_TAP);if(N){let x=ae([N[1],N[2],N[3]]),$=ae([N[4],N[5],N[6]]);s.push({originalText:r,type:"TAP",target:x,relativeTo:$,optional:o});continue}let de=c.match(G.TYPE);if(de){let x=ae([de[1],de[2],de[3]]),$=ae([de[4],de[5],de[6]]);s.push({originalText:r,type:"TYPE",value:x,target:$,optional:o});continue}let he=c.match(G.CLEAR);if(he){let x=ae([he[1],he[2],he[3]]);s.push({originalText:r,type:"CLEAR",target:x,optional:o});continue}let g=c.match(G.VERIFY);if(g){let x=ae([g[1],g[2],g[3]]),$=(g[4]||"visible").toLowerCase(),A=$.includes("not visible")||$.includes("not present")||$.includes("absent")||$.includes("hidden")||$.includes("gone"),H=A?"absent":$==="exists"||$==="enabled"||$==="disabled"?$:"visible";s.push({originalText:r,type:"VERIFY",target:x,expectedState:H,negative:A,optional:o});continue}let P=c.match(G.TAP);if(P&&!c.toLowerCase().includes("back")){let x=ae([P[1],P[2],P[3]]);s.push({originalText:r,type:"TAP",target:x,optional:o});continue}let O=c.match(G.FALLBACK_QUOTED_TAP);if(O&&(c.toLowerCase().startsWith("tap")||c.toLowerCase().startsWith("click"))){s.push({originalText:r,type:"TAP",target:O[1],optional:o});continue}Ge.warn(`Unrecognized prompt step: "${i}". Skipping.`)}return Bn(s)}function Ni(a,e,t){let s=e.map(n=>(n.text||n.contentDesc||"").trim()).filter(n=>n.length>1),i=bt(a,s,3),r=i.length>0?`
|
|
802
|
+
\u{1F4A1} Did you mean one of these visible items?
|
|
803
|
+
`+i.map(n=>` \u2022 "${n.text}" (${Math.round(n.score*100)}% match)`).join(`
|
|
804
|
+
`):`
|
|
805
|
+
\u{1F4A1} No similar text found on current screen.`;return new Error(`${t}${r}`)}function Li(a,e,t,s){let i=oe(e),r=i.includes("password")||i.includes("passcode")||i.includes("pin")||i.includes("pwd")||i.includes("secret"),n=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=>pe(e,p.contentDesc)||pe(e,p.resourceId)||pe(e,p.text));if(c)return c;let l=a.filter(p=>!p.className.includes("EditText")&&(pe(e,p.text)||pe(e,p.contentDesc)||pe(e,p.resourceId))&&p.bounds.width>0);for(let p of l){let d=o.filter(h=>h.bounds.centerY>=p.bounds.centerY&&h.bounds.centerY-p.bounds.centerY<300&&Math.abs(h.bounds.centerX-p.bounds.centerX)<450);if(d.length>0)return d.sort((h,u)=>h.bounds.centerY-u.bounds.centerY),d[0]}if(s){let p=s.getAllCandidates("TYPE",e);for(let d of p){let h=o.find(u=>pe(d,u.contentDesc)||pe(d,u.resourceId)||pe(d,u.text));if(h)return h}}if(r){let p=o.find(d=>d.password);if(p)return p;if(o.length>1){let d=o.find(h=>h.text?.toLowerCase().includes("email")||h.contentDesc?.toLowerCase().includes("email"));if(d){let h=o.filter(u=>u.bounds.centerY>d.bounds.centerY);if(h.length>0)return h.sort((u,m)=>u.bounds.centerY-m.bounds.centerY),h[0]}}if(o.length>=2)return o[1]}if(n){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 Qt(a,e,t,s="en",i,r){let n=i?.type||"TAP",o=oe(e),l=a.filter(u=>(oe(u.text)===o||oe(u.contentDesc)===o)&&u.bounds.width>0&&u.bounds.height>0).find(u=>u.clickable);if(l)return[l];let p=t.getAllCandidates(n,e,s,r),d=[];for(let u of p){let m=a.filter(y=>{let v=pe(u,y.text),T=pe(u,y.contentDesc),S=pe(u,y.resourceId);return(v||T||S)&&y.bounds.width>0&&y.bounds.height>0});if(m.length>0){d=m;break}}if(d.length===0){let u=[];for(let y of a)y.text&&y.text.trim().length>1&&u.push(y.text.trim()),y.contentDesc&&y.contentDesc.trim().length>1&&u.push(y.contentDesc.trim());let m=bt(e,u,1);if(m.length>0&&m[0].score>=.8){let y=m[0].text,v=a.filter(T=>(pe(y,T.text)||pe(y,T.contentDesc))&&T.bounds.width>0&&T.bounds.height>0);v.length>0&&(console.log(ge.yellow(` \u{1F4A1} [Self-Healing] Auto-resolved "${e}" \u2192 "${y}" (${Math.round(m[0].score*100)}% match)`)),d=v)}}if(d.length===0)return[];let h=d.filter(u=>{let m=oe(u.text),y=oe(u.contentDesc);return m===o||y===o});if(h.length>0)d=h;else{let u=d.filter(m=>{let y=oe(m.contentDesc);return y.endsWith(o)||y.includes(`, ${o}`)});u.length>0&&(d=u)}if(i?.relativeTo){let u=a.find(m=>pe(i.relativeTo,m.text)||pe(i.relativeTo,m.contentDesc));if(u){let m=d.filter(y=>Math.abs(y.bounds.centerY-u.bounds.centerY)<140).sort((y,v)=>{let T=Math.hypot(y.bounds.centerX-u.bounds.centerX,y.bounds.centerY-u.bounds.centerY),S=Math.hypot(v.bounds.centerX-u.bounds.centerX,v.bounds.centerY-u.bounds.centerY);return T-S});if(m.length>0)return m}}if(i?.ordinal){let u=i.ordinal.toLowerCase();if(u==="1st"||u==="first")return[d[0]];if(u==="2nd"&&d.length>1)return[d[1]];if(u==="3rd"&&d.length>2)return[d[2]];if(u==="4th"&&d.length>3)return[d[3]];if(u==="5th"&&d.length>4)return[d[4]];if(u==="last"&&d.length>0)return[d[d.length-1]]}return d}function be(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 r=0;r<i.length;r++)e^=i.charCodeAt(r),e=Math.imul(e,16777619)}return(e>>>0).toString(16)}var Un=[/\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 Ii(a){if(!a)return"";let e=a;for(let t of Un)e=e.replace(t,"<VAL>");return e.trim()}function Oe(a,e){if(!a||a.length===0)return"0";let s=(e?.height||2400)*.04,i=2166136261;for(let r=0;r<a.length;r++){let n=a[r];if(n.bounds&&n.bounds.centerY<s)continue;let o=Ii(n.text||""),c=Ii(n.contentDesc||""),l=n.resourceId||"",p=n.className||"",d=n.clickable?"1":"0",h=n.checkable?"1":"0",u=Math.round((n.bounds?.x1||0)/50),m=Math.round((n.bounds?.y1||0)/50),y=Math.round((n.bounds?.width||0)/50),v=Math.round((n.bounds?.height||0)/50),T=`${p}|${l}|${o}|${c}|${d}|${h}|${u},${m},${y},${v}`;for(let S=0;S<T.length;S++)i^=T.charCodeAt(S),i=Math.imul(i,16777619)}return(i>>>0).toString(16)}function Ao(a,e){let t=be(a),s=be(e);return{hasChanged:t!==s,previousHash:t,currentHash:s,nodeCountDelta:e.length-a.length}}function Mi(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,r]=s.split("-").map(c=>c.trim()),n=parseInt(i,10),o=parseInt(r,10);if(!isNaN(n)&&!isNaN(o)){let[c,l]=n<=o?[n,o]:[o,n];for(let p=c;p<=l;p++)e.add(p)}}else{let i=parseInt(s,10);isNaN(i)||e.add(i)}return e}function Ri(a){let e=new Set,t=a.split(`
|
|
806
|
+
`);for(let s of t){let i=s.trim();if(!i.startsWith("#"))continue;let r=i.match(/#\s*@tags?:\s*(.+)/i);if(r){r[1].split(",").map(o=>o.trim().toLowerCase()).filter(Boolean).forEach(o=>e.add(o));continue}let n=i.match(/#\s*@([a-zA-Z0-9_-]+)/);n&&n[1].toLowerCase()!=="tags"&&n[1].toLowerCase()!=="tag"&&e.add(n[1].toLowerCase())}return Array.from(e)}function Oi(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),r=t.type.padEnd(14),n=(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(r)} `+ge.gray("\u2502")+` ${ge.yellow(n)} `+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
|
|
807
|
+
`)),e.join(`
|
|
808
|
+
`)}function Zt(a,e,t=[],s="SKIPPED",i="Validation"){let r=new Date().toISOString(),n=s==="PASS";return{packageName:a||"none",deviceId:e||"none",startTime:r,endTime:r,durationSeconds:0,totalSteps:t.length,passedSteps:n?t.length:0,failedSteps:0,skippedSteps:n?0:t.length,warnSteps:0,errorsDetected:[],steps:t.map((o,c)=>({stepIndex:c+1,timestamp:r,phase:i,description:o.originalText,action:o.type,target:o.target,status:s,durationMs:0}))}}function $o(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)}var jn=["ProgressBar","CircularProgressIndicator","LinearProgressIndicator","ContentLoadingProgressBar","LoadingView","ActivityIndicator"],Yn=/(?:loading|spinner|shimmer|skeleton|progress[-_]?bar|refreshing)/i,Fi=/^(?:loading|please wait|fetching|authenticating|syncing|processing)\.{0,3}$/i;function Es(a){if(!a||a.length===0)return{loading:!1};for(let e of a){if(e.className&&jn.some(t=>e.className.includes(t)))return{loading:!0,reason:`Active widget <${e.className}>`};if(e.resourceId&&Yn.test(e.resourceId))return{loading:!0,reason:`Loading resource ID "${e.resourceId}"`};if(e.contentDesc&&Fi.test(e.contentDesc.trim()))return{loading:!0,reason:`Loading description "${e.contentDesc}"`};if(e.text&&Fi.test(e.text.trim()))return{loading:!0,reason:`Loading status text "${e.text}"`}}return{loading:!1}}async function Ps(a,e=4500,t=150){let s=Date.now(),i="",r=0,n=[];for(;Date.now()-s<e;){a.setLastHierarchy(null);let{flat:o}=await a.getCleanHierarchy(a.serial);if(n=o,Es(o).loading){r=0,i="",await new Promise(h=>setTimeout(h,220));continue}let l=be(o);if(l===i&&l!=="0"){if(r++,r>=1)return{settled:!0,durationMs:Date.now()-s,finalHash:l,flat:n}}else r=0,i=l;let p=Date.now()-s,d=e-p;if(d<=0)break;await new Promise(h=>setTimeout(h,Math.min(t,d)))}return{settled:!1,durationMs:Date.now()-s,finalHash:i||(n.length>0?be(n):"0"),flat:n}}function ie(a){return new Promise(e=>setTimeout(e,a))}function Wn(a){let e=a.screenDimensions.height,t=a.navBarHeight>0?e-a.navBarHeight:e,s=a.navBarHeight>0?t*.94:e*C.gestures.bottomNavThresholdRatio;return{effectiveHeight:t,bottomThreshold:s}}var ks=class{type="TAP";async execute(e,t){let s=e.target,{width:i,height:r}=t.screenDimensions,n=Math.round(i*.5),{flat:o,matched:c}=await t.waitForTarget(s,t.serial,C.polling.defaultTimeoutMs,e);if(c.length===0&&t.upcomingSteps&&t.upcomingSteps.length>0&&!o.some(D=>D.password===!0||D.className.includes("EditText")&&o.some(B=>B.text?.toLowerCase().includes("password")))){let D=t.upcomingSteps.findIndex(k=>k.type==="VERIFY"&&k.target&&t.matchNodes(o,k.target,k).length>0);if(D!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[D].target}"`,skipCount:D};let B=t.upcomingSteps.findIndex(k=>k.type==="TAP"&&k.target&&t.matchNodes(o,k.target,k).length>0);if(B!==-1)return{fastForwarded:!0,reason:`Upcoming action "${t.upcomingSteps[B].target}" is directly actionable`,skipCount:B}}if(c.length===0){await t.driver.swipe(n,Math.round(r*.75),n,Math.round(r*.35),300,t.serial),await ie(350),t.setLastHierarchy(null);let E=await t.waitForTarget(s,t.serial,2e3,e);o=E.flat,c=E.matched}if(c.length===0)throw t.buildDiagnosticError(s,o,`Element matching "${s}" not found on current screen.`);let l=c.find(E=>E.clickable)||c[0];if(t.targetPackage&&!Gt(l.packageName,t.targetPackage))throw console.log(ue.red(` \u{1F6A8} [Jail Guard] Blocked Tap on foreign package "${l.packageName}". Target is "${t.targetPackage}".`)),await xs(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 E=await t.waitForTarget(s,t.serial,1500,e);E.matched.length>0&&(o=E.flat,c=E.matched,l=c.find(D=>D.clickable)||c[0])}let d=l.bounds.centerX,{effectiveHeight:h}=Wn(t),u=l.bounds.centerY;if(l.bounds.y2>h&&(u=Math.min(Math.round((l.bounds.y1+h)/2),h-15)),u=Math.min(u,l.bounds.y2-2),u=Math.max(u,l.bounds.y1+2),u>r*.5&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(ue.gray(` [Keyboard] Target occluded by soft keyboard (Y=${u} > ${Math.round(r*.5)}). Dismissing...`)),await t.driver.pressBack(t.serial),await ie(300),t.setLastHierarchy(null))}catch{}let m=Oe(o,t.screenDimensions),y=l.contentDesc||l.text||l.resourceId;console.log(ue.gray(` [Tap Target] (${d}, ${u}) for "${y||s}"`));let v=t.lastHierarchy?.hash;await t.driver.tap(d,u,t.serial),t.setLastHierarchy(null);let T=t.upcomingSteps&&t.upcomingSteps[0],S=T?.target?t.matchNodes(o,T.target,T).length>0:!1;if(T&&!S&&(T.type==="VERIFY"||T.type==="TAP")){let E=await Ps(t,4500),B=Oe(E.flat,t.screenDimensions)!==m,k=T.target?t.matchNodes(E.flat,T.target,T).length>0:!1;if(!B&&!k&&t.matchNodes(E.flat,s,e).length>0)throw new Error(`Navigation failed: Tap on "${s}" did not transition away from the current screen. Next expected element "${T.target}" is not visible.`)}else await ie(C.settle.tapMs);y&&oe(y)!==oe(s)&&t.memory.recordSuccess("TAP",s,y,l.contentDesc?"contentDesc":l.text?"text":"resourceId",1,void 0,v)}},Ds=class{type="LONG_PRESS";async execute(e,t){let s=e.target,{flat:i,matched:r}=await t.waitForTarget(s,t.serial,C.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,i,`Element matching "${s}" not found for long-press.`);let n=r[0];if(await t.ensureInViewport(n,t.serial)){let c=await t.waitForTarget(s,t.serial,1500,e);c.matched.length>0&&(n=c.matched[0])}await t.driver.swipe(n.bounds.centerX,n.bounds.centerY,n.bounds.centerX,n.bounds.centerY,C.gestures.longPressDurationMs,t.serial),await ie(300),t.setLastHierarchy(null)}},qt=class{type="TYPE";async execute(e,t){let s=e.target,i=e.value??"",r=[],n=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<C.polling.hierarchyCacheTtlMs){let d=t.findTargetInputField(t.lastHierarchy.flat,s,i);d&&(r=t.lastHierarchy.flat,n=d)}if(n||(r=(await t.getCleanHierarchy(t.serial)).flat,n=t.findTargetInputField(r,s,i)),!n){let d=Date.now();for(;Date.now()-d<2e3&&(await ie(200),r=(await t.getCleanHierarchy(t.serial)).flat,n=t.findTargetInputField(r,s,i),!n););}if(!n&&t.upcomingSteps&&t.upcomingSteps.length>0&&!r.some(h=>h.className.includes("EditText"))){let h=t.upcomingSteps.findIndex(u=>u.type==="VERIFY"&&u.target&&t.matchNodes(r,u.target,u).length>0);if(h!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[h].target}" and form is completed`,skipCount:h}}if(!n)throw t.buildDiagnosticError(s,r,`Input field matching "${s}" not found.`);if(t.targetPackage&&!Gt(n.packageName,t.targetPackage))throw console.log(ue.red(` \u{1F6A8} [Jail Guard] Blocked Type on foreign package "${n.packageName}". Target is "${t.targetPackage}".`)),await xs(r,t.targetPackage,t.driver,t.serial),new Error(`Security Boundary Violation: Refused to type into element belonging to foreign application "${n.packageName}". Containment enforced.`);if(n.text&&n.text===i){console.log(ue.gray(` [Input Field] Already contains desired value "${i}". Skipping typing.`));return}if(await t.ensureInViewport(n,t.serial)){r=(await t.getCleanHierarchy(t.serial)).flat;let h=t.findTargetInputField(r,s,i);h&&(n=h)}let{height:c}=t.screenDimensions;if(n.bounds.centerY>c*.5&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(ue.gray(" [Keyboard] Input field occluded by soft keyboard. Dismissing before focus...")),await t.driver.pressBack(t.serial),await ie(300),t.setLastHierarchy(null))}catch{}let l=t.lastHierarchy?.hash;await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await ie(C.settle.inputFocusMs),await t.driver.clearField(t.serial),await ie(C.settle.inputClearMs),await t.driver.inputText(i,t.serial),await ie(C.settle.inputDoneMs),t.setLastHierarchy(null);let p=n.contentDesc||n.resourceId;p&&oe(p)!==oe(s)&&t.memory.recordSuccess("TYPE",s,p,n.contentDesc?"contentDesc":"resourceId",1,void 0,l)}},As=class{type="CLEAR";async execute(e,t){let s=e.target,i=[],r=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<C.polling.hierarchyCacheTtlMs&&(r=t.findTargetInputField(t.lastHierarchy.flat,s),r&&(i=t.lastHierarchy.flat)),r||(i=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(i,s)),!r){let o=t.matchNodes(i,s,e);o.length>0&&(r=o[0])}if(!r)throw t.buildDiagnosticError(s,i,`Input field matching "${s}" not found to clear.`);await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await ie(300);let n=t.driver;n.clearField?await n.clearField(t.serial):n.clearInput&&await n.clearInput(50,t.serial),await ie(200),t.setLastHierarchy(null)}},$s=class{type="VERIFY";async execute(e,t){let s=e.target,i=e.expectedState||"visible";if(e.negative===!0||i==="absent"||i==="hidden"){let h=await t.getCleanHierarchy(t.serial);if(t.matchNodes(h.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:n,height:o}=t.screenDimensions,c=Math.round(n*.5),l=!1,p=[],d;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<C.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:Es(p).loading&&(console.log(ue.cyan(" \u23F3 [Quiescence] Loading indicator detected in Verify. Waiting for screen to settle...")),p=(await Ps(t,4500)).flat,d=t.matchNodes(p,s,e)[0],d&&(l=!0));let u=Date.now();for(;!l&&Date.now()-u<C.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 ie(400);break}await ie(200)}}if(l||(await t.driver.swipe(c,Math.round(o*.75),c,Math.round(o*.35),300,t.serial),await ie(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(u=>u.password===!0||u.className.includes("EditText")&&p.some(m=>m.text?.toLowerCase().includes("password")))){let u=t.upcomingSteps.findIndex(m=>m.type==="VERIFY"&&m.target&&t.matchNodes(p,m.target,m).length>0);if(u!==-1)return{fastForwarded:!0,reason:`Screen is already on "${t.upcomingSteps[u].target}"`,skipCount:u}}throw await t.driver.swipe(c,Math.round(o*.35),c,Math.round(o*.75),300,t.serial),await ie(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.`)}},Cs=class{type="BACK";async execute(e,t){let{flat:s}=await t.getCleanHierarchy(t.serial),i=vs(s);if(i&&vt(i)){console.log(ue.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 ie(C.settle.backMs),t.setLastHierarchy(null)}},Is=class{type="SCROLL";async execute(e,t){let{width:s,height:i}=t.screenDimensions,r=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),h=t.matchNodes(d,o,e);if(h.length>0){await t.ensureInViewport(h[0],t.serial),l=!0;break}c==="up"?await t.driver.swipe(r,Math.round(i*.35),r,Math.round(i*.75),300,t.serial):await t.driver.swipe(r,Math.round(i*.75),r,Math.round(i*.35),300,t.serial),await ie(C.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(r,Math.round(i*.35),r,Math.round(i*.75),300,t.serial):await t.driver.swipe(r,Math.round(i*.75),r,Math.round(i*.35),300,t.serial),await ie(C.settle.scrollMs),t.setLastHierarchy(null)}},Ns=class{type="SWIPE";async execute(e,t){let{width:s,height:i}=t.screenDimensions,r=Math.round(s*.5),n=e.direction||"left";if(e.target){let{matched:d}=await t.waitForTarget(e.target,t.serial,2500,e);if(d.length>0){let h=d[0],u=n==="left"?h.bounds.x2-40:n==="right"?h.bounds.x1+40:h.bounds.centerX,m=n==="left"?h.bounds.x1+40:n==="right"?h.bounds.x2-40:h.bounds.centerX,y=n==="up"?h.bounds.y2-40:n==="down"?h.bounds.y1+40:h.bounds.centerY,v=n==="up"?h.bounds.y1+40:n==="down"?h.bounds.y2-40:h.bounds.centerY;await t.driver.swipe(u,y,m,v,C.gestures.swipeDurationMs,t.serial),await ie(400),t.setLastHierarchy(null);return}}let o=n==="left"?Math.round(s*.8):n==="right"?Math.round(s*.2):r,c=n==="left"?Math.round(s*.2):n==="right"?Math.round(s*.8):r,l=Math.round(n==="up"?i*.75:n==="down"?i*.35:i*.5),p=Math.round(n==="up"?i*.35:n==="down"?i*.75:i*.5);await t.driver.swipe(o,l,c,p,C.gestures.swipeDurationMs,t.serial),await ie(400),t.setLastHierarchy(null)}},Ls=class{type="TOGGLE";async execute(e,t){let s=e.target,{flat:i,matched:r}=await t.waitForTarget(s,t.serial,C.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,i,`Toggle element matching "${s}" not found.`);let n=r.find(c=>c.clickable)||r[0];if(await t.ensureInViewport(n,t.serial)){let c=await t.waitForTarget(s,t.serial,1500,e);c.matched.length>0&&(n=c.matched.find(l=>l.clickable)||c.matched[0])}if(e.desiredState!==void 0&&n.checked!==void 0&&n.checked===e.desiredState){console.log(ue.gray(` [Toggle] "${s}" is already in desired state (${e.desiredState?"ON":"OFF"}).`));return}await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await ie(C.settle.toggleMs),t.setLastHierarchy(null)}},Ms=class{type="SELECT";async execute(e,t){let s=e.target,i=e.value,{flat:r,matched:n}=await t.waitForTarget(s,t.serial,C.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,r,`Dropdown / picker element matching "${s}" not found.`);let o=n.find(p=>p.clickable)||n[0];await t.driver.tap(o.bounds.centerX,o.bounds.centerY,t.serial),await ie(C.settle.selectMs),t.setLastHierarchy(null);let c=await t.waitForTarget(i,t.serial,C.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 ie(400),t.setLastHierarchy(null)}},Rs=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 ie(C.settle.launchMs),t.setLastHierarchy(null)}},Os=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 ie(C.settle.launchMs),t.setLastHierarchy(null)}},Fs=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 ie(C.settle.stopMs),t.setLastHierarchy(null)}},_s=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 ie(1e3),t.setLastHierarchy(null)}},Hs=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 ie(400)}},Bs=class{type="DEEP_LINK";async execute(e,t){let s=e.target;await t.driver.openDeepLink(s,t.serial),await ie(C.settle.launchMs),t.setLastHierarchy(null)}},Us=class{type="WAIT";async execute(e,t){await ie(e.durationMs||1e3)}},js=class{type="IF_VISIBLE";async execute(e,t){let s=e.conditionTarget||e.target;if(!s)return;let i=!1;try{let{matched:r}=await t.waitForTarget(s,t.serial,1500,e);i=r.length>0}catch{i=!1}i?(console.log(ue.cyan(` [Conditional] Condition met: "${s}" is visible.`)),e.thenSteps&&e.thenSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.thenSteps,t)):(console.log(ue.gray(` [Conditional] Condition not met: "${s}" is not visible.`)),e.elseSteps&&e.elseSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.elseSteps,t))}},Ys=class{type="LOOP";async execute(e,t){let s=C.flow?.maxLoopIterations||50,i=Math.min(e.loopCount||1,s),r=e.childSteps||[];if(!(r.length===0||!t.executeChildSteps)){console.log(ue.cyan(` [Loop] Starting loop iteration (1 to ${i})...`));for(let n=1;n<=i;n++){e.loopVariable&&t.variables.set(e.loopVariable,String(n)),t.loopStack.push({current:n,total:i,variable:e.loopVariable});try{await t.executeChildSteps(r,t)}finally{t.loopStack.pop()}}}}},Ws=class{type="WAIT_UNTIL";async execute(e,t){let s=e.target,i=e.durationMs||C.flow?.waitUntilTimeoutMs||1e4,r=e.expectedState||"visible";console.log(ue.gray(` [Wait Until] Waiting for "${s}" to be ${r} (up to ${i}ms)...`));let n=Date.now(),o=!1;for(;Date.now()-n<i;){try{let{matched:c}=await t.waitForTarget(s,t.serial,1e3,e);if(c.length>0){let l=c[0];if(r==="enabled"&&!l.enabled){await ie(250);continue}o=!0;break}}catch{}await ie(250)}if(!o){let{flat:c}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(s,c,`WaitUntil assertion failed: "${s}" did not become ${r} within ${i}ms.`)}}},Vs=class{type="SET_VARIABLE";async execute(e,t){let s=e.variableName,i=e.variableExpression||"";i=ft(i,Object.fromEntries(t.variables));let r=bi(i);t.variables.set(s,r),console.log(ue.cyan(` [Variable] $${s} = "${r}"`))}},Js=class{type="DEVICE_STATE";async execute(e,t){let s=e.deviceAction,i=e.deviceStateValue;switch(s){case"wifi":{let r=i===!0||i==="on"||i==="enable";console.log(ue.cyan(` [Device] Setting Wi-Fi: ${r?"ENABLED":"DISABLED"}`)),await t.driver.setWifiEnabled(r,t.serial);break}case"airplane":{let r=i===!0||i==="on"||i==="enable";console.log(ue.cyan(` [Device] Setting Airplane Mode: ${r?"ENABLED":"DISABLED"}`)),await t.driver.setAirplaneMode(r,t.serial);break}case"orientation":{let r=i==="landscape"?"landscape":"portrait";console.log(ue.cyan(` [Device] Setting Orientation: ${r.toUpperCase()}`)),await t.driver.setOrientation(r,t.serial);break}case"notifications":{let r=i==="open"||i==="expand"||i===!0;console.log(ue.cyan(` [Device] ${r?"Expanding":"Collapsing"} Notification Shade`)),r?await t.driver.openNotificationShade(t.serial):await t.driver.collapseNotificationShade(t.serial);break}default:throw new Error(`Unsupported device action: ${s}`)}await ie(400),t.setLastHierarchy(null)}},Xs=class{type="RUN_JS";async execute(e,t){let s=e.jsCode||e.value||"";if(!s)return;console.log(ue.cyan(" [JS Hook] Executing sandboxed JavaScript snippet..."));let i={vars:Object.fromEntries(t.variables),setVar:(n,o)=>{t.variables.set(n,String(o))},getVar:n=>t.variables.get(n),console:{log:(...n)=>console.log(ue.gray(" [JS Output]",...n)),error:(...n)=>console.error(ue.red(" [JS Error]",...n))}},r=_i.createContext(i);_i.runInContext(s,r,{timeout:3e3});for(let[n,o]of Object.entries(i.vars))t.variables.set(n,String(o))}},zs=class{type="ENTER_OTP";async execute(e,t){console.log(ue.cyan(" [OTP Capture] Detecting verification code..."));let s=null;if(process.env.PROMPTTEST_MOCK_OTP)s=process.env.PROMPTTEST_MOCK_OTP.trim(),console.log(ue.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),r=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);r&&(s=r[1],console.log(ue.gray(` [OTP Capture] Captured code from logcat: ${s}`)))}catch{}if(s||(s="123456",console.log(ue.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 qt().execute(i,t)}else{let{flat:i}=await t.getCleanHierarchy(t.serial),r=t.findTargetInputField(i,"code",s)||i.find(n=>n.className.includes("EditText"));r?(await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await ie(250),await t.driver.inputText(s,t.serial)):await t.driver.inputText(s,t.serial)}}},Gs=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(ue.cyan(` [API Request] ${s} ${i}...`));let r={method:s,headers:{"Content-Type":"application/json",Accept:"application/json"}};e.apiBody&&(s==="POST"||s==="PUT"||s==="PATCH")&&(r.body=e.apiBody);let n=await fetch(i,r);if(e.apiExpectedStatus!==void 0){if(n.status!==e.apiExpectedStatus)throw new Error(`API status assertion failed for ${i}: expected HTTP ${e.apiExpectedStatus}, but received HTTP ${n.status}`);console.log(ue.green(` \u2714 API Status HTTP ${n.status} matched expectation.`))}if(e.apiStorePath&&e.apiStoreVariable)try{let o=await n.text(),c=JSON.parse(o),l=this.resolveJsonPath(c,e.apiStorePath);l!==void 0&&(t.variables.set(e.apiStoreVariable,String(l)),console.log(ue.cyan(` [Variable] $${e.apiStoreVariable} = "${l}" (from ${e.apiStorePath})`)))}catch(o){Ge.warn(`Failed to parse JSON response for path extraction: ${o.message}`)}}resolveJsonPath(e,t){let s=t.replace(/^\$\.?/,"").split("."),i=e;for(let r of s){if(i==null||typeof i!="object")return;i=i[r]}return i}},Ks=class{type="EMAIL_ASSERT";async execute(e,t){let s=e.emailRecipient||"",i=e.emailSubject||"";console.log(ue.cyan(` [Email Assertion] Checking email to "${s}" with subject "${i}"...`));let r=[];if(process.env.PROMPTTEST_MOCK_EMAILS)try{r=JSON.parse(process.env.PROMPTTEST_MOCK_EMAILS)}catch{r=[]}let n=r.find(o=>o.to.toLowerCase()===s.toLowerCase()&&o.subject.toLowerCase().includes(i.toLowerCase()));if(!n){if(r.length===0){if(!s.includes("@"))throw new Error(`Invalid email recipient address: "${s}"`);console.log(ue.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&&n.body&&!n.body.includes(e.emailBodyContains))throw new Error(`Email body assertion failed: Expected email to contain "${e.emailBodyContains}", but content did not match.`);console.log(ue.green(" \u2714 Email verified successfully."))}},Vn=[new ks,new Ds,new qt,new As,new $s,new Cs,new Is,new Ns,new Ls,new Ms,new Rs,new Os,new Fs,new _s,new Hs,new Bs,new Us,new js,new Ys,new Ws,new Vs,new Js,new Xs,new zs,new Gs,new Ks],Hi=new Map(Vn.map(a=>[a.type,a]));var xt=class{providerName="heuristic";async resolveIntent(e,t){let s=oe(e);return(s.includes("login")||s.includes("log in")||s.includes("sign in")||s.includes("signin"))&&(s.includes("test user")||s.includes("default credentials")||s.includes("credentials"))?[{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"}]:s.includes("sign up with random user")||s.includes("register new user")?[{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"}]:s.includes("dismiss dialog")||s.includes("close modal")||s.includes("dismiss popup")?[{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}]:null}async findSuggestions(e,t,s){let i=[],r=oe(e),n=new Set,o=Di(e,s?.locale);for(let d of o){let h=t.find(u=>u.bounds.width>0&&u.bounds.height>0&&(pe(d,u.text)||pe(d,u.contentDesc)));if(h){let u=(h.text||h.contentDesc||d).trim();n.has(u)||(n.add(u),i.push({text:u,score:.9,node:h,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(m=>m===r||r.includes(m))){let m=(d.text||d.contentDesc||d.resourceId).trim();n.has(m)||(n.add(m),i.push({text:m,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=bt(e,l,5);for(let d of p)if(d.score>=.7&&!n.has(d.text)){n.add(d.text);let h=c.find(u=>u.text===d.text)?.node;i.push({text:d.text,score:d.score,node:h,strategy:"fuzzy",reason:`String similarity match (${Math.round(d.score*100)}%)`})}return i.sort((d,h)=>h.score-d.score)}};var Lt=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 xt().findSuggestions(e,t)}},es=class{providerName;config;heuristicFallback;constructor(e){this.config=e,this.providerName=e.provider,this.heuristicFallback=new xt}async resolveIntent(e,t){if(this.config.provider==="mock")return new Lt().resolveIntent(e,t);try{let s=`You are a test automation engineer generating steps for PromptTest.
|
|
683
809
|
Convert the following high-level user intent into a concrete sequence of plain-English test steps.
|
|
684
810
|
Valid syntax examples:
|
|
685
811
|
- Tap 'Button Label'
|
|
@@ -692,95 +818,86 @@ Valid syntax examples:
|
|
|
692
818
|
User Intent: "${e}"
|
|
693
819
|
|
|
694
820
|
Return ONLY a JSON array of plain strings representing each step, e.g.:
|
|
695
|
-
["Type 'user@test.com' into 'Email'", "Tap 'Next'"]`,i=await this.callLlm(s);if(!i)return this.heuristicFallback.resolveIntent(e,t);let
|
|
821
|
+
["Type 'user@test.com' into 'Email'", "Tap 'Next'"]`,i=await this.callLlm(s);if(!i)return this.heuristicFallback.resolveIntent(e,t);let r=i.match(/\[[\s\S]*\]/);return r?JSON.parse(r[0]).map(c=>({originalText:c,type:c.startsWith("Tap")?"TAP":c.startsWith("Type")?"TYPE":"VERIFY"})):this.heuristicFallback.resolveIntent(e,t)}catch(s){return Ge.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 Lt().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),r=`A UI test failed because an element named "${e}" could not be found.
|
|
696
822
|
Here are the visible UI elements on the current Android screen:
|
|
697
823
|
${JSON.stringify(i,null,2)}
|
|
698
824
|
|
|
699
825
|
Identify the best matching replacement element for "${e}".
|
|
700
826
|
Respond ONLY with a JSON object in this format:
|
|
701
|
-
{"bestMatch": "Exact Text of Best Element", "confidence": 0.85, "reason": "Reason for match"}`,
|
|
702
|
-
`),i="",
|
|
703
|
-
`),rows:o}}static loadFromFile(e){if(!
|
|
704
|
-
`||
|
|
705
|
-
`&&
|
|
706
|
-
|
|
707
|
-
`)}
|
|
827
|
+
{"bestMatch": "Exact Text of Best Element", "confidence": 0.85, "reason": "Reason for match"}`,n=await this.callLlm(r);if(!n)return this.heuristicFallback.findSuggestions(e,t,s);let o=n.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){Ge.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 r=this.config.apiKey||process.env.OPENAI_API_KEY;if(!r)throw new Error("OPENAI_API_KEY is not set");let n=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({model:this.config.model||"gpt-4o-mini",messages:[{role:"user",content:e}],temperature:.1}),signal:s.signal});if(!n.ok)throw new Error(`OpenAI HTTP ${n.status}: ${await n.text()}`);return(await n.json()).choices?.[0]?.message?.content||null}if(this.config.provider==="anthropic"){let r=this.config.apiKey||process.env.ANTHROPIC_API_KEY;if(!r)throw new Error("ANTHROPIC_API_KEY is not set");let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":r,"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(!n.ok)throw new Error(`Anthropic HTTP ${n.status}: ${await n.text()}`);return(await n.json()).content?.[0]?.text||null}if(this.config.provider==="ollama"){let r=this.config.endpoint||process.env.OLLAMA_BASE_URL||"http://localhost:11434",n=await fetch(`${r.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(!n.ok)throw new Error(`Ollama HTTP ${n.status}: ${await n.text()}`);return(await n.json()).message?.content||null}return null}finally{clearTimeout(i)}}};function Qs(a){let e=a?.provider||C.ai.provider;if(e==="heuristic")return new xt;if(e==="mock")return new Lt;let t={provider:e,model:a?.model||C.ai.model,endpoint:a?.endpoint||C.ai.endpoint};return new es(t)}import Bi from"fs";import Zs from"path";var Mt=class{static extractDataDirective(e,t=process.cwd()){let s=e.split(`
|
|
828
|
+
`),i="",r=-1;for(let p=0;p<s.length;p++){let d=s[p].trim();if(d.startsWith("#!data")||d.startsWith("#! data")){i=d,r=p;break}}if(r===-1)return null;let n=i.replace(/^#!\s*data\s*/,"").trim(),o=[],c="inline";if(n.startsWith("[")||n.startsWith("{"))try{let p=JSON.parse(n);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=n.replace(/^['"]+|['"]+$/g,"").trim(),d=Zs.isAbsolute(p)?p:Zs.resolve(t,p);c=d,o=this.loadFromFile(d)}let l=[...s];return l.splice(r,1),{directive:i,source:c,cleanedSpec:l.join(`
|
|
829
|
+
`),rows:o}}static loadFromFile(e){if(!Bi.existsSync(e))throw new Error(`Data file not found: ${e}`);let t=Bi.readFileSync(e,"utf-8");return Zs.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(r=>r.trim().replace(/^['"]+|['"]+$/g,"")),i=[];for(let r=1;r<t.length;r++){if(!t[r].trim())continue;let o=this.parseCsvRow(t[r]),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 r=0;r<t.iterations;r++)i.push(s[r%s.length]);return i}return s}static parseCsvRow(e){let t=[],s="",i=!1;for(let r=0;r<e.length;r++){let n=e[r];n==='"'?i&&e[r+1]==='"'?(s+='"',r++):i=!i:n===","&&!i?(t.push(s),s=""):s+=n}return t.push(s),t}static splitCsvLines(e){let t=[],s="",i=!1;for(let r=0;r<e.length;r++){let n=e[r];n==='"'?i&&e[r+1]==='"'?(s+='""',r++):(i=!i,s+=n):(n===`
|
|
830
|
+
`||n==="\r")&&!i?(n==="\r"&&e[r+1]===`
|
|
831
|
+
`&&r++,s.trim().length>0&&t.push(s),s=""):s+=n}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 Qn from"http";import ee from"fs";import z from"path";import zi from"os";import{fileURLToPath as Zn}from"url";import Te from"fs";import ye from"path";import U from"chalk";import{spawn as Jn}from"child_process";import Ui from"readline";import{createRequire as Xn}from"module";var zn=Xn(import.meta.url),qs="1.1.0";try{qs=zn("../../package.json").version||"1.1.0"}catch{}var lt=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=C.screen.fallbackWidth;touchMaxY=C.screen.fallbackHeight;displayWidth=C.screen.fallbackWidth;displayHeight=C.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||ke}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(n=>!t.has(n.toLowerCase())&&!/^\d+$/.test(n));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=yt(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 h=await this.driver.getForegroundPackage(i);h&&(this.targetPackage=h)}catch{}let r=this.extractBrandSlug(this.targetPackage),n;if(e&&e!=="specs/recorded_suite.txt")n=ye.resolve(e);else{let h=`${r}_flow`,u=ye.resolve(`specs/${h}.txt`);if(!this.isAppendMode&&Te.existsSync(u)){let m=1;for(u=ye.resolve(`specs/${h}_${m}.txt`);Te.existsSync(u);)m++,u=ye.resolve(`specs/${h}_${m}.txt`)}n=u}if(this.resolvedOutputPath=n,Te.existsSync(n))if(this.isAppendMode){let h=Te.readFileSync(n,"utf-8"),u=h.split(`
|
|
832
|
+
`);for(let y of u){let v=y.trim();if(/^\d+\.\s+/.test(v))this.existingSteps.push(v.replace(/^\d+\.\s+/,""));else if(v.startsWith("# Package:")){let T=v.match(/# Package:\s*([a-zA-Z0-9._]+)/);T&&(this.targetPackage=T[1])}}let m=`${n}.bak`;Te.writeFileSync(m,h,"utf-8"),console.log(U.cyan(`\u{1F4E5} Loaded ${this.existingSteps.length} existing step(s) from: ${ye.basename(n)}`)),console.log(U.gray(`\u{1F4E6} Safety backup preserved at: ${ye.basename(m)}`))}else{let h=Te.readFileSync(n,"utf-8"),u=`${n}.bak`;Te.writeFileSync(u,h,"utf-8"),console.log(U.yellow(`\u26A0\uFE0F File "${ye.basename(n)}" already exists.`)),console.log(U.gray(`\u{1F4E6} Safety backup preserved at: ${ye.basename(u)}`))}await this.driver.wakeDevice(i).catch(()=>{});let c=await this.driver.getScreenDimensions(i);this.displayWidth=c.width||C.screen.fallbackWidth,this.displayHeight=c.height||C.screen.fallbackHeight,this.touchMaxX=this.displayWidth,this.touchMaxY=this.displayHeight;try{let{stdout:h}=await this.driver.execAdb(["shell","getevent","-p"],i),u=h.match(/0035\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/),m=h.match(/0036\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/);u&&parseInt(u[1])>0&&(this.touchMaxX=parseInt(u[1])),m&&parseInt(m[1])>0&&(this.touchMaxY=parseInt(m[1]))}catch{}this.sessionStartTime=Date.now(),this.sessionScreenSections=[],this.screenshotCounter=0,this.crashDetected=!1,this.hierarchyStale=!0,this.currentScreenName="";let l=ye.basename(n,".txt"),p=ye.resolve("output");this.screenshotDir=ye.join(p,"screenshots",l),Te.existsSync(this.screenshotDir)||Te.mkdirSync(this.screenshotDir,{recursive:!0});let d=ye.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&&(St(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=U.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"),r=await this.driver.getDeviceModel(this.targetSerial).catch(()=>this.targetSerial);console.log(`
|
|
833
|
+
${i}`),console.log(U.bold.cyan(`\u26A1 PromptTest v${qs}`)+U.gray(" | Recording Session")),console.log(i),console.log(` ${U.gray("\u{1F4F1} Device ")} ${U.white(r)} ${U.gray(`(${this.targetSerial})`)}`),console.log(` ${U.gray("\u{1F4E6} App ")} ${U.green(this.targetPackage||"Unknown")}`),console.log(` ${U.gray("\u{1F3AF} Spec ")} ${U.yellow(ye.basename(this.resolvedOutputPath))}`),console.log(` ${U.gray("\u{1F4CA} Report ")} ${U.yellow(ye.basename(this.resolvedReportPath))}`),console.log(` ${U.gray("\u{1F4F8} Photos ")} ${U.yellow(ye.relative(process.cwd(),this.screenshotDir))}`),this.isAppendMode&&this.existingSteps.length>0&&console.log(` ${U.gray("\u{1F4CE} Mode ")} ${U.magenta(`Append \u2014 resuming from step #${this.existingSteps.length+1}`)}`),console.log(i),console.log(` ${U.green("\u2714")} Ready & streaming`),console.log(i),console.log(` ${U.gray("Use the app naturally. Every action is captured.")}`),console.log(` ${U.gray('Press Ctrl+C or type "exit" / "q" + Enter to stop and save.')}`),console.log(`${i}
|
|
834
|
+
`);let n=null,o=async()=>{if(n)try{n.close()}catch{}await this.stopSession(),this.printExitSummary(i),process.exit(0)};if(process.once("SIGINT",o),process.once("SIGTERM",o),process.stdin.isTTY)try{n=Ui.createInterface({input:process.stdin,output:process.stdout}),n.on("line",l=>{let p=l.trim().toLowerCase();(p==="exit"||p==="quit"||p==="q"||p==="stop")&&o()}),n.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=Xe(),i=Jn(s,t);this.geteventProcess=i;let r=null,n=null,o=null,c=null,l=0;Ui.createInterface({input:i.stdout}).on("line",d=>{if(this.isRecording)if(d.includes("ABS_MT_POSITION_X")){let h=d.match(/ABS_MT_POSITION_X\s+([0-9a-fA-F]+)/);h&&(r=parseInt(h[1],16))}else if(d.includes("ABS_MT_POSITION_Y")){let h=d.match(/ABS_MT_POSITION_Y\s+([0-9a-fA-F]+)/);h&&(n=parseInt(h[1],16))}else if(d.includes("BTN_TOUCH")&&d.includes("DOWN"))o=r,c=n,l=Date.now();else if(d.includes("BTN_TOUCH")&&d.includes("UP")){let h=r!==null?r:o,u=n!==null?n:c,m=Date.now()-l;if(h!==null&&u!==null&&o!==null&&c!==null){let y=Math.round(o/this.touchMaxX*this.displayWidth),v=Math.round(c/this.touchMaxY*this.displayHeight),T=Math.round(h/this.touchMaxX*this.displayWidth),S=Math.round(u/this.touchMaxY*this.displayHeight),b=T-y,E=S-v,D=Math.abs(b),B=Math.abs(E),k=Math.hypot(D,B);if(this.activeInput&&v>this.displayHeight*.58&&S>this.displayHeight*.58){m>=20&&m<400&&k<45&&T>=this.displayWidth*.78&&S>=this.displayHeight*.84?this.flushActiveInput().then(()=>{this.handleKeyPress("Enter")}).catch(()=>{}):this.scheduleInputDebounce(),r=null,n=null,o=null,c=null;return}if(m>=20&&m<400&&k<45)this.isRefreshingHierarchy?this.inFlightTapQueue.push({x:T,y:S,timestamp:Date.now()}):this.handleTapAt(T,S);else if(m>=450&&k<45)this.handleLongPressAt(T,S);else if(B>=100&&B>1.4*D){let j=E<0?"down":"up";this.handleScroll(j)}else if(D>=100&&D>1.4*B){let j=b<0?"left":"right";this.handleSwipe(j)}}r=null,n=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(U.yellow(`
|
|
835
|
+
\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(U.yellow(`
|
|
836
|
+
\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,U.blue(` \u{1F4DC} Recorded Scroll [Step #${this.getCurrentStepNumber()}]: ${U.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,U.blue(` \u{1F449} Recorded Swipe [Step #${this.getCurrentStepNumber()}]: ${U.bold(s)}`)),this.triggerAsyncHierarchyRefresh(500)}handleLongPressAt(e,t){let s=this.lastHierarchyFlat.filter(n=>e>=n.bounds.x1&&e<=n.bounds.x2&&t>=n.bounds.y1&&t<=n.bounds.y2);if(s.length===0)return;s.sort((n,o)=>{let c=(n.bounds.x2-n.bounds.x1)*(n.bounds.y2-n.bounds.y1),l=(o.bounds.x2-o.bounds.x1)*(o.bounds.y2-o.bounds.y1);return c-l});let i=s[0],r=this.resolveActionLabel(i,s,this.lastHierarchyFlat);if(r){let n=`Long press '${r}'`;this.appendStep(n,U.cyan(` \u23F1\uFE0F Recorded Long Press [Step #${this.getCurrentStepNumber()}]: ${U.bold(n)}`)),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),n=this.lastHierarchyFlat.filter(d=>{let h=d.bounds.height;return h>0&&h<320&&d.bounds.width>0&&(d.clickable||d.contentDesc||d.text)}).filter(d=>t>=d.bounds.y1-30&&t<=d.bounds.y2+40);if(n.length>=2){let d=n.find(h=>e>=h.bounds.x1-20&&e<=h.bounds.x2+20);d&&(i=[this.lastHierarchyFlat.find(u=>(this.cleanLabel(u.text).length>0||this.cleanLabel(u.contentDesc).length>0)&&Math.abs(u.bounds.centerX-d.bounds.centerX)<d.bounds.width*.48&&Math.abs(u.bounds.centerY-d.bounds.centerY)<d.bounds.height*.48&&!this.isIconGlyph(this.cleanLabel(u.text)))||d])}if(t>this.displayHeight*.82){let h=this.lastHierarchyFlat.filter(u=>{let m=u.bounds.y1>=this.displayHeight*.78||u.bounds.y2>=this.displayHeight*.82,y=u.bounds.width>0&&u.bounds.width<=this.displayWidth*.52;return m&&y}).find(u=>e>=u.bounds.x1-20&&e<=u.bounds.x2+20);if(h){let u=this.lastHierarchyFlat.find(m=>(this.cleanLabel(m.text).length>0||this.cleanLabel(m.contentDesc).length>0)&&e>=m.bounds.x1-25&&e<=m.bounds.x2+25&&m.bounds.y1>=this.displayHeight*.78&&!this.isIconGlyph(this.cleanLabel(m.text)));u?i=[u]:(this.cleanLabel(h.text)||this.cleanLabel(h.contentDesc))&&(i=[h])}}if(i.length===0){let d=this.lastHierarchyFlat.filter(m=>(this.cleanLabel(m.text).length>0||this.cleanLabel(m.contentDesc).length>0)&&(m.clickable||m.className.includes("Button")||m.className.includes("Text"))),h=null,u=70;for(let m of d){let y=Math.hypot(m.bounds.centerX-e,m.bounds.centerY-t);y<u&&(u=y,h=m)}if(h)i=[h];else{this.triggerAsyncHierarchyRefresh();return}}i.sort((d,h)=>{let u=(d.bounds.x2-d.bounds.x1)*(d.bounds.y2-d.bounds.y1),m=(h.bounds.x2-h.bounds.x1)*(h.bounds.y2-h.bounds.y1);return u-m});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(u=>this.cleanLabel(u.text)===l||this.cleanLabel(u.contentDesc)===l),h=[];for(let u of d)h.some(y=>Math.hypot(y.bounds.centerX-u.bounds.centerX,y.bounds.centerY-u.bounds.centerY)<40)||h.push(u);if(h.length>1){let m=this.lastHierarchyFlat.filter(y=>y!==o&&Math.abs(y.bounds.centerY-o.bounds.centerY)<140&&Math.abs(y.bounds.centerX-o.bounds.centerX)<550).find(y=>{let v=this.cleanLabel(y.text)||this.cleanLabel(y.contentDesc);return v.length>2&&v!==l&&!/^\d+$/.test(v)&&!this.isIconGlyph(v)});if(m){let y=this.cleanLabel(m.text)||this.cleanLabel(m.contentDesc);y&&y!==l&&(p=`Tap '${l}' next to '${y}'`)}}}this.appendStep(p,U.cyan(` \u{1F446} Recorded Tap [Step #${this.getCurrentStepNumber()}]: ${U.bold(p)}`)),this.triggerAsyncHierarchyRefresh()}handleKeyPress(e){if(this.activeInput&&this.flushActiveInput().catch(()=>{}),e==="Enter"){let t="Press 'Enter'";this.appendStep(t,U.magenta(` \u21B5 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${U.bold(t)}`))}else if(e==="Back"){let t="Tap 'Back'";this.appendStep(t,U.magenta(` \u25C0 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${U.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}=we(t);this.lastHierarchyFlat=s;let i=s.find(r=>r.className.includes("EditText")&&(r.focused||r.selected))||s.find(r=>r.className.includes("EditText")&&this.resolveFieldLabel(r,s).toLowerCase()===e.label.toLowerCase())||s.find(r=>r.className.includes("EditText")&&Math.abs(r.bounds.centerX-e.node.bounds.centerX)<80)||s.find(r=>r.className.includes("EditText"));if(i&&i.text&&i.text.trim().length>0){let r=i.text.trim(),n=/^[•*•\u2022\u25cf]+$/.test(r);if(!(r===e.startText)&&!n){if(e.startText===""&&this.isPlaceholderText(r))return;let c=e.label||this.resolveFieldLabel(i,s),l=`Type '${r}' 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(U.gray(` \u270D\uFE0F Updated Input [Step #${p+1+this.existingSteps.length}]: ${U.bold(l)}`))):this.appendStep(l,U.green(` \u270D\uFE0F Recorded Input [Step #${this.getCurrentStepNumber()}]: ${U.bold(l)}`))}else if(n&&(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,U.green(` \u270D\uFE0F Recorded Password Input [Step #${this.getCurrentStepNumber()}]: ${U.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(U.red.bold(`
|
|
837
|
+
\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`,r=ye.join(this.screenshotDir,i);(async()=>{try{let n=await this.driver.captureScreenshot(this.targetSerial);if(n&&n.length>0){await Te.promises.writeFile(r,n);let o=this.sessionScreenSections[this.sessionScreenSections.length-1];o&&!o.screenshotFile&&(o.screenshotFile=i)}}catch{}})()}triggerAsyncHierarchyRefresh(e=C.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}=we(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<C.recorder.staleTapTimeoutMs?this.handleTapAt(e.x,e.y):console.warn(U.yellow(`[Recorder] Dropped stale tap at (${e.x}, ${e.y}) \u2014 screen refresh took longer than ${C.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,U.green(` \u2714 Recorded Alert [Step #${this.getCurrentStepNumber()}]: ${U.bold(i)}`))}}}async refreshHierarchySync(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=we(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(`
|
|
838
|
+
`)){let s=t.split(/[\n,]+/).map(i=>this.cleanLabel(i)).filter(Boolean);if(s.length>1){let i=s.find(n=>n.includes("?")||/\b(are you sure|do you want|cannot be undone|would you like|please confirm)\b/i.test(n)||n.length>35);if(i){let n=s.find(o=>o!==i&&o.length<=30&&!o.includes("?"));if(n)return n}let r=s.filter(n=>/^[A-Z]{1,3}$/.test(n)||/^\d+%?$/.test(n)||this.isCardMetadataSubtitle(n)||/^(attend|present|absent|status|active|inactive)$/i.test(n)?!1:n.length>1);if(r.length>0)return r[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),r=this.isCardMetadataSubtitle(i),n=s.find(l=>l!==e&&l.clickable&&l.bounds.height>60&&l.bounds.height<600),o;n?o=t.filter(l=>l.className.includes("Text")&&l.bounds.x1>=n.bounds.x1-10&&l.bounds.x2<=n.bounds.x2+10&&l.bounds.y1>=n.bounds.y1-10&&l.bounds.y2<=n.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(r||n&&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 r=this.cleanLabel(e.text);if(r.length>0&&r.length<90){let l=r.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]:r;return this.cleanDialogOrCompoundLabel(p)}let n=this.cleanLabel(e.contentDesc);if(n.length>0&&n.length<90)return this.cleanDialogOrCompoundLabel(n);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 h=p.split(/[\n\r]+/).map(m=>this.cleanLabel(m)).filter(Boolean),u=h.length>1?h.find(m=>m.length>2&&!/^\d+$/.test(m))||h[0]:p;return this.cleanDialogOrCompoundLabel(u)}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,U.green(` \u2714 Recorded Header [Step #${this.getCurrentStepNumber()}]: ${U.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((r,n)=>n.bounds.centerY-r.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("/"),r=i[i.length-1];if(r&&!/^\d+$/.test(r)){let n=r.replace(/_/g," ").replace(/edit|text|input|field|et|txt/gi,"").trim();return n.length>1?n.charAt(0).toUpperCase()+n.slice(1):r}}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=ye.resolve(e);if(ye.basename(t).startsWith("app_flow")&&this.targetPackage&&!this.isAppendMode){let c=this.extractBrandSlug(this.targetPackage);if(c!=="app"){let l=`${c}_flow`,p=ye.resolve(`specs/${l}.txt`),d=1;for(;Te.existsSync(p);)p=ye.resolve(`specs/${l}_${d}.txt`),d++;t=p}}let i=ye.dirname(t);Te.existsSync(i)||Te.mkdirSync(i,{recursive:!0});let r=[];if(this.isAppendMode&&this.existingSteps.length>0&&Te.existsSync(t)){let c=Te.readFileSync(t,"utf-8").trim();r.push(c),r.push(""),r.push(`# --- Appended Session (${new Date().toISOString().replace("T"," ").slice(0,19)}) ---`),this.recordedSteps.forEach((l,p)=>{r.push(`${this.existingSteps.length+p+1}. ${l}`)})}else{r.push("# ==========================================================",`# Autonomous Recorded Test Spec: ${ye.basename(t)}`,...this.targetPackage?[`# Package: ${this.targetPackage}`]:[],`# Generated: ${new Date().toISOString()}`,`# PromptTest v${qs}`,"# ==========================================================","");let c=0;this.recordedSteps.forEach((l,p)=>{if(c<this.sessionScreenSections.length&&p===this.sessionScreenSections[c].stepStart){let d=this.sessionScreenSections[c];r.push(""),r.push(`# Screen: ${d.name}`),c++}r.push(`${this.existingSteps.length+p+1}. ${l}`)})}r.push("");let n=r.join(`
|
|
839
|
+
`),o=`${t}.tmp.${Date.now()}`;try{Te.writeFileSync(o,n,"utf-8"),Te.renameSync(o,t)}catch{try{Te.unlinkSync(o)}catch{}Te.writeFileSync(t,n,"utf-8")}}saveReport(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,r=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,n=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** | ${r} |`,`| **Steps in Session** | ${this.recordedSteps.length} |`,`| **Total Suite Steps** | ${n} |`,`| **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(`
|
|
840
|
+
`):"*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,h=this.recordedSteps.slice(l.stepStart,d);o.push(`### Screen: ${l.name}`),o.push(""),l.screenshotFile&&(o.push(`}/${l.screenshotFile})`),o.push("")),h.length>0?h.forEach((u,m)=>{o.push(`${l.stepStart+m+1}. \`${u}\``)}):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=ye.dirname(e);Te.existsSync(c)||Te.mkdirSync(c,{recursive:!0}),Te.writeFileSync(e,o.join(`
|
|
841
|
+
`),"utf-8")}catch{}}printExitSummary(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,r=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,n=this.existingSteps.length+this.recordedSteps.length;console.log(`
|
|
842
|
+
${e}`),console.log(U.bold.green(" \u{1F4BE} Recording Session Saved Successfully!")),console.log(e),console.log(` ${U.gray("Steps Captured ")} ${U.bold.yellow(this.recordedSteps.length.toString())} ${this.isAppendMode?U.gray(`(Total Suite: ${n})`):""}`),console.log(` ${U.gray("Screens Visited")} ${U.bold.white(this.visitedScreens.length.toString())} ${this.visitedScreens.length>0?U.gray(`(${this.visitedScreens.join(" \u2192 ")})`):""}`),console.log(` ${U.gray("Screenshots ")} ${U.bold.white(this.screenshotCounter.toString())} saved`),console.log(` ${U.gray("Session Time ")} ${U.bold.white(r)}`),console.log(` ${U.gray("Crash Signals ")} ${this.crashDetected?U.red.bold("\u26A0\uFE0F Detected"):U.green("\u2714 0 detected")}`),console.log(e),console.log(` ${U.gray("\u{1F4C4} Spec ")} ${U.cyan(this.resolvedOutputPath)}`);let o=ye.basename(this.resolvedOutputPath,".txt");console.log(` ${U.gray("\u{1F4CA} Report ")} ${U.cyan(ye.resolve("output",`${o}_report.md`))}`),console.log(`${e}
|
|
843
|
+
`)}},ji=new lt;import ts from"fs";import Yi from"path";import dt from"chalk";async function ss(a=ke,e={}){let t=[],s=process.versions.node,r=parseInt(s.split(".")[0],10)>=18;t.push({name:"Node.js Runtime",passed:r,message:`Node.js v${s} (Required >= 18.0.0)`,hint:r?void 0:"Please upgrade Node.js to v18.0.0 or higher: https://nodejs.org"});let n=!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),b=S.match(/Android Debug Bridge version ([\d.]+)/i);b?(n=!0,o=`Android Debug Bridge version ${b[1]}`,c=void 0):(n=!0,o=S.split(`
|
|
844
|
+
`)[0].trim(),c=void 0)}catch(S){o=`Failed to execute adb: ${S.message}`}t.push({name:"Android Debug Bridge (ADB)",passed:n,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(),b=S.filter(B=>B.state==="device"),E=S.filter(B=>B.state==="unauthorized"),D=S.filter(B=>B.state==="offline");if(b.length>0){l=!0;let B=b.map(k=>`${k.serial} (${k.model||"Unknown"})`).join(", ");p=`Found ${b.length} authorized device(s): ${B}`,d=void 0}else E.length>0?(p=`Device(s) found but unauthorized: ${E.map(B=>B.serial).join(", ")}`,d='Check the device screen and accept the "Allow USB debugging" RSA prompt.'):D.length>0&&(p=`Device(s) found in offline state: ${D.map(B=>B.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,b=!1,E=`Package "${S}" not found on target device`,D='Install the APK using "adb install <path.apk>" or check the package identifier.';if(l)try{let{stdout:B}=await a.execAdb(["shell","pm","list","packages",S],e.serial,5e3);B.includes(`package:${S}`)&&(b=!0,E=`Package "${S}" is installed on target device`,D=void 0)}catch(B){E=`Failed to query package status: ${B.message}`}else E="Skipped package verification (no authorized device available)",D=`Connect a device to verify package "${S}".`;t.push({name:`Target Package [${S}]`,passed:b,message:E,hint:D})}let h=!0,u="All required workspace directories are accessible",m,y=["output","memory",".prompttest"];for(let S of y)try{let b=Yi.resolve(process.cwd(),S);ts.existsSync(b)||ts.mkdirSync(b,{recursive:!0});let E=Yi.join(b,".doctor_perm_test");ts.writeFileSync(E,"ok","utf-8"),ts.unlinkSync(E)}catch(b){h=!1,u=`Filesystem permission error for "./${S}": ${b.message}`,m="Ensure the current user has write permissions to the workspace directory.";break}t.push({name:"Workspace Storage & Permissions",passed:h,message:u,hint:m});let v=t.filter(S=>S.passed).length,T=t.filter(S=>!S.passed).length;return{timestamp:new Date().toISOString(),allPassed:T===0,checks:t,summary:{passed:v,failed:T,warnings:0}}}function Wi(a){let e=["",dt.bold.cyan("\u{1FA7A} PromptTest Doctor \u2014 Environment Health Diagnostic"),dt.gray(`Scanned at ${a.timestamp}
|
|
845
|
+
`)];for(let t of a.checks){let s=t.passed?dt.green("\u2714"):dt.red("\u2716"),i=dt.bold(t.name);e.push(` ${s} ${i}: ${t.message}`),t.hint&&!t.passed&&e.push(dt.yellow(` \u{1F4A1} Fix: ${t.hint}`))}return e.push(""),a.allPassed?e.push(dt.bold.green("\u2728 All diagnostic checks passed! Your environment is ready to test.")):e.push(dt.bold.red(`\u26A0\uFE0F ${a.summary.failed} diagnostic check(s) failed. Please review the remediation hints above.`)),e.push(""),e.join(`
|
|
846
|
+
`)}import Kn from"fs";import ei from"path";import L from"chalk";import Vi from"fs";import Gn from"path";var pt=class{testData={};dataPath;isLoaded=!1;driver;constructor(e,t){this.dataPath=e||Gn.resolve(process.cwd(),"test-data.json"),this.driver=t||ke}setTestData(e){this.testData=e,this.isLoaded=!0}async ensureDataLoaded(){if(!this.isLoaded){if(Vi.existsSync(this.dataPath))try{let e=await Vi.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="",r=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);r.length>0&&(i=r[r.length-1].text.toLowerCase());let n=`${s} ${i}`.toLowerCase();if(n.includes("review")||n.includes("feedback")||n.includes("comment")||n.includes("write a review")||n.includes("experience")){if(!this.testData.review?.text)throw new Error("Missing test-data.json field: review.text");return this.testData.review.text}if(n.includes("card")||n.includes("credit")||n.includes("debit")||n.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(n.includes("phone")||n.includes("mobile")||!n.includes("card")&&n.includes("number")||n.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(n.includes("email")||n.includes("e-mail")||n.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(n.includes("cvv")||n.includes("cvc")||n.includes("security code"))return"123";if(n.includes("expiry")||n.includes("exp date")||n.includes("expiration"))return"12/28";if(n.includes("pincode")||n.includes("zip")||n.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||n.includes("password")||/\bpin\b/.test(n)&&!n.includes("pincode")||n.includes("passcode")){if(!this.testData.auth?.password)throw new Error("Missing test-data.json field: auth.password");return this.testData.auth.password}if(n.includes("otp")||n.includes("verification")||n.includes("code")&&!n.includes("postal")&&!n.includes("zip")){if(!this.testData.auth?.otp)throw new Error("Missing test-data.json field: auth.otp");return this.testData.auth.otp}if(n.includes("address")||n.includes("street")||n.includes("location")){if(!this.testData.profile?.address)throw new Error("Missing test-data.json field: profile.address");return this.testData.profile.address}if(n.includes("city")||n.includes("state")){if(!this.testData.profile?.city)throw new Error("Missing test-data.json field: profile.city");return this.testData.profile.city}if(n.includes("name")||n.includes("full name")||n.includes("first name")){if(!this.testData.profile?.name)throw new Error("Missing test-data.json field: profile.name");return this.testData.profile.name}if(n.includes("search")||n.includes("find")||n.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 r=ze(e),n=[];if(r.length===0)return{filledFields:[],submitted:!1};let o=!1;for(let p of r){let d=p.resourceId||p.text||`input_${p.bounds.centerX}_${p.bounds.centerY}`,h=(p.text||"").trim(),u=!h||/^enter\s+/i.test(h)||/^type\s+/i.test(h)||/^e\.g\./i.test(h)||/^(email|email address|password|phone|name|search)$/i.test(h);if(!i&&!u){n.push({fieldId:d,fieldLabel:p.text||p.contentDesc||p.resourceId,valueEntered:h});continue}let m=this.inferValueForNode(p,e);await this.driver.tap(p.bounds.centerX,p.bounds.centerY,t),await new Promise(y=>setTimeout(y,400)),await this.driver.clearField(t,m.length+10),await new Promise(y=>setTimeout(y,200)),await this.driver.inputText(m,t),await new Promise(y=>setTimeout(y,300)),o=!0,n.push({fieldId:d,fieldLabel:p.text||p.contentDesc||p.resourceId,valueEntered:m})}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:yi.some(h=>pe(h,d.text)||pe(h,d.contentDesc)||pe(h,d.resourceId)));if(p.length>0){let d=["submit","sign in","signin","login","save","confirm","proceed","continue"];p.sort((u,m)=>{let y=(u.text||u.contentDesc||u.resourceId||"").toLowerCase(),v=(m.text||m.contentDesc||m.resourceId||"").toLowerCase(),T=d.findIndex(D=>y.includes(D)),S=d.findIndex(D=>v.includes(D)),b=T>=0?T:99,E=S>=0?S:99;return b!==E?b-E:m.bounds.centerY-u.bounds.centerY});let h=p[0];l=h.text||h.contentDesc||h.resourceId,await this.driver.tap(h.bounds.centerX,h.bounds.centerY,t),await new Promise(u=>setTimeout(u,C.settle.submitWaitMs));try{let u=await this.driver.getUiHierarchy(t),{flat:m}=we(u),y=ze(m);c=!(y.length>0&&r.every(T=>y.some(S=>S.resourceId&&S.resourceId===T.resourceId)))}catch{c=!0}}}return{filledFields:n,submitted:c,submitButtonText:l}}},Ji=new pt;import se from"chalk";var is=class{driver;reporter;memory;formFiller;screenLedger=new Map;callStack=[];executedStepCount=0;visitedScreenHashes=new Set;devDefectsList=[];safetyHitList=[];externalSkippedList=[];stepListener;abortFlag;constructor(e=ke,t=nt,s=Ct){this.driver=e,this.reporter=t,this.memory=s,this.formFiller=new pt(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:r}=we(i),n=0;for(;n<s;){let o=jt(r);if(!o)break;n++;let c=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(se.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(se.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(se.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(se.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(d=>setTimeout(d,800)),i=await this.driver.getUiHierarchy(t),r=we(i).flat}return{xml:i,flat:r}}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=vt(s);console.log(se.yellow(` \u{1F6A8} External App Jailbreak Detected [${s}]. Recovering...`)),i||(await this.driver.pressBack(t),await new Promise(n=>setTimeout(n,800)));let r=await this.driver.getForegroundPackage(t);return(!r||!r.includes(e))&&(console.log(se.red(` Force restoring ${e} foreground...`)),await this.driver.launchApp(e,t),await new Promise(n=>setTimeout(n,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(se.yellow(` \u{1F6E1}\uFE0F External Media Chooser Intercepted [${s}]. Dismissing to stay in-app...`)),await this.driver.pressBack(t),await new Promise(n=>setTimeout(n,800));let r=await this.driver.getForegroundPackage(t);return r&&!r.includes(e)&&i&&(await this.driver.launchApp(e,t),await new Promise(n=>setTimeout(n,1200)),this.callStack=this.callStack.slice(0,1)),!0}return!1}catalogScreen(e,t,s=[]){let i=[],r=t.height,n=r*.06,o=r*.88,c=b=>s.some(E=>Math.abs(E.bounds.centerX-b.bounds.centerX)<30&&Math.abs(E.bounds.centerY-b.bounds.centerY)<30),l=ze(e);for(let b of l){if(c(b))continue;let E=b.text||b.contentDesc||b.resourceId||"Text Input";i.push({node:b,type:"input",label:E,tested:!1})}let p=Dt(e);for(let b of p){if(c(b))continue;let E=b.text||b.contentDesc||b.resourceId||"Toggle Control";i.push({node:b,type:"toggle",label:E,tested:!1})}let d=Qe(e);for(let b of d){if(c(b)||st([b],r,t.width)||Re([b],r,t.width,!0))continue;let E=b.text||b.contentDesc||b.resourceId||"Action Button";if(Ue(b)){this.externalSkippedList.push(E);continue}let D=b.selected!==void 0||b.checkable||/(?:tab|chip|pill|filter|segment|toggle)/i.test(`${b.resourceId} ${b.className} ${b.contentDesc}`)||/(?:today|yesterday|all|active|archived|pending|completed|present|absent)/i.test(E);i.push({node:b,type:D?"toggle":"transition",label:E,tested:!1})}let h=xi(e,r,t.width);for(let b of h){if(c(b)||Re([b],r,t.width,!0)||i.some(D=>Math.abs(D.node.bounds.centerX-b.bounds.centerX)<25&&Math.abs(D.node.bounds.centerY-b.bounds.centerY)<25))continue;let E=b.text||b.contentDesc||b.resourceId||"Notification / Header Action";if(Ue(b)){this.externalSkippedList.push(E);continue}i.push({node:b,type:"transition",label:E,tested:!1})}let u=e.filter(b=>{if(!b.clickable||b.bounds.width===0)return!1;let E=`${b.text} ${b.contentDesc} ${b.resourceId}`.toLowerCase();return E.includes("now playing")||E.includes("play")||E.includes("pause")});for(let b of u){if(c(b)||i.some(D=>Math.abs(D.node.bounds.centerX-b.bounds.centerX)<25&&Math.abs(D.node.bounds.centerY-b.bounds.centerY)<25))continue;let E=b.text||b.contentDesc||b.resourceId||"Media Control";i.push({node:b,type:"toggle",label:E,tested:!1})}let m=Bt(e,t).filter(b=>!c(b)&&b.bounds.centerY>n&&b.bounds.centerY<o&&!Re([b],r,t.width,!0)&&!Ue(b)),y=Pi(m,2);for(let b of y){let E=b.text||b.contentDesc||b.resourceId||`Item (${b.bounds.centerX},${b.bounds.centerY})`;i.push({node:b,type:"transition",label:E,tested:!1})}let v=0,T=0,S=[];for(let b of i){let E=/\.(?:mp4|mkv|mov|webm|flv|avi)\b/i.test(b.label),D=/\.(?:mp3|wav|m4a|aac|ogg)\b/i.test(b.label);if(E){if(v++,v>1)continue}else if(D&&(T++,T>1))continue;S.push(b)}return S}async safeBacktrack(e,t,s,i,r=!0){let{flat:n}=await this.getCleanUiHierarchy(t,s),{height:o,width:c}=await this.driver.getScreenDimensions(s),l=Oe(n,{width:c,height:o});if(l===e)return!0;let p=Re(n,o,c,!0);if(p&&p.bounds.width>0){console.log(se.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(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let d=await this.getCleanUiHierarchy(t,s),h=Oe(d.flat,{width:c,height:o});if(h===e||h!==l)return!0}if(i&&i.bounds.width>0){console.log(se.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(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let d=await this.getCleanUiHierarchy(t,s),h=Oe(d.flat,{width:c,height:o});if(h===e||h!==l)return!0}if(r){if(console.log(se.gray(" [Backtrack] Sending fallback KEYCODE_BACK...")),await this.driver.pressKey(4,s),await new Promise(m=>setTimeout(m,1e3)),await this.packageJailGuard(t,s))return console.log(se.yellow(" \u26A0\uFE0F Backtrack via KEYCODE_BACK caused app jailbreak. Aborting branch restoration.")),!1;let h=await this.getCleanUiHierarchy(t,s),u=Oe(h.flat,{width:c,height:o});if(u===e||u!==l)return!0}return!1}async explore(e){let{packageName:t,serial:s,maxScreens:i=30,maxDepth:r=3,stepBudget:n=100,maxInteractionsPerScreen:o=6,safetyMode:c="strict",safetyBlacklist:l=[],onStep:p,abortSignal:d}=e;this.stepListener=p,this.abortFlag=d,console.log(se.bold.cyan(`
|
|
847
|
+
\u{1F916} PromptTest Universal State-Graph DFS Engine`)),console.log(se.gray(`Target Package: ${t}`)),console.log(se.gray(`Safety Policy: ${c.toUpperCase()}`)),console.log(se.gray(`Limits: Max Screens = ${i}, Step Budget = ${n}, Max Depth = ${r}`)),await this.driver.clearCrashLogs(s);let h=await this.driver.getScreenDimensions(s),u=await this.driver.getForegroundPackage(s);(!u||!u.includes(t))&&(console.log(se.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(b=>setTimeout(b,2500)));let{flat:m}=await this.getCleanUiHierarchy(t,s);await this.dismissSoftKeyboard(s);let y=us(m,h,t);console.log(se.magenta(`\u26A1 Universal Paradigm Detected: [${y.paradigm.toUpperCase()}] with ${y.roots.length} root node(s).`));let v=[],T;if(y.paradigm==="drawer"&&y.roots.length>0){T=y.roots[0];let b={...m[0]||{},text:"Home Screen / Main Hub",contentDesc:"Home Screen / Main Hub",clickable:!0,bounds:{x1:0,y1:0,x2:h.width,y2:h.height,centerX:h.width/2,centerY:h.height/2,width:h.width,height:h.height}};v.push(b),console.log(se.gray(" Opening drawer to catalog root destinations...")),await this.driver.tap(T.bounds.centerX,T.bounds.centerY,s),await new Promise(M=>setTimeout(M,1200));let E=await this.getCleanUiHierarchy(t,s),D=E.flat.filter(M=>{if(!M.clickable||M.bounds.width===0||M.bounds.height===0||M.bounds.width>=h.width*.95&&M.bounds.height>=h.height*.95||Re([M],h.height,h.width,!0))return!1;let J=`${M.contentDesc} ${M.text}`.trim(),Y=M.bounds.width>h.width*.15&&M.bounds.height>h.height*.05;return J.toLowerCase().includes("developed by")||M.bounds.centerY>h.height*.85?!1:J.length>=2||Y});for(let M of D)v.some(J=>Math.abs(J.bounds.centerX-M.bounds.centerX)<30&&Math.abs(J.bounds.centerY-M.bounds.centerY)<30)||v.push(M);let B=Re(E.flat,h.height,h.width,!0);B?await this.driver.tap(B.bounds.centerX,B.bounds.centerY,s):await this.driver.tap(T.bounds.centerX,T.bounds.centerY,s),await new Promise(M=>setTimeout(M,1200));let k=await this.getCleanUiHierarchy(t,s);if(k.flat.some(M=>`${M.contentDesc} ${M.text}`.includes("Gallery")&&`${M.contentDesc} ${M.text}`.includes("Planner"))){let M=Re(k.flat,h.height,h.width,!0);M?await this.driver.tap(M.bounds.centerX,M.bounds.centerY,s):await this.driver.tap(h.width-50,h.height/2,s),await new Promise(J=>setTimeout(J,1e3))}console.log(se.magenta(` Discovered ${v.length} destinations (1 Main Hub + ${v.length-1} Drawer destinations).`))}else y.roots.length>0?v=y.roots:v=[m[0]||{text:"Main Hub",clickable:!0}];let S=1;for(let b of v){if(this.executedStepCount>=n||this.visitedScreenHashes.size>=i||this.isAborted())break;let E=b.text||b.contentDesc||`Root #${S}`;if(console.log(se.yellow(`
|
|
848
|
+
[Domain ${S}/${v.length}] Entering Root Tree: "${E}"...`)),this.emitStep({type:"action",description:`Tap "${E}" to enter the ${E} section`,screenTitle:E,depth:0}),y.paradigm==="bottom_tabs"||y.paradigm==="top_tabs"){let k=b.bounds.height<25?Math.max(b.bounds.y1-10,b.bounds.centerY):Math.min(b.bounds.centerY,b.bounds.y2-4);await this.driver.tap(b.bounds.centerX,k,s),this.executedStepCount++,await new Promise(j=>setTimeout(j,1200))}else y.paradigm==="drawer"&&S>1&&T&&(await this.dismissSoftKeyboard(s),console.log(se.gray(` Opening drawer to select "${E}"...`)),await this.driver.tap(T.bounds.centerX,T.bounds.centerY,s),await new Promise(k=>setTimeout(k,1e3)),await this.driver.tap(b.bounds.centerX,b.bounds.centerY,s),this.executedStepCount++,await new Promise(k=>setTimeout(k,1500)));m=(await this.getCleanUiHierarchy(t,s)).flat,await this.dismissSoftKeyboard(s);let B=S===1?Math.max(25,Math.ceil(n*.45)):Math.max(8,Math.ceil(n*.55/Math.max(1,v.length-1)));if(await this.exploreDfsNode({packageName:t,serial:s,screenDims:h,rootNodes:y.roots,activeRootNode:b,currentDepth:0,maxDepth:r,maxScreens:i,stepBudget:n,domainStepLimit:this.executedStepCount+B,maxInteractionsPerScreen:o,safetyMode:c,safetyBlacklist:l,domainLabel:E}),y.paradigm==="drawer"&&S>1){let k=0;for(;k<4;){let j=await this.getCleanUiHierarchy(t,s),M=st(j.flat,h.height,h.width),J=j.flat.some(K=>`${K.contentDesc} ${K.text}`.includes("Gallery")&&`${K.contentDesc} ${K.text}`.includes("Planner"));if(M&&!J)break;let Y=Re(j.flat,h.height,h.width,!0);if(Y)console.log(se.gray(" [Domain Wrap-Up] Returning to Home Screen via in-app back...")),await this.driver.tap(Y.bounds.centerX,Y.bounds.centerY,s),await new Promise(K=>setTimeout(K,1e3)),k++;else break}}if(S===1&&v.length===1){let k=await this.getCleanUiHierarchy(t,s),j=us(k.flat,h,t);if((j.paradigm==="bottom_tabs"||j.paradigm==="top_tabs")&&j.roots.length>1){console.log(se.magenta(`
|
|
849
|
+
\u26A1 Post-Auth Navigation Discovered: [${j.paradigm.toUpperCase()}] with ${j.roots.length} root domain(s)!`)),y.paradigm=j.paradigm,y.roots=j.roots;let M=j.roots.slice(1);v.push(...M.length>0?M:j.roots)}}S++}for(let b of this.visitedScreenHashes)this.memory.markScreenCrawled(b);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(se.green(`
|
|
850
|
+
\u2714 Universal DFS Traversal Complete!`)),console.log(se.cyan(` Visited Screens: ${this.visitedScreenHashes.size}`)),console.log(se.cyan(` Total Steps Executed: ${this.executedStepCount}/${n}`)),console.log(se.cyan(` Defects Triaged: ${this.devDefectsList.length}`))}async exploreDfsNode(e){let{packageName:t,serial:s,screenDims:i,rootNodes:r,activeRootNode:n,currentDepth:o,maxDepth:c,maxScreens:l,stepBudget:p,domainStepLimit:d,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:m,domainLabel:y}=e;if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l||d&&this.executedStepCount>=d||this.isAborted())return;let{flat:v}=await this.getCleanUiHierarchy(t,s),T=be(v),S=Oe(v,i);this.visitedScreenHashes.add(T);let b=this.screenLedger.get(S);if(b){if(b.status==="FULLY_EXPLORED"){console.log(se.gray(` \u26A1 Cycle Detected: Screen [${S.slice(0,8)}] already fully explored. Pruning branch.`));return}}else{let k=this.catalogScreen(v,i,r);b={hash:T,semanticHash:S,title:`${y} (depth ${o})`,elements:k,status:"IN_PROGRESS",depth:o,interactionCount:0},this.screenLedger.set(S,b),console.log(se.cyan(` \u{1F50E} Discovered Screen [${S.slice(0,8)}] at depth ${o} with ${k.length} candidate element(s).`)),this.emitStep({type:"state_change",description:`Discovered screen "${y}" at depth ${o} with ${k.length} candidate element(s)`,screenHash:S,screenTitle:y,depth:o})}this.callStack.push({screenHash:T,semanticHash:S,title:b.title,timestamp:Date.now()});let E=b.elements.filter(k=>k.type==="input"&&!k.tested);if(E.length>0&&b.interactionCount<h){console.log(se.magenta(` Filling in-place form fields (${E.length} inputs)...`));let k=await this.formFiller.fillAndSubmitForm(v,s,!0,!1);this.executedStepCount++,b.interactionCount++;for(let j of E)j.tested=!0;await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s),this.reporter.logStep("In-Place Form Fill",`Populated ${k.filledFields.length} field(s) on [${S.slice(0,8)}]`,"FormSubmit","PASS",k.submitButtonText||"Auto");for(let j of k.filledFields)this.emitStep({type:"action",description:`Type "${j.valueEntered}" in the "${j.fieldLabel}" field`,screenHash:S,screenTitle:y,depth:o});k.submitButtonText&&this.emitStep({type:"action",description:`Tap "${k.submitButtonText}" to submit the form`,screenHash:S,screenTitle:y,depth:o})}let D=b.elements.filter(k=>k.type==="toggle"&&!k.tested);for(let k of D){if(this.executedStepCount>=p||b.interactionCount>=h)break;if(k.tested=!0,Be(k.node,m,u)){this.safetyHitList.push(k.label),this.emitStep({type:"safety_block",description:`Safety policy [${u.toUpperCase()}] blocked toggle "${k.label}"`,screenHash:S,screenTitle:y,depth:o});continue}console.log(se.gray(` Exercising toggle: "${k.label.slice(0,30)}"...`)),this.executedStepCount++,b.interactionCount++,await this.driver.tap(k.node.bounds.centerX,k.node.bounds.centerY,s),await new Promise(j=>setTimeout(j,600)),this.reporter.logStep("In-Place Toggle",`Toggled control "${k.label}"`,"Tap","PASS",k.label),this.emitStep({type:"action",description:`Toggle "${k.label}"`,screenHash:S,screenTitle:y,depth:o})}let B=b.elements.filter(k=>k.type==="transition"&&!k.tested);for(let k of B){if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l||d&&this.executedStepCount>=d&&!(o===0&&y.includes("Home Screen"))||b.interactionCount>=h||this.isAborted())break;if(k.tested=!0,Ue(k.node)){this.externalSkippedList.push(k.label);continue}if(Be(k.node,m,u)){this.safetyHitList.push(k.label),this.emitStep({type:"safety_block",description:`Safety policy [${u.toUpperCase()}] blocked transition "${k.label}"`,screenHash:S,screenTitle:y,depth:o});continue}console.log(se.magenta(` \u26A1 [DFS Depth ${o}] Testing transition: "${k.label.slice(0,40)}"...`)),this.executedStepCount++,b.interactionCount++,await this.driver.tap(k.node.bounds.centerX,k.node.bounds.centerY,s),await new Promise(Y=>setTimeout(Y,1500)),await this.dismissSoftKeyboard(s),await this.handleExternalMediaChooser(t,s),await this.packageJailGuard(t,s);let j=await this.getCleanUiHierarchy(t,s),M=Oe(j.flat,i),J=M!==S;if(this.reporter.logStep("DFS Transition",`Tapped "${k.label}" [${J?"Navigated":"In-Place"}]`,"Tap","PASS",k.label),this.emitStep({type:"action",description:`Tap "${k.label}"${J?" to navigate to the next screen":""}`,screenHash:S,screenTitle:y,depth:o}),J&&M&&this.emitStep({type:"state_change",description:`Navigated to screen [${M.slice(0,8)}] via "${k.label}"`,screenHash:M,screenTitle:`${y} > ${k.label.slice(0,20)}`,depth:o+1}),J){if(o<c){let le=o===0&&y.includes("Home Screen")?Math.min(this.executedStepCount+3,d||this.executedStepCount+3):d;await this.exploreDfsNode({packageName:t,serial:s,screenDims:i,rootNodes:r,activeRootNode:n,domainStepLimit:le,currentDepth:o+1,maxDepth:c,maxScreens:l,stepBudget:p,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:m,domainLabel:`${y} > ${k.label.slice(0,20)}`})}console.log(se.gray(` [DFS Backtrack] Returning to [${S.slice(0,8)}]...`)),await this.safeBacktrack(S,t,s,o===0?n:void 0,o>0),await this.dismissSoftKeyboard(s);let Y=await this.getCleanUiHierarchy(t,s);if(Oe(Y.flat,i)!==S){let le=Re(Y.flat,i.height,i.width,!0);le&&(console.log(se.gray(" [Backtrack Verification] Re-tapping in-app back/close button...")),await this.driver.tap(le.bounds.centerX,le.bounds.centerY,s),await new Promise(De=>setTimeout(De,1e3)),await this.packageJailGuard(t,s));let Z=await this.getCleanUiHierarchy(t,s);if(Oe(Z.flat,i)!==S){console.log(se.yellow(` \u26A0\uFE0F Unable to restore parent screen [${S.slice(0,8)}]. Unwinding branch to prevent jailbreak loop.`));break}}}}b.status="FULLY_EXPLORED",this.callStack.pop()}};var ut=class{driver;formFiller;reporter;memory;safetyHitList=[];externalSkippedList=[];devDefectsList=[];visitedScreenHashes=new Set;executedStepCount=0;constructor(e,t,s,i){this.driver=e||ke,this.formFiller=t||Ji,this.reporter=s||nt,this.memory=i||Ct}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=vt(s);console.log(L.yellow(` \u{1F6E1}\uFE0F Jail Containment: App escaped to "${s}". Executing containment recovery...`)),i||(await this.driver.pressBack(t),await new Promise(n=>setTimeout(n,600)));let r=await this.driver.getForegroundPackage(t);return(!r||!r.includes(e))&&(console.log(L.gray(` Force re-launching ${e} to restore foreground...`)),await this.driver.launchApp(e,t),await new Promise(n=>setTimeout(n,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:r}=we(i),n=0;for(;n<s;){let o=jt(r);if(!o)break;n++;let c=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(L.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(L.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(L.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(L.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(d=>setTimeout(d,800)),i=await this.driver.getUiHierarchy(t),r=we(i).flat}return{xml:i,flat:r}}async handleDevOverlays(e,t,s){let i=jt(e);if(!i)return!1;let r=`[${(i.severity||"error").toUpperCase()} - ${i.type.toUpperCase()}]`,n=i.sourceLocation?` [${i.sourceLocation}]`:"";console.log(L.red(` \u{1F6A8} Dev Overlay Detected: ${r} "${i.errorText.slice(0,80)}"${n}`)),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 ${r} error: "${i.errorText}"${n}`,"Verify","FAIL",i.errorText,o,{errors:[i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText]}),i.dismissButton&&i.dismissButton.bounds.width>0?(console.log(L.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(L.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(i.node.bounds.centerX,i.node.bounds.centerY,s)):(console.log(L.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=C.explorer?.maxTabs||15,exploreLists:r=!0,skipAlreadyCrawled:n=!1,safetyMode:o=C.safety?.mode||"strict",safetyBlacklist:c=C.safety?.customBlacklist?[...C.safety.customBlacklist]:[],maxScreens:l=C.explorer?.maxScreens||30,stepBudget:p=C.explorer?.stepBudget||100,screenshots:d=C.explorer?.screenshots||"state-change",video:h=e.video??!1,onStep:u,abortSignal:m}=e;console.log(L.cyan(`
|
|
851
|
+
\u{1F916} PromptTest Autonomous Exploration Brain v3`)),console.log(L.gray("Target Package: ")+L.bold.white(t)),console.log(L.gray("Safety Policy: ")+L.bold.yellow(o.toUpperCase())+(c.length>0?L.gray(` (+${c.length} custom blacklist)`):"")),console.log(L.gray("Screenshots Policy: ")+L.bold.white(d));let y=[],v=0,T=k=>{v++,u?.({...k,stepNumber:v,packageName:t,totalSteps:k.totalSteps??this.executedStepCount,discoveredScreens:k.discoveredScreens??this.visitedScreenHashes.size})},S=async(k,j=!0)=>{if(!(d==="failure-only"&&k!=="FAIL")&&!(d==="state-change"&&!j&&k!=="FAIL"))try{return await this.driver.captureScreenshot(s)}catch{return}};await this.memory.init(t);let b=s||this.driver.getDefaultDevice(),E=b||"Default Device";this.reporter.init(t,E);let D=null;b&&(D=yt(b));let B=null;this.safetyHitList=[],this.externalSkippedList=[],this.devDefectsList=[],this.visitedScreenHashes.clear(),this.executedStepCount=0;try{if(await this.driver.clearCrashLogs(s),h&&(console.log(L.cyan("\u{1F3AC} Starting ADB screen recording for exploration (--video enabled)...")),B=await this.driver.startScreenRecording("/sdcard/prompttest_explore_temp.mp4",s)),(e.strategy||C.explorer?.strategy||"heuristic")==="dfs"){let P=new is(this.driver,this.reporter,this.memory);await P.explore({packageName:t,serial:s,maxScreens:l,maxDepth:e.maxDepth||C.explorer?.maxDepth||5,stepBudget:p,safetyMode:o,safetyBlacklist:c,screenshotPolicy:d,skipAlreadyCrawled:n,onStep:x=>T({type:x.type,description:x.description,screenHash:x.screenHash,screenTitle:x.screenTitle,depth:x.depth,elementCount:x.elementCount,totalSteps:x.totalSteps,discoveredScreens:x.discoveredScreens}),abortSignal:m}),this.safetyHitList=P.safetyHitList,this.externalSkippedList=P.externalSkippedList,this.devDefectsList=P.devDefectsList,this.visitedScreenHashes=P.visitedScreenHashes,this.executedStepCount=P.executedStepCount;let O=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${O.totalScreens} crawled screen(s).`,"Verify","PASS"),await this.reporter.generateReport(),console.log(L.bold.green(`
|
|
852
|
+
\u2728 Full Audit Report generated at: output/prompttest-report.md`));return}let{width:j,height:M}=await this.driver.getScreenDimensions(s);console.log(L.yellow(`
|
|
853
|
+
[1/5] Verifying Foreground State...`));let J=await this.driver.getForegroundPackage(s);(!J||!J.includes(t))&&(console.log(L.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(P=>setTimeout(P,2500)));let Y=await this.runErrorSentinel(t,s,"Post-Launch"),K=Y.hasError?"FAIL":"PASS",le=await S(K,!0);this.reporter.logStep("Init",`Launched and verified foreground for ${t}`,"Launch",K,t,le,Y.hasError?{errors:Y.errors}:void 0),console.log(K==="PASS"?L.green("\u2714 App is active in foreground."):L.red(`\u2716 Issues detected during launch for ${t}.`)),console.log(L.yellow(`
|
|
854
|
+
[2/5] Inspecting UI Hierarchy for Forms...`));let{xml:Z,flat:_}=await this.getCleanUiHierarchy(t,s),De=be(_);if(this.visitedScreenHashes.add(De),this.memory.isScreenCrawled(De)&&n)console.log(L.cyan(` \u26A1 Fast-Forward: Screen [${De.slice(0,8)}] was previously crawled offline. Skipping redundant element interactions.`)),this.reporter.logStep("Fast Forward",`Fast-forwarded past previously crawled screen [${De.slice(0,8)}] (Memory Engine)`,"Skip","PASS");else{let P=ze(_);if(P.length>0){console.log(L.magenta(`\u26A1 Detected ${P.length} form field(s)! Engaging Semantic Form Filler...`));for(let Q of P)console.log(L.gray(` - Field: "${Q.text||Q.contentDesc||Q.resourceId}"`));let A=await this.formFiller.fillAndSubmitForm(_,s,!0,!1);this.executedStepCount++,await new Promise(Q=>setTimeout(Q,1500)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let H=await this.getCleanUiHierarchy(t,s);Z=H.xml,_=H.flat,this.visitedScreenHashes.add(be(_));let R=await this.runErrorSentinel(t,s,"Post-Form-Submit"),W=ze(_),te=R.hasError||W.length===P.length&&R.errors.length>0?"FAIL":"PASS",q=await S(te,!0),ne=A.filledFields.map(Q=>`${Q.fieldLabel} -> "${Q.valueEntered}"`).join(", ");this.reporter.logStep("Form Fill",`Filled ${A.filledFields.length} field(s) [${ne}] and submitted via "${A.submitButtonText||"Auto"}"`,"FormSubmit",te,A.submitButtonText,q,R.hasError?{errors:R.errors}:void 0),console.log(te==="PASS"?L.green("\u2714 Form populated and submitted successfully!"):L.red("\u2716 Form submission triggered an error or remained unauthenticated."))}else console.log(L.gray("No form input fields detected on initial screen."));console.log(L.yellow(`
|
|
855
|
+
[3/5] Inspecting Interactive Action Controls...`));let O=Qe(_).filter(A=>{let H=(A.text+" "+A.contentDesc).toLowerCase();if(H.includes("submit")||H.includes("cancel")||st([A],M))return!1;if(Ue(A)){let R=A.text||A.contentDesc||A.resourceId||"External Link";return console.log(L.gray(` \u{1F517} External Link Bypassed: "${R}"`)),this.externalSkippedList.push(R),!1}if(Be(A,c,o)){let R=A.text||A.contentDesc||A.resourceId||"Action";return console.log(L.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive action "${R}"`)),this.safetyHitList.push(R),!1}return!0});if(O.length>0){let A=O[0],H=A.text||A.contentDesc||A.resourceId;console.log(L.magenta(`\u26A1 Found action button: "${H}". Testing interaction...`));let R=be(_);this.executedStepCount++,await this.driver.tap(A.bounds.centerX,A.bounds.centerY,s),await new Promise(Se=>setTimeout(Se,1200)),await this.packageJailGuard(t,s);let W=await this.getCleanUiHierarchy(t,s);Z=W.xml,_=W.flat;let X=be(_);this.visitedScreenHashes.add(X);let te=await this.runErrorSentinel(t,s,"Post-Action-Tap"),q=R!==X,ne="PASS",Q="";te.hasError?(ne="FAIL",Q="Action triggered error or crash"):q?(ne="PASS",Q="Screen transitioned successfully"):(ne="WARN",Q="No visible screen transition or state change observed (No-Op)",console.log(L.yellow(` \u26A0\uFE0F Outcome Warning: Action "${H}" produced no UI state change.`)));let Ae=await S(ne,q);this.reporter.logStep("Action Testing",`Tapped action button "${H}" [${Q}]`,"Tap",ne,H,Ae,te.hasError?{errors:te.errors}:void 0),console.log(ne==="PASS"?L.green(`\u2714 Action interaction complete (${Q}).`):ne==="WARN"?L.yellow(`\u2714 Action interaction recorded with warning (${Q}).`):L.red("\u2716 Action interaction triggered an error.")),ne!=="FAIL"&&(this.memory.recordSuccess("TAP",H,A.resourceId||A.text||A.contentDesc||H,"text",1,void 0,R),this.memory.markScreenCrawled(R,[H]))}else console.log(L.gray("No standalone action buttons to test."));let x=Dt(_).filter(A=>!Be(A,c,o));if(x.length>0){console.log(L.yellow(`
|
|
856
|
+
[3b/5] Inspecting Toggle & Checkable Controls...`));let A=x[0],H=A.text||A.contentDesc||A.resourceId||"Switch/Checkbox",R=A.checked;console.log(L.magenta(`\u26A1 Found toggle: "${H}" (checked: ${R}). Testing toggle interaction...`)),this.executedStepCount++,await this.driver.tap(A.bounds.centerX,A.bounds.centerY,s),await new Promise(Se=>setTimeout(Se,1e3)),Z=await this.driver.getUiHierarchy(s),_=we(Z).flat;let W=be(_);this.visitedScreenHashes.add(W);let te=Dt(_).find(Se=>Math.abs(Se.bounds.centerX-A.bounds.centerX)<25&&Math.abs(Se.bounds.centerY-A.bounds.centerY)<25),q=te?te.checked!==R:!0,ne=await this.runErrorSentinel(t,s,"Post-Toggle"),Q=ne.hasError?"FAIL":q?"PASS":"WARN",Ae=await S(Q,q);this.reporter.logStep("Toggle Testing",`Toggled "${H}" (Checked: ${R} -> ${te?te.checked:"flipped"})`,"Toggle",Q,H,Ae,ne.hasError?{errors:ne.errors}:void 0),console.log(Q==="PASS"?L.green("\u2714 Toggle control flipped successfully!"):Q==="WARN"?L.yellow("\u26A0\uFE0F Toggle tapped but checked state did not flip."):L.red("\u2716 Toggle control triggered an error.")),Q!=="FAIL"&&this.memory.markScreenCrawled(W,[H])}let $=st(_,M);if($&&!Be($,c,o)){let A=$.contentDesc||$.text||$.resourceId||"Drawer Menu";console.log(L.yellow(`
|
|
857
|
+
[3c/5] Inspecting Side Navigation Drawer...`)),console.log(L.magenta(`\u26A1 Found drawer trigger: "${A}". Opening side drawer...`));let H=be(_);this.executedStepCount++,await this.driver.tap($.bounds.centerX,$.bounds.centerY,s),await new Promise(Q=>setTimeout(Q,1200)),await this.packageJailGuard(t,s);let R=await this.getCleanUiHierarchy(t,s);Z=R.xml,_=R.flat;let W=be(_);this.visitedScreenHashes.add(W);let X=H!==W,te=await this.runErrorSentinel(t,s,"Drawer-Open"),q=te.hasError?"FAIL":X?"PASS":"WARN",ne=await S(q,X);if(this.reporter.logStep("Drawer Navigation",`Opened side drawer via "${A}"`,"Tap",q,A,ne,te.hasError?{errors:te.errors}:void 0),q==="PASS"){console.log(L.green("\u2714 Side drawer opened successfully!"));let Q=Qe(_).filter(Se=>!Be(Se,c,o)&&!Ue(Se)&&Se.bounds.centerY>$.bounds.y2);if(Q.length>0){let Se=Q[0],He=Se.text||Se.contentDesc||Se.resourceId||"Drawer Item";console.log(L.gray(` - Testing drawer item: "${He}"...`)),this.executedStepCount++,await this.driver.tap(Se.bounds.centerX,Se.bounds.centerY,s),await new Promise(fe=>setTimeout(fe,1200)),await this.packageJailGuard(t,s);let gt=await this.getCleanUiHierarchy(t,s);Z=gt.xml,_=gt.flat,this.visitedScreenHashes.add(be(_))}console.log(L.gray(" Closing side drawer to restore main view...")),await this.driver.pressBack(s),await new Promise(Se=>setTimeout(Se,1e3));let Ae=await this.getCleanUiHierarchy(t,s);Z=Ae.xml,_=Ae.flat,this.visitedScreenHashes.add(be(_)),console.log(L.green("\u2714 Main view restored from side drawer."))}else q==="WARN"&&console.log(L.yellow("\u26A0\uFE0F Drawer button tapped but no visible screen change occurred."));q!=="FAIL"&&this.memory.markScreenCrawled(H,[A])}if(r){console.log(L.yellow(`
|
|
858
|
+
[4/5] Inspecting Lists & Master-Detail Flows...`));let A=Ti(_);if(A.length>0){console.log(L.magenta(`\u26A1 Found ${A.length} scrollable container(s). Performing vertical scroll exploration...`));let R=be(_),W=Math.round(j*.5);await this.driver.swipe(W,Math.round(M*.7),W,Math.round(M*.3),300,s),await new Promise(Q=>setTimeout(Q,1200));let X=await this.getCleanUiHierarchy(t,s);Z=X.xml,_=X.flat;let te=be(_);this.visitedScreenHashes.add(te);let q=R!==te,ne=await S("PASS",q);this.reporter.logStep("Scroll Exploration",q?"Scrolled vertically to discover off-screen elements":"Scrolled but content remained at edge","Swipe","PASS","SwipeUp",ne),q&&console.log(L.green("\u2714 Vertical scroll succeeded; discovered off-screen content below fold."))}let H=Bt(_).filter(R=>{if(Ue(R)){let W=R.text||R.contentDesc||"External Link";return this.externalSkippedList.push(W),!1}if(Be(R,c,o)){let W=R.text||R.contentDesc||"List Item";return console.log(L.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive list item "${W}"`)),this.safetyHitList.push(W),!1}return!0});if(H.length>0){let R=H[0],W=R.text||R.contentDesc||`Item at (${R.bounds.centerX}, ${R.bounds.centerY})`;console.log(L.magenta(`\u26A1 Found list item: "${W}". Diving into detail view...`));let X=be(_);await this.driver.tap(R.bounds.centerX,R.bounds.centerY,s),await new Promise(We=>setTimeout(We,1800));let te=await this.getCleanUiHierarchy(t,s);Z=te.xml,_=te.flat;let q=be(_);this.visitedScreenHashes.add(q);let ne=await this.runErrorSentinel(t,s,"Detail-View"),Q=X!==q,Ae=ne.hasError?"FAIL":Q?"PASS":"WARN",Se=await S(Ae,Q);this.reporter.logStep("List Dive",`Dived into detail view for "${W}" [${Q?"Navigated":"Unchanged"}]`,"Tap",Ae,W,Se,ne.hasError?{errors:ne.errors}:void 0),console.log(Ae==="PASS"?L.green("\u2714 Detail screen loaded."):Ae==="WARN"?L.yellow("\u26A0\uFE0F Detail view tapped but no navigation detected."):L.red("\u2716 Detail view triggered an error."));let He=Re(te.flat,C.screen.fallbackHeight,C.screen.fallbackWidth,!0);He&&He.bounds.width>0?(console.log(L.gray(`Navigating back via in-app back button "${He.text||He.contentDesc||He.className}"...`)),await this.driver.tap(He.bounds.centerX,He.bounds.centerY,s)):(console.log(L.gray("Navigating back to main view...")),await this.driver.pressKey(4,s)),await new Promise(We=>setTimeout(We,1200));let gt=await this.driver.getForegroundPackage(s);gt&&!gt.includes(t)&&(console.log(L.yellow(`Restoring ${t} foreground after back navigation...`)),await this.driver.launchApp(t,s),await new Promise(We=>setTimeout(We,2e3)));let fe=await this.getCleanUiHierarchy(t,s);Z=fe.xml,_=fe.flat,this.visitedScreenHashes.add(be(_));let $e=await this.runErrorSentinel(t,s,"Post-Back-Restore"),et=$e.hasError?"FAIL":"PASS",Jt=await S(et,!0);this.reporter.logStep("List Dive","Navigated back to master screen","Back",et,"KEYCODE_BACK",Jt,$e.hasError?{errors:$e.errors}:void 0),et==="PASS"&&console.log(L.green("\u2714 Master view restored."))}else console.log(L.gray("No list items found for master-detail exploration."))}}console.log(L.yellow(`
|
|
859
|
+
[5/5] Inspecting Navigation Tabs...`));let f=await this.driver.getForegroundPackage(s);f&&!f.includes(t)&&(console.log(L.gray(`Restoring ${t} foreground for tab traversal...`)),await this.driver.launchApp(t,s),await new Promise(P=>setTimeout(P,2e3))),await this.dismissSoftKeyboard(s);let I=await this.getCleanUiHierarchy(t,s);Z=I.xml,_=I.flat;let N=Ut(_,void 0,t);if(N.length>1){console.log(L.magenta(`\u26A1 Found ${N.length} navigation tab(s). Traversal sequence initiated...`));let P=N.slice(0,i),O=1;for(let x of P){let $=x.text||x.contentDesc||`Tab #${O}`;console.log(L.gray(` - Visiting ${$}...`)),await this.dismissSoftKeyboard(s);let A=Math.min(x.bounds.centerY,x.bounds.y2-4);this.executedStepCount++,await this.driver.tap(x.bounds.centerX,A,s),await new Promise(q=>setTimeout(q,1500)),await this.packageJailGuard(t,s);let H=await this.getCleanUiHierarchy(t,s);Z=H.xml,_=H.flat;let R=be(_);this.visitedScreenHashes.add(R),this.memory.markScreenCrawled(R,[$]);let W=await this.runErrorSentinel(t,s,`Tab-${$}`),X=W.hasError?"FAIL":"PASS",te=await S(X,!0);if(this.reporter.logStep("Tab Traversal",`Navigated to tab "${$}"`,"Tap",X,$,te,W.hasError?{errors:W.errors}:void 0),console.log(X==="PASS"?L.green(` \u2714 Tab "${$}" loaded cleanly.`):L.red(` \u2716 Tab "${$}" triggered errors.`)),this.executedStepCount<p&&this.visitedScreenHashes.size<l){let q=[],ne=M*.08,Q=M*.88,Ae=fe=>fe.bounds.centerY>ne&&fe.bounds.centerY<Q&&fe.clickable&&fe.bounds.width>30&&fe.bounds.height>20&&N.every($e=>Math.abs($e.bounds.centerX-fe.bounds.centerX)>40||Math.abs($e.bounds.centerY-fe.bounds.centerY)>40),Se=Bt(_,{width:j,height:M}).filter(Ae);for(let fe of Se.slice(0,3))q.push({node:fe,type:"list"});let He=Qe(_).filter(fe=>!(!Ae(fe)||st([fe],M)));for(let fe of He.slice(0,4))q.push({node:fe,type:"button"});let gt=Dt(_).filter(Ae);for(let fe of gt.slice(0,2))q.push({node:fe,type:"toggle"});for(let fe of q){if(this.executedStepCount>=p||this.visitedScreenHashes.size>=l)break;let $e=fe.node;if(Ue($e)){this.externalSkippedList.push($e.text||$e.contentDesc||"External Link");continue}if(Be($e,c,o)){let Et=$e.text||$e.contentDesc||"Destructive Action";this.safetyHitList.push(Et);continue}let et=$e.text||$e.contentDesc||$e.resourceId||`${fe.type} element`;console.log(L.gray(` Sub-crawl [${$}]: Exercising ${fe.type} "${et.slice(0,40)}"...`)),this.executedStepCount++,await this.driver.tap($e.bounds.centerX,$e.bounds.centerY,s),await new Promise(Et=>setTimeout(Et,1200)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let Jt=await this.getCleanUiHierarchy(t,s);Z=Jt.xml,_=Jt.flat;let We=be(_),cn=!this.visitedScreenHashes.has(We);this.visitedScreenHashes.add(We);let ns=await this.runErrorSentinel(t,s,`Sub-${et.slice(0,30)}`),di=ns.hasError?"FAIL":"PASS",ln=await S(di,cn);if(this.reporter.logStep("Tab Sub-Crawl",`Tested ${fe.type} "${et}" under tab "${$}"`,"Tap",di,et,ln,ns.hasError?{errors:ns.errors}:void 0),We!==R){console.log(L.cyan(` \u{1F50E} Screen transitioned. Discovered new screen state [${We.slice(0,8)}]`));let Et=Qe(_).filter(Ve=>Ae(Ve)&&!Be(Ve,c,o)&&!Ue(Ve));if(Et.length>0&&this.executedStepCount<p){let Ve=Et[0],dn=Ve.text||Ve.contentDesc||"Child Action";console.log(L.gray(` Exercising child action "${dn.slice(0,30)}"...`)),this.executedStepCount++,await this.driver.tap(Ve.bounds.centerX,Ve.bounds.centerY,s),await new Promise(pn=>setTimeout(pn,1e3)),await this.dismissSoftKeyboard(s)}console.log(L.gray(` Restoring ${$} master view via Back...`)),await this.driver.pressBack(s),await new Promise(Ve=>setTimeout(Ve,1e3)),await this.dismissSoftKeyboard(s);let pi=await this.getCleanUiHierarchy(t,s);Z=pi.xml,_=pi.flat}}}O++}console.log(L.green("\u2714 Navigation tabs traversed successfully!"))}else console.log(L.gray("Single-screen or tabs not detected at screen footer."));for(let P of this.visitedScreenHashes)this.memory.markScreenCrawled(P);await this.memory.save();let de=this.memory.getStats();if(this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${de.crawledScreens} crawled screen(s).`,"Verify","PASS"),await this.runErrorSentinel(t,s,"Final-State"),B){console.log(L.cyan("\u{1F3AC} Finalizing exploration screen recording..."));let P=ei.resolve(process.cwd(),"output"),O=ei.join(P,`${t}-exploration.mp4`),x=await this.driver.stopScreenRecording(B,O,s);x&&Kn.existsSync(x)&&(this.reporter.setVideoPath?.(`${t}-exploration.mp4`),console.log(L.green(`\u2714 Screen recording saved to: output/${t}-exploration.mp4`))),B=null}let he=await this.reporter.generateReport(),g=he.failedSteps===0&&he.errorsDetected.length===0;console.log(g?L.bold.green(`
|
|
860
|
+
\u2728 PromptTest Exploration Complete \u2014 All Steps Passed!`):L.bold.red(`
|
|
861
|
+
\u26A0\uFE0F PromptTest Exploration Complete \u2014 Issues Detected!`)),console.log(L.white(`Summary: ${he.passedSteps} passed, ${he.warnSteps} warnings, ${he.failedSteps} failed, ${he.errorsDetected.length} errors detected.`)),this.safetyHitList.length>0&&console.log(L.cyan(`\u{1F6E1}\uFE0F Safety Shield: Blocked ${this.safetyHitList.length} destructive action(s) [${this.safetyHitList.join(", ")}].`)),console.log(L.cyan(`\u{1F5FA}\uFE0F State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s).`)),console.log(L.cyan(`\u{1F9E0} Memory Engine Coverage: ${de.crawledScreens} crawled screen(s) indexed offline.`)),console.log(L.cyan(`Full Audit Report generated at: output/prompttest-report.md
|
|
862
|
+
`))}finally{if(B)try{await this.driver.stopScreenRecording(B,ei.join("output",`${t}-exploration.mp4`),s)}catch{}D&&St(D)}}async runErrorSentinel(e,t,s){let i=[];try{let[r,n]=await Promise.all([this.driver.checkCrashes(e,t),this.driver.getUiHierarchy(t)]);if(r){let l=`Crash in ${s}: ${r.slice(0,300)}`;console.log(L.bold.red(`\u{1F6A8} FATAL EXCEPTION DETECTED in ${e} [${s}]!`)),this.reporter.logError(l),i.push(l)}let{flat:o}=we(n),c=vi(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(L.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}}},Xi=new ut;var qn={".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 Gi(a={}){let e=a.port??4040,t=a.host||"127.0.0.1",s=process.cwd();(s==="/"||s==="\\")&&(s=zi.homedir?zi.homedir():process.env.HOME||process.env.USERPROFILE||"/tmp");let i=a.outputDir?z.resolve(a.outputDir):z.resolve(s,"output"),r=a.suiteName||"PromptTest Live Monitor",n=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
|
|
863
|
+
|
|
864
|
+
`)}catch{o.delete(w)}},15e3),l=a.driver||new tt,p=z.dirname(Zn(import.meta.url)),d=a.specsDir?z.resolve(a.specsDir):z.resolve(process.cwd(),"specs");if(!ee.existsSync(d)){let w=z.resolve(p,"../specs");ee.existsSync(w)&&(d=w)}let h=null;function u(){return h||(h=new Ke(l)),h}let m=z.join(i,"baselines"),y=new ct(m),v=null,T=null,S=["strict","moderate","interactive","disabled"],b=null,E=0;function D(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 B(w){let f=w.match(/"([^"]+)"/);return f?f[1]:null}function k(w){let f=w.specLines.length>0?w.specLines:["Launch the app"],I=["# 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&&I.push(`# Device: ${w.deviceId}`),[...I,"",...f,""].join(`
|
|
865
|
+
`)}function j(w,f,I){w.status=f,w.finishedAt=new Date().toISOString(),I&&(w.error=I),Y("explore",{...D(w),event:{type:f==="failed"?"error":"done",description:I||f}})}function M(w){let f=b;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 I=B(w.description);I&&f.elementLabels.add(I),w.description&&f.specLines[f.specLines.length-1]!==w.description&&f.specLines.push(w.description)}if(w.screenHash){let I=w.screenTitle||w.description||w.screenHash.slice(0,8),N=f.screens.find(de=>de.hash===w.screenHash);N?(N.visits++,typeof w.elementCount=="number"&&(N.elements=w.elementCount),N.label===N.hash.slice(0,8)&&w.screenTitle&&(N.label=w.screenTitle,N.title=w.screenTitle)):f.screens.push({id:w.screenHash,hash:w.screenHash,depth:w.depth??f.screens.length,title:I,label:I,visits:1,elements:w.elementCount??0}),f.screensDiscovered=Math.max(f.screensDiscovered,f.screens.length)}if(w.type==="crash"){let I=new Date().toISOString(),N=w.screenHash,de=N?f.screens.find(he=>he.hash===N):void 0;f.crashes.push({id:N||`crash-${f.crashes.length+1}`,type:w.description.toLowerCase().includes("anr")?"anr":"crash",message:w.description,screen:de?.label||N?.slice(0,8),timestamp:I,description:w.description,screenHash:N})}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(),Y("explore",{...D(f),event:w})}}function J(w){let f=S.includes(w.safetyMode||"")?w.safetyMode:"strict";E++;let I={id:`explore-${Date.now()}-${E}`,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}};b=I;let N=new ut(l);return Y("explore",{...D(I),event:{type:"state_change",description:`Auto-Pilot launched on ${I.packageName} (${I.safetyMode} mode)`}}),N.explore({packageName:I.packageName,serial:I.deviceId,strategy:"dfs",safetyMode:I.safetyMode,maxDepth:I.maxDepth,maxScreens:I.maxScreens,stepBudget:I.maxSteps,screenshots:"state-change",onStep:M,abortSignal:I.abort}).then(()=>{j(I,I.abort.aborted?"stopped":"completed")}).catch(de=>{j(I,I.abort.aborted?"stopped":"failed",de instanceof Error?de.message:String(de))}),I}function Y(w,f){let I=`event: ${w}
|
|
866
|
+
data: ${JSON.stringify(f)}
|
|
867
|
+
|
|
868
|
+
`;for(let N of o)try{N.write(I)}catch{o.delete(N)}}function K(w){return new Promise((f,I)=>{let N="";w.on("data",de=>{N+=de}),w.on("end",()=>{try{f(N?JSON.parse(N):{})}catch{I(new Error("Invalid JSON payload"))}}),w.on("error",I)})}let le=Qn.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 I=new URL(w.url||"/",`http://${t}:${e}`),N=decodeURIComponent(I.pathname);if(N==="/api/devices"){try{let g=await l.getConnectedDevices();f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,devices:g}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/screen-state"){try{let g=I.searchParams.get("deviceId")||void 0,P=I.searchParams.get("hierarchy")!=="false",[O,x,$]=await Promise.all([l.captureScreenshot(g),P?l.getUiHierarchy(g):Promise.resolve(null),l.getForegroundPackage(g)]),A=[];if(x){let{flat:H}=we(x);A=H.map(R=>({index:R.index,text:R.text,resourceId:R.resourceId,className:R.className,contentDesc:R.contentDesc,clickable:R.clickable,scrollable:R.scrollable,bounds:R.bounds}))}f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,deviceId:g||l.getDefaultDevice()||"default",foregroundApp:$,screenshot:`data:image/png;base64,${O.toString("base64")}`,elements:P?A:void 0,elementCount:A.length}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/tap"&&w.method==="POST"){try{let g=await K(w);if(typeof g.x!="number"||typeof g.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(g.x,g.y,g.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,tapped:{x:g.x,y:g.y}}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/type"&&w.method==="POST"){try{let g=await K(w);if(typeof g.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(g.text,g.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,typed:g.text}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/key"&&w.method==="POST"){try{let g=await K(w);if(g.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(g.keyCode,g.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,keyCode:g.keyCode}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/wake"&&w.method==="POST"){try{let g=await K(w);await l.wakeDevice(g.deviceId),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/wifi/connect"&&w.method==="POST"){try{let g=await K(w),P=await l.connectWifi(g.target,g.port||5555,g.deviceId);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:P.success,target:P.target,message:P.message}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/wifi/disconnect"&&w.method==="POST"){try{let g=await K(w),P=await l.disconnectWifi(g.target);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:P}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/wifi/pair"&&w.method==="POST"){try{let g=await K(w);if(!g.target||!g.pairingCode){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing target or pairingCode"}));return}let P=await l.pairWifi(g.target,g.pairingCode);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify(P))}catch(g){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/metrics"&&w.method==="GET"){try{let g=I.searchParams.get("deviceId")||void 0,P=await l.getDeviceMetrics(g);if(Object.keys(P).length===0)throw new Error(`No metrics available for device ${g||"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:P}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/doctor"&&w.method==="GET"){try{let g=I.searchParams.get("deviceId")||void 0,P=I.searchParams.get("packageName")||void 0,O=await ss(l,{serial:g,packageName:P});f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,report:O}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if((N==="/api/explore/start"||N==="/api/explore")&&w.method==="POST"){try{let g=await K(w),P=(g.packageName||g.targetPackage||"").trim();if(!P){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing packageName (packageName or targetPackage)"}));return}if(b&&b.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:b.id}));return}let O=J({packageName:P,deviceId:g.deviceId||g.serial,safetyMode:g.safetyMode||g.safety,maxDepth:g.maxDepth??g.depth,maxSteps:g.maxSteps??g.stepBudget,maxScreens:g.maxScreens});f.writeHead(202,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,sessionId:O.id,status:O.status,packageName:O.packageName}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if((N==="/api/explore/status"||N==="/api/explore")&&w.method==="GET"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify(D(b)));return}if((N==="/api/explore/stop"||N==="/api/explore")&&(w.method==="POST"||w.method==="DELETE")){if(!b){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}b.abort.aborted=!0,f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,sessionId:b.id,status:"stopping",packageName:b.packageName}));return}if(N==="/api/explore/export"&&w.method==="POST"){try{let g=await K(w);if(!b){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 P=(g.specName||`explored_${b.packageName}.txt`).trim(),O=z.basename(P).replace(/[^a-zA-Z0-9._-]/g,"_"),x=O.endsWith(".txt")?O:`${O}.txt`,$=k(b);await ee.promises.mkdir(d,{recursive:!0}),await ee.promises.writeFile(z.join(d,x),$,"utf8"),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specName:x,content:$,screensDiscovered:b.screensDiscovered,stepsTaken:b.stepsTaken}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/record/start"&&w.method==="POST"){try{let g=await K(w);if(v){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 P=g.deviceId||l.getDefaultDevice()||void 0,O=g.specName?z.join(d,z.basename(g.specName)):void 0;v=new lt(l),T=P||"default",v.onStep=x=>{Y("record-step",{step:x,deviceId:P})},await v.startSession(O,P,{append:g.append}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"Recording session started",deviceId:P}))}catch(g){if(v)try{await v.stopSession()}catch{}v=null,T=null,f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/record/stop"&&w.method==="POST"){try{if(!v){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"No active recording session",steps:[]}));return}let g=await v.stopSession();v=null,T=null,f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,steps:g.steps,specPath:g.specPath,reportPath:g.reportPath}))}catch(g){v=null,T=null,f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/record/status"&&w.method==="GET"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,isRecording:v!==null,deviceId:T}));return}if(N==="/api/specs"&&w.method==="GET"){try{ee.existsSync(d)||ee.mkdirSync(d,{recursive:!0});let P=ee.readdirSync(d).filter(O=>O.endsWith(".txt")||O.endsWith(".spec")).map(O=>{let x=z.join(d,O),$=ee.statSync(x);return{name:O,path:z.relative(process.cwd(),x).replace(/\\/g,"/"),size:$.size,modified:$.mtime.toISOString()}});f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,specs:P}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if((N.startsWith("/api/specs/")||N==="/api/spec")&&w.method==="GET"){try{let g="";N.startsWith("/api/specs/")?g=decodeURIComponent(N.slice(11)):g=I.searchParams.get("name")||"";let P=z.basename(g.trim());if(!P){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing spec file name"}));return}let O=z.join(d,P);if(!ee.existsSync(O)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Spec file not found: ${P}`}));return}let x=ee.readFileSync(O,"utf-8");f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,name:P,content:x}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if((N==="/api/specs"||N==="/api/spec")&&w.method==="POST"){try{let g=await K(w),P=(g.name||"").trim();if(!P){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing spec file name"}));return}!P.endsWith(".txt")&&!P.endsWith(".spec")&&(P+=".txt");let O=z.basename(P);ee.existsSync(d)||ee.mkdirSync(d,{recursive:!0});let x=z.join(d,O);ee.writeFileSync(x,g.content??"","utf-8"),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,name:O,path:x}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/action"&&w.method==="POST"){try{let g=await K(w);if(!g.step||typeof g.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 P=Nt(g.step);if(P.length===0){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Could not parse step: "${g.step}"`}));return}let O=u(),x=P[0],$=g.deviceId||l.getDefaultDevice()||void 0,A=Date.now(),H=await O.executeStep(x,$),R=Date.now()-A;Y("step",{stepNumber:n.steps.length+1,instruction:x.originalText,status:"PASS",durationMs:R}),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,step:x.originalText,type:x.type,durationMs:R,result:H||null}))}catch(g){let P=g instanceof Error?g.message:String(g);Y("step",{stepNumber:n.steps.length+1,instruction:"Step Execution",status:"FAIL",durationMs:0,error:P}),f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:P}))}return}if(N==="/api/run"&&w.method==="POST"){try{let g=await K(w),P="";if(g.specName){let A=z.basename(g.specName);if(P=z.join(d,A),!ee.existsSync(P)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Spec file not found: ${A}`}));return}}else if(g.spec&&typeof g.spec=="string")ee.existsSync(i)||ee.mkdirSync(i,{recursive:!0}),P=z.join(i,"_studio_temp_spec.txt"),ee.writeFileSync(P,g.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 O=g.deviceId||l.getDefaultDevice()||void 0,x=u();n.steps=[],n.totalSteps=0,n.passedSteps=0,n.failedSteps=0,n.warnSteps=0,n.skippedSteps=0;let $=nt.onStep?.(A=>{Y("step",{stepNumber:A.stepIndex,instruction:A.description,status:A.status,durationMs:A.durationMs||0,error:A.details?.error})});(async()=>{try{let A=await x.runSpec(P,{serial:O,saveBaseline:g.saveBaseline!==void 0?g.saveBaseline:!1,compareBaseline:g.compareBaseline!==void 0?g.compareBaseline:!0,screenshotMode:"all",heal:g.heal??!1,fresh:g.fresh??!1,continueOnError:g.continueOnError??!1});n=A,Y("complete",A)}catch(A){let H=A instanceof Error?A.message:String(A);n.errorsDetected.push(H),Y("error",{error:H}),Y("complete",n)}finally{$&&$()}})(),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,message:"Execution started"}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/reports"&&w.method==="GET"){try{if(!ee.existsSync(i)){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,reports:[]}));return}let O=ee.readdirSync(i).filter(x=>x.endsWith("-results.json")).map(x=>{let $=x.replace(/-results\.json$/,""),A=z.join(i,x),H=`${$}-report.html`,R=ee.existsSync(z.join(i,H)),W=ee.statSync(A);try{let X=JSON.parse(ee.readFileSync(A,"utf-8")),te=X.totalSteps||X.steps?.length||0,q=X.passedSteps||0,ne=X.failedSteps||0,Q=te>0?Math.round(q/te*100):100;return{id:$,fileName:x,suiteName:X.packageName||$,packageName:X.packageName||"Unknown",deviceId:X.deviceId||"Unknown",startTime:X.startTime||W.mtime.toISOString(),endTime:X.endTime||W.mtime.toISOString(),durationSeconds:X.durationSeconds||0,totalSteps:te,passedSteps:q,failedSteps:ne,warnSteps:X.warnSteps||0,skippedSteps:X.skippedSteps||0,passRate:Q,errorsCount:X.errorsDetected?.length||0,htmlReportPath:R?`/${H}`:null,jsonReportPath:`/${x}`}}catch{return null}}).filter(Boolean).sort((x,$)=>new Date($.startTime).getTime()-new Date(x.startTime).getTime());f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,reports:O}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if((N.startsWith("/api/reports/")||N==="/api/report-detail")&&w.method==="GET"){try{let g="";N.startsWith("/api/reports/")?g=decodeURIComponent(N.slice(13)):g=I.searchParams.get("id")||"";let P=z.basename(g.trim()),O=P.endsWith("-results.json")?P:`${P}-results.json`,x=z.join(i,O);if(!ee.existsSync(x)){f.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:`Report not found: ${P}`}));return}let $=JSON.parse(ee.readFileSync(x,"utf-8"));f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,id:P,report:$}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines"&&w.method==="GET"){try{ee.existsSync(m)||ee.mkdirSync(m,{recursive:!0});let g=I.searchParams.get("spec")||"",P=g.replace(/[^a-zA-Z0-9._-]/g,"_"),O=ee.readdirSync(m),x=new Map;for(let A of O){if(P&&!A.startsWith(`${P}_step`))continue;let H=A.match(/_step(\d+)(_current|_diff)?\.png$/);if(!H)continue;let R=parseInt(H[1],10),W=H[2];x.has(R)||x.set(R,{});let X=x.get(R);W?W==="_current"?X.current=`/baselines/${A}`:W==="_diff"&&(X.diff=`/baselines/${A}`):X.baseline=`/baselines/${A}`}let $=await Promise.all(Array.from(x.entries()).map(async([A,H])=>{let R=await y.getMasks(g,A);return{stepIndex:A,...H,masks:R}}));$.sort((A,H)=>A.stepIndex-H.stepIndex),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,spec:g,baselines:$,matchingModes:ys}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/compare"&&w.method==="POST"){try{let g=await K(w);if(!g.specName||typeof g.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 P;if(g.screenshot){let $=g.screenshot.replace(/^data:image\/\w+;base64,/,"");P=Buffer.from($,"base64")}else{let $=g.deviceId||l.getDefaultDevice()||void 0;P=await l.captureScreenshot($)}let O=await y.compare(g.specName,g.stepIndex,P,{threshold:g.threshold,mode:g.mode,maskRegions:g.maskRegions}),x=await y.getMasks(g.specName,g.stepIndex);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,result:{...O,masks:x,baselineUrl:`/baselines/${z.basename(O.baselineFile)}`,currentUrl:`/baselines/${z.basename(O.currentFile)}`,diffUrl:O.diffImagePath?`/baselines/${z.basename(O.diffImagePath)}`:null}}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/approve"&&w.method==="POST"){try{let g=await K(w);if(!g.specName||typeof g.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 P;if(g.screenshot){let x=g.screenshot.replace(/^data:image\/\w+;base64,/,"");P=Buffer.from(x,"base64")}else{let x=g.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),$=z.join(m,`${x}_step${String(g.stepIndex).padStart(3,"0")}_current.png`);if(!ee.existsSync($)){let A=g.deviceId||l.getDefaultDevice()||void 0;try{P=await l.captureScreenshot(A)}catch{}}}let O=await y.approveBaseline(g.specName,g.stepIndex,P);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,approved:!0,stepIndex:g.stepIndex,baselineUrl:`/baselines/${z.basename(O)}`}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/clear"&&w.method==="POST"){try{let g=await K(w);if(!g.specName){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName"}));return}await y.clearBaselines(g.specName),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,cleared:!0,specName:g.specName}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/delete-step"&&w.method==="POST"){try{let g=await K(w);if(!g.specName||typeof g.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 y.deleteStepBaseline(g.specName,g.stepIndex),f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,deleted:!0,specName:g.specName,stepIndex:g.stepIndex}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/upload"&&w.method==="POST"){try{let g=await K(w);if(!g.specName||typeof g.stepIndex!="number"||!g.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 P=g.image.replace(/^data:image\/\w+;base64,/,""),O=Buffer.from(P,"base64"),x=await y.saveBaseline(g.specName,g.stepIndex,O),$=g.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),A=z.join(m,`${$}_step${String(g.stepIndex).padStart(3,"0")}_diff.png`);if(ee.existsSync(A))try{await ee.promises.unlink(A)}catch{}let H=z.join(m,`${$}_step${String(g.stepIndex).padStart(3,"0")}_current.png`),R,W;if(ee.existsSync(H)){let te=await ee.promises.readFile(H),q=await y.compare(g.specName,g.stepIndex,te);R=`/baselines/${z.basename(H)}`,W=q.diffImagePath?`/baselines/${z.basename(q.diffImagePath)}`:void 0}else if(g.deviceId||l.getDefaultDevice()){let te=g.deviceId||l.getDefaultDevice()||void 0;try{let q=await l.captureScreenshot(te),ne=await y.compare(g.specName,g.stepIndex,q);R=`/baselines/${z.basename(H)}`,W=ne.diffImagePath?`/baselines/${z.basename(ne.diffImagePath)}`:void 0}catch{}}let X=await y.getMasks(g.specName,g.stepIndex);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,uploaded:!0,stepIndex:g.stepIndex,baselineUrl:`/baselines/${z.basename(x)}`,currentUrl:R,diffUrl:W,masks:X}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/masks"&&w.method==="GET"){try{let g=I.searchParams.get("specName")||I.searchParams.get("spec")||"",P=parseInt(I.searchParams.get("stepIndex")||"",10);if(!g||isNaN(P)){f.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:"Missing specName or valid stepIndex"}));return}let O=await y.getMasks(g,P);f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,masks:O}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/api/baselines/masks"&&w.method==="POST"){try{let g=await K(w);if(!g.specName||typeof g.stepIndex!="number"||!Array.isArray(g.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 y.saveMasks(g.specName,g.stepIndex,g.masks);let P=g.specName.replace(/[^a-zA-Z0-9._-]/g,"_"),O=z.join(m,`${P}_step${String(g.stepIndex).padStart(3,"0")}_current.png`),x,$,A=0,H=0,R=!0;if(ee.existsSync(O)){let W=await ee.promises.readFile(O),X=await y.compare(g.specName,g.stepIndex,W,{mode:g.mode,threshold:g.threshold,maskRegions:g.masks});x=`/baselines/${z.basename(O)}`,$=X.diffImagePath?`/baselines/${z.basename(X.diffImagePath)}`:void 0,A=X.diffRatio,H=X.diffPixels,R=X.passed}f.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!0,masks:g.masks,currentUrl:x,diffUrl:$,diffRatio:A,diffPixels:H,passed:R}))}catch(g){f.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),f.end(JSON.stringify({success:!1,error:g instanceof Error?g.message:String(g)}))}return}if(N==="/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
|
|
708
869
|
data: ${JSON.stringify({status:"connected",time:Date.now()})}
|
|
709
870
|
|
|
710
|
-
`),
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
\u{
|
|
718
|
-
|
|
719
|
-
`):`
|
|
720
|
-
\u{1F4A1} No similar text found on current screen.`;return new Error(`${t}${n}`)}function Zs(p,e,t,s){let i=X(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=p.filter(c=>c.className.includes("EditText")&&c.bounds.width>0);if(o.length===0)return null;let a=o.find(c=>z(e,c.contentDesc)||z(e,c.resourceId)||z(e,c.text));if(a)return a;let d=p.filter(c=>!c.className.includes("EditText")&&(z(e,c.text)||z(e,c.contentDesc)||z(e,c.resourceId))&&c.bounds.width>0);for(let c of d){let l=o.filter(h=>h.bounds.centerY>=c.bounds.centerY&&h.bounds.centerY-c.bounds.centerY<300&&Math.abs(h.bounds.centerX-c.bounds.centerX)<450);if(l.length>0)return l.sort((h,u)=>h.bounds.centerY-u.bounds.centerY),l[0]}if(s){let c=s.getAllCandidates("TYPE",e);for(let l of c){let h=o.find(u=>z(l,u.contentDesc)||z(l,u.resourceId)||z(l,u.text));if(h)return h}}if(n){let c=o.find(l=>l.password);if(c)return c;if(o.length>1){let l=o.find(h=>h.text?.toLowerCase().includes("email")||h.contentDesc?.toLowerCase().includes("email"));if(l){let h=o.filter(u=>u.bounds.centerY>l.bounds.centerY);if(h.length>0)return h.sort((u,g)=>u.bounds.centerY-g.bounds.centerY),h[0]}}if(o.length>=2)return o[1]}if(r){let c=o.find(l=>!l.password);if(c)return c;if(o.length>0)return o[0]}return o.length===1?o[0]:null}function It(p,e,t,s="en",i,n){let r=i?.type||"TAP",o=X(e),d=p.filter(u=>(X(u.text)===o||X(u.contentDesc)===o)&&u.bounds.width>0&&u.bounds.height>0).find(u=>u.clickable);if(d)return[d];let c=t.getAllCandidates(r,e,s,n),l=[];for(let u of c){let g=p.filter(f=>{let y=z(u,f.text),S=z(u,f.contentDesc),b=z(u,f.resourceId);return(y||S||b)&&f.bounds.width>0&&f.bounds.height>0});if(g.length>0){l=g;break}}if(l.length===0){let u=[];for(let f of p)f.text&&f.text.trim().length>1&&u.push(f.text.trim()),f.contentDesc&&f.contentDesc.trim().length>1&&u.push(f.contentDesc.trim());let g=We(e,u,1);if(g.length>0&&g[0].score>=.8){let f=g[0].text,y=p.filter(S=>(z(f,S.text)||z(f,S.contentDesc))&&S.bounds.width>0&&S.bounds.height>0);y.length>0&&(console.log(ie.yellow(` \u{1F4A1} [Self-Healing] Auto-resolved "${e}" \u2192 "${f}" (${Math.round(g[0].score*100)}% match)`)),l=y)}}if(l.length===0)return[];let h=l.filter(u=>{let g=X(u.text),f=X(u.contentDesc);return g===o||f===o});if(h.length>0)l=h;else{let u=l.filter(g=>{let f=X(g.contentDesc);return f.endsWith(o)||f.includes(`, ${o}`)});u.length>0&&(l=u)}if(i?.relativeTo){let u=p.find(g=>z(i.relativeTo,g.text)||z(i.relativeTo,g.contentDesc));if(u){let g=l.filter(f=>Math.abs(f.bounds.centerY-u.bounds.centerY)<140).sort((f,y)=>{let S=Math.hypot(f.bounds.centerX-u.bounds.centerX,f.bounds.centerY-u.bounds.centerY),b=Math.hypot(y.bounds.centerX-u.bounds.centerX,y.bounds.centerY-u.bounds.centerY);return S-b});if(g.length>0)return g}}if(i?.ordinal){let u=i.ordinal.toLowerCase();if(u==="1st"||u==="first")return[l[0]];if(u==="2nd"&&l.length>1)return[l[1]];if(u==="3rd"&&l.length>2)return[l[2]];if(u==="4th"&&l.length>3)return[l[3]];if(u==="5th"&&l.length>4)return[l[4]];if(u==="last"&&l.length>0)return[l[l.length-1]]}return l}function ce(p){if(!p||p.length===0)return"0";let e=2166136261;for(let t=0;t<p.length;t++){let s=p[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 Mi=[/\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 Qs(p){if(!p)return"";let e=p;for(let t of Mi)e=e.replace(t,"<VAL>");return e.trim()}function Ne(p,e){if(!p||p.length===0)return"0";let s=(e?.height||2400)*.04,i=2166136261;for(let n=0;n<p.length;n++){let r=p[n];if(r.bounds&&r.bounds.centerY<s)continue;let o=Qs(r.text||""),a=Qs(r.contentDesc||""),d=r.resourceId||"",c=r.className||"",l=r.clickable?"1":"0",h=r.checkable?"1":"0",u=Math.round((r.bounds?.x1||0)/50),g=Math.round((r.bounds?.y1||0)/50),f=Math.round((r.bounds?.width||0)/50),y=Math.round((r.bounds?.height||0)/50),S=`${c}|${d}|${o}|${a}|${l}|${h}|${u},${g},${f},${y}`;for(let b=0;b<S.length;b++)i^=S.charCodeAt(b),i=Math.imul(i,16777619)}return(i>>>0).toString(16)}function bn(p,e){let t=ce(p),s=ce(e);return{hasChanged:t!==s,previousHash:t,currentHash:s,nodeCountDelta:e.length-p.length}}function ei(p){let e=new Set;if(!p)return e;let t=p.split(",").map(s=>s.trim()).filter(Boolean);for(let s of t)if(s.includes("-")){let[i,n]=s.split("-").map(a=>a.trim()),r=parseInt(i,10),o=parseInt(n,10);if(!isNaN(r)&&!isNaN(o)){let[a,d]=r<=o?[r,o]:[o,r];for(let c=a;c<=d;c++)e.add(c)}}else{let i=parseInt(s,10);isNaN(i)||e.add(i)}return e}function ti(p){let e=new Set,t=p.split(`
|
|
721
|
-
`);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 si(p){let e=["",ie.bold.cyan(`\u{1F4CB} Parsed Test Steps (${p.length} total):`),ie.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"),ie.gray("\u2502")+` ${ie.bold("#".padEnd(3))} `+ie.gray("\u2502")+` ${ie.bold("Type".padEnd(14))} `+ie.gray("\u2502")+` ${ie.bold("Target".padEnd(28))} `+ie.gray("\u2502")+` ${ie.bold("Value / Detail".padEnd(30))} `+ie.gray("\u2502")+` ${ie.bold("Optional".padEnd(8))} `+ie.gray("\u2502"),ie.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 p.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),a=(t.optional?"Yes":"No").padEnd(8);e.push(ie.gray("\u2502")+` ${ie.white(i)} `+ie.gray("\u2502")+` ${ie.cyan(n)} `+ie.gray("\u2502")+` ${ie.yellow(r)} `+ie.gray("\u2502")+` ${ie.white(o)} `+ie.gray("\u2502")+` ${ie.gray(a)} `+ie.gray("\u2502"))}),e.push(ie.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
|
|
722
|
-
`)),e.join(`
|
|
723
|
-
`)}function Lt(p,e,t=[],s="SKIPPED",i="Validation"){let n=new Date().toISOString(),r=s==="PASS";return{packageName:p||"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,a)=>({stepIndex:a+1,timestamp:n,phase:i,description:o.originalText,action:o.type,target:o.target,status:s,durationMs:0}))}}function yn(p,e){return p&&(e&&/password|passwd|pin\b|secret|token|api[_-]?key|auth|credential/i.test(e)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":p)}var Ye=class{driver;memory;reporter;checkpoints;baselines;lastHierarchy=null;screenDimensions={width:E.screen.fallbackWidth,height:E.screen.fallbackHeight};navBarHeight=0;constructor(e,t,s,i,n,r){this.driver=e||he,this.memory=t||at,this.reporter=s||nt,this.checkpoints=i||Xs,this.baselines=n||Kt,this.semanticResolver=r||ws()}semanticResolver;healEnabled=!1;activeLocale="en";runtimeVariables=new Map;loopStack=[];expandSpecIncludes(e,t=new Set){return Ts(e,t)}async expandSpec(e,t){let s=t||this.semanticResolver,i=e.split(`
|
|
724
|
-
`),n=[],r=0;for(let o of i){let a=o.trim();if(!a||a.startsWith("#")||a.startsWith("//")){n.push(o);continue}let d=this.parsePrompt(a);if(d.length>0&&d[0].type!==void 0&&!a.toLowerCase().startsWith("intent:")){n.push(o);continue}let l=a.replace(/^intent:\s*/i,""),h=this.memory?.getIntentExpansion(l);if(h?.length){n.push(`# [Cached Intent] ${a}`,...h),r+=h.length;continue}let u=await s.resolveIntent(l);if(u?.length){n.push(`# [AI Expanded] ${a}`);let g=u.map(f=>f.originalText);n.push(...g),this.memory&&(this.memory.recordIntentExpansion(l,g),await this.memory.save().catch(()=>{})),r+=u.length}else n.push(o)}return{expanded:n.join(`
|
|
725
|
-
`),stepsAdded:r}}parsePrompt(e,t){return Ct(e,t)}async runSpec(e,t,s){if(!Ce.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=ws({provider:"heuristic"})),this.activeLocale=(i.locale||E.locale||"en").toLowerCase(),typeof this.memory.setLocale=="function"&&this.memory.setLocale(this.activeLocale);let n=this.expandSpecIncludes(e),r=n,o=[],a=dt.extractDataDirective(n,me.dirname(e));if(a)r=a.cleanedSpec,o=a.rows;else if(i.dataFile){let b=me.isAbsolute(i.dataFile)?i.dataFile:me.resolve(process.cwd(),i.dataFile);o=dt.loadFromFile(b)}(i.onlyRow!==void 0||i.iterations!==void 0)&&(o.length>0?o=dt.filterRows(o,{onlyRow:i.onlyRow,iterations:i.iterations}):i.iterations&&i.iterations>0&&(o=Array.from({length:i.iterations},()=>({}))));let d=o.length>0?o.map(b=>({...i.variables||{},...b})):[i.variables||{}],c=me.basename(e,me.extname(e)),l=r.match(/#\s*(?:Target\s*)?Package:\s*([a-zA-Z0-9._-]+)/i),h=l?l[1]:void 0;if(i.tags){let b=ti(n),m=i.tags.split(",").map(x=>x.trim().toLowerCase()).filter(Boolean);if(!m.some(x=>b.includes(x)))return console.log(R.yellow(`
|
|
726
|
-
\u23E9 Skipping ${e}: tags [${b.join(", ")}] do not match filter [${m.join(", ")}]`)),Lt(h||i.packageName||"",i.serial||"",[],"SKIPPED")}if(i.listSteps){let b=this.parsePrompt(r,d[0]);return console.log(si(b)),Lt(h||i.packageName||"",i.serial||"",b,"SKIPPED","Listing")}if(i.dryRun){let b=this.parsePrompt(r,d[0]);return console.log(R.bold.cyan(`
|
|
727
|
-
\u{1F50D} [Dry Run] Validated ${b.length} test step(s) in ${e} successfully (no device interaction).`)),Lt(h||i.packageName||"",i.serial||"",b,"PASS","Validation")}if(d.length>1)console.log(R.cyan(`
|
|
728
|
-
\u{1F4CB} Loaded spec with ${d.length} data iteration(s) from ${e}`));else{let b=this.parsePrompt(r,d[0]);console.log(R.cyan(`
|
|
729
|
-
\u{1F4CB} Loaded ${b.length} test step(s) from ${e}`))}console.log(R.gray("Execution Policy: ")+R.bold.white(i.continueOnError?"Continue on Error (Modular Run)":"Fail-Fast (Default)")+R.gray(" | Screenshots: ")+R.bold.white(i.screenshotMode==="all"?"All Steps":"Failure-Only")),i.serial=await this.driver.ensureDefaultDevice(i.serial);let u=i.serial||this.driver.getDefaultDevice()||"Default Device",g=null;i.serial&&(g=Ke(i.serial)),i.embedScreenshots&&typeof this.reporter.setEmbedScreenshots=="function"&&this.reporter.setEmbedScreenshots(!0);let f,y;if(i.serve){let b=typeof i.serve=="number"?i.serve:4040;try{f=await zs({port:b,suiteName:c}),console.log(R.bold.magenta(`
|
|
730
|
-
\u{1F4E1} Live Monitor streaming at: ${f.url}
|
|
731
|
-
`)),typeof this.reporter.onStep=="function"&&(y=this.reporter.onStep(m=>{f?.broadcastStep(m)}))}catch(m){let v=m;console.warn(R.yellow(`Warning: Could not start live server: ${v.message}`))}}let S=null;i.video&&(console.log(R.cyan("\u{1F3AC} Starting ADB screen recording (--video enabled)...")),S=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(R.gray("Target Screen Geometry: ")+R.bold.cyan(`${this.screenDimensions.width}x${this.screenDimensions.height}`)+(this.navBarHeight>0?R.gray(` (Nav Bar: ${this.navBarHeight}px)`):"")),i.apkPath&&(Ce.existsSync(i.apkPath)?(console.log(R.cyan(`\u{1F4E6} Installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(B=>setTimeout(B,2e3))):console.log(R.yellow(`Warning: Specified APK file not found at: ${i.apkPath}`)));let b=i.packageName||h||(typeof this.driver.getForegroundPackage=="function"?await this.driver.getForegroundPackage(i.serial):null)||"Foreground App";if(b&&!b.includes("Launcher")&&!b.includes("Foreground")){if(!(typeof this.driver.isAppInstalled=="function"?await this.driver.isAppInstalled(b,i.serial):!0))if(i.apkPath&&Ce.existsSync(i.apkPath))console.log(R.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 "${b}" is not installed on device (${u}).
|
|
871
|
+
`),o.add(f),w.on("close",()=>{o.delete(f)});return}if(N==="/"||N==="/report"||N==="/index.html"){let g=hs(n,{suiteName:r});f.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}),f.end(g);return}if(N==="/api/report"||N==="/results.json"){f.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),f.end(JSON.stringify(n,null,2));return}let de=N.replace(/^\/+/,""),he=z.join(i,de);if(!he.startsWith(i)){f.writeHead(403,{"Content-Type":"text/plain"}),f.end("Access Denied");return}if(ee.existsSync(he)&&ee.statSync(he).isFile()){let g=z.extname(he).toLowerCase(),P=qn[g]||"application/octet-stream";f.writeHead(200,{"Content-Type":P,"Cache-Control":"no-cache"}),ee.createReadStream(he).pipe(f);return}f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not Found")});await new Promise((w,f)=>{le.once("error",f),le.listen(e,t,()=>{w()})});let Z=le.address(),_=typeof Z=="object"&&Z?Z.port:e,De=`http://${t}:${_}`;return{server:le,port:_,url:De,broadcastStep(w){n.steps.push(w),n.totalSteps=n.steps.length,w.status==="PASS"?n.passedSteps++:w.status==="FAIL"?n.failedSteps++:w.status==="WARN"?n.warnSteps++:w.status==="SKIPPED"&&n.skippedSteps++,Y("step",w)},broadcastComplete(w){n=w,Y("complete",w)},broadcastError(w){n.errorsDetected.push(w),Y("error",{error:w})},updateReport(w){n=w},async close(){if(clearInterval(c),v){try{await v.stopSession()}catch{}v=null,T=null}b&&b.status==="running"&&(b.abort.aborted=!0);for(let w of o)try{w.end()}catch{}o.clear(),await new Promise((w,f)=>{le.close(I=>{I?f(I):w()})})}}}import er from"zlib";import tr from"fs";function sr(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 ir(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 nr(a){let e=[],t=[],s=0;for(let c of a){let l=c.data,p=er.deflateRawSync(l),d=p.length<l.length,h=d?p:l,u=d?8:0,m=sr(l),y=l.length,v=h.length,{time:T,date:S}=ir(c.date),b=Buffer.from(c.name.replace(/\\/g,"/"),"utf-8"),E=Buffer.alloc(30+b.length);E.writeUInt32LE(67324752,0),E.writeUInt16LE(20,4),E.writeUInt16LE(2048,6),E.writeUInt16LE(u,8),E.writeUInt16LE(T,10),E.writeUInt16LE(S,12),E.writeUInt32LE(m,14),E.writeUInt32LE(v,18),E.writeUInt32LE(y,22),E.writeUInt16LE(b.length,26),E.writeUInt16LE(0,28),b.copy(E,30),e.push(E),e.push(h);let D=Buffer.alloc(46+b.length);D.writeUInt32LE(33639248,0),D.writeUInt16LE(20,4),D.writeUInt16LE(20,6),D.writeUInt16LE(2048,8),D.writeUInt16LE(u,10),D.writeUInt16LE(T,12),D.writeUInt16LE(S,14),D.writeUInt32LE(m,16),D.writeUInt32LE(v,20),D.writeUInt32LE(y,24),D.writeUInt16LE(b.length,28),D.writeUInt16LE(0,30),D.writeUInt16LE(0,32),D.writeUInt16LE(0,34),D.writeUInt16LE(0,36),D.writeUInt32LE(0,38),D.writeUInt32LE(s,42),b.copy(D,46),t.push(D),s+=E.length+h.length}let i=Buffer.concat(t),r=i.length,n=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(r,12),o.writeUInt32LE(n,16),o.writeUInt16LE(0,20),Buffer.concat([...e,i,o])}async function Ki(a,e){let t=nr(e);await tr.promises.writeFile(a,t)}import rr from"chalk";var ti=null;async function Qi(a,e){if(ti)return ti;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),h=(p||"").toLowerCase(),u=(d||"").toLowerCase();s=l?.trim()==="1"||h.includes("sdk")||h.includes("emulator")||u.includes("emulator")}catch{s=!1}let i=1;t?i=s?2.8:2:s?i=1.5:i=1;let r=parseFloat(process.env.PROMPTTEST_SETTLE_FACTOR||"");!isNaN(r)&&r>0&&(i=Math.max(.5,r));let n={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};ti=n;let o=s?"Android Emulator":"Physical Android Device",c=t?"CI / Cloud Runner":"Local Environment";return console.log(rr.cyan(`\u26A1 [Device Profiler] Detected ${o} in ${c} (Velocity Multiplier: ${i.toFixed(1)}x, Dynamic Timeout: ${n.defaultTimeoutMs}ms)`)),n}var Ke=class{driver;memory;reporter;checkpoints;baselines;lastHierarchy=null;screenDimensions={width:C.screen.fallbackWidth,height:C.screen.fallbackHeight};navBarHeight=0;targetPackage=void 0;constructor(e,t,s,i,r,n){this.driver=e||ke,this.memory=t||Ct,this.reporter=s||nt,this.checkpoints=i||$i,this.baselines=r||Ss,this.semanticResolver=n||Qs()}semanticResolver;healEnabled=!1;activeLocale="en";runtimeVariables=new Map;loopStack=[];expandSpecIncludes(e,t=new Set){return Ts(e,t)}async expandSpec(e,t){let s=t||this.semanticResolver,i=e.split(`
|
|
872
|
+
`),r=[],n=0;for(let o of i){let c=o.trim();if(!c||c.startsWith("#")||c.startsWith("//")){r.push(o);continue}let l=this.parsePrompt(c);if(l.length>0&&l[0].type!==void 0&&!c.toLowerCase().startsWith("intent:")){r.push(o);continue}let d=c.replace(/^intent:\s*/i,""),h=this.memory?.getIntentExpansion(d);if(h?.length){r.push(`# [Cached Intent] ${c}`,...h),n+=h.length;continue}let u=await s.resolveIntent(d);if(u?.length){r.push(`# [AI Expanded] ${c}`);let m=u.map(y=>y.originalText);r.push(...m),this.memory&&(this.memory.recordIntentExpansion(d,m),await this.memory.save().catch(()=>{})),n+=u.length}else r.push(o)}return{expanded:r.join(`
|
|
873
|
+
`),stepsAdded:n}}parsePrompt(e,t){return Nt(e,t)}async runSpec(e,t,s){if(!Ye.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=Qs({provider:"heuristic"})),this.activeLocale=(i.locale||C.locale||"en").toLowerCase(),typeof this.memory.setLocale=="function"&&this.memory.setLocale(this.activeLocale);let r=this.expandSpecIncludes(e),n=r,o=[],c=Mt.extractDataDirective(r,Ie.dirname(e));if(c)n=c.cleanedSpec,o=c.rows;else if(i.dataFile){let S=Ie.isAbsolute(i.dataFile)?i.dataFile:Ie.resolve(process.cwd(),i.dataFile);o=Mt.loadFromFile(S)}(i.onlyRow!==void 0||i.iterations!==void 0)&&(o.length>0?o=Mt.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=Ie.basename(e,Ie.extname(e)),d=n.match(/#\s*(?:Target\s*)?Package:\s*([a-zA-Z0-9._-]+)/i),h=d?d[1]:void 0;if(i.tags){let S=Ri(r),b=i.tags.split(",").map(D=>D.trim().toLowerCase()).filter(Boolean);if(!b.some(D=>S.includes(D)))return console.log(V.yellow(`
|
|
874
|
+
\u23E9 Skipping ${e}: tags [${S.join(", ")}] do not match filter [${b.join(", ")}]`)),Zt(h||i.packageName||"",i.serial||"",[],"SKIPPED")}if(i.listSteps){let S=this.parsePrompt(n,l[0]);return console.log(Oi(S)),Zt(h||i.packageName||"",i.serial||"",S,"SKIPPED","Listing")}if(i.dryRun){let S=this.parsePrompt(n,l[0]);return console.log(V.bold.cyan(`
|
|
875
|
+
\u{1F50D} [Dry Run] Validated ${S.length} test step(s) in ${e} successfully (no device interaction).`)),Zt(h||i.packageName||"",i.serial||"",S,"PASS","Validation")}if(l.length>1)console.log(V.cyan(`
|
|
876
|
+
\u{1F4CB} Loaded spec with ${l.length} data iteration(s) from ${e}`));else{let S=this.parsePrompt(n,l[0]);console.log(V.cyan(`
|
|
877
|
+
\u{1F4CB} Loaded ${S.length} test step(s) from ${e}`))}console.log(V.gray("Execution Policy: ")+V.bold.white(i.continueOnError?"Continue on Error (Modular Run)":"Fail-Fast (Default)")+V.gray(" | Screenshots: ")+V.bold.white(i.screenshotMode==="all"?"All Steps":"Failure-Only")),i.serial=await this.driver.ensureDefaultDevice(i.serial);let u=i.serial||this.driver.getDefaultDevice()||"Default Device",m=null;i.serial&&(m=yt(i.serial)),i.embedScreenshots&&typeof this.reporter.setEmbedScreenshots=="function"&&this.reporter.setEmbedScreenshots(!0);let y,v;if(i.serve){let S=typeof i.serve=="number"?i.serve:4040;try{y=await Gi({port:S,suiteName:p}),console.log(V.bold.magenta(`
|
|
878
|
+
\u{1F4E1} Live Monitor streaming at: ${y.url}
|
|
879
|
+
`)),typeof this.reporter.onStep=="function"&&(v=this.reporter.onStep(b=>{y?.broadcastStep(b)}))}catch(b){let E=b;console.warn(V.yellow(`Warning: Could not start live server: ${E.message}`))}}let T=null;i.video&&(console.log(V.cyan("\u{1F3AC} Starting ADB screen recording (--video enabled)...")),T=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(V.gray("Target Screen Geometry: ")+V.bold.cyan(`${this.screenDimensions.width}x${this.screenDimensions.height}`)+(this.navBarHeight>0?V.gray(` (Nav Bar: ${this.navBarHeight}px)`):"")),i.apkPath&&(Ye.existsSync(i.apkPath)?(console.log(V.cyan(`\u{1F4E6} Installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(M=>setTimeout(M,2e3))):console.log(V.yellow(`Warning: Specified APK file not found at: ${i.apkPath}`)));let S=i.packageName||h||(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&&Ye.existsSync(i.apkPath))console.log(V.cyan(`\u{1F4E6} Target app not found. Auto-installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(Y=>setTimeout(Y,2500));else throw new Error(`Target application "${S}" is not installed on device (${u}).
|
|
732
880
|
\u{1F4A1} Suggestions:
|
|
733
881
|
\u2022 Install the app manually or via: adb install <path-to-apk>
|
|
734
|
-
\u2022 Or provide an APK path to auto-install before running: --apk=path/to/app.apk`);let
|
|
882
|
+
\u2022 Or provide an APK path to auto-install before running: --apk=path/to/app.apk`);let J=await this.driver.getForegroundPackage(i.serial);(i.fresh||J&&J!==S)&&(console.log(V.cyan(`\u{1F680} Launching target application: ${V.bold(S)}...`)),i.fresh&&(await this.driver.forceStop(S,i.serial),await new Promise(Y=>setTimeout(Y,600))),await this.driver.launchApp(S,i.serial),await new Promise(Y=>setTimeout(Y,2500)))}i.reporter&&(this.reporter=i.reporter),i.reporters&&typeof this.reporter.setFormats=="function"&&this.reporter.setFormats(i.reporters),i.serial&&await Qi(this.driver,i.serial).catch(()=>{}),this.targetPackage=S&&!S.includes("Foreground")&&!S.includes("Launcher")?S:void 0,this.reporter.init(S,u),await this.memory.init(S),this.lastHierarchy=null;let b=Date.now(),E=0;for(let M=0;M<l.length;M++){let J=l[M],Y=l.length>1,K=i.onlyRow?`Row ${i.onlyRow}`:Y?`Row ${M+1}`:void 0,le=K?`${p} [${K}]`:p;Y&&(console.log(V.bold.magenta(`
|
|
735
883
|
======================================================
|
|
736
|
-
\u{1F504} [Data-Driven Iteration ${
|
|
737
|
-
======================================================`)),i.fresh&&
|
|
738
|
-
[Step ${
|
|
739
|
-
\u{1F6D1} Aborting dependent flow due to upstream failure at Step ${
|
|
740
|
-
\u{1F50D} Visual QA Sentinel Warnings (${
|
|
741
|
-
\u2728 PromptTest Script Execution Finished in ${
|
|
742
|
-
`)),i.json&&console.log(JSON.stringify(w,null,2)),w}finally{if(S)try{await this.driver.stopScreenRecording(S,me.join("output",`${c}-recording.mp4`),i.serial)}catch{}g&&ze(g)}}async getCleanHierarchy(e){let t=await this.driver.getUiHierarchy(e),{flat:s}=ue(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=ue(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,a=n.bounds.centerY;await this.driver.tap(o,a,e),await new Promise(d=>setTimeout(d,350)),t=await this.driver.getUiHierarchy(e),s=ue(t).flat}let r=ce(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*E.gestures.bottomNavThresholdRatio;if(e.bounds.centerY>o||e.bounds.y1>o)return!1;let d=e.bounds.y2>r,c=e.bounds.y1<Math.round(i*.04)&&e.bounds.centerY<Math.round(i*.06);return d?(await this.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.45),250,t),await new Promise(l=>setTimeout(l,200)),this.lastHierarchy=null,!0):c?(await this.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.65),250,t),await new Promise(l=>setTimeout(l,200)),this.lastHierarchy=null,!0):!1}async waitForTarget(e,t,s=3e3,i){if(this.lastHierarchy&&Date.now()-this.lastHierarchy.timestamp<E.polling.hierarchyCacheTtlMs){let a=this.matchNodes(this.lastHierarchy.flat,e,i);if(a.length>0)return{flat:this.lastHierarchy.flat,matched:a}}let n=Date.now();for(;Date.now()-n<s;){let{flat:a}=await this.getCleanHierarchy(t),d=this.matchNodes(a,e,i);if(d.length>0)return{flat:a,matched:d};await new Promise(c=>setTimeout(c,ks()))}let{flat:r}=await this.getCleanHierarchy(t),o=this.matchNodes(r,e,i);if(o.length===0&&(this.healEnabled||E.ai.selfHealing))try{let a=await this.semanticResolver.findSuggestions(e,r,{locale:this.activeLocale}),d=E.ai.confidenceThreshold||.75,c=a.find(l=>l.score>=d);if(c){let l=c.node||r.find(h=>(z(c.text,h.text)||z(c.text,h.contentDesc))&&h.bounds.width>0);if(l){console.log(R.yellow(` \u{1F4A1} [Self-Healing] Auto-healed "${e}" \u2192 "${c.text}" (${Math.round(c.score*100)}% confidence, ${c.strategy})`)),i&&(i.healedFrom=e);let h=l.text?"text":l.contentDesc?"contentDesc":"resourceId",u=this.lastHierarchy?.hash,g=Math.min(E.memory?.maxHealedConfidence??.65,c.score);this.memory.recordSuccess(i?.type||"TAP",e,c.text,h,g,e,u),o=[l]}}}catch(a){ke.warn(`Self-healing resolution failed: ${a.message}`)}return{flat:r,matched:o}}buildDiagnosticError(e,t,s){return qs(e,t,s)}async executeStep(e,t,s){let i=Gs.get(e.type);if(!i)throw new Error(`No handler registered for step type: ${e.type}`);e.target&&e.target.includes("$")&&(e.target=Xe(e.target,Object.fromEntries(this.runtimeVariables))),e.value&&e.value.includes("$")&&(e.value=Xe(e.value,Object.fromEntries(this.runtimeVariables)));let n={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,a,d)=>this.waitForTarget(r,o,a,d),matchNodes:(r,o,a)=>this.matchNodes(r,o,a),ensureInViewport:(r,o)=>this.ensureInViewport(r,o),buildDiagnosticError:(r,o,a)=>this.buildDiagnosticError(r,o,a),findTargetInputField:(r,o,a)=>this.findTargetInputField(r,o,a),upcomingSteps:s,variables:this.runtimeVariables,loopStack:this.loopStack,executeChildSteps:async(r,o)=>{for(let a=0;a<r.length;a++){let d=r[a];await this.executeStep(d,o.serial,r.slice(a+1))}}};return i.execute(e,n)}findTargetInputField(e,t,s){return Zs(e,t,s,this.memory)}matchNodes(e,t,s){return It(e,t,this.memory,this.activeLocale,s,this.lastHierarchy?.hash)}},Jn=new Ye;import P from"chalk";import ii from"fs";import Fi from"path";var je=class{testData={};dataPath;isLoaded=!1;driver;constructor(e,t){this.dataPath=e||Fi.resolve(process.cwd(),"test-data.json"),this.driver=t||he}setTestData(e){this.testData=e,this.isLoaded=!0}async ensureDataLoaded(){if(!this.isLoaded){if(ii.existsSync(this.dataPath))try{let e=await ii.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 a="4532";for(let d=0;d<12;d++)a+=Math.floor(Math.random()*10);return a}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=_e(e),r=[];if(n.length===0)return{filledFields:[],submitted:!1};let o=!1;for(let c of n){let l=c.resourceId||c.text||`input_${c.bounds.centerX}_${c.bounds.centerY}`,h=(c.text||"").trim(),u=!h||/^enter\s+/i.test(h)||/^type\s+/i.test(h)||/^e\.g\./i.test(h)||/^(email|email address|password|phone|name|search)$/i.test(h);if(!i&&!u){r.push({fieldId:l,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:h});continue}let g=this.inferValueForNode(c,e);await this.driver.tap(c.bounds.centerX,c.bounds.centerY,t),await new Promise(f=>setTimeout(f,400)),await this.driver.clearField(t,g.length+10),await new Promise(f=>setTimeout(f,200)),await this.driver.inputText(g,t),await new Promise(f=>setTimeout(f,300)),o=!0,r.push({fieldId:l,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:g})}o&&(await this.driver.pressKey(4,t),await new Promise(c=>setTimeout(c,500)));let a=!1,d;if(s){let c=e.filter(l=>!l.clickable||l.bounds.width===0?!1:Ns.some(h=>z(h,l.text)||z(h,l.contentDesc)||z(h,l.resourceId)));if(c.length>0){let l=["submit","sign in","signin","login","save","confirm","proceed","continue"];c.sort((u,g)=>{let f=(u.text||u.contentDesc||u.resourceId||"").toLowerCase(),y=(g.text||g.contentDesc||g.resourceId||"").toLowerCase(),S=l.findIndex(x=>f.includes(x)),b=l.findIndex(x=>y.includes(x)),m=S>=0?S:99,v=b>=0?b:99;return m!==v?m-v:g.bounds.centerY-u.bounds.centerY});let h=c[0];d=h.text||h.contentDesc||h.resourceId,await this.driver.tap(h.bounds.centerX,h.bounds.centerY,t),await new Promise(u=>setTimeout(u,E.settle.submitWaitMs));try{let u=await this.driver.getUiHierarchy(t),{flat:g}=ue(u),f=_e(g);a=!(f.length>0&&n.every(S=>f.some(b=>b.resourceId&&b.resourceId===S.resourceId)))}catch{a=!0}}}return{filledFields:r,submitted:a,submitButtonText:d}}},ri=new je;import H from"chalk";var Rt=class{driver;reporter;memory;formFiller;screenLedger=new Map;callStack=[];executedStepCount=0;visitedScreenHashes=new Set;devDefectsList=[];safetyHitList=[];externalSkippedList=[];constructor(e=he,t=nt,s=at){this.driver=e,this.reporter=t,this.memory=s,this.formFiller=new je(void 0,e)}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,d=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(H.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${d}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${d}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(H.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(H.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(H.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(l=>setTimeout(l,800)),i=await this.driver.getUiHierarchy(t),n=ue(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=s.includes("launcher")||s.includes("home")||s.includes("trebuchet");console.log(H.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(H.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(H.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,a=m=>s.some(v=>Math.abs(v.bounds.centerX-m.bounds.centerX)<30&&Math.abs(v.bounds.centerY-m.bounds.centerY)<30),d=_e(e);for(let m of d){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Text Input";i.push({node:m,type:"input",label:v,tested:!1})}let c=it(e);for(let m of c){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Toggle Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let l=Ge(e);for(let m of l){if(a(m)||Oe([m],n,t.width)||we([m],n,t.width,!0))continue;let v=m.text||m.contentDesc||m.resourceId||"Action Button";if(Pe(m)){this.externalSkippedList.push(v);continue}let x=m.selected!==void 0||m.checkable||/(?:tab|chip|pill|filter|segment|toggle)/i.test(`${m.resourceId} ${m.className} ${m.contentDesc}`)||/(?:today|yesterday|all|active|archived|pending|completed|present|absent)/i.test(v);i.push({node:m,type:x?"toggle":"transition",label:v,tested:!1})}let h=Os(e,n,t.width);for(let m of h){if(a(m)||we([m],n,t.width,!0)||i.some(x=>Math.abs(x.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(x.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Notification / Header Action";if(Pe(m)){this.externalSkippedList.push(v);continue}i.push({node:m,type:"transition",label:v,tested:!1})}let u=e.filter(m=>{if(!m.clickable||m.bounds.width===0)return!1;let v=`${m.text} ${m.contentDesc} ${m.resourceId}`.toLowerCase();return v.includes("now playing")||v.includes("play")||v.includes("pause")});for(let m of u){if(a(m)||i.some(x=>Math.abs(x.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(x.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Media Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let g=bt(e,t).filter(m=>!a(m)&&m.bounds.centerY>r&&m.bounds.centerY<o&&!we([m],n,t.width,!0)&&!Pe(m)),f=Us(g,2);for(let m of f){let v=m.text||m.contentDesc||m.resourceId||`Item (${m.bounds.centerX},${m.bounds.centerY})`;i.push({node:m,type:"transition",label:v,tested:!1})}let y=0,S=0,b=[];for(let m of i){let v=/\.(?:mp4|mkv|mov|webm|flv|avi)\b/i.test(m.label),x=/\.(?:mp3|wav|m4a|aac|ogg)\b/i.test(m.label);if(v){if(y++,y>1)continue}else if(x&&(S++,S>1))continue;b.push(m)}return b}async safeBacktrack(e,t,s,i,n=!0){let{flat:r}=await this.getCleanUiHierarchy(t,s),{height:o,width:a}=await this.driver.getScreenDimensions(s),d=Ne(r,{width:a,height:o});if(d===e)return!0;let c=we(r,o,a,!0);if(c&&c.bounds.width>0){console.log(H.gray(` [Backtrack] Tapping in-app back/close button "${c.text||c.contentDesc||c.className}"...`)),await this.driver.tap(c.bounds.centerX,c.bounds.centerY,s),await new Promise(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let l=await this.getCleanUiHierarchy(t,s),h=Ne(l.flat,{width:a,height:o});if(h===e||h!==d)return!0}if(i&&i.bounds.width>0){console.log(H.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(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let l=await this.getCleanUiHierarchy(t,s),h=Ne(l.flat,{width:a,height:o});if(h===e||h!==d)return!0}if(n){if(console.log(H.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(H.yellow(" \u26A0\uFE0F Backtrack via KEYCODE_BACK caused app jailbreak. Aborting branch restoration.")),!1;let h=await this.getCleanUiHierarchy(t,s),u=Ne(h.flat,{width:a,height:o});if(u===e||u!==d)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:a="strict",safetyBlacklist:d=[]}=e;console.log(H.bold.cyan(`
|
|
743
|
-
\u{1F916} PromptTest Universal State-Graph DFS Engine`)),console.log(H.gray(`Target Package: ${t}`)),console.log(H.gray(`Safety Policy: ${a.toUpperCase()}`)),console.log(H.gray(`Limits: Max Screens = ${i}, Step Budget = ${r}, Max Depth = ${n}`)),await this.driver.clearCrashLogs(s);let c=await this.driver.getScreenDimensions(s),l=await this.driver.getForegroundPackage(s);(!l||!l.includes(t))&&(console.log(H.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(S=>setTimeout(S,2500)));let{flat:h}=await this.getCleanUiHierarchy(t,s);await this.dismissSoftKeyboard(s);let u=Yt(h,c,t);console.log(H.magenta(`\u26A1 Universal Paradigm Detected: [${u.paradigm.toUpperCase()}] with ${u.roots.length} root node(s).`));let g=[],f;if(u.paradigm==="drawer"&&u.roots.length>0){f=u.roots[0];let S={...h[0]||{},text:"Home Screen / Main Hub",contentDesc:"Home Screen / Main Hub",clickable:!0,bounds:{x1:0,y1:0,x2:c.width,y2:c.height,centerX:c.width/2,centerY:c.height/2,width:c.width,height:c.height}};g.push(S),console.log(H.gray(" Opening drawer to catalog root destinations...")),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let b=await this.getCleanUiHierarchy(t,s),m=b.flat.filter(w=>{if(!w.clickable||w.bounds.width===0||w.bounds.height===0||w.bounds.width>=c.width*.95&&w.bounds.height>=c.height*.95||we([w],c.height,c.width,!0))return!1;let A=`${w.contentDesc} ${w.text}`.trim(),B=w.bounds.width>c.width*.15&&w.bounds.height>c.height*.05;return A.toLowerCase().includes("developed by")||w.bounds.centerY>c.height*.85?!1:A.length>=2||B});for(let w of m)g.some(A=>Math.abs(A.bounds.centerX-w.bounds.centerX)<30&&Math.abs(A.bounds.centerY-w.bounds.centerY)<30)||g.push(w);let v=we(b.flat,c.height,c.width,!0);v?await this.driver.tap(v.bounds.centerX,v.bounds.centerY,s):await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let x=await this.getCleanUiHierarchy(t,s);if(x.flat.some(w=>`${w.contentDesc} ${w.text}`.includes("Gallery")&&`${w.contentDesc} ${w.text}`.includes("Planner"))){let w=we(x.flat,c.height,c.width,!0);w?await this.driver.tap(w.bounds.centerX,w.bounds.centerY,s):await this.driver.tap(c.width-50,c.height/2,s),await new Promise(A=>setTimeout(A,1e3))}console.log(H.magenta(` Discovered ${g.length} destinations (1 Main Hub + ${g.length-1} Drawer destinations).`))}else u.roots.length>0?g=u.roots:g=[h[0]||{text:"Main Hub",clickable:!0}];let y=1;for(let S of g){if(this.executedStepCount>=r||this.visitedScreenHashes.size>=i)break;let b=S.text||S.contentDesc||`Root #${y}`;if(console.log(H.yellow(`
|
|
744
|
-
[Domain ${y}/${g.length}] Entering Root Tree: "${b}"...`)),u.paradigm==="bottom_tabs"||u.paradigm==="top_tabs"){let x=S.bounds.height<25?Math.max(S.bounds.y1-10,S.bounds.centerY):Math.min(S.bounds.centerY,S.bounds.y2-4);await this.driver.tap(S.bounds.centerX,x,s),this.executedStepCount++,await new Promise(D=>setTimeout(D,1200))}else u.paradigm==="drawer"&&y>1&&f&&(await this.dismissSoftKeyboard(s),console.log(H.gray(` Opening drawer to select "${b}"...`)),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(x=>setTimeout(x,1e3)),await this.driver.tap(S.bounds.centerX,S.bounds.centerY,s),this.executedStepCount++,await new Promise(x=>setTimeout(x,1500)));h=(await this.getCleanUiHierarchy(t,s)).flat,await this.dismissSoftKeyboard(s);let v=y===1?Math.max(25,Math.ceil(r*.45)):Math.max(8,Math.ceil(r*.55/Math.max(1,g.length-1)));if(await this.exploreDfsNode({packageName:t,serial:s,screenDims:c,rootNodes:u.roots,activeRootNode:S,currentDepth:0,maxDepth:n,maxScreens:i,stepBudget:r,domainStepLimit:this.executedStepCount+v,maxInteractionsPerScreen:o,safetyMode:a,safetyBlacklist:d,domainLabel:b}),u.paradigm==="drawer"&&y>1){let x=0;for(;x<4;){let D=await this.getCleanUiHierarchy(t,s),w=Oe(D.flat,c.height,c.width),A=D.flat.some(Z=>`${Z.contentDesc} ${Z.text}`.includes("Gallery")&&`${Z.contentDesc} ${Z.text}`.includes("Planner"));if(w&&!A)break;let B=we(D.flat,c.height,c.width,!0);if(B)console.log(H.gray(" [Domain Wrap-Up] Returning to Home Screen via in-app back...")),await this.driver.tap(B.bounds.centerX,B.bounds.centerY,s),await new Promise(Z=>setTimeout(Z,1e3)),x++;else break}}if(y===1&&g.length===1){let x=await this.getCleanUiHierarchy(t,s),D=Yt(x.flat,c,t);if((D.paradigm==="bottom_tabs"||D.paradigm==="top_tabs")&&D.roots.length>1){console.log(H.magenta(`
|
|
745
|
-
\u26A1 Post-Auth Navigation Discovered: [${D.paradigm.toUpperCase()}] with ${D.roots.length} root domain(s)!`)),u.paradigm=D.paradigm,u.roots=D.roots;let w=D.roots.slice(1);g.push(...w.length>0?w:D.roots)}}y++}for(let S of this.visitedScreenHashes)this.memory.markScreenCrawled(S);await this.memory.save(),console.log(H.green(`
|
|
746
|
-
\u2714 Universal DFS Traversal Complete!`)),console.log(H.cyan(` Visited Screens: ${this.visitedScreenHashes.size}`)),console.log(H.cyan(` Total Steps Executed: ${this.executedStepCount}/${r}`)),console.log(H.cyan(` Defects Triaged: ${this.devDefectsList.length}`))}async exploreDfsNode(e){let{packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,currentDepth:o,maxDepth:a,maxScreens:d,stepBudget:c,domainStepLimit:l,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:g,domainLabel:f}=e;if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d||l&&this.executedStepCount>=l)return;let{flat:y}=await this.getCleanUiHierarchy(t,s),S=ce(y),b=Ne(y,i);this.visitedScreenHashes.add(S);let m=this.screenLedger.get(b);if(m){if(m.status==="FULLY_EXPLORED"){console.log(H.gray(` \u26A1 Cycle Detected: Screen [${b.slice(0,8)}] already fully explored. Pruning branch.`));return}}else{let w=this.catalogScreen(y,i,n);m={hash:S,semanticHash:b,title:`${f} (depth ${o})`,elements:w,status:"IN_PROGRESS",depth:o,interactionCount:0},this.screenLedger.set(b,m),console.log(H.cyan(` \u{1F50E} Discovered Screen [${b.slice(0,8)}] at depth ${o} with ${w.length} candidate element(s).`))}this.callStack.push({screenHash:S,semanticHash:b,title:m.title,timestamp:Date.now()});let v=m.elements.filter(w=>w.type==="input"&&!w.tested);if(v.length>0&&m.interactionCount<h){console.log(H.magenta(` Filling in-place form fields (${v.length} inputs)...`));let w=await this.formFiller.fillAndSubmitForm(y,s,!0,!1);this.executedStepCount++,m.interactionCount++;for(let A of v)A.tested=!0;await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s),this.reporter.logStep("In-Place Form Fill",`Populated ${w.filledFields.length} field(s) on [${b.slice(0,8)}]`,"FormSubmit","PASS",w.submitButtonText||"Auto")}let x=m.elements.filter(w=>w.type==="toggle"&&!w.tested);for(let w of x){if(this.executedStepCount>=c||m.interactionCount>=h)break;if(w.tested=!0,Ee(w.node,g,u)){this.safetyHitList.push(w.label);continue}console.log(H.gray(` Exercising toggle: "${w.label.slice(0,30)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(A=>setTimeout(A,600)),this.reporter.logStep("In-Place Toggle",`Toggled control "${w.label}"`,"Tap","PASS",w.label)}let D=m.elements.filter(w=>w.type==="transition"&&!w.tested);for(let w of D){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d||l&&this.executedStepCount>=l&&!(o===0&&f.includes("Home Screen"))||m.interactionCount>=h)break;if(w.tested=!0,Pe(w.node)){this.externalSkippedList.push(w.label);continue}if(Ee(w.node,g,u)){this.safetyHitList.push(w.label);continue}console.log(H.magenta(` \u26A1 [DFS Depth ${o}] Testing transition: "${w.label.slice(0,40)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(j=>setTimeout(j,1500)),await this.dismissSoftKeyboard(s),await this.handleExternalMediaChooser(t,s),await this.packageJailGuard(t,s);let A=await this.getCleanUiHierarchy(t,s),Z=Ne(A.flat,i)!==b;if(this.reporter.logStep("DFS Transition",`Tapped "${w.label}" [${Z?"Navigated":"In-Place"}]`,"Tap","PASS",w.label),Z){if(o<a){let te=o===0&&f.includes("Home Screen")?Math.min(this.executedStepCount+3,l||this.executedStepCount+3):l;await this.exploreDfsNode({packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,domainStepLimit:te,currentDepth:o+1,maxDepth:a,maxScreens:d,stepBudget:c,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:g,domainLabel:`${f} > ${w.label.slice(0,20)}`})}console.log(H.gray(` [DFS Backtrack] Returning to [${b.slice(0,8)}]...`)),await this.safeBacktrack(b,t,s,o===0?r:void 0,o>0),await this.dismissSoftKeyboard(s);let j=await this.getCleanUiHierarchy(t,s);if(Ne(j.flat,i)!==b){let te=we(j.flat,i.height,i.width,!0);te&&(console.log(H.gray(" [Backtrack Verification] Re-tapping in-app back/close button...")),await this.driver.tap(te.bounds.centerX,te.bounds.centerY,s),await new Promise(be=>setTimeout(be,1e3)),await this.packageJailGuard(t,s));let le=await this.getCleanUiHierarchy(t,s);if(Ne(le.flat,i)!==b){console.log(H.yellow(` \u26A0\uFE0F Unable to restore parent screen [${b.slice(0,8)}]. Unwinding branch to prevent jailbreak loop.`));break}}}}m.status="FULLY_EXPLORED",this.callStack.pop()}};var ut=class{driver;formFiller;reporter;memory;safetyHitList=[];externalSkippedList=[];devDefectsList=[];visitedScreenHashes=new Set;executedStepCount=0;constructor(e,t,s,i){this.driver=e||he,this.formFiller=t||ri,this.reporter=s||nt,this.memory=i||at}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=s.includes("launcher")||s.includes("home")||s.includes("trebuchet");console.log(P.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(P.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}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,d=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(P.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${d}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${d}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(P.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(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(P.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(l=>setTimeout(l,800)),i=await this.driver.getUiHierarchy(t),n=ue(i).flat}return{xml:i,flat:n}}async handleDevOverlays(e,t,s){let i=yt(e);if(!i)return!1;let n=`[${(i.severity||"error").toUpperCase()} - ${i.type.toUpperCase()}]`,r=i.sourceLocation?` [${i.sourceLocation}]`:"";console.log(P.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(P.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(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(i.node.bounds.centerX,i.node.bounds.centerY,s)):(console.log(P.gray(" Pressing Back to dismiss error overlay...")),await this.driver.pressBack(s)),await new Promise(a=>setTimeout(a,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=E.explorer?.maxTabs||15,exploreLists:n=!0,skipAlreadyCrawled:r=!1,safetyMode:o=E.safety?.mode||"strict",safetyBlacklist:a=E.safety?.customBlacklist?[...E.safety.customBlacklist]:[],maxScreens:d=E.explorer?.maxScreens||30,stepBudget:c=E.explorer?.stepBudget||100,screenshots:l=E.explorer?.screenshots||"state-change"}=e;console.log(P.cyan(`
|
|
747
|
-
\u{1F916} PromptTest Autonomous Exploration Brain v3`)),console.log(P.gray("Target Package: ")+P.bold.white(t)),console.log(P.gray("Safety Policy: ")+P.bold.yellow(o.toUpperCase())+(a.length>0?P.gray(` (+${a.length} custom blacklist)`):"")),console.log(P.gray("Screenshots Policy: ")+P.bold.white(l));let h=async(y,S=!0)=>{if(!(l==="failure-only"&&y!=="FAIL")&&!(l==="state-change"&&!S&&y!=="FAIL"))try{return await this.driver.captureScreenshot(s)}catch{return}};await this.memory.init(t);let u=s||this.driver.getDefaultDevice(),g=u||"Default Device";this.reporter.init(t,g);let f=null;u&&(f=Ke(u)),this.safetyHitList=[],this.externalSkippedList=[],this.devDefectsList=[],this.visitedScreenHashes.clear(),this.executedStepCount=0;try{if(await this.driver.clearCrashLogs(s),(e.strategy||E.explorer?.strategy||"heuristic")==="dfs"){let ne=new Rt(this.driver,this.reporter,this.memory);await ne.explore({packageName:t,serial:s,maxScreens:d,maxDepth:e.maxDepth||E.explorer?.maxDepth||5,stepBudget:c,safetyMode:o,safetyBlacklist:a,screenshotPolicy:l,skipAlreadyCrawled:r}),this.safetyHitList=ne.safetyHitList,this.externalSkippedList=ne.externalSkippedList,this.devDefectsList=ne.devDefectsList,this.visitedScreenHashes=ne.visitedScreenHashes,this.executedStepCount=ne.executedStepCount;let J=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${J.totalScreens} crawled screen(s).`,"Verify","PASS"),await this.reporter.generateReport(),console.log(P.bold.green(`
|
|
748
|
-
\u2728 Full Audit Report generated at: output/prompttest-report.md`));return}let{width:S,height:b}=await this.driver.getScreenDimensions(s);console.log(P.yellow(`
|
|
749
|
-
[1/5] Verifying Foreground State...`));let m=await this.driver.getForegroundPackage(s);(!m||!m.includes(t))&&(console.log(P.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2500)));let v=await this.runErrorSentinel(t,s,"Post-Launch"),x=v.hasError?"FAIL":"PASS",D=await h(x,!0);this.reporter.logStep("Init",`Launched and verified foreground for ${t}`,"Launch",x,t,D,v.hasError?{errors:v.errors}:void 0),console.log(x==="PASS"?P.green("\u2714 App is active in foreground."):P.red(`\u2716 Issues detected during launch for ${t}.`)),console.log(P.yellow(`
|
|
750
|
-
[2/5] Inspecting UI Hierarchy for Forms...`));let{xml:w,flat:A}=await this.getCleanUiHierarchy(t,s),B=ce(A);if(this.visitedScreenHashes.add(B),this.memory.isScreenCrawled(B)&&r)console.log(P.cyan(` \u26A1 Fast-Forward: Screen [${B.slice(0,8)}] was previously crawled offline. Skipping redundant element interactions.`)),this.reporter.logStep("Fast Forward",`Fast-forwarded past previously crawled screen [${B.slice(0,8)}] (Memory Engine)`,"Skip","PASS");else{let ne=_e(A);if(ne.length>0){console.log(P.magenta(`\u26A1 Detected ${ne.length} form field(s)! Engaging Semantic Form Filler...`));for(let L of ne)console.log(P.gray(` - Field: "${L.text||L.contentDesc||L.resourceId}"`));let C=await this.formFiller.fillAndSubmitForm(A,s,!0,!1);this.executedStepCount++,await new Promise(L=>setTimeout(L,1500)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat,this.visitedScreenHashes.add(ce(A));let I=await this.runErrorSentinel(t,s,"Post-Form-Submit"),F=_e(A),T=I.hasError||F.length===ne.length&&I.errors.length>0?"FAIL":"PASS",k=await h(T,!0),_=C.filledFields.map(L=>`${L.fieldLabel} -> "${L.valueEntered}"`).join(", ");this.reporter.logStep("Form Fill",`Filled ${C.filledFields.length} field(s) [${_}] and submitted via "${C.submitButtonText||"Auto"}"`,"FormSubmit",T,C.submitButtonText,k,I.hasError?{errors:I.errors}:void 0),console.log(T==="PASS"?P.green("\u2714 Form populated and submitted successfully!"):P.red("\u2716 Form submission triggered an error or remained unauthenticated."))}else console.log(P.gray("No form input fields detected on initial screen."));console.log(P.yellow(`
|
|
751
|
-
[3/5] Inspecting Interactive Action Controls...`));let J=Ge(A).filter(C=>{let M=(C.text+" "+C.contentDesc).toLowerCase();if(M.includes("submit")||M.includes("cancel")||Oe([C],b))return!1;if(Pe(C)){let I=C.text||C.contentDesc||C.resourceId||"External Link";return console.log(P.gray(` \u{1F517} External Link Bypassed: "${I}"`)),this.externalSkippedList.push(I),!1}if(Ee(C,a,o)){let I=C.text||C.contentDesc||C.resourceId||"Action";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive action "${I}"`)),this.safetyHitList.push(I),!1}return!0});if(J.length>0){let C=J[0],M=C.text||C.contentDesc||C.resourceId;console.log(P.magenta(`\u26A1 Found action button: "${M}". Testing interaction...`));let I=ce(A);this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1200)),await this.packageJailGuard(t,s);let F=await this.getCleanUiHierarchy(t,s);w=F.xml,A=F.flat;let K=ce(A);this.visitedScreenHashes.add(K);let T=await this.runErrorSentinel(t,s,"Post-Action-Tap"),k=I!==K,_="PASS",L="";T.hasError?(_="FAIL",L="Action triggered error or crash"):k?(_="PASS",L="Screen transitioned successfully"):(_="WARN",L="No visible screen transition or state change observed (No-Op)",console.log(P.yellow(` \u26A0\uFE0F Outcome Warning: Action "${M}" produced no UI state change.`)));let oe=await h(_,k);this.reporter.logStep("Action Testing",`Tapped action button "${M}" [${L}]`,"Tap",_,M,oe,T.hasError?{errors:T.errors}:void 0),console.log(_==="PASS"?P.green(`\u2714 Action interaction complete (${L}).`):_==="WARN"?P.yellow(`\u2714 Action interaction recorded with warning (${L}).`):P.red("\u2716 Action interaction triggered an error.")),_!=="FAIL"&&(this.memory.recordSuccess("TAP",M,C.resourceId||C.text||C.contentDesc||M,"text",1,void 0,I),this.memory.markScreenCrawled(I,[M]))}else console.log(P.gray("No standalone action buttons to test."));let N=it(A).filter(C=>!Ee(C,a,o));if(N.length>0){console.log(P.yellow(`
|
|
752
|
-
[3b/5] Inspecting Toggle & Checkable Controls...`));let C=N[0],M=C.text||C.contentDesc||C.resourceId||"Switch/Checkbox",I=C.checked;console.log(P.magenta(`\u26A1 Found toggle: "${M}" (checked: ${I}). Testing toggle interaction...`)),this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1e3)),w=await this.driver.getUiHierarchy(s),A=ue(w).flat;let F=ce(A);this.visitedScreenHashes.add(F);let T=it(A).find(ee=>Math.abs(ee.bounds.centerX-C.bounds.centerX)<25&&Math.abs(ee.bounds.centerY-C.bounds.centerY)<25),k=T?T.checked!==I:!0,_=await this.runErrorSentinel(t,s,"Post-Toggle"),L=_.hasError?"FAIL":k?"PASS":"WARN",oe=await h(L,k);this.reporter.logStep("Toggle Testing",`Toggled "${M}" (Checked: ${I} -> ${T?T.checked:"flipped"})`,"Toggle",L,M,oe,_.hasError?{errors:_.errors}:void 0),console.log(L==="PASS"?P.green("\u2714 Toggle control flipped successfully!"):L==="WARN"?P.yellow("\u26A0\uFE0F Toggle tapped but checked state did not flip."):P.red("\u2716 Toggle control triggered an error.")),L!=="FAIL"&&this.memory.markScreenCrawled(F,[M])}let Q=Oe(A,b);if(Q&&!Ee(Q,a,o)){let C=Q.contentDesc||Q.text||Q.resourceId||"Drawer Menu";console.log(P.yellow(`
|
|
753
|
-
[3c/5] Inspecting Side Navigation Drawer...`)),console.log(P.magenta(`\u26A1 Found drawer trigger: "${C}". Opening side drawer...`));let M=ce(A);this.executedStepCount++,await this.driver.tap(Q.bounds.centerX,Q.bounds.centerY,s),await new Promise(L=>setTimeout(L,1200)),await this.packageJailGuard(t,s);let I=await this.getCleanUiHierarchy(t,s);w=I.xml,A=I.flat;let F=ce(A);this.visitedScreenHashes.add(F);let K=M!==F,T=await this.runErrorSentinel(t,s,"Drawer-Open"),k=T.hasError?"FAIL":K?"PASS":"WARN",_=await h(k,K);if(this.reporter.logStep("Drawer Navigation",`Opened side drawer via "${C}"`,"Tap",k,C,_,T.hasError?{errors:T.errors}:void 0),k==="PASS"){console.log(P.green("\u2714 Side drawer opened successfully!"));let L=Ge(A).filter(ee=>!Ee(ee,a,o)&&!Pe(ee)&&ee.bounds.centerY>Q.bounds.y2);if(L.length>0){let ee=L[0],fe=ee.text||ee.contentDesc||ee.resourceId||"Drawer Item";console.log(P.gray(` - Testing drawer item: "${fe}"...`)),this.executedStepCount++,await this.driver.tap(ee.bounds.centerX,ee.bounds.centerY,s),await new Promise(q=>setTimeout(q,1200)),await this.packageJailGuard(t,s);let Ie=await this.getCleanUiHierarchy(t,s);w=Ie.xml,A=Ie.flat,this.visitedScreenHashes.add(ce(A))}console.log(P.gray(" Closing side drawer to restore main view...")),await this.driver.pressBack(s),await new Promise(ee=>setTimeout(ee,1e3));let oe=await this.getCleanUiHierarchy(t,s);w=oe.xml,A=oe.flat,this.visitedScreenHashes.add(ce(A)),console.log(P.green("\u2714 Main view restored from side drawer."))}else k==="WARN"&&console.log(P.yellow("\u26A0\uFE0F Drawer button tapped but no visible screen change occurred."));k!=="FAIL"&&this.memory.markScreenCrawled(M,[C])}if(n){console.log(P.yellow(`
|
|
754
|
-
[4/5] Inspecting Lists & Master-Detail Flows...`));let C=Bs(A);if(C.length>0){console.log(P.magenta(`\u26A1 Found ${C.length} scrollable container(s). Performing vertical scroll exploration...`));let I=ce(A),F=Math.round(S*.5);await this.driver.swipe(F,Math.round(b*.7),F,Math.round(b*.3),300,s),await new Promise(L=>setTimeout(L,1200));let K=await this.getCleanUiHierarchy(t,s);w=K.xml,A=K.flat;let T=ce(A);this.visitedScreenHashes.add(T);let k=I!==T,_=await h("PASS",k);this.reporter.logStep("Scroll Exploration",k?"Scrolled vertically to discover off-screen elements":"Scrolled but content remained at edge","Swipe","PASS","SwipeUp",_),k&&console.log(P.green("\u2714 Vertical scroll succeeded; discovered off-screen content below fold."))}let M=bt(A).filter(I=>{if(Pe(I)){let F=I.text||I.contentDesc||"External Link";return this.externalSkippedList.push(F),!1}if(Ee(I,a,o)){let F=I.text||I.contentDesc||"List Item";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive list item "${F}"`)),this.safetyHitList.push(F),!1}return!0});if(M.length>0){let I=M[0],F=I.text||I.contentDesc||`Item at (${I.bounds.centerX}, ${I.bounds.centerY})`;console.log(P.magenta(`\u26A1 Found list item: "${F}". Diving into detail view...`));let K=ce(A);await this.driver.tap(I.bounds.centerX,I.bounds.centerY,s),await new Promise(Ae=>setTimeout(Ae,1800));let T=await this.getCleanUiHierarchy(t,s);w=T.xml,A=T.flat;let k=ce(A);this.visitedScreenHashes.add(k);let _=await this.runErrorSentinel(t,s,"Detail-View"),L=K!==k,oe=_.hasError?"FAIL":L?"PASS":"WARN",ee=await h(oe,L);this.reporter.logStep("List Dive",`Dived into detail view for "${F}" [${L?"Navigated":"Unchanged"}]`,"Tap",oe,F,ee,_.hasError?{errors:_.errors}:void 0),console.log(oe==="PASS"?P.green("\u2714 Detail screen loaded."):oe==="WARN"?P.yellow("\u26A0\uFE0F Detail view tapped but no navigation detected."):P.red("\u2716 Detail view triggered an error."));let fe=we(T.flat,E.screen.fallbackHeight,E.screen.fallbackWidth,!0);fe&&fe.bounds.width>0?(console.log(P.gray(`Navigating back via in-app back button "${fe.text||fe.contentDesc||fe.className}"...`)),await this.driver.tap(fe.bounds.centerX,fe.bounds.centerY,s)):(console.log(P.gray("Navigating back to main view...")),await this.driver.pressKey(4,s)),await new Promise(Ae=>setTimeout(Ae,1200));let Ie=await this.driver.getForegroundPackage(s);Ie&&!Ie.includes(t)&&(console.log(P.yellow(`Restoring ${t} foreground after back navigation...`)),await this.driver.launchApp(t,s),await new Promise(Ae=>setTimeout(Ae,2e3)));let q=await this.getCleanUiHierarchy(t,s);w=q.xml,A=q.flat,this.visitedScreenHashes.add(ce(A));let pe=await this.runErrorSentinel(t,s,"Post-Back-Restore"),Me=pe.hasError?"FAIL":"PASS",Tt=await h(Me,!0);this.reporter.logStep("List Dive","Navigated back to master screen","Back",Me,"KEYCODE_BACK",Tt,pe.hasError?{errors:pe.errors}:void 0),Me==="PASS"&&console.log(P.green("\u2714 Master view restored."))}else console.log(P.gray("No list items found for master-detail exploration."))}}console.log(P.yellow(`
|
|
755
|
-
[5/5] Inspecting Navigation Tabs...`));let j=await this.driver.getForegroundPackage(s);j&&!j.includes(t)&&(console.log(P.gray(`Restoring ${t} foreground for tab traversal...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2e3))),await this.dismissSoftKeyboard(s);let Te=await this.getCleanUiHierarchy(t,s);w=Te.xml,A=Te.flat;let te=Ut(A,void 0,t);if(te.length>1){console.log(P.magenta(`\u26A1 Found ${te.length} navigation tab(s). Traversal sequence initiated...`));let ne=te.slice(0,i),J=1;for(let N of ne){let Q=N.text||N.contentDesc||`Tab #${J}`;console.log(P.gray(` - Visiting ${Q}...`)),await this.dismissSoftKeyboard(s);let C=Math.min(N.bounds.centerY,N.bounds.y2-4);this.executedStepCount++,await this.driver.tap(N.bounds.centerX,C,s),await new Promise(k=>setTimeout(k,1500)),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat;let I=ce(A);this.visitedScreenHashes.add(I),this.memory.markScreenCrawled(I,[Q]);let F=await this.runErrorSentinel(t,s,`Tab-${Q}`),K=F.hasError?"FAIL":"PASS",T=await h(K,!0);if(this.reporter.logStep("Tab Traversal",`Navigated to tab "${Q}"`,"Tap",K,Q,T,F.hasError?{errors:F.errors}:void 0),console.log(K==="PASS"?P.green(` \u2714 Tab "${Q}" loaded cleanly.`):P.red(` \u2716 Tab "${Q}" triggered errors.`)),this.executedStepCount<c&&this.visitedScreenHashes.size<d){let k=[],_=b*.08,L=b*.88,oe=q=>q.bounds.centerY>_&&q.bounds.centerY<L&&q.clickable&&q.bounds.width>30&&q.bounds.height>20&&te.every(pe=>Math.abs(pe.bounds.centerX-q.bounds.centerX)>40||Math.abs(pe.bounds.centerY-q.bounds.centerY)>40),ee=bt(A,{width:S,height:b}).filter(oe);for(let q of ee.slice(0,3))k.push({node:q,type:"list"});let fe=Ge(A).filter(q=>!(!oe(q)||Oe([q],b)));for(let q of fe.slice(0,4))k.push({node:q,type:"button"});let Ie=it(A).filter(oe);for(let q of Ie.slice(0,2))k.push({node:q,type:"toggle"});for(let q of k){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d)break;let pe=q.node;if(Pe(pe)){this.externalSkippedList.push(pe.text||pe.contentDesc||"External Link");continue}if(Ee(pe,a,o)){let Ze=pe.text||pe.contentDesc||"Destructive Action";this.safetyHitList.push(Ze);continue}let Me=pe.text||pe.contentDesc||pe.resourceId||`${q.type} element`;console.log(P.gray(` Sub-crawl [${Q}]: Exercising ${q.type} "${Me.slice(0,40)}"...`)),this.executedStepCount++,await this.driver.tap(pe.bounds.centerX,pe.bounds.centerY,s),await new Promise(Ze=>setTimeout(Ze,1200)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let Tt=await this.getCleanUiHierarchy(t,s);w=Tt.xml,A=Tt.flat;let Ae=ce(A),hi=!this.visitedScreenHashes.has(Ae);this.visitedScreenHashes.add(Ae);let Mt=await this.runErrorSentinel(t,s,`Sub-${Me.slice(0,30)}`),As=Mt.hasError?"FAIL":"PASS",gi=await h(As,hi);if(this.reporter.logStep("Tab Sub-Crawl",`Tested ${q.type} "${Me}" under tab "${Q}"`,"Tap",As,Me,gi,Mt.hasError?{errors:Mt.errors}:void 0),Ae!==I){console.log(P.cyan(` \u{1F50E} Screen transitioned. Discovered new screen state [${Ae.slice(0,8)}]`));let Ze=Ge(A).filter($e=>oe($e)&&!Ee($e,a,o)&&!Pe($e));if(Ze.length>0&&this.executedStepCount<c){let $e=Ze[0],mi=$e.text||$e.contentDesc||"Child Action";console.log(P.gray(` Exercising child action "${mi.slice(0,30)}"...`)),this.executedStepCount++,await this.driver.tap($e.bounds.centerX,$e.bounds.centerY,s),await new Promise(fi=>setTimeout(fi,1e3)),await this.dismissSoftKeyboard(s)}console.log(P.gray(` Restoring ${Q} master view via Back...`)),await this.driver.pressBack(s),await new Promise($e=>setTimeout($e,1e3)),await this.dismissSoftKeyboard(s);let $s=await this.getCleanUiHierarchy(t,s);w=$s.xml,A=$s.flat}}}J++}console.log(P.green("\u2714 Navigation tabs traversed successfully!"))}else console.log(P.gray("Single-screen or tabs not detected at screen footer."));for(let ne of this.visitedScreenHashes)this.memory.markScreenCrawled(ne);await this.memory.save();let le=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${le.crawledScreens} crawled screen(s).`,"Verify","PASS"),await this.runErrorSentinel(t,s,"Final-State");let U=await this.reporter.generateReport(),be=U.failedSteps===0&&U.errorsDetected.length===0;console.log(be?P.bold.green(`
|
|
756
|
-
\u2728 PromptTest Exploration Complete \u2014 All Steps Passed!`):P.bold.red(`
|
|
757
|
-
\u26A0\uFE0F PromptTest Exploration Complete \u2014 Issues Detected!`)),console.log(P.white(`Summary: ${U.passedSteps} passed, ${U.warnSteps} warnings, ${U.failedSteps} failed, ${U.errorsDetected.length} errors detected.`)),this.safetyHitList.length>0&&console.log(P.cyan(`\u{1F6E1}\uFE0F Safety Shield: Blocked ${this.safetyHitList.length} destructive action(s) [${this.safetyHitList.join(", ")}].`)),console.log(P.cyan(`\u{1F5FA}\uFE0F State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s).`)),console.log(P.cyan(`\u{1F9E0} Memory Engine Coverage: ${le.crawledScreens} crawled screen(s) indexed offline.`)),console.log(P.cyan(`Full Audit Report generated at: output/prompttest-report.md
|
|
758
|
-
`))}finally{f&&ze(f)}}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 d=`Crash in ${s}: ${n.slice(0,300)}`;console.log(P.bold.red(`\u{1F6A8} FATAL EXCEPTION DETECTED in ${e} [${s}]!`)),this.reporter.logError(d),i.push(d)}let{flat:o}=ue(r),a=_s(o);if(a.length>0)for(let d of a){let c=d.text||d.contentDesc,l=`UI Error dialog in ${s}: "${c}"`;console.log(P.bold.yellow(`\u26A0\uFE0F Error Dialog/Banner on screen [${s}]: "${c}"`)),this.reporter.logError(l),i.push(l)}}catch{}return{hasError:i.length>0,errors:i}}},No=new ut;import de from"fs";import re from"path";import $ from"chalk";import{spawn as _i}from"child_process";import ni from"readline";import{createRequire as Oi}from"module";var Bi=Oi(import.meta.url),Es="1.1.0";try{Es=Bi("../../package.json").version||"1.1.0"}catch{}var pt=class{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=E.screen.fallbackWidth;touchMaxY=E.screen.fallbackHeight;displayWidth=E.screen.fallbackWidth;displayHeight=E.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||he}flushToDisk(){if(this.resolvedOutputPath)try{this.saveSpec(this.resolvedOutputPath)}catch{}if(this.resolvedReportPath)try{this.saveReport(this.resolvedReportPath)}catch{}}appendStep(e,t){this.recordedSteps[this.recordedSteps.length-1]!==e&&(this.recordedSteps.push(e),this.flushToDisk(),t&&console.log(t))}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 startRecording(e,t,s){let i=await this.driver.ensureDefaultDevice(t);if(!i)throw new Error("No Android device connected for recording.");this.deviceLock=Ke(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 v=await this.driver.getForegroundPackage(i);v&&(this.targetPackage=v)}catch{}let n=this.extractBrandSlug(this.targetPackage),r;if(e&&e!=="specs/recorded_suite.txt")r=re.resolve(e);else{let v=`${n}_flow`,x=re.resolve(`specs/${v}.txt`);if(!this.isAppendMode&&de.existsSync(x)){let D=1;for(x=re.resolve(`specs/${v}_${D}.txt`);de.existsSync(x);)D++,x=re.resolve(`specs/${v}_${D}.txt`)}r=x}if(this.resolvedOutputPath=r,de.existsSync(r))if(this.isAppendMode){let v=de.readFileSync(r,"utf-8"),x=v.split(`
|
|
759
|
-
`);for(let w of x){let A=w.trim();if(/^\d+\.\s+/.test(A))this.existingSteps.push(A.replace(/^\d+\.\s+/,""));else if(A.startsWith("# Package:")){let B=A.match(/# Package:\s*([a-zA-Z0-9._]+)/);B&&(this.targetPackage=B[1])}}let D=`${r}.bak`;de.writeFileSync(D,v,"utf-8"),console.log($.cyan(`\u{1F4E5} Loaded ${this.existingSteps.length} existing step(s) from: ${re.basename(r)}`)),console.log($.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(D)}`))}else{let v=de.readFileSync(r,"utf-8"),x=`${r}.bak`;de.writeFileSync(x,v,"utf-8"),console.log($.yellow(`\u26A0\uFE0F File "${re.basename(r)}" already exists.`)),console.log($.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(x)}`))}await this.driver.wakeDevice(i).catch(()=>{});let a=await this.driver.getScreenDimensions(i);this.displayWidth=a.width||E.screen.fallbackWidth,this.displayHeight=a.height||E.screen.fallbackHeight,this.touchMaxX=this.displayWidth,this.touchMaxY=this.displayHeight;try{let{stdout:v}=await this.driver.execAdb(["shell","getevent","-p"],i),x=v.match(/0035\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/),D=v.match(/0036\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/);x&&parseInt(x[1])>0&&(this.touchMaxX=parseInt(x[1])),D&&parseInt(D[1])>0&&(this.touchMaxY=parseInt(D[1]))}catch{}this.sessionStartTime=Date.now(),this.sessionScreenSections=[],this.screenshotCounter=0,this.crashDetected=!1,this.hierarchyStale=!0,this.currentScreenName="";let d=re.basename(r,".txt"),c=re.resolve("output");this.screenshotDir=re.join(c,"screenshots",d),de.existsSync(this.screenshotDir)||de.mkdirSync(this.screenshotDir,{recursive:!0});let l=$.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"),h=await this.driver.getDeviceModel(i).catch(()=>i);console.log(`
|
|
760
|
-
${l}`),console.log($.bold.cyan(`\u26A1 PromptTest v${Es}`)+$.gray(" | Recording Session")),console.log(l),console.log(` ${$.gray("\u{1F4F1} Device ")} ${$.white(h)} ${$.gray(`(${i})`)}`),console.log(` ${$.gray("\u{1F4E6} App ")} ${$.green(this.targetPackage||"Unknown")}`),console.log(` ${$.gray("\u{1F3AF} Spec ")} ${$.yellow(re.basename(r))}`);let u=re.join(c,`${d}_report.md`);this.resolvedReportPath=u,console.log(` ${$.gray("\u{1F4CA} Report ")} ${$.yellow(re.basename(u))}`),console.log(` ${$.gray("\u{1F4F8} Photos ")} ${$.yellow(re.relative(process.cwd(),this.screenshotDir))}`),this.isAppendMode&&this.existingSteps.length>0&&console.log(` ${$.gray("\u{1F4CE} Mode ")} ${$.magenta(`Append \u2014 resuming from step #${this.existingSteps.length+1}`)}`),console.log(l),process.stdout.write(` ${$.gray("Checking device health...")} `),console.log($.green("\u2714 Ready")),process.stdout.write(` ${$.gray("Loading initial screen...")} `);let g=Date.now();await this.refreshHierarchySync();let f=Date.now()-g,y=this.currentScreenName?$.bold.white(this.currentScreenName):$.gray("Unknown");console.log(`${$.green("\u2714")} ${y} ${$.gray(`[${f}ms]`)}`),process.stdout.write(` ${$.gray("Starting screen watcher...")} `),this.startLogcatScreenWatcher(i),this.startLogcatCrashWatcher(i),console.log($.green("\u2714 Streaming")),console.log(l),console.log(` ${$.gray("Use the app naturally. Every action is captured.")}`),console.log(` ${$.gray('Press Ctrl+C or type "exit" / "q" + Enter to stop and save.')}`),console.log(`${l}
|
|
761
|
-
`),this.flushToDisk();let S=null,b=()=>{if(this.isRecording=!1,S)try{S.close()}catch{}if(this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),this.deviceLock&&(ze(this.deviceLock),this.deviceLock=null),this.geteventProcess)try{this.geteventProcess.kill()}catch{}if(this.logcatEventProcess)try{this.logcatEventProcess.kill()}catch{}if(this.logcatCrashProcess)try{this.logcatCrashProcess.kill()}catch{}this.flushToDisk(),this.printExitSummary(l),process.exit(0)};if(process.once("SIGINT",b),process.once("SIGTERM",b),process.stdin.isTTY)try{S=ni.createInterface({input:process.stdin,output:process.stdout}),S.on("line",v=>{let x=v.trim().toLowerCase();(x==="exit"||x==="quit"||x==="q"||x==="stop")&&b()}),S.on("SIGINT",()=>{b()})}catch{}this.startEventStream(i);let m=0;for(;this.isRecording;)if(await new Promise(v=>setTimeout(v,1500)),m++,m%20===0&&this.driver.wakeDevice(i).catch(()=>{}),!this.targetPackage){let v=await this.driver.getForegroundPackage(i).catch(()=>null);v&&(this.targetPackage=v)}}startEventStream(e){let s=_i("adb",e?["-s",e,"shell","getevent","-l"]:["shell","getevent","-l"]);this.geteventProcess=s;let i=null,n=null,r=null,o=null,a=0;ni.createInterface({input:s.stdout}).on("line",c=>{if(this.isRecording)if(c.includes("ABS_MT_POSITION_X")){let l=c.match(/ABS_MT_POSITION_X\s+([0-9a-fA-F]+)/);l&&(i=parseInt(l[1],16))}else if(c.includes("ABS_MT_POSITION_Y")){let l=c.match(/ABS_MT_POSITION_Y\s+([0-9a-fA-F]+)/);l&&(n=parseInt(l[1],16))}else if(c.includes("BTN_TOUCH")&&c.includes("DOWN"))r=i,o=n,a=Date.now();else if(c.includes("BTN_TOUCH")&&c.includes("UP")){let l=i!==null?i:r,h=n!==null?n:o,u=Date.now()-a;if(l!==null&&h!==null&&r!==null&&o!==null){let g=Math.round(r/this.touchMaxX*this.displayWidth),f=Math.round(o/this.touchMaxY*this.displayHeight),y=Math.round(l/this.touchMaxX*this.displayWidth),S=Math.round(h/this.touchMaxY*this.displayHeight),b=y-g,m=S-f,v=Math.abs(b),x=Math.abs(m),D=Math.hypot(v,x);if(this.activeInput&&f>this.displayHeight*.58&&S>this.displayHeight*.58){u>=20&&u<400&&D<45&&y>=this.displayWidth*.78&&S>=this.displayHeight*.84?this.flushActiveInput().then(()=>{this.handleKeyPress("Enter")}).catch(()=>{}):this.scheduleInputDebounce(),i=null,n=null,r=null,o=null;return}if(u>=20&&u<400&&D<45)this.isRefreshingHierarchy?this.inFlightTapQueue.push({x:y,y:S,timestamp:Date.now()}):this.handleTapAt(y,S);else if(u>=450&&D<45)this.handleLongPressAt(y,S);else if(x>=100&&x>1.4*v){let w=m<0?"down":"up";this.handleScroll(w)}else if(v>=100&&v>1.4*x){let w=b<0?"left":"right";this.handleSwipe(w)}}i=null,n=null,r=null,o=null}else c.includes("KEY_ENTER")&&c.includes("DOWN")?this.handleKeyPress("Enter"):c.includes("KEY_BACK")&&c.includes("DOWN")&&this.handleKeyPress("Back")}),s.on("close",c=>{this.isRecording&&(console.warn($.yellow(`
|
|
762
|
-
\u26A0\uFE0F [EventStream] ADB event listener stream closed (code ${c}). Auto-reconnecting in 800ms...`)),setTimeout(()=>{this.isRecording&&this.startEventStream(e)},800))}),s.on("error",c=>{this.isRecording&&console.warn($.yellow(`
|
|
763
|
-
\u26A0\uFE0F [EventStream] ADB stream error: ${c.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,$.blue(` \u{1F4DC} Recorded Scroll [Step #${this.getCurrentStepNumber()}]: ${$.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,$.blue(` \u{1F449} Recorded Swipe [Step #${this.getCurrentStepNumber()}]: ${$.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 a=(r.bounds.x2-r.bounds.x1)*(r.bounds.y2-r.bounds.y1),d=(o.bounds.x2-o.bounds.x1)*(o.bounds.y2-o.bounds.y1);return a-d});let i=s[0],n=this.resolveActionLabel(i,s,this.lastHierarchyFlat);if(n){let r=`Long press '${n}'`;this.appendStep(r,$.cyan(` \u23F1\uFE0F Recorded Long Press [Step #${this.getCurrentStepNumber()}]: ${$.bold(r)}`)),this.triggerAsyncHierarchyRefresh()}}handleTapAt(e,t){let s=Date.now(),i=this.lastHierarchyFlat.filter(l=>e>=l.bounds.x1&&e<=l.bounds.x2&&t>=l.bounds.y1&&t<=l.bounds.y2),r=this.lastHierarchyFlat.filter(l=>{let h=l.bounds.height;return h>0&&h<320&&l.bounds.width>0&&(l.clickable||l.contentDesc||l.text)}).filter(l=>t>=l.bounds.y1-30&&t<=l.bounds.y2+40);if(r.length>=2){let l=r.find(h=>e>=h.bounds.x1-20&&e<=h.bounds.x2+20);l&&(i=[this.lastHierarchyFlat.find(u=>(this.cleanLabel(u.text).length>0||this.cleanLabel(u.contentDesc).length>0)&&Math.abs(u.bounds.centerX-l.bounds.centerX)<l.bounds.width*.48&&Math.abs(u.bounds.centerY-l.bounds.centerY)<l.bounds.height*.48&&!this.isIconGlyph(this.cleanLabel(u.text)))||l])}if(t>this.displayHeight*.82){let h=this.lastHierarchyFlat.filter(u=>{let g=u.bounds.y1>=this.displayHeight*.78||u.bounds.y2>=this.displayHeight*.82,f=u.bounds.width>0&&u.bounds.width<=this.displayWidth*.52;return g&&f}).find(u=>e>=u.bounds.x1-20&&e<=u.bounds.x2+20);if(h){let u=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)));u?i=[u]:(this.cleanLabel(h.text)||this.cleanLabel(h.contentDesc))&&(i=[h])}}if(i.length===0){let l=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"))),h=null,u=70;for(let g of l){let f=Math.hypot(g.bounds.centerX-e,g.bounds.centerY-t);f<u&&(u=f,h=g)}if(h)i=[h];else{this.triggerAsyncHierarchyRefresh();return}}i.sort((l,h)=>{let u=(l.bounds.x2-l.bounds.x1)*(l.bounds.y2-l.bounds.y1),g=(h.bounds.x2-h.bounds.x1)*(h.bounds.y2-h.bounds.y1);return u-g});let o=i[0],a=i.find(l=>l.className.includes("EditText"))||(o.className.includes("EditText")?o:null);if(a){this.activeInput&&this.activeInput.node!==a&&this.flushActiveInput().catch(()=>{});let l=this.resolveFieldLabel(a,this.lastHierarchyFlat);this.activeInput={node:a,label:l,startText:a.text||""},this.triggerAsyncHierarchyRefresh();return}this.activeInput&&this.flushActiveInput().catch(()=>{});let d=this.resolveActionLabel(o,i,this.lastHierarchyFlat);if(!d||d.length===0){this.triggerAsyncHierarchyRefresh();return}if(!o.clickable&&!i.some(l=>l.clickable||l.className.includes("Button"))&&/^\d+%$|^\d+$/.test(d)){this.triggerAsyncHierarchyRefresh();return}if(d===this.lastRecordedTapTarget&&s-this.lastTapTimestamp<350)return;this.lastTapTimestamp=s,this.lastRecordedTapTarget=d;let c;if(o.checkable||o.className.includes("Switch")||o.className.includes("CheckBox")){let l=o.checked!==void 0?!o.checked:!0;c=`Toggle '${d}' to ${l?"on":"off"}`}else{c=`Tap '${d}'`;let l=this.lastHierarchyFlat.filter(u=>this.cleanLabel(u.text)===d||this.cleanLabel(u.contentDesc)===d),h=[];for(let u of l)h.some(f=>Math.hypot(f.bounds.centerX-u.bounds.centerX,f.bounds.centerY-u.bounds.centerY)<40)||h.push(u);if(h.length>1){let g=this.lastHierarchyFlat.filter(f=>f!==o&&Math.abs(f.bounds.centerY-o.bounds.centerY)<140&&Math.abs(f.bounds.centerX-o.bounds.centerX)<550).find(f=>{let y=this.cleanLabel(f.text)||this.cleanLabel(f.contentDesc);return y.length>2&&y!==d&&!/^\d+$/.test(y)&&!this.isIconGlyph(y)});if(g){let f=this.cleanLabel(g.text)||this.cleanLabel(g.contentDesc);f&&f!==d&&(c=`Tap '${d}' next to '${f}'`)}}}this.appendStep(c,$.cyan(` \u{1F446} Recorded Tap [Step #${this.getCurrentStepNumber()}]: ${$.bold(c)}`)),this.triggerAsyncHierarchyRefresh()}handleKeyPress(e){if(this.activeInput&&this.flushActiveInput().catch(()=>{}),e==="Enter"){let t="Press 'Enter'";this.appendStep(t,$.magenta(` \u21B5 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${$.bold(t)}`))}else if(e==="Back"){let t="Tap 'Back'";this.appendStep(t,$.magenta(` \u25C0 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${$.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}=ue(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 a=e.label||this.resolveFieldLabel(i,s),d=`Type '${n}' into '${a}'`,c=this.recordedSteps.length-1,l=c>=0?this.recordedSteps[c]:"";l.startsWith("Type ")&&l.endsWith(`into '${a}'`)?l!==d&&(this.recordedSteps[c]=d,this.flushToDisk(),console.log($.gray(` \u270D\uFE0F Updated Input [Step #${c+1+this.existingSteps.length}]: ${$.bold(d)}`))):this.appendStep(d,$.green(` \u270D\uFE0F Recorded Input [Step #${this.getCurrentStepNumber()}]: ${$.bold(d)}`))}else if(r&&(i.password||e.label.toLowerCase().includes("password"))){let a=e.label||"Password",d=`Type '<password>' into '${a}'`,c=this.recordedSteps.length-1,l=c>=0?this.recordedSteps[c]:"";(!l.startsWith("Type ")||!l.endsWith(`into '${a}'`))&&this.appendStep(d,$.green(` \u270D\uFE0F Recorded Password Input [Step #${this.getCurrentStepNumber()}]: ${$.bold(d)}`))}}}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($.red.bold(`
|
|
764
|
-
\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=re.join(this.screenshotDir,i);(async()=>{try{let r=await this.driver.captureScreenshot(this.targetSerial);if(r&&r.length>0){await de.promises.writeFile(n,r);let o=this.sessionScreenSections[this.sessionScreenSections.length-1];o&&!o.screenshotFile&&(o.screenshotFile=i)}}catch{}})()}triggerAsyncHierarchyRefresh(e=E.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}=ue(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<E.recorder.staleTapTimeoutMs?this.handleTapAt(e.x,e.y):console.warn($.yellow(`[Recorder] Dropped stale tap at (${e.x}, ${e.y}) \u2014 screen refresh took longer than ${E.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,$.green(` \u2714 Recorded Alert [Step #${this.getCurrentStepNumber()}]: ${$.bold(i)}`))}}}async refreshHierarchySync(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=ue(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(`
|
|
765
|
-
`)){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(d=>d!==e&&d.clickable&&d.bounds.height>60&&d.bounds.height<600),o;r?o=t.filter(d=>d.className.includes("Text")&&d.bounds.x1>=r.bounds.x1-10&&d.bounds.x2<=r.bounds.x2+10&&d.bounds.y1>=r.bounds.y1-10&&d.bounds.y2<=r.bounds.y2+10):o=t.filter(d=>d!==e&&d.className.includes("Text")&&d.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-d.bounds.centerY<160&&Math.abs(d.bounds.centerX-e.bounds.centerX)<500);let a=o.filter(d=>{let c=this.cleanLabel(d.text);return c.length>2&&!this.isCardMetadataSubtitle(c)&&!this.isIconGlyph(c)&&!/^\d+$/.test(c)&&!/^(active|inactive|present|absent|new|pending)$/i.test(c)}).sort((d,c)=>d.bounds.y1-c.bounds.y1);if(a.length>0){let d=this.cleanLabel(a[0].text);if(n||r&&d!==i&&!e.clickable)return d}return null}resolveActionLabel(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82){let d=this.cleanLabel(e.contentDesc)||this.cleanLabel(e.text);if(d&&d.length>0&&!this.isIconGlyph(d))return this.cleanDialogOrCompoundLabel(d);for(let c of t){let l=this.cleanLabel(c.contentDesc)||this.cleanLabel(c.text);if(l&&l.length>0&&!this.isIconGlyph(l))return this.cleanDialogOrCompoundLabel(l)}}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 d=n.split(/[\n\r]+/).map(l=>this.cleanLabel(l)).filter(Boolean),c=d.length>1?d.find(l=>l.length>2&&!/^\d+$/.test(l))||d[0]:n;return this.cleanDialogOrCompoundLabel(c)}let r=this.cleanLabel(e.contentDesc);if(r.length>0&&r.length<90)return this.cleanDialogOrCompoundLabel(r);let o=t.find(d=>(d.clickable||d.className.includes("Button"))&&(this.cleanLabel(d.text)||this.cleanLabel(d.contentDesc)));if(o){let d=this.cleanLabel(o.text)||this.cleanLabel(o.contentDesc);if(d.length>0&&d.length<90)return this.cleanDialogOrCompoundLabel(d)}for(let d of t){let c=this.cleanLabel(d.text);if(c.length>0&&c.length<90){let h=c.split(/[\n\r]+/).map(g=>this.cleanLabel(g)).filter(Boolean),u=h.length>1?h.find(g=>g.length>2&&!/^\d+$/.test(g))||h[0]:c;return this.cleanDialogOrCompoundLabel(u)}let l=this.cleanLabel(d.contentDesc);if(l.length>0&&l.length<90)return this.cleanDialogOrCompoundLabel(l)}let a=s.find(d=>d!==e&&(this.cleanLabel(d.text).length>0||this.cleanLabel(d.contentDesc).length>0)&&Math.abs(d.bounds.centerX-e.bounds.centerX)<80&&Math.abs(d.bounds.centerY-e.bounds.centerY)<100);if(a){let d=this.cleanLabel(a.text)||this.cleanLabel(a.contentDesc);if(d.length>0)return this.cleanDialogOrCompoundLabel(d)}if(e.resourceId){let d=e.resourceId.split("/"),c=d[d.length-1];if(c&&!/^\d+$/.test(c)){let l=c.replace(/_/g," ").replace(/btn|button|icon|view|action/gi,"").trim();if(l.length>1)return l.charAt(0).toUpperCase()+l.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,$.green(` \u2714 Recorded Header [Step #${this.getCurrentStepNumber()}]: ${$.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=re.resolve(e);if(re.basename(t).startsWith("app_flow")&&this.targetPackage&&!this.isAppendMode){let a=this.extractBrandSlug(this.targetPackage);if(a!=="app"){let d=`${a}_flow`,c=re.resolve(`specs/${d}.txt`),l=1;for(;de.existsSync(c);)c=re.resolve(`specs/${d}_${l}.txt`),l++;t=c}}let i=re.dirname(t);de.existsSync(i)||de.mkdirSync(i,{recursive:!0});let n=[];if(this.isAppendMode&&this.existingSteps.length>0&&de.existsSync(t)){let a=de.readFileSync(t,"utf-8").trim();n.push(a),n.push(""),n.push(`# --- Appended Session (${new Date().toISOString().replace("T"," ").slice(0,19)}) ---`),this.recordedSteps.forEach((d,c)=>{n.push(`${this.existingSteps.length+c+1}. ${d}`)})}else{n.push("# ==========================================================",`# Autonomous Recorded Test Spec: ${re.basename(t)}`,...this.targetPackage?[`# Package: ${this.targetPackage}`]:[],`# Generated: ${new Date().toISOString()}`,`# PromptTest v${Es}`,"# ==========================================================","");let a=0;this.recordedSteps.forEach((d,c)=>{if(a<this.sessionScreenSections.length&&c===this.sessionScreenSections[a].stepStart){let l=this.sessionScreenSections[a];n.push(""),n.push(`# Screen: ${l.name}`),a++}n.push(`${this.existingSteps.length+c+1}. ${d}`)})}n.push("");let r=n.join(`
|
|
766
|
-
`),o=`${t}.tmp.${Date.now()}`;try{de.writeFileSync(o,r,"utf-8"),de.renameSync(o,t)}catch{try{de.unlinkSync(o)}catch{}de.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((a,d)=>`${d+1}. **${a}**`).join(`
|
|
767
|
-
`):"*Single screen flow*","","---","","## Recorded Interactions",""];if(this.sessionScreenSections.length>0)for(let a=0;a<this.sessionScreenSections.length;a++){let d=this.sessionScreenSections[a],c=this.sessionScreenSections[a+1],l=c?c.stepStart:this.recordedSteps.length,h=this.recordedSteps.slice(d.stepStart,l);o.push(`### Screen: ${d.name}`),o.push(""),d.screenshotFile&&(o.push(`}/${d.screenshotFile})`),o.push("")),h.length>0?h.forEach((u,g)=>{o.push(`${d.stepStart+g+1}. \`${u}\``)}):o.push("*(No interactions on this screen)*"),o.push("")}else o.push("### Steps"),o.push(""),this.recordedSteps.forEach((a,d)=>{o.push(`${d+1}. \`${a}\``)}),o.push("");try{let a=re.dirname(e);de.existsSync(a)||de.mkdirSync(a,{recursive:!0}),de.writeFileSync(e,o.join(`
|
|
768
|
-
`),"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(`
|
|
769
|
-
${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successfully!")),console.log(e),console.log(` ${$.gray("Steps Captured ")} ${$.bold.yellow(this.recordedSteps.length.toString())} ${this.isAppendMode?$.gray(`(Total Suite: ${r})`):""}`),console.log(` ${$.gray("Screens Visited")} ${$.bold.white(this.visitedScreens.length.toString())} ${this.visitedScreens.length>0?$.gray(`(${this.visitedScreens.join(" \u2192 ")})`):""}`),console.log(` ${$.gray("Screenshots ")} ${$.bold.white(this.screenshotCounter.toString())} saved`),console.log(` ${$.gray("Session Time ")} ${$.bold.white(n)}`),console.log(` ${$.gray("Crash Signals ")} ${this.crashDetected?$.red.bold("\u26A0\uFE0F Detected"):$.green("\u2714 0 detected")}`),console.log(e),console.log(` ${$.gray("\u{1F4C4} Spec ")} ${$.cyan(this.resolvedOutputPath)}`);let o=re.basename(this.resolvedOutputPath,".txt");console.log(` ${$.gray("\u{1F4CA} Report ")} ${$.cyan(re.resolve("output",`${o}_report.md`))}`),console.log(`${e}
|
|
770
|
-
`)}},Jo=new pt;import oi from"fs";import Hi from"path";var vt=null;function Ui(p){return JSON.parse(JSON.stringify(p))}function ai(p,e){for(let t of Object.keys(e)){let s=e[t],i=p[t];s&&typeof s=="object"&&!Array.isArray(s)&&i&&typeof i=="object"?ai(i,s):s!==void 0&&(p[t]=s)}return p}function Yi(p){let e=Ui(E),t=p||Hi.resolve(process.cwd(),"prompttest.config.json");if(oi.existsSync(t))try{let m=oi.readFileSync(t,"utf-8"),v=JSON.parse(m);typeof v=="object"&&v!==null&&ai(e,v)}catch{}let s=process.env.PROMPTTEST_ADB_COMMAND_TIMEOUT_MS||process.env.PROMPTTEST_COMMAND_TIMEOUT_MS;if(s){let m=parseInt(s,10);isNaN(m)||(e.adb.commandTimeoutMs=m)}let i=process.env.PROMPTTEST_POLLING_INTERVAL_MS||process.env.PROMPTTEST_POLL_INTERVAL_MS;if(i){let m=parseInt(i,10);isNaN(m)||(e.polling.intervalMs=m)}let n=process.env.PROMPTTEST_POLLING_DEFAULT_TIMEOUT_MS||process.env.PROMPTTEST_DEFAULT_TIMEOUT_MS;if(n){let m=parseInt(n,10);isNaN(m)||(e.polling.defaultTimeoutMs=m)}let r=process.env.PROMPTTEST_SCREEN_FALLBACK_WIDTH||process.env.PROMPTTEST_FALLBACK_WIDTH;if(r){let m=parseInt(r,10);isNaN(m)||(e.screen.fallbackWidth=m)}let o=process.env.PROMPTTEST_SCREEN_FALLBACK_HEIGHT||process.env.PROMPTTEST_FALLBACK_HEIGHT;if(o){let m=parseInt(o,10);isNaN(m)||(e.screen.fallbackHeight=m)}let a=process.env.PROMPTTEST_VISUAL_OVERLAP_RATIO||process.env.PROMPTTEST_OVERLAP_RATIO;if(a){let m=parseFloat(a);isNaN(m)||(e.visual.overlapRatio=m)}let d=process.env.PROMPTTEST_DEVICE_MAX_DEVICE_RETRIES||process.env.PROMPTTEST_MAX_DEVICE_RETRIES;if(d){let m=parseInt(d,10);isNaN(m)||(e.device.maxDeviceRetries=m)}let c=process.env.PROMPTTEST_DEVICE_AUTO_RECONNECT??process.env.PROMPTTEST_AUTO_RECONNECT;c!==void 0&&(e.device.autoReconnect=c.toLowerCase()!=="false");let l=process.env.PROMPTTEST_GESTURES_SWIPE_DURATION_MS||process.env.PROMPTTEST_SWIPE_DURATION_MS;if(l){let m=parseInt(l,10);isNaN(m)||(e.gestures.swipeDurationMs=m)}let h=process.env.PROMPTTEST_FLOW_MAX_LOOP_ITERATIONS||process.env.PROMPTTEST_MAX_LOOP_ITERATIONS;if(h){let m=parseInt(h,10);isNaN(m)||(e.flow.maxLoopIterations=m)}let u=process.env.PROMPTTEST_AI_PROVIDER;u&&["heuristic","openai","anthropic","ollama","mock"].includes(u)&&(e.ai.provider=u);let g=process.env.PROMPTTEST_AI_MODEL;g&&(e.ai.model=g);let f=process.env.PROMPTTEST_SELF_HEALING;f!==void 0&&(e.ai.selfHealing=f.toLowerCase()!=="false");let y=process.env.PROMPTTEST_CONFIDENCE_THRESHOLD;if(y){let m=parseFloat(y);isNaN(m)||(e.ai.confidenceThreshold=m)}let S=process.env.PROMPTTEST_AI_ENDPOINT;S&&(e.ai.endpoint=S);let b=process.env.PROMPTTEST_LOCALE;return b&&(e.locale=b.toLowerCase()),vt=e,e}function ta(){return vt||(vt=Yi()),vt}function sa(){vt=null}import xe from"chalk";function ci(p,e){if(p.length===0)return 0;let t=[...p].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 Ps(p){if(p.length===0)return{minMs:0,maxMs:0,avgMs:0,p50Ms:0,p95Ms:0,iterations:0,durations:[]};let e=Math.round(Math.min(...p)*100)/100,t=Math.round(Math.max(...p)*100)/100,s=p.reduce((o,a)=>o+a,0),i=Math.round(s/p.length*100)/100,n=ci(p,50),r=ci(p,95);return{minMs:e,maxMs:t,avgMs:i,p50Ms:n,p95Ms:r,iterations:p.length,durations:p}}function ji(p=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<p;i++){let n=t[i%t.length],r=n.includes("Button")||n.includes("CheckBox")||n.includes("Switch"),o=s[i%s.length],a=`${o} #${i}`,d=Math.min(2400,250+i*20%2e3),c=50+i*30%900;e.push({index:i,className:n,packageName:"com.app",text:n.includes("ImageView")?"":a,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:c,y1:d,x2:c+200,y2:d+80,width:200,height:80,centerX:c+100,centerY:d+40}})}return e}async function la(p=he,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 p.ensureDefaultDevice(e.serial),i&&(n=await p.getDeviceModel(i),r=!0)}catch{r=!1}let o=[];for(let g=0;g<t;g++){let f=performance.now();r?await p.captureScreenshot(i):(await new Promise(y=>setTimeout(y,15)),Buffer.alloc(1024*1024)),o.push(performance.now()-f)}let a=[];for(let g=0;g<t;g++){let f=performance.now();r?await p.getUiHierarchy(i):await new Promise(y=>setTimeout(y,25)),a.push(performance.now()-f)}let d=ji(1e3),c=new He,l=["Submit","Email Address","Mathematics","Save Changes","NonExistent Query Fallback"],h=[];for(let g=0;g<t;g++){let f=l[g%l.length],y=performance.now();It(d,f,c),h.push(performance.now()-y)}let u=Date.now()-s;return{timestamp:new Date().toISOString(),device:n,package:e.packageName,screencap:Ps(o),uiHierarchy:Ps(a),nodeMatching:Ps(h),totalDurationMs:u}}function da(p){let e=(n,r)=>{let o=`${r.minMs.toFixed(1)}ms`.padStart(9),a=`${r.avgMs.toFixed(1)}ms`.padStart(9),d=`${r.p50Ms.toFixed(1)}ms`.padStart(9),c=`${r.p95Ms.toFixed(1)}ms`.padStart(9),l=`${r.maxMs.toFixed(1)}ms`.padStart(9);return`\u2502 ${n.padEnd(28)} \u2502 ${o} \u2502 ${a} \u2502 ${d} \u2502 ${c} \u2502 ${l} \u2502`};return["",xe.bold.cyan("\u26A1 PromptTest Performance Diagnostic Benchmark"),xe.gray("Device: ")+xe.bold.white(p.device)+xe.gray(` | Samples: ${p.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 ${xe.bold("Operation".padEnd(28))} \u2502 ${xe.bold("Min".padStart(9))} \u2502 ${xe.bold("Avg".padStart(9))} \u2502 ${xe.bold("p50".padStart(9))} \u2502 ${xe.bold("p95".padStart(9))} \u2502 ${xe.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",p.screencap),e("UI Hierarchy Dump (XML)",p.uiHierarchy),e("Node Matching (1k nodes)",p.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",xe.gray("Total Benchmark Wall-Time: ")+xe.bold.green(`${p.totalDurationMs}ms
|
|
884
|
+
\u{1F504} [Data-Driven Iteration ${M+1}/${l.length}] Row Data: ${JSON.stringify(J)}
|
|
885
|
+
======================================================`)),i.fresh&&M>0&&S&&(await this.driver.clearAppData(S,i.serial),await new Promise(f=>setTimeout(f,1e3)))),this.runtimeVariables.clear();for(let[f,I]of Object.entries(J))this.runtimeVariables.set(f,I);this.loopStack=[];let Z=this.parsePrompt(n,J),_=1,De=i.resume&&M===0?await this.checkpoints.getResumeIndex(p):0;De>0&&console.log(V.cyan(`\u23ED Resuming from step ${De+1} (checkpoint found).`));let w=i.only?Mi(i.only):null;for(let f=0;f<Z.length;f++){let I=Z[f];if(_=f+1,w&&!w.has(_)){console.log(V.gray(`[Step ${_}/${Z.length}] \u23E9 Skipped (not in --only range: ${i.only})`)),this.reporter.logStep(le,I.originalText,I.type,"SKIPPED",`Filtered out by --only="${i.only}"`,void 0,{videoOffsetMs:Math.max(0,Date.now()-b)},0);continue}if(f<De){this.reporter.logStep(le,I.originalText,I.type,"SKIPPED","Resumed \u2014 already passed",void 0,{videoOffsetMs:0},0);continue}let N=Z.slice(f+1);console.log(V.bold.blue(`
|
|
886
|
+
[Step ${_}/${Z.length}] ${I.originalText}`));let de=Date.now();try{let he=await this.executeStep(I,i.serial,N),g=Date.now()-de;if(he&&he.fastForwarded){if(console.log(V.cyan(`\u23E9 Fast-Forward: ${he.reason}. Redundant step(s) bypassed.`)),this.reporter.logStep(le,I.originalText,I.type,"PASS",`Fast-Forward: ${he.reason}`,void 0,{videoOffsetMs:Math.max(0,de-b)},g),console.log(V.green(`\u2714 Step ${_} PASSED (Fast-Forward)`)),he?.skipCount&&he.skipCount>0){let P=he.skipCount;for(let O=0;O<P&&f+1<Z.length;O++){f++;let x=Z[f],$=f+1;this.reporter.logStep(le,x.originalText,x.type,"PASS",`Fast-Forward: ${he.reason}`,void 0,{videoOffsetMs:Math.max(0,de-b)},0),console.log(V.gray(` [Step ${$}/${Z.length}] \u23E9 Fast-Forward: ${x.originalText}`))}}}else{let P;if((i.screenshotMode==="all"||i.saveBaseline||i.compareBaseline)&&(P=await this.driver.captureScreenshot(i.serial)),P&&i.compareBaseline){let O=await this.baselines.compare(le,_,P,i.baselineThreshold);O.passed||(console.log(V.yellow(` \u26A0\uFE0F [Baseline] Step ${_} visual diff ${(O.diffRatio*100).toFixed(1)}% exceeds threshold ${(O.threshold*100).toFixed(1)}%`)),this.reporter.logError(`Visual baseline diff at Step ${_}: ${(O.diffRatio*100).toFixed(1)}% changed`))}P&&i.saveBaseline&&!i.compareBaseline&&await this.baselines.saveBaseline(le,_,P),this.reporter.logStep(le,I.originalText,I.type,"PASS",I.target||I.value,i.screenshotMode==="all"?P:void 0,{videoOffsetMs:Math.max(0,de-b)},g),console.log(V.green(`\u2714 Step ${_} PASSED`)),i.benchmark&&console.log(V.gray(` \u23F1 [Benchmark] Step ${_} latency: ${g}ms (${I.type}${I.target?` -> "${I.target}"`:""})`))}i.resume&&!Y&&await this.checkpoints.save(p,S,f,Z.length)}catch(he){let g=he,P=Date.now()-de;if(I.optional){console.log(V.yellow(`\u26AA Step ${_} OPTIONAL (Skipped: ${g.message})`)),this.reporter.logStep(le,I.originalText,I.type,"SKIPPED",`Optional step bypassed: ${g.message}`,void 0,{error:g.message,videoOffsetMs:Math.max(0,de-b)},P);continue}E++,console.log(V.red(`\u274C Step ${_} FAILED: ${g.message}`)),I.target&&this.memory.recordFailure(I.type,I.target);let O=await this.driver.captureScreenshot(i.serial).catch(()=>{}),x;try{let $=Ie.resolve(process.cwd(),"output"),A=`${p}_step_${_}`,H=Ie.join($,"failures",A);Ye.existsSync(H)||Ye.mkdirSync(H,{recursive:!0}),O&&await Ye.promises.writeFile(Ie.join(H,"screenshot.png"),O);let R=this.lastHierarchy?.xml||await this.driver.getUiHierarchy(i.serial).catch(()=>"");R&&await Ye.promises.writeFile(Ie.join(H,"hierarchy.xml"),R,"utf-8");let W=await this.driver.getLogcatTail(150,i.serial);await Ye.promises.writeFile(Ie.join(H,"logcat_tail.log"),W,"utf-8");let X=this.lastHierarchy?.flat||[],te=I.target&&X.length>0?bt(I.target,X.map(Se=>Se.text||Se.contentDesc||"").filter(Boolean)):[];await Ye.promises.writeFile(Ie.join(H,"match_scores.json"),JSON.stringify(te,null,2),"utf-8");let q={specName:le,stepNumber:_,stepType:I.type,target:I.target||I.value,error:g.message,timestamp:new Date().toISOString(),videoOffsetMs:Math.max(0,de-b)};await Ye.promises.writeFile(Ie.join(H,"manifest.json"),JSON.stringify(q,null,2),"utf-8");let ne=[{name:"manifest.json",data:Buffer.from(JSON.stringify(q,null,2),"utf-8")},{name:"logcat_tail.log",data:Buffer.from(W,"utf-8")},{name:"match_scores.json",data:Buffer.from(JSON.stringify(te,null,2),"utf-8")}];R&&ne.push({name:"hierarchy.xml",data:Buffer.from(R,"utf-8")}),O&&ne.push({name:"screenshot.png",data:O});let Q=`${A}.zip`,Ae=Ie.join($,"failures",Q);await Ki(Ae,ne),x=Ie.join("failures",Q).replace(/\\/g,"/"),console.log(V.red(` \u{1F4C1} Failure Triage ZIP Bundle generated at: output/${x}`))}catch{}if(this.reporter.logStep(le,I.originalText,I.type,"FAIL",g.message,O,{error:g.message,videoOffsetMs:Math.max(0,de-b)},P,x),this.reporter.logError(`Step ${_} failed: ${g.message}`),i.continueOnError)console.log(V.yellow("Continuing with next test step (--continue enabled)..."));else{let $=Z.slice(f+1);if($.length>0){console.log(V.yellow(`
|
|
887
|
+
\u{1F6D1} Aborting dependent flow due to upstream failure at Step ${_}.`)),console.log(V.gray(`Cascading skip applied to ${$.length} downstream step(s):`));for(let A=0;A<$.length;A++){let H=$[A],R=_+1+A;this.reporter.logStep(le,H.originalText,H.type,"SKIPPED",`Cascading skip: Precondition failed at Step ${_} (${I.originalText})`,void 0,{videoOffsetMs:Math.max(0,Date.now()-b)},0),console.log(V.gray(` [Step ${R}/${Z.length}] \u26AA SKIPPED: ${H.originalText}`))}}break}}}}try{let M=this.lastHierarchy;if(M?.flat){let J=Ei(M.flat,this.screenDimensions.width,this.screenDimensions.height);if(J.length>0){console.log(V.bold.yellow(`
|
|
888
|
+
\u{1F50D} Visual QA Sentinel Warnings (${J.length} detected):`));for(let Y of J)console.log(V.yellow(` \u2022 [${Y.type}] ${Y.description}`)),this.reporter.logError(`Visual Defect (${Y.type}): ${Y.description}`)}}}catch{}await this.memory.save(),i.resume&&E===0&&await this.checkpoints.clear(p);let D=this.memory.getStats();if(D.totalMappings>0&&console.log(V.cyan(`\u{1F9E0} Knowledge Engine: ${D.totalMappings} active learned mapping(s) for ${D.package}`)),T){console.log(V.cyan("\u{1F3AC} Finalizing video recording..."));let M=Ie.resolve(process.cwd(),"output"),J=Ie.join(M,`${p}-recording.mp4`),Y=await this.driver.stopScreenRecording(T,J,i.serial);Y&&Ye.existsSync(Y)&&(this.reporter.setVideoPath?.(`${p}-recording.mp4`),console.log(V.green(`\u2714 Screen recording saved to: output/${p}-recording.mp4`))),T=null}let B=((Date.now()-b)/1e3).toFixed(1),k=await this.reporter.generateReport(p);y&&(y.broadcastComplete(k),v&&v()),console.log(V.bold.green(`
|
|
889
|
+
\u2728 PromptTest Script Execution Finished in ${B}s!`));let j=k.failedSteps===0?V.bold.green:V.bold.yellow;return console.log(j(`Result: ${k.passedSteps}/${k.totalSteps} passed (${k.failedSteps} failed, ${k.skippedSteps} skipped).`)),console.log(V.cyan(`Report saved to output/${p}-report.html
|
|
890
|
+
`)),i.json&&console.log(JSON.stringify(k,null,2)),k}finally{if(T)try{await this.driver.stopScreenRecording(T,Ie.join("output",`${p}-recording.mp4`),i.serial)}catch{}m&&St(m)}}async getCleanHierarchy(e){let t=await this.driver.getUiHierarchy(e),{flat:s}=we(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=we(t).flat);let r=s.find(o=>o.contentDesc&&(o.contentDesc.startsWith("!, ")||o.contentDesc.includes("react.dev/link")));if(r){let o=r.bounds.x2-45,c=r.bounds.centerY;await this.driver.tap(o,c,e),await new Promise(l=>setTimeout(l,350)),t=await this.driver.getUiHierarchy(e),s=we(t).flat}let n=be(s);return this.lastHierarchy={xml:t,flat:s,timestamp:Date.now(),hash:n},{xml:t,flat:s}}async ensureInViewport(e,t){let s=this.screenDimensions.width,i=this.screenDimensions.height,r=Math.round(s*.5),n=this.navBarHeight>0?i-this.navBarHeight:i,o=this.navBarHeight>0?n*.94:i*C.gestures.bottomNavThresholdRatio;if(e.bounds.centerY>o||e.bounds.y1>o)return!1;let l=e.bounds.y2>n,p=e.bounds.y1<Math.round(i*.04)&&e.bounds.centerY<Math.round(i*.06);return l?(await this.driver.swipe(r,Math.round(i*.75),r,Math.round(i*.45),250,t),await new Promise(d=>setTimeout(d,200)),this.lastHierarchy=null,!0):p?(await this.driver.swipe(r,Math.round(i*.35),r,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<C.polling.hierarchyCacheTtlMs){let c=this.matchNodes(this.lastHierarchy.flat,e,i);if(c.length>0)return{flat:this.lastHierarchy.flat,matched:c}}let r=Date.now();for(;Date.now()-r<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,ui()))}let{flat:n}=await this.getCleanHierarchy(t),o=this.matchNodes(n,e,i);if(o.length===0&&(this.healEnabled||C.ai.selfHealing))try{let c=await this.semanticResolver.findSuggestions(e,n,{locale:this.activeLocale}),l=C.ai.confidenceThreshold||.75,p=c.find(d=>d.score>=l);if(p){let d=p.node||n.find(h=>(pe(p.text,h.text)||pe(p.text,h.contentDesc))&&h.bounds.width>0);if(d){console.log(V.yellow(` \u{1F4A1} [Self-Healing] Auto-healed "${e}" \u2192 "${p.text}" (${Math.round(p.score*100)}% confidence, ${p.strategy})`)),i&&(i.healedFrom=e);let h=d.text?"text":d.contentDesc?"contentDesc":"resourceId",u=this.lastHierarchy?.hash,m=Math.min(C.memory?.maxHealedConfidence??.65,p.score);this.memory.recordSuccess(i?.type||"TAP",e,p.text,h,m,e,u),o=[d]}}}catch(c){Ge.warn(`Self-healing resolution failed: ${c.message}`)}return{flat:n,matched:o}}buildDiagnosticError(e,t,s){return Ni(e,t,s)}async executeStep(e,t,s){let i=Hi.get(e.type);if(!i)throw new Error(`No handler registered for step type: ${e.type}`);e.target&&e.target.includes("$")&&(e.target=ft(e.target,Object.fromEntries(this.runtimeVariables))),e.value&&e.value.includes("$")&&(e.value=ft(e.value,Object.fromEntries(this.runtimeVariables))),(e.type==="LAUNCH_APP"||e.type==="RESTART_APP")&&e.target&&(this.targetPackage=e.target);let r={targetPackage:this.targetPackage,driver:this.driver,memory:this.memory,serial:t,screenDimensions:this.screenDimensions,navBarHeight:this.navBarHeight,lastHierarchy:this.lastHierarchy,setLastHierarchy:n=>{this.lastHierarchy=n},getCleanHierarchy:n=>this.getCleanHierarchy(n),waitForTarget:(n,o,c,l)=>this.waitForTarget(n,o,c,l),matchNodes:(n,o,c)=>this.matchNodes(n,o,c),ensureInViewport:(n,o)=>this.ensureInViewport(n,o),buildDiagnosticError:(n,o,c)=>this.buildDiagnosticError(n,o,c),findTargetInputField:(n,o,c)=>this.findTargetInputField(n,o,c),upcomingSteps:s,variables:this.runtimeVariables,loopStack:this.loopStack,executeChildSteps:async(n,o)=>{for(let c=0;c<n.length;c++){let l=n[c];await this.executeStep(l,o.serial,n.slice(c+1))}}};return i.execute(e,r)}findTargetInputField(e,t,s){return Li(e,t,s,this.memory)}matchNodes(e,t,s){return Qt(e,t,this.memory,this.activeLocale,s,this.lastHierarchy?.hash)}},Zi=new Ke;import qi from"fs";import or from"path";var Wt=null;function ar(a){return JSON.parse(JSON.stringify(a))}function en(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"?en(i,s):s!==void 0&&(a[t]=s)}return a}function cr(a){let e=ar(C),t=a||or.resolve(process.cwd(),"prompttest.config.json");if(qi.existsSync(t))try{let b=qi.readFileSync(t,"utf-8"),E=JSON.parse(b);typeof E=="object"&&E!==null&&en(e,E)}catch{}let s=process.env.PROMPTTEST_ADB_COMMAND_TIMEOUT_MS||process.env.PROMPTTEST_COMMAND_TIMEOUT_MS;if(s){let b=parseInt(s,10);isNaN(b)||(e.adb.commandTimeoutMs=b)}let i=process.env.PROMPTTEST_POLLING_INTERVAL_MS||process.env.PROMPTTEST_POLL_INTERVAL_MS;if(i){let b=parseInt(i,10);isNaN(b)||(e.polling.intervalMs=b)}let r=process.env.PROMPTTEST_POLLING_DEFAULT_TIMEOUT_MS||process.env.PROMPTTEST_DEFAULT_TIMEOUT_MS;if(r){let b=parseInt(r,10);isNaN(b)||(e.polling.defaultTimeoutMs=b)}let n=process.env.PROMPTTEST_SCREEN_FALLBACK_WIDTH||process.env.PROMPTTEST_FALLBACK_WIDTH;if(n){let b=parseInt(n,10);isNaN(b)||(e.screen.fallbackWidth=b)}let o=process.env.PROMPTTEST_SCREEN_FALLBACK_HEIGHT||process.env.PROMPTTEST_FALLBACK_HEIGHT;if(o){let b=parseInt(o,10);isNaN(b)||(e.screen.fallbackHeight=b)}let c=process.env.PROMPTTEST_VISUAL_OVERLAP_RATIO||process.env.PROMPTTEST_OVERLAP_RATIO;if(c){let b=parseFloat(c);isNaN(b)||(e.visual.overlapRatio=b)}let l=process.env.PROMPTTEST_DEVICE_MAX_DEVICE_RETRIES||process.env.PROMPTTEST_MAX_DEVICE_RETRIES;if(l){let b=parseInt(l,10);isNaN(b)||(e.device.maxDeviceRetries=b)}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 b=parseInt(d,10);isNaN(b)||(e.gestures.swipeDurationMs=b)}let h=process.env.PROMPTTEST_FLOW_MAX_LOOP_ITERATIONS||process.env.PROMPTTEST_MAX_LOOP_ITERATIONS;if(h){let b=parseInt(h,10);isNaN(b)||(e.flow.maxLoopIterations=b)}let u=process.env.PROMPTTEST_AI_PROVIDER;u&&["heuristic","openai","anthropic","ollama","mock"].includes(u)&&(e.ai.provider=u);let m=process.env.PROMPTTEST_AI_MODEL;m&&(e.ai.model=m);let y=process.env.PROMPTTEST_SELF_HEALING;y!==void 0&&(e.ai.selfHealing=y.toLowerCase()!=="false");let v=process.env.PROMPTTEST_CONFIDENCE_THRESHOLD;if(v){let b=parseFloat(v);isNaN(b)||(e.ai.confidenceThreshold=b)}let T=process.env.PROMPTTEST_AI_ENDPOINT;T&&(e.ai.endpoint=T);let S=process.env.PROMPTTEST_LOCALE;return S&&(e.locale=S.toLowerCase()),Wt=e,e}function vl(){return Wt||(Wt=cr()),Wt}function xl(){Wt=null}import Fe from"chalk";function tn(a,e){if(a.length===0)return 0;let t=[...a].sort((i,r)=>i-r),s=Math.min(t.length-1,Math.max(0,Math.floor(e/100*(t.length-1))));return Math.round(t[s]*100)/100}function si(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,r=tn(a,50),n=tn(a,95);return{minMs:e,maxMs:t,avgMs:i,p50Ms:r,p95Ms:n,iterations:a.length,durations:a}}function lr(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 r=t[i%t.length],n=r.includes("Button")||r.includes("CheckBox")||r.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:r,packageName:"com.app",text:r.includes("ImageView")?"":c,resourceId:`com.app:id/element_${i}`,contentDesc:r.includes("ImageView")?`Icon of ${o}`:"",clickable:n,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 $l(a=ke,e={}){let t=e.iterations||5,s=Date.now(),i=e.serial,r="Synthetic Mock Android Environment",n=!1;if(!e.forceMock)try{i=await a.ensureDefaultDevice(e.serial),i&&(r=await a.getDeviceModel(i),n=!0)}catch{n=!1}let o=[];for(let m=0;m<t;m++){let y=performance.now();n?await a.captureScreenshot(i):(await new Promise(v=>setTimeout(v,15)),Buffer.alloc(1024*1024)),o.push(performance.now()-y)}let c=[];for(let m=0;m<t;m++){let y=performance.now();n?await a.getUiHierarchy(i):await new Promise(v=>setTimeout(v,25)),c.push(performance.now()-y)}let l=lr(1e3),p=new rt,d=["Submit","Email Address","Mathematics","Save Changes","NonExistent Query Fallback"],h=[];for(let m=0;m<t;m++){let y=d[m%d.length],v=performance.now();Qt(l,y,p),h.push(performance.now()-v)}let u=Date.now()-s;return{timestamp:new Date().toISOString(),device:r,package:e.packageName,screencap:si(o),uiHierarchy:si(c),nodeMatching:si(h),totalDurationMs:u}}function Cl(a){let e=(r,n)=>{let o=`${n.minMs.toFixed(1)}ms`.padStart(9),c=`${n.avgMs.toFixed(1)}ms`.padStart(9),l=`${n.p50Ms.toFixed(1)}ms`.padStart(9),p=`${n.p95Ms.toFixed(1)}ms`.padStart(9),d=`${n.maxMs.toFixed(1)}ms`.padStart(9);return`\u2502 ${r.padEnd(28)} \u2502 ${o} \u2502 ${c} \u2502 ${l} \u2502 ${p} \u2502 ${d} \u2502`};return["",Fe.bold.cyan("\u26A1 PromptTest Performance Diagnostic Benchmark"),Fe.gray("Device: ")+Fe.bold.white(a.device)+Fe.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 ${Fe.bold("Operation".padEnd(28))} \u2502 ${Fe.bold("Min".padStart(9))} \u2502 ${Fe.bold("Avg".padStart(9))} \u2502 ${Fe.bold("p50".padStart(9))} \u2502 ${Fe.bold("p95".padStart(9))} \u2502 ${Fe.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",Fe.gray("Total Benchmark Wall-Time: ")+Fe.bold.green(`${a.totalDurationMs}ms
|
|
771
891
|
`)].join(`
|
|
772
|
-
`)}import
|
|
773
|
-
`)
|
|
774
|
-
|
|
775
|
-
`)
|
|
776
|
-
`)}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
`),c();return}if(
|
|
781
|
-
\u{1F4DC} Session History (${n.history.length} commands):`)),n.history.forEach((y,S)=>{l(` ${S+1}. ${y}`)}),l(""),c();return}if(f==="clear"){n.successfulSteps=[],n.history=[],l(G.green("Session history cleared.")),c();return}if(f.startsWith("save")){let S=g.split(/\s+/)[1]||"output/repl_spec.txt";try{let b=di.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=n.successfulSteps.map((v,x)=>`${x+1}. ${v}`).join(`
|
|
782
|
-
`);ht.writeFileSync(S,m,"utf-8"),l(G.bold.green(`\u2714 Saved ${n.successfulSteps.length} step(s) to ${S}`))}catch(b){let m=b;l(G.red(`Failed to save spec: ${m.message}`))}c();return}if(f.startsWith("screenshot")){let S=g.split(/\s+/)[1]||`output/repl_screenshot_${Date.now()}.png`;try{let b=di.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=await p.captureScreenshot(s);ht.writeFileSync(S,m),l(G.bold.green(`\u2714 Screenshot saved to ${S}`))}catch(b){let m=b;l(G.red(`Failed to capture screenshot: ${m.message}`))}c();return}if(f==="inspect"||f==="tree"){try{l(G.gray("Dumping UI hierarchy..."));let y=await p.getUiHierarchy(s),{flat:S}=ue(y),b=S.filter(m=>m.clickable||m.className.includes("Button")||m.className.includes("EditText"));l(G.bold.white(`
|
|
783
|
-
\u{1F50D} Visible Interactive Elements (${b.length} found):`)),b.slice(0,25).forEach((m,v)=>{let x=m.text||m.contentDesc||m.resourceId||`<Unnamed ${m.className}>`,D=m.className.split(".").pop()||m.className;l(` [${v+1}] (${D}) "${x}" at (${m.bounds.centerX}, ${m.bounds.centerY})`)}),b.length>25&&l(G.gray(` ... and ${b.length-25} more elements.`)),l("")}catch(y){let S=y;l(G.red(`Failed to inspect hierarchy: ${S.message}`))}c();return}try{let y=Ct(g);if(y.length===0){l(G.yellow(`Could not parse natural language step: "${g}"`)),c();return}let S=y[0],b=performance.now();await i.executeStep(S,s);let m=Math.round(performance.now()-b);n.successfulSteps.push(g),l(G.green(`\u2714 [${S.type}] Completed in ${m}ms: `)+G.white(S.originalText))}catch(y){let S=y;l(G.red(`\u2716 Step failed: ${S.message}`))}c()}),a.on("close",()=>{d=!0,h(n)})})}import{execFile as qe}from"child_process";var ui=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=>{qe("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 a=r[o];if(Array.isArray(a))for(let d of a)d.isAvailable&&d.state==="Booted"&&n.push({serial:d.udid,state:"simulator",model:`${d.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)=>{qe("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"?>
|
|
892
|
+
`)}import dr from"readline";import Rt from"fs";import sn from"path";import ce from"chalk";async function nn(a=ke,e,t={}){let s=await a.ensureDefaultDevice(t.serial),i=e||new Ke(a),r={history:[],successfulSteps:[]},n=t.input||process.stdin,o=t.output||process.stdout,c=dr.createInterface({input:n,output:o,prompt:ce.bold.cyan("prompttest> ")}),l=!1,p=()=>{if(!l)try{c.prompt()}catch{}},d=h=>{o.write(h+`
|
|
893
|
+
`)};return d(ce.bold.cyan(`
|
|
894
|
+
\u26A1 PromptTest Interactive Live REPL / Playground (v1.1.0)`)),d(ce.gray("Device: ")+ce.bold.white(s||"No device connected (offline mock)")+(t.packageName?ce.gray(" | Package: ")+ce.bold.white(t.packageName):"")),d(ce.gray(`Type natural language instructions (e.g. Tap 'Sign In'), or REPL commands: "inspect", "screenshot", "history", "save <file.txt>", "exit".
|
|
895
|
+
`)),new Promise(h=>{p(),c.on("line",async u=>{let m=u.trim();if(!m){p();return}r.history.push(m);let y=m.toLowerCase();if(y==="exit"||y==="quit"||y===":q"){l=!0,d(ce.yellow("Exiting PromptTest REPL.")),c.close();return}if(y==="help"||y==="?"){d(ce.bold.white(`
|
|
896
|
+
\u{1F4D6} PromptTest REPL Commands:`)),d(` \u2022 ${ce.cyan("Tap '...'")} / ${ce.cyan("Type '...' into '...'")} : Execute action live on device`),d(` \u2022 ${ce.cyan("Verify '...' is visible")} : Assert element visibility`),d(` \u2022 ${ce.cyan("inspect")} / ${ce.cyan("tree")} : List interactive elements and input fields on screen`),d(` \u2022 ${ce.cyan("screenshot [path]")} : Capture current screen to image file`),d(` \u2022 ${ce.cyan("history")} : Show executed commands in current session`),d(` \u2022 ${ce.cyan("save <file.txt>")} : Save successful steps into a reusable spec file`),d(` \u2022 ${ce.cyan("clear")} : Clear session history`),d(` \u2022 ${ce.cyan("exit")} : Quit the REPL
|
|
897
|
+
`),p();return}if(y==="history"){d(ce.bold.white(`
|
|
898
|
+
\u{1F4DC} Session History (${r.history.length} commands):`)),r.history.forEach((v,T)=>{d(` ${T+1}. ${v}`)}),d(""),p();return}if(y==="clear"){r.successfulSteps=[],r.history=[],d(ce.green("Session history cleared.")),p();return}if(y.startsWith("save")){let T=m.split(/\s+/)[1]||"output/repl_spec.txt";try{let S=sn.dirname(T);S&&!Rt.existsSync(S)&&Rt.mkdirSync(S,{recursive:!0});let b=r.successfulSteps.map((E,D)=>`${D+1}. ${E}`).join(`
|
|
899
|
+
`);Rt.writeFileSync(T,b,"utf-8"),d(ce.bold.green(`\u2714 Saved ${r.successfulSteps.length} step(s) to ${T}`))}catch(S){let b=S;d(ce.red(`Failed to save spec: ${b.message}`))}p();return}if(y.startsWith("screenshot")){let T=m.split(/\s+/)[1]||`output/repl_screenshot_${Date.now()}.png`;try{let S=sn.dirname(T);S&&!Rt.existsSync(S)&&Rt.mkdirSync(S,{recursive:!0});let b=await a.captureScreenshot(s);Rt.writeFileSync(T,b),d(ce.bold.green(`\u2714 Screenshot saved to ${T}`))}catch(S){let b=S;d(ce.red(`Failed to capture screenshot: ${b.message}`))}p();return}if(y==="inspect"||y==="tree"){try{d(ce.gray("Dumping UI hierarchy..."));let v=await a.getUiHierarchy(s),{flat:T}=we(v),S=T.filter(b=>b.clickable||b.className.includes("Button")||b.className.includes("EditText"));d(ce.bold.white(`
|
|
900
|
+
\u{1F50D} Visible Interactive Elements (${S.length} found):`)),S.slice(0,25).forEach((b,E)=>{let D=b.text||b.contentDesc||b.resourceId||`<Unnamed ${b.className}>`,B=b.className.split(".").pop()||b.className;d(` [${E+1}] (${B}) "${D}" at (${b.bounds.centerX}, ${b.bounds.centerY})`)}),S.length>25&&d(ce.gray(` ... and ${S.length-25} more elements.`)),d("")}catch(v){let T=v;d(ce.red(`Failed to inspect hierarchy: ${T.message}`))}p();return}try{let v=Nt(m);if(v.length===0){d(ce.yellow(`Could not parse natural language step: "${m}"`)),p();return}let T=v[0],S=performance.now();await i.executeStep(T,s);let b=Math.round(performance.now()-S);r.successfulSteps.push(m),d(ce.green(`\u2714 [${T.type}] Completed in ${b}ms: `)+ce.white(T.originalText))}catch(v){let T=v;d(ce.red(`\u2716 Step failed: ${T.message}`))}p()}),c.on("close",()=>{l=!0,h(r)})})}import{execFile as Tt}from"child_process";var rn=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(r=>r.state==="simulator"||r.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=>{Tt("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),r=[],n=i.devices||{};for(let o of Object.keys(n)){let c=n[o];if(Array.isArray(c))for(let l of c)l.isAvailable&&l.state==="Booted"&&r.push({serial:l.udid,state:"simulator",model:`${l.name} (${o.split(".").pop()||"iOS"})`,platform:"ios"})}e(r.length>0?r:[{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)=>{Tt("xcrun",["simctl","io",t,"screenshot","--type=png","-"],{encoding:"buffer",maxBuffer:10*1024*1024},(r,n)=>{if(r)return i(r);s(n)})})}async getUiHierarchy(e){let t=`<?xml version="1.0" encoding="UTF-8"?>
|
|
784
901
|
<hierarchy rotation="0">
|
|
785
902
|
<XCUIElementTypeApplication type="XCUIElementTypeApplication" name="TargetApp" label="TargetApp" enabled="true" visible="true" x="0" y="0" width="390" height="844">
|
|
786
903
|
<XCUIElementTypeWindow type="XCUIElementTypeWindow" enabled="true" visible="true" x="0" y="0" width="390" height="844">
|
|
@@ -789,7 +906,7 @@ ${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successful
|
|
|
789
906
|
<XCUIElementTypeTextField type="XCUIElementTypeTextField" identifier="user_field" name="Username" label="Username" enabled="true" visible="true" x="40" y="120" width="310" height="44" />
|
|
790
907
|
</XCUIElementTypeWindow>
|
|
791
908
|
</XCUIElementTypeApplication>
|
|
792
|
-
</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(
|
|
909
|
+
</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(r=>{Tt("idb",["ui","tap",`${e}`,`${t}`,"--udid",i],()=>r())})}}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=>{Tt("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,r=300,n){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(n),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:r/1e3})}).catch(()=>{}))}async launchApp(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{Tt("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=>{Tt("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=>{Tt("xcrun",["simctl","get_app_container",s,e],r=>{i(!r)})})}async getForegroundPackage(e){return"com.apple.mobilesafari"}};import Vt from"fs";import ii from"path";function on(a){let e=a.totalSteps||0,t=a.passedSteps||0,s=a.failedSteps||0,i=a.skippedSteps||0,r=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 n=t/e,o=Math.min(30,r*10),c=s>0?35+Math.min(25,s*5):0,l=Math.round(n*80+20-o-c);l=Math.max(0,Math.min(100,l));let p="F",d="RELEASE_BLOCKER",h="";return l>=90?(p="A",d="READY_FOR_RELEASE",h="High quality gate confidence. All critical assertion paths verified."):l>=80?(p="B",d="READY_FOR_RELEASE",h="Acceptable release confidence. Minor non-critical or optional warnings observed."):l>=70?(p="C",d="PROCEED_WITH_CAUTION",h="Elevated risk. Visual QA warnings or multiple non-critical step failures detected."):(p="F",d="RELEASE_BLOCKER",h=`Critical test failures (${s}) or visual defects (${r}) block safe release.`),{score:l,grade:p,verdict:d,rationale:h,metrics:{passRate:Math.round(n*100)/100,criticalFailures:s,visualDefects:r,totalSteps:e,skippedSteps:i}}}function Jl(a="output"){let e=[],t=u=>{if(!Vt.existsSync(u))return;let m=Vt.readdirSync(u,{withFileTypes:!0});for(let y of m){let v=ii.join(u,y.name);y.isDirectory()?t(v):y.isFile()&&(y.name.endsWith("-results.json")||y.name.endsWith("-report.json"))&&e.push(v)}};if(Array.isArray(a))for(let u of a)Vt.existsSync(u)&&(Vt.statSync(u).isDirectory()?t(u):e.push(u));else t(a);let s=[],i=new Set,r=0,n=0,o=0,c=0,l=[];for(let u of e)try{let m=Vt.readFileSync(u,"utf-8"),y=JSON.parse(m),v=on(y),T=y.deviceId||"unknown-device";i.add(T),r+=y.totalSteps||0,n+=y.passedSteps||0,o+=y.failedSteps||0,c+=y.skippedSteps||0,y.errorsDetected&&l.push(...y.errorsDetected),s.push({deviceId:T,suiteName:ii.basename(u,ii.extname(u)).replace(/-results|-report/,""),packageName:y.packageName||"unknown",totalSteps:y.totalSteps||0,passedSteps:y.passedSteps||0,failedSteps:y.failedSteps||0,skippedSteps:y.skippedSteps||0,durationSeconds:y.durationSeconds||0,confidenceScore:v.score,confidenceGrade:v.grade,sourceFile:u})}catch{}let p=r>0?Math.round(n/r*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((u,m)=>u+m.durationSeconds,0),totalSteps:r,passedSteps:n,failedSteps:o,skippedSteps:c,warnSteps:0,errorsDetected:l,steps:[]},h=on(d);return{timestamp:new Date().toISOString(),totalRuns:s.length,uniqueDevices:Array.from(i),totalSteps:r,passedSteps:n,failedSteps:o,skippedSteps:c,overallPassRate:p,overallConfidence:h,deviceSummaries:s}}function Xl(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 r=i.confidenceGrade==="A"?"#10B981":i.confidenceGrade==="B"?"#3B82F6":i.confidenceGrade==="C"?"#F59E0B":"#EF4444";return`
|
|
793
910
|
<tr style="border-bottom: 1px solid #334155;">
|
|
794
911
|
<td style="padding: 12px; font-weight: bold; color: #F8FAFC;">${i.deviceId}</td>
|
|
795
912
|
<td style="padding: 12px; color: #94A3B8;">${i.suiteName}</td>
|
|
@@ -799,7 +916,7 @@ ${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successful
|
|
|
799
916
|
<td style="padding: 12px; text-align: center; color: #EF4444; font-weight: bold;">${i.failedSteps}</td>
|
|
800
917
|
<td style="padding: 12px; text-align: center; color: #64748B;">${i.skippedSteps}</td>
|
|
801
918
|
<td style="padding: 12px; text-align: center;">
|
|
802
|
-
<span style="background: ${
|
|
919
|
+
<span style="background: ${r}22; color: ${r}; border: 1px solid ${r}; padding: 4px 10px; border-radius: 9999px; font-weight: bold; font-size: 12px;">
|
|
803
920
|
Grade ${i.confidenceGrade} (${i.confidenceScore}%)
|
|
804
921
|
</span>
|
|
805
922
|
</td>
|
|
@@ -822,12 +939,12 @@ ${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successful
|
|
|
822
939
|
<div class="card header-grid">
|
|
823
940
|
<div>
|
|
824
941
|
<h1 style="margin-top: 0; color: #38BDF8;">PromptTest Executive Quality Matrix</h1>
|
|
825
|
-
<p style="color: #94A3B8; margin-bottom: 20px;">Generated at ${
|
|
942
|
+
<p style="color: #94A3B8; margin-bottom: 20px;">Generated at ${a.timestamp} across ${a.uniqueDevices.length} target device(s).</p>
|
|
826
943
|
<div style="display: flex; gap: 24px;">
|
|
827
|
-
<div><span style="font-size: 24px; font-weight: bold; color: #F8FAFC;">${
|
|
828
|
-
<div><span style="font-size: 24px; font-weight: bold; color: #10B981;">${
|
|
829
|
-
<div><span style="font-size: 24px; font-weight: bold; color: #EF4444;">${
|
|
830
|
-
<div><span style="font-size: 24px; font-weight: bold; color: #38BDF8;">${Math.round(
|
|
944
|
+
<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>
|
|
945
|
+
<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>
|
|
946
|
+
<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>
|
|
947
|
+
<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>
|
|
831
948
|
</div>
|
|
832
949
|
</div>
|
|
833
950
|
<div class="score-badge">
|
|
@@ -859,4 +976,25 @@ ${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successful
|
|
|
859
976
|
</table>
|
|
860
977
|
</div>
|
|
861
978
|
</body>
|
|
862
|
-
</html>`}function
|
|
979
|
+
</html>`}import Ot from"os";import _e from"chalk";var pr="https://github.com/shriramsingh/prompttest-community/issues/new";function ur(a){if(!a)return"";let e=a;try{let t=Ot.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 Zl(a){if(!a||a instanceof Je&&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 hr(a){let e=a.repoUrl||pr,t=(a.errorMessage||"Unexpected internal error").split(`
|
|
980
|
+
`)[0].trim(),s=`[Crash]: ${t}`,i=s.length>80?s.substring(0,77)+"...":s,r=`${Ot.type()} ${Ot.release()} (${Ot.arch()})`,n=process.version,o=`${r}, Node: ${n}`,c=ur(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 ql(a,e={}){let t=a&&typeof a=="object"?a:{},s=t.message||String(a),i=t.stack,r=e.command||(process.argv.slice(2).length>0?`npx prompttest ${process.argv.slice(2).join(" ")}`:"npx prompttest"),n=hr({errorMessage:s,stack:i,command:r,exitCode:e.exitCode}),o=`${Ot.type()} ${Ot.arch()}`,c=process.version;console.error(),console.error(_e.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(_e.red.bold("\u{1F4A5} PromptTest Encountered an Unexpected Error / Crash")),console.error(_e.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(_e.white("Error: ")+_e.red(s.split(`
|
|
981
|
+
`)[0])),console.error(_e.white("Command: ")+_e.gray(r)),console.error(_e.white("Environment: ")+_e.gray(`${o} | Node: ${c}`)),console.error(),console.error(_e.cyan("\u{1F4A1} Think this is a bug in PromptTest? You can report it in 1 click (pre-filled):")),console.error(_e.bold.underline.cyan(n)),console.error(_e.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()}import fr from"readline";import ci from"fs";import li from"path";import F from"chalk";async function br(a=ke){try{let t=(await a.getConnectedDevices()).find(r=>r.state==="device");if(!t)return{isOnline:!1};let s=t.serial,i;try{let r=await a.getForegroundPackage(s);r&&!r.includes("launcher")&&!r.includes("systemui")&&(i=r)}catch{}return{device:t,serial:s,activePackage:i,isOnline:!0}}catch{return{isOnline:!1}}}function yr(a=process.cwd()){let e=[],t=[li.join(a,"specs"),a];for(let s of t)if(ci.existsSync(s)&&ci.statSync(s).isDirectory())try{let i=ci.readdirSync(s);for(let r of i)if(r.endsWith(".txt")||r.endsWith(".spec")||r.endsWith(".prompt")){let n=li.relative(a,li.join(s,r)).replace(/\\/g,"/");e.includes(n)||e.push(n)}}catch{}return e.sort()}function ht(a,e){return new Promise(t=>{a.question(e,s=>{t(s.trim())})})}async function yd(a={}){let e=a.driver||ke,t=a.runner||Zi,s=a.input||process.stdin,i=a.output||process.stdout,r=fr.createInterface({input:s,output:i}),n=(o="")=>{i.write(o+`
|
|
982
|
+
`)};try{n(F.bold.cyan(`
|
|
983
|
+
\u26A1 PromptTest \u2014 Autonomous Mobile Testing Brain`)),n(F.gray("Inspecting device connectivity and active application..."));let o=await br(e);switch(n(F.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?n(F.white("\u{1F4F1} Target Device: ")+F.bold.green(`${o.serial}`)+(o.device.model?F.gray(` (${o.device.model})`):"")+F.green(" [Online]")):n(F.white("\u{1F4F1} Target Device: ")+F.yellow("No authorized device online (Check USB/Wi-Fi)")),o.activePackage?n(F.white("\u{1F3AF} Active App: ")+F.bold.magenta(o.activePackage)+F.gray(" (Detected)")):n(F.white("\u{1F3AF} Active App: ")+F.gray("None detected / Home Launcher")),n(F.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
|
|
984
|
+
`)),n(F.bold.white("What would you like to do?")),n(` ${F.bold.cyan("[1]")} \u{1F680} ${F.bold("Explore app autonomously")} ${F.gray("(Zero-code AI crawl)")}`),n(` ${F.bold.cyan("[2]")} \u{1F534} ${F.bold("Record a test")} ${F.gray("(Capture real device taps into spec)")}`),n(` ${F.bold.cyan("[3]")} \u25B6\uFE0F ${F.bold("Run a test specification")} ${F.gray("(Execute .txt spec with healing)")}`),n(` ${F.bold.cyan("[4]")} \u{1F4AC} ${F.bold("Open Live REPL Playground")} ${F.gray("(Interactive terminal session)")}`),n(` ${F.bold.cyan("[5]")} \u{1FA7A} ${F.bold("Run Diagnostic Doctor")} ${F.gray("(Check ADB, Node, permissions)")}`),n(` ${F.bold.cyan("[6]")} \u{1F4F1} ${F.bold("Inspect UI Components")} ${F.gray("(Summary of buttons, inputs, tabs)")}`),n(` ${F.bold.cyan("[7]")} \u2753 ${F.bold("Help & CLI Syntax Reference")}`),n(` ${F.bold.cyan("[8]")} \u{1F4AC} ${F.bold("Share Feedback & Suggestions")} ${F.gray("(1-click community link)")}`),n(` ${F.bold.cyan("[0]")} \u{1F6AA} ${F.gray("Exit")}
|
|
985
|
+
`),await ht(r,F.bold.cyan("Select an option [0-8]: "))){case"1":{n(F.bold.cyan(`
|
|
986
|
+
\u{1F680} Autonomous App Exploration`));let l=o.activePackage||"",p=l?F.white(`Target package [default: ${F.bold.magenta(l)}]: `):F.white("Target package name (e.g. com.example.app): "),h=await ht(r,p)||l;if(!h){n(F.red("Error: Package name is required to start exploration."));break}let u=F.white(`Safety mode [strict/moderate/disabled] (default: ${F.bold.green("strict")}): `),m=await ht(r,u)||"strict",y=["strict","moderate","interactive","disabled"].includes(m)?m:"strict";r.close(),n(F.green(`
|
|
987
|
+
Starting autonomous exploration on ${F.bold(h)}...
|
|
988
|
+
`)),await Xi.explore({packageName:h,serial:o.serial,strategy:"dfs",safetyMode:y});return}case"2":{n(F.bold.cyan(`
|
|
989
|
+
\u{1F534} Interactive Record & Replay`));let l=F.white(`Target spec file to save [default: ${F.bold.green("specs/recorded_flow.txt")}]: `),p=await ht(r,l)||"specs/recorded_flow.txt";r.close(),n(F.green(`
|
|
990
|
+
Starting recording session on device. Output: ${p}...
|
|
991
|
+
`)),await ji.startRecording(p,o.serial,{append:!1});return}case"3":{n(F.bold.cyan(`
|
|
992
|
+
\u25B6\uFE0F Run Test Specification`));let l=yr(),p="";if(l.length>0){n(F.white("Discovered existing test specs:")),l.forEach((D,B)=>{n(` [${B+1}] ${F.cyan(D)}`)}),n();let S=F.white(`Select spec number [1-${l.length}] or enter path: `),b=await ht(r,S),E=parseInt(b,10);!isNaN(E)&&E>=1&&E<=l.length?p=l[E-1]:b&&(p=b)}if(p||(p=await ht(r,F.white("Enter spec file path (e.g. specs/login.txt): "))),!p){n(F.red("Error: Spec file path is required."));break}let d=o.activePackage||"",h=d?F.white(`Target package [default: ${F.bold.magenta(d)}]: `):F.white("Target package (optional): "),m=await ht(r,h)||d||void 0,y=F.white(`Enable dynamic self-healing locators? [Y/n] (default: ${F.bold.green("yes")}): `),v=(await ht(r,y)).toLowerCase(),T=v!=="n"&&v!=="no";r.close(),n(F.green(`
|
|
993
|
+
Executing spec "${p}"...
|
|
994
|
+
`)),await t.runSpec(p,{packageName:m,serial:o.serial,heal:T});return}case"4":{n(F.bold.cyan(`
|
|
995
|
+
\u{1F4AC} Launching Live REPL Playground...`)),r.close(),await nn(e,t,{serial:o.serial,packageName:o.activePackage});return}case"5":{n(F.bold.cyan(`
|
|
996
|
+
\u{1FA7A} Running Diagnostic Health Check...`)),r.close();let l=await ss(e,{serial:o.serial,packageName:o.activePackage});n(Wi(l));return}case"6":{if(!o.isOnline||!o.serial){n(F.red("No device online to inspect."));break}n(F.cyan(`
|
|
997
|
+
\u{1F50D} Inspecting Active Screen UI Hierarchy...`));try{let l=await e.getUiHierarchy(o.serial),{flat:p}=we(l),d=ze(p),h=Qe(p),u=Ut(p);n(F.white(`
|
|
998
|
+
On-Screen Component Breakdown:`)),n(`- \u{1F4DD} Input Fields: ${F.bold.magenta(d.length.toString())}`),d.slice(0,5).forEach(m=>n(` \u2022 "${m.text||m.contentDesc||m.resourceId}"`)),n(`- \u{1F518} Action Buttons: ${F.bold.blue(h.length.toString())}`),h.slice(0,5).forEach(m=>n(` \u2022 "${m.text||m.contentDesc||m.resourceId}"`)),n(`- \u{1F4D1} Navigation Tabs: ${F.bold.yellow(u.length.toString())}`),u.forEach(m=>n(` \u2022 "${m.text||m.contentDesc}"`)),n()}catch(l){let p=l instanceof Error?l.message:String(l);n(F.red(`Failed to read UI hierarchy: ${p}`))}break}case"7":{n(F.bold.cyan(`
|
|
999
|
+
\u{1F4D6} Quick CLI Command Reference`)),n(" npx prompttest Interactive guided CLI wizard"),n(" npx prompttest feedback [message] Share feedback or feature requests in 1 click"),n(" npx prompttest doctor Check system dependencies & ADB"),n(" npx prompttest explore <package> Autonomous AI crawl with safety policies"),n(" npx prompttest record <spec.txt> Interactive record touches from phone"),n(" npx prompttest run <spec.txt> [package] Execute plain-English test spec"),n(" npx prompttest repl [package] Interactive live terminal playground"),n(" npx prompttest devices List all connected devices & serials"),n(` npx prompttest wifi <device_ip> Connect wireless device over Wi-Fi
|
|
1000
|
+
`);break}case"8":{r.close();let{startFeedbackSession:l}=await Promise.resolve().then(()=>(ai(),an));await l({input:s,output:i});return}default:{n(F.gray("Exiting PromptTest. Have a great day!"));break}}}finally{try{r.close()}catch{}}}ai();function Ad(a,e,t){return new Ke(a,e,t)}function $d(a,e,t){return new ut(a,e,t)}function Cd(a){return new tt(a)}function Id(){return new rt}function Nd(a){return new At(a)}function Ld(a){return new lt(a)}function Md(a,e){return new pt(a,e)}function Rd(a,e){return new ct(a,e)}export{Si as ACTION_KEYWORDS,tt as AndroidDriver,Gs as ApiHandler,ut as AutonomousExplorer,lt as AutonomousRecorder,Cs as BackHandler,ct as BaselineManager,C as CONFIG,_s as ClearDataHandler,As as ClearHandler,js as ConditionalHandler,os as ConfigError,In as DESTRUCTIVE_ACTION_PATTERNS,Mt as DataSpecLoader,Bs as DeepLinkHandler,mt as DeviceError,Js as DeviceStateHandler,Ln as EXTERNAL_INTENT_PATTERNS,Ks as EmailHandler,cs as ExitCode,zr as GLOBAL_SEED_DICTIONARY,Hs as GrantPermissionHandler,xt as HeuristicResolver,rn as IosDriver,es as LLMResolver,$t as LOCALE_PACKS,Cn as LOGBOX_PATTERNS,Rs as LaunchAppHandler,rs as LocatorError,as as LockError,zt as Logger,Ds as LongPressHandler,Ys as LoopHandler,Nn as MODERATE_DESTRUCTIVE_PATTERNS,rt as MemoryEngine,Lt as MockAIProvider,zs as OtpHandler,G as PROMPT_ACTION_PATTERNS,Ke as PromptRunner,Je as PromptTestError,At as QaReporter,Os as RestartAppHandler,Xs as RunJsHandler,Hi as STEP_HANDLER_REGISTRY,fi as STEP_PREFIX_REGEX,yi as SUBMIT_KEYWORDS,Is as ScrollHandler,Ms as SelectHandler,pt as SemanticFormFiller,Vs as SetVariableHandler,_t as SpecRecursionError,Ns as SwipeHandler,ks as TapHandler,Fs as TerminateAppHandler,Ls as ToggleHandler,qt as TypeHandler,Un as VOLATILE_DATA_PATTERNS,$s as VerifyHandler,Us as WaitHandler,Ws as WaitUntilHandler,Ht as XML_HIERARCHY_PATTERNS,yt as acquireDeviceLock,Bn as assembleAstBlocks,Ss as baselineManager,Ni as buildDiagnosticError,oi as buildFeedbackUrl,hr as buildIssueUrl,tn as calculatePercentile,on as calculateReleaseConfidence,Pi as clusterSiblingElements,Ao as compareHierarchyNodes,Oe as computeCanonicalSemanticHash,be as computeHierarchyHash,Cd as createAndroidDriver,$d as createAutonomousExplorer,Ld as createAutonomousRecorder,Rd as createBaselineManager,Md as createFormFiller,Id as createMemoryEngine,Ad as createPromptRunner,Nd as createQaReporter,Qs as createSemanticResolver,Zt as createSyntheticReport,br as detectActiveEnvironment,us as detectNavigationParadigm,Ei as detectVisualDefects,ql as displayCrashTriage,Ts as expandSpecIncludes,bi as extractQuotedText,Ri as extractSpecTags,Qe as findActionButtons,Dt as findCheckableControls,bt as findClosestMatches,jt as findDevOverlay,st as findDrawerButton,vi as findErrorDialogs,yr as findExistingSpecs,xi as findHeaderActionButtons,Re as findInAppBackButton,ze as findInputFields,Bt as findListItems,Ut as findNavigationTabs,jr as findNodes,Ti as findScrollableContainers,Li as findTargetInputField,Cl as formatBenchmarkTable,Wi as formatDoctorReport,Oi as formatStepTable,Xl as generateAggregatedHtml,lr as generateSyntheticHierarchy,vl as getActiveConfig,ui as getJitteredPollDelay,Yt as getSeedSynonyms,mn as getSettleFactor,Kr as getSupportedLocales,Di as getSynonyms,ft as interpolateVariables,Be as isDestructiveAction,Ue as isExternalIntentAction,Zl as isFrameworkCrash,Me as isLogBoxNode,kn as levenshteinDistance,cr as loadConfig,Ge as logger,$o as maskSensitiveValue,Qt as matchNodes,pe as matchesText,Jl as mergeReports,Ii as normalizeSemanticText,oe as normalizeText,wi as parseBounds,we as parseHierarchyXml,An as parseHierarchyXmlRegex,$n as parseHierarchyXmlStreaming,Nt as parsePrompt,Mi as parseStepRange,Gr as registerLocalePack,St as releaseDeviceLock,xl as resetActiveConfig,ae as resolveTokenMatch,$l as runBenchmark,ss as runDoctor,ur as sanitizeStackTrace,Le as scaleSettle,mr as startFeedbackSession,yd as startInteractiveWizard,Gi as startLiveServer,nn as startRepl,Dn as stringSimilarity,si as summarizeMetrics,kt as unescapeXml};
|