rnxsim 0.1.317 → 0.1.319

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.
Files changed (183) hide show
  1. package/cli/bin.ts +1 -8
  2. package/cli/commands/debug.ts +1 -8
  3. package/cli/commands/detox.ts +16 -4
  4. package/cli/commands/flow.ts +1 -2
  5. package/cli/commands/inspect/wait-event.ts +1 -1
  6. package/cli/commands/inspect/wait-selector.ts +1 -1
  7. package/cli/commands/inspect.ts +56 -33
  8. package/cli/commands/maestro.ts +1 -1
  9. package/cli/commands/profile.ts +4 -6
  10. package/cli/commands/runtime.ts +0 -4
  11. package/cli/commands/storage.ts +1 -1
  12. package/cli/commands/telemetry.ts +0 -2
  13. package/cli/commands/timeline.ts +2 -4
  14. package/cli/parse-args.ts +0 -3
  15. package/detox/index.ts +155 -15
  16. package/detox/jest-preset.cjs +0 -1
  17. package/dist-cli/bin.js +5 -5
  18. package/dist-cli/chunks/{agent-EKGLRJEN.js → agent-Q4VAKGOL.js} +2 -2
  19. package/dist-cli/chunks/{agent-wrapper-FONNWB7J.js → agent-wrapper-Q2O4TR7H.js} +2 -2
  20. package/dist-cli/chunks/{app-fonts-XPM54HRY.js → app-fonts-B7UP3XTI.js} +2 -2
  21. package/dist-cli/chunks/{assert-PILHTZRZ.js → assert-NAFO4KMH.js} +2 -2
  22. package/dist-cli/chunks/{auth-Q2VUD5NQ.js → auth-CNUGYLCX.js} +2 -2
  23. package/dist-cli/chunks/{beta-P4XLZ3KL.js → beta-GN5BSED6.js} +2 -2
  24. package/dist-cli/chunks/{camera-O4PEVPI4.js → camera-EJRFUEXV.js} +2 -2
  25. package/dist-cli/chunks/{chunk-R6DDJVBB.js → chunk-2TNUPISH.js} +2 -2
  26. package/dist-cli/chunks/{chunk-BJ5CYKA7.js → chunk-3DEQXXSF.js} +4 -4
  27. package/dist-cli/chunks/{chunk-VB2ZZ4JI.js → chunk-3F3R7BM4.js} +2 -2
  28. package/dist-cli/chunks/{chunk-CUILVYWI.js → chunk-4UY4JSQ4.js} +1 -1
  29. package/dist-cli/chunks/chunk-522E7BRF.js +937 -0
  30. package/dist-cli/chunks/{chunk-NF63TOPI.js → chunk-5ABSWU6L.js} +2 -2
  31. package/dist-cli/chunks/{chunk-NA4AMR2E.js → chunk-5KXQT465.js} +1 -1
  32. package/dist-cli/chunks/{chunk-6WG4RQKM.js → chunk-6BGXKWGF.js} +2 -2
  33. package/dist-cli/chunks/{chunk-67ZR7PU7.js → chunk-72VB52IV.js} +1 -1
  34. package/dist-cli/chunks/{chunk-JQ4Y2XVT.js → chunk-76EVUPAL.js} +1 -1
  35. package/dist-cli/chunks/{chunk-OWADERTW.js → chunk-7DABL656.js} +2 -2
  36. package/dist-cli/chunks/{chunk-WWW5DC3G.js → chunk-7IW3PBRN.js} +2 -2
  37. package/dist-cli/chunks/{chunk-S23KHLTR.js → chunk-AX7PASOS.js} +2 -2
  38. package/dist-cli/chunks/{chunk-SZIPYT3D.js → chunk-AZ6S36CJ.js} +2 -2
  39. package/dist-cli/chunks/{chunk-T6W3B2KA.js → chunk-B27W3QWS.js} +1 -1
  40. package/dist-cli/chunks/{chunk-GQ3D2D4O.js → chunk-BQEWRZON.js} +1 -1
  41. package/dist-cli/chunks/{chunk-ADAIY3DX.js → chunk-BSCOA6LL.js} +2 -2
  42. package/dist-cli/chunks/{chunk-NUSBQSRQ.js → chunk-BVVUWEDG.js} +2 -2
  43. package/dist-cli/chunks/chunk-DD6F2WOA.js +4 -0
  44. package/dist-cli/chunks/{chunk-J4MCKLWE.js → chunk-DIADYUIH.js} +4 -4
  45. package/dist-cli/chunks/{chunk-KO7UG262.js → chunk-GHHVBATM.js} +2 -2
  46. package/dist-cli/chunks/{chunk-QCQQ2VDW.js → chunk-HCM7K4AU.js} +2 -2
  47. package/dist-cli/chunks/chunk-HPO2HNJX.js +124 -0
  48. package/dist-cli/chunks/{chunk-67OCUGZD.js → chunk-IHBAZ6ZJ.js} +2 -2
  49. package/dist-cli/chunks/{chunk-QGPNBTHT.js → chunk-IJYWC6QT.js} +2 -2
  50. package/dist-cli/chunks/{chunk-JZXCQEKO.js → chunk-JWAF5GXK.js} +2 -2
  51. package/dist-cli/chunks/{chunk-LSC2HFAB.js → chunk-JZIFPU64.js} +1 -1
  52. package/dist-cli/chunks/{chunk-RCPPPW7B.js → chunk-KMOLZN54.js} +1 -1
  53. package/dist-cli/chunks/{chunk-GMWPCQ63.js → chunk-L5JZXGYY.js} +1 -1
  54. package/dist-cli/chunks/{chunk-YRVJHPCU.js → chunk-LKO7E4VO.js} +2 -2
  55. package/dist-cli/chunks/{chunk-WJVNVBAI.js → chunk-M52VGRRN.js} +1 -1
  56. package/dist-cli/chunks/{chunk-7Q7IQ2SS.js → chunk-PFRV3TNY.js} +2 -2
  57. package/dist-cli/chunks/{chunk-3G7I72XV.js → chunk-PYDVLJOW.js} +2 -2
  58. package/dist-cli/chunks/{chunk-ATOUAYJP.js → chunk-QNNCKWZF.js} +1 -1
  59. package/dist-cli/chunks/{chunk-ODHQKXLB.js → chunk-R4JD7RQ5.js} +2 -2
  60. package/dist-cli/chunks/chunk-RIRZMX6H.js +4 -0
  61. package/dist-cli/chunks/{chunk-FIPCJ5OS.js → chunk-RVKU4F4H.js} +1 -1
  62. package/dist-cli/chunks/{chunk-A3GVXVSG.js → chunk-S5XIMHEZ.js} +2 -2
  63. package/dist-cli/chunks/{chunk-HJKQ6NEU.js → chunk-SPHYBQAZ.js} +2 -2
  64. package/dist-cli/chunks/chunk-TJSU45JD.js +4 -0
  65. package/dist-cli/chunks/{chunk-R6MEMDNB.js → chunk-UGYANOZR.js} +2 -2
  66. package/dist-cli/chunks/{chunk-W4YHMJOO.js → chunk-VB6FBQBW.js} +2 -2
  67. package/dist-cli/chunks/{chunk-5XVHBFAT.js → chunk-VLT3KCQT.js} +3 -3
  68. package/dist-cli/chunks/{chunk-OO5D7IJE.js → chunk-VQJMFDUN.js} +1 -1
  69. package/dist-cli/chunks/{chunk-EL23MRFL.js → chunk-WUZNWEBT.js} +1 -1
  70. package/dist-cli/chunks/{chunk-5BYFLVSZ.js → chunk-X2AHIPGY.js} +1 -1
  71. package/dist-cli/chunks/{chunk-OXSCF4UD.js → chunk-XJHAGKJD.js} +2 -2
  72. package/dist-cli/chunks/{chunk-RG3CME4Y.js → chunk-YPDFFAE7.js} +2 -2
  73. package/dist-cli/chunks/{chunk-HF4NZ5SD.js → chunk-YS6EWKGV.js} +2 -2
  74. package/dist-cli/chunks/{chunk-2SAOKV6V.js → chunk-YT6RDBLT.js} +1 -1
  75. package/dist-cli/chunks/{chunk-KZS5VM6Y.js → chunk-Z4LSUN4M.js} +1 -1
  76. package/dist-cli/chunks/{chunk-TUFL7CQK.js → chunk-Z72QDFQG.js} +2 -2
  77. package/dist-cli/chunks/{chunk-ARICQ4CG.js → chunk-ZH5X2H73.js} +2 -2
  78. package/dist-cli/chunks/{cleanup-O6IWLGDY.js → cleanup-GBLORG7C.js} +2 -2
  79. package/dist-cli/chunks/cli-version-6C4ZR7I7.js +4 -0
  80. package/dist-cli/chunks/{compat-562BT6JM.js → compat-OIWTQTTQ.js} +2 -2
  81. package/dist-cli/chunks/{config-7RO6O45J.js → config-DZCL6YFH.js} +2 -2
  82. package/dist-cli/chunks/{control-XYKZG442.js → control-MY5IZSCI.js} +2 -2
  83. package/dist-cli/chunks/daemon-42K3PILG.js +4 -0
  84. package/dist-cli/chunks/{debug-3VCEOVRM.js → debug-6UQUAZKP.js} +4 -4
  85. package/dist-cli/chunks/{desktop-K3PPS6VL.js → desktop-DFBFLSQ3.js} +3 -3
  86. package/dist-cli/chunks/detox-CIHUJOCI.js +52 -0
  87. package/dist-cli/chunks/{device-NZCR7JIN.js → device-7SOHSSJO.js} +2 -2
  88. package/dist-cli/chunks/{diagnose-VVJY6RF2.js → diagnose-P2FMX5HU.js} +2 -2
  89. package/dist-cli/chunks/{disk-cleanup-2VJMHUIY.js → disk-cleanup-6PP5CQVO.js} +2 -2
  90. package/dist-cli/chunks/drivers-CFJGYQFX.js +4 -0
  91. package/dist-cli/chunks/{film-CEMBA2DA.js → film-2WWHMPGU.js} +3 -3
  92. package/dist-cli/chunks/flow-KL7ZTVKL.js +4 -0
  93. package/dist-cli/chunks/help-T2OCMQPI.js +4 -0
  94. package/dist-cli/chunks/hidden-runtime-alias-ZZMC3E6R.js +4 -0
  95. package/dist-cli/chunks/{home-paths-TKPTU62O.js → home-paths-Y6X4LFSU.js} +2 -2
  96. package/dist-cli/chunks/inspect-PVMJQHMF.js +4 -0
  97. package/dist-cli/chunks/install-desktop-NHQZI4EH.js +4 -0
  98. package/dist-cli/chunks/{login-CIQT627K.js → login-BARKKDRL.js} +4 -4
  99. package/dist-cli/chunks/{logout-V2DJVY3U.js → logout-YVUMTGMP.js} +2 -2
  100. package/dist-cli/chunks/{maestro-YSZ6ZC5C.js → maestro-UPVELJ7G.js} +7 -7
  101. package/dist-cli/chunks/{maestro-generate-6JUELIXK.js → maestro-generate-EP76F4GB.js} +3 -3
  102. package/dist-cli/chunks/{mode-D4HQ6YN3.js → mode-ULOBJKDO.js} +2 -2
  103. package/dist-cli/chunks/{optional-demo-registry-AC6YJKT4.js → optional-demo-registry-O6RANNU3.js} +2 -2
  104. package/dist-cli/chunks/{perf-5GRZ4G5X.js → perf-ANPUHMRS.js} +2 -2
  105. package/dist-cli/chunks/{permissions-4V6UVWGK.js → permissions-NGMRAUGD.js} +2 -2
  106. package/dist-cli/chunks/{record-IDNLOQLR.js → record-CBO3QGRB.js} +3 -3
  107. package/dist-cli/chunks/{report-issue-TF6R77TT.js → report-issue-K7XKNJ2D.js} +2 -2
  108. package/dist-cli/chunks/reset-FXAX2W5A.js +4 -0
  109. package/dist-cli/chunks/runtime-GNCU66RR.js +4 -0
  110. package/dist-cli/chunks/{screenshot-command-CHJN7WUT.js → screenshot-command-KZZSYRX5.js} +3 -3
  111. package/dist-cli/chunks/{screenshot-layers-MSDCGYNE.js → screenshot-layers-Z3KSMJ3R.js} +2 -2
  112. package/dist-cli/chunks/{screenshots-capture-OGP3OQYR.js → screenshots-capture-QTB5GQNA.js} +2 -2
  113. package/dist-cli/chunks/{serve-GPBLCMXX.js → serve-JKTMCDG2.js} +2 -2
  114. package/dist-cli/chunks/{setup-S2KYWZZO.js → setup-GCAPEHZH.js} +2 -2
  115. package/dist-cli/chunks/{skills-AUS5DTUE.js → skills-Y4YDYEKA.js} +2 -2
  116. package/dist-cli/chunks/{state-QLYTMIKF.js → state-3HTG2CZU.js} +2 -2
  117. package/dist-cli/chunks/storage-XQE2XZJM.js +37 -0
  118. package/dist-cli/chunks/store-22QXHYUS.js +4 -0
  119. package/dist-cli/chunks/telemetry-VYGOHQWW.js +4 -0
  120. package/dist-cli/chunks/{timeline-EUHPXPFP.js → timeline-XYACO63Y.js} +3 -3
  121. package/dist-cli/chunks/{upgrade-JMMBM3ZN.js → upgrade-EVQTCUSG.js} +2 -2
  122. package/dist-cli/chunks/upload-XH3RQR4U.js +4 -0
  123. package/dist-cli/chunks/{version-QCF7RCA2.js → version-NLGYSRXS.js} +2 -2
  124. package/dist-cli/chunks/{web-WPYHMOVH.js → web-25OBFWDS.js} +2 -2
  125. package/dist-cli/chunks/{what-happened-3RNZP4MB.js → what-happened-MRN6CH5W.js} +2 -2
  126. package/dist-lib/agent-daemon-client.cjs +1 -1
  127. package/dist-lib/agent-events.cjs +1 -1
  128. package/dist-lib/agent-identity.cjs +1 -1
  129. package/dist-lib/agent-sessions.cjs +1 -1
  130. package/dist-lib/attached-projects.cjs +1 -1
  131. package/dist-lib/auth/shared-session.cjs +1 -1
  132. package/dist-lib/backend-origin.cjs +1 -1
  133. package/dist-lib/beta.cjs +1 -1
  134. package/dist-lib/beta.mjs +1 -1
  135. package/dist-lib/bridge-constants.cjs +1 -1
  136. package/dist-lib/bridge-contract.cjs +1 -1
  137. package/dist-lib/cli-constants.cjs +1 -1
  138. package/dist-lib/config.cjs +1 -1
  139. package/dist-lib/detox/index.cjs +93 -11
  140. package/dist-lib/detox/jest-preset.cjs +0 -1
  141. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  142. package/dist-lib/home-paths.cjs +1 -1
  143. package/dist-lib/host/bridge-host.cjs +1 -1
  144. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  145. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  146. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  147. package/dist-lib/host/websocket-proxy.cjs +1 -1
  148. package/dist-lib/index.cjs +1 -1
  149. package/dist-lib/jump-to-source-babel.cjs +1 -1
  150. package/dist-lib/menu.cjs +1 -1
  151. package/dist-lib/menu.mjs +1 -1
  152. package/dist-lib/metro.cjs +1 -1
  153. package/dist-lib/profiles.cjs +1 -1
  154. package/dist-lib/public-brand.cjs +1 -1
  155. package/dist-lib/render-mode.cjs +1 -1
  156. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  157. package/dist-lib/sdk.cjs +1 -1
  158. package/dist-lib/sdk.mjs +1 -1
  159. package/dist-lib/skills.cjs +62 -28
  160. package/dist-lib/vite.cjs +1 -1
  161. package/package.json +1 -1
  162. package/skills/contrast/SKILL.md +0 -1
  163. package/skills/rnx-perf/SKILL.md +17 -0
  164. package/src/vite-plugin.ts +74 -43
  165. package/dist-cli/chunks/chunk-744422UA.js +0 -4
  166. package/dist-cli/chunks/chunk-CHKTOWRH.js +0 -939
  167. package/dist-cli/chunks/chunk-O6OIXJ54.js +0 -4
  168. package/dist-cli/chunks/chunk-VUKB6JW3.js +0 -125
  169. package/dist-cli/chunks/cli-version-F2R7SUY7.js +0 -4
  170. package/dist-cli/chunks/daemon-WE37QLQC.js +0 -4
  171. package/dist-cli/chunks/detox-6ODNKASO.js +0 -52
  172. package/dist-cli/chunks/drivers-44ZJZ37B.js +0 -4
  173. package/dist-cli/chunks/flow-ORGIXYVS.js +0 -4
  174. package/dist-cli/chunks/help-UW52M7FZ.js +0 -4
  175. package/dist-cli/chunks/hidden-runtime-alias-R2QQLZZA.js +0 -4
  176. package/dist-cli/chunks/inspect-TNFI6C6G.js +0 -4
  177. package/dist-cli/chunks/install-desktop-NEJEPL4L.js +0 -4
  178. package/dist-cli/chunks/reset-D7WAFOZO.js +0 -4
  179. package/dist-cli/chunks/runtime-O5TNQBYH.js +0 -4
  180. package/dist-cli/chunks/storage-2MNS4TYO.js +0 -37
  181. package/dist-cli/chunks/store-UT52X7AA.js +0 -4
  182. package/dist-cli/chunks/telemetry-CAQVTTHY.js +0 -4
  183. package/dist-cli/chunks/upload-CEX4UBJL.js +0 -4
