rnxsim 0.1.375 → 0.1.377

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 (295) hide show
  1. package/README.md +28 -25
  2. package/cli/app-config.ts +9 -12
  3. package/cli/app-fonts.ts +3 -3
  4. package/cli/app-project.ts +8 -8
  5. package/cli/auth.ts +7 -9
  6. package/cli/bin.ts +16 -31
  7. package/cli/bridge-flow-runner.ts +3 -3
  8. package/cli/browser-backend.ts +44 -0
  9. package/cli/command-contract.ts +221 -0
  10. package/cli/command-registry.ts +291 -0
  11. package/cli/commands/agent-wrapper.ts +2 -2
  12. package/cli/commands/app-fonts.ts +2 -2
  13. package/cli/commands/assert.ts +3 -3
  14. package/cli/commands/auth.ts +1 -1
  15. package/cli/commands/box/cloud-box.ts +1 -1
  16. package/cli/commands/box/plane-share.ts +2 -2
  17. package/cli/commands/box.ts +4 -6
  18. package/cli/commands/compat.ts +1 -1
  19. package/cli/commands/config.ts +2 -2
  20. package/cli/commands/control.ts +42 -28
  21. package/cli/commands/cpu-profile.ts +7 -7
  22. package/cli/commands/daemon-mac-app.ts +7 -7
  23. package/cli/commands/daemon.ts +10 -10
  24. package/cli/commands/debug.ts +11 -11
  25. package/cli/commands/detox.ts +13 -13
  26. package/cli/commands/diagnose.ts +6 -6
  27. package/cli/commands/do-chain.ts +1 -2
  28. package/cli/commands/electron.ts +1 -3
  29. package/cli/commands/film.ts +3 -3
  30. package/cli/commands/flow.ts +43 -43
  31. package/cli/commands/inspect/count.ts +1 -1
  32. package/cli/commands/inspect/describe.ts +1 -1
  33. package/cli/commands/inspect/env.ts +2 -2
  34. package/cli/commands/inspect/get-layout.ts +1 -1
  35. package/cli/commands/inspect/keyboard.ts +1 -1
  36. package/cli/commands/inspect/list.ts +1 -1
  37. package/cli/commands/inspect/memory.ts +1 -1
  38. package/cli/commands/inspect/resolve-target.ts +1 -1
  39. package/cli/commands/inspect/screens.ts +1 -1
  40. package/cli/commands/inspect/tree.ts +1 -1
  41. package/cli/commands/inspect/url.ts +1 -1
  42. package/cli/commands/inspect/wait-event.ts +5 -5
  43. package/cli/commands/inspect.ts +34 -34
  44. package/cli/commands/install-desktop.ts +3 -3
  45. package/cli/commands/login.ts +6 -6
  46. package/cli/commands/maestro-generate.ts +5 -5
  47. package/cli/commands/maestro.ts +5 -5
  48. package/cli/commands/profile.ts +1 -1
  49. package/cli/commands/record.ts +9 -9
  50. package/cli/commands/runtime.ts +18 -18
  51. package/cli/commands/screenshot-command.ts +1 -1
  52. package/cli/commands/screenshot-layers.ts +5 -5
  53. package/cli/commands/screenshot-mode.ts +1 -1
  54. package/cli/commands/screenshot.ts +8 -8
  55. package/cli/commands/screenshots-capture.ts +5 -5
  56. package/cli/commands/serve.ts +3 -3
  57. package/cli/commands/setup.ts +20 -12
  58. package/cli/commands/skills.ts +5 -5
  59. package/cli/commands/slides.ts +1 -1
  60. package/cli/commands/telemetry.ts +1 -1
  61. package/cli/commands/three-mode.ts +1 -1
  62. package/cli/commands/timeline.ts +8 -8
  63. package/cli/commands/upgrade.ts +116 -131
  64. package/cli/commands/upload.ts +12 -12
  65. package/cli/commands/version.ts +7 -7
  66. package/cli/commands/what-happened.ts +9 -9
  67. package/cli/current-sim.ts +3 -3
  68. package/cli/desktop-companion.ts +1 -1
  69. package/cli/drivers/playwright.ts +9 -9
  70. package/cli/drivers/registry.ts +1 -1
  71. package/cli/drivers/types.ts +1 -1
  72. package/cli/flow-file.ts +2 -2
  73. package/cli/flow-session.ts +1 -1
  74. package/cli/help-core.ts +136 -0
  75. package/cli/help.ts +17 -53
  76. package/cli/hints.ts +5 -5
  77. package/cli/inspect-notice-state.ts +1 -1
  78. package/cli/maestro-js.ts +1 -1
  79. package/cli/outbound-endpoints.ts +23 -5
  80. package/cli/parse-args.ts +19 -66
  81. package/cli/recording-access.ts +1 -1
  82. package/cli/registry.ts +1 -0
  83. package/cli/run-registry.ts +1 -1
  84. package/cli/run-rnx-core.ts +148 -0
  85. package/cli/run-rnx.ts +6 -9
  86. package/cli/runtime-notes.ts +3 -3
  87. package/cli/standalone.ts +4 -0
  88. package/cli/ws-bridge.ts +8 -8
  89. package/detox/config-loader.ts +2 -2
  90. package/detox/index.ts +8 -8
  91. package/detox/jest-preset.cjs +1 -1
  92. package/detox/navigation.ts +2 -2
  93. package/dist-lib/agent-daemon-client.cjs +5 -5
  94. package/dist-lib/agent-events.cjs +1 -1
  95. package/dist-lib/agent-identity.cjs +2 -2
  96. package/dist-lib/agent-sessions.cjs +10 -10
  97. package/dist-lib/attached-projects.cjs +6 -6
  98. package/dist-lib/auth/shared-session.cjs +6 -6
  99. package/dist-lib/backend-origin.cjs +1 -1
  100. package/dist-lib/beta.cjs +1 -1
  101. package/dist-lib/beta.mjs +1 -1
  102. package/dist-lib/bridge-constants.cjs +1 -1
  103. package/dist-lib/bridge-contract-input.cjs +1 -1
  104. package/dist-lib/bridge-contract-input.mjs +1 -1
  105. package/dist-lib/bridge-contract.cjs +1 -1
  106. package/dist-lib/bridge-contract.mjs +1 -1
  107. package/dist-lib/cli-constants.cjs +1 -1
  108. package/dist-lib/config.cjs +25 -25
  109. package/dist-lib/detox/index.cjs +9 -9
  110. package/dist-lib/detox/jest-preset.cjs +1 -1
  111. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  112. package/dist-lib/home-paths.cjs +29 -29
  113. package/dist-lib/host/bridge-host.cjs +274 -181
  114. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  115. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  116. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  117. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  118. package/dist-lib/host/websocket-proxy.cjs +1 -1
  119. package/dist-lib/index.cjs +14 -14
  120. package/dist-lib/jump-to-source-babel.cjs +1 -1
  121. package/dist-lib/menu.cjs +1 -1
  122. package/dist-lib/menu.mjs +1 -1
  123. package/dist-lib/metro-production-bundle.cjs +1 -1
  124. package/dist-lib/metro-production-bundle.mjs +1 -1
  125. package/dist-lib/metro.cjs +8 -8
  126. package/dist-lib/profiles.cjs +12 -12
  127. package/dist-lib/public-brand.cjs +1 -1
  128. package/dist-lib/react-native-host-modules.cjs +1 -1
  129. package/dist-lib/react-native-host-modules.mjs +1 -1
  130. package/dist-lib/render-mode.cjs +1 -1
  131. package/dist-lib/scripts/dev-server-scanner.cjs +25 -11
  132. package/dist-lib/sdk.cjs +1 -1
  133. package/dist-lib/sdk.mjs +1 -1
  134. package/dist-lib/skills.cjs +470 -322
  135. package/dist-lib/vite.cjs +9 -9
  136. package/package.json +4 -11
  137. package/scripts/dev-server-scanner.ts +25 -7
  138. package/scripts/optional-demo-registry.ts +1 -1
  139. package/skills/contrast/SKILL.md +3 -3
  140. package/skills/rnx-debug/SKILL.md +1 -1
  141. package/skills/rnx-test/SKILL.md +2 -2
  142. package/src/agent-identity.ts +1 -1
  143. package/src/agent-sessions.ts +7 -5
  144. package/src/cli-version.ts +12 -4
  145. package/src/config.ts +26 -28
  146. package/src/disk-cleanup.ts +11 -11
  147. package/src/home-paths.ts +28 -28
  148. package/src/host/bridge-host.ts +16 -16
  149. package/src/metro-plugin.ts +2 -2
  150. package/src/profiles.ts +2 -2
  151. package/src/runtime-assets.ts +7 -7
  152. package/src/runtime-delivery.ts +13 -13
  153. package/src/screenshots/orchestrate.ts +1 -1
  154. package/src/screenshots/schema.ts +2 -2
  155. package/src/skills/builtin/a11y-review.ts +2 -2
  156. package/src/skills/builtin/compat-check.ts +2 -2
  157. package/src/skills/builtin/maestro-test.ts +2 -2
  158. package/src/skills/builtin/perf-profile.ts +2 -2
  159. package/src/skills/builtin/screenshot-all.ts +2 -2
  160. package/src/skills/builtin/visual-diff.ts +2 -2
  161. package/src/skills/registry.ts +8 -8
  162. package/src/skills/types.ts +1 -1
  163. package/src/vite-plugin-one.ts +3 -3
  164. package/src/vite-plugin.ts +15 -2
  165. package/dist-cli/bin.js +0 -15
  166. package/dist-cli/chunks/agent-JJN7U6FR.js +0 -48
  167. package/dist-cli/chunks/agent-wrapper-AVVUJ3WF.js +0 -17
  168. package/dist-cli/chunks/app-fonts-QJ22CNAZ.js +0 -4
  169. package/dist-cli/chunks/assert-PZZKIY3K.js +0 -49
  170. package/dist-cli/chunks/auth-5AVDJO33.js +0 -12
  171. package/dist-cli/chunks/beta-PFRGP266.js +0 -4
  172. package/dist-cli/chunks/box-ILC2O7ZO.js +0 -1730
  173. package/dist-cli/chunks/camera-J3V62PP7.js +0 -33
  174. package/dist-cli/chunks/chunk-25KRGDZT.js +0 -4
  175. package/dist-cli/chunks/chunk-2BRBFLWA.js +0 -38
  176. package/dist-cli/chunks/chunk-2GXNAZHB.js +0 -74
  177. package/dist-cli/chunks/chunk-2IUMRRYV.js +0 -7
  178. package/dist-cli/chunks/chunk-4ALPWIMP.js +0 -10
  179. package/dist-cli/chunks/chunk-4CEZZKRY.js +0 -4
  180. package/dist-cli/chunks/chunk-4EUKOIAV.js +0 -4
  181. package/dist-cli/chunks/chunk-4IKE4YUS.js +0 -32
  182. package/dist-cli/chunks/chunk-4ZXR2M3D.js +0 -4
  183. package/dist-cli/chunks/chunk-5CGJFU27.js +0 -7
  184. package/dist-cli/chunks/chunk-5HHWECGT.js +0 -4
  185. package/dist-cli/chunks/chunk-5PZVYF42.js +0 -312
  186. package/dist-cli/chunks/chunk-7NCPUZ52.js +0 -27
  187. package/dist-cli/chunks/chunk-7OSIJCBR.js +0 -107
  188. package/dist-cli/chunks/chunk-AQ5TMOAI.js +0 -4
  189. package/dist-cli/chunks/chunk-BQCEI37V.js +0 -5
  190. package/dist-cli/chunks/chunk-C6B5FOP3.js +0 -4
  191. package/dist-cli/chunks/chunk-CCMZSHJB.js +0 -71
  192. package/dist-cli/chunks/chunk-CX7VCKAT.js +0 -14
  193. package/dist-cli/chunks/chunk-DQUPSAHE.js +0 -4
  194. package/dist-cli/chunks/chunk-DSD2UBZI.js +0 -4
  195. package/dist-cli/chunks/chunk-EWPAI4MO.js +0 -7
  196. package/dist-cli/chunks/chunk-EZXV6U2N.js +0 -497
  197. package/dist-cli/chunks/chunk-F5F7FIPM.js +0 -6
  198. package/dist-cli/chunks/chunk-FUTYK55H.js +0 -30
  199. package/dist-cli/chunks/chunk-FW6AN7I2.js +0 -3
  200. package/dist-cli/chunks/chunk-FZDRA7Z4.js +0 -4
  201. package/dist-cli/chunks/chunk-GDLE4NIV.js +0 -4
  202. package/dist-cli/chunks/chunk-GEX7RVHY.js +0 -5
  203. package/dist-cli/chunks/chunk-H4MYYOYJ.js +0 -5
  204. package/dist-cli/chunks/chunk-HEV7BAPE.js +0 -11
  205. package/dist-cli/chunks/chunk-HNDWYCND.js +0 -506
  206. package/dist-cli/chunks/chunk-HNPHODBD.js +0 -4
  207. package/dist-cli/chunks/chunk-HWDVC6YA.js +0 -11
  208. package/dist-cli/chunks/chunk-JOHJZUGG.js +0 -4
  209. package/dist-cli/chunks/chunk-JWUDT4QK.js +0 -5
  210. package/dist-cli/chunks/chunk-K7QQWKGE.js +0 -4
  211. package/dist-cli/chunks/chunk-LAOKTKT4.js +0 -4
  212. package/dist-cli/chunks/chunk-LD7I266X.js +0 -24
  213. package/dist-cli/chunks/chunk-LMHBU5LZ.js +0 -4
  214. package/dist-cli/chunks/chunk-LSOGXSDV.js +0 -535
  215. package/dist-cli/chunks/chunk-MP2GPO4T.js +0 -4
  216. package/dist-cli/chunks/chunk-MXJ2UWRV.js +0 -4
  217. package/dist-cli/chunks/chunk-OJNKRIZF.js +0 -15
  218. package/dist-cli/chunks/chunk-PBOWUNXO.js +0 -4
  219. package/dist-cli/chunks/chunk-PNRJFHX4.js +0 -4
  220. package/dist-cli/chunks/chunk-QJQOK34O.js +0 -28
  221. package/dist-cli/chunks/chunk-RLCQLMFF.js +0 -142
  222. package/dist-cli/chunks/chunk-S65CK3RI.js +0 -9
  223. package/dist-cli/chunks/chunk-SWBUNMQS.js +0 -4
  224. package/dist-cli/chunks/chunk-SXBFGGAM.js +0 -4
  225. package/dist-cli/chunks/chunk-T4ISWS5H.js +0 -4
  226. package/dist-cli/chunks/chunk-TPPVAA7Z.js +0 -5
  227. package/dist-cli/chunks/chunk-USM3P74H.js +0 -4
  228. package/dist-cli/chunks/chunk-V4EJJHF5.js +0 -4
  229. package/dist-cli/chunks/chunk-V7RGRZOL.js +0 -423
  230. package/dist-cli/chunks/chunk-XUBV77WH.js +0 -130
  231. package/dist-cli/chunks/chunk-XYSDYGKC.js +0 -4
  232. package/dist-cli/chunks/chunk-YNHRSDVG.js +0 -5
  233. package/dist-cli/chunks/chunk-YX52RJKO.js +0 -4
  234. package/dist-cli/chunks/chunk-Z5O5H4O7.js +0 -99
  235. package/dist-cli/chunks/chunk-Z6LOIW46.js +0 -7
  236. package/dist-cli/chunks/chunk-ZXFVBYJY.js +0 -5
  237. package/dist-cli/chunks/cleanup-KPUW4SFK.js +0 -25
  238. package/dist-cli/chunks/cli-version-APGT6GAT.js +0 -4
  239. package/dist-cli/chunks/compat-XXRFD2TW.js +0 -23
  240. package/dist-cli/chunks/config-DDMFDQ7F.js +0 -13
  241. package/dist-cli/chunks/connect-IPG47YXM.js +0 -4
  242. package/dist-cli/chunks/control-O22Z3UJ5.js +0 -4
  243. package/dist-cli/chunks/daemon-PADUIMJV.js +0 -4
  244. package/dist-cli/chunks/debug-MYIP46TM.js +0 -200
  245. package/dist-cli/chunks/desktop-ENFFBQAA.js +0 -31
  246. package/dist-cli/chunks/detox-J5WVK6OH.js +0 -52
  247. package/dist-cli/chunks/device-RAVQVL75.js +0 -18
  248. package/dist-cli/chunks/diagnose-PJMPXKJY.js +0 -43
  249. package/dist-cli/chunks/disk-cleanup-YLAY445J.js +0 -4
  250. package/dist-cli/chunks/do-chain-UBE7GIOU.js +0 -5
  251. package/dist-cli/chunks/drivers-ZFNX3T5Z.js +0 -4
  252. package/dist-cli/chunks/env-Y5XJSNRD.js +0 -4
  253. package/dist-cli/chunks/film-W3V6VURB.js +0 -74
  254. package/dist-cli/chunks/flow-VMLI7BYM.js +0 -4
  255. package/dist-cli/chunks/help-PKZCWHJJ.js +0 -4
  256. package/dist-cli/chunks/hidden-runtime-alias-S5DJ7EDF.js +0 -4
  257. package/dist-cli/chunks/home-paths-5O4IZPYV.js +0 -4
  258. package/dist-cli/chunks/inspect-LT4MXK37.js +0 -4
  259. package/dist-cli/chunks/install-desktop-EXCFMXFS.js +0 -4
  260. package/dist-cli/chunks/login-V6TZ54ZH.js +0 -26
  261. package/dist-cli/chunks/logout-SPMLFWYA.js +0 -4
  262. package/dist-cli/chunks/maestro-5ISTBAZE.js +0 -108
  263. package/dist-cli/chunks/maestro-generate-WUI64NHR.js +0 -36
  264. package/dist-cli/chunks/mode-QPNBYXUF.js +0 -26
  265. package/dist-cli/chunks/optional-demo-registry-CBSYF4CG.js +0 -4
  266. package/dist-cli/chunks/perf-T6N5PVYV.js +0 -48
  267. package/dist-cli/chunks/permissions-YZ7RRSZJ.js +0 -13
  268. package/dist-cli/chunks/platform-XDQAA72X.js +0 -6
  269. package/dist-cli/chunks/privacy-54FIGXLT.js +0 -4
  270. package/dist-cli/chunks/record-QGYXRUKP.js +0 -72
  271. package/dist-cli/chunks/report-issue-VUUTGX7V.js +0 -29
  272. package/dist-cli/chunks/reset-CGO52KBW.js +0 -4
  273. package/dist-cli/chunks/resolve-target-NNQCALDM.js +0 -4
  274. package/dist-cli/chunks/runtime-4EP6YJVL.js +0 -4
  275. package/dist-cli/chunks/screenshot-command-NZCMSJ4P.js +0 -159
  276. package/dist-cli/chunks/screenshot-layers-VMTQ6XIU.js +0 -20
  277. package/dist-cli/chunks/screenshots-capture-K3MWIDBK.js +0 -42
  278. package/dist-cli/chunks/serve-QJRIB2BV.js +0 -56
  279. package/dist-cli/chunks/setup-6XXEJQVF.js +0 -4
  280. package/dist-cli/chunks/sim-client-5YUVL45C.js +0 -4
  281. package/dist-cli/chunks/skills-T3CS7CXK.js +0 -50
  282. package/dist-cli/chunks/state-AJC3VK3G.js +0 -14
  283. package/dist-cli/chunks/storage-KVGZKC3Y.js +0 -37
  284. package/dist-cli/chunks/store-AWUMOQUH.js +0 -4
  285. package/dist-cli/chunks/telemetry-W5ZDGWK6.js +0 -4
  286. package/dist-cli/chunks/timeline-DXDCAZUA.js +0 -24
  287. package/dist-cli/chunks/upgrade-SRPTJACU.js +0 -7
  288. package/dist-cli/chunks/upload-ZDV4BFED.js +0 -4
  289. package/dist-cli/chunks/version-SOLPSBMG.js +0 -6
  290. package/dist-cli/chunks/web-RT75LD7A.js +0 -4
  291. package/dist-cli/chunks/welcome-IJ55EC7U.js +0 -5
  292. package/dist-cli/chunks/what-happened-CEIWJIWK.js +0 -25
  293. package/dist-cli/chunks/ws-bridge-YK5R3HOI.js +0 -4
  294. package/scripts/postinstall.cjs +0 -3
  295. package/scripts/preuninstall.cjs +0 -118
