sootsim 0.1.185 → 0.1.186

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 (157) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-VF756RZU.js → agent-HOCS7BA7.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-IAFL7ROV.js → agent-wrapper-OFIKO65K.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-VWLEC7ZA.js → app-fonts-PXVMBZZ7.js} +2 -2
  5. package/dist-cli/chunks/{assert-I55QVGG7.js → assert-OZS6AXZE.js} +2 -2
  6. package/dist-cli/chunks/beta-LUMNYREE.js +2 -0
  7. package/dist-cli/chunks/{camera-CYYBJH7W.js → camera-QJ2PKIJB.js} +2 -2
  8. package/dist-cli/chunks/{chunk-2T73IGB2.js → chunk-2B2D2EBR.js} +2 -2
  9. package/dist-cli/chunks/{chunk-ARNLQPMQ.js → chunk-353E6UCU.js} +2 -2
  10. package/dist-cli/chunks/chunk-3ISH4ZRW.js +1 -0
  11. package/dist-cli/chunks/{chunk-PIUKLO3W.js → chunk-4HVMPXJZ.js} +1 -1
  12. package/dist-cli/chunks/chunk-5TTEOJ4A.js +1 -0
  13. package/dist-cli/chunks/chunk-5XIRXMOS.js +971 -0
  14. package/dist-cli/chunks/chunk-6MJVRIUP.js +118 -0
  15. package/dist-cli/chunks/{chunk-EXFB33AZ.js → chunk-6OQVIQY7.js} +2 -2
  16. package/dist-cli/chunks/chunk-BU5CRHHR.js +24 -0
  17. package/dist-cli/chunks/{chunk-TUF6EPCQ.js → chunk-DPXVA7ZF.js} +2 -2
  18. package/dist-cli/chunks/{chunk-R4KLD4P4.js → chunk-FN64EREO.js} +2 -2
  19. package/dist-cli/chunks/{chunk-BI56RR3G.js → chunk-FUHNIWFL.js} +4 -4
  20. package/dist-cli/chunks/{chunk-WEJKLJ4B.js → chunk-GNGEYMS3.js} +2 -2
  21. package/dist-cli/chunks/{chunk-QTFCJYBF.js → chunk-I65LTDPY.js} +3 -3
  22. package/dist-cli/chunks/{chunk-BMCBPMTC.js → chunk-INIASYOZ.js} +1 -1
  23. package/dist-cli/chunks/{chunk-FUHXL6BW.js → chunk-KNICGV7H.js} +1 -1
  24. package/dist-cli/chunks/{chunk-E5DE33BU.js → chunk-LV7DFIBL.js} +1 -1
  25. package/dist-cli/chunks/{chunk-M3P67TBN.js → chunk-MAGDSBXT.js} +1 -1
  26. package/dist-cli/chunks/chunk-MP4CRGWM.js +2 -0
  27. package/dist-cli/chunks/{chunk-MADEJDFD.js → chunk-MPUCQL3Q.js} +1 -1
  28. package/dist-cli/chunks/{chunk-FY6DJGOS.js → chunk-N3PLEUYD.js} +39 -15
  29. package/dist-cli/chunks/{chunk-CYBRFHPU.js → chunk-NYYP5QQK.js} +2 -2
  30. package/dist-cli/chunks/{chunk-4OUQAR34.js → chunk-O2SQQXUO.js} +1 -1
  31. package/dist-cli/chunks/{chunk-K2THZIVC.js → chunk-OMFESSKA.js} +1 -1
  32. package/dist-cli/chunks/{chunk-C3UEINOZ.js → chunk-P5UT637B.js} +2 -2
  33. package/dist-cli/chunks/{chunk-C63EVPDN.js → chunk-POOE26UD.js} +2 -2
  34. package/dist-cli/chunks/{chunk-HQG4DRQ3.js → chunk-PTUTIFWJ.js} +1 -1
  35. package/dist-cli/chunks/{chunk-IJP257WP.js → chunk-QBLTH2F6.js} +1 -1
  36. package/dist-cli/chunks/{chunk-LJ3SOZBF.js → chunk-RAY2ZSNI.js} +2 -2
  37. package/dist-cli/chunks/{chunk-DZLBZGHN.js → chunk-RDM3LVH2.js} +2 -2
  38. package/dist-cli/chunks/chunk-RP5CVR6O.js +382 -0
  39. package/dist-cli/chunks/{chunk-PKZNXDUJ.js → chunk-TYV3FMBE.js} +2 -2
  40. package/dist-cli/chunks/{chunk-4NUQVW5P.js → chunk-U3BTJLRM.js} +17 -6
  41. package/dist-cli/chunks/{chunk-QQ4NSPAD.js → chunk-UATE6GSA.js} +2 -2
  42. package/dist-cli/chunks/chunk-V434ATFM.js +13 -0
  43. package/dist-cli/chunks/{chunk-GX6MKIFC.js → chunk-VGAD3CMW.js} +1 -1
  44. package/dist-cli/chunks/{chunk-LI4RLX6B.js → chunk-VPUJQTEO.js} +1 -1
  45. package/dist-cli/chunks/chunk-WBPTJ3WC.js +5 -0
  46. package/dist-cli/chunks/{chunk-NL5IFN4T.js → chunk-WFSLSEGX.js} +2 -2
  47. package/dist-cli/chunks/{chunk-TFZO277G.js → chunk-XFQOFRYY.js} +1 -1
  48. package/dist-cli/chunks/{chunk-TNHF6BON.js → chunk-XQ6PPMM6.js} +1 -1
  49. package/dist-cli/chunks/{chunk-FHJTTB3W.js → chunk-YYZGAZQI.js} +2 -2
  50. package/dist-cli/chunks/{chunk-WBY4JJ2K.js → chunk-ZE2O7AA5.js} +2 -2
  51. package/dist-cli/chunks/{chunk-X4KS33ZC.js → chunk-ZJ64K2PL.js} +2 -2
  52. package/dist-cli/chunks/cli-version-474OBNTF.js +2 -0
  53. package/dist-cli/chunks/{compat-ZJA3N4ZT.js → compat-BNXJOVMU.js} +3 -3
  54. package/dist-cli/chunks/control-6LPRGKTF.js +2 -0
  55. package/dist-cli/chunks/{cpu-profile-ACSQMVXY.js → cpu-profile-3KXOGOJP.js} +2 -2
  56. package/dist-cli/chunks/daemon-OMT3RVU4.js +2 -0
  57. package/dist-cli/chunks/{debug-W2ZOVTQO.js → debug-B3MN6772.js} +11 -10
  58. package/dist-cli/chunks/{detox-ANJO6T27.js → detox-YKSX4DUO.js} +2 -2
  59. package/dist-cli/chunks/{device-KPPN4KYD.js → device-NZX6AKQI.js} +2 -2
  60. package/dist-cli/chunks/{diagnose-5PEJYGES.js → diagnose-26HE6KS5.js} +2 -2
  61. package/dist-cli/chunks/drivers-2PZC4QA3.js +2 -0
  62. package/dist-cli/chunks/{electron-U456QLSQ.js → electron-XEUWIM47.js} +3 -3
  63. package/dist-cli/chunks/flow-P22NDT6V.js +2 -0
  64. package/dist-cli/chunks/help-ECGL4JSP.js +2 -0
  65. package/dist-cli/chunks/{hints-MBBQLMQU.js → hints-C56M4PMW.js} +2 -2
  66. package/dist-cli/chunks/{home-paths-KQKYP2SE.js → home-paths-EYH3RBPS.js} +2 -2
  67. package/dist-cli/chunks/inspect-LJYG4WC6.js +2 -0
  68. package/dist-cli/chunks/{install-desktop-OR6ZJ43X.js → install-desktop-UWHLWFKB.js} +3 -3
  69. package/dist-cli/chunks/{keys-JSQMBUE7.js → keys-Q37NM52E.js} +2 -2
  70. package/dist-cli/chunks/{login-DVMWAI3G.js → login-6E6ZEJRF.js} +4 -4
  71. package/dist-cli/chunks/{logout-RIVPFE5N.js → logout-A7QHH6DQ.js} +2 -2
  72. package/dist-cli/chunks/{maestro-TX6FPTVH.js → maestro-YJRGFGDQ.js} +2 -2
  73. package/dist-cli/chunks/optional-demo-registry-OVWOHGTW.js +2 -0
  74. package/dist-cli/chunks/{preview-3AD7WNA6.js → preview-3OYFVL4A.js} +2 -2
  75. package/dist-cli/chunks/{profile-HY55VFNR.js → profile-5Z2YGBCJ.js} +2 -2
  76. package/dist-cli/chunks/{react-HDRCKCKV.js → react-ZNFFE3VQ.js} +2 -2
  77. package/dist-cli/chunks/{record-HW4C7QYN.js → record-V4CBW3GG.js} +2 -2
  78. package/dist-cli/chunks/runtime-OC6S2C22.js +2 -0
  79. package/dist-cli/chunks/{screenshot-XFR3QN5T.js → screenshot-QWMRWTIQ.js} +2 -2
  80. package/dist-cli/chunks/{screenshot-mode-Y5CVO267.js → screenshot-mode-36EUFBF5.js} +2 -2
  81. package/dist-cli/chunks/{screenshots-RKUL2ZZT.js → screenshots-LOS6WHZN.js} +2 -2
  82. package/dist-cli/chunks/{screenshots-capture-RVNF75ZD.js → screenshots-capture-6D6TBI6A.js} +2 -2
  83. package/dist-cli/chunks/{serve-QMRYLWL5.js → serve-YWGZ2JSI.js} +16 -16
  84. package/dist-cli/chunks/{setup-ELNJS7AI.js → setup-JS35KZ6P.js} +3 -3
  85. package/dist-cli/chunks/{skills-GPSJYS4W.js → skills-2TRDAXNC.js} +2 -2
  86. package/dist-cli/chunks/{slides-OCFNPIFG.js → slides-AO5MBP5Q.js} +2 -2
  87. package/dist-cli/chunks/store-HQKPCA6W.js +2 -0
  88. package/dist-cli/chunks/telemetry-I2H25VVF.js +2 -0
  89. package/dist-cli/chunks/{telemetry-KFZQUFG5.js → telemetry-MBWJUKBU.js} +2 -2
  90. package/dist-cli/chunks/{test-Z2HZXCZM.js → test-TRP2O6AP.js} +3 -3
  91. package/dist-cli/chunks/{three-mode-NKJFCDYS.js → three-mode-VVNOGAZT.js} +2 -2
  92. package/dist-cli/chunks/{timeline-PRGQMQRR.js → timeline-4WDFXUXB.js} +2 -2
  93. package/dist-cli/chunks/{upgrade-3NW7JRRX.js → upgrade-NHQRFD4J.js} +2 -2
  94. package/dist-cli/chunks/upload-6C2EC56N.js +2 -0
  95. package/dist-cli/chunks/{version-FDTZRIYT.js → version-T7O46MZL.js} +2 -2
  96. package/dist-cli/chunks/{web-4N5QQEQJ.js → web-7YW2ISLF.js} +2 -2
  97. package/dist-cli/chunks/{what-happened-IX2RRCOS.js → what-happened-IDOUXSFI.js} +2 -2
  98. package/dist-cli/chunks/{whoami-QZ42FYYF.js → whoami-DQBR3UTO.js} +2 -2
  99. package/dist-lib/agent-daemon-client.cjs +1 -1
  100. package/dist-lib/agent-events.cjs +1 -1
  101. package/dist-lib/agent-sessions.cjs +1 -1
  102. package/dist-lib/attached-projects.cjs +1 -1
  103. package/dist-lib/auth/shared-session.cjs +1 -1
  104. package/dist-lib/backend-origin.cjs +1 -1
  105. package/dist-lib/beta.cjs +1 -1
  106. package/dist-lib/beta.mjs +1 -1
  107. package/dist-lib/bridge-constants.cjs +1 -1
  108. package/dist-lib/cli-constants.cjs +1 -1
  109. package/dist-lib/config.cjs +1 -1
  110. package/dist-lib/detox/index.cjs +1 -1
  111. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  112. package/dist-lib/home-paths.cjs +2 -2
  113. package/dist-lib/host/bridge-host.cjs +77 -44
  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/websocket-proxy.cjs +1 -1
  118. package/dist-lib/index.cjs +28 -1
  119. package/dist-lib/jump-to-source-babel.cjs +1 -1
  120. package/dist-lib/menu.cjs +1 -1
  121. package/dist-lib/menu.mjs +1 -1
  122. package/dist-lib/metro.cjs +28 -1
  123. package/dist-lib/profiles.cjs +1 -1
  124. package/dist-lib/render-mode.cjs +1 -1
  125. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  126. package/dist-lib/sdk.cjs +38 -10
  127. package/dist-lib/sdk.mjs +38 -10
  128. package/dist-lib/skills.cjs +283 -254
  129. package/dist-lib/vite.cjs +28 -1
  130. package/package.json +1 -1
  131. package/src/home-paths.ts +8 -1
  132. package/src/host/bridge-host.ts +15 -1
  133. package/src/runtime-assets.ts +70 -0
  134. package/src/vite-plugin.ts +9 -0
  135. package/dist-cli/chunks/beta-X6YPQVZH.js +0 -2
  136. package/dist-cli/chunks/chunk-7OAUPGLN.js +0 -23
  137. package/dist-cli/chunks/chunk-IGJHME3T.js +0 -1
  138. package/dist-cli/chunks/chunk-JRL7PFNZ.js +0 -463
  139. package/dist-cli/chunks/chunk-KOKIECMB.js +0 -118
  140. package/dist-cli/chunks/chunk-OAHGYDJR.js +0 -13
  141. package/dist-cli/chunks/chunk-PDLQWZN4.js +0 -2
  142. package/dist-cli/chunks/chunk-SL6565MR.js +0 -1
  143. package/dist-cli/chunks/chunk-V4M2R6FZ.js +0 -2
  144. package/dist-cli/chunks/chunk-V5JEPE3P.js +0 -5
  145. package/dist-cli/chunks/chunk-XU5EMZ4B.js +0 -264
  146. package/dist-cli/chunks/cli-version-ICHQMND6.js +0 -2
  147. package/dist-cli/chunks/control-CZFSYSYG.js +0 -2
  148. package/dist-cli/chunks/daemon-337B4P3B.js +0 -2
  149. package/dist-cli/chunks/drivers-MSDIFHBD.js +0 -2
  150. package/dist-cli/chunks/flow-JL3SC6HC.js +0 -2
  151. package/dist-cli/chunks/help-PA4RTR5X.js +0 -2
  152. package/dist-cli/chunks/inspect-ZP5SM4EW.js +0 -987
  153. package/dist-cli/chunks/optional-demo-registry-ONYG6DUI.js +0 -2
  154. package/dist-cli/chunks/runtime-RHHPW5WO.js +0 -2
  155. package/dist-cli/chunks/store-MBKDUQEQ.js +0 -2
  156. package/dist-cli/chunks/telemetry-46XXIUEE.js +0 -2
  157. package/dist-cli/chunks/upload-QVDVJ6ZK.js +0 -2
