sootsim 0.1.188 → 0.1.190

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 (178) hide show
  1. package/README.md +9 -9
  2. package/dist-cli/bin.js +7 -7
  3. package/dist-cli/chunks/{agent-BRLC23GZ.js → agent-XZWMKC4F.js} +2 -2
  4. package/dist-cli/chunks/{agent-wrapper-HDWSAABN.js → agent-wrapper-CFJYDDAY.js} +2 -2
  5. package/dist-cli/chunks/{app-fonts-KQHDDWAH.js → app-fonts-64UN5GRY.js} +2 -2
  6. package/dist-cli/chunks/{assert-BA3G3DLH.js → assert-A3MQH7ZB.js} +2 -2
  7. package/dist-cli/chunks/auth-CNKNHD6U.js +10 -0
  8. package/dist-cli/chunks/beta-CDL7U2RE.js +2 -0
  9. package/dist-cli/chunks/camera-YQPIDOEN.js +20 -0
  10. package/dist-cli/chunks/{chunk-I52NHG4X.js → chunk-24OZOK2K.js} +1 -1
  11. package/dist-cli/chunks/{chunk-OXB6RPMX.js → chunk-3JVMBXLH.js} +2 -2
  12. package/dist-cli/chunks/{chunk-GAP76GG5.js → chunk-5IM3DYTZ.js} +1 -1
  13. package/dist-cli/chunks/{chunk-DBOVJCG5.js → chunk-6EFMFMJB.js} +2 -2
  14. package/dist-cli/chunks/{chunk-DKOKNFWR.js → chunk-6UQKBGI7.js} +2 -3
  15. package/dist-cli/chunks/{chunk-ERHMPVNZ.js → chunk-7TSFDDU7.js} +2 -2
  16. package/dist-cli/chunks/chunk-AAQ6AYYW.js +2 -0
  17. package/dist-cli/chunks/chunk-CD3ARXZW.js +1 -0
  18. package/dist-cli/chunks/chunk-CTP3U4WV.js +13 -0
  19. package/dist-cli/chunks/{chunk-QDUHROO5.js → chunk-CVUAT6TO.js} +1 -1
  20. package/dist-cli/chunks/chunk-DHDV2I2T.js +1 -0
  21. package/dist-cli/chunks/{chunk-TAXDBR5N.js → chunk-EBBYYBYM.js} +3 -3
  22. package/dist-cli/chunks/chunk-F6GCSGBJ.js +8 -0
  23. package/dist-cli/chunks/{chunk-HIS4TFND.js → chunk-INRO26KS.js} +2 -2
  24. package/dist-cli/chunks/{install-desktop-F43JZSJO.js → chunk-IOJDFCGV.js} +7 -7
  25. package/dist-cli/chunks/{chunk-D6GYUATH.js → chunk-ITQV76PX.js} +1 -1
  26. package/dist-cli/chunks/chunk-IUVDM73R.js +140 -0
  27. package/dist-cli/chunks/{chunk-2MRFRROI.js → chunk-K5GLQDTG.js} +2 -2
  28. package/dist-cli/chunks/{chunk-FUZNRCAR.js → chunk-K7OCH4WY.js} +2 -2
  29. package/dist-cli/chunks/{chunk-NCENLBIL.js → chunk-KLGX6B46.js} +2 -2
  30. package/dist-cli/chunks/{chunk-AUQ7FZIX.js → chunk-LRJVY7SN.js} +2 -2
  31. package/dist-cli/chunks/{chunk-2T6Z4WCN.js → chunk-MH6BMKK5.js} +1 -1
  32. package/dist-cli/chunks/{chunk-Y3I43AUV.js → chunk-MJU4XNZ3.js} +1 -1
  33. package/dist-cli/chunks/{chunk-ZZ7FODQE.js → chunk-NAI6N6SN.js} +8 -7
  34. package/dist-cli/chunks/chunk-P7MW7S62.js +87 -0
  35. package/dist-cli/chunks/chunk-PGQHNKRL.js +119 -0
  36. package/dist-cli/chunks/chunk-PR3IKD6A.js +2 -0
  37. package/dist-cli/chunks/chunk-PSETHPMH.js +565 -0
  38. package/dist-cli/chunks/{chunk-BZNPGYJQ.js → chunk-QJVITDKU.js} +1 -1
  39. package/dist-cli/chunks/{chunk-SVSZFGNA.js → chunk-QNVY6BLP.js} +1 -1
  40. package/dist-cli/chunks/{chunk-YNY3WSH4.js → chunk-R3VO3MDO.js} +1 -1
  41. package/dist-cli/chunks/{chunk-5U22ZNDP.js → chunk-SJHC6HZH.js} +1 -1
  42. package/dist-cli/chunks/{chunk-ZZTGVTE3.js → chunk-SMDCNCVZ.js} +1 -1
  43. package/dist-cli/chunks/{chunk-TPHYWQB2.js → chunk-SPYRMNAJ.js} +5 -5
  44. package/dist-cli/chunks/{chunk-B272R3FA.js → chunk-TBFBGSRV.js} +1 -1
  45. package/dist-cli/chunks/chunk-UPN7Z5XZ.js +916 -0
  46. package/dist-cli/chunks/{chunk-KOEBHC3D.js → chunk-WHYPFQIZ.js} +2 -2
  47. package/dist-cli/chunks/{chunk-NDAGMI4C.js → chunk-WR5IDCCN.js} +1 -1
  48. package/dist-cli/chunks/{chunk-BJMQRL7V.js → chunk-WT74ZUKN.js} +1 -1
  49. package/dist-cli/chunks/{chunk-5XZN2C22.js → chunk-Y6CZ5N26.js} +2 -2
  50. package/dist-cli/chunks/{chunk-IULK4TUU.js → chunk-YWQH2KQJ.js} +1 -1
  51. package/dist-cli/chunks/cli-version-PVRNMRL7.js +2 -0
  52. package/dist-cli/chunks/{compat-6QHB5UPF.js → compat-AU7EW2AY.js} +3 -3
  53. package/dist-cli/chunks/config-TNZV6ASD.js +11 -0
  54. package/dist-cli/chunks/control-TKDPQACC.js +2 -0
  55. package/dist-cli/chunks/daemon-L57B7HBL.js +2 -0
  56. package/dist-cli/chunks/{debug-OTEVKM5L.js → debug-H5UHUDC4.js} +3 -3
  57. package/dist-cli/chunks/desktop-WYPCYR3Z.js +32 -0
  58. package/dist-cli/chunks/{detox-MISIYJRV.js → detox-36VI5PZ3.js} +2 -2
  59. package/dist-cli/chunks/{device-R3BORN7B.js → device-XPSGGSM5.js} +2 -2
  60. package/dist-cli/chunks/{diagnose-G7UE2PUJ.js → diagnose-CH3VYGFO.js} +10 -10
  61. package/dist-cli/chunks/drivers-XDAXVIZF.js +2 -0
  62. package/dist-cli/chunks/flow-Q24HN25I.js +2 -0
  63. package/dist-cli/chunks/help-OPVDM7BI.js +2 -0
  64. package/dist-cli/chunks/{home-paths-EJFFLJZR.js → home-paths-IT2LCG6O.js} +2 -2
  65. package/dist-cli/chunks/inspect-FEMU6KSY.js +2 -0
  66. package/dist-cli/chunks/install-desktop-NCMJNSW7.js +2 -0
  67. package/dist-cli/chunks/{login-3ZNZJ7P4.js → login-O6XRDK26.js} +5 -5
  68. package/dist-cli/chunks/{logout-34JBFFT4.js → logout-YK7BH4AK.js} +2 -2
  69. package/dist-cli/chunks/{maestro-JYCD7OQT.js → maestro-T52UBLSK.js} +6 -6
  70. package/dist-cli/chunks/mode-L4GR563F.js +93 -0
  71. package/dist-cli/chunks/optional-demo-registry-PDFLBZMQ.js +2 -0
  72. package/dist-cli/chunks/perf-7DYLYEBO.js +43 -0
  73. package/dist-cli/chunks/{record-L54OVMQQ.js → record-MNIFB5DJ.js} +7 -7
  74. package/dist-cli/chunks/runtime-E4KWRPBT.js +2 -0
  75. package/dist-cli/chunks/screenshot-command-D77AXBND.js +190 -0
  76. package/dist-cli/chunks/{serve-D6HGTNWI.js → serve-LFPZVOVA.js} +2 -2
  77. package/dist-cli/chunks/{setup-MR7SX23V.js → setup-6FX2KQP4.js} +3 -3
  78. package/dist-cli/chunks/skills-36CRDBMN.js +48 -0
  79. package/dist-cli/chunks/storage-N45XGOMV.js +35 -0
  80. package/dist-cli/chunks/store-USJP5W6S.js +2 -0
  81. package/dist-cli/chunks/telemetry-WQ7RK6NE.js +2 -0
  82. package/dist-cli/chunks/test-GCVW3U2P.js +69 -0
  83. package/dist-cli/chunks/{timeline-SBCWQHQT.js → timeline-4ALLBESW.js} +2 -2
  84. package/dist-cli/chunks/{upgrade-RGJVNFZO.js → upgrade-75XAVSMJ.js} +2 -2
  85. package/dist-cli/chunks/upload-34BCSEFZ.js +2 -0
  86. package/dist-cli/chunks/{version-23HGJOE3.js → version-MSFDAHVF.js} +2 -2
  87. package/dist-cli/chunks/{web-YMQPB45M.js → web-IS75NWAC.js} +2 -2
  88. package/dist-cli/chunks/{what-happened-3AJBD35R.js → what-happened-TW6SN7Z7.js} +2 -2
  89. package/dist-lib/agent-daemon-client.cjs +1 -1
  90. package/dist-lib/agent-events.cjs +1 -1
  91. package/dist-lib/agent-identity.cjs +53 -0
  92. package/dist-lib/agent-sessions.cjs +1 -1
  93. package/dist-lib/attached-projects.cjs +1 -1
  94. package/dist-lib/auth/shared-session.cjs +1 -1
  95. package/dist-lib/backend-origin.cjs +1 -1
  96. package/dist-lib/beta.cjs +1 -1
  97. package/dist-lib/beta.mjs +1 -1
  98. package/dist-lib/bridge-constants.cjs +1 -1
  99. package/dist-lib/cli-constants.cjs +1 -1
  100. package/dist-lib/config.cjs +1 -1
  101. package/dist-lib/detox/index.cjs +1 -1
  102. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  103. package/dist-lib/home-paths.cjs +1 -1
  104. package/dist-lib/host/bridge-host.cjs +1 -1
  105. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  106. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  107. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  108. package/dist-lib/host/websocket-proxy.cjs +1 -1
  109. package/dist-lib/index.cjs +15 -7
  110. package/dist-lib/jump-to-source-babel.cjs +1 -1
  111. package/dist-lib/menu.cjs +1 -1
  112. package/dist-lib/menu.mjs +1 -1
  113. package/dist-lib/metro.cjs +13 -5
  114. package/dist-lib/profiles.cjs +1 -1
  115. package/dist-lib/render-mode.cjs +1 -1
  116. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  117. package/dist-lib/sdk.cjs +1 -1
  118. package/dist-lib/sdk.mjs +1 -1
  119. package/dist-lib/skills.cjs +121 -79
  120. package/dist-lib/vite.cjs +13 -5
  121. package/package.json +1 -1
  122. package/skills/{soot.md → soot/SKILL.md} +12 -25
  123. package/skills/{sootsim-debug.md → sootsim-debug/SKILL.md} +1 -1
  124. package/skills/sootsim-perf/SKILL.md +169 -0
  125. package/skills/{sootsim-test.md → sootsim-test/SKILL.md} +10 -7
  126. package/src/metro-plugin.ts +2 -2
  127. package/src/runtime-assets.ts +16 -2
  128. package/src/screenshots/orchestrate.ts +1 -1
  129. package/src/screenshots/org-deck.ts +1 -1
  130. package/src/vite-plugin-one.ts +2 -2
  131. package/dist-cli/chunks/beta-O43XI622.js +0 -2
  132. package/dist-cli/chunks/camera-22Q4QVTC.js +0 -20
  133. package/dist-cli/chunks/chunk-3ECPODR2.js +0 -382
  134. package/dist-cli/chunks/chunk-4JG6GDLB.js +0 -2
  135. package/dist-cli/chunks/chunk-5D6TXWZQ.js +0 -3
  136. package/dist-cli/chunks/chunk-6LAPS7RP.js +0 -3
  137. package/dist-cli/chunks/chunk-FHHOZTPI.js +0 -3
  138. package/dist-cli/chunks/chunk-FXHED7P5.js +0 -79
  139. package/dist-cli/chunks/chunk-HGER3AOP.js +0 -69
  140. package/dist-cli/chunks/chunk-HXEGZCLS.js +0 -118
  141. package/dist-cli/chunks/chunk-JOE4R2PO.js +0 -1
  142. package/dist-cli/chunks/chunk-MXYAGDBC.js +0 -24
  143. package/dist-cli/chunks/chunk-PCKWE63K.js +0 -987
  144. package/dist-cli/chunks/chunk-QCDWRDUC.js +0 -1
  145. package/dist-cli/chunks/chunk-SGZP6JCZ.js +0 -16
  146. package/dist-cli/chunks/chunk-V7V6WDIM.js +0 -13
  147. package/dist-cli/chunks/chunk-WST3QKHD.js +0 -180
  148. package/dist-cli/chunks/cli-version-74E3VGPF.js +0 -2
  149. package/dist-cli/chunks/control-A2KALMZE.js +0 -2
  150. package/dist-cli/chunks/cpu-profile-A3ST63G2.js +0 -2
  151. package/dist-cli/chunks/daemon-KBQK2QRU.js +0 -2
  152. package/dist-cli/chunks/drivers-4URQ5PMT.js +0 -2
  153. package/dist-cli/chunks/electron-DXMMDHR3.js +0 -19
  154. package/dist-cli/chunks/flow-OETRQOLM.js +0 -2
  155. package/dist-cli/chunks/help-FSZ5FRHV.js +0 -2
  156. package/dist-cli/chunks/hints-QJSWKWC5.js +0 -2
  157. package/dist-cli/chunks/inspect-EFTHNTN2.js +0 -2
  158. package/dist-cli/chunks/keys-P2HBCVAX.js +0 -19
  159. package/dist-cli/chunks/optional-demo-registry-MM6GWJNB.js +0 -2
  160. package/dist-cli/chunks/preview-PIEAC5MZ.js +0 -17
  161. package/dist-cli/chunks/profile-BTCKOPAU.js +0 -22
  162. package/dist-cli/chunks/react-UYKTFQZW.js +0 -30
  163. package/dist-cli/chunks/runtime-ZB7S4Z3H.js +0 -2
  164. package/dist-cli/chunks/screenshot-A5WQUFIQ.js +0 -35
  165. package/dist-cli/chunks/screenshot-mode-GBZSTZTV.js +0 -17
  166. package/dist-cli/chunks/screenshots-EHE2FKTA.js +0 -74
  167. package/dist-cli/chunks/screenshots-capture-MOZJ2RQV.js +0 -41
  168. package/dist-cli/chunks/skills-NHV2ZFOU.js +0 -48
  169. package/dist-cli/chunks/slides-WDFLQWCZ.js +0 -46
  170. package/dist-cli/chunks/store-7EYKU7RK.js +0 -2
  171. package/dist-cli/chunks/telemetry-MU23XMBJ.js +0 -2
  172. package/dist-cli/chunks/telemetry-NF6KAWA4.js +0 -2
  173. package/dist-cli/chunks/test-CVQHZHMJ.js +0 -31
  174. package/dist-cli/chunks/three-mode-UCOVUXVY.js +0 -58
  175. package/dist-cli/chunks/upload-GHIMBL2Y.js +0 -2
  176. package/dist-cli/chunks/whoami-ZM3TCPNU.js +0 -2
  177. /package/skills/{sootsim-setup.md → sootsim-setup/SKILL.md} +0 -0
  178. /package/skills/{sootsim-visual.md → sootsim-visual/SKILL.md} +0 -0