@@ -1,535 +0,0 @@
1
- /*! rnx v0.1.375 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as nt}from"./chunk-BQCEI37V.js";import{a as ot}from"./chunk-QJQOK34O.js";import{a as Se,b as ve,c as et,d as xe,e as Te,f as tt,g as rt}from"./chunk-EZXV6U2N.js";import{a as Qe}from"./chunk-RLCQLMFF.js";import{e as it}from"./chunk-Z5O5H4O7.js";import{a as re}from"./chunk-V7RGRZOL.js";import{f as qe,g as Ye,o as ze,q as Xe,u as Ze}from"./chunk-EWPAI4MO.js";import{l as je}from"./chunk-CX7VCKAT.js";import{a as Ke}from"./chunk-Z6LOIW46.js";import{h as Ge,m as Je}from"./chunk-2BRBFLWA.js";import{G as ye,o as We,p as Ve}from"./chunk-5PZVYF42.js";import{b as Ue}from"./chunk-4ZXR2M3D.js";import{a as Le,b as Ne,d as Ce}from"./chunk-H4MYYOYJ.js";import{g as me,h as ge,t as we,u as be,v as He}from"./chunk-7NCPUZ52.js";import{c as E}from"./chunk-T4ISWS5H.js";import{b as kt,d as $t}from"./chunk-DQUPSAHE.js";var dt=kt((fr,lt)=>{"use strict";var J=Object.freeze({channelThreshold:24,contentBandInsetFraction:.08,minimumContentPercent:.005}),Mt=3;function st(i,e){return!i||!e||i.length!==e.length?!1:i.equals(e)}function at(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("proof content measurement requires an input object");let{data:e,width:t,height:r}=i;if(!e||typeof e.length!="number"||!Number.isInteger(t)||!Number.isInteger(r)||t<=0||r<=0||e.length!==t*r*4)throw new Error("proof content measurement needs RGBA pixels and dimensions");let n=Math.floor(r*J.contentBandInsetFraction),o=Math.ceil(r*(1-J.contentBandInsetFraction)),s=new Uint32Array(1024*32),a=0;for(let g=n;g<o;g++)for(let f=0;f<t;f++){let v=(g*t+f)*4,P=e[v]>>3<<10|e[v+1]>>3<<5|e[v+2]>>3;s[P]++,a++}let l=0;for(let g=1;g<s.length;g++)s[g]>s[l]&&(l=g);let u={red:((l>>10&31)<<3)+4,green:((l>>5&31)<<3)+4,blue:((l&31)<<3)+4},h=0;for(let g=n;g<o;g++)for(let f=0;f<t;f++){let v=(g*t+f)*4;Math.max(Math.abs(e[v]-u.red),Math.abs(e[v+1]-u.green),Math.abs(e[v+2]-u.blue))>=J.channelThreshold&&h++}let m=h/a*100;return{contentPercent:m,contentPixels:h,dominant:u,passedMinimum:m>=J.minimumContentPercent,totalPixels:a}}function Rt(i,e){if(!e)return{decision:"continue",content:null};let t=at(e);return t.passedMinimum?i&&st(i,e.data)?{decision:"identical",content:t}:{decision:"changed",content:t}:{decision:"insufficient-content",content:t}}lt.exports={PROOF_CONTENT_DEFINITION:J,REQUIRED_IDENTICAL_PROOF_FRAMES:Mt,framesIdentical:st,measureProofFrameContent:at,settleDecision:Rt}});import*as $ from"fs";import{createHash as tr,randomUUID as rr}from"node:crypto";import{tmpdir as Z}from"os";import*as b from"path";import*as I from"fs";import*as S from"path";var X=$t(dt(),1);var Bt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",ut=1;function Lt(i){let e=Ce(i),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,n=e.width,o=e.height,s=Le(e),a=r?e.width+58:s.frameWidth,l=r?e.height+111+111:s.frameHeight,u=9.5,h=ut,m=a+u*2,g=l+ut*2,f=u+(r?29:s.screenLeft),v=r?111:s.screenTop,P=r?52:s.frameRadius,U=[{side:e.hardwareButtons.lock.side,top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.ringToggle.side,top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeUp.side,top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeDown.side,top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:i,renderScale:t,outerWidth:Math.round(m*t),outerHeight:Math.round(g*t),logicalOuterWidth:m,logicalOuterHeight:g,logicalFrameWidth:a,logicalFrameHeight:l,logicalFrameLeft:u,logicalFrameTop:h,logicalScreenWidth:n,logicalScreenHeight:o,logicalScreenLeft:f,logicalScreenTop:v,logicalScreenRadius:r?0:s.screenRadius,logicalFrameRadius:P,frameBackground:r?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:r?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:r?null:Bt,buttons:U,legacyHomeButton:r?{top:111+e.height+47/2,left:e.width/2-64/2+29,size:64,ring:1.5}:null,showHomeIndicator:e.homeIndicatorHeight>0,logicalHomeIndicatorStripHeight:e.homeIndicatorHeight}}function Nt(i){let e=i.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
5
- <div
6
- aria-hidden="true"
7
- style="
8
- position:absolute;
9
- ${e?`right:-${i.width}px;`:`left:-${i.width}px;`}
10
- top:${i.top}px;
11
- width:${i.width}px;
12
- height:${i.height}px;
13
- background-color:#212121;
14
- border-top-left-radius:${e?0:1.5}px;
15
- border-bottom-left-radius:${e?0:1.5}px;
16
- border-top-right-radius:${e?1.5:0}px;
17
- border-bottom-right-radius:${e?1.5:0}px;
18
- box-shadow:
19
- inset 0 0.5px 0 #616161,
20
- inset 0 -0.5px 0 #3F3F3F,
21
- ${e?"inset -0.5px 0 0 #3F3F3F,":"inset 0.5px 0 0 #3F3F3F,"}
22
- 0 0 0 0.5px #676767,
23
- 0 0 0 1.5px #000;
24
- clip-path:${t};
25
- pointer-events:none;
26
- z-index:2;
27
- "
28
- ></div>
29
- `}function Ct(i,e){let t=i.buttons.map(Nt).join(""),r=i.metallicRingShadow?`
30
- <div
31
- aria-hidden="true"
32
- style="
33
- position:absolute;
34
- inset:0;
35
- border-radius:${i.logicalFrameRadius}px;
36
- box-shadow:${i.metallicRingShadow};
37
- pointer-events:none;
38
- z-index:10;
39
- "
40
- ></div>
41
- `:"",n=i.legacyHomeButton?`
42
- <div
43
- aria-hidden="true"
44
- style="
45
- position:absolute;
46
- top:${i.legacyHomeButton.top}px;
47
- left:${i.legacyHomeButton.left}px;
48
- width:${i.legacyHomeButton.size}px;
49
- height:${i.legacyHomeButton.size}px;
50
- border-radius:50%;
51
- background:
52
- radial-gradient(circle at 35% 32%, rgba(62,64,68,0.35) 0%, rgba(17,18,20,0.98) 72%, rgba(8,9,11,1) 100%);
53
- box-shadow:
54
- inset 0 0 0 1px rgba(255,255,255,0.06),
55
- inset 0 0 0 ${i.legacyHomeButton.ring}px rgba(184,192,204,0.45),
56
- 0 0 0 1px rgba(0,0,0,0.5);
57
- z-index:3;
58
- pointer-events:none;
59
- display:flex;
60
- align-items:center;
61
- justify-content:center;
62
- "
63
- >
64
- <div
65
- style="
66
- width:16px;
67
- height:16px;
68
- border-radius:4px;
69
- box-shadow:inset 0 0 0 1.5px rgba(188,194,202,0.5);
70
- "
71
- ></div>
72
- </div>
73
- `:"",o=i.showHomeIndicator?`
74
- <div
75
- aria-hidden="true"
76
- style="
77
- position:absolute;
78
- left:0;
79
- right:0;
80
- bottom:4px;
81
- height:${i.logicalHomeIndicatorStripHeight}px;
82
- display:flex;
83
- align-items:center;
84
- justify-content:center;
85
- pointer-events:none;
86
- z-index:10;
87
- "
88
- >
89
- <div
90
- style="
91
- width:134px;
92
- height:5px;
93
- border-radius:2.5px;
94
- background-color:rgb(150, 150, 150);
95
- opacity:0.5;
96
- "
97
- ></div>
98
- </div>
99
- `:"";return`<!doctype html>
100
- <html>
101
- <head>
102
- <meta charset="utf-8" />
103
- <style>
104
- html, body {
105
- margin: 0;
106
- width: ${i.outerWidth}px;
107
- height: ${i.outerHeight}px;
108
- background: transparent;
109
- }
110
- body {
111
- overflow: hidden;
112
- }
113
- img {
114
- display: block;
115
- width: 100%;
116
- height: 100%;
117
- }
118
- </style>
119
- </head>
120
- <body>
121
- <div
122
- id="frame-export-root"
123
- style="
124
- position:relative;
125
- width:${i.outerWidth}px;
126
- height:${i.outerHeight}px;
127
- overflow:hidden;
128
- background:transparent;
129
- "
130
- >
131
- <div
132
- id="frame-scale-layer"
133
- style="
134
- position:absolute;
135
- top:0;
136
- left:0;
137
- width:${i.logicalOuterWidth}px;
138
- height:${i.logicalOuterHeight}px;
139
- transform:scale(${i.renderScale});
140
- transform-origin:top left;
141
- overflow:visible;
142
- "
143
- >
144
- <div
145
- id="frame"
146
- style="
147
- position:absolute;
148
- top:${i.logicalFrameTop}px;
149
- left:${i.logicalFrameLeft}px;
150
- width:${i.logicalFrameWidth}px;
151
- height:${i.logicalFrameHeight}px;
152
- border-radius:${i.logicalFrameRadius}px;
153
- box-sizing:border-box;
154
- overflow:visible;
155
- background:${i.frameBackground};
156
- box-shadow:${i.frameOutline};
157
- "
158
- >
159
- ${t}
160
- ${r}
161
- ${n}
162
- <div
163
- id="screen"
164
- style="
165
- position:absolute;
166
- top:${i.logicalScreenTop}px;
167
- left:${i.logicalScreenLeft-i.logicalFrameLeft}px;
168
- width:${i.logicalScreenWidth}px;
169
- height:${i.logicalScreenHeight}px;
170
- border-radius:${i.logicalScreenRadius}px;
171
- overflow:hidden;
172
- background:#000;
173
- "
174
- >
175
- <img src="${e}" alt="" />
176
- ${o}
177
- </div>
178
- </div>
179
- </div>
180
- </div>
181
- </body>
182
- </html>`}async function pt(i,e){let{chromium:t}=await import("playwright"),r=await nt(n=>t.launch(n),{headless:!0});try{let n=await Ht(r);try{return await n.compose(i,e)}finally{await n.close()}}finally{await r.close()}}async function Ht(i){let e=new Map;async function t(r){let n=e.get(r);if(n)return n;let o=Lt(r),s=await i.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),a=await s.newPage(),l={layout:o,context:s,page:a};return e.set(r,l),l}return{async compose(r,n){let o=await t(n),s=`data:image/png;base64,${r.toString("base64")}`;return await o.page.setContent(Ct(o.layout,s),{waitUntil:"load"}),await o.page.waitForTimeout(20),await o.page.screenshot({type:"png",clip:{x:0,y:0,width:o.layout.outerWidth,height:o.layout.outerHeight},omitBackground:!0})},async close(){for(let r of e.values())await r.context.close();e.clear()}}}import{spawnSync as Ut}from"child_process";import*as C from"vm";var jt=3e5,Wt=`
183
- let input = '';
184
- process.stdin.on('data', (c) => { input += c });
185
- process.stdin.on('end', async () => {
186
- try {
187
- const req = JSON.parse(input);
188
- const res = await fetch(req.url, {
189
- method: req.method,
190
- headers: req.headers,
191
- body: req.body === undefined || req.body === null ? undefined : req.body,
192
- });
193
- const body = await res.text();
194
- const headers = {};
195
- for (const [k, v] of res.headers.entries()) {
196
- headers[k] = headers[k] ? headers[k] + ',' + v : v;
197
- }
198
- process.stdout.write(JSON.stringify({ ok: res.ok, status: res.status, body, headers }));
199
- } catch (err) {
200
- process.stdout.write(JSON.stringify({ __error: (err && err.message) || String(err) }));
201
- process.exitCode = 1;
202
- }
203
- });
204
- `;function K(i,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by rnx yet");let r={...process.env};for(let a of Object.keys(r))(a.startsWith("BUN_INSPECT")||a==="NODE_OPTIONS")&&delete r[a];let n=Ut(process.execPath,["-e",Wt],{input:JSON.stringify({url:i,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:jt,maxBuffer:64*1024*1024,env:r});if(n.error)throw new Error(`http ${e} ${i} failed: ${n.error.message}`);let o;try{o=JSON.parse(n.stdout||"")}catch{throw new Error(`http ${e} ${i} failed: no response (${(n.stderr||"").trim().slice(0,200)})`)}let s=o;if(s.__error)throw new Error(`http ${e} ${i} failed: ${s.__error}`);return s}var Vt=/(?<!\\)\$\{([^$]*)\}/g,Gt=/\\(\$\{[^$]*\})/g,Jt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ne=class{context;envBinding=new Map;envScopeStack=[];syncedEnvKeys=new Set;output={};maestro;constructor(e={}){this.maestro={copiedText:null,platform:e.platform??"ios"};let t=e.onLog??(n=>console.log(`[flow] js: ${n}`)),r={output:this.output,maestro:this.maestro,http:{get:(n,o)=>K(n,"GET",o),post:(n,o)=>K(n,"POST",o),put:(n,o)=>K(n,"PUT",o),delete:(n,o)=>K(n,"DELETE",o),request:(n,o)=>K(n,(o?.method??"GET").toUpperCase(),o)},console:{log:(...n)=>t(n.map(o=>typeof o=="string"?o:ht(o)).join(" "))}};this.context=C.createContext(r),C.runInContext(`
205
- globalThis.__maestroScope = new Proxy(globalThis, {
206
- has() { return true },
207
- get(target, key) { return target[key] },
208
- })
209
- function json(text) { return JSON.parse(text) }
210
- function relativePoint(x, y) {
211
- var xPercent = Math.ceil(x * 100) + '%'
212
- var yPercent = Math.ceil(y * 100) + '%'
213
- return xPercent + ',' + yPercent
214
- }
215
- `,this.context);for(let[n,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(n,o)}putEnv(e,t){this.envBinding.set(e,t)}setCopiedText(e){this.maestro.copiedText=e}enterEnvScope(){this.envScopeStack.push(new Map(this.envBinding))}leaveEnvScope(){let e=this.envScopeStack.pop();if(e){this.envBinding.clear();for(let[t,r]of e)this.envBinding.set(t,r)}}evaluate(e,t={}){let r=t.env;if(r&&Object.keys(r).length>0){this.enterEnvScope();try{for(let[n,o]of Object.entries(r))this.envBinding.set(n,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,r]of this.envBinding)try{e[t]=r,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Vt,(r,n)=>{if(n.trim().length===0)return"";let o=this.evaluate(n);if(o===void 0&&Jt.test(n.trim()))throw new Error(`missing variable for flow placeholder: ${n.trim()}`);return ht(o)}).replace(Gt,(r,n)=>n)}interpolateStep(e){return this.interpolateValue(e,null)}interpolateValue(e,t){return typeof e=="string"?t==="evalScript"?e:this.evaluateStringTemplate(e):Array.isArray(e)?t==="commands"||t==="onFlowStart"||t==="onFlowComplete"?e:e.map(r=>this.interpolateValue(r,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,this.interpolateValue(n,r)])):e}};function ht(i){if(i===void 0)return"undefined";if(i===null)return"null";if(typeof i=="object")try{return JSON.stringify(i)}catch{return String(i)}return String(i)}function ft(i){if(i==null)return!1;if(typeof i=="boolean")return i;let e=String(i);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var ie=1e4,Kt=Math.min(10,Math.max(1,Number(process.env.SOOTSIM_FLOW_TIMEOUT_SCALE)||1)),q=i=>Math.round(i*Kt),se=393,H=852;function w(i){return new Promise(e=>setTimeout(e,i))}function Y(i){return!!(i&&typeof i=="object"&&!Array.isArray(i))}function z(i,e){if(!Y(i))return null;let t=i[e];return typeof t=="string"&&t.length>0?t:null}function qt(i,e){return Y(i)?i[e]===!0:!1}function Yt(i){if(!i)return null;let e=i.recentApps;if(Array.isArray(e))for(let r of e){let n=z(r,"id");if(n)return n}let t=i.surfaceBindings;return z(t,"app:one")||z(t,"app:two")||null}function zt(i){return i?S.basename(i)===".maestro"?S.dirname(i):i:process.cwd()}function Xt(i,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(S.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let n=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():zt(t.flowDir);return S.resolve(n,r)}return S.join(i,r)}function Zt(i){if(typeof i=="string")return{path:i,withFrame:!1};let e=i.path?.trim()||i.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:i.withFrame===!0,layers:i.layers}}function oe(i,e){let[t,r]=i.split(",").map(a=>a.trim()),n=(a,l)=>a.endsWith("%")?Number.parseFloat(a)/100*l:Number.parseFloat(a),o=e?.x??0,s=e?.y??0;return{x:o+n(t,e?.width??se),y:s+n(r,e?.height??H)}}function mt(i){switch(i){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[i]:!0}}}function Qt(i){let e=i.split(/^---$/m),t=e.length>1?e[e.length-1]:i,r=Qe.parse(t);return Array.isArray(r)?r:[]}var ae=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new ne({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;appStopped=!1;launchArgumentsActive=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingStartedAtMs=null;lastRecordingDurationMs=null;lastRecordingFrameStats=null;flowTraceSteps=[];lastFailedStep=null;get simId(){return this.opts.simId}async evaluate(e,t){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e},t?{timeoutMs:t}:void 0)}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async perform(e){return this.bridge.send({type:"perform",simId:this.opts.simId,steps:e})}async waitForTree(e=ie){let t=await Ve(this.bridge,q(e));if(!t.ready)throw t.externalError?new Error(`app failed to load: ${t.externalError}`):t.bridgeError?new Error(`target sim is not responding to the bridge (${t.bridgeError}). it is likely a stale orphan; run \`rnx list\`, then close it with \`rnx close <id>\` or start a fresh one with \`rnx open --new <port>\`.`):new Error(`app not ready after ${e}ms: ${We(t)}`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(this.opts.requireRecordingEntitlement&&await ot("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
216
- const rec = window.__sootsimRecorder
217
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
218
- const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
219
- if (rec.state() === 'recording') return { ok: true, format }
220
- return rec.start({ format, fps: 24 })
221
- })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let r=e[t];if(typeof r=="string")return r.slice(0,80);if(typeof r=="number"||typeof r=="boolean")return String(r);if(!r||typeof r!="object")return;let n=r,o=n.id??n.text??n.name??n.path;if(typeof o=="string"&&o)return o.slice(0,80);let s=n.visible??n.notVisible;if(typeof s=="string"&&s)return s.slice(0,80);if(s&&typeof s=="object"){let a=s,l=a.id??a.text;if(typeof l=="string"&&l)return l.slice(0,80)}if(n.point&&typeof n.point=="string")return n.point.slice(0,80);if(typeof n.x=="number"&&typeof n.y=="number")return`${Math.round(n.x)}, ${Math.round(n.y)}`}recordFlowTraceStep(e){let t=Date.now(),r={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(r.error=e.error instanceof Error?e.error.message:String(e.error)),e.screenshotPath&&(r.screenshotPath=e.screenshotPath),this.flowTraceSteps.push(r)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let r=[],n=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${n}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),n=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");I.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",a=S.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${s}`);return I.writeFileSync(a,Buffer.concat(r)),a}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await w(t);return}let r=await re({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(r.settled?` [flow] recording tail settled in ${r.elapsed}ms`:` [flow] recording tail reached ${r.elapsed}ms budget`)}async findElement(e){if(e.childOf!=null||typeof e.index=="number")return this.findElementScoped(e);let t=!!e.text&&/[.*+?^$()[\]{}|\\]/.test(e.text);return this.evaluate(`(async () => {
222
- const test = window.__sootsimTest
223
- if (!test) return null
224
- let node = null
225
- if (${JSON.stringify(!!e.text)}) {
226
- node = await test.findByText(${JSON.stringify(e.text||"")})
227
- // maestro matches a text selector against the element's ACCESSIBILITY
228
- // text too, not just rendered glyphs \u2014 icon-only buttons (e.g. bluesky's
229
- // "Pin to Home" / "Mute accounts" pin/menu controls) carry the label on
230
- // accessibilityLabel with no visible text node, so findByText misses
231
- // them. fall back to an exact a11y-label match, mirroring the real
232
- // driver. findByLabel resolves a node, but its info shape omits nodeId/
233
- // isTextInput; re-resolve through findByTestId/findById when it exposes
234
- // an id so tapOn still gets a resolveTapTarget-able nodeId.
235
- if (!node) {
236
- const labelled = await test.findByLabel?.(${JSON.stringify(e.text||"")})
237
- if (labelled) {
238
- const reId = labelled.testID || labelled.id
239
- node =
240
- (reId &&
241
- ((await test.findByTestId?.(reId)) || (await test.findById?.(reId)))) ||
242
- labelled
243
- }
244
- }
245
- if (!node && ${JSON.stringify(t)} && test.queryAll) {
246
- // regex selector fallback: match the pattern against each visible
247
- // node's text; prefer the narrowest matching node so a tight <text>
248
- // wins over a wide container that merely contains it.
249
- let re = null
250
- try { re = new RegExp(${JSON.stringify(e.text||"")}) } catch (e) { re = null }
251
- if (re) {
252
- const all = (await test.queryAll({ pruneHidden: true })) || []
253
- const hits = all.filter(
254
- (n) =>
255
- n && n.absolutePosition && n.layout &&
256
- typeof n.text === 'string' && re.test(n.text),
257
- )
258
- hits.sort((a, b) => (a.text || '').length - (b.text || '').length)
259
- if (hits[0]) node = hits[0]
260
- }
261
- }
262
- }
263
- if (!node && ${JSON.stringify(!!e.id)}) {
264
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
265
- }
266
- if (!node || !node.absolutePosition || !node.layout) return null
267
- return {
268
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
269
- id: node.id || null,
270
- testID: node.testID || null,
271
- text: node.text || null,
272
- absolutePosition: node.absolutePosition,
273
- layout: node.layout,
274
- isTextInput: !!node.isTextInput,
275
- }
276
- })()`)}async findElementScoped(e){let t=typeof e.index=="number"?e.index:0;return this.evaluate(`(async () => {
277
- const test = window.__sootsimTest
278
- if (!test || !test.queryAll) return null
279
- // NOT pruneHidden: that over-filters (it dropped every postDropdownBtn in a
280
- // feed and made index:0 resolve to nothing \u2014 worse than findByTestId). reach
281
- // for the same set findByTestId sees, then PREFER on-screen ones below.
282
- const filter = {}
283
- if (${JSON.stringify(!!e.id)}) filter.hasId = ${JSON.stringify(e.id||"")}
284
- if (${JSON.stringify(!!e.text)}) filter.hasText = ${JSON.stringify(e.text||"")}
285
- let candidates = (await test.queryAll(filter)) || []
286
- // a11y-label fallback (icon-only buttons) for text matchers, mirroring
287
- // findElement's simple path.
288
- if (${JSON.stringify(!!e.text)} && candidates.length === 0) {
289
- const all = (await test.queryAll({})) || []
290
- candidates = all.filter((n) => (n.accessibilityLabel || '') === ${JSON.stringify(e.text||"")})
291
- }
292
- candidates = candidates.filter((n) => n && n.absolutePosition && n.layout)
293
- // prefer on-screen matches (findByTestId's visible-first behavior); only
294
- // fall back to off-screen ones when nothing is on-screen, so index: still
295
- // resolves a target that needs scrolling into view.
296
- const onScreen = candidates.filter((n) => {
297
- const cy = n.absolutePosition.y + n.layout.height / 2
298
- return cy > 0 && cy < ${H}
299
- })
300
- if (onScreen.length > 0) candidates = onScreen
301
- ${e.childOf?`
302
- const container = ${e.childOf.id?`(await test.findByTestId(${JSON.stringify(e.childOf.id)})) || (await test.findById(${JSON.stringify(e.childOf.id)}))`:`await test.findByText(${JSON.stringify(e.childOf.text||"")})`}
303
- if (!container || !container.absolutePosition || !container.layout) return null
304
- const x0 = container.absolutePosition.x
305
- const y0 = container.absolutePosition.y
306
- const x1 = x0 + container.layout.width
307
- const y1 = y0 + container.layout.height
308
- candidates = candidates.filter((n) => {
309
- const cx = n.absolutePosition.x + n.layout.width / 2
310
- const cy = n.absolutePosition.y + n.layout.height / 2
311
- return cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1
312
- })`:""}
313
- const node = candidates[${t}]
314
- if (!node) return null
315
- return {
316
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
317
- id: node.id || null,
318
- testID: node.testID || null,
319
- text: node.text || null,
320
- absolutePosition: node.absolutePosition,
321
- layout: node.layout,
322
- isTextInput: !!node.isTextInput,
323
- }
324
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
325
- const test = window.__sootsimTest
326
- if (!test?.resolveTapTarget) return null
327
- return await test.resolveTapTarget(${e})
328
- })()`)}async activatePressTarget(e){let t=e.id?{id:e.id,testID:e.id,text:null}:{id:null,testID:null,text:e.text??null};return this.evaluate(`(async () => {
329
- const test = window.__sootsimTest
330
- if (!test) return null
331
- const node = ${e.id?`(await test.findByTestId?.(${JSON.stringify(e.id)})) || (await test.findById?.(${JSON.stringify(e.id)}))`:`await test.findByText?.(${JSON.stringify(e.text||"")})`}
332
- let point = null
333
- if (node?.absolutePosition && node?.layout) {
334
- point = {
335
- x: node.absolutePosition.x + node.layout.width / 2,
336
- y: node.absolutePosition.y + node.layout.height / 2,
337
- }
338
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
339
- const resolved = await test.resolveTapTarget(node.nodeId)
340
- if (
341
- resolved &&
342
- Number.isFinite(resolved.cx) &&
343
- Number.isFinite(resolved.cy)
344
- ) {
345
- point = { x: resolved.cx, y: resolved.cy }
346
- }
347
- }
348
- }
349
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
350
- if (direct?.ok && point) {
351
- window.dispatchEvent(
352
- new CustomEvent('sootsim:agentAction', {
353
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
354
- }),
355
- )
356
- }
357
- return direct || null
358
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
359
- const test = window.__sootsimTest
360
- if (!test?.activatePressAt) return null
361
- const direct = await test.activatePressAt(${e}, ${t})
362
- if (direct?.ok) {
363
- window.dispatchEvent(
364
- new CustomEvent('sootsim:agentAction', {
365
- detail: { type: 'tap', x: ${e}, y: ${t} },
366
- }),
367
- )
368
- }
369
- return direct
370
- })()`)}async tap(e,t,r){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:r})}async longPress(e,t,r,n){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:r,target:n})}async waitForElement(e,t=5e3){let r=Date.now()+t,n=await this.findElement(e);for(;!n&&Date.now()<r;)await w(150),n=await this.findElement(e);if(!n)return n;let o=Date.now()+1200,s=n;for(;Date.now()<o;){await w(120);let a=await this.findElement(e);if(!a)break;let l=Math.abs(a.absolutePosition.x-s.absolutePosition.x)>.5||Math.abs(a.absolutePosition.y-s.absolutePosition.y)>.5||Math.abs(a.layout.width-s.layout.width)>.5||Math.abs(a.layout.height-s.layout.height)>.5;if(n=a,!l)return n;s=a}return n}replayTargetForElement(e,t,r){return{id:e.id??r?.target?.id??t.id??null,testID:e.id??r?.target?.testID??t.testID??null,text:e.text??r?.target?.text??r?.target?.accessibilityLabel??t.text??t.accessibilityLabel??null,type:r?.target?.type??t.type??null}}async resolveInteractionPoint(e){if(e.point&&!e.id&&!e.text&&e.index===void 0&&!e.childOf)return{...oe(e.point),element:null,target:void 0};let t=await this.waitForElement(e);if(!t)return null;let r=typeof t.nodeId=="number"?await this.resolveTapTarget(t.nodeId):null,n=this.replayTargetForElement(e,t,r);return e.point?{...oe(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:n}:{x:r?.cx??t.absolutePosition.x+t.layout.width/2,y:r?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:n}}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let o=await this.resolveInteractionPoint(t);if(!o)throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`);(await this.activatePressAt(o.x,o.y))?.ok||await this.tap(o.x,o.y,o.target),await w(300);return}let r=await this.waitForElement(t);if(r){let o=r.isTextInput?4:1;for(let s=0;s<o;s++){let a=s===0?r:await this.findElement({text:t.text,id:t.id});if(!a)break;let l=typeof a.nodeId=="number"?await this.resolveTapTarget(a.nodeId):null,u=l?.cx??a.absolutePosition.x+a.layout.width/2,h=l?.cy??a.absolutePosition.y+a.layout.height/2;if((await this.tap(u,h,this.replayTargetForElement(t,a,l)))?.hit===!0){if(await w(300),!a.isTextInput||await this.waitForFocusedTextInput(600,a))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await w(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async longPressOn(e){let t=typeof e=="string"?{text:e}:e,r=await this.resolveInteractionPoint(t);if(!r)throw new Error(`longPressOn: element not found: ${JSON.stringify(t)}`);let n=await this.longPress(r.x,r.y,3e3,r.target);if(n?.ok===!1||n?.value===!1)throw new Error(`longPressOn: long press missed: ${JSON.stringify(t)}`);await w(300)}async tapAtCoords(e,t){await this.tap(e,t),await w(300)}async doubleTapAtCoords(e,t,r=80){let n=await this.perform([{type:"doubleTap",x:e,y:t,gapMs:Math.max(0,Math.round(r))}]);if(!n?.ok)throw new Error(`doubleTapAtCoords failed at (${e}, ${t}): ${n?.error??"double tap missed"}`);await w(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let o=0;o<15;o++){if(await this.isElementVisible(t))return;await w(200)}let r=await this.findElement(t),n=r?` (matched node at y=${Math.round(r.absolutePosition.y)} h=${Math.round(r.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${n}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let r=await this.findElement(t),n=r?` at (${Math.round(r.absolutePosition.x)},${Math.round(r.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${n}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<H)}async inputText(e){if(!await this.waitForFocusedTextInput())throw new Error("inputText: no focused TextInput; tap the input and wait for focus before typing");await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await w(200)}focusedTextInputMatches(e,t){if(!t||typeof t.nodeId=="number"&&typeof e.nodeId=="number"&&t.nodeId===e.nodeId)return!0;let r=t.testID??null,n=e.testID??null;if(r&&n&&r===n)return!0;let o=t.id??null,s=e.id??null;return!!(o&&s&&o===s)}async waitForFocusedTextInput(e=1500,t){let r=Date.now()+e;for(;Date.now()<r;){try{let n=await this.callTest("getFocusedNode");if(n&&this.focusedTextInputMatches(n,t))return!0}catch{}await w(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await w(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await w(120)}async hideKeyboard(){try{await this.callTest("blurFocusedTextInput")}catch{}await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dismiss"});let e=Date.now()+3e3;for(;Date.now()<e;){let t=await this.evaluate(`(() => {
371
- const keyboard =
372
- window.__sootsimKeyboard ??
373
- window.SootSim?.bridges?.keyboard ??
374
- null
375
- const test = window.__sootsimTest
376
- return {
377
- visible: !!keyboard?.isVisible?.(),
378
- focused: !!test?.isTextInputFocused?.(),
379
- }
380
- })()`);if(!t?.visible&&!t?.focused){await w(80);return}await w(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await w(100)}async waitFor(e){let t=Date.now()+q(e.timeout||ie);for(;Date.now()<t;){if(await this.findElement(e))return;await w(200)}let r=await this.findElement(e),n=r?` (matched node y=${Math.round(r.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||ie}ms${n}`)}async takeScreenshot(e){let t=Zt(e),r=Xt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});I.mkdirSync(S.dirname(r),{recursive:!0});let n=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};n&&n!=="full"&&(o.layers=n);let s=null,a=1,l=null;for(let u=0;u<12;u++){await this.waitForVisualSettle();let h=await this.bridge.send(o),m=Buffer.from(h.replace(/^data:image\/png;base64,/,""),"base64");if((0,X.framesIdentical)(s,m)){if(a++,a>=X.REQUIRED_IDENTICAL_PROOF_FRAMES){l=m;break}}else a=1;s=m}if(!l)throw new Error(`screenshot did not reach ${X.REQUIRED_IDENTICAL_PROOF_FRAMES} identical idle frames`);if(t.withFrame){let u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let h=await pt(l,u);return I.writeFileSync(r,h),console.log(`[flow] screenshot: ${r} (frame: ${u})`),r}return I.writeFileSync(r,l),console.log(`[flow] screenshot: ${r}`),r}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.settings.get",args:[]}),t=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!t||!(t in Ne)?null:t}async captureScreenshot(e){await this.takeScreenshot({path:e})}async captureFailureBundle(e,t){I.mkdirSync(e,{recursive:!0});let r=(h,m)=>{try{I.writeFileSync(S.join(e,h),m)}catch{}},n=async h=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:h})}catch{return null}},o=await n(`(async () => {
381
- const out = {
382
- simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
383
- url: location.href,
384
- title: document.title,
385
- hidden: document.hidden,
386
- }
387
- try {
388
- const params = new URL(location.href).searchParams
389
- const bundle = params.get('bundle')
390
- if (bundle) {
391
- const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
392
- if (baseMatch) {
393
- const res = await fetch(baseMatch[0] + '/', {
394
- headers: { 'expo-platform': 'ios' },
395
- cache: 'no-store',
396
- })
397
- if (res.ok) {
398
- out.manifest = await res.json().catch(() => null)
399
- }
400
- }
401
- }
402
- } catch {}
403
- return out
404
- })()`);r("error.json",JSON.stringify({message:t.error.message,stack:t.error.stack,stepIndex:t.stepIndex,stepKind:t.stepKind,stepTarget:t.stepTarget,capturedAt:new Date().toISOString(),sim:o??null},null,2));try{let m=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(m,"base64"))}catch{}let s=await n(`(async () => {
405
- const t = window.__sootsimTest
406
- const mainShell = window.SootSim?.bridges?.mainShell
407
- if (!t) return { error: 'no test bridge' }
408
- let shell = null
409
- try {
410
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
411
- } catch {}
412
- const all = await t.queryAll({ pruneHidden: true })
413
- return { shell, nodes: all, url: location.href, title: document.title }
414
- })()`);s&&r("describe.json",JSON.stringify(s,null,2));let a=await n("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof a=="string"&&r("a11y.txt",a);let l=await n("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let u=await n(`(() => {
415
- const c = window.__sootsimConsole
416
- return {
417
- errors: c?.getErrors?.() ?? [],
418
- warnings: c?.getWarnings?.() ?? [],
419
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
420
- }
421
- })()`);return u&&r("console.json",JSON.stringify(u,null,2)),e}async swipe(e="UP",t=300){let r=se/2,n=H/2,o=200,s=r,a=n,l=r,u=n;switch(e.toUpperCase()){case"UP":a+=o,u-=o;break;case"DOWN":a-=o,u+=o;break;case"LEFT":s+=o,l-=o;break;case"RIGHT":s-=o,l+=o;break}let h=Math.max(10,Math.round(t/16));await this.drag(s,a,l,u,h,16)}async drag(e,t,r,n,o=12,s=16){let a=await this.perform([{type:"drag",fromX:e,fromY:t,toX:r,toY:n,steps:Math.max(1,Math.round(o)),stepMs:Math.max(0,Math.round(s))}]);if(!a?.ok)throw new Error(`drag failed: ${a?.error??"drag missed"}`);await w(300)}async swipeCoords(e,t,r=300){let n=oe(e),o=oe(t),s=Math.max(10,Math.round(r/16));await this.drag(n.x,n.y,o.x,o.y,s,16)}async swipeFrom(e,t="UP",r=300){let n=await this.findElement(e);if(!n)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=n.absolutePosition.x+n.layout.width/2,s=n.absolutePosition.y+n.layout.height/2,a=180,l=o,u=s;switch(t.toUpperCase()){case"UP":u-=a;break;case"DOWN":u+=a;break;case"LEFT":l-=a;break;case"RIGHT":l+=a;break}let h=Math.max(10,Math.round(r/16));await this.drag(o,s,l,u,h,16)}async scrollTo(e,t,r){let n=await this.callTest("scrollTo",e,t,r,!1);if(!n?.ok)throw new Error(`scrollTo failed: ${n?.reason||"unknown error"}`);await w(250)}async pinch(e){let t=await this.perform([{type:"pinch",fromX1:e.from[0],fromY1:e.from[1],fromX2:e.from[2],fromY2:e.from[3],toX1:e.to[0],toY1:e.to[1],toX2:e.to[2],toY2:e.to[3],steps:e.steps||12,stepMs:e.stepMs||16}]);if(!t?.ok)throw new Error(`pinch failed: ${t?.error||"unknown error"}`);await w(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;if(!(await re({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled)throw new Error(`animation did not settle within ${t}ms`)}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",n=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<H-50){if(e.centerElement){let s=H/2,a=o.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),u=a>0?s-l:s+l;await this.drag(se/2,s,se/2,u,10,16)}}return}await this.swipe(n,250),await w(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+q(e.timeout||ie);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,n=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&n)return;await w(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(){await this.evaluate("window.location.reload()").catch(()=>{})}async resetGuestAppData(e){let t=await this.bridge.send({type:"reset",simId:this.opts.simId,resetOptions:{strategy:"data",...e}},{timeoutMs:12e4});if(!t.ok)throw new Error(t.error??"guest app data reset failed");if(!t.relaunched)throw new Error("guest app data reset did not relaunch the app");if(t.workerReloaded!==!0)throw new Error("guest app data reset did not replace the tenant worker")}async reloadGuestAppRuntime(e){await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.hotRemount.reloadExternalApp",args:[e]},{timeoutMs:12e4})}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;)try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(r){t=r,await w(250)}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){let t=!1,r;if(Y(e)&&Object.prototype.hasOwnProperty.call(e,"arguments")){if(!Y(e.arguments))throw new Error("launchApp.arguments must be a JSON object");t=!0,r=e.arguments}let n=!!(e&&typeof e=="object"&&e.clearState),o=qt(e,"resetRuntime");if(!this.firstLaunchDone&&!n)this.firstLaunchDone=!0,t?(await this.launchShellAppFromHomeIfNeeded(e)&&await this.waitForTree(12e4),await this.reloadGuestAppRuntime({launchArguments:r,initialUrl:null}),await this.waitForTree(12e4)):o?(await this.launchShellAppFromHomeIfNeeded(e)&&await this.waitForTree(12e4),await this.reloadGuestAppRuntime({}),await this.waitForTree(12e4)):this.appStopped?(await this.launchShellAppFromHomeIfNeeded(e),await this.reloadGuestAppRuntime({launchArguments:null,initialUrl:null}),await this.waitForTree(12e4)):await this.launchShellAppFromHomeIfNeeded(e),await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,n?await this.resetGuestAppData({launchArguments:t?r:null,initialUrl:null}):t||this.launchArgumentsActive||this.appStopped?await this.reloadGuestAppRuntime({launchArguments:t?r:null,initialUrl:null}):await this.reloadGuestApp(),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch(this.opts.simId)}catch(s){console.warn(` warn: onAfterLaunch hook threw: ${s instanceof Error?s.message:s}`)}this.appStopped=!1,this.launchArgumentsActive=t,this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){let e=await re({bridge:this.bridge,simId:this.opts.simId,maxMs:1e4,pollMs:32,stablePolls:3,strict:!0});if(!e.settled)throw new Error(`visual state did not settle within ${e.elapsed}ms`)}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(Y(e)){let r=z(e,"appId")||z(e,"id");if(r)return r}return Yt(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,n=null;for(;Date.now()<r;){try{n=await ye(this.bridge)}catch{n=null}if(n?.state==="app"&&n.activeApp===e&&n.showSwitcher===!1&&typeof n.launchProgress=="number"&&n.launchProgress>=.98)return;await w(16)}}async launchShellAppFromHomeIfNeeded(e){let t=null;try{t=await ye(this.bridge)}catch{return!1}if(t?.state!=="home"||t.activeApp!=null)return!1;let r=this.resolveShellLaunchAppId(e,t);return this.recordingEnabled&&await this.ensureRecordingStarted(),await Ge(this.bridge,"launchApp",1e3,r),await this.waitForShellAppLaunched(r,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
422
- if (!window.__sootsimShellPerf) {
423
- return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
424
- }
425
- window.__sootsimShellPerf.start()
426
- return { started: true }
427
- })()`);if(e?.error)throw new Error(e.error);this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async () => {
428
- if (!window.__sootsimShellPerf) {
429
- return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
430
- }
431
- return await window.__sootsimShellPerf.stop()
432
- })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestAppRuntime({relaunch:!1}),this.appStopped=!0}async clearState(){await this.resetGuestAppData(),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: rnx has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let n=r.text??r.testID??"";this.js.setCopiedText(n),this.js.putEnv("maestroCopiedText",n),console.log(`[flow] copied text: ${JSON.stringify(n)}`)}evalScript(e){let r=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);r!==void 0&&r!==""&&console.log("[flow] evalScript ->",r)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let r=S.resolve(this.opts.flowDir,t.file),n=I.readFileSync(r,"utf8");this.js.evaluate(n,{env:t.env}),console.log(`[flow] runScript: ${t.file} done`)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");await this.reloadGuestAppRuntime({initialUrl:null,launchArguments:null}),await this.waitForTree(12e4);let r=await this.callTest("openDeepLink",t);if(!r?.ok)throw new Error(`openLink failed: ${r?.error||"no test bridge"}`);this.appStopped=!1,this.launchArgumentsActive=!1,this.firstLaunchDone=!0}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?ft(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),n=r?r[1]:void 0;return!!(n&&typeof n=="object"&&"optional"in n&&n.optional)}async runStep(e,t){let r=typeof e=="string"?mt(e):e,n=Object.keys(r).find(l=>l!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${n}`);let o=Date.now(),s=this.flowStepTargetLabel(r,n),a;try{a=this.js.interpolateStep(r),s=this.flowStepTargetLabel(a,n)??s}catch(l){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:r[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"failure",error:l}),l}if(a.when&&!await this.evaluateWhen(a.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"skipped"});return}try{let l=!!(a.extendedWaitUntil||a.waitFor||a.scrollUntilVisible||a.launchApp||a.runFlow||a.runScript),u=1e4,h=this.runStepInner(a),m;if(l){let f=await h;typeof f=="string"&&(m=f)}else{let f=null,v=new Promise((P,U)=>{f=setTimeout(()=>{U(new Error(`step watchdog: ${n} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{let P=await Promise.race([h,v]);typeof P=="string"&&(m=P)}finally{f&&clearTimeout(f)}}let g=!!(a.assertVisible||a.assertNotVisible||a.extendedWaitUntil||a.waitFor);this.stepDelay>0&&!g&&await w(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"success",screenshotPath:m})}catch(l){if(this.isOptional(a)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:a[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:s,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else{if(e.takeScreenshot)return this.takeScreenshot(e.takeScreenshot);if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await w(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,r=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(r))throw new Error(`repeat.times is not a number: ${t}`);let n=e.repeat.when??e.repeat.condition,o=async()=>n?this.evaluateWhen(n):!0,s=n?r:Math.min(r,1e3),a=0;for(;a<s&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);a++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,r=typeof t=="string"?void 0:t.when;if(r&&!await this.evaluateWhen(r)){console.log("[flow] runScript skipped (when predicate false)");return}this.runScript(t)}else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,r=typeof t=="string"?t:t.file,n=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,s=typeof t=="string"?void 0:t.when;if(s&&!await this.evaluateWhen(s)){console.log(`[flow] runFlow skipped (when predicate false): ${r??"inline commands"}`);return}if(!r&&!n)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[a,l]of Object.entries(o))this.js.putEnv(a,l);if(r){let a=S.resolve(this.opts.flowDir,r),l=I.readFileSync(a,"utf8"),u=this.opts.flowDir;this.opts.flowDir=S.dirname(a);try{await this.runFlow(Qt(l))}finally{this.opts.flowDir=u}}else if(n)for(let a=0;a<n.length;a++)await this.runStep(n[a],a)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}}liveStatus=null;async runFlow(e){let t=[],r=[],n=[];for(let s of e){let a=Object.keys(s);if(a.length===1&&a[0]==="onFlowStart"&&Array.isArray(s.onFlowStart)){t.push(...s.onFlowStart);continue}if(a.length===1&&a[0]==="onFlowComplete"&&Array.isArray(s.onFlowComplete)){r.push(...s.onFlowComplete);continue}n.push(s)}if(this.liveStatus&&await this.liveStatus.plan(n.map((s,a)=>{let l=typeof s=="string"?mt(s):s,u=Object.keys(l).find(h=>h!=="when")??Object.keys(l)[0];return{index:a,name:u,target:this.flowStepTargetLabel(l,u)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let s=0;s<t.length;s++)await this.runStep(t[s],s)}let o=null;try{await this.runFlowBody(n)}catch(s){o=s instanceof Error?s:new Error(String(s))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let s=0;s<r.length;s++)try{await this.runStep(r[s],s)}catch(a){console.warn(`[flow] onFlowComplete step ${s+1} failed: ${a instanceof Error?a.message:a}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],n=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,s=typeof r.extendedWaitUntil?.timeout=="number"?r.extendedWaitUntil.timeout:0,a=Math.max(6e4,n+15e3,q(o)+15e3,q(s)+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let l=Date.now(),u=async(h,m)=>{if(!this.liveStatus)return;let g=this.flowTraceSteps[this.flowTraceSteps.length-1],f=g&&g.stepIndex===t&&g.startedAtMs>=l;await this.liveStatus.step(t,h?"failure":f&&g.status==="skipped"?"skipped":"success",{durationMs:Date.now()-l,error:h?m instanceof Error?m.message.slice(0,300):String(m).slice(0,300):f&&g.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((h,m)=>setTimeout(()=>m(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${a}ms deadline`)),a))])}catch(h){let m=this.flowTraceSteps[this.flowTraceSteps.length-1];if(!(m&&m.stepIndex===t&&m.startedAtMs>=l)){let g=Object.keys(r)[0];this.lastFailedStep={index:t,kind:g,target:r[g]},this.recordFlowTraceStep({stepIndex:t,stepName:g,targetLabel:this.flowStepTargetLabel(r,g),startedAtMs:l,status:"failure",error:h})}throw await u(!0,h),h}await u(!1)}}};function er(i){if(typeof i!="object"||i==null||!("control"in i))return!1;let e=i.control;return typeof e=="object"&&e!=null&&"paused"in e&&e.paused===!0}var le=class{constructor(e,t,r){this.bridge=e;this.flowName=t;this.getSimId=r}disabled=!1;paused=!1;lastSimId;plannedSteps=null;completedSteps=new Map;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async send(e,t){let r=await this.bridge.send({type:"flowStatus",simId:t,status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=er(r)}async push(e){if(!this.disabled)try{let t=this.getSimId?.();if(t!==this.lastSimId&&this.lastSimId!=null&&this.plannedSteps&&e.phase!=="plan"){await this.send({phase:"plan",state:"running",steps:this.plannedSteps},t);for(let r of this.completedSteps.values())await this.send({phase:"step",state:"running",step:r},t)}this.lastSimId=t,await this.send(e,t)}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){this.plannedSteps=e.map(t=>({...t})),this.completedSteps.clear(),await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){let n={index:e,status:t,...r};await this.push({phase:"step",state:"running",step:n}),this.completedSteps.set(e,n)}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var Ae=null;function qr(){return Ae}var Pe=[];function Yr(){return Pe}async function nr(i){if(!i)return{target:""};let e=i.trim();if(!e)return{target:""};if(/^\d+$/.test(e))return{target:e};if(e.startsWith("http://")||e.startsWith("https://"))return{target:e};let r=(await Ue()).find(n=>n.name.toLowerCase()===e.toLowerCase());return r?{target:String(r.preferredPort),runtimeConfig:r.runtimeConfig}:{target:e}}async function ir(){let i=await je(),e=i.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=i[0];return t?`http://localhost:${t.port}/__soot/`:null}async function wt(i){Ae=null,Pe=[],(i.length===0||i.includes("--help")||i.includes("-h"))&&(console.log(`
433
- sootsim maestro \u2014 author and run Maestro YAML flows
434
-
435
- usage:
436
- sootsim maestro test <flow.yaml> [options]
437
- sootsim maestro start
438
- sootsim maestro keep
439
- sootsim maestro end [--output <path>] [--validate] [--video]
440
- sootsim maestro validate <path>
441
-
442
- options:
443
- --record record a webm artifact while the flow runs
444
- --profile capture perf stats while the flow runs
445
- --out <dir> output directory (default: /tmp/sootsim-recordings)
446
- --device <model> override the flow frontmatter device for this run
447
- --slow <ms> delay between steps for natural pacing
448
- --tail-wait <ms> hold the recording open after the last step so the
449
- final UI state is captured (default: smart idle up to
450
- 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
451
- --url <url> load this target before running the flow
452
- --screenshot-paths <mode>
453
- screenshot path mode: dir (default) or flow
454
- --no-shell capture every screenshot tenant-only (no status bar,
455
- keyboard, notification center, or other shell overlays).
456
- use for clean demo asset sets. per-step \`layers:\`
457
- still wins over this default.
458
- --shell-only inverse \u2014 capture shell chrome only
459
- --replace <m>=<f> replace a Metro module with a local file for this run
460
- --new open a fresh sim before running the flow
461
- --driver <id> when paired with --new, use playwright or electron;
462
- browser sims default to isolated playwright
463
- --headless pass headless=true to the launch driver (useful
464
- with --driver playwright)
465
- --headed force a fresh, VISIBLE window for this run (implies
466
- --new; overrides --headless). use when you want to
467
- watch the flow run live even if the current sim is
468
- headless or stale
469
- --electron prefer opening the target in the desktop companion
470
- --sim <id> target a specific current sim
471
- --validate replay the drafted flow before clearing it
472
- --video replay and record the drafted flow before clearing it
473
- --preview record events+video, upload, and print /preview/<id>
474
- --preview-open open the uploaded preview link after a successful run
475
- --preview-origin <url>
476
- upload target for --preview (default: auto)
477
- --preview-public-origin <url>
478
- public link origin for --preview (default: sootsim.com
479
- for prod uploads)
480
- --billing-kind test_run
481
- meter the chained preview upload as a test run
482
- --owner <org> associate preview upload with a linked org repo
483
- --repo <repo> repo name for --owner; user must belong to the team
484
-
485
- frontmatter (top of flow.yaml between --- markers):
486
- app: 8081 load this target before the flow starts
487
- device: iphone-14 set the live device model for this flow run
488
- electron: true prefer the desktop companion sim for this flow
489
-
490
- default runtime:
491
- bridge-backed flow playback against the current sim
492
- if no current sim exists, flow opens the discovered target first
493
- recording and profiling both run on the same bridge-backed path
494
-
495
- examples:
496
- sootsim maestro test login.yaml
497
- sootsim maestro test demo.yaml --url 8081 --record --slow 500 --out ./recordings
498
- sootsim maestro test demo.yaml --sim a2
499
- sootsim maestro start
500
- sootsim maestro keep
501
- sootsim maestro end --output ./.maestro/draft.yaml
502
- sootsim maestro end --output ./.maestro/draft.yaml --validate
503
- sootsim maestro end --output ./.maestro/draft.yaml --video
504
- sootsim maestro validate ./.maestro/draft.yaml
505
-
506
- flow extension:
507
- takeScreenshot: hero
508
- takeScreenshot:
509
- path: marketing/hero
510
- withFrame: true
511
- `),E(0));let e=i[0];$.existsSync(e)||(console.error(` error: ${e} not found`),E(1));let t=p=>i.find((d,y)=>i[y-1]===p),r=i.includes("--profile"),n=i.includes("--headed"),o=i.includes("--new")||n,s=t("--out")||"/tmp/sootsim-recordings",a=t("--screenshots")||(t("--out")?s:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",u=i.includes("--no-shell")?"tenant":i.includes("--shell-only")?"shell":void 0,h=t("--device")?.trim()||"",m=i.includes("--slow")?+(t("--slow")||"500"):0,g=i.includes("--electron"),f=i.includes("--preview"),v=f?await it(t("--preview-origin")):"",P=t("--preview-public-origin"),U=i.includes("--preview-open"),ke=t("--owner")?.trim()||"",$e=t("--repo")?.trim()||"",j=t("--billing-kind")?.trim()||"",bt=f?`maestro:${process.env.GITHUB_RUN_ID?`github:${process.env.GITHUB_RUN_ID}:attempt:${process.env.GITHUB_RUN_ATTEMPT||"1"}:job:${process.env.GITHUB_JOB||"preview"}`:`local:${rr()}`}:flow:${tr("sha256").update(b.relative(process.cwd(),b.resolve(e))).digest("hex").slice(0,16)}`:"";j&&j!=="test_run"&&(console.error(` error: invalid --billing-kind: ${j}`),E(1));let yt=i.flatMap((p,d)=>i[d-1]==="--replace"?["--replace",p]:[]),St=i.flatMap((p,d)=>i[d-1]==="--remap"?["--remap",p]:[]),D=i.includes("--record")||f,vt=i.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):D?f?6e3:2e3:0,xt=$.readFileSync(e,"utf8"),{frontmatter:T,steps:B}=Se(xt);B.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),E(1));let Q=h||T.device||"",Me=T.theme||"",de=g||T.electron===!0,Tt=T.app===void 0||T.app===null?"":typeof T.app=="number"?String(T.app):T.app,Re=await nr(Tt),ce=Re.target,Oe={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless","--headed"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--remap","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver","--billing-kind","--owner","--repo"]},x=we(i,Oe),Et=t("--url")||"";de&&!Ke()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),E(1));let It=de?"desktop companion":"bridge",Ft=ce?` | target: ${ce}`:"";console.log(`
512
- sootsim maestro \u2014 ${b.basename(e)}
513
- ${B.length} steps | ${It}${Ft}${D?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
514
- `);let M=Et||ce||"",ue=o||de&&x.simIdSource!=="flag",_e=t("--driver")||"",pe=!1,he=new Set,De=!1;if(!M&&!ue&&x.simIdSource==="none"){let p=He(x);try{let d=await p.listSims(),y=d.find(_=>_.isPrimary&&_.readyState==="open"),k=d.find(_=>_.readyState==="open"),G=y??k;G&&(De=!0,console.log(` reusing active sim: ${G.id}`))}catch{}finally{p.close()}}if(!M&&!De&&(ue||x.simIdSource==="none")){let p=await ir();p||(console.error(" error: no current sim and no sootsim target found"),E(1)),M=p}if(M&&Q){let p=new URL(await Ye(M,qe(x.wsPort)));p.searchParams.set("device",Q),M=p.toString()}if(M){let p=[M];if(p.push(...yt),p.push(...St),ue&&p.push("--new"),p.push("--no-describe"),x.simIdSource==="flag"&&x.simId&&p.push("--sim",x.simId),_e&&(p.push("--driver",_e),pe=!0),i.includes("--headless")&&!n&&p.push("--headless"),await Xe(p,{port:x.wsPort,timeoutMs:x.commandTimeoutMs,runtimeConfig:Re.runtimeConfig}),pe){let d=me();d&&he.add(d)}}let L=we(i,Oe),ee=L.simIdSource==="flag"?L.simId:me()||L.simId,At=L.simIdSource==="flag"?"flag":ee?"saved":"none",F=be(L.wsPort,{commandTimeoutMs:L.commandTimeoutMs,simId:ee,simIdSource:At}),c,Be=async()=>{let p=T.env?.SOOTSIM_STATUS_BAR_TIME;if(p){if(!/^(?:[1-9]|1[0-2]):[0-5][0-9]$/.test(p))throw new Error("SOOTSIM_STATUS_BAR_TIME must be a 12-hour time such as 9:41");await F.send({type:"evaluate",simId:c.simId,code:`window.dispatchEvent(new CustomEvent('sootsim:statusBarOverride', { detail: { time: ${JSON.stringify(p)} } }))`})}return Me&&await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",Me]}),Q?!!await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",Q]}):!1};if(c=new ae(F,{screenshotDir:a,flowDir:b.dirname(b.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:ee,recordingOutputDir:D?s:void 0,recordingFormat:f?"mp4":"webm",billingOriginOverride:f?v:void 0,allowGitHubRecording:f,requireRecordingEntitlement:f,onAfterLaunch:async p=>{p&&ge(p),await Be()&&await c.waitForTree(12e4),f&&await F.send({type:"evaluate",simId:c.simId,code:`(() => {
515
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
516
- return r?.start?.() ?? false
517
- })()`})}}),m&&(c.stepDelay=m),c.liveStatus=new le(F,b.basename(e),()=>c.simId),c.js.putEnv("MAESTRO_FILENAME",b.basename(e,b.extname(e))),T.env&&typeof T.env=="object")for(let[p,d]of Object.entries(T.env))c.js.putEnv(p,d);let R=null,A=null,N=null,O=null,W=null,fe=null,V=0,te=!!B[0]?.launchApp;try{te||await c.waitForTree(12e4),await Be()&&!te&&await c.waitForTree(12e4),f&&!te&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),D&&(te?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),f&&(await F.send({type:"evaluate",simId:c.simId,code:`(() => {
518
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
519
- return r?.start?.() ?? false
520
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(B),r&&(R=await c.stopProfile()),await c.waitForRecordingTail({maxMs:vt,smart:f}),D&&(A=await c.stopRecording(),N=c.getLastRecordingDurationMs()),f&&(O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
521
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
522
- return r?.stop?.() ?? []
523
- })()`}),console.log(` captured ${O.length} replay events`),W=b.join(a,"preview-final.png"),await c.captureScreenshot(W),console.log(` final screenshot: ${W}`));let d=B.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
524
- + completed (${B.length} steps)`),d>0&&console.log(` screenshots: ${d} \u2192 ${a}`),R&&gt(R),A&&console.log(` video: ${A}`),console.log()}catch(p){if(r&&!R)try{R=await c.stopProfile()}catch{}if(D&&!A)try{A=await c.stopRecording(),N=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(f&&!O)try{O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
525
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
526
- return r?.stop?.() ?? []
527
- })()`}),console.log(` captured ${O.length} partial replay events`)}catch(d){console.warn(` event recorder stop failed: ${d?.message||String(d)}`)}console.error(`
528
- x failed: ${p.message}
529
- `),R&&(console.log(" partial profile:"),gt(R)),A&&console.log(` partial video: ${A}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",k=b.join(a,y);await c.captureFailureBundle(k,{error:p,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),fe=k,console.log(` failure bundle: ${k}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let y=b.join(a,"error.png");await c.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await Je(F,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),V=1}if(await c.liveStatus?.end(V===0?"passed":"failed"),f&&(V===0||A||O))try{let p=await sr(O??[]),d=["--origin",v,"--events",p];P&&d.push("--public-origin",P),A&&d.push("--video",A),W&&d.push("--screenshot",W),A&&N&&Number.isFinite(N)&&(d.push("--video-duration-ms",String(Math.round(N))),d.push("--recorded-duration-ms",String(Math.round(N))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),x.wsPort&&d.push("--port",String(x.wsPort)),c.simId&&d.push("--sim",c.simId),U&&d.push("--open"),ke&&d.push("--owner",ke),$e&&d.push("--repo",$e),d.push("--run-scope",bt),j&&d.push("--billing-kind",j),console.log(`
530
- preparing preview upload\u2026`);let k=c.getFlowTraceSteps();k.length>0&&d.push("--timeline-events",await ar(k));let G=await lr(k,y);G&&d.push("--snapshot-manifest",G),fe&&d.push("--failure-bundle",fe);let _=c.getLastRecordingFrameStats();_&&d.push("--trace-frame-stats",await dr(_));let{runUpload:Pt}=await import("./upload-ZDV4BFED.js");Ae=await Pt(d,{})}catch(p){console.error(` preview upload failed: ${p?.message||p}`),V=1}return Pe=c.getFlowTraceSteps(),F.close(),pe?(c.simId&&he.add(c.simId),await or(x.wsPort,x.commandTimeoutMs,[...he])):c.simId&&c.simId!==ee&&ge(c.simId),V}async function or(i,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let n=be(i,{commandTimeoutMs:e});try{let o=await n.listSims(),s=r.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(s.length===0)return;let a=await Ze(n,i,e,s);await ze(o,s),a.closed.length>0&&console.log(` closed flow sim(s): ${a.closed.join(", ")}`),a.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${a.remaining.join(", ")}`)}catch(o){console.warn(` warn: failed to close flow sim(s): ${o instanceof Error?o.message:String(o)}`)}finally{n.close()}}async function sr(i){let{gzipSync:e}=await import("zlib"),t=i.map(o=>JSON.stringify(o)).join(`
531
- `)+(i.length?`
532
- `:""),r=e(Buffer.from(t,"utf8")),n=b.join(Z(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(n,r),console.log(` events: ${i.length} written to ${n} (${r.length} bytes gz)`),n}async function ar(i){let{gzipSync:e}=await import("zlib"),t=i.map((s,a)=>({schemaVersion:1,t:s.endedAtMs,seq:1e6+a,context:"host",kind:"flow-step",id:`flow-step-${s.stepIndex}`,data:{stepIndex:s.stepIndex,stepNumber:s.stepIndex+1,stepName:s.stepName,...s.targetLabel?{targetLabel:s.targetLabel}:{},status:s.status,durationMs:s.durationMs,startedAtMs:s.startedAtMs,endedAtMs:s.endedAtMs,...s.error?{error:s.error}:{}}})),r=t.map(s=>JSON.stringify(s)).join(`
533
- `)+`
534
- `,n=e(Buffer.from(r,"utf8")),o=b.join(Z(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return $.writeFileSync(o,n),console.log(` flow trace: ${t.length} step events written to ${o} (${n.length} bytes gz)`),o}async function lr(i,e){if(!e)return null;let t=i.flatMap(n=>n.screenshotPath?[{id:`flow-step-${n.stepIndex}`,label:n.targetLabel??`Step ${n.stepIndex+1}`,kind:"interaction",t:Math.max(0,n.endedAtMs-e),path:n.screenshotPath}]:[]);if(t.length===0)return null;let r=b.join(Z(),`sootsim-flow-snapshots-${Date.now()}.json`);return $.writeFileSync(r,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${r}`),r}async function dr(i){let e=b.join(Z(),`sootsim-frame-stats-${Date.now()}.json`);return $.writeFileSync(e,JSON.stringify(i)),console.log(` frame stats: written to ${e}`),e}async function cr(i){let e=i[0],t=r=>i.find((n,o)=>i[o-1]===r);switch(e){case"start":{let{path:r,state:n}=et();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${n.steps.length}`);return}case"keep":{let r=Te();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),E(1)),!r.kept){console.log(" no pending action to keep");return}console.log(` kept: ${r.candidate.summary}`),console.log(` steps: ${r.stepCount}`);return}case"end":{let r=t("--output")||(i[1]&&!i[1].startsWith("-")?i[1]:void 0),n=i.includes("--validate")||i.includes("--video"),o=i.includes("--video"),s=Te();s.active&&s.kept&&console.log(` auto-kept trailing action: ${s.candidate.summary}`);let a=tt(r||(n?pr():void 0));if(a.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),E(1)),!a.valid){console.error(" flow draft is not valid:");for(let l of a.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim maestro start` to reset"),E(1)}if(n){let l=hr(i,a.outputPath),u=await wt(l);if(u!==0){console.error(`
535
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}xe(),console.log(` flow draft validated (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath&&console.log(` saved: ${a.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(xe(),console.log(` flow draft ended (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath){console.log(` saved: ${a.outputPath}`),console.log(` next: sootsim maestro test ${a.outputPath} --record`);return}console.log(""),process.stdout.write(a.yaml);return}case"validate":{let r=i[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),E(1));let n=ve(r);if(n.length>0){console.error(` x ${r} failed validation:`);for(let o of n)console.error(` - ${o}`);E(1)}console.log(` + ${r} looks valid`);return}}}function ur(i){return i[0]==="--sim"&&i.length>=2?[...i.slice(2),"--sim",i[1]]:i}async function zr(i){let e=ur(i),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await cr(e),0;let r=await wt(e);return r!==0&&(process.exitCode=r),r}function gt(i){console.log(""),rt(i)}function pr(){return b.join(Z(),`sootsim-flow-draft-${Date.now()}.yaml`)}function hr(i,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<i.length;r++){let n=i[r];if(!(n==="--validate"||n==="--video")){if(n==="--output"){r+=1;continue}r===1&&!n.startsWith("-")||t.push(n)}}return!t.includes("--record")&&i.includes("--video")&&t.push("--record"),t}export{pt as a,Ht as b,qr as c,Yr as d,nr as e,ir as f,wt as g,ur as h,zr as i};