@@ -1,463 +0,0 @@
1
- /*! sootsim v0.1.185 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as We}from"./chunk-2T73IGB2.js";import{a as Ue}from"./chunk-QQ4NSPAD.js";import{a as Je}from"./chunk-ARNLQPMQ.js";import{a as oe,b as je,c as se,d as ae,e as Le,f as le,h as de,i as Ve,j as ce}from"./chunk-XU5EMZ4B.js";import{h as De,p as Ne,s as Ce,w as Be}from"./chunk-OAHGYDJR.js";import{f as ke}from"./chunk-V5JEPE3P.js";import{h as Oe,m as Re}from"./chunk-FHJTTB3W.js";import{I as ne,m as Fe,n as Ee,o as Ae,p as Me}from"./chunk-FY6DJGOS.js";import{a as $e}from"./chunk-K2THZIVC.js";import{c as re,d as ie,e as Pe}from"./chunk-7OAUPGLN.js";import{a as _e}from"./chunk-BMCBPMTC.js";import{a as xe,b as ee}from"./chunk-C63EVPDN.js";import{d as te,e as Ie}from"./chunk-E5DE33BU.js";import{g as Te}from"./chunk-FUHXL6BW.js";import*as R from"fs";import{tmpdir as ze}from"os";import*as b from"path";import*as v from"fs";import*as g from"path";import{spawnSync as st}from"child_process";import*as P from"vm";var at=3e5,lt=`
3
- let input = '';
4
- process.stdin.on('data', (c) => { input += c });
5
- process.stdin.on('end', async () => {
6
- try {
7
- const req = JSON.parse(input);
8
- const res = await fetch(req.url, {
9
- method: req.method,
10
- headers: req.headers,
11
- body: req.body === undefined || req.body === null ? undefined : req.body,
12
- });
13
- const body = await res.text();
14
- const headers = {};
15
- for (const [k, v] of res.headers.entries()) {
16
- headers[k] = headers[k] ? headers[k] + ',' + v : v;
17
- }
18
- process.stdout.write(JSON.stringify({ ok: res.ok, status: res.status, body, headers }));
19
- } catch (err) {
20
- process.stdout.write(JSON.stringify({ __error: (err && err.message) || String(err) }));
21
- process.exitCode = 1;
22
- }
23
- });
24
- `;function C(i,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let n={...process.env};for(let a of Object.keys(n))(a.startsWith("BUN_INSPECT")||a==="NODE_OPTIONS")&&delete n[a];let r=st(process.execPath,["-e",lt],{input:JSON.stringify({url:i,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:at,maxBuffer:64*1024*1024,env:n});if(r.error)throw new Error(`http ${e} ${i} failed: ${r.error.message}`);let o;try{o=JSON.parse(r.stdout||"")}catch{throw new Error(`http ${e} ${i} failed: no response (${(r.stderr||"").trim().slice(0,200)})`)}let s=o;if(s.__error)throw new Error(`http ${e} ${i} failed: ${s.__error}`);return s}var dt=/(?<!\\)\$\{([^$]*)\}/g,ct=/\\(\$\{[^$]*\})/g,ut=/^[A-Za-z_$][A-Za-z0-9_$]*$/,H=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??(r=>console.log(`[flow] js: ${r}`)),n={output:this.output,maestro:this.maestro,http:{get:(r,o)=>C(r,"GET",o),post:(r,o)=>C(r,"POST",o),put:(r,o)=>C(r,"PUT",o),delete:(r,o)=>C(r,"DELETE",o),request:(r,o)=>C(r,(o?.method??"GET").toUpperCase(),o)},console:{log:(...r)=>t(r.map(o=>typeof o=="string"?o:He(o)).join(" "))}};this.context=P.createContext(n),P.runInContext(`
25
- globalThis.__maestroScope = new Proxy(globalThis, {
26
- has() { return true },
27
- get(target, key) { return target[key] },
28
- })
29
- function json(text) { return JSON.parse(text) }
30
- function relativePoint(x, y) {
31
- var xPercent = Math.ceil(x * 100) + '%'
32
- var yPercent = Math.ceil(y * 100) + '%'
33
- return xPercent + ',' + yPercent
34
- }
35
- `,this.context);for(let[r,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(r,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,n]of e)this.envBinding.set(t,n)}}evaluate(e,t={}){let n=t.env;if(n&&Object.keys(n).length>0){this.enterEnvScope();try{for(let[r,o]of Object.entries(n))this.envBinding.set(r,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 P.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=P.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,n]of this.envBinding)try{e[t]=n,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(dt,(n,r)=>{if(r.trim().length===0)return"";let o=this.evaluate(r);if(o===void 0&&ut.test(r.trim()))throw new Error(`missing variable for flow placeholder: ${r.trim()}`);return He(o)}).replace(ct,(n,r)=>r)}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(n=>this.interpolateValue(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,this.interpolateValue(r,n)])):e}};function He(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 Ke(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 K=1e4,q=393,O=852,qe="__sootsimCliPerf";function m(i){return new Promise(e=>setTimeout(e,i))}function fe(i){return!!(i&&typeof i=="object"&&!Array.isArray(i))}function B(i,e){if(!fe(i))return null;let t=i[e];return typeof t=="string"&&t.length>0?t:null}function ft(i,e){return fe(i)?i[e]===!0:!1}function pt(i){if(!i)return null;let e=i.recentApps;if(Array.isArray(e))for(let n of e){let r=B(n,"id");if(r)return r}let t=i.surfaceBindings;return B(t,"app:one")||B(t,"app:two")||null}function mt(i){return i?g.basename(i)===".maestro"?g.dirname(i):i:process.cwd()}function ht(i,e,t){let n=e.endsWith(".png")?e:`${e}.png`;if(g.isAbsolute(n))return n;if(t.mode==="flow"&&/[\\/]/.test(n)){let r=n.startsWith("./")||n.startsWith("../")?t.flowDir??process.cwd():mt(t.flowDir);return g.resolve(r,n)}return g.join(i,n)}function wt(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 ue(i){let[e,t]=i.split(",").map(r=>r.trim()),n=(r,o)=>r.endsWith("%")?Number.parseFloat(r)/100*o:Number.parseFloat(r);return{x:n(e,q),y:n(t,O)}}function gt(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 yt(i){let e=i.split(/^---$/m),t=e.length>1?e[e.length-1]:i,n=je.parse(t);return Array.isArray(n)?n:[]}var G=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new H({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingDurationMs=null;lastVisualSettledAtMs=0;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let n=t.searchParams.toString();return`${t.origin}${t.pathname}${n?`?${n}`:""}`}catch{return e}}async refreshSimId(){if(this.opts.simId)try{let e=await this.bridge.listSims(),t=e.find(l=>l.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(l=>l.id===this.opts.simId&&l.readyState==="open")||!this.simRouteHint)return;let r=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!r)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),s=e.find(l=>l.readyState==="open"),a=r??o??s;a&&(this.opts.simId=a.id,console.log(` [flow] sim rotated to ${a.id}`))}catch{}}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 waitForTree(e=K){let t=Date.now()+e,n=Date.now(),r=null,o=0,s=0,a=-1,l=n;for(;Date.now()<t;){try{let d=await this.evaluate(Fe,8e3);if(o=0,d?.externalError)throw new Error(`app failed to load: ${d.externalError}`);if(d){let h=Date.now();d.nodes!==a&&(a=d.nodes,l=h);let A=d.flag===!0&&Ae(d),w=d.flag!==!0&&Me(d);if((A||w)&&d.externalReady!==!1&&!d.externalError&&!d.loadingText&&h-l>=Ee)return}}catch(d){if(r=d instanceof Error?d:new Error(String(d)),r.message.startsWith("app failed to load:"))throw r;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${r.message}). it is likely a stale orphan \u2014 run \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let f=Date.now()-n;f-s>=5e3&&(s=f,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(f/1e3)}s)`)),await m(500)}throw r?.message.startsWith("app failed to load:")?r:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(await Ue("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
36
- const rec = window.__sootsimRecorder
37
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
38
- const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
39
- if (rec.state() === 'recording') return { ok: true, format }
40
- return rec.start({ format, fps: 24 })
41
- })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}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,new Error(t?.error||"recording stop failed");this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.recordingStartedAtMs=null;let n=[],r=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${r}, chunk: 2097152 })`);if(!l||(n.push(Buffer.from(l.data,"base64")),r=l.offset,l.done))break}if(n.length===0)throw new Error("recording requested but no video buffer was produced");v.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",a=g.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${s}`);return v.writeFileSync(a,Buffer.concat(n)),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 m(t);return}let n=await ce({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(n.settled?` [flow] recording tail settled in ${n.elapsed}ms`:` [flow] recording tail reached ${n.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 () => {
42
- const test = window.__sootsimTest
43
- if (!test) return null
44
- let node = null
45
- if (${JSON.stringify(!!e.text)}) {
46
- node = await test.findByText(${JSON.stringify(e.text||"")})
47
- // maestro matches a text selector against the element's ACCESSIBILITY
48
- // text too, not just rendered glyphs \u2014 icon-only buttons (e.g. bluesky's
49
- // "Pin to Home" / "Mute accounts" pin/menu controls) carry the label on
50
- // accessibilityLabel with no visible text node, so findByText misses
51
- // them. fall back to an exact a11y-label match, mirroring the real
52
- // driver. findByLabel resolves a node, but its info shape omits nodeId/
53
- // isTextInput; re-resolve through findByTestId/findById when it exposes
54
- // an id so tapOn still gets a resolveTapTarget-able nodeId.
55
- if (!node) {
56
- const labelled = await test.findByLabel?.(${JSON.stringify(e.text||"")})
57
- if (labelled) {
58
- const reId = labelled.testID || labelled.id
59
- node =
60
- (reId &&
61
- ((await test.findByTestId?.(reId)) || (await test.findById?.(reId)))) ||
62
- labelled
63
- }
64
- }
65
- if (!node && ${JSON.stringify(t)} && test.queryAll) {
66
- // regex selector fallback: match the pattern against each visible
67
- // node's text; prefer the narrowest matching node so a tight <text>
68
- // wins over a wide container that merely contains it.
69
- let re = null
70
- try { re = new RegExp(${JSON.stringify(e.text||"")}) } catch (e) { re = null }
71
- if (re) {
72
- const all = (await test.queryAll({ pruneHidden: true })) || []
73
- const hits = all.filter(
74
- (n) =>
75
- n && n.absolutePosition && n.layout &&
76
- typeof n.text === 'string' && re.test(n.text),
77
- )
78
- hits.sort((a, b) => (a.text || '').length - (b.text || '').length)
79
- if (hits[0]) node = hits[0]
80
- }
81
- }
82
- }
83
- if (!node && ${JSON.stringify(!!e.id)}) {
84
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
85
- }
86
- if (!node || !node.absolutePosition || !node.layout) return null
87
- return {
88
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
89
- id: node.id || null,
90
- testID: node.testID || null,
91
- text: node.text || null,
92
- absolutePosition: node.absolutePosition,
93
- layout: node.layout,
94
- isTextInput: !!node.isTextInput,
95
- }
96
- })()`)}async findElementScoped(e){let t=typeof e.index=="number"?e.index:0;return this.evaluate(`(async () => {
97
- const test = window.__sootsimTest
98
- if (!test || !test.queryAll) return null
99
- // NOT pruneHidden: that over-filters (it dropped every postDropdownBtn in a
100
- // feed and made index:0 resolve to nothing \u2014 worse than findByTestId). reach
101
- // for the same set findByTestId sees, then PREFER on-screen ones below.
102
- const filter = {}
103
- if (${JSON.stringify(!!e.id)}) filter.hasId = ${JSON.stringify(e.id||"")}
104
- if (${JSON.stringify(!!e.text)}) filter.hasText = ${JSON.stringify(e.text||"")}
105
- let candidates = (await test.queryAll(filter)) || []
106
- // a11y-label fallback (icon-only buttons) for text matchers, mirroring
107
- // findElement's simple path.
108
- if (${JSON.stringify(!!e.text)} && candidates.length === 0) {
109
- const all = (await test.queryAll({})) || []
110
- candidates = all.filter((n) => (n.accessibilityLabel || '') === ${JSON.stringify(e.text||"")})
111
- }
112
- candidates = candidates.filter((n) => n && n.absolutePosition && n.layout)
113
- // prefer on-screen matches (findByTestId's visible-first behavior); only
114
- // fall back to off-screen ones when nothing is on-screen, so index: still
115
- // resolves a target that needs scrolling into view.
116
- const onScreen = candidates.filter((n) => {
117
- const cy = n.absolutePosition.y + n.layout.height / 2
118
- return cy > 0 && cy < ${O}
119
- })
120
- if (onScreen.length > 0) candidates = onScreen
121
- ${e.childOf?`
122
- 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||"")})`}
123
- if (!container || !container.absolutePosition || !container.layout) return null
124
- const x0 = container.absolutePosition.x
125
- const y0 = container.absolutePosition.y
126
- const x1 = x0 + container.layout.width
127
- const y1 = y0 + container.layout.height
128
- candidates = candidates.filter((n) => {
129
- const cx = n.absolutePosition.x + n.layout.width / 2
130
- const cy = n.absolutePosition.y + n.layout.height / 2
131
- return cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1
132
- })`:""}
133
- const node = candidates[${t}]
134
- if (!node) return null
135
- return {
136
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
137
- id: node.id || null,
138
- testID: node.testID || null,
139
- text: node.text || null,
140
- absolutePosition: node.absolutePosition,
141
- layout: node.layout,
142
- isTextInput: !!node.isTextInput,
143
- }
144
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
145
- const test = window.__sootsimTest
146
- if (!test?.resolveTapTarget) return null
147
- return await test.resolveTapTarget(${e})
148
- })()`)}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 () => {
149
- const test = window.__sootsimTest
150
- if (!test) return null
151
- 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||"")})`}
152
- let point = null
153
- if (node?.absolutePosition && node?.layout) {
154
- point = {
155
- x: node.absolutePosition.x + node.layout.width / 2,
156
- y: node.absolutePosition.y + node.layout.height / 2,
157
- }
158
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
159
- const resolved = await test.resolveTapTarget(node.nodeId)
160
- if (
161
- resolved &&
162
- Number.isFinite(resolved.cx) &&
163
- Number.isFinite(resolved.cy)
164
- ) {
165
- point = { x: resolved.cx, y: resolved.cy }
166
- }
167
- }
168
- }
169
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
170
- if (direct?.ok && point) {
171
- window.dispatchEvent(
172
- new CustomEvent('sootsim:agentAction', {
173
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
174
- }),
175
- )
176
- }
177
- return direct || null
178
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
179
- const test = window.__sootsimTest
180
- if (!test?.activatePressAt) return null
181
- const direct = await test.activatePressAt(${e}, ${t})
182
- if (direct?.ok) {
183
- window.dispatchEvent(
184
- new CustomEvent('sootsim:agentAction', {
185
- detail: { type: 'tap', x: ${e}, y: ${t} },
186
- }),
187
- )
188
- }
189
- return direct
190
- })()`)}async tap(e,t,n){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:n})}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let l=ue(t.point);(await this.activatePressAt(l.x,l.y))?.ok||await this.tap(l.x,l.y),await m(300);return}let n=5e3,r=150,o=Date.now()+n,s=await this.findElement({text:t.text,id:t.id});for(;!s&&Date.now()<o;)await m(r),s=await this.findElement({text:t.text,id:t.id});if(s){let l=s.isTextInput?4:1;for(let f=0;f<l;f++){let d=f===0?s:await this.findElement({text:t.text,id:t.id});if(!d)break;let h=typeof d.nodeId=="number"?await this.resolveTapTarget(d.nodeId):null,A=h?.cx??d.absolutePosition.x+d.layout.width/2,w=h?.cy??d.absolutePosition.y+d.layout.height/2;if((await this.tap(A,w,{id:t.id??h?.target?.id??d.id??null,testID:t.id??h?.target?.testID??d.testID??null,text:t.text??h?.target?.text??h?.target?.accessibilityLabel??d.text??d.accessibilityLabel??null,type:h?.target?.type??d.type??null}))?.hit===!0){if(await m(300),!d.isTextInput||await this.waitForFocusedTextInput(600,d))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await m(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async tapAtCoords(e,t){await this.tap(e,t),await m(300)}async doubleTapAtCoords(e,t,n=80){let r=Math.max(0,Math.round(n));if(!await this.evaluate(`(async () => {
191
- const interact = window.__sootsimInteract
192
- if (interact?.doubleTap) {
193
- return !!(await interact.doubleTap(${e}, ${t}, ${r}))
194
- }
195
- if (!interact?.tap) return false
196
- const first = await interact.tap(${e}, ${t})
197
- if (!first || first.hit === false) return false
198
- await new Promise((resolve) => setTimeout(resolve, ${r}))
199
- const second = await interact.tap(${e}, ${t})
200
- return !!second && second.hit !== false
201
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await m(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 m(200)}let n=await this.findElement(t),r=n?` (matched node at y=${Math.round(n.absolutePosition.y)} h=${Math.round(n.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${r}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let n=await this.findElement(t),r=n?` at (${Math.round(n.absolutePosition.x)},${Math.round(n.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${r}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<O)}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 m(200)}focusedTextInputMatches(e,t){if(!t||typeof t.nodeId=="number"&&typeof e.nodeId=="number"&&t.nodeId===e.nodeId)return!0;let n=t.testID??null,r=e.testID??null;if(n&&r&&n===r)return!0;let o=t.id??null,s=e.id??null;return!!(o&&s&&o===s)}async waitForFocusedTextInput(e=1500,t){let n=Date.now()+e;for(;Date.now()<n;){try{let r=await this.callTest("getFocusedNode");if(r&&this.focusedTextInputMatches(r,t))return!0}catch{}await m(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await m(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await m(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(`(() => {
202
- const keyboard =
203
- window.__sootsimKeyboard ??
204
- window.SootSim?.bridges?.keyboard ??
205
- null
206
- const test = window.__sootsimTest
207
- return {
208
- visible: !!keyboard?.isVisible?.(),
209
- focused: !!test?.isTextInputFocused?.(),
210
- }
211
- })()`);if(!t?.visible&&!t?.focused){await m(80);return}await m(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 m(100)}async waitFor(e){let t=Date.now()+(e.timeout||K);for(;Date.now()<t;){if(await this.findElement(e))return;await m(200)}let n=await this.findElement(e),r=n?` (matched node y=${Math.round(n.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||K}ms${r}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await m(250)}catch{}let t=wt(e),n=ht(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});v.mkdirSync(g.dirname(n),{recursive:!0});let r=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};r&&r!=="full"&&(o.layers=r);let a=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(a,"base64");if(t.withFrame){let f=await this.readCurrentDeviceModel();if(!f)throw new Error("could not read current device model for framed screenshot");let d=await We(l,f);v.writeFileSync(n,d),console.log(`[flow] screenshot: ${n} (frame: ${f})`);return}v.writeFileSync(n,l),console.log(`[flow] screenshot: ${n}`)}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 Te)?null:t}async captureFailureScreenshot(e){v.mkdirSync(g.dirname(e),{recursive:!0});let n=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");v.writeFileSync(e,Buffer.from(n,"base64"))}async captureFailureBundle(e,t){v.mkdirSync(e,{recursive:!0});let n=(d,h)=>{try{v.writeFileSync(g.join(e,d),h)}catch{}},r=async d=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:d})}catch{return null}},o=await r(`(async () => {
212
- const out = {
213
- simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
214
- url: location.href,
215
- title: document.title,
216
- hidden: document.hidden,
217
- }
218
- try {
219
- const params = new URL(location.href).searchParams
220
- const bundle = params.get('bundle')
221
- if (bundle) {
222
- const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
223
- if (baseMatch) {
224
- const res = await fetch(baseMatch[0] + '/', {
225
- headers: { 'expo-platform': 'ios' },
226
- cache: 'no-store',
227
- })
228
- if (res.ok) {
229
- out.manifest = await res.json().catch(() => null)
230
- }
231
- }
232
- }
233
- } catch {}
234
- return out
235
- })()`);n("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 h=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");n("screenshot.png",Buffer.from(h,"base64"))}catch{}let s=await r(`(async () => {
236
- const t = window.__sootsimTest
237
- const mainShell = window.SootSim?.bridges?.mainShell
238
- if (!t) return { error: 'no test bridge' }
239
- let shell = null
240
- try {
241
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
242
- } catch {}
243
- const all = await t.queryAll({ pruneHidden: true })
244
- return { shell, nodes: all, url: location.href, title: document.title }
245
- })()`);s&&n("describe.json",JSON.stringify(s,null,2));let a=await r("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof a=="string"&&n("a11y.txt",a);let l=await r("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&n("tree.txt",l);let f=await r(`(() => {
246
- const c = window.__sootsimConsole
247
- return {
248
- errors: c?.getErrors?.() ?? [],
249
- warnings: c?.getWarnings?.() ?? [],
250
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
251
- }
252
- })()`);return f&&n("console.json",JSON.stringify(f,null,2)),e}async swipe(e="UP",t=300){let n=q/2,r=O/2,o=200,s=n,a=r,l=n,f=r;switch(e.toUpperCase()){case"UP":a+=o,f-=o;break;case"DOWN":a-=o,f+=o;break;case"LEFT":s+=o,l-=o;break;case"RIGHT":s-=o,l+=o;break}let d=Math.max(10,Math.round(t/16));await this.drag(s,a,l,f,d,16)}async drag(e,t,n,r,o=12,s=16){if(!(await this.evaluate(`(async () => {
253
- const interact = window.__sootsimInteract
254
- if (!interact?.drag) return { ok: false }
255
- const value = await interact.drag(${e}, ${t}, ${n}, ${r}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(s))})
256
- return { ok: !!value, value }
257
- })()`))?.ok)throw new Error("drag failed");await m(300)}async swipeCoords(e,t,n=300){let r=ue(e),o=ue(t),s=Math.max(10,Math.round(n/16));await this.drag(r.x,r.y,o.x,o.y,s,16)}async swipeFrom(e,t="UP",n=300){let r=await this.findElement(e);if(!r)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=r.absolutePosition.x+r.layout.width/2,s=r.absolutePosition.y+r.layout.height/2,a=180,l=o,f=s;switch(t.toUpperCase()){case"UP":f-=a;break;case"DOWN":f+=a;break;case"LEFT":l-=a;break;case"RIGHT":l+=a;break}let d=Math.max(10,Math.round(n/16));await this.drag(o,s,l,f,d,16)}async scrollTo(e,t,n){let r=await this.callTest("scrollTo",e,t,n,!1);if(!r?.ok)throw new Error(`scrollTo failed: ${r?.reason||"unknown error"}`);await m(250)}async pinch(e){let t=await this.evaluate(`(async () => {
258
- const interact = window.__sootsimInteract
259
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
260
- const ok = await interact.pinch(
261
- ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
262
- ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
263
- ${e.steps||12}, ${e.stepMs||16}
264
- )
265
- return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
266
- })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await m(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;(await ce({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled&&this.markVisualSettled()}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),n=e.direction?.toUpperCase()||"DOWN",r=n==="DOWN"?"UP":n==="UP"?"DOWN":n;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<O-50){if(e.centerElement){let s=O/2,a=o.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),f=a>0?s-l:s+l;await this.drag(q/2,s,q/2,f,10,16)}}return}await this.swipe(r,250),await m(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||K);for(;Date.now()<t;){let n=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,r=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(n&&r)return;await m(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let r=!1;for(let o=0;o<3&&!r;o++)try{r=await this.evaluate(oe(!0),2e4)}catch{await m(1e3)}r||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await m(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(oe(e),12e4))throw new Error("guest app soft reload bridge unavailable")}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;){await this.refreshSimId();try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(n){t=n,await m(250)}}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){await this.refreshSimId(),e&&typeof e=="object"&&e.arguments&&console.log("[flow] launchApp.arguments ignored (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),n=ft(e,"resetRuntime");if(!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,n?(this.recordingEnabled&&await this.ensureRecordingStarted(),await this.softReloadGuestApp(!1),await this.launchShellAppFromHomeIfNeeded(e),await this.waitForTree(12e4)):await this.launchShellAppFromHomeIfNeeded(e),await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
267
- requestAnimationFrame(() => {
268
- requestAnimationFrame(() => {
269
- requestAnimationFrame(() => {
270
- setTimeout(resolve, 180)
271
- })
272
- })
273
- })
274
- })`),this.markVisualSettled()}catch{await m(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(fe(e)){let n=B(e,"appId")||B(e,"id");if(n)return n}return pt(t)||"connect"}async waitForShellAppLaunched(e,t){let n=Date.now()+t,r=null;for(;Date.now()<n;){try{r=await ne(this.bridge)}catch{r=null}if(r?.state==="app"&&r.activeApp===e&&r.showSwitcher===!1&&typeof r.launchProgress=="number"&&r.launchProgress>=.98)return;await m(16)}}async launchShellAppFromHomeIfNeeded(e){let t=null;try{t=await ne(this.bridge)}catch{return!1}if(t?.state!=="home"||t.activeApp!=null)return!1;let n=this.resolveShellLaunchAppId(e,t);return this.recordingEnabled&&await this.ensureRecordingStarted(),await Oe(this.bridge,"launchApp",1e3,n),await this.waitForShellAppLaunched(n,1e3),!0}async startProfile(){await this.evaluate(`((sessionKey) => {
275
- const perf = window.__sootsimPerf
276
- const a11y = window.__sootsimA11y
277
- perf?.enableFrameStats?.(true)
278
- perf?.resetFrameStats?.()
279
- a11y?.resetProfile?.()
280
- window[sessionKey] = {
281
- active: true,
282
- mode: window.__sootsimRenderHost ? 'render-worker' : 'main-thread',
283
- lastSamples: [],
284
- startedAt: performance.now(),
285
- }
286
- })(${JSON.stringify(qe)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
287
- const host = window.__sootsimRenderHost
288
- if (host?.flushSamples) {
289
- const perf = window.__sootsimPerf
290
- const session = window[sessionKey] || {}
291
- const priorSamples = session.active && Array.isArray(session.lastSamples)
292
- ? session.lastSamples
293
- : []
294
- const flushedSamples = await host.flushSamples()
295
- await perf?.disableFrameStats?.()
296
- const samples = priorSamples.concat(flushedSamples)
297
- window[sessionKey] = {
298
- ...session,
299
- active: false,
300
- mode: 'render-worker',
301
- lastSamples: samples,
302
- stoppedAt: performance.now(),
303
- }
304
-
305
- const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0)
306
- const sorted = [...frameTimes].sort((a, b) => a - b)
307
- const worstFrames = samples
308
- .slice()
309
- .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
310
- .slice(0, 10)
311
- .map((sample) => [
312
- Number(sample?.[0]) || 0,
313
- Number(sample?.[1]) || 0,
314
- Number(sample?.[2]) || 0,
315
- Number(sample?.[3]) || 0,
316
- Number(sample?.[4]) || 0,
317
- ])
318
-
319
- return {
320
- mode: 'render-worker',
321
- frames: frameTimes.length,
322
- totalMs: frameTimes.reduce((sum, value) => sum + value, 0),
323
- avgMs: frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0,
324
- maxMs: sorted[sorted.length - 1] || 0,
325
- layoutTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
326
- renderTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
327
- copyTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
328
- layoutAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0) / frameTimes.length : 0,
329
- renderAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0) / frameTimes.length : 0,
330
- copyAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0) / frameTimes.length : 0,
331
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
332
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
333
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
334
- jankFrames: frameTimes.filter((value) => value > 16.67).length,
335
- sampleCount: frameTimes.length,
336
- worstFrames,
337
- }
338
- }
339
-
340
- const perf = window.__sootsimPerf
341
- const a11y = window.__sootsimA11y
342
- if (!perf && !a11y) return { error: 'no perf globals available' }
343
-
344
- const stoppedStats = await perf?.disableFrameStats?.()
345
- const frameStats = stoppedStats || await perf?.getFrameStats?.() || {}
346
- const profile = a11y?.profile?.() || {}
347
- const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
348
- const sorted = [...recent].sort((a, b) => a - b)
349
-
350
- return {
351
- mode: 'main-thread',
352
- frames: frameStats.frames || profile.syncCount || 0,
353
- totalMs: frameStats.totalMs || 0,
354
- avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
355
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
356
- layoutTotalMs: frameStats.layoutTotalMs || 0,
357
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
358
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
359
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
360
- jankFrames: recent.filter((value) => value > 16.67).length,
361
- sampleCount: recent.length,
362
- worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
363
- }
364
- })(${JSON.stringify(qe)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,n=await this.findElement(t);if(!n)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let r=n.text??n.testID??"";this.js.setCopiedText(r),this.js.putEnv("maestroCopiedText",r),console.log(`[flow] copied text: ${JSON.stringify(r)}`)}evalScript(e){let n=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);n!==void 0&&n!==""&&console.log("[flow] evalScript ->",n)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let n=g.resolve(this.opts.flowDir,t.file),r=v.readFileSync(n,"utf8");this.js.evaluate(r,{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");let n=await this.callTest("openDeepLink",t);if(!n?.ok)throw new Error(`openLink failed: ${n?.error||"no test bridge"}`);await m(300)}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?Ke(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let n=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),r=n?n[1]:void 0;return!!(r&&typeof r=="object"&&"optional"in r&&r.optional)}async runStep(e,t){let n=typeof e=="string"?gt(e):e,r=Object.keys(n).find(s=>s!=="when")||Object.keys(n)[0];console.log(`[flow] step ${t+1}: ${r}`);let o;try{o=this.js.interpolateStep(n)}catch(s){if(this.isOptional(n)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:n[r]},s}if(o.when&&!await this.evaluateWhen(o.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let s=!!(o.extendedWaitUntil||o.waitFor||o.scrollUntilVisible||o.launchApp||o.runFlow||o.runScript),a=1e4,l=this.runStepInner(o);if(s)await l;else{let d=null,h=new Promise((A,w)=>{d=setTimeout(()=>{w(new Error(`step watchdog: ${r} made no progress in ${a}ms \u2014 bridge or bundle probably hung`))},a)});try{await Promise.race([l,h])}finally{d&&clearTimeout(d)}}let f=!!(o.assertVisible||o.assertNotVisible||o.extendedWaitUntil||o.waitFor);this.stepDelay>0&&!f&&await m(this.stepDelay)}catch(s){if(this.isOptional(o)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:o[r]},s}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);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)await this.takeScreenshot(e.takeScreenshot);else 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 m(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,n=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(n))throw new Error(`repeat.times is not a number: ${t}`);let r=e.repeat.when??e.repeat.condition,o=async()=>r?this.evaluateWhen(r):!0,s=r?n:Math.min(n,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,n=typeof t=="string"?void 0:t.when;if(n&&!await this.evaluateWhen(n)){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,n=typeof t=="string"?t:t.file,r=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): ${n??"inline commands"}`);return}if(!n&&!r)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(n){let a=g.resolve(this.opts.flowDir,n),l=v.readFileSync(a,"utf8"),f=this.opts.flowDir;this.opts.flowDir=g.dirname(a);try{await this.runFlow(yt(l))}finally{this.opts.flowDir=f}}else if(r)for(let a=0;a<r.length;a++)await this.runStep(r[a],a)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],n=[],r=[];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)){n.push(...s.onFlowComplete);continue}r.push(s)}if(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(r)}catch(s){o=s instanceof Error?s:new Error(String(s))}if(n.length>0){console.log(`[flow] onFlowComplete (${n.length} steps)`);for(let s=0;s<n.length;s++)try{await this.runStep(n[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 n=e[t],r=typeof n.wait=="number"?n.wait:0,o=typeof n.waitFor?.timeout=="number"?n.waitFor.timeout:0,s=Math.max(6e4,r+15e3,o+15e3);if(n.runFlow||n.launchApp){await this.runStep(n,t);continue}await Promise.race([this.runStep(n,t),new Promise((a,l)=>setTimeout(()=>l(new Error(`step ${t+1} (${Object.keys(n)[0]}) exceeded ${s}ms deadline`)),s))])}}};async function bt(i){if(!i)return"";let e=i.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let n=(await $e()).find(r=>r.name.toLowerCase()===e.toLowerCase());return n?String(n.preferredPort):e}async function vt(){let i=await ke(),e=i.find(n=>n.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=i[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Ye(i){(i.length===0||i.includes("--help")||i.includes("-h"))&&(console.log(`
365
- sootsim flow \u2014 run flows or manage a draft
366
-
367
- usage:
368
- sootsim flow <flow.yaml> [options]
369
- sootsim flow start
370
- sootsim flow keep
371
- sootsim flow end [--output <path>] [--validate] [--video]
372
- sootsim flow validate <path>
373
-
374
- options:
375
- --record record a webm artifact while the flow runs
376
- --profile capture perf stats while the flow runs
377
- --out <dir> output directory (default: /tmp/sootsim-recordings)
378
- --device <model> override the flow frontmatter device for this run
379
- --slow <ms> delay between steps for natural pacing
380
- --tail-wait <ms> hold the recording open after the last step so the
381
- final UI state is captured (default: smart idle up to
382
- 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
383
- --url <url> load this target before running the flow
384
- --screenshot-paths <mode>
385
- screenshot path mode: dir (default) or flow
386
- --no-shell capture every screenshot tenant-only (no status bar,
387
- keyboard, notification center, or other shell overlays).
388
- use for clean demo asset sets. per-step \`layers:\`
389
- still wins over this default.
390
- --shell-only inverse \u2014 capture shell chrome only
391
- --replace <m>=<f> replace a Metro module with a local file for this run
392
- --new open a fresh sim before running the flow
393
- --driver <id> when paired with --new, launch through a specific
394
- driver from the registry (e.g. playwright for
395
- hermetic CI runs); see 'sootsim list --drivers'
396
- --headless pass headless=true to the launch driver (useful
397
- with --driver playwright)
398
- --headed force a fresh, VISIBLE window for this run (implies
399
- --new; overrides --headless). use when you want to
400
- watch the flow run live even if the current sim is
401
- headless or stale
402
- --electron prefer opening the target in the desktop companion
403
- --sim <id> target a specific current sim
404
- --validate replay the drafted flow before clearing it
405
- --video replay and record the drafted flow before clearing it
406
- --preview record events+video, upload, and print /preview/<id>
407
- --preview-open open the uploaded preview link after a successful run
408
- --preview-origin <url>
409
- upload target for --preview (default: auto)
410
- --preview-public-origin <url>
411
- public link origin for --preview (default: sootsim.com
412
- for prod uploads)
413
- --owner <org> associate preview upload with a linked org repo
414
- --repo <repo> repo name for --owner; user must belong to the team
415
-
416
- frontmatter (top of flow.yaml between --- markers):
417
- app: 8081 load this target before the flow starts
418
- device: iphone-14 set the live device model for this flow run
419
- electron: true prefer the desktop companion sim for this flow
420
-
421
- default runtime:
422
- bridge-backed flow playback against the current sim
423
- if no current sim exists, flow opens the discovered target first
424
- recording and profiling both run on the same bridge-backed path
425
-
426
- examples:
427
- sootsim flow login.yaml
428
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
429
- sootsim flow demo.yaml --sim a2
430
- sootsim flow start
431
- sootsim flow keep
432
- sootsim flow end --output ./flows/draft.yaml
433
- sootsim flow end --output ./flows/draft.yaml --validate
434
- sootsim flow end --output ./flows/draft.yaml --video
435
- sootsim flow validate ./flows/draft.yaml
436
-
437
- flow extension:
438
- takeScreenshot: hero
439
- takeScreenshot:
440
- path: marketing/hero
441
- withFrame: true
442
- `),process.exit(0));let e=i[0];R.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=p=>i.find((u,y)=>i[y-1]===p),n=i.includes("--profile"),r=i.includes("--headed"),o=i.includes("--new")||r,s=t("--out")||"/tmp/sootsim-recordings",a=t("--screenshots")||(t("--out")?s:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",f=i.includes("--no-shell")?"tenant":i.includes("--shell-only")?"shell":void 0,d=t("--device")?.trim()||"",h=i.includes("--slow")?+(t("--slow")||"500"):0,A=i.includes("--electron"),w=i.includes("--preview"),_=await Je(t("--preview-origin")),pe=t("--preview-public-origin"),Xe=i.includes("--preview-open"),me=t("--owner")?.trim()||"",he=t("--repo")?.trim()||"",Ze=i.flatMap((p,u)=>i[u-1]==="--replace"?["--replace",p]:[]),Qe=i.flatMap((p,u)=>i[u-1]==="--remap"?["--remap",p]:[]),I=i.includes("--record")||w,et=i.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):I?w?6e3:2e3:0,tt=R.readFileSync(e,"utf8"),{frontmatter:x,steps:F}=se(tt);F.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let D=d||x.device||"",j=A||x.electron===!0,nt=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,z=await bt(nt),we={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"]},S=re(i,we),rt=t("--url")||"";j&&!_e()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let ge=j?"desktop companion":"bridge",it=z?` | target: ${z}`:"";console.log(`
443
- sootsim flow \u2014 ${b.basename(e)}
444
- ${F.length} steps | ${ge}${it}${I?" | recording":""}${n?" | profiling":""}${h?` | ${h}ms delay`:""}
445
- `),w&&xe({event:"preview_flow_started",properties:{flowName:b.basename(e),stepCount:F.length,mode:ge,electron:j,record:I,profile:n,previewOrigin:_}});let $=rt||z||"",Y=o||j&&S.simIdSource!=="flag",ye=t("--driver")||"",X=!1,Z=new Set,be=!1;if(!$&&!Y&&S.simIdSource==="none"){let p=Pe(S);try{let u=await p.listSims(),y=u.find(U=>U.isPrimary&&U.readyState==="open"),J=u.find(U=>U.readyState==="open"),Se=y??J;Se&&(be=!0,console.log(` reusing active sim: ${Se.id}`))}catch{}finally{p.close()}}if(!$&&!be&&(Y||S.simIdSource==="none")){let p=await vt();p||(console.error(" error: no current sim and no sootsim target found"),await ee(),process.exit(1)),$=p}if($&&D){let p=new URL(await De($));p.searchParams.set("device",D),$=p.toString()}if($){let p=[$];if(p.push(...Ze),p.push(...Qe),Y&&p.push("--new"),p.push("--no-describe"),S.simIdSource==="flag"&&S.simId&&p.push("--sim",S.simId),ye&&(p.push("--driver",ye),X=!0),i.includes("--headless")&&!r&&p.push("--headless"),await Ce(p,{port:S.wsPort,timeoutMs:S.commandTimeoutMs}),X){let u=te();u&&Z.add(u)}}let M=re(i,we),L=M.simIdSource==="flag"?M.simId:te()||M.simId,ot=M.simIdSource==="flag"?"flag":L?"saved":"none",k=ie(M.wsPort,{commandTimeoutMs:M.commandTimeoutMs,simId:L,simIdSource:ot}),c,ve=async()=>{if(!D)return!1;let p=await k.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof p=="string"&&p.length>0){let u=new URL(p);u.searchParams.set("device",D),c.setSimRouteHint(u.toString())}return!!await k.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",D]})};if(c=new G(k,{screenshotDir:a,flowDir:b.dirname(b.resolve(e)),screenshotPathMode:l,screenshotLayers:f,simId:L,recordingOutputDir:I?s:void 0,recordingFormat:w?"mp4":"webm",billingOriginOverride:w?_:void 0,allowGitHubRecording:I,onAfterLaunch:async()=>{await ve()&&await c.waitForTree(12e4),w&&await k.send({type:"evaluate",simId:c.simId,code:`(() => {
446
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
447
- return r?.start?.() ?? false
448
- })()`})}}),h&&(c.stepDelay=h),c.js.putEnv("MAESTRO_FILENAME",b.basename(e,b.extname(e))),x.env&&typeof x.env=="object")for(let[p,u]of Object.entries(x.env))c.js.putEnv(p,u);let E=null,T=null,N=null,Q=null,V=0,W=!!F[0]?.launchApp;try{W||await c.waitForTree(12e4),await ve()&&!W&&await c.waitForTree(12e4),w&&!W&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),I&&(W?c.prepareRecording():await c.startRecording()),n&&await c.startProfile(),w&&(await k.send({type:"evaluate",simId:c.simId,code:`(() => {
449
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
450
- return r?.start?.() ?? false
451
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(F),n&&(E=await c.stopProfile()),await c.waitForRecordingTail({maxMs:et,smart:w}),I&&(T=await c.stopRecording(),N=c.getLastRecordingDurationMs()),w&&(Q=await k.send({type:"evaluate",simId:c.simId,code:`(() => {
452
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
453
- return r?.stop?.() ?? []
454
- })()`}),console.log(` captured ${Q.length} replay events`));let u=F.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
455
- + completed (${F.length} steps)`),u>0&&console.log(` screenshots: ${u} \u2192 ${a}`),E&&Ge(E),T&&console.log(` video: ${T}`),console.log()}catch(p){if(n&&!E)try{E=await c.stopProfile()}catch{}if(I&&!T)try{T=await c.stopRecording(),N=c.getLastRecordingDurationMs()}catch(u){console.warn(` recording stop failed: ${u?.message||String(u)}`)}console.error(`
456
- x failed: ${p.message}
457
- `),E&&(console.log(" partial profile:"),Ge(E)),T&&console.log(` partial video: ${T}`);try{let u=c.lastFailedStep,y=u?`step-${String(u.index+1).padStart(2,"0")}-${u.kind}`:"unstaged",J=b.join(a,y);await c.captureFailureBundle(J,{error:p,stepIndex:u?.index,stepKind:u?.kind,stepTarget:u?.target}),console.log(` failure bundle: ${J}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(u){try{let y=b.join(a,"error.png");await c.captureFailureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${u instanceof Error?u.message:String(u)})`)}await Re(k,{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}finally{k.close()}if(V===0&&w)try{let p=await xt(Q??[]),u=["--origin",_,"--events",p];pe&&u.push("--public-origin",pe),T&&u.push("--video",T),T&&N&&Number.isFinite(N)&&u.push("--video-duration-ms",String(Math.round(N))),c.simId&&u.push("--sim",c.simId),Xe&&u.push("--open"),me&&u.push("--owner",me),he&&u.push("--repo",he),console.log(`
458
- preparing preview upload\u2026`);let{runUpload:y}=await import("./upload-QVDVJ6ZK.js");await y(u,{})}catch(p){console.error(` preview upload failed: ${p?.message||p}`),V=1}return X?(c.simId&&Z.add(c.simId),await St(S.wsPort,S.commandTimeoutMs,[...Z])):c.simId&&c.simId!==L&&Ie(c.simId),await ee(),V}async function St(i,e,t){let n=[...new Set(t.filter(Boolean))];if(n.length===0)return;let r=ie(i,{commandTimeoutMs:e});try{let o=await r.listSims(),s=n.filter(l=>o.some(f=>f.id===l&&f.readyState==="open"));if(s.length===0)return;let a=await Be(r,i,e,s);await Ne(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{r.close()}}async function xt(i){let{gzipSync:e}=await import("zlib"),t=i.map(o=>JSON.stringify(o)).join(`
459
- `)+(i.length?`
460
- `:""),n=e(Buffer.from(t,"utf8")),r=b.join(ze(),`sootsim-events-${Date.now()}.jsonl.gz`);return R.writeFileSync(r,n),console.log(` events: ${i.length} written to ${r} (${n.length} bytes gz)`),r}async function Tt(i){let e=i[0],t=n=>i.find((r,o)=>i[o-1]===n);switch(e){case"start":{let{path:n,state:r}=Le();console.log(" flow draft started"),console.log(` session: ${n}`),console.log(` steps: ${r.steps.length}`);return}case"keep":case"good":{let n=de();if(n.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!n.kept){console.log(" no pending action to keep");return}console.log(` kept: ${n.candidate.summary}`),console.log(` steps: ${n.stepCount}`);return}case"end":{let n=t("--output")||(i[1]&&!i[1].startsWith("-")?i[1]:void 0),r=i.includes("--validate")||i.includes("--video"),o=i.includes("--video"),s=de();s.active&&s.kept&&console.log(` auto-kept trailing action: ${s.candidate.summary}`);let a=Ve(n||(r?$t():void 0));if(a.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(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 flow start` to reset"),process.exit(1)}if(r){let l=kt(i,a.outputPath),f=await Ye(l);if(f!==0){console.error(`
461
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=f;return}le(),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(le(),console.log(` flow draft ended (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath){console.log(` saved: ${a.outputPath}`),console.log(` next: sootsim flow ${a.outputPath} --record`);return}console.log(""),process.stdout.write(a.yaml);return}case"validate":{let n=i[1];(!n||n.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let r=ae(n);if(r.length>0){console.error(` x ${n} failed validation:`);for(let o of r)console.error(` - ${o}`);process.exit(1)}console.log(` + ${n} looks valid`);return}}}function It(i){return i[0]==="--sim"&&i.length>=2?[...i.slice(2),"--sim",i[1]]:i}async function Zt(i){let e=It(i),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Tt(e),0;let n=await Ye(e);return n!==0&&(process.exitCode=n),n}function Ge(i){let e=i.avgMs>0?(1e3/i.avgMs).toFixed(1):"?",t=i.sampleCount>0?(i.jankFrames/i.sampleCount*100).toFixed(1):"0";console.log(`
462
- profile:`),console.log(` frames: ${i.frames}`),console.log(` total: ${i.totalMs.toFixed(1)}ms`),console.log(` avg: ${i.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${i.maxMs.toFixed(2)}ms`),i.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${i.layoutAvgMs.toFixed(2)}ms | render ${i.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${i.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${i.p95.toFixed(2)}ms`),console.log(` p99: ${i.p99.toFixed(2)}ms`),console.log(` jank: ${i.jankFrames}/${i.sampleCount} (${t}%) >16.67ms`);let n=Array.isArray(i.worstFrames)?i.worstFrames:[];if(n.length!==0){if(console.log(`
463
- worst frames:`),i.mode==="render-worker"){console.log(" total layout render copy t+");for(let r of n){let[o,s,a,l,f]=r;console.log(` ${s.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${String(o).padStart(5)}`)}return}console.log(` ${n.map(r=>r.toFixed(2)).join(", ")}`)}}function $t(){return b.join(ze(),`sootsim-flow-draft-${Date.now()}.yaml`)}function kt(i,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let n=1;n<i.length;n++){let r=i[n];if(!(r==="--validate"||r==="--video")){if(r==="--output"){n+=1;continue}n===1&&!r.startsWith("-")||t.push(r)}}return!t.includes("--record")&&i.includes("--video")&&t.push("--record"),t}export{vt as a,Ye as b,It as c,Zt as d};