@@ -0,0 +1,916 @@
1
+ /*! sootsim v0.1.190 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as ce}from"./chunk-IUVDM73R.js";import{b as Rt,c as Et,k as Pt}from"./chunk-CTP3U4WV.js";import{a as oe,b as P,c as D,d as Ie,e as ie,f as V,g as de,h as ge,i as Mt,j as Ft,k as Te,l as Ot}from"./chunk-WHYPFQIZ.js";import{A as wt,B as xt,E as $t,G as St,I as ue,J as vt,P as We,a as ve,b as nt,c as rt,d as it,e as at,f as lt,g as ct,h as ut,i as dt,j as pt,k as Be,l as Ce,q as je,r as mt,s as ft,t as fe,u as gt,v as ke,w as Le,x as yt,y as ht,z as bt}from"./chunk-QNVY6BLP.js";import{e as kt,g as _t,i as It,j as Tt,k as Nt,l as _e}from"./chunk-Y6CZ5N26.js";import{a as tt}from"./chunk-PR3IKD6A.js";import{a as Ae,c as De,d as Q}from"./chunk-PGQHNKRL.js";import{c as ot}from"./chunk-CVUAT6TO.js";import{b as st}from"./chunk-SJHC6HZH.js";function qe(e){return`(async () => {
3
+ const bridge = globalThis.SootSim && globalThis.SootSim.bridges && globalThis.SootSim.bridges.hotRemount
4
+ if (!bridge || typeof bridge.reloadExternalApp !== 'function') return false
5
+ await bridge.reloadExternalApp({ resetStorage: ${e?"true":"false"} })
6
+ return true
7
+ })()`}function At(e){return`(async () => {
8
+ const __t = window.__sootsimTest
9
+ if (!__t) throw new Error('__sootsimTest not available')
10
+ const __id = ${JSON.stringify(e.id||"")}
11
+ const __text = ${JSON.stringify(e.text||"")}
12
+ let __node = null
13
+ if (__id) {
14
+ __node = (__t.findByTestId && await __t.findByTestId(__id)) ||
15
+ (__t.findById && await __t.findById(__id)) || null
16
+ } else if (__text) {
17
+ __node = __t.findByText ? await __t.findByText(__text) : null
18
+ }
19
+ if (!__node) return null
20
+ const __pos = __node.absolutePosition || { x: __node.layout?.x || 0, y: __node.layout?.y || 0 }
21
+ const __layout = __node.layout || {}
22
+ return {
23
+ x: __pos.x,
24
+ y: __pos.y,
25
+ w: __layout.width || 1,
26
+ h: __layout.height || 1,
27
+ }
28
+ })()`}function Dt(e){return`(async () => {
29
+ const __rect = ${JSON.stringify(e)}
30
+ const __screenshot = window.__sootsimScreenshot
31
+ if (typeof __screenshot !== 'function') {
32
+ throw new Error('screenshot bridge not installed')
33
+ }
34
+ const __dataUrl = await __screenshot({ crop: __rect })
35
+ const __img = await new Promise((res, rej) => {
36
+ const img = new Image()
37
+ img.onload = () => res(img)
38
+ img.onerror = () => rej(new Error('failed to decode cropped screenshot'))
39
+ img.src = __dataUrl
40
+ })
41
+ const __w = __img.naturalWidth
42
+ const __h = __img.naturalHeight
43
+ const __canvas = document.createElement('canvas')
44
+ __canvas.width = __w
45
+ __canvas.height = __h
46
+ const __ctx = __canvas.getContext('2d')
47
+ if (!__ctx) throw new Error('could not acquire 2d context')
48
+ __ctx.drawImage(__img, 0, 0)
49
+ const __data = __ctx.getImageData(0, 0, __w, __h).data
50
+ const __n = __data.length / 4
51
+ let __r = 0, __g = 0, __b = 0, __a = 0
52
+ for (let __i = 0; __i < __data.length; __i += 4) {
53
+ __r += __data[__i]
54
+ __g += __data[__i + 1]
55
+ __b += __data[__i + 2]
56
+ __a += __data[__i + 3]
57
+ }
58
+ const __round = (v) => Math.round(v / __n)
59
+ const __rr = __round(__r), __gg = __round(__g), __bb = __round(__b), __aa = __round(__a)
60
+ const __hex =
61
+ '#' +
62
+ [__rr, __gg, __bb]
63
+ .map((v) => v.toString(16).padStart(2, '0'))
64
+ .join('')
65
+ const __dpr = window.devicePixelRatio || 1
66
+ return {
67
+ r: __rr, g: __gg, b: __bb, a: __aa,
68
+ hex: __hex,
69
+ samples: __n,
70
+ rect: { x: __rect.x, y: __rect.y, w: __rect.w, h: __rect.h },
71
+ deviceWidth: __w / __dpr,
72
+ deviceHeight: __h / __dpr,
73
+ }
74
+ })()`}import{existsSync as Eo,mkdirSync as Ct,readFileSync as Po,rmSync as Ke,writeFileSync as jt}from"fs";import{tmpdir as Ao}from"os";import{dirname as Lt,join as Do,resolve as Wt}from"path";import*as Ne from"fs";function Ro(e){let o={},s=e,a=p=>Array.isArray(p)?p:[],c=e.match(/^---\n([\s\S]*?)\n---\n?/);if(c){try{o=ce.parse(c[1])??{}}catch(f){console.warn(` warn: could not parse frontmatter: ${f.message}`)}s=e.slice(c[0].length);let p=ce.parse(s);return{frontmatter:o,steps:a(p)}}if(/\n---\s*\n/.test(e))try{let p=ce.parseAllDocuments(e);if(p.length>=2){let f=p[0].toJS(),v=p[p.length-1].toJS();return{frontmatter:f&&typeof f=="object"?f:{},steps:a(v)}}}catch(p){console.warn(` warn: could not parse multi-doc flow: ${p.message}`)}let l=ce.parse(s);return{frontmatter:o,steps:a(l)}}var Bt=new Set(["tapOn","inputText","pressKey","dispatchKey","hideKeyboard","swipe","pinch","scroll","scrollUntilVisible"]);function Je(e){let o=[];if(!Array.isArray(e)||e.length===0)return o.push("flow body must be a non-empty YAML array of steps"),o;let s=0;for(let a of e)a&&typeof a=="object"?Object.keys(a).some(l=>Bt.has(l))&&(s+=1):typeof a=="string"&&Bt.has(a)&&(s+=1);return s===0&&o.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),o}function Ns(e){if(!Ne.existsSync(e))return[`file not found: ${e}`];let o;try{o=Ne.readFileSync(e,"utf8")}catch(s){return[`cannot read file: ${s.message}`]}if(o.trim().length===0)return["file is empty"];try{let s=Ro(o);return Je(s.steps)}catch(s){return[`yaml parse error: ${s.message}`]}}var He=1;function Me(){return Wt(process.env.SOOTSIM_FLOW_SESSION_PATH||Do(Ao(),"sootsim-flow-session.json"))}function Ue(e){let o=Me();Ct(Lt(o),{recursive:!0}),jt(o,JSON.stringify(e,null,2)+`
75
+ `)}function Ge(){let e=Me();if(!Eo(e))return null;try{let o=JSON.parse(Po(e,"utf8"));return o.version!==He||!Array.isArray(o.steps)||typeof o.startedAt!="string"||typeof o.updatedAt!="string"?(Ke(e,{force:!0}),null):{version:He,startedAt:o.startedAt,updatedAt:o.updatedAt,steps:o.steps,candidate:o.candidate??null}}catch{return Ke(e,{force:!0}),null}}function As(){let e=new Date().toISOString(),o={version:He,startedAt:e,updatedAt:e,steps:[],candidate:null};return Ue(o),{path:Me(),state:o}}function Bo(){Ke(Me(),{force:!0})}function Ds(){Bo()}function Fe(e){let o=Ge();if(!o)return{active:!1};let s=o.candidate,a={...o,updatedAt:new Date().toISOString(),candidate:{step:e.step,summary:e.summary,source:e.source,recordedAt:new Date().toISOString()}};return Ue(a),{active:!0,candidate:a.candidate,replaced:s}}function Bs(){let e=Ge();if(!e)return{active:!1,kept:!1,reason:"no-session"};if(!e.candidate)return{active:!0,kept:!1,reason:"no-candidate"};let o=e.candidate,s={...e,updatedAt:new Date().toISOString(),steps:[...e.steps,o.step],candidate:null};return Ue(s),{active:!0,kept:!0,candidate:o,stepCount:s.steps.length}}function Co(e){return ce.stringify(e).trimEnd()+`
76
+ `}function Cs(e){let o=Ge();if(!o)return{active:!1};let s=Co(o.steps),a=Je(o.steps);if(a.length>0)return{active:!0,valid:!1,issues:a,yaml:s,stepCount:o.steps.length,outputPath:null};let c=null;return e&&(c=Wt(e),Ct(Lt(c),{recursive:!0}),jt(c,s)),{active:!0,valid:!0,issues:[],yaml:s,stepCount:o.steps.length,outputPath:c}}import{existsSync as jo,mkdirSync as Lo,readFileSync as Wo,rmSync as qt,writeFileSync as qo}from"fs";import{tmpdir as Jo}from"os";import{dirname as Ko,join as Ho,resolve as Uo}from"path";var ye=1,Go="SOOTSIM_INSPECT_NOTICE_PATH",zo=300*1e3,Yo=15e3;function Jt(){return Uo(process.env[Go]||Ho(Jo(),"sootsim-inspect-notice-state.json"))}function Xo(e,o){return Object.fromEntries(Object.entries(e).filter(([,s])=>typeof s?.signature=="string"&&Number.isFinite(s?.updatedAt)&&o-s.updatedAt<=zo))}function Vo(e){let o=Jt();if(!jo(o))return{version:ye,entries:{}};try{let s=JSON.parse(Wo(o,"utf8"));return s.version!==ye||!s.entries||typeof s.entries!="object"?(qt(o,{force:!0}),{version:ye,entries:{}}):{version:ye,entries:Xo(s.entries,e)}}catch{return qt(o,{force:!0}),{version:ye,entries:{}}}}function Qo(e){let o=Jt();Lo(Ko(o),{recursive:!0}),qo(o,JSON.stringify(e,null,2)+`
77
+ `)}function Zo(e,o){let s=o.trim()||"default";return`${e}:${s}`}function ze(e,o,s,a={}){let c=a.nowMs??Date.now(),l=a.cooldownMs??Yo,p=Vo(c),f=Zo(e,o),v=p.entries[f];return v&&v.signature===s&&c-v.updatedAt<l?!1:(p.entries[f]={signature:s,updatedAt:c},Qo(p),!0)}async function se({bridge:e,simId:o,maxMs:s,pollMs:a=50,stablePolls:c=3,strict:l=!1}){let p=await e.send({type:"evaluate",simId:o,code:`(async () => {
78
+ const start = Date.now()
79
+ const deadline = start + ${Math.max(0,Math.round(s))}
80
+ const pollMs = ${Math.max(1,Math.round(a))}
81
+ const requiredStablePolls = ${Math.max(1,Math.round(c))}
82
+ const strict = ${l?"true":"false"}
83
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
84
+
85
+ // route-aware settle: a tap that pushes/pops a screen is async \u2014 the
86
+ // old screen still renders for a moment, then the new one mounts and
87
+ // its content loads. a pure layout-hash check reports "idle" on the
88
+ // outgoing screen or on the incoming skeleton, so a driver re-taps
89
+ // and stacks duplicate navigations. drain any in-flight screen
90
+ // transition FIRST, bounded by the overall budget. when no
91
+ // transition is happening this returns in ~80ms (startWindowMs), so
92
+ // a plain button tap barely pays for it.
93
+ try {
94
+ const wfst = window.__sootsimTest?.waitForScreenTransitions
95
+ if (typeof wfst === 'function') {
96
+ const remaining = deadline - Date.now()
97
+ if (remaining > 120) {
98
+ await wfst({
99
+ timeoutMs: Math.min(remaining - 80, 4000),
100
+ settleMs: 64,
101
+ startWindowMs: 80,
102
+ })
103
+ }
104
+ }
105
+ } catch {}
106
+
107
+ const readSnapshot = async () => {
108
+ let animating = false
109
+ let pendingFetches = 0
110
+ let requestTotal = 0
111
+ let requestInFlight = 0
112
+ try {
113
+ const stats = await window.__sootsimRenderHost?.queryStats?.()
114
+ if (stats) {
115
+ animating =
116
+ stats.hasActiveAnims === true ||
117
+ stats.hasActiveNativeAnimations === true ||
118
+ stats.hasPendingAnimationFrames === true
119
+ // a freshly-pushed screen showing a skeleton is layout-stable
120
+ // but not actually settled \u2014 its data/images are still in
121
+ // flight. treat bounded image-loader fetches as not-idle so
122
+ // settle waits for real content, capped by the budget.
123
+ const pf = stats.memory && stats.memory.imageLoader
124
+ ? stats.memory.imageLoader.pendingFetches
125
+ : 0
126
+ pendingFetches = typeof pf === 'number' ? pf : 0
127
+ }
128
+ } catch {}
129
+ try {
130
+ const counts = await window.__sootsimTest?.getRequestCounts?.()
131
+ requestTotal = typeof counts?.total === 'number' ? counts.total : 0
132
+ requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight : 0
133
+ } catch {}
134
+ const root = window.__sootsimRoot
135
+ const nodes = []
136
+ if (root) {
137
+ const walk = (n) => {
138
+ if (n.layout && n.layout.width > 0) {
139
+ nodes.push(Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width))
140
+ }
141
+ for (const c of n.children || []) walk(c)
142
+ }
143
+ walk(root)
144
+ }
145
+ return { layout: nodes.join(';'), animating, pendingFetches, requestTotal, requestInFlight }
146
+ }
147
+
148
+ // how long generic background network is allowed to keep us waiting AFTER
149
+ // the screen is otherwise visually settled. apps with continuous traffic
150
+ // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
151
+ // requestInFlight===0 / a stable requestTotal, so requiring full network
152
+ // quiet burns the ENTIRE budget on every command \u2014 the leading idle that
153
+ // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
154
+ // layout-stability + the image-loader already prove visible content
155
+ // loaded (a data load changes layout; an image load shows in the loader),
156
+ // so the generic request counters are a courtesy, not a gate: honor them
157
+ // only within this grace once the screen is visually still.
158
+ const networkQuietGraceMs = 1200
159
+ let lastLayout = ''
160
+ let lastRequestTotal = -1
161
+ let stable = 0
162
+ let visuallyStillSince = 0
163
+ while (Date.now() < deadline) {
164
+ const snapshot = await readSnapshot()
165
+ const strictOk = !strict || !snapshot.animating
166
+ // visually settled: no animations, no image content loading, layout
167
+ // unchanged since the last poll.
168
+ const visuallyStill =
169
+ strictOk && snapshot.pendingFetches === 0 && snapshot.layout === lastLayout
170
+ // generic network quiet: nothing in flight and no new requests issued.
171
+ const networkQuiet =
172
+ snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
173
+ if (visuallyStill) {
174
+ stable++
175
+ if (visuallyStillSince === 0) visuallyStillSince = Date.now()
176
+ // settle once the screen has held still long enough AND either the
177
+ // network is genuinely quiet OR it has refused to quiet within the
178
+ // grace (continuous background traffic must not block forever).
179
+ if (
180
+ stable >= requiredStablePolls &&
181
+ (networkQuiet || Date.now() - visuallyStillSince >= networkQuietGraceMs)
182
+ ) {
183
+ return { settled: true, elapsed: Date.now() - start }
184
+ }
185
+ } else {
186
+ stable = 0
187
+ visuallyStillSince = 0
188
+ }
189
+ lastLayout = snapshot.layout
190
+ lastRequestTotal = snapshot.requestTotal
191
+ await sleep(pollMs)
192
+ }
193
+ return { settled: false, elapsed: Date.now() - start }
194
+ })()`},{timeoutMs:s+1e3}),{elapsed:f,settled:v}=p??{};return{elapsed:typeof f=="number"?f:s,settled:v===!0}}var es={initialWaitMs:3e3,deadlineMs:5e3,retryWaitMs:700},ts={initialWaitMs:1200,deadlineMs:2500,retryWaitMs:700};function os(e,o={}){return{...e?es:ts,...o}}function pe(e){return!(!e||e.hit===!1||e.ok===!1||e.pointerTapHandled===!1&&!e.keyboardOpened&&!e.isTextInput)}function ss(e,o){return{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??o??null,type:e.target?.type??e.match?.type??e.node?.type??null}}async function he(e,o){let s=os(!!o.agent,o.timing),a=0,c=null,l=null;try{await se({bridge:e,maxMs:s.initialWaitMs,pollMs:32,stablePolls:2})}catch{}let p=Date.now()+s.deadlineMs;for(;Date.now()<=p||a===0;){a++;let f=await o.resolve();if(c=f,f?.error==="bridge-not-ready"||f?.ambiguous||f?.nthOutOfRange)return{payload:f,result:null,attempts:a,failure:"special"};if(f&&typeof f.cx=="number"&&typeof f.cy=="number"){let _=await e.send({type:"tap",x:f.cx,y:f.cy,target:ss(f,o.textFallback)});if(l=_,pe(_))return{payload:f,result:_,attempts:a}}let v=p-Date.now();if(v<=0)break;try{await se({bridge:e,maxMs:Math.min(v,s.retryWaitMs),pollMs:32,stablePolls:2})}catch{await new Promise(_=>setTimeout(_,Math.min(120,v)))}}return{payload:c,result:l,attempts:a,failure:c&&typeof c.cx=="number"?"missed":"not-found"}}async function Kt(e,o,s,a){return e.send({type:"tap",x:o,y:s,...a?{target:a}:{}})}async function Ht(e,o,s={}){let a=JSON.stringify(o);return he(e,{agent:s.agent,timing:s.timing,resolve:()=>e.send({type:"evaluate",code:`(async () => {
195
+ const t = window.__sootsimTest
196
+ if (!t) return null
197
+ const n = (await t.findByTestId(${a})) || (await t.findById(${a}))
198
+ if (!n || !n.absolutePosition || !n.layout) return { cx: null }
199
+ const resolved =
200
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
201
+ ? await t.resolveTapTarget(n.nodeId)
202
+ : null
203
+ const target = (resolved && resolved.target) || n
204
+ const cx =
205
+ resolved && typeof resolved.cx === 'number'
206
+ ? resolved.cx
207
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
208
+ const cy =
209
+ resolved && typeof resolved.cy === 'number'
210
+ ? resolved.cy
211
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
212
+ return {
213
+ cx,
214
+ cy,
215
+ match: {
216
+ nodeId: n.nodeId ?? null,
217
+ id: n.id,
218
+ testID: n.testID,
219
+ text: n.text ?? n.accessibilityLabel ?? null,
220
+ type: n.type,
221
+ },
222
+ target: {
223
+ nodeId: target.nodeId ?? null,
224
+ id: target.id,
225
+ testID: target.testID,
226
+ text:
227
+ target.text ??
228
+ target.accessibilityLabel ??
229
+ n.text ??
230
+ n.accessibilityLabel ??
231
+ null,
232
+ type: target.type,
233
+ },
234
+ strategy: (resolved && resolved.strategy) || 'matched-node',
235
+ }
236
+ })()`})})}async function Ut(e,o,s={},a={}){let c=JSON.stringify({query:o,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 he(e,{agent:a.agent,timing:a.timing,textFallback:o,resolve:()=>e.send({type:"evaluate",code:`(async () => {
237
+ const t = window.__sootsimTest
238
+ if (!t) return { error: 'bridge-not-ready' }
239
+ const F = ${c}
240
+
241
+ const res = await t.queryTextCandidates({
242
+ query: F.query,
243
+ exact: !!F.exact,
244
+ ...(F.role ? { role: F.role } : {}),
245
+ })
246
+
247
+ let candidates = res.candidates || []
248
+
249
+ candidates = candidates.filter((c) => {
250
+ const ax = c.info.absolutePosition && c.info.absolutePosition.x
251
+ const ay = c.info.absolutePosition && c.info.absolutePosition.y
252
+ if (F.minX !== null && !(ax >= F.minX)) return false
253
+ if (F.maxX !== null && !(ax <= F.maxX)) return false
254
+ if (F.minY !== null && !(ay >= F.minY)) return false
255
+ if (F.maxY !== null && !(ay <= F.maxY)) return false
256
+ if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
257
+ return true
258
+ })
259
+
260
+ if (F.near) {
261
+ candidates.sort((a, b) => {
262
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
263
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
264
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
265
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
266
+ return (
267
+ Math.hypot(ax - F.near.x, ay - F.near.y) -
268
+ Math.hypot(bx - F.near.x, by - F.near.y)
269
+ )
270
+ })
271
+ } else {
272
+ candidates.sort((a, b) => {
273
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
274
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
275
+ if (Math.abs(ay - by) > 2) return ay - by
276
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
277
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
278
+ return ax - bx
279
+ })
280
+ }
281
+
282
+ const total = candidates.length
283
+ if (total === 0) return { matched: 0, total: 0 }
284
+
285
+ let idx = 0
286
+ if (F.nth !== null) {
287
+ idx = F.nth < 0 ? total + F.nth : F.nth
288
+ if (idx < 0 || idx >= total) {
289
+ return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
290
+ }
291
+ } else if (total > 1 && !F.first && !F.near) {
292
+ return {
293
+ ambiguous: true,
294
+ total,
295
+ candidates: candidates.slice(0, 10).map((c, i) => ({
296
+ idx: i,
297
+ nodeId: c.info.nodeId,
298
+ type: c.info.type,
299
+ testID: c.info.testID,
300
+ text: (c.info.text || '').slice(0, 60),
301
+ abs: c.info.absolutePosition,
302
+ layout: c.info.layout
303
+ ? {
304
+ width: Math.round(c.info.layout.width || 0),
305
+ height: Math.round(c.info.layout.height || 0),
306
+ }
307
+ : null,
308
+ ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
309
+ })),
310
+ }
311
+ }
312
+
313
+ const picked = candidates[idx]
314
+ const n = picked.info
315
+ if (!n.absolutePosition || !n.layout) return { matched: 0, total }
316
+
317
+ const resolved =
318
+ typeof n.nodeId === 'number' &&
319
+ typeof t.resolveTapTarget === 'function'
320
+ ? await t.resolveTapTarget(n.nodeId)
321
+ : null
322
+ const target = (resolved && resolved.target) || n
323
+ const cx =
324
+ resolved && typeof resolved.cx === 'number'
325
+ ? resolved.cx
326
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
327
+ const cy =
328
+ resolved && typeof resolved.cy === 'number'
329
+ ? resolved.cy
330
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
331
+ return {
332
+ cx,
333
+ cy,
334
+ match: {
335
+ nodeId: n.nodeId ?? null,
336
+ id: n.id,
337
+ testID: n.testID,
338
+ type: n.type,
339
+ },
340
+ target: {
341
+ nodeId: target.nodeId ?? null,
342
+ id: target.id,
343
+ testID: target.testID,
344
+ text:
345
+ target.text ??
346
+ target.accessibilityLabel ??
347
+ n.text ??
348
+ n.accessibilityLabel ??
349
+ null,
350
+ type: target.type,
351
+ },
352
+ strategy: (resolved && resolved.strategy) || 'matched-node',
353
+ total,
354
+ idx,
355
+ }
356
+ })()`})})}async function Gt(e,o,s={}){let a=JSON.stringify(o);return he(e,{agent:s.agent,timing:s.timing,textFallback:o,resolve:async()=>{let c=await e.send({type:"evaluate",code:`(async () => {
357
+ const t = window.__sootsimTest
358
+ if (!t) return { error: 'bridge-not-ready' }
359
+ const byTestId =
360
+ (await t.findByTestId(${a})) || (await t.findById(${a}))
361
+ if (byTestId && byTestId.absolutePosition && byTestId.layout) {
362
+ return {
363
+ strategy: 'testid',
364
+ node: {
365
+ nodeId: byTestId.nodeId ?? null,
366
+ id: byTestId.id,
367
+ testID: byTestId.testID,
368
+ type: byTestId.type,
369
+ text: byTestId.text,
370
+ absolutePosition: byTestId.absolutePosition,
371
+ layout: byTestId.layout,
372
+ },
373
+ }
374
+ }
375
+ const byText = await t.findByText(${a})
376
+ if (byText && byText.absolutePosition && byText.layout) {
377
+ return {
378
+ strategy: 'text',
379
+ node: {
380
+ nodeId: byText.nodeId ?? null,
381
+ id: byText.id,
382
+ testID: byText.testID,
383
+ type: byText.type,
384
+ text: byText.text,
385
+ absolutePosition: byText.absolutePosition,
386
+ layout: byText.layout,
387
+ },
388
+ }
389
+ }
390
+ return { strategy: 'none' }
391
+ })()`});if(!c||!("node"in c))return c;let l=c.node,p=l.absolutePosition.x+l.layout.width/2,f=l.absolutePosition.y+l.layout.height/2;return{...c,cx:p,cy:f,target:{id:l.id,testID:l.testID,text:c.strategy==="text"?o:l.text,type:l.type}}}})}async function zt(e,o={args:[]}){let s=await rt(e);if(P(o.args)){D(s);return}console.log(` nodes: ${s.nodes}`)}function Ye(e,o){let s=e.indexOf(o);return s>=0&&s+1<e.length?e[s+1]:null}async function Yt(e){let{bridge:o,args:s,positional:a}=e,c=s.includes("--verbose")||s.includes("-v"),l=P(s),p=c&&!l,f=s.includes("--watch")||s.includes("-w"),v=1e3,_=s.includes("--compact"),h=s.includes("--no-xy"),I=s.includes("--no-clipped"),F=s.includes("--include-occluded"),N=Ye(s,"--testid-like"),L=Ye(s,"--only"),M=Ye(s,"--subtree"),u=a[1]&&!a[1].startsWith("-")?a[1]:void 0,j=u?/[*?]/.test(u):!1,A=!j&&!L?u:void 0,E=L??(j?u:void 0),H=async()=>{await de(o,{verbose:p});let S=await lt(o,{describe:!0,verbose:c,filter:A||"",testIdLike:N||void 0,onlyGlob:E||void 0,subtreeRoot:M||void 0,compact:_,hideXy:h,includeOccluded:F}),O=S?.tree,J=S?.shell,K=S?.keyboard;if(l){D({shell:J,tree:O??"",keyboard:K});return}if(J&&typeof J=="object"){let C=[J.state?`state=${J.state}`:null,J.activeApp?`app=${J.activeApp}`:null,J.showSwitcher?"switcher":null,J.switcherPhase&&J.switcherPhase!=="idle"?`phase=${J.switcherPhase}`:null].filter(Boolean);C.length>0&&console.log(` shell: ${C.join(" ")}`)}if(typeof O=="string"&&O.startsWith("__SUBTREE_NOT_FOUND__:")){let C=O.slice(22);console.log(` subtree root not found: ${C}`),Q("subtree-root-not-found",C);return}if(!O){let C=S?.nodeCount??0;console.log(" no matching nodes found"),!(A||N||E||M)&&C<10&&Q("app-still-loading",C);return}let ee=O,te=0;if(I&&typeof ee=="string"){let C=ee.split(`
392
+ `),le=[];for(let $e of C){if($e.includes("(clipped:")){te+=1;continue}le.push($e)}ee=le.join(`
393
+ `)}console.log(ee),te>0&&console.log(` ${te} clipped row(s) hidden (omit --no-clipped to see)`);let re=A||N||E||M;if((A||N||E)&&!f&&Q("describe-filter-context"),!re&&!f&&O.split(`
394
+ `).length>=80&&Q("describe-use-filters"),K&&K.visible){let C=K.spec,le=[C?.keyboardType?`type=${C.keyboardType}`:null,C?.returnKeyType&&C.returnKeyType!=="default"?`return=${C.returnKeyType}`:null,K.mode!=="letters"?`mode=${K.mode}`:null,K.shifted?"shift":null,K.capsLock?"caps":null,C?.autoCapitalize&&C.autoCapitalize!=="sentences"?`autoCap=${C.autoCapitalize}`:null,K.accessoryBarId?`accessory=${K.accessoryBarId}`:null].filter(Boolean);console.log(`
395
+ keyboard: ${le.join(" ")||"visible"}`)}};if(f)for(console.log(` watching... (Ctrl+C to stop)
396
+ `);;)console.clear(),await H(),await oe(v);else await H()}var ns=["SOOTSIM_AGENT","AGENTBUS_SESSION","CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CURSOR_TRACE_ID","AIDER_MODEL"];function me(){if(process.env.SOOTSIM_AGENT==="0")return!1;for(let e of ns){let o=process.env[e];if(o&&o.trim()&&o!=="0")return!0}return!1}async function Xt(e){let{bridge:o,args:s,effectiveArgs:a,positional:c,inspectUsage:l}=e,p=S=>{let O=a.indexOf(S);return O>=0&&O+1<a.length?a[O+1]:null},f=S=>a.includes(S),v=p("--testid")||p("--test-id"),_=p("--role"),h=p("--type"),I=p("--text"),F=f("--pressable"),N=f("--visible"),L=f("--interactive-targets")||f("--actions"),M=!v&&!_&&!h&&!I&&!F&&!N&&!L?c[1]:null,u=I??M,j=await pt(o,{testId:v,role:_,type:h,text:u,pressable:F,visible:N,interactive:L});j||(console.error(l("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible | --interactive-targets")),process.exit(1));let{mode:A,result:E}=j,H=P(s),U=s.includes("--verbose")||s.includes("--dump");if(H)A==="interactive-targets"&&Array.isArray(E)?D(Be(E).map(S=>({...S,tap:Ce(S)}))):D(E??null);else if(Array.isArray(E))if(E.length===0){console.log(` no ${A} nodes found`);let S=await o.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof S=="number"&&S<10&&Q("app-still-loading",S)}else if(A==="interactive-targets"){let S=Be(E);console.log(` found ${S.length} interactive target${S.length===1?"":"s"} (sorted by score):`);for(let O of S.slice(0,20)){let J=O.absolutePosition?`@(${Math.round(O.absolutePosition.x)},${Math.round(O.absolutePosition.y)})`:"",K=O.layout?`${Math.round(O.layout.width)}x${Math.round(O.layout.height)}`:"?x?",ee=O.text?` "${O.text.slice(0,30)}"`:"",te=O.testID?` #${O.testID}`:"",re=O.accessibilityLabel?` \u24D8"${String(O.accessibilityLabel).slice(0,24)}"`:"",xe=O.accessibilityRole?`[${O.accessibilityRole}]`:O.type,C=Ce(O);console.log(` ${xe}${ee}${re}${te} ${K} ${J}`),console.log(` \u2192 ${C}`),U&&console.log(Xe(JSON.stringify(O,null,2)," "))}S.length>20&&console.log(` ... and ${S.length-20} more`)}else{console.log(` found ${E.length} node${E.length===1?"":"s"} (${A}):`);for(let S of E.slice(0,20)){let O=S.absolutePosition?`@(${Math.round(S.absolutePosition.x)},${Math.round(S.absolutePosition.y)})`:"",J=S.layout?`${Math.round(S.layout.width)}x${Math.round(S.layout.height)}`:"?x?",K=S.text?` "${S.text.slice(0,30)}"`:"",ee=S.testID?` #${S.testID}`:"",te=S.pressable?" (tap)":"",re=S.accessibilityRole?`[${S.accessibilityRole}]`:S.type;console.log(` ${re}${K}${ee} ${J} ${O}${te}`),U&&console.log(Xe(JSON.stringify(S,null,2)," "))}E.length>20&&console.log(` ... and ${E.length-20} more`)}else if(E==null)console.log(` not found: ${u||v||_||h||""||A}`),v&&Q("wait-selector-for-missing-testid",v);else{let S=E;if(S.type&&S.absolutePosition){let O=`@(${Math.round(S.absolutePosition.x)},${Math.round(S.absolutePosition.y)})`,J=S.layout?`${Math.round(S.layout.width)}x${Math.round(S.layout.height)}`:"?x?",K=S.text?` "${S.text.slice(0,40)}"`:"",ee=S.testID?` #${S.testID}`:"",te=S.pressable?" (tap)":"",re=S.accessibilityRole?`[${S.accessibilityRole}]`:S.type;console.log(` ${re}${K}${ee} ${J} ${O}${te}`),U&&console.log(Xe(JSON.stringify(S,null,2)," "))}else console.log(JSON.stringify(E,null,2))}}function Xe(e,o){return e.split(`
397
+ `).map(s=>o+s).join(`
398
+ `)}async function Vt(e){let{bridge:o,args:s}=e,a=P(s);await de(o,{verbose:!a});let c=s.includes("--styling"),l=await ct(o,{styling:c});if(a){D({count:l.length,elements:l});return}console.log(` layout (${l.length} element${l.length===1?"":"s"}):
399
+ `),console.log(ut(l,{styling:c}))}async function Qt(e,o={}){let s=await St(e);if("error"in s&&(console.error(s.error),process.exit(1)),o.json){console.log(JSON.stringify(s,null,2));return}let{visible:a,spec:c,mode:l,shifted:p,capsLock:f,accessoryBarId:v}=s,_=[];_.push(`keyboard: ${a?"visible":"hidden"}`),c?(_.push(` type: ${c.keyboardType}`),_.push(` returnKey: ${c.returnKeyType}`),_.push(` autoCap: ${c.autoCapitalize}`),_.push(` autoCorrect: ${c.autoCorrect?"on":"off"}`),_.push(` appearance: ${c.keyboardAppearance}`),c.secureTextEntry&&_.push(" secureTextEntry: true"),c.enablesReturnKeyAutomatically&&_.push(` return: ${c.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):_.push(" spec: <none> (shown via dev-tools with no TextInput)"),_.push(` mode: ${l}${p?" (shifted)":""}${f?" (caps)":""}`),v&&_.push(` accessoryBar: ${v}`),console.log(_.join(`
400
+ `))}async function Zt(e){let o=await e.bridge.listSims(),s=e.args.includes("--all"),a=e.args.find((f,v)=>e.args[v-1]==="--bundle"),c=e.args.find((f,v)=>e.args[v-1]==="--app-port"),l=e.args.includes("--primary"),p=o.filter(f=>!(l&&!f.isPrimary||a&&!(f.url??"").includes(a)||c&&!(f.url??"").includes(`/rn/${c}`)||!s&&!a&&!c&&!l&&!(f.url&&(f.url.includes("bundle=")||f.url.includes("/index.bundle")))&&f.id!==e.simId));if(P(e.args)){D(p.map(f=>({...f,active:f.id===e.simId})));return}Pt(p,e.simId),p.length<o.length&&!P(e.args)&&console.log(` (${o.length-p.length} more hidden \u2014 pass --all to show)`)}function ae(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function rs(e,o){return o<=0?"?":`${(e/o*100).toFixed(0)}%`}function is(e){let o={},s=(a,c)=>{c&&(c.nodesRegistered!=null&&(o[`${a}.nodes`]=c.nodesRegistered),c.nodesDetached!=null&&(o[`${a}.detached`]=c.nodesDetached),c.objects&&(o[`${a}.paragraphs`]=c.objects.paragraphs,o[`${a}.yogaNodes`]=c.objects.yogaNodes,o[`${a}.pictures`]=c.objects.pictures,o[`${a}.rasterImages`]=c.objects.rasterImages),c.imageLoader&&(o[`${a}.imageCacheEntries`]=c.imageLoader.cacheEntries,o[`${a}.imagePixelBytes`]=c.imageLoader.cachePixelBytes),c.workerHeap&&(o[`${a}.heapBytes`]=c.workerHeap.usedJSHeapSize))};return s("tenant",e.tenant),s("shell",e.shell),e.hostHeap&&(o["host.heapBytes"]=e.hostHeap.usedJSHeapSize),o}function eo(e,o){return e.endsWith("Bytes")?ae(o):String(o)}function to(e,o){if(!o){console.log(` ${e}: not available`);return}let s=o.objects;if(console.log(` ${e}`),o.nodesRegistered!=null&&console.log(` nodes registered: ${o.nodesRegistered}`),o.nodesDetached!=null){let a=Object.entries(o.detachedTypes??{}).map(([c,l])=>`${c}:${l}`).join(" ");console.log(` nodes detached: ${o.nodesDetached}${a?` (${a})`:""}`)}if(s&&(console.log(` paragraphs: ${s.paragraphs}`),console.log(` yoga nodes: ${s.yogaNodes}`),console.log(` pictures: ${s.pictures}`),console.log(` raster images: ${s.rasterImages}`)),o.activeNativeAnimations!=null&&console.log(` native anims: ${o.activeNativeAnimations}`),o.imageLoader){let a=o.imageLoader;console.log(` image cache: ${a.cacheEntries}/${a.cacheMaxEntries} entries, ${ae(a.cachePixelBytes)}/${ae(a.cachePixelBudget)} (${rs(a.cachePixelBytes,a.cachePixelBudget)})`)}o.workerHeap&&console.log(` js heap: ${ae(o.workerHeap.usedJSHeapSize)} used / ${ae(o.workerHeap.totalJSHeapSize)} total`)}function as(e){console.log(" memory:"),to("tenant worker",e.tenant),to("shell worker",e.shell),e.hostHeap?(console.log(" host"),console.log(` js heap: ${ae(e.hostHeap.usedJSHeapSize)} used / ${ae(e.hostHeap.totalJSHeapSize)} total`)):console.log(" host js heap: not available (chrome only)")}function ls(e,o,s){let a=e.indexOf(o);if(a===-1)return s;let c=Number(e[a+1]);return Number.isFinite(c)&&c>0?c:s}async function oo(e,o={args:[]}){let s=P(o.args),a=o.args.indexOf("--watch");if(a===-1){let M=await We(e);if(s){D(M);return}as(M);return}let c=Number(o.args[a+1]),l=Number.isFinite(c)&&c>0?c:60,p=ls(o.args,"--interval",5),f=[],v=Date.now(),_=null;for(s||console.log(` sampling every ${p}s for ${l}s \u2014 deltas per tick:`);;){let M=await We(e),u=(Date.now()-v)/1e3,j=is(M);if(f.push({tSec:u,counters:j}),!s){let A=[];for(let[E,H]of Object.entries(j)){let U=_&&E in _?H-_[E]:null;if(U===null||U===0)continue;let S=U>0?"+":"-",O=E.endsWith("Bytes")?`${S}${ae(Math.abs(U))}`:`${S}${Math.abs(U)}`;A.push(`${E} ${eo(E,H)} (${O})`)}console.log(` t+${u.toFixed(0)}s ${A.length?A.join(" "):_?"no change":Object.entries(j).map(([E,H])=>`${E} ${eo(E,H)}`).join(" ")}`)}if(_=j,u>=l)break;await new Promise(A=>setTimeout(A,p*1e3))}let h=f[0],I=f[f.length-1],F=Math.max(I.tSec-h.tSec,.001),N={};for(let M of Object.keys(I.counters))M in h.counters&&(N[M]=(I.counters[M]-h.counters[M])/F);if(s){D({samples:f,perSecond:N,elapsedSec:F});return}console.log(`
401
+ slope over ${F.toFixed(0)}s:`);let L=Object.entries(N).filter(([,M])=>M!==0).sort((M,u)=>Math.abs(u[1])-Math.abs(M[1]));if(L.length===0){console.log(" all counters flat");return}for(let[M,u]of L){let j=M.endsWith("Bytes")?`${ae(Math.abs(u))}/s${u<0?" (shrinking)":""}`:`${u>0?"+":""}${u.toFixed(2)}/s`;console.log(` ${M.padEnd(28)}${j}`)}}var Z="<redacted secure text>";function be(e){let o=e?.layout?.spec??e?.spec??null;return!!o?.secureTextEntry&&o.keyboardType!=="visible-password"}function Ve(e,o){return be(o)?Z:e}function Qe(e){if(!e||!be(e))return e;let o=e.focusedInput;return!o||typeof o!="object"?e:{...e,focusedInput:{...o,secureTextEntry:!0,text:typeof o.text=="string"?Z:o.text}}}function we(e){let o=e.indexOf("--testid");if(o>=0&&e[o+1])return{mode:"testid",value:e[o+1]};let s=e.indexOf("--test-id");if(s>=0&&e[s+1])return{mode:"testid",value:e[s+1]};let a=e.indexOf("--text");return a>=0&&e[a+1]?{mode:"text",value:e[a+1]}:null}async function Oe(e,o){let s=JSON.stringify(o.value),a=o.mode==="testid"?`(await t.findByTestId(${s})) || (await t.findById(${s}))`:`await t.findByText(${s})`;return await e.send({type:"evaluate",code:`(async () => {
402
+ const t = window.__sootsimTest
403
+ if (!t) return null
404
+ const n = ${a}
405
+ if (!n || !n.absolutePosition || !n.layout) return null
406
+ const resolved =
407
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
408
+ ? await t.resolveTapTarget(n.nodeId)
409
+ : null
410
+ const cx =
411
+ typeof resolved?.cx === 'number'
412
+ ? resolved.cx
413
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
414
+ const cy =
415
+ typeof resolved?.cy === 'number'
416
+ ? resolved.cy
417
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
418
+ return {
419
+ x: cx,
420
+ y: cy,
421
+ id: n.id ?? null,
422
+ testID: n.testID ?? null,
423
+ text: ${JSON.stringify(o.mode==="text")} ? ${s} : (n.text ?? n.accessibilityLabel ?? null),
424
+ type: n.type ?? null,
425
+ }
426
+ })()`})??null}async function so(e,o={}){let{nav:s,keyboard:a,shell:c}=await vt(e);if(o.json){console.log(JSON.stringify({shell:c??null,nav:s,keyboard:a},null,2));return}let l=[];if(c){let p=c.activeApp??c.state??"<none>",f=c.showSwitcher?" (app switcher open)":"",v=typeof c.launchProgress=="number"&&c.launchProgress<.98?` launching (${Math.round(c.launchProgress*100)}%)`:"";l.push(`shell: ${p}${f}${v}`)}else l.push("shell: <unavailable>");if(s){let p=s.transitionPhase!=="idle"?` (${s.transitionPhase}, ${s.activeTransitionCount} active)`:"";if(l.push(`nav: phase=${s.transitionPhase}${p}`),s.screens.length===0)l.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let f of s.screens){let v=f.isActive?"\u25B6":" ",_=f.routeName?` ${f.routeName}`:"",h=f.headerHeight>0?` header=${f.headerHeight}`:"",I=f.largeTitleState&&f.largeTitleState!=="expanded"?` large-title=${f.largeTitleState}`:"";l.push(` ${v} #${f.id}${_}${h}${I}`)}}else l.push("nav: <runtime not available>");if(a&&a.visible){let p=a.spec?.keyboardType??"default",f=a.spec?.returnKeyType??"default";l.push(`keyboard: visible (${p}, return=${f}, mode=${a.mode??"?"})`)}else l.push("keyboard: hidden");console.log(l.join(`
427
+ `))}async function no(e){let{bridge:o,args:s,positional:a}=e,c=a[1]?Number(a[1])*1e3:3e3,l=s.includes("--strict"),{elapsed:p,settled:f}=await se({bridge:o,maxMs:c,strict:l});console.log(f?` settled in ${p}ms`:` timed out after ${p}ms (may still be animating)`)}async function ro(e){let o=e.positional[1]?Number(e.positional[1]):.5;(!Number.isFinite(o)||o<0)&&(console.error(e.inspectUsage("sleep","[seconds]")),process.exit(1)),await oe(o*1e3),console.log(` slept ${o}s`)}async function io(e){let{bridge:o,args:s,positional:a}=e,c=a[1]?Number(a[1]):5,{tree:l}=await it(o,c);if(P(s)){D({depth:c,tree:l??null});return}console.log(typeof l=="string"?l:JSON.stringify(l,null,2))}async function ao(e,o={args:[]}){let s=await at(e);if(P(o.args)){D(s);return}console.log(s.url)}async function lo(e){let{wsPort:o,commandTimeoutMs:s,simId:a,simIdSource:c,positional:l}=e,p=l[1]?Number(l[1]):30,f=Math.max(1e3,(Number.isFinite(p)?p:30)*1e3),v=Math.max(1,Math.ceil(f/500));console.log(" waiting for sim reconnect...");let _=await Mt(o,s,a,{attempts:v,simIdSource:c});_||(console.error(" timed out waiting for sim reconnect"),process.exit(1)),_.bridge.close(),Fe({source:"inspect wait",step:{wait:f},summary:`wait ${Math.round(f/1e3)}s`}),console.log(` ready: ${_.count} nodes`)}var co=new Set(["app-launch","toast","keyboard","screen","route","alert","actionsheet","picker","notification","fetch","console","shell","scroll","gesture","text-input","react-commit","animation","reanimated"]);function Re(e,o){let s=e.indexOf(o);if(s>=0&&s+1<e.length)return e[s+1]}function cs(e,o){if(!o.filter&&!o.equals)return!0;let s=e.data,a=[];if(s&&typeof s=="object")for(let l of["url","displayUrl","message","name","activeName","path","pathname","title","phase","event","type","kind"]){let p=s[l];typeof p=="string"&&p.length>0&&a.push(p)}let c=a.join(" ");return o.equals?a.some(l=>l===o.equals):o.filter?c.toLowerCase().includes(o.filter.toLowerCase()):!0}async function uo(e){let{bridge:o,args:s,positional:a,inspectUsage:c}=e,l=a[1];l||(console.error(c("wait event","<kind> [--max-ms 5000] [--filter <substring>] [--equals <exact>] [--since now|cursor]")),process.exit(1)),co.has(l)||console.error(` warning: '${l}' is not a known timeline kind \u2014 waiting anyway. known: ${[...co].sort().join(", ")}`);let p=Re(s,"--max-ms"),f=p&&Number.isFinite(Number(p))?Math.max(100,Number(p)):5e3,v=Re(s,"--filter"),_=Re(s,"--equals"),h=Re(s,"--since")??"now",I=s.includes("--json"),F=Date.now(),N=F+f,L=200,M=F;for(;Date.now()<N;){let j={kinds:[l],since:h==="cursor"?void 0:M,limit:50},A=await o.send({type:"evaluate",code:`(async () => {
428
+ const t = window.SootSim?.bridges?.timeline
429
+ if (!t) return { ok: false, error: 'timeline bridge missing' }
430
+ return { ok: true, result: await t.recent(${JSON.stringify(j)}) }
431
+ })()`});(!A||!A.ok)&&(console.error(` could not query timeline: ${A&&"error"in A?A.error:"unknown"}`),process.exit(1));let E=A.result.events??[];for(let H of E)if(cs(H,{filter:v,equals:_})){let U=Date.now()-F;console.log(I?JSON.stringify({found:!0,elapsedMs:U,event:H}):` ${l} event after ${U}ms${v?` (filter: ${v})`:""}${_?` (equals: ${_})`:""}`);return}A.result.watermark&&A.result.watermark>M&&(M=A.result.watermark),await new Promise(H=>setTimeout(H,L))}let u=Date.now()-F;I?console.log(JSON.stringify({found:!1,elapsedMs:u,kind:l,filter:v,equals:_})):console.error(` \u26A0 wait event ${l} timed out after ${u}ms${v?` (filter: ${v})`:""}${_?` (equals: ${_})`:""}`),process.exit(1)}async function po(e){let{bridge:o,args:s}=e,a=s.includes("--strict"),c=ve(s,3e3),{elapsed:l,settled:p}=await se({bridge:o,maxMs:c,strict:a});p?console.log(` idle in ${l}ms`):(console.error(` \u26A0 wait idle timed out after ${l}ms (may still be animating)`),process.exit(1))}async function mo(e){let{bridge:o,args:s}=e,a=ve(s,2e4),{ready:c,elapsedMs:l,nodes:p,targets:f,flag:v,loadingText:_,externalReady:h,externalError:I,suppressedEntryError:F,errors:N}=await mt(o,a,{onProgress(M){console.error(` still waiting after ${M.elapsedMs}ms \u2014 ${je(M)} (nodes: ${M.nodes}, targets: ${M.targets}, errors: ${M.errors})`)}});if(c){let M=a-l,u=Math.max(100,Math.min(1e4,M)),j=await se({bridge:o,maxMs:u,pollMs:32,stablePolls:2});j.settled||(console.error(` \u26A0 wait ready timed out after ${l+j.elapsed}ms \u2014 app mounted but did not settle (nodes: ${p}, targets: ${f})`),process.exit(1)),console.log(` ready in ${l+j.elapsed}ms: ${p} nodes, ${f} targets`);return}let L=je({externalError:I,loadingText:_,externalReady:h,flag:v,targets:f,suppressedEntryError:F});console.error(` \u26A0 wait ready timed out after ${l}ms \u2014 ${L} (nodes: ${p}, targets: ${f}, errors: ${N})`),process.exit(1)}async function fo(e){let{bridge:o,args:s,positional:a,inspectUsage:c}=e,l=a[1];l||(console.error(c("wait selector","<testid> [--max-ms 5000] [--gone]")),process.exit(1));let p=s.indexOf("--max-ms"),f=p>=0&&s[p+1]?Math.max(100,Number(s[p+1])):5e3,v=s.includes("--gone"),{found:_,node:h,elapsed:I}=await ft(o,l,f,{gone:v});if(v){_?console.log(` #${l} gone after ${I}ms`):(console.error(` \u26A0 wait selector #${l} --gone timed out after ${I??f}ms (still present)`),process.exit(1));return}if(_&&h){let F=h.absolutePosition?`@(${Math.round(h.absolutePosition.x)},${Math.round(h.absolutePosition.y)})`:"",N=h.layout?`${Math.round(h.layout.width)}x${Math.round(h.layout.height)}`:"?x?";console.log(` found #${l} in ${I}ms ${N} ${F}`)}else console.error(` \u26A0 wait selector #${l} timed out after ${I??f}ms`),process.exit(1)}function ko(e){return e==null?"\u2014":e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/1024/1024).toFixed(1)}M`}function _o(e){return e==null?" \u2026":e<1e3?`${e}ms`.padStart(5):`${(e/1e3).toFixed(2)}s`.padStart(5)}function go(){process.stderr.write(` the sim is not responding. recover it with:
432
+ sootsim close --sim <id> # force-close the wedged sim
433
+ sootsim list # confirm it's gone
434
+ `)}async function ds(e){try{return await e.send({type:"evaluate",code:"1"},{timeoutMs:3e3}),!0}catch{return!1}}async function ps(e,o){try{let s=await e.send({type:"evaluate",code:`(async () => {
435
+ const t = window.__sootsimTest
436
+ if (!t || typeof t.queryAll !== 'function') return []
437
+ try {
438
+ // queryAll is async in render-worker mode (the canonical mode now)
439
+ // because the call has to round-trip the worker \u2014 must await it.
440
+ // a sync result is still handled fine since await on a non-Promise
441
+ // is a no-op.
442
+ const nodes = await t.queryAll({})
443
+ if (!Array.isArray(nodes)) return []
444
+ const out = new Set()
445
+ for (const n of nodes) {
446
+ const id = n && (n.testID || n.id)
447
+ if (typeof id === 'string' && id) out.add(id)
448
+ }
449
+ return Array.from(out)
450
+ } catch {
451
+ return []
452
+ }
453
+ })()`});if(!Array.isArray(s)||s.length===0)return;let a=o.toLowerCase(),c=s.map(l=>({id:l,score:ms(a,l.toLowerCase())})).filter(l=>l.score<a.length+4).sort((l,p)=>l.score-p.score).slice(0,5);if(c.length===0)return;console.error(" similar testIDs:");for(let l of c)console.error(` ${l.id}`)}catch{}}function ms(e,o){if(o===e)return 0;if(o.includes(e))return 1;if(e.includes(o))return 2;let s=0;for(;s<e.length&&s<o.length&&e[s]===o[s];)s+=1;return fs(e,o)-s}function fs(e,o){if(e===o)return 0;if(!e.length)return o.length;if(!o.length)return e.length;let s=new Array(o.length+1),a=new Array(o.length+1);for(let c=0;c<=o.length;c++)s[c]=c;for(let c=1;c<=e.length;c++){a[0]=c;for(let p=1;p<=o.length;p++)a[p]=Math.min(s[p]+1,a[p-1]+1,s[p-1]+(e[c-1]===o[p-1]?0:1));let l=s;s=a,a=l}return s[o.length]}function gs(e){return e.error?"err":e.status==null?" \u2026 ":String(e.status)}function yo(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 ho(e){let o=ie(e.startTs),s=gs(e).padEnd(3),a=e.method.padEnd(5),c=ko(e.size).padStart(6),l=_o(e.durationMs);console.log(` [${o}] ${s} ${a} ${c} ${l} ${e.displayUrl}`),e.error&&console.log(` error: ${e.error}`)}function ys(e){let o=[["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",ie(e.startTs)],["duration",_o(e.durationMs).trim()],["size",ko(e.size)],["content-type",e.type??"\u2014"]];for(let[s,a]of o)console.log(` ${s.padEnd(13)} ${a}`)}var hs={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},bo="\x1B[0m",bs="\x1B[2m";function wo(e,o){let s=ie(e.ts),a=e.level.toUpperCase().padEnd(5),c=e.args.join(" ");if(o){let l=hs[e.level];console.log(` ${bs}[${s}]${bo} ${l}${a}${bo} ${c}`)}else console.log(` [${s}] ${a} ${c}`);if(e.stack&&e.level==="error"){let l=e.stack.split(`
454
+ `).slice(0,5);for(let p of l)console.log(` ${p.trim()}`)}}var ws=120;async function xo(e,o){let s=e.find((F,N)=>e[N-1]==="--id"),a=e.find((F,N)=>e[N-1]==="--text");if(s||a){let F=await o.send({type:"evaluate",code:At({id:s,text:a})});if(!F)throw new Error(s?`no node with id "${s}"`:`no node matching text "${a}"`);let{x:N,y:L,w:M,h:u}=F;return{x:N,y:L,w:M,h:u}}let c=e.find((F,N)=>e[N-1]==="--area");if(c){let F=c.split(",").map(j=>Number(j.trim()));if(F.length!==4||F.some(j=>!Number.isFinite(j)))throw new Error(`--area expects x,y,w,h (got "${c}")`);let[N,L,M,u]=F;return{x:N,y:L,w:M,h:u}}let l=F=>{let N=e.find((M,u)=>e[u-1]===F);if(N==null)return null;let L=Number(N);return Number.isFinite(L)?L:null},p=l("--x"),f=l("--y"),v=l("--w"),_=l("--h");if(p!=null||f!=null||v!=null||_!=null)return{x:p??0,y:f??0,w:v??1,h:_??1};let I=e.filter((F,N)=>N>0&&!F.startsWith("-")&&e[N-1]!=="--output"&&e[N-1]!=="--area"&&e[N-1]!=="--id"&&e[N-1]!=="--text"&&e[N-1]!=="--x"&&e[N-1]!=="--y"&&e[N-1]!=="--w"&&e[N-1]!=="--h").map(Number).filter(F=>Number.isFinite(F));if(I.length>=2){let[F,N,L=1,M=1]=I;return{x:F,y:N,w:L,h:M}}return null}function $o(e){let o=e.avgMs>0?(1e3/e.avgMs).toFixed(1):"?";console.log(` shell frame profile:
455
+ `),console.log(` painted frames: ${e.frames}${e.skippedFrames?` (+${e.skippedFrames} skipped idle ticks)`:""}`),console.log(` avg: ${e.avgMs}ms (${o} fps) \xB7 max ${e.maxMs}ms`),console.log(` p50/p95/p99: ${e.p50} / ${e.p95} / ${e.p99} ms`),console.log(` jank: ${e.jankFrames} frames (${e.jankPct}%) >16.67ms`),console.log(` avg per frame: overlay ${e.avgOverlayMs}ms \xB7 aux ${e.avgAuxMs}ms \xB7 layout ${e.avgLayoutMs}ms`);let s=e.cadence;s&&typeof s=="object"&&(console.log(""),console.log(` cadence (frame delivery, ${s.vsyncTicks} vsync ticks):`),console.log(` display clock: ${s.displayHz}hz \xB7 host rAF interval p50 ${s.hostIntervalP50} / p95 ${s.hostIntervalP95} / max ${s.hostIntervalMax} ms${s.hostGaps?` \xB7 ${s.hostGaps} gaps >1.5x (host rAF starved)`:""}`),console.log(` delivery lag: p50 ${s.deliveryLagP50} / p95 ${s.deliveryLagP95} / max ${s.deliveryLagMax} ms (vsync postMessage \u2192 shell receipt)`),console.log(` paint interval: p50 ${s.paintIntervalP50} / p95 ${s.paintIntervalP95} / max ${s.paintIntervalMax} ms${s.idleBreaks?` \xB7 ${s.idleBreaks} idle breaks excluded`:""}`));let a=Array.isArray(e.auxSurfaces)?e.auxSurfaces:[];if(a.length>0){console.log(""),console.log(" surfaces (last 100 frames):");for(let p of a)console.log(` ${String(p.surfaceId).padEnd(10)} ${String(p.frames).padStart(4)} paints avg ${p.avgMs}ms (layout ${p.avgLayoutMs}, render ${p.avgRenderMs}, flush ${p.avgFlushMs}) max ${p.maxMs}ms`)}let c=e.renderProfile;if(c&&typeof c=="object"){console.log(""),console.log(" render profile (per frame):"),console.log(` node visits: ${c.nodeVisitsPerFrame}`),console.log(` boundaries: ${c.recordsPerFrame} records (${c.avgBoundaryRecordMs}ms) / ${c.replaysPerFrame} replays`),console.log(` raster tier: ${c.rasterPromotionsPerFrame} promotions / ${c.rasterBlitsPerFrame} blits`);let p=[c.rasterRejectRebuild?`rebuild ${c.rasterRejectRebuild}`:"",c.rasterRejectLinear?`linear ${c.rasterRejectLinear}`:"",c.rasterRejectAnimated?`animated ${c.rasterRejectAnimated}`:"",c.rasterRejectTransform?`transform ${c.rasterRejectTransform}`:"",c.rasterRejectOpacity?`opacity ${c.rasterRejectOpacity}`:"",c.rasterRejectCacheable?`cacheable ${c.rasterRejectCacheable}`:"",c.rasterRejectBounds?`bounds ${c.rasterRejectBounds}`:"",c.rasterRejectPixels?`pixels ${c.rasterRejectPixels}`:"",c.rasterWarming?`warming ${c.rasterWarming}`:""].filter(Boolean).join(" \xB7 ");p&&console.log(` raster skips: ${p} (total across run)`),console.log(` blur: ${c.avgBlurMs}ms`),console.log(` draw calls: text ${c.textDrawsPerFrame} \xB7 image ${c.imageDrawsPerFrame} \xB7 path ${c.pathDrawsPerFrame} \xB7 saveLayer ${c.saveLayersPerFrame}`)}let l=Array.isArray(e.worstFrames)?e.worstFrames:[];if(l.length>0){console.log(""),console.log(" worst frames (of last 100):");for(let p of l){let f=(p.auxSurfaces??[]).map(v=>`${v.surfaceId} ${v.totalMs}ms (layout ${v.layoutMs}, render ${v.renderMs})`).join(" \xB7 ");console.log(` ${String(p.totalMs).padStart(7)}ms overlay ${p.overlayMs} \xB7 aux ${p.auxMs} \xB7 layout ${p.layoutMs}${f?` [${f}]`:""}`)}}}async function Ee(e,o,s){let a=Date.now()+o,c=await ue(e,o);for(;;){if(s(c))return{settled:!0,state:c};if(Date.now()>=a)return{settled:!1,state:c};await oe(16),c=await ue(e)}}async function et(e){return e.send({type:"evaluate",code:`(async () => {
456
+ const kb = window.__sootsimKeyboard
457
+ const test = window.__sootsimTest
458
+ if (!kb) return { error: 'keyboard bridge not available' }
459
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
460
+ const secureTextEntry =
461
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
462
+ const visible = kb.isVisible()
463
+ const mode = kb.getMode()
464
+ let focused = null
465
+ if (test && typeof test.getFocusedNode === 'function') {
466
+ try {
467
+ focused = await test.getFocusedNode()
468
+ } catch {}
469
+ }
470
+ let runtimeSnapshot = null
471
+ if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
472
+ try {
473
+ runtimeSnapshot = await test.getFocusKeyboardSnapshot()
474
+ } catch {}
475
+ }
476
+ return {
477
+ visible,
478
+ mode,
479
+ layout,
480
+ focusedInput: focused ? {
481
+ nodeId: focused.nodeId ?? null,
482
+ testID: focused.testID || null,
483
+ id: focused.id || null,
484
+ placeholder: focused.placeholder || null,
485
+ secureTextEntry,
486
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
487
+ } : null,
488
+ phase: runtimeSnapshot?.keyboard?.phase ?? null,
489
+ frame: runtimeSnapshot?.keyboard?.frame ?? null,
490
+ focusedRect: runtimeSnapshot?.focused?.rect ?? null,
491
+ }
492
+ })()`}).then(o=>Qe(o))}function xs(e,o,s){if(!e.visible)return!1;let a=e.focusedInput;return!(o&&a&&!(a.testID===o||a.id===o)||s!==null&&be(e)!==s)}async function $s(e,o=600,s={}){let a=Date.now()+o;for(;Date.now()<=a;){let c=await et(e);if(xs(c,s.targetId??null,s.secureTextEntry??null))return c;await oe(30)}return et(e)}async function Pe(e,o){let s=await et(e);if(s.visible&&s.focusedInput)return s;s.visible&&(console.error(` ${o} requires a focused TextInput. the iOS keyboard is visible, but no input owns focus.`),process.exit(1)),console.error(` ${o} requires the iOS keyboard to be visible. focus an input first with sootsim do tap-id/tap-text or sootsim do type-into.`),process.exit(1)}async function So(e,o,s){return o==="appearance"?e.send({type:"evaluate",code:`(async () => {
493
+ const requested = ${JSON.stringify(s??"toggle")}
494
+ // the engine owns toggle + auto resolution (settingsStore is the single
495
+ // source of truth). never infer the current scheme client-side \u2014 the old
496
+ // documentElement '#333333' sniff is never set in embedded / shell-chrome
497
+ // contexts, so 'toggle' read 'light' forever and stuck on the boot scheme.
498
+ window.postMessage({ type: 'soot-action', action: 'set-appearance', value: requested }, '*')
499
+ // let the engine's message handler apply + publish window.__sootsimColorScheme
500
+ await new Promise((r) => setTimeout(r, 60))
501
+ const applied = window.__sootsimColorScheme?.resolved
502
+ ?? (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
503
+ const setting = window.__sootsimColorScheme?.setting ?? requested
504
+ return { ok: true, requested, setting, applied }
505
+ })()`}):o==="lock"?e.send({type:"evaluate",code:`(async () => {
506
+ const toggleLock = window.SootSim?.bridges?.mainShell?.toggleLock
507
+ if (typeof toggleLock !== 'function') {
508
+ throw new Error('SootSim mainShell.toggleLock bridge unavailable')
509
+ }
510
+ await toggleLock()
511
+ return { ok: true, action: 'lock' }
512
+ })()`}):e.send({type:"evaluate",code:`(async () => {
513
+ window.dispatchEvent(new CustomEvent('sootsim:shake'))
514
+ return { ok: true, action: 'shake' }
515
+ })()`})}function Ss(e){let o={Enter:"return",NumpadEnter:"return",Backspace:"delete",Delete:"delete",Space:"space",ShiftLeft:"shift",ShiftRight:"shift"};if(o[e])return o[e];let s=e.match(/^Digit([0-9])$/);if(s)return s[1];let a=e.match(/^Key([A-Z])$/);return a?a[1].toLowerCase():null}function vs(e){if(typeof e!="string")return null;let o=e.replace(/\s+/g," ").trim();return o?o.slice(0,80):null}function Io(...e){for(let o of e){if(typeof o!="string")continue;let s=o.trim();if(s)return s}return null}function ks(e){let o=e.indexOf("--node-id");if(o<0)return null;let s=e[o+1];if(!s)return null;let a=Number(s);return Number.isInteger(a)&&a>0?a:null}async function q(e,o,s){let a=Fe({source:e,step:o,summary:s});a.active&&(a.replaced?console.error(` draft: replaced unkept action "${a.replaced.summary}" \u2014 \`flow keep\` commits one action at a time`):console.error(" draft: action pending \u2014 `sootsim flow keep` to commit"))}function vo(e,o,s){if(!s||s.hit===!1)return null;let a=Io(s.responderTestID,s.testID);if(a)return{step:{tapOn:{id:a}},summary:`tap #${a}`};let c=vs(s.text);return c?{step:{tapOn:c},summary:`tap "${c}"`}:{step:{tapAtCoords:{x:e,y:o}},summary:`tap @${Math.round(e)},${Math.round(o)}`}}function Ze(e,o,s){let a=Io(o?.testID,o?.id);return a?{step:{tapOn:{id:a}},summary:`tap #${a}`}:s==="id"?{step:{tapOn:{id:e}},summary:`tap #${e}`}:{step:{tapOn:e},summary:`tap "${e}"`}}async function Or(e,o){let s=e[0]==="get"||e[0]==="do"||e[0]==="debug"||e[0]==="wait"?e[0]:null,a=s?e.slice(1):e,c=_t(a,{port:o.port,commandTimeoutMs:o.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"]}),l=c.positional,p=l[0],f=s==="get"||s==="do"||s==="debug"||s==="wait"?s:"inspect",v=typeof a[0]=="string"&&tt.has(a[0]),_=v?a[0]:null,h=x=>o.internalShellPerf&&x==="perf"?"sootsim perf shell":v&&x===a[0]?`sootsim ${x}`:`sootsim ${f} ${x}`,I=(x,t)=>` usage: ${h(x)}${t?` ${t}`:""}`;if(!p||e.includes("--help")||e.includes("-h")){let x={bridgePort:7668,defaultShellUrl:ot};if(f==="do"||f==="get"||f==="debug"||f==="wait"){let r=Ae(f,x);r&&(console.log(`${r}
516
+ `),process.exit(0))}if(_==="shell"){let r=De("shell",x);r&&(console.log(`${r}
517
+ `),process.exit(0))}let t=De("inspect",x),n=["do","get","debug","wait"].map(r=>Ae(r,x)).filter(r=>r!=null).join(`
518
+
519
+ `);console.log(`${t??""}
520
+
521
+ ${n}
522
+ `),process.exit(0)}let F=c.wsPort,N=c.simId,L=c.simIdSource,M=c.commandTimeoutMs;if(f==="get"&&p==="diagnosis"){let x=a.indexOf("diagnosis"),t=x>=0?[...a.slice(0,x),...a.slice(x+1)]:a,{runDiagnose:n}=await import("./diagnose-CH3VYGFO.js"),r=await n(["recent",...t],o);process.exitCode=r;return}if(f==="do"&&p==="scan"){let{runCamera:x}=await import("./camera-YQPIDOEN.js");await x(a,{port:o.port});return}if(p==="list"&&a.some(x=>x==="--drivers"||x==="-D")){let{buildDriverListRows:x}=await import("./drivers-XDAXVIZF.js"),t=x();console.log(` available drivers (${t.length}):
523
+ `);let n=Math.max(...t.map(i=>i.id.length),6),r=Math.max(...t.map(i=>i.kind.length),4);for(let i of t){let d=i.available?"\u2713":"\u2717",m=i.id.padEnd(n),g=i.kind.padEnd(r);console.log(` ${d} ${m} ${g} ${i.description}`),i.available&&i.detail?console.log(` ${i.detail}`):!i.available&&i.reason&&console.log(` unavailable: ${i.reason}`)}return}let u=It(c),j=N||"default",A=new Set(["errors","warnings","requests","js","eval","reload","globals","perf","storage-clear","list","wait","sleep"]),E=200;function H(x){let t=x.replace(/\s+/g," ").trim();if(!t)return"";if(/^<(!doctype html|html|\?xml)|<body[\s>]/i.test(t)){let r=/<title[^>]*>([^<]+)<\/title>/i.exec(x)?.[1]?.trim(),i=/<body[^>]*>([\s\S]*?)<\//i.exec(x)?.[1]?.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,80),d=r||i||"html error page";return`<html ${x.length}B> "${d}" (body elided \u2014 add --json for the full payload)`}return t.length<=E?t:`${t.slice(0,E)}\u2026 (+${t.length-E} more bytes)`}function U(x){let t=x.displayUrl||x.url;return x.status!=null?`${x.method} ${t} -> ${x.status}${x.statusText?` ${x.statusText}`:""}`:x.error?`${x.method} ${t} -> ${x.error}`:`${x.method} ${t}`}async function S(x){let t=me()?5e3:1500;try{let{settled:n,elapsed:r}=await se({bridge:x,maxMs:t,pollMs:32,stablePolls:2});n||process.stderr.write(` \u26A0 auto-wait timed out after ${r??t}ms \u2014 next command may see mid-animation state. use \`sootsim do settle\` for a longer wait.
524
+ `)}catch{}}function O(x,t){console.error(` tap failed: ${x} stayed visible but did not receive a hittable press after ${t.attempts} attempt${t.attempts===1?"":"s"}`),t.result&&console.error(` last result: ${JSON.stringify(t.result)}`)}async function J(){try{return await u.send({type:"evaluate",code:`(() => ({
525
+ console: ${ke},
526
+ requests: window.__sootsimTest?.getRequestCounts?.() || null,
527
+ }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function K(x={}){let t=x.counts!==void 0?x.counts:await V(u,"getRequestCounts");if(!t||typeof t!="object")return;let n=Math.max(0,Number(t.failed)||0);if(n===0||!x.includeTail&&!ze("requests",j,String(n))||(console.log(`
528
+ network: ${n} failed request${n===1?"":"s"}`),console.log(` inspect: ${h("requests")} 5`),!x.includeTail))return;let r=await V(u,"getFailedRequests",5);if(!(!Array.isArray(r)||r.length===0)){console.log(`
529
+ recent failed requests:
530
+ `);for(let i of r){let d=ie(i.timestamp);console.log(` [${d}] ${U(i)}`),i.responseBody?console.log(` ${H(i.responseBody)}`):i.error&&console.log(` ${i.error}`)}}}function ee(x){for(let t of x){let n=t.title?` (\u201C${t.title}\u201D)`:"";console.log(`
531
+ note: ${t.label} is open${n} \u2014 taps/drags hit it, not the app`)}}async function te(x={}){let t=x.counts!==void 0?x.counts:await u.send({type:"evaluate",code:ke});if(!t||typeof t!="object")return;let n=t,r=Math.max(0,Number(n.errors)||0),i=Math.max(0,Number(n.warnings)||0);if(r===0&&i===0||!x.includeTail&&!ze("console",j,`${r}:${i}`))return;let d=[];if(r>0&&d.push(`${r} console error${r===1?"":"s"}`),i>0&&d.push(`${i} console warning${i===1?"":"s"}`),console.log(`
532
+ console: ${d.join(", ")}`),console.log(` inspect: ${h("errors")} 5`),i>0&&console.log(` inspect: ${h("warnings")} 5`),!x.includeTail||r===0)return;let m=await fe(u,5);if(!(!Array.isArray(m)||m.length===0)){console.log(`
533
+ recent console errors:
534
+ `);for(let g of m){let b=ie(g.timestamp),y=Array.isArray(g.args)?g.args.map($=>typeof $=="object"?JSON.stringify($):String($)).join(" "):String(g);console.log(` [${b}] ${y}`)}}}let re=["console","fetch","toast","alert","notification","screen","app-launch","keyboard","route","actionsheet","picker","shell","scroll","gesture","text-input","animation","reanimated"];async function xe(x){let t=st(),n=null;try{n=await Nt(x,`(() => {
535
+ const tl = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.timeline
536
+ if (!tl || typeof tl.summary !== 'function') return null
537
+ const cursorKey = ${JSON.stringify(t)}
538
+ const summary = tl.summary({ sinceCursor: cursorKey })
539
+ let consoleSplit = null
540
+ if (summary && summary.byKind && summary.byKind.console) {
541
+ const events = tl.recent({ sinceCursor: cursorKey, kinds: 'console', limit: 100000 }).events
542
+ consoleSplit = { error: 0, warn: 0 }
543
+ for (const ev of events) {
544
+ const lvl = ev && ev.data && ev.data.level
545
+ if (lvl === 'error') consoleSplit.error++
546
+ else if (lvl === 'warn') consoleSplit.warn++
547
+ }
548
+ }
549
+ return summary ? { summary, consoleSplit } : null
550
+ })()`)}catch{return}if(!n||!n.summary||!n.summary.total)return;let r=n.summary.byKind??{},i=[],d=new Set;for(let m of re){let g=r[m];if(g)if(d.add(m),m==="console"&&n.consoleSplit){let{error:b,warn:y}=n.consoleSplit;b>0&&i.push(`${b} error${b===1?"":"s"}`),y>0&&i.push(`${y} warning${y===1?"":"s"}`)}else i.push(`${g} ${m}${g===1?"":"s"}`)}for(let[m,g]of Object.entries(r))!d.has(m)&&g&&i.push(`${g} ${m}${g===1?"":"s"}`);if(i.length!==0&&(console.log(`
551
+ since last: ${i.join(" \xB7 ")} \u2014 sootsim what-happened`),n.summary.lastAt))try{await _e(x,"SootSim.bridges.timeline.cursorAdvance",t,n.summary.lastAt)}catch{}}let C=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"]),$e=(e.includes("--verbose")||e.includes("-v"))&&!e.includes("--json");f==="do"&&p==="shell"&&(console.error(" `sootsim do shell` was removed. use `sootsim shell ...` instead."),process.exit(1)),C.has(p)&&await Tt(u),le.has(p)&&await de(u,{verbose:$e});try{let x=C.has(p)&&!P(a)?await $t(u):[];switch(p){case"list":{kt(c.wsPort),await Zt({bridge:u,simId:N,args:a});break}case"tree":{await io({bridge:u,args:a,positional:l});break}case"a11y":{let t=await dt(u);if(!Array.isArray(t)||t.length===0){console.log(" no accessible nodes found");break}if(e.includes("--json"))console.log(JSON.stringify(t,null,2));else{console.log(` accessibility tree (${t.length} nodes):
552
+ `);for(let n of t){let r=[];if(r.push(`[${n.role}]`),n.label){let i=n.label.length>50?n.label.slice(0,47)+"...":n.label;r.push(`"${i}"`)}if(n.hint&&r.push(`(hint: "${n.hint}")`),n.testID&&r.push(`#${n.testID}`),n.state){let i=[];n.state.disabled&&i.push("disabled"),n.state.selected&&i.push("selected"),n.state.checked===!0&&i.push("checked"),n.state.checked==="mixed"&&i.push("mixed"),n.state.busy&&i.push("busy"),n.state.expanded===!0&&i.push("expanded"),n.state.expanded===!1&&i.push("collapsed"),i.length&&r.push(`{${i.join(", ")}}`)}n.position&&r.push(`@(${n.position.x},${n.position.y})`),n.size&&r.push(`${n.size.w}x${n.size.h}`),console.log(" "+r.join(" "))}}break}case"find":{await Xt({bridge:u,args:e,effectiveArgs:a,positional:l,inspectUsage:I});break}case"count":{await zt(u,{args:a});break}case"keyboard":{await Qt(u,{json:e.includes("--json")});break}case"screens":{await so(u,{json:e.includes("--json")});break}case"memory":{await oo(u,{args:a});break}case"wait":{await lo({wsPort:F,commandTimeoutMs:M,simId:N,simIdSource:L,positional:l});break}case"sleep":{await ro({positional:l,inspectUsage:I});break}case"settle":{await no({bridge:u,args:e,positional:l});break}case"ready":{await mo({bridge:u,args:e});break}case"idle":{await po({bridge:u,args:e,positional:l});break}case"selector":{await fo({bridge:u,args:e,positional:l,inspectUsage:I});break}case"event":{await uo({bridge:u,args:e,positional:l,inspectUsage:I});break}case"layout":{let t=l[1];if(!t){await Vt({bridge:u,args:a});break}let n=await u.send({type:"evaluate",code:`(async () => await window.__sootsimTest.getLayout(${JSON.stringify(t)}))()`});console.log(JSON.stringify(n,null,2));break}case"capture":case"screenshot":{let n=e.find((b,y)=>e[y-1]==="--output")||"/tmp/sootsim-inspect.png",r=await xo(e,u),i={type:"screenshot"};r&&(i.crop=r);let m=(await u.send(i)).replace(/^data:image\/png;base64,/,"");r&&console.log(` area: x=${r.x} y=${r.y} w=${r.w} h=${r.h}`),(await import("fs")).writeFileSync(n,Buffer.from(m,"base64")),console.log(` saved: ${n}`);break}case"sample-color":{let t=await xo(e,u);t||(console.error(I("sample-color","<x> <y> [w] [h] | --id <testID> | --text <text>")),console.error(" samples an averaged color from the canvas. coords are logical sootsim units."),process.exit(1));let n=await u.send({type:"evaluate",code:Dt(t)});if(e.includes("--json"))console.log(JSON.stringify(n,null,2));else{let{r,g:i,b:d,a:m,hex:g,samples:b}=n,y=t.w===1&&t.h===1?`@(${t.x},${t.y})`:`@(${t.x},${t.y}) ${t.w}x${t.h}`;console.log(` ${g} rgba(${r}, ${i}, ${d}, ${m}) ${y} ${b} samples`)}break}case"node":{let t=l[1];t||(console.error(I("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let n=await u.send({type:"evaluate",code:`(async () => {
553
+ const t = window.__sootsimTest
554
+ const q = ${JSON.stringify(t)}
555
+ let node = null
556
+ let via = null
557
+ if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
558
+ if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
559
+ if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
560
+ if (!node) return { matcher: q, found: false }
561
+
562
+ // read the resolved transform (if any) off the style \u2014 useful
563
+ // because canvas nodes often animate via transform and describe
564
+ // output strips that.
565
+ const transform =
566
+ node.style && Array.isArray(node.style.transform)
567
+ ? node.style.transform
568
+ : node.style && node.style.transform
569
+ ? node.style.transform
570
+ : null
571
+
572
+ // parent chain \u2014 walk up from the node so the JSON dump is
573
+ // self-describing.
574
+ const parentChain = []
575
+ const root = window.__sootsimRoot
576
+ if (root && node.id != null) {
577
+ const findPath = (n, targetId, path) => {
578
+ if (!n) return null
579
+ if (n.id === targetId) return path
580
+ if (n.children) {
581
+ for (const child of n.children) {
582
+ const nextPath = [
583
+ ...path,
584
+ {
585
+ type: n.type || 'view',
586
+ testID: n.props?.testID || null,
587
+ text: n.text || null,
588
+ },
589
+ ]
590
+ const found = findPath(child, targetId, nextPath)
591
+ if (found) return found
592
+ }
593
+ }
594
+ return null
595
+ }
596
+ const chain = findPath(root, node.id, [])
597
+ if (chain) parentChain.push(...chain)
598
+ }
599
+
600
+ return {
601
+ matcher: q,
602
+ found: true,
603
+ resolvedVia: via,
604
+ node,
605
+ transform,
606
+ parentChain,
607
+ }
608
+ })()`});console.log(JSON.stringify(n,null,2));break}case"tap":{let t=Number(l[1]),n=Number(l[2]),r=we(e);if(r){let m=await he(u,{agent:me(),textFallback:r.mode==="text"?r.value:void 0,resolve:async()=>{let y=await Oe(u,r);return y?{cx:y.x,cy:y.y,match:{id:r.mode==="testid"?r.value:y.id??null,testID:r.mode==="testid"?r.value:y.testID??null,text:r.mode==="text"?r.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}}),g=m.payload;(!g||typeof g.cx!="number")&&(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),pe(m.result)||(O(`${r.mode} "${r.value}"`,m),process.exit(1));let b=vo(g.cx,g.cy,m.result);b&&await q("inspect tap",b.step,b.summary),console.log(JSON.stringify({...m.attempts>1?{attempts:m.attempts}:{},...m.result},null,2));break}(!Number.isFinite(t)||!Number.isFinite(n))&&(console.error(I("tap","<x> <y> | --testid <id> | --text <t>")),process.exit(1));let i=await Kt(u,t,n),d=vo(t,n,i);d&&await q("inspect tap",d.step,d.summary),console.log(JSON.stringify(i,null,2));break}case"drag":case"swipe":{let t=Number(l[1]),n=Number(l[2]),r=Number(l[3]),i=Number(l[4]),d=p==="swipe"?10:12,m=p==="swipe"?8:16,g=l[5]?Number(l[5]):d,b=l[6]?Number(l[6]):m;(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(g)||!Number.isFinite(b))&&(console.error(I(p,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let y=await u.send({type:"evaluate",code:`(async () => {
609
+ const interact = window.__sootsimInteract
610
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
611
+ const value = await interact.drag(${t}, ${n}, ${r}, ${i}, ${Math.max(1,Math.round(g))}, ${Math.max(0,Math.round(b))})
612
+ return { ok: !!value, value }
613
+ })()`});if(y?.ok){let $=Math.max(1,Math.round(Math.max(1,g)*Math.max(0,b)));await q(`inspect ${p}`,{swipe:{start:`${t}, ${n}`,end:`${r}, ${i}`,duration:$}},`${p} ${t},${n} -> ${r},${i}`)}console.log(JSON.stringify(y,null,2));break}case"pinch":{let t=Number(l[1]),n=Number(l[2]),r=Number(l[3]),i=Number(l[4]),d=Number(l[5]),m=Number(l[6]),g=Number(l[7]),b=Number(l[8]),y=l[9]?Number(l[9]):12,$=l[10]?Number(l[10]):16;(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(d)||!Number.isFinite(m)||!Number.isFinite(g)||!Number.isFinite(b)||!Number.isFinite(y)||!Number.isFinite($))&&(console.error(I("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let W=await u.send({type:"evaluate",code:`(async () => {
614
+ const interact = window.__sootsimInteract
615
+ if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
616
+ const value = await interact.pinch(${t}, ${n}, ${r}, ${i}, ${d}, ${m}, ${g}, ${b}, ${Math.max(1,Math.round(y))}, ${Math.max(0,Math.round($))})
617
+ return { ok: !!value, value }
618
+ })()`});W?.ok&&await q("inspect pinch",{pinch:{from:[t,n,r,i],to:[d,m,g,b],steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round($))}},`pinch (${t},${n}) (${r},${i}) -> (${d},${m}) (${g},${b})`),console.log(JSON.stringify(W,null,2));break}case"tap-text":{let t=l[1];t||(console.error(I("tap-text","<text>")),process.exit(1));let n=Y=>{let B=e.indexOf(Y);return B>=0&&B+1<e.length?e[B+1]:null},r=Y=>e.includes(Y),i=n("--nth")??n("--index"),d=i!==null?Number(i):null;d!==null&&!Number.isFinite(d)&&(console.error(` --nth/--index requires an integer, got: ${i}`),process.exit(1));let m=n("--within"),g=n("--role"),b=r("--exact"),y=r("--first"),$=n("--min-y"),W=n("--max-y"),X=n("--min-x"),G=n("--max-x");for(let[Y,B]of[["--min-y",$],["--max-y",W],["--min-x",X],["--max-x",G]])B!==null&&!Number.isFinite(Number(B))&&(console.error(` ${Y} requires a number, got: ${B}`),process.exit(1));let z=e.indexOf("--near"),R=null;if(z>=0){let Y=Number(e[z+1]),B=Number(e[z+2]);(!Number.isFinite(Y)||!Number.isFinite(B))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),R={x:Y,y:B}}let w={exact:b,role:g,within:m,minX:X!==null?Number(X):null,maxX:G!==null?Number(G):null,minY:$!==null?Number($):null,maxY:W!==null?Number(W):null,near:R,nth:d,first:y},k=await Ut(u,t,w,{agent:me()}),T=k.payload;if(T?.error==="bridge-not-ready"&&(console.error(" sootsim test bridge not ready"),process.exit(1)),T?.ambiguous){let Y=T.candidates;console.error(` ambiguous: ${T.total} matches for "${t}"`);for(let B of Y){let Se=B.abs?`@(${Math.round(B.abs.x)},${Math.round(B.abs.y)})`:"",To=B.layout?` ${B.layout.width}x${B.layout.height}`:"",No=B.testID?` #${B.testID}`:"",Mo=B.text?` "${B.text}"`:"",Fo=B.ancestorTestIDs.length>0?` within ${B.ancestorTestIDs.slice(0,3).map(Oo=>`#${Oo}`).join(" > ")}`:"";console.error(` [${B.idx}] <${B.type}>${Mo}${No} ${Se}${To}${Fo}`)}T.total>Y.length&&console.error(` ... and ${T.total-Y.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)}T?.nthOutOfRange&&(console.error(` not found: nth ${T.nth} of ${T.total} match${T.total===1?"":"es"} for "${t}"`),process.exit(1)),(!T||typeof T.cx!="number")&&(console.error(` not found: ${t}`),process.exit(1)),pe(k.result)||(O(`text "${t}"`,k),process.exit(1));let ne=Ze(t,{id:T.target?.id??null,testID:T.target?.testID??null,type:T.target?.type??null,cx:T.cx,cy:T.cy},"text");await q("inspect tap-text",ne.step,ne.summary),console.log(JSON.stringify({matched:T.match,tapped:{nodeId:T.target?.nodeId??null,id:T.target?.id??null,testID:T.target?.testID??null,type:T.target?.type??null,cx:T.cx,cy:T.cy},...T.strategy&&T.strategy!=="matched-node"?{strategy:T.strategy}:{},...T.total>1||d!==null?{nth:{index:T.idx,total:T.total}}:{},...k.attempts>1?{attempts:k.attempts}:{},result:k.result},null,2));break}case"tap-best":{let t=l[1];t||(console.error(I("tap-best","<query>")),process.exit(1));let n=await Gt(u,t,{agent:me()}),r=n.payload;r||(console.error(` tap-best: no testID or visible text matched "${t}". try \`sootsim find --interactive-targets\` to list candidates.`),process.exit(1)),"error"in r&&(console.error(` ${r.error}`),process.exit(1)),r.strategy==="none"&&(console.error(` tap-best: no testID or visible text matched "${t}". try \`sootsim find --interactive-targets\` to list candidates.`),process.exit(1));let i=r.node;pe(n.result)||(O(`best "${t}"`,n),process.exit(1));let d=Ze(t,{id:i.id,testID:i.testID,type:i.type,cx:r.cx,cy:r.cy},r.strategy==="testid"?"id":"text");await q("inspect tap-best",d.step,d.summary),console.log(JSON.stringify({matched:{strategy:r.strategy,nodeId:i.nodeId,id:i.id,testID:i.testID,type:i.type,text:i.text},tapped:{cx:r.cx,cy:r.cy},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"tap-id":{let t=l[1];t||(console.error(I("tap-id","<id>")),process.exit(1));let n=await Ht(u,t,{agent:me()}),r=n.payload;(!r||typeof r.cx!="number")&&(console.error(` not found: ${t}`),await ps(u,t),process.exit(1)),pe(n.result)||(O(`id "${t}"`,n),process.exit(1));let i=Ze(t,{id:r.target?.id??null,testID:r.target?.testID??null,type:r.target?.type??null,cx:r.cx,cy:r.cy},"id");await q("inspect tap-id",i.step,i.summary),console.log(JSON.stringify({matched:r.match,tapped:{nodeId:r.target?.nodeId??null,id:r.target?.id??null,testID:r.target?.testID??null,type:r.target?.type??null,cx:r.cx,cy:r.cy},...r.strategy&&r.strategy!=="matched-node"?{strategy:r.strategy}:{},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"type-into":{let t=l[1],n=l.slice(2).join(" ");(!t||!n)&&(console.error(I("type-into","<id> <text>")),process.exit(1));let r=JSON.stringify(t),i=await u.send({type:"evaluate",code:`(async () => {
619
+ const t = window.__sootsimTest
620
+ if (!t) return null
621
+ const n = await (t.findByTestId(${r}) || t.findById(${r}))
622
+ if (!n || !n.absolutePosition || !n.layout) return null
623
+ return {
624
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
625
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
626
+ id: n.id,
627
+ testID: n.testID,
628
+ type: n.type,
629
+ isTextInput: !!n.isTextInput,
630
+ secureTextEntry: !!n.secureTextEntry,
631
+ placeholder: n.placeholder || null,
632
+ }
633
+ })()`});(!i||typeof i.cx!="number")&&(console.error(` not found: ${t}`),process.exit(1)),i.isTextInput||console.error(` warning: ${t} is not a text input (isTextInput: false)`);let d=await u.send({type:"tap",x:i.cx,y:i.cy,target:{id:i.id??t,testID:i.testID??t,text:null,type:i.type??null}}),m=i.secureTextEntry===!0,g=await $s(u,1e3,{targetId:t,secureTextEntry:m});g.visible||(console.error(` keyboard did not open after tapping ${t}`),process.exit(1));let b=g.focusedInput;b&&(b.testID===t||b.id===t||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(t)} but focus is on ${JSON.stringify(b.testID??b.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await u.send({type:"keyboard",action:"type",text:n});let y=m||be(g),$=y?Z:Ve(n,g),W=y&&g.focusedInput?{...g.focusedInput,secureTextEntry:!0,text:typeof g.focusedInput.text=="string"?Z:g.focusedInput.text}:g.focusedInput??null;await q("inspect type-into",{tapOn:{id:t},inputText:$},$===Z?`type-into #${t} ${Z}`:`type-into #${t} ${JSON.stringify(n)}`),console.log(JSON.stringify({target:t,isTextInput:i.isTextInput,secureTextEntry:y,keyboardOpened:g.visible??d?.keyboardOpened??!1,focusedInput:W,typed:$},null,2));break}case"type":{let t=l.slice(1).join(" ");t||(console.error(I("type","<text>")),process.exit(1));let n=await Pe(u,"type");await u.send({type:"keyboard",action:"type",text:t});let r=Ve(t,n);await q("inspect type",{inputText:r},r===Z?`type ${Z}`:`type ${JSON.stringify(t)}`),console.log(r===Z?` typed: ${Z}`:` typed: ${JSON.stringify(t)}`);break}case"key":{let t=l[1];t||(console.error(I("key","<name>")),process.exit(1)),await Pe(u,"key"),await u.send({type:"keyboard",action:"press",text:t}),await q("inspect key",{pressKey:t},`key ${t}`),console.log(` pressed: ${t}`);break}case"key-sequence":{let t=l.slice(1);t.length===0&&(console.error(I("key-sequence","<key> [<key> ...]")),process.exit(1)),await Pe(u,"key-sequence");for(let n of t)await u.send({type:"keyboard",action:"press",text:n});await q("inspect key-sequence",{pressKey:t.join(" ")},`key-sequence ${t.join(" ")}`),console.log(` pressed: ${t.join(", ")}`);break}case"keycode":{let t=l.slice(1);t.length===0&&(console.error(I("keycode","<code> [<code> ...]")),process.exit(1));let n=t.map(i=>({code:i,key:Ss(i)})),r=n.filter(i=>!i.key);r.length>0&&(console.error(` unsupported keycode(s): ${r.map(i=>i.code).join(", ")}`),process.exit(1)),await Pe(u,"keycode");for(let i of n)await u.send({type:"keyboard",action:"press",text:i.key});await q("inspect keycode",{pressKey:n.map(i=>i.key).join(" ")},`keycode ${t.join(" ")}`),console.log(` pressed: ${t.join(", ")}`);break}case"dispatch":{let t=l[1];t||(console.error(I("dispatch","<char>")),process.exit(1)),await u.send({type:"keyboard",action:"dispatchKey",text:t}),await q("inspect dispatch",{dispatchKey:t},`dispatch ${JSON.stringify(t)}`),console.log(` dispatched: ${t}`);break}case"dismiss":{await u.send({type:"keyboard",action:"dismiss"}),await q("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let t=Number(l[1]),n=Number(l[2]),r=we(e);if(r){let g=await Oe(u,r);g||(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),t=g.x,n=g.y}let i=l[3]?Number(l[3]):80;(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(i))&&(console.error(I("double-tap","<x> <y> [gapMs] | --testid <id>")),process.exit(1));let d=Math.max(0,Math.round(i)),m=await u.send({type:"evaluate",code:`(async () => {
634
+ const interact = window.__sootsimInteract
635
+ if (interact?.doubleTap) {
636
+ return {
637
+ ok: !!(await interact.doubleTap(${t}, ${n}, ${d})),
638
+ gapMs: ${d},
639
+ }
640
+ }
641
+ if (!interact?.tap) {
642
+ return { ok: false, reason: 'no interact.tap', gapMs: ${d} }
643
+ }
644
+ const first = await interact.tap(${t}, ${n})
645
+ if (!first || first.hit === false) {
646
+ return { ok: false, reason: 'first tap missed', gapMs: ${d}, first }
647
+ }
648
+ await new Promise((resolve) => setTimeout(resolve, ${d}))
649
+ const second = await interact.tap(${t}, ${n})
650
+ return {
651
+ ok: !!second && second.hit !== false,
652
+ gapMs: ${d},
653
+ first,
654
+ second,
655
+ }
656
+ })()`});m?.ok&&await q("inspect double-tap",{doubleTapAtCoords:{x:t,y:n,gapMs:d}},`double-tap @${t},${n}`),console.log(JSON.stringify(m,null,2));break}case"long-press":{let t=Number(l[1]),n=Number(l[2]),r=we(e),i=null;if(r){let y=await Oe(u,r);y||(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),t=y.x,n=y.y,i={id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}let d=r?l[1]:l[3],m=d?Number(d):600;(!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(m))&&(console.error(I("long-press","<x> <y> [durationMs] | --testid <id>")),process.exit(1));let g=Math.max(0,Math.round(m)),b=await u.send({type:"longPress",x:t,y:n,durationMs:g,target:i});b?.ok&&await q("inspect long-press",{tapAtCoords:{x:t,y:n}},`long-press @${t},${n}`),console.log(JSON.stringify(b,null,2));break}case"touch":{let t=l[1],n=Number(l[2]),r=Number(l[3]),i=l[4]?Number(l[4]):999,d=t==="down"?"touchDown":t==="move"?"touchMove":t==="up"?"touchUp":t==="cancel"?"touchCancel":null;d||(console.error(I("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),t!=="cancel"&&(!Number.isFinite(n)||!Number.isFinite(r))&&(console.error(I("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let m=t==="down"?"tap":t==="move"?"move":null,g=m&&Number.isFinite(n)&&Number.isFinite(r)?`window.dispatchEvent(new CustomEvent('sootsim:agentAction', { detail: { type: '${m}', x: ${n}, y: ${r} } }));`:"",b=await u.send({type:"evaluate",code:`(async () => {
657
+ ${g}
658
+ const interact = window.__sootsimInteract
659
+ if (!interact?.${d}) return { ok: false, reason: 'no interact.${d}' }
660
+ const value = ${t==="cancel"?`await interact.${d}(${Math.max(1,Math.round(i))})`:`await interact.${d}(${n}, ${r}, ${Math.max(1,Math.round(i))})`}
661
+ return { ok: !!value, value }
662
+ })()`});b?.ok&&t!=="cancel"&&await q("inspect touch",{tapAtCoords:{x:n,y:r}},`touch ${t} @${n},${r}`),console.log(JSON.stringify(b,null,2));break}case"gesture":{let t=["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=l[1],r=l[2]?Number(l[2]):220;(!n||!Number.isFinite(r))&&(console.error(I("gesture","<preset> [durationMs]")),console.error(` presets: ${t.join(", ")}`),process.exit(1)),t.includes(n)||(console.error(` unknown gesture preset: ${n}`),console.error(` presets: ${t.join(", ")}`),process.exit(1));let i=await u.send({type:"evaluate",code:`(async () => {
663
+ const spec = globalThis.__sootsimDeviceSpec || {}
664
+ return {
665
+ width: spec.width || window.innerWidth || 393,
666
+ height: spec.height || window.innerHeight || 852,
667
+ statusBarHeight: spec.statusBarHeight || 0,
668
+ homeIndicatorHeight: spec.homeIndicatorHeight || 0,
669
+ }
670
+ })()`}),d=Number(i?.width)||393,m=Number(i?.height)||852,g=Number(i?.statusBarHeight)||0,b=Number(i?.homeIndicatorHeight)||0,y=Math.round(d/2),$=Math.round(m/2),W=Math.max(24,g+18),X=Math.max(24,b+18),G=18,z=Math.min(220,Math.round(m*.24)),R=Math.min(180,Math.round(d*.32)),w=y,k=$,T=y,ne=$;switch(n){case"scroll-up":k=$+Math.round(z/2),ne=$-Math.round(z/2);break;case"scroll-down":k=$-Math.round(z/2),ne=$+Math.round(z/2);break;case"scroll-left":w=y+Math.round(R/2),T=y-Math.round(R/2);break;case"scroll-right":w=y-Math.round(R/2),T=y+Math.round(R/2);break;case"swipe-from-left-edge":w=G,k=$,T=Math.min(d-G,G+R);break;case"swipe-from-right-edge":w=d-G,k=$,T=Math.max(G,d-G-R);break;case"swipe-from-top-edge":w=y,k=W,ne=Math.min(m-X,W+z);break;case"swipe-from-bottom-edge":w=y,k=m-X,ne=Math.max(W,m-X-z);break}let Y=Math.max(8,Math.round(r/16)),B=Math.max(1,Math.round(r/Y)),Se=await u.send({type:"evaluate",code:`(async () => {
671
+ const interact = window.__sootsimInteract
672
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
673
+ const value = await interact.drag(${w}, ${k}, ${T}, ${ne}, ${Y}, ${B})
674
+ return { ok: !!value, value }
675
+ })()`});Se?.ok&&await q("inspect gesture",{swipe:{start:`${w}, ${k}`,end:`${T}, ${ne}`,duration:Math.max(1,Math.round(r))}},`gesture ${n}`),console.log(JSON.stringify({preset:n,from:{x:w,y:k},to:{x:T,y:ne},result:Se},null,2));break}case"scroll":{let t=we(e),n=ks(e),r=t?.mode==="testid"?t.value:n==null?l[1]:null,i=t||n!=null?1:2,d=Number(l[i]),m=Number(l[i+1]);(!r&&n==null||!Number.isFinite(d)||!Number.isFinite(m))&&(console.error(I("scroll","<id> <x> <y> | --testid <id> <x> <y> | --node-id <nodeId> <x> <y>")),process.exit(1));let g=await u.send({type:"evaluate",code:`(async () => {
676
+ const t = window.__sootsimTest
677
+ if (!t) return null
678
+ const n = ${n!=null?`await t.inspectByNodeId(${JSON.stringify(n)})`:`await t.findByTestId(${JSON.stringify(r)})
679
+ || await t.findById(${JSON.stringify(r)})`}
680
+ if (!n || !n.absolutePosition || !n.layout) return null
681
+ return {
682
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
683
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
684
+ }
685
+ })()`}),b=await V(u,"scrollTo",n!=null?{nodeId:n}:r,d,m,!1);if(b?.ok){let y=n!=null?`node ${n}`:`#${r}`;await q("inspect scroll",{scrollTo:{...n!=null?{nodeId:n}:{id:r},x:d,y:m}},`scroll ${y} -> ${d},${m}`)}console.log(JSON.stringify({...b,...g?{at:{x:g.cx,y:g.cy}}:{}},null,2));break}case"state":{let t=l[1];if(s==="get"&&!t){let r=await V(u,"getRuntimeState"),i=await u.send({type:"evaluate",code:ke});if(r&&typeof r=="object"&&r.diagnostics&&(r.diagnostics.errors=i?.errors??0,r.diagnostics.warnings=i?.warnings??0),r&&typeof r=="object"&&r.shell==null)try{let d=await ue(u);d&&(r.shell=d)}catch{}console.log(JSON.stringify(r,null,2));break}if(!t||t==="--help"||t==="-h"){console.log(`
686
+ ${h("state")} \u2014 dump raw runtime state
687
+
688
+ subcommands:
689
+ shell dump shell transition/layout state
690
+ worker dump render-worker host/animation state
691
+ keyboard dump keyboard visibility, mode, and focused input
692
+ ownership dump surface ownership + pointerOnSurface delivery stats
693
+ node <id> dump raw node info by id or testID
694
+ scroll <id> dump scroll metrics and runtime state
695
+ scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
696
+ hit <x> <y> dump the hit-test ancestry at coordinates
697
+ gesture <x> <y> dump gesture routing/debug info at coordinates
698
+ gesture-seam dump shell-hosted gesture recognizer state/events
699
+
700
+ examples:
701
+ ${h("state")} shell
702
+ ${h("state")} worker
703
+ ${h("state")} keyboard
704
+ ${h("state")} ownership
705
+ ${h("state")} node photos
706
+ ${h("state")} scroll feed
707
+ ${h("state")} scroll-hit 360 420
708
+ ${h("state")} hit 200 720
709
+ `);break}let n;switch(t){case"shell":n=await ue(u,500);break;case"worker":n=await _e(u,"__sootsimRenderHost.queryStats");break;case"ownership":n=await u.send({type:"evaluate",code:`(() => {
710
+ const h = window.__sootsimRenderHost
711
+ if (!h || typeof h.getOwnershipSnapshot !== 'function') {
712
+ return { error: 'getOwnershipSnapshot not available' }
713
+ }
714
+ return h.getOwnershipSnapshot()
715
+ })()`});break;case"keyboard":n=await u.send({type:"evaluate",code:`(async () => {
716
+ const kb = window.__sootsimKeyboard
717
+ const test = window.__sootsimTest
718
+ if (!kb) return { error: 'keyboard bridge not available' }
719
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
720
+ const secureTextEntry =
721
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
722
+ const visible = kb.isVisible()
723
+ const mode = kb.getMode()
724
+ let focused = null
725
+ if (test && typeof test.getFocusedNode === 'function') {
726
+ try {
727
+ focused = await test.getFocusedNode()
728
+ } catch {}
729
+ }
730
+ return {
731
+ visible,
732
+ mode,
733
+ layout,
734
+ focusedInput: focused ? {
735
+ nodeId: focused.nodeId ?? null,
736
+ testID: focused.testID || null,
737
+ id: focused.id || null,
738
+ placeholder: focused.placeholder || null,
739
+ secureTextEntry,
740
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
741
+ } : null,
742
+ }
743
+ })()`}),n=Qe(n);break;case"node":{let r=l[2];r||(console.error(` usage: ${h("state")} node <id>`),process.exit(1)),n=await V(u,"findByTestId",r)||await V(u,"findById",r);break}case"scroll":{let r=l[2];r||(console.error(` usage: ${h("state")} scroll <id>`),process.exit(1)),n=await V(u,"getScrollState",r);break}case"scroll-hit":{let r=Number(l[2]),i=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(i))&&(console.error(` usage: ${h("state")} scroll-hit <x> <y>`),process.exit(1)),n=await V(u,"getScrollStateAt",r,i);break}case"hit":{let r=Number(l[2]),i=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(i))&&(console.error(` usage: ${h("state")} hit <x> <y>`),process.exit(1)),n=await V(u,"debugHitAt",r,i);break}case"gesture":{let r=Number(l[2]),i=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(i))&&(console.error(` usage: ${h("state")} gesture <x> <y>`),process.exit(1)),n=await V(u,"debugGestureAt",r,i);break}case"gesture-seam":n=await _e(u,"SootSim.bridges.mainShell.callTestBridge","getShellGestureSeamDebug");break;default:console.error(` unknown state subcommand: ${t}`),process.exit(1)}console.log(JSON.stringify(n,null,2));break}case"shell":{let t=l[1];if(!t||t==="--help"||t==="-h"){console.log(`
744
+ ${h("shell")} \u2014 run built-in shell commands
745
+
746
+ subcommands:
747
+ launch <appId> [waitMs] [--clear-state]
748
+ launch app and wait for settled shell state
749
+ home [waitMs] go home and wait for settled shell state
750
+ switcher [waitMs] open switcher and wait for settled shell state
751
+ open-card <appId> [waitMs]
752
+ open a specific switcher card and wait for app settle
753
+ appearance <light|dark|auto|toggle>
754
+ update simulator appearance
755
+ lock toggle device lock state
756
+ shake trigger the simulator shake gesture
757
+
758
+ examples:
759
+ ${h("shell")} launch photos
760
+ ${h("shell")} launch rn --clear-state
761
+ ${h("shell")} launch photos 1500
762
+ ${h("shell")} home 500
763
+ ${h("shell")} switcher 800
764
+ ${h("shell")} open-card clock 800
765
+ ${h("shell")} appearance dark
766
+ ${h("shell")} lock
767
+ `);break}let n=t==="launch"||t==="open-card"||t==="home"||t==="switcher",r=t==="launch"||t==="open-card"?l[3]:l[2],i=r?Number(r):350;n&&(!Number.isFinite(i)||i<0)&&(console.error(I("shell",t==="launch"||t==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let d=!1,m=!1,g=null,b=e.includes("--clear-state");if(t==="launch"){let y=l[2];y||(console.error(I("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),b&&await u.send({type:"evaluate",code:qe(!0)}),d=!!await ge(u,"launchApp",i,y),{settled:m,state:g}=await Ee(u,Math.round(i),$=>!!$&&$.state==="app"&&$.activeApp===y&&$.showSwitcher===!1&&$.switcherPhase==="idle"&&typeof $.launchProgress=="number"&&$.launchProgress>=.98),d&&await q("inspect shell launch",b?{launchApp:{clearState:!0}}:{launchApp:{}},b?"launch app (clear state)":"launch app")}else if(t==="home")d=!!await ge(u,"goHome",i),{settled:m,state:g}=await Ee(u,Math.round(i),y=>!!y&&y.state==="home"&&y.activeApp==null&&y.showSwitcher===!1&&y.switcherPhase==="idle"&&typeof y.launchProgress=="number"&&y.launchProgress>=.98);else if(t==="switcher")d=!!await ge(u,"openSwitcher",i),{settled:m,state:g}=await Ee(u,Math.round(i),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(ws),g=await ue(u));else if(t==="open-card"){let y=l[2];y||(console.error(I("shell","open-card <appId> [settleMs]")),process.exit(1)),d=!!await ge(u,"openSwitcherCard",i,y),{settled:m,state:g}=await Ee(u,Math.round(i),$=>!!$&&$.state==="app"&&$.activeApp===y&&$.showSwitcher===!1&&$.switcherPhase==="idle"&&typeof $.zoomLevel=="number"&&$.zoomLevel>=.98&&typeof $.horizontalZoom=="number"&&$.horizontalZoom>=.98),d&&await q("inspect shell open-card",{openSwitcherCard:{appId:y}},`open switcher card ${y}`)}else if(t==="appearance"){let y=l[2];(!y||!["light","dark","auto","toggle"].includes(y))&&(console.error(I("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let $=await So(u,"appearance",y);if(d=!!$?.ok,g={appearance:$},d){let W=$?.applied??y;console.log(` appearance: ${W}`)}}else if(t==="lock"||t==="shake"){let y=await So(u,t);d=!!y?.ok,g={[t]:y}}else console.error(` unknown shell subcommand: ${t}`),process.exit(1);console.log(JSON.stringify({ok:d,settled:m,state:g},null,2));break}case"url":{await ao(u,{args:a});break}case"reload":{let r=!1,i=!1;try{await u.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let g=await u.send({type:"evaluate",code:`;(async () => {
768
+ // in-place guest reload is only valid while the page still runs
769
+ // the engine build the server would serve NOW. the shell dev
770
+ // server has no HMR client, so a long-lived sim tab otherwise
771
+ // keeps a stale engine forever while builds churn underneath it.
772
+ // compare the inlined engine manifest against a fresh fetch of
773
+ // this page's html; any drift means the whole page must reload.
774
+ let engineStale = false
775
+ try {
776
+ const loaded = document.getElementById('__sootsim-engine-manifest')?.textContent
777
+ if (loaded) {
778
+ const res = await fetch(location.href, { cache: 'no-store' })
779
+ const html = await res.text()
780
+ const m = html.match(/<script[^>]*id="__sootsim-engine-manifest"[^>]*>([^<]*)<\\/script>/)
781
+ if (m && m[1] !== loaded) engineStale = true
782
+ }
783
+ } catch {}
784
+ const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
785
+ if (!engineStale && typeof reloadExternalApp === 'function') {
786
+ reloadExternalApp()
787
+ return { kind: 'external-app' }
788
+ }
789
+ window.location.reload()
790
+ return { kind: 'page', engineStale }
791
+ })()`});i=!!g&&g.kind==="external-app",r=!0,g&&g.engineStale&&console.log(" engine build changed since page load \u2014 full page reload")}catch{}console.log(" reloading...");let d=u,m=null;if(i)m=await Te(u,{timeoutMs:1e4,errorGraceMs:3e3});else{r&&await oe(300);let b=await Ft(F,M,N,{timeoutMs:3e4,simIdSource:L});b?(d=b,m=await Te(b,{timeoutMs:3e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 30000ms"),d=null)}if(m)if(m.ready){let g=m.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${m.elapsedMs}ms: ${m.nodes} nodes${g}`)}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 g=yo(m);console.log(` \u26A0 reload timed out after ${m.elapsedMs}ms \u2014 ${g} (nodes: ${m.nodes}, targets: ${m.targets}, errors: ${m.errors})`)}if(d)try{let g=await fe(d,10);if(d!==u&&d.close(),Array.isArray(g)&&g.length>0){console.log(`
792
+ \u26A0 ${g.length} error(s) during mount:
793
+ `);for(let b of g){let y=b.args.map($=>typeof $=="object"?JSON.stringify($):$).join(" ");if(console.log(` ${y}`),b.stack){let $=b.stack.split(`
794
+ `).slice(0,2);for(let W of $)console.log(` ${W.trim()}`)}}}}catch{}m&&!m.ready&&(process.exitCode=1);break}case"storage-clear":{if(await Le(u),await u.send({type:"evaluate",code:qe(!0)})!==!0){P(a)?D({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 i=await Te(u,{timeoutMs:1e4,errorGraceMs:3e3});if(P(a)){D({cleared:!0,ready:i.ready,reload:i}),i.ready||(process.exitCode=1);break}if(i.ready){let d=i.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` cleared tenant storage; ready in ${i.elapsedMs}ms: ${i.nodes} nodes${d}`)}else if(i.source==="error-bail")console.log(` \u26A0 storage clear reloaded but bailed after ${i.elapsedMs}ms: ${i.errors} console error(s), ready signal never fired`);else{let d=yo(i);console.log(` \u26A0 storage clear reloaded but timed out after ${i.elapsedMs}ms \u2014 ${d} (nodes: ${i.nodes}, targets: ${i.targets}, errors: ${i.errors})`)}try{let d=await fe(u,10);if(Array.isArray(d)&&d.length>0){console.log(`
795
+ \u26A0 ${d.length} error(s) during mount:
796
+ `);for(let m of d){let g=m.args.map(b=>typeof b=="object"?JSON.stringify(b):b).join(" ");if(console.log(` ${g}`),m.stack){let b=m.stack.split(`
797
+ `).slice(0,2);for(let y of b)console.log(` ${y.trim()}`)}}}}catch{}i.ready||(process.exitCode=1);break}case"eval":case"js":{let t=l.slice(1).join(" ");t||(console.error(I("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(` ${h("js")} SootSim.bridges.test.findByText("Sign in")`),console.error(` ${h("js")} SootSim.bridges.debug.snapshot("before")`),console.error(` ${h("js")} SootSim.bridges.keyboard.type("hello")`),console.error(` ${h("js")} SootSim.state.root.children.length`),process.exit(1));let n=t;n.startsWith("(async")||(n=`(async () => ${n})()`);let r=await u.send({type:"evaluate",code:n});console.log(JSON.stringify(r,null,2));let i=t.toLowerCase(),d=[];(i.includes("sootsim:gohome")||i.includes("gohome"))&&d.push("sootsim shell home"),(i.includes("sootsim:appswitcher")||i.includes("appswitcher"))&&d.push("sootsim shell switcher"),(i.includes("keyboard.isvisible")||i.includes("keyboard.getmode"))&&d.push("sootsim debug state keyboard"),i.includes("interact.tap")&&d.push("sootsim do tap <x> <y>"),i.includes("keyboard.type")&&d.push("sootsim do type <text>"),(i.includes("keyboard.press")||i.includes("keyboard.dispatchkey"))&&d.push("sootsim do key <name>"),i.includes("keyboard.dismiss")&&d.push("sootsim do dismiss"),i.includes("dumptree")&&d.push("sootsim get tree"),i.includes("dumpaccessibilitytree")&&d.push("sootsim get a11y"),i.includes("getnodecount")&&d.push("sootsim get count"),i.includes("findbytext")&&d.push("sootsim find <text>"),(i.includes("findbytestid")||i.includes("findbyid"))&&d.push("sootsim find --testid <id>"),i.includes("document.hidden")&&d.push("sootsim debug state keyboard (includes tab health)"),d.length>0&&Q("prefer-cli-over-eval",d);break}case"globals":{let t=await u.send({type:"evaluate",code:`(async () => {
798
+ const globals = {}
799
+
800
+ // test bridge (proxy in worker mode)
801
+ const testMethods = [
802
+ 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
803
+ 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
804
+ 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
805
+ 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
806
+ 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
807
+ 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
808
+ 'debugGestureAt'
809
+ ]
810
+ globals['test (\u2192 __sootsimTest)'] = testMethods
811
+
812
+ // debug
813
+ if (window.__sootsimDebug) {
814
+ globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
815
+ }
816
+
817
+ // interact
818
+ if (window.__sootsimInteract) {
819
+ globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
820
+ }
821
+
822
+ // keyboard
823
+ if (window.__sootsimKeyboard) {
824
+ globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
825
+ }
826
+
827
+ // other globals
828
+ globals['other'] = [
829
+ 'root (\u2192 __sootsimRoot) - live node tree',
830
+ 'render() (\u2192 __sootsimForceRender) - force re-render'
831
+ ]
832
+
833
+ return globals
834
+ })()`});console.log(` sootsim JS API:
835
+ `);for(let[n,r]of Object.entries(t)){console.log(` ${n}:`);for(let i of r)console.log(` .${i}`);console.log("")}console.log(` use: ${h("js")} <expression>`),console.log(` example: ${h("js")} test.findByText("Sign in")`);break}case"describe":{await Yt({bridge:u,args:e,positional:l});break}case"perf":{f==="debug"&&!o.internalShellPerf&&(console.error(" `sootsim debug perf` was removed. use `sootsim perf shell ...`."),process.exit(1));let t=l[1];if(!t||t==="--help"||t==="-h"){console.log(`
836
+ ${h("perf")} \u2014 shell frame profiling (the worker that paints)
837
+
838
+ records per-painted-frame timing in the shell worker \u2014 the surface that
839
+ actually draws the app's pixels \u2014 merged with render-profile counters
840
+ (node visits, boundary records/replays, raster tier, blur ms, draw calls).
841
+
842
+ subcommands:
843
+ start begin recording (clears prior frames + counters)
844
+ stop stop recording and report results
845
+ transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
846
+
847
+ stop and transition accept --json for the full machine-readable payload.
848
+
849
+ examples:
850
+ ${h("perf")} start
851
+ # ... interact with the app ...
852
+ ${h("perf")} stop
853
+ ${h("perf")} stop --json
854
+ ${h("perf")} transition goHome
855
+ `);break}switch(t){case"start":{let n=await u.send({type:"evaluate",code:`(() => {
856
+ if (!window.__sootsimShellPerf) {
857
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
858
+ }
859
+ window.__sootsimShellPerf.start()
860
+ return { started: true }
861
+ })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1)),console.log(` shell profiling started \u2014 interact with the app, then run '${h("perf")} stop'`);break}case"stop":{let n=await u.send({type:"evaluate",code:`(async () => {
862
+ if (!window.__sootsimShellPerf) {
863
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
864
+ }
865
+ return await window.__sootsimShellPerf.stop()
866
+ })()`});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)),P(a)){D(n);break}$o(n);break}case"transition":{let n=l[2];if(!n||!["goHome","appSwitcher","lockScreen"].includes(n)){console.log(`
867
+ ${h("perf")} transition <event> \u2014 profile a shell transition
868
+
869
+ events:
870
+ goHome swipe-to-home animation
871
+ appSwitcher app switcher card animation
872
+ lockScreen lock screen transition
873
+
874
+ note: uses 600ms capture window \u2014 may need --timeout 10000 flag
875
+
876
+ examples:
877
+ ${h("perf")} transition goHome --timeout 10000
878
+ ${h("perf")} transition appSwitcher
879
+ `);break}let i=`sootsim:${n}`;Ie(` profiling ${n} transition...`),Ie(" (use --timeout 10000 if this times out)");let d=await u.send({type:"evaluate",code:`(async () => {
880
+ if (!window.__sootsimShellPerf) {
881
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
882
+ }
883
+ window.__sootsimShellPerf.start()
884
+ // give a frame for profiling to engage before the event
885
+ await new Promise(r => requestAnimationFrame(() => r(undefined)))
886
+ window.dispatchEvent(new Event('${i}'))
887
+ // shell animations are ~300-500ms; fixed timing avoids complex
888
+ // animation-end detection
889
+ await new Promise(r => setTimeout(r, 600))
890
+ return await window.__sootsimShellPerf.stop()
891
+ })()`});if(d?.error&&(console.error(` error: ${d.error}`),process.exit(1)),P(a)){D(d);break}Ie(` ${n} transition profiled:`),$o(d);break}default:console.error(` unknown perf subcommand: ${t}`),console.error(" valid: start, stop, transition"),/^--?reset$/.test(t)&&console.error(" note: 'perf start' already clears prior frames \u2014 no reset needed"),(t==="stats"||t==="frames"||t==="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 t=l[1];if(t==="clear"){await Le(u),P(a)?D({cleared:!0}):console.log(" error buffer cleared");break}let n=t?Number(t):20,r=await fe(u,n);if(P(a)){D(r);break}if(r.length===0){console.log(" no errors captured");break}console.log(` ${r.length} error(s):
892
+ `);for(let i of r){let d=ie(i.timestamp),m=i.args.map(g=>typeof g=="object"?JSON.stringify(g):g).join(" ");if(console.log(` [${d}] ${m}`),i.stack){let g=i.stack.split(`
893
+ `).slice(0,3);for(let b of g)console.log(` ${b.trim()}`)}}break}case"warnings":{let t=l[1]?Number(l[1]):20,n=await gt(u,t);if(P(a)){D(n);break}if(n.length===0){console.log(" no warnings captured");break}console.log(` ${n.length} warning(s):
894
+ `);for(let r of n){let i=ie(r.timestamp),d=r.args.map(m=>typeof m=="object"?JSON.stringify(m):m).join(" ");console.log(` [${i}] ${d}`)}break}case"animations":{let t=await V(u,"listAnimations")??[];if(e.includes("--json")){console.log(JSON.stringify(t,null,2));break}if(t.length===0){console.log(" no active animations");break}console.log(` ${t.length} active animation(s):
895
+ `);for(let n of t){let r=String(n.kind).padEnd(6),i=`${Number(n.from).toFixed(2)}\u2192${Number(n.to).toFixed(2)}`,d=Number(n.current??0).toFixed(2),m=`${Math.round((n.progress??0)*100)}%`,g=`${Math.round(n.elapsedMs??0)}ms`,b=n.loop?" loop":"",y=n.layoutBound?" layout":"";console.log(` #${n.id} ${r} ${i.padEnd(14)} cur=${d.padEnd(7)} ${m.padStart(4)} ${g}${b}${y}`)}break}case"animation":{let t=l[1];(!t||t==="--help"||t==="-h")&&(console.error(` usage: ${h("animation")} <id>`),process.exit(1));let n=Number(t);Number.isFinite(n)||(console.error(` invalid id: ${t}`),process.exit(1));let r=await V(u,"getAnimation",n);console.log(JSON.stringify(r,null,2));break}case"stop-animation":{let t=l[1];(!t||t==="--help"||t==="-h")&&(console.error(` usage: ${h("stop-animation")} <id|all>`),process.exit(1));let n=t==="all"?"all":Number(t);n!=="all"&&!Number.isFinite(n)&&(console.error(` invalid id: ${t}`),process.exit(1));let r=await V(u,"stopAnimation",n);console.log(` stopped ${r??0} animation(s)`);break}case"requests":{let t=l[1];if(t==="clear"){await ht(u),P(a)?D({cleared:!0}):console.log(" request buffer cleared");break}let n=t==="all",r=n?l[2]:t,i=r?Number(r):20,d=await yt(u,{failed:!n,limit:i});if(P(a)){D(d);break}if(d.length===0){console.log(n?" no requests captured":" no failed requests captured");break}console.log(` ${d.length} ${n?"request(s)":"failed request(s)"}:
896
+ `);for(let m of d){let g=ie(m.timestamp);console.log(` [${g}] ${U(m)}`),m.responseBody?console.log(` ${m.responseBody}`):m.error&&console.log(` ${m.error}`)}break}case"network":{let t=l[1],n=null,r=null,i=!1,d=!1,m=1e3,g=!1,b=!1;for(let R=0;R<a.length;R++){let w=a[R];if(w==="--filter")n=a[R+1]??null,R++;else if(w==="--limit"){let k=Number(a[R+1]);Number.isFinite(k)&&(r=k),R++}else if(w==="--threshold"){let k=Number(a[R+1]);Number.isFinite(k)&&k>0&&(m=k),R++}else w==="--failed"?i=!0:w==="--slow"?d=!0:w==="--tail"||w==="-f"?g=!0:w==="--json"&&(b=!0)}if(t==="clear"){await u.send({type:"evaluate",code:'window.__sootsimObservability?.network.clear(); "cleared"'}),console.log(" network buffer cleared");break}if(t==="get"){let R=l[2];R||(console.error(" usage: sootsim network get <id>"),process.exit(1));let w=await u.send({type:"evaluate",code:`(() => {
897
+ const obs = window.__sootsimObservability;
898
+ if (!obs) return null;
899
+ return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(R)}) || null;
900
+ })()`});w||(console.error(` no entry with id ${R}`),process.exit(1)),b?console.log(JSON.stringify(w,null,2)):ys(w);break}let y=r??(g?200:t?Number(t):20);Number.isFinite(y)||(console.error(` invalid limit: ${t} \u2014 \`network\` takes a numeric count (e.g. ${h("network")} 100).
901
+ to target a specific sim, use \`--sim ${t}\` instead.`),process.exit(1));let $=async()=>{let R=await u.send({type:"evaluate",code:`(() => {
902
+ const obs = window.__sootsimObservability;
903
+ if (!obs) return { ok: false };
904
+ return { ok: true, entries: obs.network.getSnapshot() };
905
+ })()`});if(!R||!R.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return R.entries??[]},W=R=>{let w=R;if(i&&(w=w.filter(k=>!!k.error||k.status!=null&&k.status>=400)),d&&(w=w.filter(k=>k.durationMs!=null&&k.durationMs>=m)),n){let k=n.toLowerCase();w=w.filter(T=>(T.displayUrl||T.url).toLowerCase().includes(k))}return d&&!g&&(w=[...w].sort((k,T)=>(T.durationMs??0)-(k.durationMs??0))),w};if(!g){let R=await $(),w=W(R).slice(-y);if(b){console.log(JSON.stringify(w,null,2));break}if(w.length===0){R.length===0?console.log(" no network requests captured"):console.log(d?` no requests slower than ${m}ms (${R.length} total \u2014 try --threshold <ms>)`:" no matching requests");break}console.log(d?` ${w.length} request(s) slower than ${m}ms (sorted by duration desc):
906
+ `:` ${w.length} request(s):
907
+ `);for(let k of w)ho(k);break}console.log(` tailing network (ctrl-c to stop)...
908
+ `);let X=new Set,G=!0,z=()=>{G=!1};process.on("SIGINT",z);try{for(;G;){let R=await $(),w=W(R);for(let k of w)k.durationMs!=null&&(X.has(k.id)||(X.add(k.id),b?console.log(JSON.stringify(k)):ho(k)));await oe(250)}}finally{process.off("SIGINT",z)}break}case"logs":{let t=l[1],n=null,r=null,i=null,d=!1,m=!1,g=!1;for(let w=0;w<a.length;w++){let k=a[w];if(k==="--filter")n=a[w+1]??null,w++;else if(k==="--limit"){let T=Number(a[w+1]);Number.isFinite(T)&&(r=T),w++}else k==="--level"?(i=a[w+1]??null,w++):k==="--tail"||k==="-f"?d=!0:k==="--json"?m=!0:(k==="--internal"||k==="--all")&&(g=!0)}let b=i?new Set(i.split(",").map(w=>w.trim()).filter(w=>w==="log"||w==="info"||w==="warn"||w==="error"||w==="debug")):null;if(t==="clear"){await wt(u),console.log(" log buffer cleared");break}let y=!m&&process.stdout.isTTY===!0,$=r??(d?500:t?Number(t):50);Number.isFinite($)||(console.error(` invalid limit: ${t} \u2014 \`logs\` takes a numeric count (e.g. ${h("logs")} 100).
909
+ to target a specific sim, use \`--sim ${t}\` instead.`),process.exit(1));let W=()=>bt(u),X=w=>xt(w,{level:b,filter:n,showInternal:g});if(!d){let w=await W(),k=X(w).slice(-$);if(m){console.log(JSON.stringify(k,null,2));break}if(k.length===0){console.log(w.length===0?" no logs captured":" no matching logs");break}console.log(` ${k.length} log(s):
910
+ `);for(let T of k)wo(T,y);break}console.log(` tailing logs (ctrl-c to stop)...
911
+ `);let G=new Set,z=!0,R=()=>{z=!1};process.on("SIGINT",R);try{for(;z;){let w=await W(),k=X(w);for(let T of k)G.has(T.id)||(G.add(T.id),m?console.log(JSON.stringify(T)):wo(T,y));await oe(250)}}finally{process.off("SIGINT",R)}break}default:console.error(` unknown subcommand: ${p}`),process.exit(1)}if(C.has(p)&&!e.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&!await nt(u,p)&&await S(u),x.length>0&&ee(x),!A.has(p)&&!P(a))try{await xe(u)}catch{}}catch(x){let t=x instanceof Error?x.message:String(x);console.error(` ${p??"inspect"} failed: ${t}`);let n=/^no sim connected with id (.+)$/.exec(t),r=/^command timed out after (\d+)s$/.exec(t),i=t.startsWith("sim disconnected:")||t.startsWith("bridge never reconnected")||t.startsWith("could not connect to ws://");if(n)await Et(u,F,n[1]);else if(/^no sim connected$/.test(t))Rt(F);else if(r)if(await ds(u)){let m=p??"describe";process.stderr.write(` the sim is still responsive \u2014 '${m}' just exceeded the ${r[1]}s command budget.
912
+ the screen's node tree is large; narrow the query or raise the budget:
913
+ sootsim ${m} --testid <id> # scope to one subtree
914
+ sootsim find --testid <id> # targeted single-node lookup
915
+ sootsim ${m} --timeout 60000 # raise per-command budget (ms)
916
+ `)}else go();else if(i)go();else{try{await Ot(u)}catch{}try{await te({includeTail:!0})}catch{}try{await K({includeTail:!0})}catch{}}process.exit(1)}finally{u.close()}}export{qe as a,At as b,Ro as c,Ns as d,As as e,Ds as f,Bs as g,Cs as h,se as i,$o as j,Or as k};