@@ -0,0 +1,937 @@
1
+ /*! rnx v0.1.319 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{b as jt,c as qt}from"./chunk-WUZNWEBT.js";import{a as Dt,b as Bt}from"./chunk-VQJMFDUN.js";import{a as de}from"./chunk-2TNUPISH.js";import{k as Ct}from"./chunk-SPHYBQAZ.js";import{a as oe,b as C,c as B,d as Me,e as ae,f as X,g as pe,h as ye,i as Et,j as At,k as Ne,l as _t}from"./chunk-YS6EWKGV.js";import{A as Mt,B as Nt,C as Ft,F as Ot,H as Pt,J as ue,K as Rt,Q as We,a as Ie,b as mt,c as ft,d as gt,e as yt,f as ht,g as bt,h as wt,i as xt,j as $t,k as Ce,l as je,r as qe,s as St,t as vt,u as ge,v as kt,w as Te,x as Le,y as It,z as Tt}from"./chunk-Z4LSUN4M.js";import{a as st}from"./chunk-DD6F2WOA.js";import{a as Q}from"./chunk-Z72QDFQG.js";import{e as it,j as at,o as lt,q as ct,s as dt,t as ut,u as pt,v as ce}from"./chunk-S5XIMHEZ.js";import{c as nt,d as Be,f as rt}from"./chunk-HPO2HNJX.js";function Je(e){return`(async () => {
5
+ const bridge = globalThis.SootSim && globalThis.SootSim.bridges && globalThis.SootSim.bridges.hotRemount
6
+ if (!bridge || typeof bridge.reloadExternalApp !== 'function') return false
7
+ await bridge.reloadExternalApp({ resetStorage: ${e?"true":"false"} })
8
+ return true
9
+ })()`}import{existsSync as Bo,mkdirSync as Wt,readFileSync as Co,rmSync as Ke,writeFileSync as Jt}from"fs";import{tmpdir as jo}from"os";import{dirname as Ht,join as qo,resolve as Kt}from"path";import*as Fe from"fs";function Do(e){let t={},s=e,i=p=>Array.isArray(p)?p:[],d=e.match(/^---\n([\s\S]*?)\n---\n?/);if(d){try{t=de.parse(d[1])??{}}catch(b){console.warn(` warn: could not parse frontmatter: ${b.message}`)}s=e.slice(d[0].length);let p=de.parse(s);return{frontmatter:t,steps:i(p)}}if(/\n---\s*\n/.test(e))try{let p=de.parseAllDocuments(e);if(p.length>=2){let b=p[0].toJS(),h=p[p.length-1].toJS();return{frontmatter:b&&typeof b=="object"?b:{},steps:i(h)}}}catch(p){console.warn(` warn: could not parse multi-doc flow: ${p.message}`)}let r=de.parse(s);return{frontmatter:t,steps:i(r)}}var Lt=new Set(["tapOn","inputText","pressKey","dispatchKey","hideKeyboard","swipe","pinch","scroll","scrollUntilVisible"]);function He(e){let t=[];if(!Array.isArray(e)||e.length===0)return t.push("flow body must be a non-empty YAML array of steps"),t;let s=0;for(let i of e)i&&typeof i=="object"?Object.keys(i).some(r=>Lt.has(r))&&(s+=1):typeof i=="string"&&Lt.has(i)&&(s+=1);return s===0&&t.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),t}function Ps(e){if(!Fe.existsSync(e))return[`file not found: ${e}`];let t;try{t=Fe.readFileSync(e,"utf8")}catch(s){return[`cannot read file: ${s.message}`]}if(t.trim().length===0)return["file is empty"];try{let s=Do(t);return He(s.steps)}catch(s){return[`yaml parse error: ${s.message}`]}}var Ue=1;function Oe(){return Kt(process.env.SOOTSIM_FLOW_SESSION_PATH||qo(jo(),"sootsim-flow-session.json"))}function Ge(e){let t=Oe();Wt(Ht(t),{recursive:!0}),Jt(t,JSON.stringify(e,null,2)+`
10
+ `)}function Ye(){let e=Oe();if(!Bo(e))return null;try{let t=JSON.parse(Co(e,"utf8"));return t.version!==Ue||!Array.isArray(t.steps)||typeof t.startedAt!="string"||typeof t.updatedAt!="string"?(Ke(e,{force:!0}),null):{version:Ue,startedAt:t.startedAt,updatedAt:t.updatedAt,steps:t.steps,candidate:t.candidate??null}}catch{return Ke(e,{force:!0}),null}}function Cs(){let e=new Date().toISOString(),t={version:Ue,startedAt:e,updatedAt:e,steps:[],candidate:null};return Ge(t),{path:Oe(),state:t}}function Lo(){Ke(Oe(),{force:!0})}function js(){Lo()}function Pe(e){let t=Ye();if(!t)return{active:!1};let s=t.candidate,i={...t,updatedAt:new Date().toISOString(),candidate:{step:e.step,summary:e.summary,source:e.source,recordedAt:new Date().toISOString()}};return Ge(i),{active:!0,candidate:i.candidate,replaced:s}}function qs(){let e=Ye();if(!e)return{active:!1,kept:!1,reason:"no-session"};if(!e.candidate)return{active:!0,kept:!1,reason:"no-candidate"};let t=e.candidate,s={...e,updatedAt:new Date().toISOString(),steps:[...e.steps,t.step],candidate:null};return Ge(s),{active:!0,kept:!0,candidate:t,stepCount:s.steps.length}}function Wo(e){return de.stringify(e).trimEnd()+`
11
+ `}function Ls(e){let t=Ye();if(!t)return{active:!1};let s=Wo(t.steps),i=He(t.steps);if(i.length>0)return{active:!0,valid:!1,issues:i,yaml:s,stepCount:t.steps.length,outputPath:null};let d=null;return e&&(d=Kt(e),Wt(Ht(d),{recursive:!0}),Jt(d,s)),{active:!0,valid:!0,issues:[],yaml:s,stepCount:t.steps.length,outputPath:d}}import{existsSync as Jo,mkdirSync as Ho,readFileSync as Ko,rmSync as Ut,writeFileSync as Uo}from"fs";import{tmpdir as Go}from"os";import{dirname as Yo,join as zo,resolve as Xo}from"path";var he=1,Vo="SOOTSIM_INSPECT_NOTICE_PATH",Qo=300*1e3,Zo=15e3;function Gt(){return Xo(process.env[Vo]||zo(Go(),"sootsim-inspect-notice-state.json"))}function es(e,t){return Object.fromEntries(Object.entries(e).filter(([,s])=>typeof s?.signature=="string"&&Number.isFinite(s?.updatedAt)&&t-s.updatedAt<=Qo))}function ts(e){let t=Gt();if(!Jo(t))return{version:he,entries:{}};try{let s=JSON.parse(Ko(t,"utf8"));return s.version!==he||!s.entries||typeof s.entries!="object"?(Ut(t,{force:!0}),{version:he,entries:{}}):{version:he,entries:es(s.entries,e)}}catch{return Ut(t,{force:!0}),{version:he,entries:{}}}}function os(e){let t=Gt();Ho(Yo(t),{recursive:!0}),Uo(t,JSON.stringify(e,null,2)+`
12
+ `)}function ss(e,t){let s=t.trim()||"default";return`${e}:${s}`}function ze(e,t,s,i={}){let d=i.nowMs??Date.now(),r=i.cooldownMs??Zo,p=ts(d),b=ss(e,t),h=p.entries[b];return h&&h.signature===s&&d-h.updatedAt<r?!1:(p.entries[b]={signature:s,updatedAt:d},os(p),!0)}async function se({bridge:e,simId:t,maxMs:s,pollMs:i=50,stablePolls:d=3,strict:r=!1}){let p=await e.send({type:"evaluate",simId:t,code:`(async () => {
13
+ const start = Date.now()
14
+ const deadline = start + ${Math.max(0,Math.round(s))}
15
+ const pollMs = ${Math.max(1,Math.round(i))}
16
+ const requiredStablePolls = ${Math.max(1,Math.round(d))}
17
+ const strict = ${r?"true":"false"}
18
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
19
+
20
+ // route-aware settle: a tap that pushes/pops a screen is async \u2014 the
21
+ // old screen still renders for a moment, then the new one mounts and
22
+ // its content loads. a pure layout-hash check reports "idle" on the
23
+ // outgoing screen or on the incoming skeleton, so a driver re-taps
24
+ // and stacks duplicate navigations. drain any in-flight screen
25
+ // transition FIRST, bounded by the overall budget. when no
26
+ // transition is happening this returns in ~80ms (startWindowMs), so
27
+ // a plain button tap barely pays for it.
28
+ try {
29
+ const wfst = window.__sootsimTest?.waitForScreenTransitions
30
+ if (typeof wfst === 'function') {
31
+ const remaining = deadline - Date.now()
32
+ if (remaining > 120) {
33
+ await wfst({
34
+ timeoutMs: Math.min(remaining - 80, 4000),
35
+ settleMs: 64,
36
+ startWindowMs: 80,
37
+ })
38
+ }
39
+ }
40
+ } catch {}
41
+
42
+ const readSnapshot = async () => {
43
+ let animating = false
44
+ let pendingFetches = 0
45
+ let requestTotal = 0
46
+ let requestInFlight = 0
47
+ try {
48
+ const stats = await window.__sootsimRenderHost?.queryStats?.()
49
+ if (stats) {
50
+ animating =
51
+ stats.hasActiveAnims === true ||
52
+ stats.hasActiveNativeAnimations === true ||
53
+ stats.hasPendingAnimationFrames === true
54
+ // a freshly-pushed screen showing a skeleton is layout-stable
55
+ // but not actually settled \u2014 its data/images are still in
56
+ // flight. treat bounded image-loader fetches as not-idle so
57
+ // settle waits for real content, capped by the budget.
58
+ const pf = stats.memory && stats.memory.imageLoader
59
+ ? stats.memory.imageLoader.pendingFetches
60
+ : 0
61
+ pendingFetches = typeof pf === 'number' ? pf : 0
62
+ }
63
+ } catch {}
64
+ try {
65
+ const counts = await window.__sootsimTest?.getRequestCounts?.()
66
+ requestTotal = typeof counts?.total === 'number' ? counts.total : 0
67
+ requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight : 0
68
+ } catch {}
69
+ const root = window.__sootsimRoot
70
+ const nodes = []
71
+ if (root) {
72
+ const walk = (n) => {
73
+ if (n.layout && n.layout.width > 0) {
74
+ nodes.push(Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width))
75
+ }
76
+ for (const c of n.children || []) walk(c)
77
+ }
78
+ walk(root)
79
+ }
80
+ return { layout: nodes.join(';'), animating, pendingFetches, requestTotal, requestInFlight }
81
+ }
82
+
83
+ // how long generic background network is allowed to keep us waiting AFTER
84
+ // the screen is otherwise visually settled. apps with continuous traffic
85
+ // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
86
+ // requestInFlight===0 / a stable requestTotal, so requiring full network
87
+ // quiet burns the ENTIRE budget on every command \u2014 the leading idle that
88
+ // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
89
+ // layout-stability + the image-loader already prove visible content
90
+ // loaded (a data load changes layout; an image load shows in the loader),
91
+ // so the generic request counters are a courtesy, not a gate: honor them
92
+ // only within this grace once the screen is visually still.
93
+ const networkQuietGraceMs = 1200
94
+ let lastLayout = ''
95
+ let lastRequestTotal = -1
96
+ let stable = 0
97
+ let visuallyStillSince = 0
98
+ while (Date.now() < deadline) {
99
+ const snapshot = await readSnapshot()
100
+ const strictOk = !strict || !snapshot.animating
101
+ // visually settled: no animations, no image content loading, layout
102
+ // unchanged since the last poll.
103
+ const visuallyStill =
104
+ strictOk && snapshot.pendingFetches === 0 && snapshot.layout === lastLayout
105
+ // generic network quiet: nothing in flight and no new requests issued.
106
+ const networkQuiet =
107
+ snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
108
+ if (visuallyStill) {
109
+ stable++
110
+ if (visuallyStillSince === 0) visuallyStillSince = Date.now()
111
+ // settle once the screen has held still long enough AND either the
112
+ // network is genuinely quiet OR it has refused to quiet within the
113
+ // grace (continuous background traffic must not block forever).
114
+ if (
115
+ stable >= requiredStablePolls &&
116
+ (networkQuiet || Date.now() - visuallyStillSince >= networkQuietGraceMs)
117
+ ) {
118
+ return { settled: true, elapsed: Date.now() - start }
119
+ }
120
+ } else {
121
+ stable = 0
122
+ visuallyStillSince = 0
123
+ }
124
+ lastLayout = snapshot.layout
125
+ lastRequestTotal = snapshot.requestTotal
126
+ await sleep(pollMs)
127
+ }
128
+ return { settled: false, elapsed: Date.now() - start }
129
+ })()`},{timeoutMs:s+1e3}),{elapsed:b,settled:h}=p??{};return{elapsed:typeof b=="number"?b:s,settled:h===!0}}var Re=`(() => {
130
+ const spec = window.SootSim?.state?.engineSnapshot?.windowState?.deviceSpec
131
+ return spec && spec.width > 0 && spec.height > 0
132
+ ? { width: spec.width, height: spec.height }
133
+ : null
134
+ })()`,ns={initialWaitMs:3e3,deadlineMs:5e3,retryWaitMs:700},rs={initialWaitMs:1200,deadlineMs:2500,retryWaitMs:700};function is(e,t={}){return{...e?ns:rs,...t}}function me(e){return!(!e||e.hit===!1||e.ok===!1||e.requestedTargetMatched===!1||e.pointerTapHandled===!1&&!e.keyboardOpened&&!e.isTextInput)}function as(e,t){return{nodeId:e.target?.nodeId??e.match?.nodeId??e.node?.nodeId??null,id:e.target?.id??e.match?.id??e.node?.id??null,testID:e.target?.testID??e.match?.testID??e.node?.testID??null,text:e.target?.text??e.target?.accessibilityLabel??e.match?.text??e.match?.accessibilityLabel??e.node?.text??t??null,type:e.target?.type??e.match?.type??e.node?.type??null}}async function be(e,t){let s=is(!!t.agent,t.timing),i=0,d=null,r=null;try{await se({bridge:e,maxMs:s.initialWaitMs,pollMs:32,stablePolls:2})}catch{}let p=Date.now()+s.deadlineMs,b=null;for(;Date.now()<=p||i===0;){i++;let h=await t.resolve();if(d=h,h?.error==="bridge-not-ready"||h?.ambiguous||h?.nthOutOfRange)return{payload:h,result:null,attempts:i,failure:"special"};if(h&&typeof h.cx=="number"&&typeof h.cy=="number")if(h.offscreen){r={hit:!1,reason:"offscreen",x:h.cx,y:h.cy,screen:h.screen};let w=`${Math.round(h.cx)},${Math.round(h.cy)}`;if(b===w)return{payload:h,result:r,attempts:i,failure:"missed"};b=w}else{b=null;let w=as(h,t.textFallback),g=await e.send({type:"evaluate",code:`(async () => {
135
+ const t = window.__sootsimTest
136
+ if (
137
+ !t ||
138
+ typeof t.inspectAt !== 'function' ||
139
+ typeof t.resolveTapTarget !== 'function'
140
+ ) {
141
+ return { error: 'tap-target-inspection-unavailable' }
142
+ }
143
+ const requestedTarget = ${JSON.stringify(w)}
144
+ const inspected = await t.inspectAt(${h.cx}, ${h.cy})
145
+ const resolved =
146
+ inspected && typeof inspected.nodeId === 'number'
147
+ ? await t.resolveTapTarget(inspected.nodeId)
148
+ : null
149
+ const node = (resolved && resolved.target) || inspected
150
+ const coordinateTarget = node
151
+ ? {
152
+ nodeId: node.nodeId ?? null,
153
+ id: node.id ?? null,
154
+ testID: node.testID ?? null,
155
+ text: node.text ?? node.accessibilityLabel ?? null,
156
+ type: node.type ?? null,
157
+ }
158
+ : null
159
+ const coordinateAncestors = Array.isArray(inspected?.ancestors)
160
+ ? inspected.ancestors
161
+ : []
162
+ const ancestorMatchesRequested = coordinateAncestors.some(
163
+ (ancestor) =>
164
+ (typeof requestedTarget.nodeId === 'number' &&
165
+ ancestor?.nodeId === requestedTarget.nodeId) ||
166
+ (requestedTarget.testID &&
167
+ ancestor?.testID === requestedTarget.testID) ||
168
+ (requestedTarget.id && ancestor?.id === requestedTarget.id),
169
+ )
170
+ const requestedTargetMatched =
171
+ coordinateTarget === null
172
+ ? false
173
+ : typeof requestedTarget.nodeId === 'number' &&
174
+ typeof coordinateTarget.nodeId === 'number'
175
+ ? requestedTarget.nodeId === coordinateTarget.nodeId ||
176
+ ancestorMatchesRequested
177
+ : requestedTarget.testID && coordinateTarget.testID
178
+ ? requestedTarget.testID === coordinateTarget.testID
179
+ || ancestorMatchesRequested
180
+ : requestedTarget.id && coordinateTarget.id
181
+ ? requestedTarget.id === coordinateTarget.id
182
+ || ancestorMatchesRequested
183
+ : ancestorMatchesRequested
184
+ if (!requestedTargetMatched) {
185
+ return {
186
+ requestedTargetMatched,
187
+ requestedTarget,
188
+ coordinateTarget,
189
+ }
190
+ }
191
+ if (typeof t.activatePressAt !== 'function') {
192
+ return { error: 'tap-target-activation-unavailable' }
193
+ }
194
+ const activation = await t.activatePressAt(
195
+ ${h.cx},
196
+ ${h.cy},
197
+ requestedTarget.nodeId,
198
+ )
199
+ if (activation?.ok) {
200
+ window.dispatchEvent(
201
+ new CustomEvent('sootsim:agentAction', {
202
+ detail: {
203
+ type: 'tap',
204
+ x: ${h.cx},
205
+ y: ${h.cy},
206
+ target: requestedTarget,
207
+ },
208
+ }),
209
+ )
210
+ }
211
+ return {
212
+ activation,
213
+ requestedTargetMatched,
214
+ requestedTarget,
215
+ coordinateTarget,
216
+ }
217
+ })()`});if(g?.error)return{payload:h,result:{hit:!1,reason:g.error,requestedTarget:w},attempts:i,failure:"special"};if(g?.requestedTargetMatched===!1)return{payload:h,result:{hit:!1,reason:"target-covered",...g},attempts:i,failure:"missed"};let M=g?.activation?.tap??g?.activation,x=M&&typeof M=="object"?{...M,...g?.activation,...g}:{hit:!!M,...g};if(r=x,me(x))return{payload:h,result:x,attempts:i}}let I=p-Date.now();if(I<=0)break;try{await se({bridge:e,maxMs:Math.min(I,s.retryWaitMs),pollMs:32,stablePolls:2})}catch{await new Promise(w=>setTimeout(w,Math.min(120,I)))}}return{payload:d,result:r,attempts:i,failure:d&&typeof d.cx=="number"?"missed":"not-found"}}async function Yt(e,t,s,i){return e.send({type:"tap",x:t,y:s,...i?{target:i}:{}})}async function zt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,resolve:()=>e.send({type:"evaluate",code:`(async () => {
218
+ const t = window.__sootsimTest
219
+ if (!t) return null
220
+ const n = (await t.findByTestId(${i})) || (await t.findById(${i}))
221
+ if (!n || !n.absolutePosition || !n.layout) return { cx: null }
222
+ const resolved =
223
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
224
+ ? await t.resolveTapTarget(n.nodeId)
225
+ : null
226
+ const target = (resolved && resolved.target) || n
227
+ const cx =
228
+ resolved && typeof resolved.cx === 'number'
229
+ ? resolved.cx
230
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
231
+ const cy =
232
+ resolved && typeof resolved.cy === 'number'
233
+ ? resolved.cy
234
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
235
+ const scr = ${Re}
236
+ const offscreen =
237
+ !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
238
+ return {
239
+ cx,
240
+ cy,
241
+ ...(offscreen ? { offscreen: true, screen: scr } : {}),
242
+ match: {
243
+ nodeId: n.nodeId ?? null,
244
+ id: n.id,
245
+ testID: n.testID,
246
+ text: n.text ?? n.accessibilityLabel ?? null,
247
+ type: n.type,
248
+ },
249
+ target: {
250
+ nodeId: target.nodeId ?? null,
251
+ id: target.id,
252
+ testID: target.testID,
253
+ text:
254
+ target.text ??
255
+ target.accessibilityLabel ??
256
+ n.text ??
257
+ n.accessibilityLabel ??
258
+ null,
259
+ type: target.type,
260
+ },
261
+ strategy: (resolved && resolved.strategy) || 'matched-node',
262
+ }
263
+ })()`})})}async function Xt(e,t,s={},i={}){let d=JSON.stringify({query:t,exact:!!s.exact,role:s.role??null,within:s.within??null,minX:s.minX??null,maxX:s.maxX??null,minY:s.minY??null,maxY:s.maxY??null,near:s.near??null,nth:s.nth??null,first:!!s.first});return be(e,{agent:i.agent,timing:i.timing,textFallback:t,resolve:()=>e.send({type:"evaluate",code:`(async () => {
264
+ const t = window.__sootsimTest
265
+ if (!t) return { error: 'bridge-not-ready' }
266
+ const F = ${d}
267
+
268
+ const res = await t.queryTextCandidates({
269
+ query: F.query,
270
+ exact: !!F.exact,
271
+ ...(F.role ? { role: F.role } : {}),
272
+ })
273
+
274
+ let candidates = res.candidates || []
275
+
276
+ candidates = candidates.filter((c) => {
277
+ const ax = c.info.absolutePosition && c.info.absolutePosition.x
278
+ const ay = c.info.absolutePosition && c.info.absolutePosition.y
279
+ if (F.minX !== null && !(ax >= F.minX)) return false
280
+ if (F.maxX !== null && !(ax <= F.maxX)) return false
281
+ if (F.minY !== null && !(ay >= F.minY)) return false
282
+ if (F.maxY !== null && !(ay <= F.maxY)) return false
283
+ if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
284
+ return true
285
+ })
286
+
287
+ if (F.near) {
288
+ candidates.sort((a, b) => {
289
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
290
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
291
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
292
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
293
+ return (
294
+ Math.hypot(ax - F.near.x, ay - F.near.y) -
295
+ Math.hypot(bx - F.near.x, by - F.near.y)
296
+ )
297
+ })
298
+ } else {
299
+ candidates.sort((a, b) => {
300
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
301
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
302
+ if (Math.abs(ay - by) > 2) return ay - by
303
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
304
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
305
+ return ax - bx
306
+ })
307
+ }
308
+
309
+ const total = candidates.length
310
+ if (total === 0) return { matched: 0, total: 0 }
311
+
312
+ let idx = 0
313
+ if (F.nth !== null) {
314
+ idx = F.nth < 0 ? total + F.nth : F.nth
315
+ if (idx < 0 || idx >= total) {
316
+ return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
317
+ }
318
+ } else if (total > 1 && !F.first && !F.near) {
319
+ return {
320
+ ambiguous: true,
321
+ total,
322
+ candidates: candidates.slice(0, 10).map((c, i) => ({
323
+ idx: i,
324
+ nodeId: c.info.nodeId,
325
+ type: c.info.type,
326
+ testID: c.info.testID,
327
+ text: (c.info.text || '').slice(0, 60),
328
+ abs: c.info.absolutePosition,
329
+ layout: c.info.layout
330
+ ? {
331
+ width: Math.round(c.info.layout.width || 0),
332
+ height: Math.round(c.info.layout.height || 0),
333
+ }
334
+ : null,
335
+ ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
336
+ })),
337
+ }
338
+ }
339
+
340
+ const picked = candidates[idx]
341
+ const n = picked.info
342
+ if (!n.absolutePosition || !n.layout) return { matched: 0, total }
343
+
344
+ const resolved =
345
+ typeof n.nodeId === 'number' &&
346
+ typeof t.resolveTapTarget === 'function'
347
+ ? await t.resolveTapTarget(n.nodeId)
348
+ : null
349
+ const target = (resolved && resolved.target) || n
350
+ const cx =
351
+ resolved && typeof resolved.cx === 'number'
352
+ ? resolved.cx
353
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
354
+ const cy =
355
+ resolved && typeof resolved.cy === 'number'
356
+ ? resolved.cy
357
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
358
+ const scr = ${Re}
359
+ const offscreen =
360
+ !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
361
+ return {
362
+ cx,
363
+ cy,
364
+ ...(offscreen ? { offscreen: true, screen: scr } : {}),
365
+ match: {
366
+ nodeId: n.nodeId ?? null,
367
+ id: n.id,
368
+ testID: n.testID,
369
+ type: n.type,
370
+ },
371
+ target: {
372
+ nodeId: target.nodeId ?? null,
373
+ id: target.id,
374
+ testID: target.testID,
375
+ text:
376
+ target.text ??
377
+ target.accessibilityLabel ??
378
+ n.text ??
379
+ n.accessibilityLabel ??
380
+ null,
381
+ type: target.type,
382
+ },
383
+ strategy: (resolved && resolved.strategy) || 'matched-node',
384
+ total,
385
+ idx,
386
+ }
387
+ })()`})})}async function Vt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,textFallback:t,resolve:async()=>{let d=await e.send({type:"evaluate",code:`(async () => {
388
+ const t = window.__sootsimTest
389
+ if (!t) return { error: 'bridge-not-ready' }
390
+ const byTestId =
391
+ (await t.findByTestId(${i})) || (await t.findById(${i}))
392
+ if (byTestId && byTestId.absolutePosition && byTestId.layout) {
393
+ return {
394
+ strategy: 'testid',
395
+ node: {
396
+ nodeId: byTestId.nodeId ?? null,
397
+ id: byTestId.id,
398
+ testID: byTestId.testID,
399
+ type: byTestId.type,
400
+ text: byTestId.text,
401
+ absolutePosition: byTestId.absolutePosition,
402
+ layout: byTestId.layout,
403
+ },
404
+ screen: ${Re},
405
+ }
406
+ }
407
+ const byText = await t.findByText(${i})
408
+ if (byText && byText.absolutePosition && byText.layout) {
409
+ return {
410
+ strategy: 'text',
411
+ node: {
412
+ nodeId: byText.nodeId ?? null,
413
+ id: byText.id,
414
+ testID: byText.testID,
415
+ type: byText.type,
416
+ text: byText.text,
417
+ absolutePosition: byText.absolutePosition,
418
+ layout: byText.layout,
419
+ },
420
+ screen: ${Re},
421
+ }
422
+ }
423
+ return { strategy: 'none' }
424
+ })()`});if(!d||!("node"in d))return d;let r=d.node,p=r.absolutePosition.x+r.layout.width/2,b=r.absolutePosition.y+r.layout.height/2,h=d.screen??null,I=!!h&&(p<0||b<0||p>h.width||b>h.height);return{...d,cx:p,cy:b,...I?{offscreen:!0,screen:h}:{},target:{id:r.id,testID:r.testID,text:d.strategy==="text"?t:r.text,type:r.type}}}})}async function Qt(e,t={args:[]}){let s=await ft(e);if(C(t.args)){B(s);return}console.log(` nodes: ${s.nodes}`)}function Xe(e,t){let s=e.indexOf(t);return s>=0&&s+1<e.length?e[s+1]:null}async function Zt(e){let{bridge:t,args:s,positional:i}=e,d=s.includes("--verbose")||s.includes("-v"),r=C(s),p=d&&!r,b=s.includes("--watch")||s.includes("-w"),h=1e3,I=s.includes("--compact"),w=s.includes("--no-xy"),g=s.includes("--no-clipped"),M=s.includes("--include-occluded"),x=Xe(s,"--testid-like"),_=Xe(s,"--only"),O=Xe(s,"--subtree"),c=i[1]&&!i[1].startsWith("-")?i[1]:void 0,D=c?/[*?]/.test(c):!1,R=!D&&!_?c:void 0,A=_??(D?c:void 0),J=async()=>{await pe(t,{verbose:p});let T=await ht(t,{describe:!0,verbose:d,filter:R||"",testIdLike:x||void 0,onlyGlob:A||void 0,subtreeRoot:O||void 0,compact:I,hideXy:w,includeOccluded:M,fullText:r}),P=T?.tree,H=T?.shell,K=T?.keyboard;if(r){B({shell:H,tree:P??"",keyboard:K});return}if(H&&typeof H=="object"){let q=[H.state?`state=${H.state}`:null,H.activeApp?`app=${H.activeApp}`:null,H.showSwitcher?"switcher":null,H.switcherPhase&&H.switcherPhase!=="idle"?`phase=${H.switcherPhase}`:null].filter(Boolean);q.length>0&&console.log(` shell: ${q.join(" ")}`)}if(typeof P=="string"&&P.startsWith("__SUBTREE_NOT_FOUND__:")){let q=P.slice(22);console.log(` subtree root not found: ${q}`),Q("subtree-root-not-found",q);return}if(!P){let q=T?.nodeCount??0;console.log(" no matching nodes found"),!(R||x||A||O)&&q<10&&Q("app-still-loading",q);return}let ee=P,te=0;if(g&&typeof ee=="string"){let q=ee.split(`
425
+ `),le=[];for(let ve of q){if(ve.includes("(clipped:")){te+=1;continue}le.push(ve)}ee=le.join(`
426
+ `)}console.log(ee),te>0&&console.log(` ${te} clipped row(s) hidden (omit --no-clipped to see)`);let ie=R||x||A||O;if((R||x||A)&&!b&&Q("describe-filter-context"),!ie&&!b&&P.split(`
427
+ `).length>=80&&Q("describe-use-filters"),K&&K.visible){let q=K.spec,le=[q?.keyboardType?`type=${q.keyboardType}`:null,q?.returnKeyType&&q.returnKeyType!=="default"?`return=${q.returnKeyType}`:null,K.mode!=="letters"?`mode=${K.mode}`:null,K.shifted?"shift":null,K.capsLock?"caps":null,q?.autoCapitalize&&q.autoCapitalize!=="sentences"?`autoCap=${q.autoCapitalize}`:null,K.accessoryBarId?`accessory=${K.accessoryBarId}`:null].filter(Boolean);console.log(`
428
+ keyboard: ${le.join(" ")||"visible"}`)}};if(b)for(console.log(` watching... (Ctrl+C to stop)
429
+ `);;)console.clear(),await J(),await oe(h);else await J()}var ls=["SOOTSIM_AGENT","TM_SESSION","CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CURSOR_TRACE_ID","AIDER_MODEL"];function fe(){if(process.env.SOOTSIM_AGENT==="0")return!1;for(let e of ls){let t=process.env[e];if(t&&t.trim()&&t!=="0")return!0}return!1}async function eo(e){let{bridge:t,args:s,effectiveArgs:i,positional:d,inspectUsage:r}=e,p=T=>{let P=i.indexOf(T);return P>=0&&P+1<i.length?i[P+1]:null},b=T=>i.includes(T),h=p("--testid")||p("--test-id"),I=p("--role"),w=p("--type"),g=p("--text"),M=b("--pressable"),x=b("--visible"),_=b("--interactive-targets")||b("--actions"),O=!h&&!I&&!w&&!g&&!M&&!x&&!_?d[1]:null,c=g??O,D=await $t(t,{testId:h,role:I,type:w,text:c,pressable:M,visible:x,interactive:_});D||(console.error(r("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible | --interactive-targets")),process.exit(1));let{mode:R,result:A}=D,J=C(s),U=s.includes("--verbose")||s.includes("--dump");if(J)R==="interactive-targets"&&Array.isArray(A)?B(Ce(A).map(T=>({...T,tap:je(T)}))):B(A??null);else if(Array.isArray(A))if(A.length===0){console.log(` no ${R} nodes found`);let T=await t.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof T=="number"&&T<10&&Q("app-still-loading",T)}else if(R==="interactive-targets"){let T=Ce(A);console.log(` found ${T.length} interactive target${T.length===1?"":"s"} (sorted by score):`);for(let P of T.slice(0,20)){let H=P.absolutePosition?`@(${Math.round(P.absolutePosition.x)},${Math.round(P.absolutePosition.y)})`:"",K=P.layout?`${Math.round(P.layout.width)}x${Math.round(P.layout.height)}`:"?x?",ee=P.text?` "${P.text.slice(0,30)}"`:"",te=P.testID?` #${P.testID}`:"",ie=P.accessibilityLabel?` \u24D8"${String(P.accessibilityLabel).slice(0,24)}"`:"",Se=P.accessibilityRole?`[${P.accessibilityRole}]`:P.type,q=je(P);console.log(` ${Se}${ee}${ie}${te} ${K} ${H}`),console.log(` \u2192 ${q}`),U&&console.log(Ve(JSON.stringify(P,null,2)," "))}T.length>20&&console.log(` ... and ${T.length-20} more`)}else{console.log(` found ${A.length} node${A.length===1?"":"s"} (${R}):`);for(let T of A.slice(0,20)){let P=T.absolutePosition?`@(${Math.round(T.absolutePosition.x)},${Math.round(T.absolutePosition.y)})`:"",H=T.layout?`${Math.round(T.layout.width)}x${Math.round(T.layout.height)}`:"?x?",K=T.text?` "${T.text.slice(0,30)}"`:"",ee=T.testID?` #${T.testID}`:"",te=T.pressable?" (tap)":"",ie=T.accessibilityRole?`[${T.accessibilityRole}]`:T.type;console.log(` ${ie}${K}${ee} ${H} ${P}${te}`),U&&console.log(Ve(JSON.stringify(T,null,2)," "))}A.length>20&&console.log(` ... and ${A.length-20} more`)}else if(A==null)console.log(` not found: ${c||h||I||w||""||R}`),h&&Q("wait-selector-for-missing-testid",h);else{let T=A;if(T.type&&T.absolutePosition){let P=`@(${Math.round(T.absolutePosition.x)},${Math.round(T.absolutePosition.y)})`,H=T.layout?`${Math.round(T.layout.width)}x${Math.round(T.layout.height)}`:"?x?",K=T.text?` "${T.text.slice(0,40)}"`:"",ee=T.testID?` #${T.testID}`:"",te=T.pressable?" (tap)":"",ie=T.accessibilityRole?`[${T.accessibilityRole}]`:T.type;console.log(` ${ie}${K}${ee} ${H} ${P}${te}`),U&&console.log(Ve(JSON.stringify(T,null,2)," "))}else console.log(JSON.stringify(A,null,2))}}function Ve(e,t){return e.split(`
430
+ `).map(s=>t+s).join(`
431
+ `)}async function to(e){let{bridge:t,args:s}=e,i=C(s);await pe(t,{verbose:!i});let d=s.includes("--styling"),r=s.indexOf("--filter"),p=r>=0?s[r+1]:void 0,b=await bt(t,{styling:d,filter:p});if(i){B({count:b.length,elements:b});return}console.log(` layout (${b.length} element${b.length===1?"":"s"}):
432
+ `),console.log(wt(b,{styling:d}))}async function oo(e,t={}){let s=await Pt(e);if("error"in s&&(console.error(s.error),process.exit(1)),t.json){console.log(JSON.stringify(s,null,2));return}let{visible:i,spec:d,mode:r,shifted:p,capsLock:b,accessoryBarId:h}=s,I=[];I.push(`keyboard: ${i?"visible":"hidden"}`),d?(I.push(` type: ${d.keyboardType}`),I.push(` returnKey: ${d.returnKeyType}`),I.push(` autoCap: ${d.autoCapitalize}`),I.push(` autoCorrect: ${d.autoCorrect?"on":"off"}`),I.push(` appearance: ${d.keyboardAppearance}`),d.secureTextEntry&&I.push(" secureTextEntry: true"),d.enablesReturnKeyAutomatically&&I.push(` return: ${d.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):I.push(" spec: <none> (shown via dev-tools with no TextInput)"),I.push(` mode: ${r}${p?" (shifted)":""}${b?" (caps)":""}`),h&&I.push(` accessoryBar: ${h}`),console.log(I.join(`
433
+ `))}async function so(e){let t=await e.bridge.listSims(),s=e.args.includes("--all"),i=e.args.find((b,h)=>e.args[h-1]==="--bundle"),d=e.args.find((b,h)=>e.args[h-1]==="--app-port"),r=e.args.includes("--primary"),p=t.filter(b=>!(r&&!b.isPrimary||i&&!(b.url??"").includes(i)||d&&!(b.url??"").includes(`/rn/${d}`)||!s&&!i&&!d&&!r&&!(b.url&&(b.url.includes("bundle=")||b.url.includes("/index.bundle")))&&b.id!==e.simId));if(C(e.args)){B(p.map(b=>({...b,active:b.id===e.simId})));return}Ct(p,e.simId),p.length<t.length&&!C(e.args)&&console.log(` (${t.length-p.length} more hidden \u2014 pass --all to show)`)}function re(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function cs(e,t){return t<=0?"?":`${(e/t*100).toFixed(0)}%`}function ds(e){let t={},s=(i,d)=>{d&&(d.nodesRegistered!=null&&(t[`${i}.nodes`]=d.nodesRegistered),d.nodesDetached!=null&&(t[`${i}.detached`]=d.nodesDetached),d.objects&&(t[`${i}.paragraphs`]=d.objects.paragraphs,t[`${i}.yogaNodes`]=d.objects.yogaNodes,t[`${i}.pictures`]=d.objects.pictures,t[`${i}.rasterImages`]=d.objects.rasterImages),d.imageLoader&&(t[`${i}.imageCacheEntries`]=d.imageLoader.cacheEntries,t[`${i}.imagePixelBytes`]=d.imageLoader.cachePixelBytes),d.workerHeap&&(t[`${i}.heapBytes`]=d.workerHeap.usedJSHeapSize),d.wasmHeapBytes!=null&&(t[`${i}.wasmHeapBytes`]=d.wasmHeapBytes))};return s("tenant",e.tenant),s("shell",e.shell),s("compositor",e.compositor),e.hostHeap&&(t["host.heapBytes"]=e.hostHeap.usedJSHeapSize),t}function no(e,t){return e.endsWith("Bytes")?re(t):String(t)}function Qe(e,t){if(!t){console.log(` ${e}: not available`);return}let s=t.objects;if(console.log(` ${e}`),t.nodesRegistered!=null&&console.log(` nodes registered: ${t.nodesRegistered}`),t.nodesDetached!=null){let i=Object.entries(t.detachedTypes??{}).map(([d,r])=>`${d}:${r}`).join(" ");console.log(` nodes detached: ${t.nodesDetached}${i?` (${i})`:""}`)}if(s&&(console.log(` paragraphs: ${s.paragraphs}`),console.log(` yoga nodes: ${s.yogaNodes}`),console.log(` pictures: ${s.pictures}`),console.log(` raster images: ${s.rasterImages}`)),t.activeNativeAnimations!=null&&console.log(` native anims: ${t.activeNativeAnimations}`),t.imageLoader){let i=t.imageLoader;console.log(` image cache: ${i.cacheEntries}/${i.cacheMaxEntries} entries, ${re(i.cachePixelBytes)}/${re(i.cachePixelBudget)} (${cs(i.cachePixelBytes,i.cachePixelBudget)})`)}t.workerHeap&&console.log(` js heap: ${re(t.workerHeap.usedJSHeapSize)} used / ${re(t.workerHeap.totalJSHeapSize)} total`),t.wasmHeapBytes!=null&&console.log(` canvaskit wasm: ${re(t.wasmHeapBytes)}`)}function us(e){console.log(" memory:"),Qe("tenant worker",e.tenant),Qe("shell worker",e.shell),Qe("compositor worker",e.compositor),e.hostHeap?(console.log(" host"),console.log(` js heap: ${re(e.hostHeap.usedJSHeapSize)} used / ${re(e.hostHeap.totalJSHeapSize)} total`)):console.log(" host js heap: not available (chrome only)")}function ps(e,t,s){let i=e.indexOf(t);if(i===-1)return s;let d=Number(e[i+1]);return Number.isFinite(d)&&d>0?d:s}async function ro(e,t={args:[]}){let s=C(t.args),i=t.args.indexOf("--watch");if(i===-1){let O=await We(e);if(s){B(O);return}us(O);return}let d=Number(t.args[i+1]),r=Number.isFinite(d)&&d>0?d:60,p=ps(t.args,"--interval",5),b=[],h=Date.now(),I=null;for(s||console.log(` sampling every ${p}s for ${r}s \u2014 deltas per tick:`);;){let O=await We(e),c=(Date.now()-h)/1e3,D=ds(O);if(b.push({tSec:c,counters:D}),!s){let R=[];for(let[A,J]of Object.entries(D)){let U=I&&A in I?J-I[A]:null;if(U===null||U===0)continue;let T=U>0?"+":"-",P=A.endsWith("Bytes")?`${T}${re(Math.abs(U))}`:`${T}${Math.abs(U)}`;R.push(`${A} ${no(A,J)} (${P})`)}console.log(` t+${c.toFixed(0)}s ${R.length?R.join(" "):I?"no change":Object.entries(D).map(([A,J])=>`${A} ${no(A,J)}`).join(" ")}`)}if(I=D,c>=r)break;await new Promise(R=>setTimeout(R,p*1e3))}let w=b[0],g=b[b.length-1],M=Math.max(g.tSec-w.tSec,.001),x={};for(let O of Object.keys(g.counters))O in w.counters&&(x[O]=(g.counters[O]-w.counters[O])/M);if(s){B({samples:b,perSecond:x,elapsedSec:M});return}console.log(`
434
+ slope over ${M.toFixed(0)}s:`);let _=Object.entries(x).filter(([,O])=>O!==0).sort((O,c)=>Math.abs(c[1])-Math.abs(O[1]));if(_.length===0){console.log(" all counters flat");return}for(let[O,c]of _){let D=O.endsWith("Bytes")?`${re(Math.abs(c))}/s${c<0?" (shrinking)":""}`:`${c>0?"+":""}${c.toFixed(2)}/s`;console.log(` ${O.padEnd(28)}${D}`)}}var Z="<redacted secure text>";function we(e){let t=e?.layout?.spec??e?.spec??null;return!!t?.secureTextEntry&&t.keyboardType!=="visible-password"}function Ze(e,t){return we(t)?Z:e}function et(e){if(!e||!we(e))return e;let t=e.focusedInput;return!t||typeof t!="object"?e:{...e,focusedInput:{...t,secureTextEntry:!0,text:typeof t.text=="string"?Z:t.text}}}function xe(e,t){let s=e.indexOf("--testid");if(s>=0&&e[s+1])return{mode:"testid",value:e[s+1]};let i=e.indexOf("--test-id");if(i>=0&&e[i+1])return{mode:"testid",value:e[i+1]};let d=e.indexOf("--text");if(d>=0&&e[d+1])return{mode:"text",value:e[d+1]};let r=t?.[1];return r&&!r.startsWith("-")&&!Number.isFinite(Number(r))?{mode:"testid",value:r}:null}async function Ee(e,t){let s=JSON.stringify(t.value),i=t.mode==="testid"?`(await t.findByTestId(${s})) || (await t.findById(${s}))`:`await t.findByText(${s})`;return await e.send({type:"evaluate",code:`(async () => {
435
+ const t = window.__sootsimTest
436
+ if (!t) return null
437
+ const n = ${i}
438
+ if (!n || !n.absolutePosition || !n.layout) return null
439
+ const resolved =
440
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
441
+ ? await t.resolveTapTarget(n.nodeId)
442
+ : null
443
+ const cx =
444
+ typeof resolved?.cx === 'number'
445
+ ? resolved.cx
446
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
447
+ const cy =
448
+ typeof resolved?.cy === 'number'
449
+ ? resolved.cy
450
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
451
+ return {
452
+ x: cx,
453
+ y: cy,
454
+ id: n.id ?? null,
455
+ testID: n.testID ?? null,
456
+ text: ${JSON.stringify(t.mode==="text")} ? ${s} : (n.text ?? n.accessibilityLabel ?? null),
457
+ type: n.type ?? null,
458
+ }
459
+ })()`})??null}async function io(e,t={}){let{nav:s,route:i,keyboard:d,shell:r}=await Rt(e);if(t.json){console.log(JSON.stringify({shell:r??null,nav:s,route:i,keyboard:d},null,2));return}let p=[];if(r){let b=r.activeApp??r.state??"<none>",h=r.showSwitcher?" (app switcher open)":"",I=typeof r.launchProgress=="number"&&r.launchProgress<.98?` launching (${Math.round(r.launchProgress*100)}%)`:"";p.push(`shell: ${b}${h}${I}`)}else p.push("shell: <unavailable>");if(s){let b=s.transitionPhase!=="idle"?` (${s.transitionPhase}, ${s.activeTransitionCount} active)`:"";if(p.push(`nav: phase=${s.transitionPhase}${b}`),s.screens.length===0)p.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let h of s.screens){let I=h.isActive?"\u25B6":" ",w=h.routeName?` ${h.routeName}`:"",g=h.headerHeight>0?` header=${h.headerHeight}`:"",M=h.largeTitleState&&h.largeTitleState!=="expanded"?` large-title=${h.largeTitleState}`:"";p.push(` ${I} #${h.id}${w}${g}${M}`)}}else p.push("nav: <runtime not available>");if(p.push(`route: ${i?.currentPath??"<unavailable>"}`),i?.coveringPath&&p.push(`covered: a presented screen (${i.coveringPath}) is above this route`),d&&d.visible){let b=d.spec?.keyboardType??"default",h=d.spec?.returnKeyType??"default";p.push(`keyboard: visible (${b}, return=${h}, mode=${d.mode??"?"})`)}else p.push("keyboard: hidden");console.log(p.join(`
460
+ `))}async function ao(e){let{bridge:t,args:s,positional:i}=e,d=i[1]?Number(i[1])*1e3:3e3,r=s.includes("--strict"),{elapsed:p,settled:b}=await se({bridge:t,maxMs:d,strict:r});console.log(b?` settled in ${p}ms`:` timed out after ${p}ms (may still be animating)`)}async function lo(e){let t=e.positional[1]?Number(e.positional[1]):.5;(!Number.isFinite(t)||t<0)&&(console.error(e.inspectUsage("sleep","[seconds]")),process.exit(1)),await oe(t*1e3),console.log(` slept ${t}s`)}async function co(e){let{bridge:t,args:s,positional:i}=e,d=s.includes("--boxes"),r=i[1]?Number(i[1]):d?50:5,{tree:p}=await gt(t,r,d?{format:"boxes"}:void 0);if(C(s)){B({depth:r,tree:p??null});return}console.log(typeof p=="string"?p:JSON.stringify(p,null,2))}async function uo(e,t={args:[]}){let s=await yt(e);if(C(t.args)){B(s);return}console.log(s.url)}async function po(e){let{wsPort:t,commandTimeoutMs:s,simId:i,simIdSource:d,positional:r}=e,p=r[1]?Number(r[1]):30,b=Math.max(1e3,(Number.isFinite(p)?p:30)*1e3),h=Math.max(1,Math.ceil(b/500));console.log(" waiting for sim reconnect...");let I=await Et(t,s,i,{attempts:h,simIdSource:d});I||(console.error(" timed out waiting for sim reconnect"),process.exit(1)),I.bridge.close(),Pe({source:"inspect wait",step:{wait:b},summary:`wait ${Math.round(b/1e3)}s`}),console.log(` ready: ${I.count} nodes`)}var mo=new Set(["app-launch","toast","keyboard","screen","flow-step","route","alert","actionsheet","picker","notification","fetch","console","shell","scroll","gesture","text-input","react-commit","animation","reanimated"]);function Ae(e,t){let s=e.indexOf(t);if(s>=0&&s+1<e.length)return e[s+1]}function ms(e,t){if(!t.filter&&!t.equals)return!0;let s=e.data,i=[];if(s&&typeof s=="object")for(let r of["url","displayUrl","message","name","activeName","path","pathname","title","phase","event","type","kind"]){let p=s[r];typeof p=="string"&&p.length>0&&i.push(p)}let d=i.join(" ");return t.equals?i.some(r=>r===t.equals):t.filter?d.toLowerCase().includes(t.filter.toLowerCase()):!0}async function fo(e){let{bridge:t,args:s,positional:i,inspectUsage:d}=e,r=i[1];r||(console.error(d("event","<kind> [--max-ms 5000] [--filter <substring>] [--equals <exact>] [--since now|cursor]")),process.exit(1)),mo.has(r)||console.error(` warning: '${r}' is not a known timeline kind \u2014 waiting anyway. known: ${[...mo].sort().join(", ")}`);let p=Ae(s,"--max-ms"),b=p&&Number.isFinite(Number(p))?Math.max(100,Number(p)):5e3,h=Ae(s,"--filter"),I=Ae(s,"--equals"),w=Ae(s,"--since")??"now",g=s.includes("--json"),M=Date.now(),x=M+b,_=200,O=M;for(;Date.now()<x;){let D={kinds:[r],since:w==="cursor"?void 0:O,limit:50},R=await t.send({type:"evaluate",code:`(async () => {
461
+ const t = window.SootSim?.bridges?.timeline
462
+ if (!t) return { ok: false, error: 'timeline bridge missing' }
463
+ return { ok: true, result: await t.recent(${JSON.stringify(D)}) }
464
+ })()`});(!R||!R.ok)&&(console.error(` could not query timeline: ${R&&"error"in R?R.error:"unknown"}`),process.exit(1));let A=R.result.events??[];for(let J of A)if(ms(J,{filter:h,equals:I})){let U=Date.now()-M;console.log(g?JSON.stringify({found:!0,elapsedMs:U,event:J}):` ${r} event after ${U}ms${h?` (filter: ${h})`:""}${I?` (equals: ${I})`:""}`);return}R.result.watermark&&R.result.watermark>O&&(O=R.result.watermark),await new Promise(J=>setTimeout(J,_))}let c=Date.now()-M;g?console.log(JSON.stringify({found:!1,elapsedMs:c,kind:r,filter:h,equals:I})):console.error(` \u26A0 wait event ${r} timed out after ${c}ms${h?` (filter: ${h})`:""}${I?` (equals: ${I})`:""}`),process.exit(1)}async function go(e){let{bridge:t,args:s}=e,i=s.includes("--strict"),d=Ie(s,3e3),{elapsed:r,settled:p}=await se({bridge:t,maxMs:d,strict:i});p?console.log(` idle in ${r}ms`):(console.error(` \u26A0 wait idle timed out after ${r}ms (may still be animating)`),process.exit(1))}async function yo(e){let{bridge:t,args:s}=e,i=Ie(s,2e4),{ready:d,elapsedMs:r,nodes:p,targets:b,liveFrameActive:h,liveFrameChannels:I,flag:w,loadingText:g,externalReady:M,externalError:x,suppressedEntryError:_,errors:O,bridgeError:c}=await St(t,i,{onProgress(R){console.error(` still waiting after ${R.elapsedMs}ms \u2014 ${qe(R)} (nodes: ${R.nodes}, targets: ${R.targets}, live surfaces: ${R.liveFrameActive?R.liveFrameChannels:0}, errors: ${R.errors})`)}});if(d){let R=i-r,A=Math.max(100,Math.min(1e4,R)),J=await se({bridge:t,maxMs:A,pollMs:32,stablePolls:2});J.settled||(console.error(` \u26A0 wait ready timed out after ${r+J.elapsed}ms \u2014 app mounted but did not settle (nodes: ${p}, targets: ${b})`),process.exit(1)),console.log(` ready in ${r+J.elapsed}ms: ${p} nodes, ${b} targets${h?`, ${I} live surfaces`:""}`);return}let D=qe({externalError:x,loadingText:g,externalReady:M,flag:w,targets:b,suppressedEntryError:_,bridgeError:c});console.error(` \u26A0 wait ready timed out after ${r}ms \u2014 ${D} (nodes: ${p}, targets: ${b}, live surfaces: ${h?I:0}, errors: ${O})`),process.exit(1)}async function ho(e){let{bridge:t,args:s,positional:i,inspectUsage:d}=e,r=i[1];r||(console.error(d("selector","<testid> [--max-ms 5000] [--gone]")),process.exit(1));let p=s.indexOf("--max-ms"),b=p>=0&&s[p+1]?Math.max(100,Number(s[p+1])):5e3,h=s.includes("--gone"),{found:I,node:w,elapsed:g}=await vt(t,r,b,{gone:h});if(h){I?console.log(` #${r} gone after ${g}ms`):(console.error(` \u26A0 wait selector #${r} --gone timed out after ${g??b}ms (still present)`),process.exit(1));return}if(I&&w){let M=w.absolutePosition?`@(${Math.round(w.absolutePosition.x)},${Math.round(w.absolutePosition.y)})`:"",x=w.layout?`${Math.round(w.layout.width)}x${Math.round(w.layout.height)}`:"?x?";console.log(` found #${r} in ${g}ms ${x} ${M}`)}else console.error(` \u26A0 wait selector #${r} timed out after ${g??b}ms`),process.exit(1)}function No(e){return e==null?"\u2014":e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/1024/1024).toFixed(1)}M`}function Fo(e){return e==null?" \u2026":e<1e3?`${e}ms`.padStart(5):`${(e/1e3).toFixed(2)}s`.padStart(5)}function bo(){process.stderr.write(` the sim is not responding. recover it with:
465
+ rnxsim close --sim <id> # force-close the wedged sim
466
+ rnxsim list # confirm it's gone
467
+ `)}async function $e(e,t){let s=await e.send({type:"perform",steps:[t]}),i=s?.steps?.[0],d=i?.error??s?.error;return{ok:s?.ok===!0,value:i?.value,...d?{error:d}:{}}}async function gs(e){try{return await e.send({type:"evaluate",code:"1"},{timeoutMs:3e3}),!0}catch{return!1}}async function ys(e,t){try{let s=await e.send({type:"evaluate",code:`(async () => {
468
+ const t = window.__sootsimTest
469
+ if (!t || typeof t.queryAll !== 'function') return []
470
+ try {
471
+ // queryAll is async in render-worker mode (the canonical mode now)
472
+ // because the call has to round-trip the worker \u2014 must await it.
473
+ // a sync result is still handled fine since await on a non-Promise
474
+ // is a no-op.
475
+ const nodes = await t.queryAll({})
476
+ if (!Array.isArray(nodes)) return []
477
+ const out = new Set()
478
+ for (const n of nodes) {
479
+ const id = n && (n.testID || n.id)
480
+ if (typeof id === 'string' && id) out.add(id)
481
+ }
482
+ return Array.from(out)
483
+ } catch {
484
+ return []
485
+ }
486
+ })()`});if(!Array.isArray(s)||s.length===0)return;let i=t.toLowerCase(),d=s.map(r=>({id:r,score:hs(i,r.toLowerCase())})).filter(r=>r.score<i.length+4).sort((r,p)=>r.score-p.score).slice(0,5);if(d.length===0)return;console.error(" similar testIDs:");for(let r of d)console.error(` ${r.id}`)}catch{}}function hs(e,t){if(t===e)return 0;if(t.includes(e))return 1;if(e.includes(t))return 2;let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];)s+=1;return bs(e,t)-s}function bs(e,t){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let s=new Array(t.length+1),i=new Array(t.length+1);for(let d=0;d<=t.length;d++)s[d]=d;for(let d=1;d<=e.length;d++){i[0]=d;for(let p=1;p<=t.length;p++)i[p]=Math.min(s[p]+1,i[p-1]+1,s[p-1]+(e[d-1]===t[p-1]?0:1));let r=s;s=i,i=r}return s[t.length]}function ws(e){return e.error?"err":e.status==null?" \u2026 ":String(e.status)}function wo(e){return e.externalError?`guest app errored: ${e.externalError}`:e.loadingText?`still showing "${e.loadingText}"`:e.externalReady===!1?"guest app is still loading":e.flag!==!0?"guest app has not emitted sootsim:externalAppReady":e.targets<=0?"ready flag emitted but no visible app content is inspectable yet":"node tree is still changing"}function xo(e){let t=ae(e.startTs),s=ws(e).padEnd(3),i=e.method.padEnd(5),d=No(e.size).padStart(6),r=Fo(e.durationMs);console.log(` [${t}] ${s} ${i} ${d} ${r} ${e.displayUrl}`),e.error&&console.log(` error: ${e.error}`)}function xs(e){let t=[["id",e.id],["source",e.source],["kind",e.kind],["method",e.method],["status",e.error?`error: ${e.error}`:`${e.status??"\u2014"} ${e.statusText??""}`.trim()],["url",e.url],["started",ae(e.startTs)],["duration",Fo(e.durationMs).trim()],["size",No(e.size)],["content-type",e.type??"\u2014"]];for(let[s,i]of t)console.log(` ${s.padEnd(13)} ${i}`)}var $s={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},$o="\x1B[0m",Ss="\x1B[2m";function So(e,t){let s=ae(e.ts),i=e.level.toUpperCase().padEnd(5),d=e.args.join(" ");if(t){let r=$s[e.level];console.log(` ${Ss}[${s}]${$o} ${r}${i}${$o} ${d}`)}else console.log(` [${s}] ${i} ${d}`);if(e.stack&&e.level==="error"){let r=e.stack.split(`
487
+ `).slice(0,5);for(let p of r)console.log(` ${p.trim()}`)}}var vs=120;async function vo(e,t){let s=e.find((M,x)=>e[x-1]==="--id"),i=e.find((M,x)=>e[x-1]==="--text");if(s||i){let M=await t.send({type:"evaluate",code:Dt({id:s,text:i})});if(!M)throw new Error(s?`no node with id "${s}"`:`no node matching text "${i}"`);let{x,y:_,w:O,h:c}=M;return{x,y:_,w:O,h:c}}let d=e.find((M,x)=>e[x-1]==="--area");if(d){let M=d.split(",").map(D=>Number(D.trim()));if(M.length!==4||M.some(D=>!Number.isFinite(D)))throw new Error(`--area expects x,y,w,h (got "${d}")`);let[x,_,O,c]=M;return{x,y:_,w:O,h:c}}let r=M=>{let x=e.find((O,c)=>e[c-1]===M);if(x==null)return null;let _=Number(x);return Number.isFinite(_)?_:null},p=r("--x"),b=r("--y"),h=r("--w"),I=r("--h");if(p!=null||b!=null||h!=null||I!=null)return{x:p??0,y:b??0,w:h??1,h:I??1};let g=e.filter((M,x)=>x>0&&!M.startsWith("-")&&e[x-1]!=="--output"&&e[x-1]!=="--area"&&e[x-1]!=="--id"&&e[x-1]!=="--text"&&e[x-1]!=="--x"&&e[x-1]!=="--y"&&e[x-1]!=="--w"&&e[x-1]!=="--h").map(Number).filter(M=>Number.isFinite(M));if(g.length>=2){let[M,x,_=1,O=1]=g;return{x:M,y:x,w:_,h:O}}return null}function ko(e,t){if(!t||typeof t!="object")return;console.log(""),console.log(` render profile \u2014 ${e} (per painted frame):`),console.log(` node visits: ${t.nodeVisitsPerFrame}`),console.log(` boundaries: ${t.recordsPerFrame} records (${t.avgBoundaryRecordMs}ms) / ${t.replaysPerFrame} replays`);let s=[t.boundaryRecordsInvalidated?`invalidated ${t.boundaryRecordsInvalidated}`:"",t.boundaryRecordsOrigin?`moved ${t.boundaryRecordsOrigin}`:"",t.boundaryRecordsScheme?`first-record ${t.boundaryRecordsScheme}`:""].filter(Boolean).join(" \xB7 ");s&&console.log(` why recorded: ${s}`),t.prewarmRecords&&console.log(` pre-recorded: ${t.prewarmRecords} boundaries at idle (${Number(t.prewarmRecordMs).toFixed(1)}ms total)`),console.log(` raster tier: ${t.rasterPromotionsPerFrame} promotions / ${t.rasterBlitsPerFrame} blits`);let i=[t.rasterRejectRebuild?`rebuild ${t.rasterRejectRebuild}`:"",t.rasterRejectLinear?`linear ${t.rasterRejectLinear}`:"",t.rasterRejectAnimated?`animated ${t.rasterRejectAnimated}`:"",t.rasterRejectTransform?`transform ${t.rasterRejectTransform}`:"",t.rasterRejectOpacity?`opacity ${t.rasterRejectOpacity}`:"",t.rasterRejectCacheable?`cacheable ${t.rasterRejectCacheable}`:"",t.rasterRejectBounds?`bounds ${t.rasterRejectBounds}`:"",t.rasterRejectPixels?`pixels ${t.rasterRejectPixels}`:"",t.rasterRejectBudget?`budget ${t.rasterRejectBudget}`:"",t.rasterWarming?`warming ${t.rasterWarming}`:""].filter(Boolean).join(" \xB7 ");i&&(console.log(` raster skips: ${i} (total across run)`),t.rasterRejectAlsoBlocked&&console.log(` ${"".padEnd(12)} ${t.rasterRejectAlsoBlocked} of those also fail a later gate \u2014 widening the named gate cannot promote them`)),console.log(` blur: ${t.avgBlurMs}ms`),(t.glassDownsampleActive||t.glassBackdropCacheMisses)&&console.log(` glass: ${t.glassDownsampleFactor}x downsample (${t.glassDownsampledDraws} draws) \xB7 cache ${t.glassBackdropCacheHits} hits / ${t.glassBackdropCacheMisses} misses / ${t.glassBackdropCacheInvalidations} invalidations`),console.log(` draw calls: text ${t.textDrawsPerFrame} \xB7 image ${t.imageDrawsPerFrame} \xB7 path ${t.pathDrawsPerFrame} \xB7 saveLayer ${t.saveLayersPerFrame}`)}function Io(e){let t=e.avgMs>0?(1e3/e.avgMs).toFixed(1):"?",s=e.jank&&typeof e.jank=="object"?e.jank:null,i=e.compositorProduction&&typeof e.compositorProduction=="object"?e.compositorProduction:null,d=i?.budgetMs??8;if(console.log(` shell frame profile:
488
+ `),s){let M=(Array.isArray(s.compositor)?s.compositor:[]).reduce((x,_)=>x+(_.jankPaints??0),0);console.log(` health: ${s.detected?"jank or cadence gaps observed":"no jank or cadence gaps observed"} \xB7 shell ${s.shell?.jankFrames??0} \xB7 compositor ${M} \xB7 host clock gaps ${s.hostGaps??0}`),console.log(" series: independent worker clocks, no per-frame pairing")}if(console.log(` painted frames: ${e.frames}${e.skippedFrames?` (+${e.skippedFrames} skipped idle ticks)`:""}`),console.log(` shell work avg: ${e.avgMs}ms (${t} fps) \xB7 worst observed ${e.maxMs}ms`),console.log(` shell p50/95/99:${e.p50} / ${e.p95} / ${e.p99} ms`),s){console.log(` shell jank: ${s.shell?.jankFrames??0}/${s.shell?.sampledFrames??0} (${s.shell?.jankPct??0}%) >${d}ms \xB7 max ${s.shell?.maxMs??0}ms`);for(let g of Array.isArray(s.compositor)?s.compositor:[])console.log(` ${String(g.surfaceId).padEnd(12)} ${g.jankPaints}/${g.sampledPaints} compositor paints (${g.jankPct}%) >${d}ms \xB7 max ${g.maxMs}ms`)}else console.log(` jank: ${e.jankFrames} frames (${e.jankPct}%) >${d}ms`);if(console.log(` avg per frame: overlay ${e.avgOverlayMs}ms \xB7 aux ${e.avgAuxMs}ms \xB7 layout ${e.avgLayoutMs}ms`),i){let g=i.frames??{};console.log(""),console.log(` compositor production (${d}ms budget):`),console.log(` frames: ${g.count??0} \xB7 avg ${Number(g.avg??0).toFixed(2)} / p95 ${Number(g.p95??0).toFixed(2)} / max ${Number(g.max??0).toFixed(2)} ms \xB7 ${i.overBudget??0} over budget (${i.overBudgetPct??0}%)`);let M=[["javascript","javascript"],["layout","layout"],["paint","paint"],["prewarm","prewarm"],["texture upload","textureUpload"],["gpu submit","gpuSubmit"],["composite","composite"],["capture/readback","capture"]];for(let[O,c]of M){let D=i.phases?.[c];!D?.count||!D.max&&!D.avg||console.log(` ${O.padEnd(16)} avg ${Number(D.avg??0).toFixed(2)} / p95 ${Number(D.p95??0).toFixed(2)} / max ${Number(D.max??0).toFixed(2)} ms`)}let x=i.captureBetweenFrames;x?.count&&x.max>0&&console.log(` capture between p95 ${Number(x.p95??0).toFixed(2)} / max ${Number(x.max??0).toFixed(2)} ms between compositor rAF callbacks`);let _=Array.isArray(i.worstFrames)?i.worstFrames.slice(0,5):[];if(_.length>0){console.log(" worst frames:");for(let O of _){let c=O.phases??{};console.log(` ${Number(O.productionMs??0).toFixed(2)}ms frame ${O.frameToken??"?"} \xB7 js ${Number(c.javascriptMs??0).toFixed(2)} \xB7 layout ${Number(c.layoutMs??0).toFixed(2)} \xB7 paint ${Number(c.paintMs??0).toFixed(2)} \xB7 prewarm ${Number(c.prewarmMs??0).toFixed(2)} \xB7 upload ${Number(c.textureUploadMs??0).toFixed(2)} \xB7 submit ${Number(c.gpuSubmitMs??0).toFixed(2)} \xB7 composite ${Number(c.compositeMs??0).toFixed(2)} \xB7 capture ${Number(c.captureMs??0).toFixed(2)}`)}}}let r=e.cadence;r&&typeof r=="object"&&(console.log(""),console.log(` cadence (frame delivery, ${r.vsyncTicks} vsync ticks):`),console.log(` display clock: ${r.displayHz}hz \xB7 host rAF interval p50 ${r.hostIntervalP50} / p95 ${r.hostIntervalP95} / max ${r.hostIntervalMax} ms${r.hostGaps?` \xB7 ${r.hostGaps} gaps >1.5x (host rAF starved)`:""}`),console.log(` delivery lag: p50 ${r.deliveryLagP50} / p95 ${r.deliveryLagP95} / max ${r.deliveryLagMax} ms (vsync postMessage \u2192 shell receipt)`),console.log(` paint interval: p50 ${r.paintIntervalP50} / p95 ${r.paintIntervalP95} / max ${r.paintIntervalMax} ms${r.idleBreaks?` \xB7 ${r.idleBreaks} idle breaks excluded`:""}`));let p=e.compositorCadence;if(p&&typeof p=="object"){console.log(` compositor rAF: p50 ${p.p50} / p95 ${p.p95} / max ${p.max} ms \xB7 ${p.gaps} gaps >1.5x`);let g=(M,x)=>{x?.count&&console.log(` ${M}: ${x.count} samples \xB7 p50 ${x.p50.toFixed(2)} / p95 ${x.p95.toFixed(2)} / max ${x.max.toFixed(2)} ms`)};g("engine-empty rAF",p.phases?.uninterruptedEngineEmpty),g("rAF with CanvasKit flush",p.phases?.withCanvaskitFlush),g("rAF after CanvasKit flush",p.phases?.afterCanvaskitFlush),g("CanvasKit submission",p.canvaskitSubmission)}let b=Array.isArray(e.auxSurfaces)?e.auxSurfaces:[],h=e.graphiteCaches,I=e.decodedImageCache;if(h||I){let g=(M,x)=>{if(typeof x?.bytes!="number"||typeof x.limitBytes!="number")return;let _=typeof x.purgeableBytes=="number"?` \xB7 ${(x.purgeableBytes/1024/1024).toFixed(1)}MB purgeable`:"";console.log(` ${M.padEnd(29)} ${(x.bytes/1024/1024).toFixed(1)}MB/${(x.limitBytes/1024/1024).toFixed(1)}MB${_}`)};console.log(""),console.log(" device-wide caches:"),g("Graphite context resources",h?.contextResources??null),g("Graphite recorder resources",h?.recorderResources??null),g("Graphite image provider",h?.imageProvider??null),g("decoded image pixels",I??null),h?.imageProvider&&console.log(` ${"".padEnd(29)} ${h.imageProvider.entries} entries \xB7 ${h.imageProvider.uploads} uploads \xB7 ${h.imageProvider.evictions} evictions`),I&&console.log(` ${"".padEnd(29)} ${I.entries} entries/${I.maxEntries} max`)}if(b.length>0){console.log(""),console.log(" surfaces (last 100 frames):");for(let g of b)console.log(` ${String(g.surfaceId).padEnd(10)} ${String(g.frames).padStart(4)} paints avg ${g.avgMs}ms (layout ${g.avgLayoutMs}, render ${g.avgRenderMs}, flush ${g.avgFlushMs}) max ${g.maxMs}ms`)}ko("shell worker",e.renderProfile),ko("compositor worker",e.compositorRenderProfile);let w=Array.isArray(e.worstFrames)?e.worstFrames:[];if(w.length>0){console.log(""),console.log(" worst observations (shell and compositor series are unpaired):");for(let g of w){if(g.source==="compositor"){console.log(` ${String(g.totalMs).padStart(7)}ms compositor ${g.surfaceId} paint ${g.paint} \xB7 layout ${g.layoutMs} \xB7 render ${g.renderMs} \xB7 flush ${g.flushMs}`);continue}let M=(g.auxSurfaces??[]).map(x=>`${x.surfaceId} ${x.totalMs}ms (layout ${x.layoutMs}, render ${x.renderMs})`).join(" \xB7 ");console.log(` ${String(g.totalMs).padStart(7)}ms overlay ${g.overlayMs} \xB7 aux ${g.auxMs} \xB7 layout ${g.layoutMs}${M?` [${M}]`:""}`)}}}async function _e(e,t,s){let i=Date.now()+t,d=await ue(e,t);for(;;){if(s(d))return{settled:!0,state:d};if(Date.now()>=i)return{settled:!1,state:d};await oe(16),d=await ue(e)}}async function ot(e){return e.send({type:"evaluate",code:`(async () => {
489
+ const kb = window.__sootsimKeyboard
490
+ const test = window.__sootsimTest
491
+ if (!kb) return { error: 'keyboard bridge not available' }
492
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
493
+ const secureTextEntry =
494
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
495
+ const visible = kb.isVisible()
496
+ const mode = kb.getMode()
497
+ let focused = null
498
+ if (test && typeof test.getFocusedNode === 'function') {
499
+ try {
500
+ focused = await test.getFocusedNode()
501
+ } catch {}
502
+ }
503
+ let runtimeSnapshot = null
504
+ if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
505
+ try {
506
+ runtimeSnapshot = await test.getFocusKeyboardSnapshot()
507
+ } catch {}
508
+ }
509
+ return {
510
+ visible,
511
+ mode,
512
+ layout,
513
+ hostedEditorFocused:
514
+ typeof kb.hasHostedEditorFocus === 'function' && kb.hasHostedEditorFocus(),
515
+ focusedInput: focused ? {
516
+ nodeId: focused.nodeId ?? null,
517
+ testID: focused.testID || null,
518
+ id: focused.id || null,
519
+ placeholder: focused.placeholder || null,
520
+ secureTextEntry,
521
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
522
+ } : null,
523
+ phase: runtimeSnapshot?.keyboard?.phase ?? null,
524
+ frame: runtimeSnapshot?.keyboard?.frame ?? null,
525
+ focusedRect: runtimeSnapshot?.focused?.rect ?? null,
526
+ }
527
+ })()`}).then(t=>et(t))}function ks(e,t,s){if(!e.visible)return!1;let i=e.focusedInput;return!(t&&i&&!(i.testID===t||i.id===t)||s!==null&&we(e)!==s)}async function Is(e,t=600,s={}){let i=Date.now()+t;for(;Date.now()<=i;){let d=await ot(e);if(ks(d,s.targetId??null,s.secureTextEntry??null))return d;await oe(30)}return ot(e)}async function De(e,t){let s=await ot(e);if(s.visible&&(s.focusedInput||s.hostedEditorFocused))return s;s.visible&&(console.error(` ${t} requires a focused editable control. the iOS keyboard is visible, but no input owns focus.`),process.exit(1)),console.error(` ${t} requires the iOS keyboard to be visible. focus an input first with rnxsim do tap-id/tap-text or rnxsim do type-into.`),process.exit(1)}async function To(e,t,s){return t==="appearance"?e.send({type:"evaluate",code:`(async () => {
528
+ const requested = ${JSON.stringify(s??"toggle")}
529
+ // the engine owns toggle + auto resolution (settingsStore is the single
530
+ // source of truth). never infer the current scheme client-side \u2014 the old
531
+ // documentElement '#333333' sniff is never set in embedded / shell-chrome
532
+ // contexts, so 'toggle' read 'light' forever and stuck on the boot scheme.
533
+ window.postMessage({ type: 'contrast-action', action: 'set-appearance', value: requested }, '*')
534
+ // let the engine's message handler apply + publish window.__sootsimColorScheme
535
+ await new Promise((r) => setTimeout(r, 60))
536
+ const applied = window.__sootsimColorScheme?.resolved
537
+ ?? (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
538
+ const setting = window.__sootsimColorScheme?.setting ?? requested
539
+ return { ok: true, requested, setting, applied }
540
+ })()`}):t==="lock"?e.send({type:"evaluate",code:`(async () => {
541
+ const toggleLock = window.SootSim?.bridges?.mainShell?.toggleLock
542
+ if (typeof toggleLock !== 'function') {
543
+ throw new Error('rnx mainShell.toggleLock bridge unavailable')
544
+ }
545
+ await toggleLock()
546
+ return { ok: true, action: 'lock' }
547
+ })()`}):e.send({type:"evaluate",code:`(async () => {
548
+ window.dispatchEvent(new CustomEvent('sootsim:shake'))
549
+ return { ok: true, action: 'shake' }
550
+ })()`})}function Ts(e){let t={Enter:"return",NumpadEnter:"return",Backspace:"delete",Delete:"delete",Space:"space",ShiftLeft:"shift",ShiftRight:"shift"};if(t[e])return t[e];let s=e.match(/^Digit([0-9])$/);if(s)return s[1];let i=e.match(/^Key([A-Z])$/);return i?i[1].toLowerCase():null}function Ms(e){if(typeof e!="string")return null;let t=e.replace(/\s+/g," ").trim();return t?t.slice(0,80):null}function Oo(...e){for(let t of e){if(typeof t!="string")continue;let s=t.trim();if(s)return s}return null}function Ns(e){let t=e.indexOf("--node-id");if(t<0)return null;let s=e[t+1];if(!s)return null;let i=Number(s);return Number.isInteger(i)&&i>0?i:null}async function W(e,t,s){let i=Pe({source:e,step:t,summary:s});i.active&&(i.replaced?console.error(` draft: replaced unkept action "${i.replaced.summary}" \u2014 \`maestro keep\` commits one action at a time`):console.error(" draft: action pending \u2014 `rnxsim maestro keep` to commit"))}function Mo(e,t,s){if(!s||s.hit===!1)return null;let i=Oo(s.responderTestID,s.testID);if(i)return{step:{tapOn:{id:i}},summary:`tap #${i}`};let d=Ms(s.text);return d?{step:{tapOn:d},summary:`tap "${d}"`}:{step:{tapAtCoords:{x:e,y:t}},summary:`tap @${Math.round(e)},${Math.round(t)}`}}function tt(e,t,s){let i=Oo(t?.testID,t?.id);return i?{step:{tapOn:{id:i}},summary:`tap #${i}`}:s==="id"?{step:{tapOn:{id:e}},summary:`tap #${e}`}:{step:{tapOn:e},summary:`tap "${e}"`}}async function _r(e,t){let s=e[0]==="get"||e[0]==="do"||e[0]==="debug"||e[0]==="wait"?e[0]:null,i=s?e.slice(1):e,d=ct(i,{port:t.port,commandTimeoutMs:t.timeoutMs,stripBooleanFlags:["--verbose","-v","--help","-h","--clear-state","--json","--all","--watch","-w","--strict","--no-wait","--dump","--failed","--slow","--tail","-f","--interactive-targets","--actions","--internal","--compact","--no-xy","--no-clipped","--include-occluded"],stripValueFlags:["--output","--nth","--index","--testid","--test-id","--text","--node-id","--max-ms","--filter","--limit","--level","--threshold","--equals","--since","--testid-like","--only","--subtree"]}),r=d.positional,p=r[0],b=s,h=typeof i[0]=="string"&&st.has(i[0]),I=h?i[0]:null,w=S=>{if(t.internalPerfCommand&&S==="perf")return`rnxsim perf ${t.internalPerfCommand}`;if(h&&S===i[0])return`rnxsim ${S}`;let o=b??nt(S)?.group;return o?`rnxsim ${o} ${S}`:`rnxsim ${S}`},g=(S,o)=>` usage: ${w(S)}${o?` ${o}`:""}`;if(!p||e.includes("--help")||e.includes("-h")){let S={bridgePort:7668,defaultShellUrl:at};if(b==="do"||b==="get"||b==="debug"||b==="wait"){let n=Be(b,S);n&&(console.log(`${n}
551
+ `),process.exit(0))}if(I==="shell"){let n=rt("shell",S);n&&(console.log(`${n}
552
+ `),process.exit(0))}let o=["do","get","debug","wait"].map(n=>Be(n,S)).filter(n=>n!=null).join(`
553
+
554
+ `);console.log(`${o}
555
+ `),process.exit(0)}let M=d.wsPort,x=d.simId,_=d.simIdSource,O=d.commandTimeoutMs;if(b==="get"&&p==="diagnosis"){let S=i.indexOf("diagnosis"),o=S>=0?[...i.slice(0,S),...i.slice(S+1)]:i,{runDiagnose:n}=await import("./diagnose-P2FMX5HU.js"),a=await n(["recent",...o],t);process.exitCode=a;return}if(b==="do"&&p==="scan"){let{runCamera:S}=await import("./camera-EJRFUEXV.js");process.exitCode=await S(i,{port:t.port});return}if(p==="list"&&i.some(S=>S==="--drivers"||S==="-D")){let{buildDriverListRows:S}=await import("./drivers-CFJGYQFX.js"),o=S();console.log(` available drivers (${o.length}):
556
+ `);let n=Math.max(...o.map(l=>l.id.length),6),a=Math.max(...o.map(l=>l.kind.length),4);for(let l of o){let u=l.available?"\u2713":"\u2717",m=l.id.padEnd(n),f=l.kind.padEnd(a);console.log(` ${u} ${m} ${f} ${l.description}`),l.available&&l.detail?console.log(` ${l.detail}`):!l.available&&l.reason&&console.log(` unavailable: ${l.reason}`)}return}let c=dt(d),D=x||"default",R=new Set(["errors","warnings","requests","js","reload","globals","perf","storage-clear","list","wait","sleep"]),A=200;function J(S){let o=S.replace(/\s+/g," ").trim();if(!o)return"";if(/^<(!doctype html|html|\?xml)|<body[\s>]/i.test(o)){let a=/<title[^>]*>([^<]+)<\/title>/i.exec(S)?.[1]?.trim(),l=/<body[^>]*>([\s\S]*?)<\//i.exec(S)?.[1]?.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,80),u=a||l||"html error page";return`<html ${S.length}B> "${u}" (body elided \u2014 add --json for the full payload)`}return o.length<=A?o:`${o.slice(0,A)}\u2026 (+${o.length-A} more bytes)`}function U(S){let o=S.displayUrl||S.url;return S.status!=null?`${S.method} ${o} -> ${S.status}${S.statusText?` ${S.statusText}`:""}`:S.error?`${S.method} ${o} -> ${S.error}`:`${S.method} ${o}`}async function T(S){let o=fe()?400:200;try{let{settled:n,elapsed:a}=await se({bridge:S,maxMs:o,pollMs:32,stablePolls:2});n||process.stderr.write(` \u26A0 auto-wait timed out after ${a??o}ms \u2014 next command may see mid-animation state. use \`rnxsim do settle\` for a longer wait.
557
+ `)}catch{}}function P(S,o){if(o.result?.reason==="offscreen"){let{x:n,y:a,screen:l}=o.result;console.error(` tap failed: ${S} resolved to (${Math.round(n)},${Math.round(a)}), outside the ${l?.width}x${l?.height} screen`),console.error(" the node exists but is scrolled out of view \u2014 scroll it on-screen first (rnxsim do scroll / swipe), then tap.");return}console.error(` tap failed: ${S} stayed visible but did not receive a hittable press after ${o.attempts} attempt${o.attempts===1?"":"s"}`),o.result&&console.error(` last result: ${JSON.stringify(o.result)}`)}async function H(){try{return await c.send({type:"evaluate",code:`(() => ({
558
+ console: ${Te},
559
+ requests: window.__sootsimTest?.getRequestCounts?.() || null,
560
+ }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function K(S={}){let o=S.counts!==void 0?S.counts:await X(c,"getRequestCounts");if(!o||typeof o!="object")return;let n=Math.max(0,Number(o.failed)||0);if(n===0||!S.includeTail&&!ze("requests",D,String(n))||(console.log(`
561
+ network: ${n} failed request${n===1?"":"s"}`),console.log(` inspect: ${w("requests")} 5`),!S.includeTail))return;let a=await X(c,"getFailedRequests",5);if(!(!Array.isArray(a)||a.length===0)){console.log(`
562
+ recent failed requests:
563
+ `);for(let l of a){let u=ae(l.timestamp);console.log(` [${u}] ${U(l)}`),l.responseBody?console.log(` ${J(l.responseBody)}`):l.error&&console.log(` ${l.error}`)}}}function ee(S){for(let o of S){let n=o.title?` (\u201C${o.title}\u201D)`:"";console.error(`
564
+ note: ${o.label} is open${n} \u2014 taps/drags hit it, not the app`)}}async function te(S={}){let o=S.counts!==void 0?S.counts:await c.send({type:"evaluate",code:Te});if(!o||typeof o!="object")return;let n=o,a=Math.max(0,Number(n.errors)||0),l=Math.max(0,Number(n.warnings)||0);if(a===0&&l===0||!S.includeTail&&!ze("console",D,`${a}:${l}`))return;let u=[];if(a>0&&u.push(`${a} console error${a===1?"":"s"}`),l>0&&u.push(`${l} console warning${l===1?"":"s"}`),console.error(`
565
+ console: ${u.join(", ")}`),console.error(` inspect: ${w("errors")} 5`),l>0&&console.error(` inspect: ${w("warnings")} 5`),!S.includeTail||a===0)return;let m=await ge(c,5);if(!(!Array.isArray(m)||m.length===0)){console.error(`
566
+ recent console errors:
567
+ `);for(let f of m){let $=ae(f.timestamp),y=Array.isArray(f.args)?f.args.map(k=>typeof k=="object"?JSON.stringify(k):String(k)).join(" "):String(f);console.error(` [${$}] ${y}`)}}}let ie=["console","fetch","toast","alert","notification","screen","app-launch","keyboard","route","actionsheet","picker","shell","scroll","gesture","text-input","animation","reanimated"];async function Se(S){let o=it(),n=null;try{n=await pt(S,`(() => {
568
+ const tl = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.timeline
569
+ if (!tl || typeof tl.summary !== 'function') return null
570
+ const cursorKey = ${JSON.stringify(o)}
571
+ const summary = tl.summary({ sinceCursor: cursorKey })
572
+ let consoleSplit = null
573
+ if (summary && summary.byKind && summary.byKind.console) {
574
+ const events = tl.recent({ sinceCursor: cursorKey, kinds: 'console', limit: 100000 }).events
575
+ consoleSplit = { error: 0, warn: 0 }
576
+ for (const ev of events) {
577
+ const lvl = ev && ev.data && ev.data.level
578
+ if (lvl === 'error') consoleSplit.error++
579
+ else if (lvl === 'warn') consoleSplit.warn++
580
+ }
581
+ }
582
+ return summary ? { summary, consoleSplit } : null
583
+ })()`)}catch{return}if(!n||!n.summary||!n.summary.total)return;let a=n.summary.byKind??{},l=[],u=new Set;for(let m of ie){let f=a[m];if(f)if(u.add(m),m==="console"&&n.consoleSplit){let{error:$,warn:y}=n.consoleSplit;$>0&&l.push(`${$} error${$===1?"":"s"}`),y>0&&l.push(`${y} warning${y===1?"":"s"}`)}else l.push(`${f} ${m}${f===1?"":"s"}`)}for(let[m,f]of Object.entries(a))!u.has(m)&&f&&l.push(`${f} ${m}${f===1?"":"s"}`);if(l.length!==0&&(console.error(`
584
+ since last: ${l.join(" \xB7 ")} \u2014 rnxsim what-happened`),n.summary.lastAt))try{await ce(S,"SootSim.bridges.timeline.cursorAdvance",o,n.summary.lastAt)}catch{}}let q=new Set(["tap","double-tap","tap-text","tap-id","type","type-into","key","key-sequence","keycode","drag","swipe","long-press","touch","gesture","pinch","scroll","shell","storage-clear"]),le=new Set(["a11y","capture","count","double-tap","drag","find","gesture","layout","long-press","node","pinch","sample-color","scroll","screenshot","swipe","tap","tap-id","tap-text","touch","tree","type-into"]),ve=(e.includes("--verbose")||e.includes("-v"))&&!e.includes("--json");b==="do"&&p==="shell"&&(console.error(" `rnxsim do shell` was removed. use `rnxsim shell ...` instead."),process.exit(1)),q.has(p)&&await ut(c),le.has(p)&&await pe(c,{verbose:ve});try{let S=q.has(p)?await Ot(c):[];switch(p){case"list":{lt(d.wsPort),await so({bridge:c,simId:x,args:i});break}case"tree":{await co({bridge:c,args:i,positional:r});break}case"a11y":{let o=await xt(c);if(!Array.isArray(o)||o.length===0){console.log(" no accessible nodes found");break}if(e.includes("--json"))console.log(JSON.stringify(o,null,2));else{console.log(` accessibility tree (${o.length} nodes):
585
+ `);for(let n of o){let a=[];if(a.push(`[${n.role}]`),n.label){let l=n.label.length>50?n.label.slice(0,47)+"...":n.label;a.push(`"${l}"`)}if(n.hint&&a.push(`(hint: "${n.hint}")`),n.testID&&a.push(`#${n.testID}`),n.state){let l=[];n.state.disabled&&l.push("disabled"),n.state.selected&&l.push("selected"),n.state.checked===!0&&l.push("checked"),n.state.checked==="mixed"&&l.push("mixed"),n.state.busy&&l.push("busy"),n.state.expanded===!0&&l.push("expanded"),n.state.expanded===!1&&l.push("collapsed"),l.length&&a.push(`{${l.join(", ")}}`)}n.position&&a.push(`@(${n.position.x},${n.position.y})`),n.size&&a.push(`${n.size.w}x${n.size.h}`),console.log(" "+a.join(" "))}}break}case"find":{await eo({bridge:c,args:e,effectiveArgs:i,positional:r,inspectUsage:g});break}case"count":{await Qt(c,{args:i});break}case"keyboard":{await oo(c,{json:e.includes("--json")});break}case"screens":{await io(c,{json:e.includes("--json")});break}case"memory":{await ro(c,{args:i});break}case"wait":{await po({wsPort:M,commandTimeoutMs:O,simId:x,simIdSource:_,positional:r});break}case"sleep":{await lo({positional:r,inspectUsage:g});break}case"settle":{await ao({bridge:c,args:e,positional:r});break}case"ready":{await yo({bridge:c,args:e});break}case"idle":{await go({bridge:c,args:e,positional:r});break}case"selector":{await ho({bridge:c,args:e,positional:r,inspectUsage:g});break}case"event":{await fo({bridge:c,args:e,positional:r,inspectUsage:g});break}case"layout":{let o=r[1];if(!o){await to({bridge:c,args:i});break}let n=await c.send({type:"evaluate",code:`(async () => await window.__sootsimTest.getLayout(${JSON.stringify(o)}))()`});console.log(JSON.stringify(n,null,2));break}case"capture":case"screenshot":{let n=e.find(($,y)=>e[y-1]==="--output")||"/tmp/sootsim-inspect.png",a=await vo(e,c),l={type:"screenshot"};a&&(l.crop=a);let m=(await c.send(l)).replace(/^data:image\/png;base64,/,"");a&&console.log(` area: x=${a.x} y=${a.y} w=${a.w} h=${a.h}`),(await import("fs")).writeFileSync(n,Buffer.from(m,"base64")),console.log(` saved: ${n}`);break}case"sample-color":{let o=await vo(e,c);o||(console.error(g("sample-color","<x> <y> [w] [h] | --id <testID> | --text <text>")),console.error(" samples an averaged color from the canvas. coords are logical rnx units."),process.exit(1));let n=await c.send({type:"evaluate",code:Bt(o)});if(e.includes("--json"))console.log(JSON.stringify(n,null,2));else{let{r:a,g:l,b:u,a:m,hex:f,samples:$}=n,y=o.w===1&&o.h===1?`@(${o.x},${o.y})`:`@(${o.x},${o.y}) ${o.w}x${o.h}`;console.log(` ${f} rgba(${a}, ${l}, ${u}, ${m}) ${y} ${$} samples`)}break}case"node":{let o=r[1];o||(console.error(g("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let n=await c.send({type:"evaluate",code:`(async () => {
586
+ const t = window.__sootsimTest
587
+ const q = ${JSON.stringify(o)}
588
+ let node = null
589
+ let via = null
590
+ if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
591
+ if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
592
+ if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
593
+ if (!node) return { matcher: q, found: false }
594
+
595
+ // read the resolved transform (if any) off the style \u2014 useful
596
+ // because canvas nodes often animate via transform and describe
597
+ // output strips that.
598
+ const transform =
599
+ node.style && Array.isArray(node.style.transform)
600
+ ? node.style.transform
601
+ : node.style && node.style.transform
602
+ ? node.style.transform
603
+ : null
604
+
605
+ // parent chain \u2014 walk up from the node so the JSON dump is
606
+ // self-describing.
607
+ const parentChain = []
608
+ const root = window.__sootsimRoot
609
+ if (root && node.id != null) {
610
+ const findPath = (n, targetId, path) => {
611
+ if (!n) return null
612
+ if (n.id === targetId) return path
613
+ if (n.children) {
614
+ for (const child of n.children) {
615
+ const nextPath = [
616
+ ...path,
617
+ {
618
+ type: n.type || 'view',
619
+ testID: n.props?.testID || null,
620
+ text: n.text || null,
621
+ },
622
+ ]
623
+ const found = findPath(child, targetId, nextPath)
624
+ if (found) return found
625
+ }
626
+ }
627
+ return null
628
+ }
629
+ const chain = findPath(root, node.id, [])
630
+ if (chain) parentChain.push(...chain)
631
+ }
632
+
633
+ return {
634
+ matcher: q,
635
+ found: true,
636
+ resolvedVia: via,
637
+ node,
638
+ transform,
639
+ parentChain,
640
+ }
641
+ })()`});console.log(JSON.stringify(n,null,2));break}case"tap":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r);if(a){let m=await be(c,{agent:fe(),textFallback:a.mode==="text"?a.value:void 0,resolve:async()=>{let y=await Ee(c,a);return y?{cx:y.x,cy:y.y,match:{id:a.mode==="testid"?a.value:y.id??null,testID:a.mode==="testid"?a.value:y.testID??null,text:a.mode==="text"?a.value:y.text??null,type:y.type??null},target:{id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}:null}}),f=m.payload;(!f||typeof f.cx!="number")&&(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),me(m.result)||(P(`${a.mode} "${a.value}"`,m),process.exit(1));let $=Mo(f.cx,f.cy,m.result);$&&await W("inspect tap",$.step,$.summary),console.log(JSON.stringify({...m.attempts>1?{attempts:m.attempts}:{},...m.result},null,2));break}(!Number.isFinite(o)||!Number.isFinite(n))&&(console.error(g("tap","<testid> | <x> <y> | --testid <id> | --text <t>")),process.exit(1));let l=await Yt(c,o,n),u=Mo(o,n,l);u&&await W("inspect tap",u.step,u.summary),console.log(JSON.stringify(l,null,2));break}case"drag":case"swipe":{let o=Number(r[1]),n=Number(r[2]),a=Number(r[3]),l=Number(r[4]),u=p==="swipe"?10:12,m=p==="swipe"?8:16,f=r[5]?Number(r[5]):u,$=r[6]?Number(r[6]):m;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(f)||!Number.isFinite($))&&(console.error(g(p,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let y=await $e(c,{type:"drag",fromX:o,fromY:n,toX:a,toY:l,steps:Math.max(1,Math.round(f)),stepMs:Math.max(0,Math.round($))});if(y?.ok){let k=Math.max(1,Math.round(Math.max(1,f)*Math.max(0,$)));await W(`inspect ${p}`,{swipe:{start:`${o}, ${n}`,end:`${a}, ${l}`,duration:k}},`${p} ${o},${n} -> ${a},${l}`)}console.log(JSON.stringify(y,null,2));break}case"pinch":{let o=Number(r[1]),n=Number(r[2]),a=Number(r[3]),l=Number(r[4]),u=Number(r[5]),m=Number(r[6]),f=Number(r[7]),$=Number(r[8]),y=r[9]?Number(r[9]):12,k=r[10]?Number(r[10]):16;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||!Number.isFinite(m)||!Number.isFinite(f)||!Number.isFinite($)||!Number.isFinite(y)||!Number.isFinite(k))&&(console.error(g("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let L=await $e(c,{type:"pinch",fromX1:o,fromY1:n,fromX2:a,fromY2:l,toX1:u,toY1:m,toX2:f,toY2:$,steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round(k))});L?.ok&&await W("inspect pinch",{pinch:{from:[o,n,a,l],to:[u,m,f,$],steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round(k))}},`pinch (${o},${n}) (${a},${l}) -> (${u},${m}) (${f},${$})`),console.log(JSON.stringify(L,null,2));break}case"tap-text":{let o=r[1];o||(console.error(g("tap-text","<text>")),process.exit(1));let n=z=>{let j=e.indexOf(z);return j>=0&&j+1<e.length?e[j+1]:null},a=z=>e.includes(z),l=n("--nth")??n("--index"),u=l!==null?Number(l):null;u!==null&&!Number.isFinite(u)&&(console.error(` --nth/--index requires an integer, got: ${l}`),process.exit(1));let m=n("--within"),f=n("--role"),$=a("--exact"),y=a("--first"),k=n("--min-y"),L=n("--max-y"),V=n("--min-x"),G=n("--max-x");for(let[z,j]of[["--min-y",k],["--max-y",L],["--min-x",V],["--max-x",G]])j!==null&&!Number.isFinite(Number(j))&&(console.error(` ${z} requires a number, got: ${j}`),process.exit(1));let Y=e.indexOf("--near"),E=null;if(Y>=0){let z=Number(e[Y+1]),j=Number(e[Y+2]);(!Number.isFinite(z)||!Number.isFinite(j))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),E={x:z,y:j}}let v={exact:$,role:f,within:m,minX:V!==null?Number(V):null,maxX:G!==null?Number(G):null,minY:k!==null?Number(k):null,maxY:L!==null?Number(L):null,near:E,nth:u,first:y},N=await Xt(c,o,v,{agent:fe()}),F=N.payload;if(F?.error==="bridge-not-ready"&&(console.error(" rnxsim test bridge not ready"),process.exit(1)),F?.ambiguous){let z=F.candidates;console.error(` ambiguous: ${F.total} matches for "${o}"`);for(let j of z){let ke=j.abs?`@(${Math.round(j.abs.x)},${Math.round(j.abs.y)})`:"",Po=j.layout?` ${j.layout.width}x${j.layout.height}`:"",Ro=j.testID?` #${j.testID}`:"",Eo=j.text?` "${j.text}"`:"",Ao=j.ancestorTestIDs.length>0?` within ${j.ancestorTestIDs.slice(0,3).map(_o=>`#${_o}`).join(" > ")}`:"";console.error(` [${j.idx}] <${j.type}>${Eo}${Ro} ${ke}${Po}${Ao}`)}F.total>z.length&&console.error(` ... and ${F.total-z.length} more`),console.error(" pick one:"),console.error(" --nth <index> pick the nth match (top-to-bottom, left-to-right; negatives from end)"),console.error(" --within <testID> narrow to descendants of a node"),console.error(" --min-y / --max-y geometric filter (pixels, absolute)"),console.error(" --min-x / --max-x geometric filter (pixels, absolute)"),console.error(" --near <x> <y> pick the closest match to a point"),console.error(" --exact exact text match (default is substring)"),console.error(" --role <role> narrow to accessibilityRole"),console.error(" --first keep the old pick-first-silently behavior"),process.exit(2)}F?.nthOutOfRange&&(console.error(` not found: nth ${F.nth} of ${F.total} match${F.total===1?"":"es"} for "${o}"`),process.exit(1)),(!F||typeof F.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),me(N.result)||(P(`text "${o}"`,N),process.exit(1));let ne=tt(o,{id:F.target?.id??null,testID:F.target?.testID??null,type:F.target?.type??null,cx:F.cx,cy:F.cy},"text");await W("inspect tap-text",ne.step,ne.summary),console.log(JSON.stringify({matched:F.match,tapped:{nodeId:F.target?.nodeId??null,id:F.target?.id??null,testID:F.target?.testID??null,type:F.target?.type??null,cx:F.cx,cy:F.cy},...F.strategy&&F.strategy!=="matched-node"?{strategy:F.strategy}:{},...F.total>1||u!==null?{nth:{index:F.idx,total:F.total}}:{},...N.attempts>1?{attempts:N.attempts}:{},result:N.result},null,2));break}case"tap-best":{let o=r[1];o||(console.error(g("tap-best","<query>")),process.exit(1));let n=await Vt(c,o,{agent:fe()}),a=n.payload;a||(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnxsim find --interactive-targets\` to list candidates.`),process.exit(1)),"error"in a&&(console.error(` ${a.error}`),process.exit(1)),a.strategy==="none"&&(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnxsim find --interactive-targets\` to list candidates.`),process.exit(1));let l=a.node;me(n.result)||(P(`best "${o}"`,n),process.exit(1));let u=tt(o,{id:l.id,testID:l.testID,type:l.type,cx:a.cx,cy:a.cy},a.strategy==="testid"?"id":"text");await W("inspect tap-best",u.step,u.summary),console.log(JSON.stringify({matched:{strategy:a.strategy,nodeId:l.nodeId,id:l.id,testID:l.testID,type:l.type,text:l.text},tapped:{cx:a.cx,cy:a.cy},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"tap-id":{let o=r[1];o||(console.error(g("tap-id","<id>")),process.exit(1));let n=await zt(c,o,{agent:fe()}),a=n.payload;(!a||typeof a.cx!="number")&&(console.error(` not found: ${o}`),await ys(c,o),process.exit(1)),me(n.result)||(P(`id "${o}"`,n),process.exit(1));let l=tt(o,{id:a.target?.id??null,testID:a.target?.testID??null,type:a.target?.type??null,cx:a.cx,cy:a.cy},"id");await W("inspect tap-id",l.step,l.summary),console.log(JSON.stringify({matched:a.match,tapped:{nodeId:a.target?.nodeId??null,id:a.target?.id??null,testID:a.target?.testID??null,type:a.target?.type??null,cx:a.cx,cy:a.cy},...a.strategy&&a.strategy!=="matched-node"?{strategy:a.strategy}:{},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"type-into":{let o=r[1],n=r.slice(2).join(" ");(!o||!n)&&(console.error(g("type-into","<id> <text>")),process.exit(1));let a=JSON.stringify(o),l=await c.send({type:"evaluate",code:`(async () => {
642
+ const t = window.__sootsimTest
643
+ if (!t) return null
644
+ const n = await (t.findByTestId(${a}) || t.findById(${a}))
645
+ if (!n || !n.absolutePosition || !n.layout) return null
646
+ return {
647
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
648
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
649
+ id: n.id,
650
+ testID: n.testID,
651
+ type: n.type,
652
+ isTextInput: !!n.isTextInput,
653
+ secureTextEntry: !!n.secureTextEntry,
654
+ placeholder: n.placeholder || null,
655
+ }
656
+ })()`});(!l||typeof l.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),l.isTextInput||console.error(` warning: ${o} is not a text input (isTextInput: false)`);let u=await c.send({type:"tap",x:l.cx,y:l.cy,target:{id:l.id??o,testID:l.testID??o,text:null,type:l.type??null}}),m=l.secureTextEntry===!0,f=await Is(c,1e3,{targetId:o,secureTextEntry:m});f.visible||(console.error(` keyboard did not open after tapping ${o}`),process.exit(1));let $=f.focusedInput;$&&($.testID===o||$.id===o||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(o)} but focus is on ${JSON.stringify($.testID??$.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await c.send({type:"keyboard",action:"type",text:n});let y=m||we(f),k=y?Z:Ze(n,f),L=y&&f.focusedInput?{...f.focusedInput,secureTextEntry:!0,text:typeof f.focusedInput.text=="string"?Z:f.focusedInput.text}:f.focusedInput??null;await W("inspect type-into",{tapOn:{id:o},inputText:k},k===Z?`type-into #${o} ${Z}`:`type-into #${o} ${JSON.stringify(n)}`),console.log(JSON.stringify({target:o,isTextInput:l.isTextInput,secureTextEntry:y,keyboardOpened:f.visible??u?.keyboardOpened??!1,focusedInput:L,typed:k},null,2));break}case"type":{let o=r.slice(1).join(" ");o||(console.error(g("type","<text>")),process.exit(1));let n=await De(c,"type");await c.send({type:"keyboard",action:"type",text:o});let a=Ze(o,n);await W("inspect type",{inputText:a},a===Z?`type ${Z}`:`type ${JSON.stringify(o)}`),console.log(a===Z?` typed: ${Z}`:` typed: ${JSON.stringify(o)}`);break}case"key":{let o=r[1];o||(console.error(g("key","<name>")),process.exit(1)),await De(c,"key"),await c.send({type:"keyboard",action:"press",text:o}),await W("inspect key",{pressKey:o},`key ${o}`),console.log(` pressed: ${o}`);break}case"key-sequence":{let o=r.slice(1);o.length===0&&(console.error(g("key-sequence","<key> [<key> ...]")),process.exit(1)),await De(c,"key-sequence");for(let n of o)await c.send({type:"keyboard",action:"press",text:n});await W("inspect key-sequence",{pressKey:o.join(" ")},`key-sequence ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"keycode":{let o=r.slice(1);o.length===0&&(console.error(g("keycode","<code> [<code> ...]")),process.exit(1));let n=o.map(l=>({code:l,key:Ts(l)})),a=n.filter(l=>!l.key);a.length>0&&(console.error(` unsupported keycode(s): ${a.map(l=>l.code).join(", ")}`),process.exit(1)),await De(c,"keycode");for(let l of n)await c.send({type:"keyboard",action:"press",text:l.key});await W("inspect keycode",{pressKey:n.map(l=>l.key).join(" ")},`keycode ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"dispatch":{let o=r[1];o||(console.error(g("dispatch","<char>")),process.exit(1)),await c.send({type:"keyboard",action:"dispatchKey",text:o}),await W("inspect dispatch",{dispatchKey:o},`dispatch ${JSON.stringify(o)}`),console.log(` dispatched: ${o}`);break}case"dismiss":{await c.send({type:"keyboard",action:"dismiss"}),await W("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r);if(a){let $=await Ee(c,a);$||(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),o=$.x,n=$.y}let l=r[3]?Number(r[3]):80;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(l))&&(console.error(g("double-tap","<testid> | <x> <y> [gapMs] | --testid <id>")),process.exit(1));let u=Math.max(0,Math.round(l)),f={...await $e(c,{type:"doubleTap",x:o,y:n,gapMs:u}),gapMs:u};f?.ok&&await W("inspect double-tap",{doubleTapAtCoords:{x:o,y:n,gapMs:u}},`double-tap @${o},${n}`),console.log(JSON.stringify(f,null,2));break}case"long-press":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r),l=null;if(a){let y=await Ee(c,a);y||(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),o=y.x,n=y.y,l={id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}let u=a?r[1]:r[3],m=u?Number(u):600;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(m))&&(console.error(g("long-press","<testid> | <x> <y> [durationMs] | --testid <id>")),process.exit(1));let f=Math.max(0,Math.round(m)),$=await c.send({type:"longPress",x:o,y:n,durationMs:f,target:l});$?.ok&&await W("inspect long-press",{tapAtCoords:{x:o,y:n}},`long-press @${o},${n}`),console.log(JSON.stringify($,null,2));break}case"touch":{let o=r[1],n=Number(r[2]),a=Number(r[3]),l=r[4]?Number(r[4]):999,u=o==="down"?"touchDown":o==="move"?"touchMove":o==="up"?"touchUp":o==="cancel"?"touchCancel":null;u||(console.error(g("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),o!=="cancel"&&(!Number.isFinite(n)||!Number.isFinite(a))&&(console.error(g("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let m=Math.max(1,Math.round(l)),f=await $e(c,u==="touchCancel"?{type:u,pointerId:m}:{type:u,x:n,y:a,pointerId:m});f?.ok&&o!=="cancel"&&await W("inspect touch",{tapAtCoords:{x:n,y:a}},`touch ${o} @${n},${a}`),console.log(JSON.stringify(f,null,2));break}case"gesture":{let o=["scroll-up","scroll-down","scroll-left","scroll-right","swipe-from-left-edge","swipe-from-right-edge","swipe-from-top-edge","swipe-from-bottom-edge"],n=r[1],a=r[2]?Number(r[2]):220;(!n||!Number.isFinite(a))&&(console.error(g("gesture","<preset> [durationMs]")),console.error(` presets: ${o.join(", ")}`),process.exit(1)),o.includes(n)||(console.error(` unknown gesture preset: ${n}`),console.error(` presets: ${o.join(", ")}`),process.exit(1));let l=await c.send({type:"evaluate",code:`(async () => {
657
+ const spec = globalThis.__sootsimDeviceSpec || {}
658
+ return {
659
+ width: spec.width || window.innerWidth || 393,
660
+ height: spec.height || window.innerHeight || 852,
661
+ statusBarHeight: spec.statusBarHeight || 0,
662
+ homeIndicatorHeight: spec.homeIndicatorHeight || 0,
663
+ }
664
+ })()`}),u=Number(l?.width)||393,m=Number(l?.height)||852,f=Number(l?.statusBarHeight)||0,$=Number(l?.homeIndicatorHeight)||0,y=Math.round(u/2),k=Math.round(m/2),L=Math.max(24,f+18),V=Math.max(24,$+18),G=18,Y=Math.min(220,Math.round(m*.24)),E=Math.min(180,Math.round(u*.32)),v=y,N=k,F=y,ne=k;switch(n){case"scroll-up":N=k+Math.round(Y/2),ne=k-Math.round(Y/2);break;case"scroll-down":N=k-Math.round(Y/2),ne=k+Math.round(Y/2);break;case"scroll-left":v=y+Math.round(E/2),F=y-Math.round(E/2);break;case"scroll-right":v=y-Math.round(E/2),F=y+Math.round(E/2);break;case"swipe-from-left-edge":v=G,N=k,F=Math.min(u-G,G+E);break;case"swipe-from-right-edge":v=u-G,N=k,F=Math.max(G,u-G-E);break;case"swipe-from-top-edge":v=y,N=L,ne=Math.min(m-V,L+Y);break;case"swipe-from-bottom-edge":v=y,N=m-V,ne=Math.max(L,m-V-Y);break}let z=Math.max(8,Math.round(a/16)),j=Math.max(1,Math.round(a/z)),ke=await $e(c,{type:"drag",fromX:v,fromY:N,toX:F,toY:ne,steps:z,stepMs:j});ke?.ok&&await W("inspect gesture",{swipe:{start:`${v}, ${N}`,end:`${F}, ${ne}`,duration:Math.max(1,Math.round(a))}},`gesture ${n}`),console.log(JSON.stringify({preset:n,from:{x:v,y:N},to:{x:F,y:ne},result:ke},null,2));break}case"scroll":{let o=xe(e),n=Ns(e),a=o?.mode==="testid"?o.value:n==null?r[1]:null,l=o||n!=null?1:2,u=Number(r[l]),m=Number(r[l+1]);(!a&&n==null||!Number.isFinite(u)||!Number.isFinite(m))&&(console.error(g("scroll","<id> <x> <y> | --testid <id> <x> <y> | --node-id <nodeId> <x> <y>")),process.exit(1));let f=await c.send({type:"evaluate",code:`(async () => {
665
+ const t = window.__sootsimTest
666
+ if (!t) return null
667
+ const n = ${n!=null?`await t.inspectByNodeId(${JSON.stringify(n)})`:`await t.findByTestId(${JSON.stringify(a)})
668
+ || await t.findById(${JSON.stringify(a)})`}
669
+ if (!n || !n.absolutePosition || !n.layout) return null
670
+ return {
671
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
672
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
673
+ }
674
+ })()`}),$=await X(c,"scrollTo",n!=null?{nodeId:n}:a,u,m,!1);if($?.ok){let y=n!=null?`node ${n}`:`#${a}`;await W("inspect scroll",{scrollTo:{...n!=null?{nodeId:n}:{id:a},x:u,y:m}},`scroll ${y} -> ${u},${m}`)}console.log(JSON.stringify({...$,...f?{at:{x:f.cx,y:f.cy}}:{}},null,2));break}case"state":{let o=r[1];if(s==="get"&&!o){let a=await X(c,"getRuntimeState"),l=await c.send({type:"evaluate",code:Te});if(a&&typeof a=="object"&&a.diagnostics&&(a.diagnostics.errors=l?.errors??0,a.diagnostics.warnings=l?.warnings??0),a&&typeof a=="object"&&a.shell==null)try{let u=await ue(c);u&&(a.shell=u)}catch{}console.log(JSON.stringify(a,null,2));break}if(!o||o==="--help"||o==="-h"){console.log(`
675
+ ${w("state")} \u2014 dump raw runtime state
676
+
677
+ subcommands:
678
+ shell dump shell transition/layout state
679
+ worker dump render-worker host/animation state
680
+ keyboard dump keyboard visibility, mode, and focused input
681
+ ownership dump surface ownership + pointerOnSurface delivery stats
682
+ worklets dump tenant + shell worklet-runtime slot/handler counts
683
+ scroll-input dump shell-owned scroll gesture and momentum state
684
+ scroll-mirror dump shell scroll registry entries and offsets
685
+ node <id> dump raw node info by id or testID
686
+ scroll <id> dump scroll metrics and runtime state
687
+ scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
688
+ hit <x> <y> dump the hit-test ancestry at coordinates
689
+ gesture <x> <y> dump gesture routing/debug info at coordinates
690
+ gesture-seam dump shell-hosted gesture recognizer state/events
691
+
692
+ examples:
693
+ ${w("state")} shell
694
+ ${w("state")} worker
695
+ ${w("state")} keyboard
696
+ ${w("state")} ownership
697
+ ${w("state")} worklets
698
+ ${w("state")} scroll-input
699
+ ${w("state")} scroll-mirror
700
+ ${w("state")} node photos
701
+ ${w("state")} scroll feed
702
+ ${w("state")} scroll-hit 360 420
703
+ ${w("state")} hit 200 720
704
+ `);break}let n;switch(o){case"shell":n=await ue(c,500);break;case"worker":n=await ce(c,"__sootsimRenderHost.queryStats");break;case"ownership":n=await c.send({type:"evaluate",code:`(() => {
705
+ const h = window.__sootsimRenderHost
706
+ if (!h || typeof h.getOwnershipSnapshot !== 'function') {
707
+ return { error: 'getOwnershipSnapshot not available' }
708
+ }
709
+ return h.getOwnershipSnapshot()
710
+ })()`});break;case"keyboard":n=await c.send({type:"evaluate",code:`(async () => {
711
+ const kb = window.__sootsimKeyboard
712
+ const test = window.__sootsimTest
713
+ if (!kb) return { error: 'keyboard bridge not available' }
714
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
715
+ const secureTextEntry =
716
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
717
+ const visible = kb.isVisible()
718
+ const mode = kb.getMode()
719
+ let focused = null
720
+ if (test && typeof test.getFocusedNode === 'function') {
721
+ try {
722
+ focused = await test.getFocusedNode()
723
+ } catch {}
724
+ }
725
+ return {
726
+ visible,
727
+ mode,
728
+ layout,
729
+ focusedInput: focused ? {
730
+ nodeId: focused.nodeId ?? null,
731
+ testID: focused.testID || null,
732
+ id: focused.id || null,
733
+ placeholder: focused.placeholder || null,
734
+ secureTextEntry,
735
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
736
+ } : null,
737
+ }
738
+ })()`}),n=et(n);break;case"node":{let a=r[2];a||(console.error(` usage: ${w("state")} node <id>`),process.exit(1)),n=await X(c,"findByTestId",a)||await X(c,"findById",a);break}case"scroll":{let a=r[2];a||(console.error(` usage: ${w("state")} scroll <id>`),process.exit(1)),n=await X(c,"getScrollState",a);break}case"scroll-hit":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} scroll-hit <x> <y>`),process.exit(1)),n=await X(c,"getScrollStateAt",a,l);break}case"hit":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} hit <x> <y>`),process.exit(1)),n=await X(c,"debugHitAt",a,l);break}case"gesture":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} gesture <x> <y>`),process.exit(1)),n=await X(c,"debugGestureAt",a,l);break}case"gesture-seam":n=await ce(c,"SootSim.bridges.mainShell.callTestBridge","getShellGestureSeamDebug");break;case"worklets":{let[a,l]=await Promise.all([X(c,"getWorkletSlotStats"),ce(c,"SootSim.bridges.mainShell.callTestBridge","getWorkletSlotStats")]);n={tenant:a,shell:l};break}case"scroll-input":n=await ce(c,"SootSim.bridges.mainShell.callTestBridge","getShellScrollInputDebug");break;case"scroll-mirror":n=await ce(c,"SootSim.bridges.mainShell.callTestBridge","getScrollMirrorDebug");break;default:console.error(` unknown state subcommand: ${o}`),process.exit(1)}console.log(JSON.stringify(n,null,2));break}case"shell":{let o=r[1];if(!o||o==="--help"||o==="-h"){console.log(`
739
+ ${w("shell")} \u2014 run built-in shell commands
740
+
741
+ subcommands:
742
+ launch <appId> [waitMs] [--clear-state]
743
+ launch app and wait for settled shell state
744
+ home [waitMs] go home and wait for settled shell state
745
+ switcher [waitMs] open switcher and wait for settled shell state
746
+ open-card <appId> [waitMs]
747
+ open a specific switcher card and wait for app settle
748
+ appearance <light|dark|auto|toggle>
749
+ update simulator appearance
750
+ lock toggle device lock state
751
+ shake trigger the simulator shake gesture
752
+
753
+ examples:
754
+ ${w("shell")} launch photos
755
+ ${w("shell")} launch rn --clear-state
756
+ ${w("shell")} launch photos 1500
757
+ ${w("shell")} home 500
758
+ ${w("shell")} switcher 800
759
+ ${w("shell")} open-card clock 800
760
+ ${w("shell")} appearance dark
761
+ ${w("shell")} lock
762
+ `);break}let n=o==="launch"||o==="open-card"||o==="home"||o==="switcher",a=o==="launch"||o==="open-card"?r[3]:r[2],l=a?Number(a):350;n&&(!Number.isFinite(l)||l<0)&&(console.error(g("shell",o==="launch"||o==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let u=!1,m=!1,f=null,$=e.includes("--clear-state");if(o==="launch"){let y=r[2];y||(console.error(g("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),$&&await c.send({type:"evaluate",code:Je(!0)}),u=!!await ye(c,"launchApp",l,y),{settled:m,state:f}=await _e(c,Math.round(l),k=>!!k&&k.state==="app"&&k.activeApp===y&&k.showSwitcher===!1&&k.switcherPhase==="idle"&&typeof k.launchProgress=="number"&&k.launchProgress>=.98),u&&await W("inspect shell launch",$?{launchApp:{clearState:!0}}:{launchApp:{}},$?"launch app (clear state)":"launch app")}else if(o==="home")u=!!await ye(c,"goHome",l),{settled:m,state:f}=await _e(c,Math.round(l),y=>!!y&&y.state==="home"&&y.activeApp==null&&y.showSwitcher===!1&&y.switcherPhase==="idle"&&typeof y.launchProgress=="number"&&y.launchProgress>=.98);else if(o==="switcher")u=!!await ye(c,"openSwitcher",l),{settled:m,state:f}=await _e(c,Math.round(l),y=>!!y&&y.state==="app"&&y.showSwitcher===!0&&y.switcherPhase==="idle"&&typeof y.zoomLevel=="number"&&Math.abs(y.zoomLevel)<=.02&&typeof y.horizontalZoom=="number"&&Math.abs(y.horizontalZoom)<=.02),m&&(await oe(vs),f=await ue(c));else if(o==="open-card"){let y=r[2];y||(console.error(g("shell","open-card <appId> [settleMs]")),process.exit(1)),u=!!await ye(c,"openSwitcherCard",l,y),{settled:m,state:f}=await _e(c,Math.round(l),k=>!!k&&k.state==="app"&&k.activeApp===y&&k.showSwitcher===!1&&k.switcherPhase==="idle"&&typeof k.zoomLevel=="number"&&k.zoomLevel>=.98&&typeof k.horizontalZoom=="number"&&k.horizontalZoom>=.98),u&&await W("inspect shell open-card",{openSwitcherCard:{appId:y}},`open switcher card ${y}`)}else if(o==="appearance"){let y=r[2];(!y||!["light","dark","auto","toggle"].includes(y))&&(console.error(g("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let k=await To(c,"appearance",y);if(u=!!k?.ok,f={appearance:k},u){let L=k?.applied??y;console.log(` appearance: ${L}`)}}else if(o==="lock"||o==="shake"){let y=await To(c,o);u=!!y?.ok,f={[o]:y}}else console.error(` unknown shell subcommand: ${o}`),process.exit(1);console.log(JSON.stringify({ok:u,settled:m,state:f},null,2));break}case"url":{await uo(c,{args:i});break}case"reload":{let a=!1,l=!1;try{await c.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let f=await c.send({type:"evaluate",code:`;(async () => {
763
+ // in-place guest reload is only valid while the page still runs
764
+ // the engine build the server would serve NOW. the shell dev
765
+ // server has no HMR client, so a long-lived sim tab otherwise
766
+ // keeps a stale engine forever while builds churn underneath it.
767
+ // compare the inlined engine manifest against a fresh fetch of
768
+ // this page's html; any drift means the whole page must reload.
769
+ let engineStale = false
770
+ try {
771
+ const loaded = document.getElementById('__sootsim-engine-manifest')?.textContent
772
+ if (loaded) {
773
+ const res = await fetch(location.href, { cache: 'no-store' })
774
+ const html = await res.text()
775
+ const m = html.match(/<script[^>]*id="__sootsim-engine-manifest"[^>]*>([^<]*)<\\/script>/)
776
+ if (m && m[1] !== loaded) engineStale = true
777
+ }
778
+ } catch {}
779
+ const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
780
+ if (!engineStale && typeof reloadExternalApp === 'function') {
781
+ reloadExternalApp()
782
+ return { kind: 'external-app' }
783
+ }
784
+ window.location.reload()
785
+ return { kind: 'page', engineStale }
786
+ })()`});l=!!f&&f.kind==="external-app",a=!0,f&&f.engineStale&&console.log(" engine build changed since page load \u2014 full page reload")}catch{}console.log(" reloading...");let u=c,m=null;if(l)m=await Ne(c,{timeoutMs:1e4,errorGraceMs:3e3});else{a&&await oe(300);let $=await At(M,O,x,{timeoutMs:3e4,simIdSource:_});$?(u=$,m=await Ne($,{timeoutMs:3e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 30000ms"),u=null)}if(m)if(m.ready){let f=m.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${m.elapsedMs}ms: ${m.nodes} nodes${f}`)}else if(m.source==="error-bail")console.log(` \u26A0 reload bailed after ${m.elapsedMs}ms: ${m.errors} console error(s), ready signal never fired`);else{let f=wo(m);console.log(` \u26A0 reload timed out after ${m.elapsedMs}ms \u2014 ${f} (nodes: ${m.nodes}, targets: ${m.targets}, errors: ${m.errors})`)}if(u)try{let f=await ge(u,10);if(u!==c&&u.close(),Array.isArray(f)&&f.length>0){console.log(`
787
+ \u26A0 ${f.length} error(s) during mount:
788
+ `);for(let $ of f){let y=$.args.map(k=>typeof k=="object"?JSON.stringify(k):k).join(" ");if(console.log(` ${y}`),$.stack){let k=$.stack.split(`
789
+ `).slice(0,2);for(let L of k)console.log(` ${L.trim()}`)}}}}catch{}m&&!m.ready&&(process.exitCode=1);break}case"storage-clear":{if(await Le(c),await c.send({type:"evaluate",code:Je(!0)})!==!0){C(i)?B({cleared:!1,ready:!1,error:"external app reload bridge is unavailable"}):console.error(" storage clear failed: external app reload bridge is unavailable"),process.exitCode=1;break}let l=await Ne(c,{timeoutMs:1e4,errorGraceMs:3e3});if(C(i)){B({cleared:!0,ready:l.ready,reload:l}),l.ready||(process.exitCode=1);break}if(l.ready){let u=l.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` cleared tenant storage; ready in ${l.elapsedMs}ms: ${l.nodes} nodes${u}`)}else if(l.source==="error-bail")console.log(` \u26A0 storage clear reloaded but bailed after ${l.elapsedMs}ms: ${l.errors} console error(s), ready signal never fired`);else{let u=wo(l);console.log(` \u26A0 storage clear reloaded but timed out after ${l.elapsedMs}ms \u2014 ${u} (nodes: ${l.nodes}, targets: ${l.targets}, errors: ${l.errors})`)}try{let u=await ge(c,10);if(Array.isArray(u)&&u.length>0){console.log(`
790
+ \u26A0 ${u.length} error(s) during mount:
791
+ `);for(let m of u){let f=m.args.map($=>typeof $=="object"?JSON.stringify($):$).join(" ");if(console.log(` ${f}`),m.stack){let $=m.stack.split(`
792
+ `).slice(0,2);for(let y of $)console.log(` ${y.trim()}`)}}}}catch{}l.ready||(process.exitCode=1);break}case"js":{let o=r.slice(1).join(" ");if(o||(console.error(g("js","<javascript>")),console.error(""),console.error(" runs the snippet in the engine realm. SootSim is the"),console.error(" canonical state surface \u2014 reach into it directly."),console.error(""),console.error(" examples:"),console.error(` ${w("js")} SootSim.bridges.test.findByText("Sign in")`),console.error(` ${w("js")} SootSim.bridges.debug.snapshot("before")`),console.error(` ${w("js")} SootSim.bridges.keyboard.type("hello")`),console.error(` ${w("js")} SootSim.state.root.children.length`),process.exit(1)),e.includes("--tenant")){let m=r.slice(1).filter($=>$!=="--tenant").join(" "),f=await c.send({type:"evaluate",code:`(async () => SootSim.bridges.test.evalInTenant(${JSON.stringify(m)}))()`});console.log(JSON.stringify(f,null,2));break}let n=o;n.startsWith("(async")||(n=`(async () => ${n})()`);let a=await c.send({type:"evaluate",code:n});console.log(JSON.stringify(a,null,2));let l=o.toLowerCase(),u=[];(l.includes("sootsim:gohome")||l.includes("gohome"))&&u.push("rnxsim shell home"),(l.includes("sootsim:appswitcher")||l.includes("appswitcher"))&&u.push("rnxsim shell switcher"),(l.includes("keyboard.isvisible")||l.includes("keyboard.getmode"))&&u.push("rnxsim debug state keyboard"),l.includes("interact.tap")&&u.push("rnxsim do tap <x> <y>"),l.includes("keyboard.type")&&u.push("rnxsim do type <text>"),(l.includes("keyboard.press")||l.includes("keyboard.dispatchkey"))&&u.push("rnxsim do key <name>"),l.includes("keyboard.dismiss")&&u.push("rnxsim do dismiss"),l.includes("dumptree")&&u.push("rnxsim get tree"),l.includes("dumpaccessibilitytree")&&u.push("rnxsim get a11y"),l.includes("getnodecount")&&u.push("rnxsim get count"),l.includes("findbytext")&&u.push("rnxsim find <text>"),(l.includes("findbytestid")||l.includes("findbyid"))&&u.push("rnxsim find --testid <id>"),l.includes("document.hidden")&&u.push("rnxsim debug state keyboard (includes tab health)"),u.length>0&&Q("prefer-cli-over-eval",u);break}case"globals":{let o=await c.send({type:"evaluate",code:`(async () => {
793
+ const globals = {}
794
+
795
+ // test bridge (proxy in worker mode)
796
+ const testMethods = [
797
+ 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
798
+ 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
799
+ 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
800
+ 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
801
+ 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
802
+ 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
803
+ 'debugGestureAt'
804
+ ]
805
+ globals['test (\u2192 __sootsimTest)'] = testMethods
806
+
807
+ // debug
808
+ if (window.__sootsimDebug) {
809
+ globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
810
+ }
811
+
812
+ // interact
813
+ if (window.__sootsimInteract) {
814
+ globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
815
+ }
816
+
817
+ // keyboard
818
+ if (window.__sootsimKeyboard) {
819
+ globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
820
+ }
821
+
822
+ // other globals
823
+ globals['other'] = [
824
+ 'root (\u2192 __sootsimRoot) - live node tree',
825
+ 'render() (\u2192 __sootsimForceRender) - force re-render'
826
+ ]
827
+
828
+ return globals
829
+ })()`});console.log(` rnx JS API:
830
+ `);for(let[n,a]of Object.entries(o)){console.log(` ${n}:`);for(let l of a)console.log(` .${l}`);console.log("")}console.log(` use: ${w("js")} <expression>`),console.log(` example: ${w("js")} test.findByText("Sign in")`);break}case"describe":{await Zt({bridge:c,args:e,positional:r});break}case"perf":{b==="debug"&&!t.internalPerfCommand&&(console.error(" `rnxsim debug perf` was removed. use `rnxsim perf shell ...`."),process.exit(1));let o=r[1];if(t.internalPerfCommand==="scroll"){if(!o||o==="--help"||o==="-h"){console.log(`
831
+ ${w("perf")} <start|stop> [options]
832
+
833
+ records per-frame scroll offsets from the tenant worker, shell worker,
834
+ and compositor worker. timestamps use the shared wall clock, while frame
835
+ sequences remain separate because the workers do not share a frame id.
836
+
837
+ options:
838
+ --limit <n> maximum samples retained per layer (default 6000)
839
+ --json emit every per-frame sample on stop
840
+
841
+ examples:
842
+ ${w("perf")} start
843
+ # ... perform consecutive swipes ...
844
+ ${w("perf")} stop
845
+ ${w("perf")} stop --json
846
+ `);break}if(o==="start"){let n=i.find((u,m)=>i[m-1]==="--limit"),a=n===void 0?6e3:Number(n);(!Number.isFinite(a)||a<120)&&(console.error(" error: --limit must be a number of at least 120"),process.exit(1));let l=await c.send({type:"evaluate",code:`(async () => {
847
+ const perf = window.SootSim?.bridges?.scrollPerf
848
+ if (!perf) return { error: 'scroll performance profile unavailable' }
849
+ await perf.start(${Math.floor(a)})
850
+ return { started: true }
851
+ })()`});l?.error&&(console.error(` error: ${l.error}`),process.exit(1)),console.log(` scroll profiling started: perform consecutive swipes, then run '${w("perf")} stop'`);break}if(o==="stop"){let n=await c.send({type:"evaluate",code:`(async () => {
852
+ const perf = window.SootSim?.bridges?.scrollPerf
853
+ if (!perf) return { error: 'scroll performance profile unavailable' }
854
+ return await perf.stop()
855
+ })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1));let a=n;if(C(i)){B(a);break}console.log(` scroll performance trace:
856
+ `),console.log(` duration: ${a.stoppedAt-a.startedAt}ms (worker series are timestamp-aligned, not frame-paired)`),console.log(` samples: tenant ${a.layers.tenant.length} \xB7 shell ${a.layers.shell.length} \xB7 compositor ${a.layers.compositor.length}`),console.log(""),console.log(" offset and phase changes (--json includes every per-frame sample):"),console.log(" t(ms) layer surface node offsetY slotY phase paint");let l=[];for(let u of Object.values(a.layers)){let m=new Map;for(let f of u){let $=`${f.surfaceId}:${f.nodeId}`,y=`${f.offsetY}:${f.slotY??""}:${f.phase??""}`;m.get($)!==y&&(m.set($,y),l.push(f))}}l.sort((u,m)=>u.t-m.t||u.seq-m.seq);for(let u of l)console.log(` ${String(u.t-a.startedAt).padStart(5)} ${u.layer.padEnd(10)} ${u.surfaceId.padEnd(8)} ${String(u.nodeId).padStart(5)} ${u.offsetY.toFixed(2).padStart(8)} ${u.slotY===void 0?" -":u.slotY.toFixed(2).padStart(8)} ${(u.phase??"-").padEnd(8)} ${u.paint===void 0?"-":u.paint}`);break}console.error(` unknown scroll perf command: ${o}`),process.exit(1)}if(!o||o==="--help"||o==="-h"){console.log(`
857
+ ${w("perf")} \u2014 shell frame profiling (the worker that paints)
858
+
859
+ records per-painted-frame timing in the shell worker \u2014 the surface that
860
+ actually draws the app's pixels \u2014 merged with render-profile counters
861
+ (node visits, boundary records/replays, raster tier, blur ms, draw calls).
862
+
863
+ subcommands:
864
+ start begin recording (clears prior frames + counters)
865
+ stop stop recording and report results
866
+ transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
867
+
868
+ stop and transition accept --json for the full machine-readable payload.
869
+
870
+ examples:
871
+ ${w("perf")} start
872
+ # ... interact with the app ...
873
+ ${w("perf")} stop
874
+ ${w("perf")} stop --json
875
+ ${w("perf")} transition goHome
876
+ `);break}switch(o){case"start":{let n=await c.send({type:"evaluate",code:`(() => {
877
+ if (!window.__sootsimShellPerf) {
878
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
879
+ }
880
+ window.__sootsimShellPerf.start()
881
+ return { started: true }
882
+ })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1)),console.log(` shell profiling started \u2014 interact with the app, then run '${w("perf")} stop'`);break}case"stop":{let n=await c.send({type:"evaluate",code:`(async () => {
883
+ if (!window.__sootsimShellPerf) {
884
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
885
+ }
886
+ return await window.__sootsimShellPerf.stop()
887
+ })()`});if(n?.error&&(console.error(` error: ${n.error}`),n.error==="timeout"&&console.error(" (shell worker did not answer within 5s \u2014 is a sim loaded?)"),process.exit(1)),C(i)){B(n);break}Io(n);break}case"transition":{let n=r[2];if(!n||!["goHome","appSwitcher","lockScreen"].includes(n)){console.log(`
888
+ ${w("perf")} transition <event> \u2014 profile a shell transition
889
+
890
+ events:
891
+ goHome swipe-to-home animation
892
+ appSwitcher app switcher card animation
893
+ lockScreen lock screen transition
894
+
895
+ note: uses 600ms capture window \u2014 may need --timeout 10000 flag
896
+
897
+ examples:
898
+ ${w("perf")} transition goHome --timeout 10000
899
+ ${w("perf")} transition appSwitcher
900
+ `);break}let l=`sootsim:${n}`;Me(` profiling ${n} transition...`),Me(" (use --timeout 10000 if this times out)");let u=await c.send({type:"evaluate",code:`(async () => {
901
+ if (!window.__sootsimShellPerf) {
902
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
903
+ }
904
+ window.__sootsimShellPerf.start()
905
+ // give a frame for profiling to engage before the event
906
+ await new Promise(r => requestAnimationFrame(() => r(undefined)))
907
+ window.dispatchEvent(new Event('${l}'))
908
+ // shell animations are ~300-500ms; fixed timing avoids complex
909
+ // animation-end detection
910
+ await new Promise(r => setTimeout(r, 600))
911
+ return await window.__sootsimShellPerf.stop()
912
+ })()`});if(u?.error&&(console.error(` error: ${u.error}`),process.exit(1)),C(i)){B(u);break}Me(` ${n} transition profiled:`),Io(u);break}default:console.error(` unknown perf subcommand: ${o}`),console.error(" valid: start, stop, transition"),/^--?reset$/.test(o)&&console.error(" note: 'perf start' already clears prior frames \u2014 no reset needed"),(o==="stats"||o==="frames"||o==="worst")&&(console.error(" note: the tenant sampler (stats/frames/worst) was removed \u2014 it hardcoded"),console.error(" layout/render/copy to zero because the shell worker owns every real paint."),console.error(" use 'perf start' / 'perf stop' (worst frames are in the stop report).")),process.exit(1)}break}case"errors":{let o=r[1];if(o==="clear"){await Le(c),C(i)?B({cleared:!0}):console.log(" error buffer cleared");break}let n=o?Number(o):20,a=await ge(c,n);if(C(i)){B(a);break}if(a.length===0){console.log(" no errors captured");break}console.log(` ${a.length} error(s):
913
+ `);for(let l of a){let u=ae(l.timestamp),m=l.args.map(f=>typeof f=="object"?JSON.stringify(f):f).join(" ");if(console.log(` [${u}] ${m}`),l.stack){let f=l.stack.split(`
914
+ `).slice(0,3);for(let $ of f)console.log(` ${$.trim()}`)}}break}case"warnings":{let o=r[1]?Number(r[1]):20,n=await kt(c,o);if(C(i)){B(n);break}if(n.length===0){console.log(" no warnings captured");break}console.log(` ${n.length} warning(s):
915
+ `);for(let a of n){let l=ae(a.timestamp),u=a.args.map(m=>typeof m=="object"?JSON.stringify(m):m).join(" ");console.log(` [${l}] ${u}`)}break}case"animations":{let o=await X(c,"listAnimations")??[];if(e.includes("--json")){console.log(JSON.stringify(o,null,2));break}if(o.length===0){console.log(" no active animations");break}console.log(` ${o.length} active animation(s):
916
+ `);for(let n of o){let a=String(n.realm??"tenant").padEnd(6),l=String(n.kind).padEnd(10),u=typeof n.from=="number"&&typeof n.to=="number"?`${n.from.toFixed(2)}\u2192${n.to.toFixed(2)}`:"\u2014",m=Number(n.current??0).toFixed(2),f=typeof n.progress=="number"?`${Math.round(n.progress*100)}%`:"\u2014",$=`${Math.round(n.elapsedMs??0)}ms`,y=[n.loop?"loop":null,n.layoutBound?"layout":null,n.remoteDriven?"remote-driven":n.graphBacked?"graph":null,n.visible===!1?"offscreen":null].filter(Boolean),k=y.length>0?` [${y.join(" ")}]`:"";console.log(` #${n.id} ${a} ${l} ${u.padEnd(14)} cur=${m.padEnd(7)} ${f.padStart(4)} ${$}${k}`)}break}case"animation":{let o=r[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${w("animation")} <id>`),process.exit(1));let n=Number(o);Number.isFinite(n)||(console.error(` invalid id: ${o}`),process.exit(1));let a=await X(c,"getAnimation",n);console.log(JSON.stringify(a,null,2));break}case"stop-animation":{let o=r[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${w("stop-animation")} <id|all>`),process.exit(1));let n=o==="all"?"all":Number(o);n!=="all"&&!Number.isFinite(n)&&(console.error(` invalid id: ${o}`),process.exit(1));let a=await X(c,"stopAnimation",n);console.log(` stopped ${a??0} animation(s)`);break}case"requests":{let o=r[1];if(o==="clear"){await Tt(c),C(i)?B({cleared:!0}):console.log(" request buffer cleared");break}let n=o==="all",a=n?r[2]:o,l=a?Number(a):20,u=await It(c,{failed:!n,limit:l});if(C(i)){B(u);break}if(u.length===0){console.log(n?" no requests captured":" no failed requests captured");break}console.log(` ${u.length} ${n?"request(s)":"failed request(s)"}:
917
+ `);for(let m of u){let f=ae(m.timestamp);console.log(` [${f}] ${U(m)}`),m.responseBody?console.log(` ${m.responseBody}`):m.error&&console.log(` ${m.error}`)}break}case"network":{let o=r[1],n=null,a=null,l=!1,u=!1,m=1e3,f=!1,$=!1;for(let E=0;E<i.length;E++){let v=i[E];if(v==="--filter")n=i[E+1]??null,E++;else if(v==="--limit"){let N=Number(i[E+1]);Number.isFinite(N)&&(a=N),E++}else if(v==="--threshold"){let N=Number(i[E+1]);Number.isFinite(N)&&N>0&&(m=N),E++}else v==="--failed"?l=!0:v==="--slow"?u=!0:v==="--tail"||v==="-f"?f=!0:v==="--json"&&($=!0)}if(o==="clear"){await c.send({type:"evaluate",code:'window.__sootsimObservability?.network.clear(); "cleared"'}),console.log(" network buffer cleared");break}if(o==="get"){let E=r[2];E||(console.error(" usage: rnxsim network get <id>"),process.exit(1));let v=await c.send({type:"evaluate",code:`(() => {
918
+ const obs = window.__sootsimObservability;
919
+ if (!obs) return null;
920
+ return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(E)}) || null;
921
+ })()`});v||(console.error(` no entry with id ${E}`),process.exit(1)),$?console.log(JSON.stringify(v,null,2)):xs(v);break}let y=a??(f?200:o?Number(o):20);Number.isFinite(y)||(console.error(` invalid limit: ${o} \u2014 \`network\` takes a numeric count (e.g. ${w("network")} 100).
922
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let k=async()=>{let E=await c.send({type:"evaluate",code:`(() => {
923
+ const obs = window.__sootsimObservability;
924
+ if (!obs) return { ok: false };
925
+ return { ok: true, entries: obs.network.getSnapshot() };
926
+ })()`});if(!E||!E.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return E.entries??[]},L=E=>{let v=E;if(l&&(v=v.filter(N=>!!N.error||N.status!=null&&N.status>=400)),u&&(v=v.filter(N=>N.durationMs!=null&&N.durationMs>=m)),n){let N=n.toLowerCase();v=v.filter(F=>(F.displayUrl||F.url).toLowerCase().includes(N))}return u&&!f&&(v=[...v].sort((N,F)=>(F.durationMs??0)-(N.durationMs??0))),v};if(!f){let E=await k(),v=L(E).slice(-y);if($){console.log(JSON.stringify(v,null,2));break}if(v.length===0){E.length===0?console.log(" no network requests captured"):console.log(u?` no requests slower than ${m}ms (${E.length} total \u2014 try --threshold <ms>)`:" no matching requests");break}console.log(u?` ${v.length} request(s) slower than ${m}ms (sorted by duration desc):
927
+ `:` ${v.length} request(s):
928
+ `);for(let N of v)xo(N);break}console.log(` tailing network (ctrl-c to stop)...
929
+ `);let V=new Set,G=!0,Y=()=>{G=!1};process.on("SIGINT",Y);try{for(;G;){let E=await k(),v=L(E);for(let N of v)N.durationMs!=null&&(V.has(N.id)||(V.add(N.id),$?console.log(JSON.stringify(N)):xo(N)));await oe(250)}}finally{process.off("SIGINT",Y)}break}case"logs":{let o=r[1],n=null,a=null,l=null,u=!1,m=!1,f=!1;for(let v=0;v<i.length;v++){let N=i[v];if(N==="--filter")n=i[v+1]??null,v++;else if(N==="--limit"){let F=Number(i[v+1]);Number.isFinite(F)&&(a=F),v++}else N==="--level"?(l=i[v+1]??null,v++):N==="--tail"||N==="-f"?u=!0:N==="--json"?m=!0:(N==="--internal"||N==="--all")&&(f=!0)}let $=l?new Set(l.split(",").map(v=>v.trim()).filter(v=>v==="log"||v==="info"||v==="warn"||v==="error"||v==="debug")):null;if(o==="clear"){await Nt(c),console.log(" log buffer cleared");break}let y=!m&&process.stdout.isTTY===!0,k=a??(u?500:o?Number(o):50);Number.isFinite(k)||(console.error(` invalid limit: ${o} \u2014 \`logs\` takes a numeric count (e.g. ${w("logs")} 100).
930
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let L=()=>Mt(c),V=v=>Ft(v,{level:$,filter:n,showInternal:f});if(!u){let v=await L(),N=V(v).slice(-k);if(m){console.log(JSON.stringify(N,null,2));break}if(N.length===0){console.log(v.length===0?" no logs captured":" no matching logs");break}console.log(` ${N.length} log(s):
931
+ `);for(let F of N)So(F,y);break}console.log(` tailing logs (ctrl-c to stop)...
932
+ `);let G=new Set,Y=!0,E=()=>{Y=!1};process.on("SIGINT",E);try{for(;Y;){let v=await L(),N=V(v);for(let F of N)G.has(F.id)||(G.add(F.id),m?console.log(JSON.stringify(F)):So(F,y));await oe(250)}}finally{process.off("SIGINT",E)}break}default:console.error(` unknown subcommand: ${p}`),process.exit(1)}if(q.has(p)&&!e.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&!await mt(c,p)&&await T(c),S.length>0&&ee(S),!R.has(p))try{await Se(c)}catch{}}catch(S){let o=S instanceof Error?S.message:String(S);console.error(` ${p??"rnxsim"} failed: ${o}`);let n=/^no sim connected with id ([^;]+)(?:; connected sims: .+)?$/.exec(o),a=/^command timed out after (\d+)s$/.exec(o),l=o.startsWith("sim disconnected:")||o.startsWith("bridge never reconnected")||o.startsWith("could not connect to ws://");if(n)await qt(c,M,n[1]);else if(/^no sim connected$/.test(o))jt(M);else if(a)if(await gs(c)){let m=p??"describe";process.stderr.write(` the sim is still responsive \u2014 '${m}' just exceeded the ${a[1]}s command budget.
933
+ the screen's node tree is large; narrow the query or raise the budget:
934
+ rnxsim ${m} --testid <id> # scope to one subtree
935
+ rnxsim find --testid <id> # targeted single-node lookup
936
+ rnxsim ${m} --timeout 60000 # raise per-command budget (ms)
937
+ `)}else bo();else if(l)bo();else{try{await _t(c)}catch{}try{await te({includeTail:!0})}catch{}try{await K({includeTail:!0})}catch{}}process.exit(1)}finally{c.close()}}export{Je as a,Do as b,Ps as c,Cs as d,js as e,qs as f,Ls as g,se as h,Io as i,_r as j};