sootsim 0.1.143 → 0.1.144

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 (150) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-25GIVRCM.js → agent-2OYPRNUE.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-SHRSOH5F.js → agent-wrapper-LPKFMZBN.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-JUWOZS4H.js → app-fonts-3F2X43ER.js} +2 -2
  5. package/dist-cli/chunks/{assert-IVGHPA5A.js → assert-MUUX2DJC.js} +2 -2
  6. package/dist-cli/chunks/auto-bootstrap-EYENX7BT.js +2 -0
  7. package/dist-cli/chunks/beta-2JIATCYM.js +2 -0
  8. package/dist-cli/chunks/{camera-W33RHKCW.js → camera-TBW2MKRE.js} +2 -2
  9. package/dist-cli/chunks/{chunk-34SQBAH2.js → chunk-2OWIXUFA.js} +2 -2
  10. package/dist-cli/chunks/{chunk-GRFBOOAG.js → chunk-2WPNYDSO.js} +1 -1
  11. package/dist-cli/chunks/chunk-3FFDAVGT.js +119 -0
  12. package/dist-cli/chunks/chunk-3LW4V4ZM.js +2 -0
  13. package/dist-cli/chunks/chunk-3ZNPJADG.js +1 -0
  14. package/dist-cli/chunks/{chunk-MREBZSAV.js → chunk-4CPUNUJC.js} +1 -1
  15. package/dist-cli/chunks/{chunk-7SXBQTHJ.js → chunk-6KI36NXX.js} +2 -2
  16. package/dist-cli/chunks/{chunk-JXZNBPSD.js → chunk-73DPWPZU.js} +1 -1
  17. package/dist-cli/chunks/{chunk-HX23DKRO.js → chunk-7R3BK6IY.js} +1 -1
  18. package/dist-cli/chunks/{chunk-XZXF5AYC.js → chunk-A3E5QVUN.js} +1 -1
  19. package/dist-cli/chunks/{chunk-YPMUEFLF.js → chunk-A72YS45Y.js} +1 -1
  20. package/dist-cli/chunks/{chunk-UN3RQBVH.js → chunk-AJKVXCHV.js} +2 -2
  21. package/dist-cli/chunks/{chunk-2BFY6NP3.js → chunk-AKHWKREF.js} +1 -1
  22. package/dist-cli/chunks/{chunk-R6XZO5GZ.js → chunk-AV2DSEYZ.js} +2 -2
  23. package/dist-cli/chunks/{chunk-BAEWF5VG.js → chunk-BBPSMK2D.js} +2 -2
  24. package/dist-cli/chunks/{chunk-4A5DOFDF.js → chunk-BCIZZLCX.js} +1 -1
  25. package/dist-cli/chunks/{chunk-XMMYQPSE.js → chunk-FQBF5HG6.js} +1 -1
  26. package/dist-cli/chunks/{chunk-QU2QUSZJ.js → chunk-FZXVYC4D.js} +2 -2
  27. package/dist-cli/chunks/chunk-GJR32NCU.js +1 -0
  28. package/dist-cli/chunks/{chunk-XXSE44NG.js → chunk-HC43FXK7.js} +2 -2
  29. package/dist-cli/chunks/{chunk-YLR5ZRKX.js → chunk-HVB4FNBH.js} +2 -2
  30. package/dist-cli/chunks/{chunk-DYCX25AE.js → chunk-IAWQFSZ2.js} +2 -2
  31. package/dist-cli/chunks/chunk-KABTL7PQ.js +406 -0
  32. package/dist-cli/chunks/{chunk-K635OII3.js → chunk-KF7TXHAG.js} +3 -3
  33. package/dist-cli/chunks/{chunk-DFKP5F2D.js → chunk-LEWUJGFD.js} +1 -1
  34. package/dist-cli/chunks/{chunk-7TN63AI6.js → chunk-MX66P64S.js} +1 -1
  35. package/dist-cli/chunks/{chunk-BHEMY7ME.js → chunk-PN4QXNKU.js} +2 -2
  36. package/dist-cli/chunks/{chunk-UC432AHL.js → chunk-QHCI5TZ6.js} +1 -1
  37. package/dist-cli/chunks/{chunk-I3YEKOFK.js → chunk-QMTPTQHG.js} +2 -2
  38. package/dist-cli/chunks/{chunk-YSJYN72Y.js → chunk-S6OUYII6.js} +2 -2
  39. package/dist-cli/chunks/{chunk-AAYFZNPR.js → chunk-T5SF5UGY.js} +1 -1
  40. package/dist-cli/chunks/{chunk-VNNV5YRW.js → chunk-TE2SHQPT.js} +1 -1
  41. package/dist-cli/chunks/{chunk-QDGEMD2I.js → chunk-TJXJCYCS.js} +1 -1
  42. package/dist-cli/chunks/{chunk-TPWSHYVO.js → chunk-TKMTONCA.js} +3 -3
  43. package/dist-cli/chunks/{chunk-YTK7ZFAM.js → chunk-TONLJPNX.js} +1 -1
  44. package/dist-cli/chunks/chunk-TVLQMXWV.js +1 -0
  45. package/dist-cli/chunks/{chunk-VVN2YEL6.js → chunk-UGRHYJUA.js} +2 -2
  46. package/dist-cli/chunks/{chunk-HNNOZQPP.js → chunk-UZO6PMW3.js} +2 -2
  47. package/dist-cli/chunks/{chunk-PJNUAUBJ.js → chunk-VFXS73Q6.js} +2 -2
  48. package/dist-cli/chunks/{chunk-NLCQST4G.js → chunk-W4KCLE5O.js} +2 -2
  49. package/dist-cli/chunks/{chunk-HBFZA6VQ.js → chunk-XJVBNNIB.js} +2 -2
  50. package/dist-cli/chunks/{chunk-QJPM3RET.js → chunk-YV6RWCPO.js} +2 -2
  51. package/dist-cli/chunks/{chunk-SWKPSL5W.js → chunk-Z52XC4UA.js} +2 -2
  52. package/dist-cli/chunks/{chunk-2R4BMZ6Z.js → chunk-ZODKBHVK.js} +2 -2
  53. package/dist-cli/chunks/{chunk-YJDPJTJ5.js → chunk-ZRVCZZCT.js} +2 -2
  54. package/dist-cli/chunks/cli-version-YEX2XZ7G.js +2 -0
  55. package/dist-cli/chunks/{compat-4RDLRPPU.js → compat-P64DATYR.js} +3 -3
  56. package/dist-cli/chunks/{config-3MVPTQK6.js → config-TDDQXUS5.js} +2 -2
  57. package/dist-cli/chunks/{control-FVYUXUVP.js → control-SNZMPDL7.js} +2 -2
  58. package/dist-cli/chunks/{cpu-profile-7ZH2O6BN.js → cpu-profile-FR47V42J.js} +2 -2
  59. package/dist-cli/chunks/{daemon-35SSSS4Z.js → daemon-LHJUCC7B.js} +2 -2
  60. package/dist-cli/chunks/{debug-A6KPCY4Y.js → debug-26NR6JCY.js} +3 -3
  61. package/dist-cli/chunks/{detox-2UJ7GS2I.js → detox-F2KTINZX.js} +2 -2
  62. package/dist-cli/chunks/{device-H7UO5Y3Q.js → device-O5COOPDN.js} +2 -2
  63. package/dist-cli/chunks/{diagnose-N2GVYOSJ.js → diagnose-PQMLUCBO.js} +2 -2
  64. package/dist-cli/chunks/drivers-W4SBNM4V.js +2 -0
  65. package/dist-cli/chunks/{electron-CZLJU4MK.js → electron-ZBL3TH2F.js} +3 -3
  66. package/dist-cli/chunks/flow-QREXGRFN.js +2 -0
  67. package/dist-cli/chunks/help-RE6HG3KD.js +2 -0
  68. package/dist-cli/chunks/{hints-6EUSL5M3.js → hints-DWE4FKYR.js} +2 -2
  69. package/dist-cli/chunks/{home-paths-O66RZCQB.js → home-paths-N2S32DRH.js} +2 -2
  70. package/dist-cli/chunks/{inspect-PI7TIHTS.js → inspect-J3BLUHGJ.js} +3 -3
  71. package/dist-cli/chunks/install-NLKZNPCO.js +2 -0
  72. package/dist-cli/chunks/{install-desktop-MTUTQFM2.js → install-desktop-73H4DAAH.js} +3 -3
  73. package/dist-cli/chunks/{keys-FHLYPKGB.js → keys-R42T6X3W.js} +2 -2
  74. package/dist-cli/chunks/{launch-4Y77LAZZ.js → launch-QGDSUNDW.js} +3 -3
  75. package/dist-cli/chunks/{login-CM7CTLRY.js → login-BYCX25K6.js} +4 -4
  76. package/dist-cli/chunks/{logout-U6ADFOLS.js → logout-TZJXACIH.js} +2 -2
  77. package/dist-cli/chunks/{maestro-CIEC2573.js → maestro-VPK6R5NN.js} +2 -2
  78. package/dist-cli/chunks/optional-demo-registry-UH3YM447.js +2 -0
  79. package/dist-cli/chunks/{preview-TBLTTHD5.js → preview-GJ7MVSHM.js} +2 -2
  80. package/dist-cli/chunks/{profile-KUBUPLTD.js → profile-2RAV3UZS.js} +2 -2
  81. package/dist-cli/chunks/{react-DKVACIO3.js → react-QE7UHEFS.js} +2 -2
  82. package/dist-cli/chunks/{record-VLV2V7SN.js → record-YYL4A7DO.js} +2 -2
  83. package/dist-cli/chunks/runtime-C4CLOL7U.js +2 -0
  84. package/dist-cli/chunks/{runtime-delivery-JXJLNWVF.js → runtime-delivery-2G4PGXGK.js} +2 -2
  85. package/dist-cli/chunks/{screenshot-7QCTJTD4.js → screenshot-BIVF76SC.js} +2 -2
  86. package/dist-cli/chunks/{screenshot-mode-GJAESKSM.js → screenshot-mode-OKAH3ZLK.js} +2 -2
  87. package/dist-cli/chunks/{screenshots-43LUBWAM.js → screenshots-AVJANXAQ.js} +2 -2
  88. package/dist-cli/chunks/{server-7SWPNQR7.js → server-6SFAUUGK.js} +3 -3
  89. package/dist-cli/chunks/setup-repo-CRCQPW3Y.js +2 -0
  90. package/dist-cli/chunks/{skills-O2EXQOQN.js → skills-7APKWTBO.js} +2 -2
  91. package/dist-cli/chunks/{start-W74HSVN6.js → start-2GETTWND.js} +4 -4
  92. package/dist-cli/chunks/store-YFAIUHAS.js +2 -0
  93. package/dist-cli/chunks/telemetry-LUP4L5RW.js +2 -0
  94. package/dist-cli/chunks/{test-LTDFFPPX.js → test-V5HHXSKL.js} +3 -3
  95. package/dist-cli/chunks/{three-mode-RXT6PH5B.js → three-mode-UVIEP3CE.js} +2 -2
  96. package/dist-cli/chunks/{timeline-PETWH7FT.js → timeline-HVEKSWHF.js} +2 -2
  97. package/dist-cli/chunks/{upgrade-OVR52N6Q.js → upgrade-FRHXNAYO.js} +2 -2
  98. package/dist-cli/chunks/upload-NWHZULFU.js +2 -0
  99. package/dist-cli/chunks/{version-JKXXLSJL.js → version-CBDBUHCC.js} +2 -2
  100. package/dist-cli/chunks/{web-QZTGXJE5.js → web-DMUBG5QR.js} +2 -2
  101. package/dist-cli/chunks/{what-happened-X2VG2PJO.js → what-happened-3J4DEIRJ.js} +2 -2
  102. package/dist-cli/chunks/{whoami-YF6SXJQ5.js → whoami-BSPU6JP4.js} +2 -2
  103. package/dist-lib/agent-daemon-client.cjs +1 -1
  104. package/dist-lib/agent-events.cjs +1 -1
  105. package/dist-lib/agent-sessions.cjs +1 -1
  106. package/dist-lib/attached-projects.cjs +1 -1
  107. package/dist-lib/auth/shared-session.cjs +1 -1
  108. package/dist-lib/backend-origin.cjs +1 -1
  109. package/dist-lib/beta.cjs +1 -1
  110. package/dist-lib/beta.mjs +1 -1
  111. package/dist-lib/bridge-constants.cjs +1 -1
  112. package/dist-lib/cli-constants.cjs +1 -1
  113. package/dist-lib/config.cjs +1 -1
  114. package/dist-lib/detox/index.cjs +1 -1
  115. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  116. package/dist-lib/home-paths.cjs +1 -1
  117. package/dist-lib/host/bridge-host.cjs +1 -1
  118. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  119. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  120. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  121. package/dist-lib/host/websocket-proxy.cjs +1 -1
  122. package/dist-lib/index.cjs +1 -1
  123. package/dist-lib/metro.cjs +1 -1
  124. package/dist-lib/profiles.cjs +1 -1
  125. package/dist-lib/render-mode.cjs +1 -1
  126. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  127. package/dist-lib/sdk.cjs +1 -1
  128. package/dist-lib/sdk.mjs +1 -1
  129. package/dist-lib/skills.cjs +81 -20
  130. package/dist-lib/vite.cjs +1 -1
  131. package/package.json +1 -1
  132. package/dist-cli/chunks/auto-bootstrap-GYRB6UPD.js +0 -2
  133. package/dist-cli/chunks/beta-5KJOURFA.js +0 -2
  134. package/dist-cli/chunks/chunk-7SBHZLQW.js +0 -406
  135. package/dist-cli/chunks/chunk-A2ZAQHNC.js +0 -1
  136. package/dist-cli/chunks/chunk-BJNIH4HL.js +0 -119
  137. package/dist-cli/chunks/chunk-GY6MAFMV.js +0 -2
  138. package/dist-cli/chunks/chunk-NGA4DA7H.js +0 -1
  139. package/dist-cli/chunks/chunk-X3H76FTW.js +0 -1
  140. package/dist-cli/chunks/cli-version-G27CVTU4.js +0 -2
  141. package/dist-cli/chunks/drivers-LZZBBF46.js +0 -2
  142. package/dist-cli/chunks/flow-D64O66ME.js +0 -2
  143. package/dist-cli/chunks/help-H6K3SYVG.js +0 -2
  144. package/dist-cli/chunks/install-4VWYAR7Y.js +0 -2
  145. package/dist-cli/chunks/optional-demo-registry-BONZAQPP.js +0 -2
  146. package/dist-cli/chunks/runtime-H6MVUEU5.js +0 -2
  147. package/dist-cli/chunks/setup-repo-7FNZWY7U.js +0 -2
  148. package/dist-cli/chunks/store-F4YJGQBN.js +0 -2
  149. package/dist-cli/chunks/telemetry-OUIYC7UJ.js +0 -2
  150. package/dist-cli/chunks/upload-CCWGR633.js +0 -2
@@ -1,406 +0,0 @@
1
- /*! sootsim v0.1.143 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as Oe}from"./chunk-YJDPJTJ5.js";import{a as Re}from"./chunk-BHEMY7ME.js";import{a as Ce}from"./chunk-R6XZO5GZ.js";import{a as B,b as xe,c as ie,d as ne,e as Te,f as oe,h as se,i as $e,j as Fe}from"./chunk-PJNUAUBJ.js";import{g as Ie,n as Pe,p as Ae,t as _e}from"./chunk-QU2QUSZJ.js";import{e as Ee}from"./chunk-UN3RQBVH.js";import{m as Se}from"./chunk-I3YEKOFK.js";import{c as te,d as re,e as ve}from"./chunk-34SQBAH2.js";import{a as ke}from"./chunk-QDGEMD2I.js";import{a as Me}from"./chunk-AAYFZNPR.js";import{d as ee}from"./chunk-MREBZSAV.js";import{a as ye,b as Q}from"./chunk-2R4BMZ6Z.js";import{f as be}from"./chunk-YPMUEFLF.js";import*as A from"fs";import{tmpdir as Be}from"os";import*as w from"path";import*as g from"fs";import*as f from"path";import{spawnSync as Xe}from"child_process";import*as P from"vm";var Ze=3e5,Qe=`
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(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let r={...process.env};for(let a of Object.keys(r))(a.startsWith("BUN_INSPECT")||a==="NODE_OPTIONS")&&delete r[a];let i=Xe(process.execPath,["-e",Qe],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Ze,maxBuffer:64*1024*1024,env:r});if(i.error)throw new Error(`http ${e} ${n} failed: ${i.error.message}`);let o;try{o=JSON.parse(i.stdout||"")}catch{throw new Error(`http ${e} ${n} failed: no response (${(i.stderr||"").trim().slice(0,200)})`)}let s=o;if(s.__error)throw new Error(`http ${e} ${n} failed: ${s.__error}`);return s}var et=/(?<!\\)\$\{([^$]*)\}/g,tt=/\\(\$\{[^$]*\})/g,rt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,V=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??(i=>console.log(`[flow] js: ${i}`)),r={output:this.output,maestro:this.maestro,http:{get:(i,o)=>C(i,"GET",o),post:(i,o)=>C(i,"POST",o),put:(i,o)=>C(i,"PUT",o),delete:(i,o)=>C(i,"DELETE",o),request:(i,o)=>C(i,(o?.method??"GET").toUpperCase(),o)},console:{log:(...i)=>t(i.map(o=>typeof o=="string"?o:Ne(o)).join(" "))}};this.context=P.createContext(r),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[i,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(i,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[i,o]of Object.entries(r))this.envBinding.set(i,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,r]of this.envBinding)try{e[t]=r,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(et,(r,i)=>{if(i.trim().length===0)return"";let o=this.evaluate(i);if(o===void 0&&rt.test(i.trim()))throw new Error(`missing variable for flow placeholder: ${i.trim()}`);return Ne(o)}).replace(tt,(r,i)=>i)}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,i])=>[r,this.interpolateValue(i,r)])):e}};function Ne(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}function De(n){if(n==null)return!1;if(typeof n=="boolean")return n;let e=String(n);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 U=1e4,W=393,R=852,je="__sootsimCliPerf";function p(n){return new Promise(e=>setTimeout(e,n))}function it(n){return n?f.basename(n)===".maestro"?f.dirname(n):n:process.cwd()}function nt(n,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(f.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():it(t.flowDir);return f.resolve(i,r)}return f.join(n,r)}function ot(n){if(typeof n=="string")return{path:n,withFrame:!1};let e=n.path?.trim()||n.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:n.withFrame===!0,layers:n.layers}}function ae(n){let[e,t]=n.split(",").map(i=>i.trim()),r=(i,o)=>i.endsWith("%")?Number.parseFloat(i)/100*o:Number.parseFloat(i);return{x:r(e,W),y:r(t,R)}}function st(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,r=xe.parse(t);return Array.isArray(r)?r:[]}var J=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new V({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingDurationMs=null;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 r=t.searchParams.toString();return`${t.origin}${t.pathname}${r?`?${r}`:""}`}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 i=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!i)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),s=e.find(l=>l.readyState==="open"),a=i??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=U){let t=Date.now()+e,r=Date.now(),i=null,o=0,s=0;for(;Date.now()<t;){try{let l=await this.evaluate(`(async () => {
36
- const test = window.__sootsimTest
37
- if (!test) return { count: 0, loading: true }
38
- const count = (await test.getNodeCount?.()) || 0
39
- const external = globalThis.__sootsimExternalAppState
40
- if (external?.error) {
41
- return { count, loading: false, error: String(external.error) }
42
- }
43
- if (external) {
44
- return {
45
- count,
46
- loading: !external.ready,
47
- error: null,
48
- }
49
- }
50
- const loadingNode = await test.findByText?.('loading')
51
- const capturingNode = await test.findByText?.('capturing')
52
- const openingAppNode = await test.findByText?.('opening app')
53
- const isLoading = !!loadingNode || !!capturingNode || !!openingAppNode || count < 5
54
- return { count, loading: isLoading, error: null }
55
- })()`,8e3);if(o=0,l?.error)throw new Error(`app failed to load: ${l.error}`);if(l&&l.count>10&&!l.loading)return}catch(l){if(i=l instanceof Error?l:new Error(String(l)),i.message.startsWith("app failed to load:"))throw i;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${i.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 a=Date.now()-r;a-s>=5e3&&(s=a,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(a/1e3)}s)`)),await p(500)}throw i?.message.startsWith("app failed to load:")?i: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 Re("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
56
- const rec = window.__sootsimRecorder
57
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
58
- const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
59
- if (rec.state() === 'recording') return { ok: true, format }
60
- return rec.start({ format, fps: 24 })
61
- })()`);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 r=[],i=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),i=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");g.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",a=f.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${s}`);return g.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 p(t);return}let r=await Fe({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){return this.evaluate(`(async () => {
62
- const test = window.__sootsimTest
63
- if (!test) return null
64
- let node = null
65
- if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
66
- if (!node && ${JSON.stringify(!!e.id)}) {
67
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
68
- }
69
- if (!node || !node.absolutePosition || !node.layout) return null
70
- return {
71
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
72
- id: node.id || null,
73
- testID: node.testID || null,
74
- text: node.text || null,
75
- absolutePosition: node.absolutePosition,
76
- layout: node.layout,
77
- isTextInput: !!node.isTextInput,
78
- }
79
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
80
- const test = window.__sootsimTest
81
- if (!test?.resolveTapTarget) return null
82
- return await test.resolveTapTarget(${e})
83
- })()`)}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 () => {
84
- const test = window.__sootsimTest
85
- if (!test) return null
86
- 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||"")})`}
87
- let point = null
88
- if (node?.absolutePosition && node?.layout) {
89
- point = {
90
- x: node.absolutePosition.x + node.layout.width / 2,
91
- y: node.absolutePosition.y + node.layout.height / 2,
92
- }
93
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
94
- const resolved = await test.resolveTapTarget(node.nodeId)
95
- if (
96
- resolved &&
97
- Number.isFinite(resolved.cx) &&
98
- Number.isFinite(resolved.cy)
99
- ) {
100
- point = { x: resolved.cx, y: resolved.cy }
101
- }
102
- }
103
- }
104
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
105
- if (direct?.ok && point) {
106
- window.dispatchEvent(
107
- new CustomEvent('sootsim:agentAction', {
108
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
109
- }),
110
- )
111
- }
112
- return direct || null
113
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
114
- const test = window.__sootsimTest
115
- if (!test?.activatePressAt) return null
116
- const direct = await test.activatePressAt(${e}, ${t})
117
- if (direct?.ok) {
118
- window.dispatchEvent(
119
- new CustomEvent('sootsim:agentAction', {
120
- detail: { type: 'tap', x: ${e}, y: ${t} },
121
- }),
122
- )
123
- }
124
- return direct
125
- })()`)}async tap(e,t,r){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:r})}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let l=ae(t.point);(await this.activatePressAt(l.x,l.y))?.ok||await this.tap(l.x,l.y),await p(300);return}let r=5e3,i=150,o=Date.now()+r,s=await this.findElement({text:t.text,id:t.id});for(;!s&&Date.now()<o;)await p(i),s=await this.findElement({text:t.text,id:t.id});if(s){let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,m=l?.cx??s.absolutePosition.x+s.layout.width/2,h=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(m,h,{id:t.id??l?.target?.id??s.id??null,testID:t.id??l?.target?.testID??s.testID??null,text:t.text??l?.target?.text??l?.target?.accessibilityLabel??s.text??s.accessibilityLabel??null,type:l?.target?.type??s.type??null}))?.hit===!0){await p(300);return}}if((await this.activatePressTarget(t))?.ok){await p(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async tapAtCoords(e,t){await this.tap(e,t),await p(300)}async doubleTapAtCoords(e,t,r=80){let i=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
126
- const interact = window.__sootsimInteract
127
- if (interact?.doubleTap) {
128
- return !!(await interact.doubleTap(${e}, ${t}, ${i}))
129
- }
130
- if (!interact?.tap) return false
131
- const first = await interact.tap(${e}, ${t})
132
- if (!first || first.hit === false) return false
133
- await new Promise((resolve) => setTimeout(resolve, ${i}))
134
- const second = await interact.tap(${e}, ${t})
135
- return !!second && second.hit !== false
136
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await p(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 p(200)}let r=await this.findElement(t),i=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${i}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let r=await this.findElement(t),i=r?` at (${Math.round(r.absolutePosition.x)},${Math.round(r.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${i}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<R)}async inputText(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await p(200)}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await p(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await p(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(`(() => {
137
- const keyboard =
138
- window.__sootsimKeyboard ??
139
- window.SootSim?.bridges?.keyboard ??
140
- null
141
- const test = window.__sootsimTest
142
- return {
143
- visible: !!keyboard?.isVisible?.(),
144
- focused: !!test?.isTextInputFocused?.(),
145
- }
146
- })()`);if(!t?.visible&&!t?.focused){await p(80);return}await p(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.pressKey("Backspace");await p(100)}async waitFor(e){let t=Date.now()+(e.timeout||U);for(;Date.now()<t;){if(await this.findElement(e))return;await p(200)}let r=await this.findElement(e),i=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||U}ms${i}`)}async takeScreenshot(e){try{await this.waitForVisualSettle()}catch{}await p(250);let t=ot(e),r=nt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});g.mkdirSync(f.dirname(r),{recursive:!0});let i=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};i&&i!=="full"&&(o.layers=i);let a=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(a,"base64");if(t.withFrame){let m=await this.readCurrentDeviceModel();if(!m)throw new Error("could not read current device model for framed screenshot");let h=await Oe(l,m);g.writeFileSync(r,h),console.log(`[flow] screenshot: ${r} (frame: ${m})`);return}g.writeFileSync(r,l),console.log(`[flow] screenshot: ${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 be)?null:t}async captureFailureScreenshot(e){g.mkdirSync(f.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");g.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){g.mkdirSync(e,{recursive:!0});let r=(h,S)=>{try{g.writeFileSync(f.join(e,h),S)}catch{}},i=async h=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:h})}catch{return null}},o=await i(`(async () => {
147
- const out = {
148
- simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
149
- url: location.href,
150
- title: document.title,
151
- hidden: document.hidden,
152
- }
153
- try {
154
- const params = new URL(location.href).searchParams
155
- const bundle = params.get('bundle')
156
- if (bundle) {
157
- const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
158
- if (baseMatch) {
159
- const res = await fetch(baseMatch[0] + '/', {
160
- headers: { 'expo-platform': 'ios' },
161
- cache: 'no-store',
162
- })
163
- if (res.ok) {
164
- out.manifest = await res.json().catch(() => null)
165
- }
166
- }
167
- }
168
- } catch {}
169
- return out
170
- })()`);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 S=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(S,"base64"))}catch{}let s=await i(`(async () => {
171
- const t = window.__sootsimTest
172
- const mainShell = window.SootSim?.bridges?.mainShell
173
- if (!t) return { error: 'no test bridge' }
174
- let shell = null
175
- try {
176
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
177
- } catch {}
178
- const all = await t.queryAll({ pruneHidden: true })
179
- return { shell, nodes: all, url: location.href, title: document.title }
180
- })()`);s&&r("describe.json",JSON.stringify(s,null,2));let a=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof a=="string"&&r("a11y.txt",a);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let m=await i(`(() => {
181
- const c = window.__sootsimConsole
182
- return {
183
- errors: c?.getErrors?.() ?? [],
184
- warnings: c?.getWarnings?.() ?? [],
185
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
186
- }
187
- })()`);return m&&r("console.json",JSON.stringify(m,null,2)),e}async swipe(e="UP",t=300){let r=W/2,i=R/2,o=200,s=r,a=i,l=r,m=i;switch(e.toUpperCase()){case"UP":a+=o,m-=o;break;case"DOWN":a-=o,m+=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,m,h,16)}async drag(e,t,r,i,o=12,s=16){if(!(await this.evaluate(`(async () => {
188
- const interact = window.__sootsimInteract
189
- if (!interact?.drag) return { ok: false }
190
- const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(s))})
191
- return { ok: !!value, value }
192
- })()`))?.ok)throw new Error("drag failed");await p(300)}async swipeCoords(e,t,r=300){let i=ae(e),o=ae(t),s=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,o.x,o.y,s,16)}async swipeFrom(e,t="UP",r=300){let i=await this.findElement(e);if(!i)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=i.absolutePosition.x+i.layout.width/2,s=i.absolutePosition.y+i.layout.height/2,a=180,l=o,m=s;switch(t.toUpperCase()){case"UP":m-=a;break;case"DOWN":m+=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,m,h,16)}async scrollTo(e,t,r){let i=await this.callTest("scrollTo",e,t,r,!1);if(!i?.ok)throw new Error(`scrollTo failed: ${i?.reason||"unknown error"}`);await p(250)}async pinch(e){let t=await this.evaluate(`(async () => {
193
- const interact = window.__sootsimInteract
194
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
195
- const ok = await interact.pinch(
196
- ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
197
- ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
198
- ${e.steps||12}, ${e.stepMs||16}
199
- )
200
- return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
201
- })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await p(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){await p(e)}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",i=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<R-50){if(e.centerElement){let s=R/2,a=o.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),m=a>0?s-l:s+l;await this.drag(W/2,s,W/2,m,10,16)}}return}await this.swipe(i,250),await p(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||U);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,i=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&i)return;await p(200)}throw new Error("extendedWaitUntil timed out")}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);if(t&&await this.evaluate(B,6e4),!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.evaluate("window.location.reload()").catch(()=>{}),await p(500),await this.refreshSimId(),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) => {
202
- requestAnimationFrame(() => {
203
- requestAnimationFrame(() => {
204
- requestAnimationFrame(() => {
205
- setTimeout(resolve, 180)
206
- })
207
- })
208
- })
209
- })`)}catch{await p(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
210
- const perf = window.__sootsimPerf
211
- const a11y = window.__sootsimA11y
212
- perf?.enableFrameStats?.(true)
213
- perf?.resetFrameStats?.()
214
- a11y?.resetProfile?.()
215
- window[sessionKey] = {
216
- active: true,
217
- mode: window.__sootsimRenderHost ? 'render-worker' : 'main-thread',
218
- lastSamples: [],
219
- startedAt: performance.now(),
220
- }
221
- })(${JSON.stringify(je)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
222
- const host = window.__sootsimRenderHost
223
- if (host?.flushSamples) {
224
- const perf = window.__sootsimPerf
225
- const session = window[sessionKey] || {}
226
- const priorSamples = session.active && Array.isArray(session.lastSamples)
227
- ? session.lastSamples
228
- : []
229
- const flushedSamples = await host.flushSamples()
230
- await perf?.disableFrameStats?.()
231
- const samples = priorSamples.concat(flushedSamples)
232
- window[sessionKey] = {
233
- ...session,
234
- active: false,
235
- mode: 'render-worker',
236
- lastSamples: samples,
237
- stoppedAt: performance.now(),
238
- }
239
-
240
- const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0)
241
- const sorted = [...frameTimes].sort((a, b) => a - b)
242
- const worstFrames = samples
243
- .slice()
244
- .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
245
- .slice(0, 10)
246
- .map((sample) => [
247
- Number(sample?.[0]) || 0,
248
- Number(sample?.[1]) || 0,
249
- Number(sample?.[2]) || 0,
250
- Number(sample?.[3]) || 0,
251
- Number(sample?.[4]) || 0,
252
- ])
253
-
254
- return {
255
- mode: 'render-worker',
256
- frames: frameTimes.length,
257
- totalMs: frameTimes.reduce((sum, value) => sum + value, 0),
258
- avgMs: frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0,
259
- maxMs: sorted[sorted.length - 1] || 0,
260
- layoutTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
261
- renderTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
262
- copyTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
263
- layoutAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0) / frameTimes.length : 0,
264
- renderAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0) / frameTimes.length : 0,
265
- copyAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0) / frameTimes.length : 0,
266
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
267
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
268
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
269
- jankFrames: frameTimes.filter((value) => value > 16.67).length,
270
- sampleCount: frameTimes.length,
271
- worstFrames,
272
- }
273
- }
274
-
275
- const perf = window.__sootsimPerf
276
- const a11y = window.__sootsimA11y
277
- if (!perf && !a11y) return { error: 'no perf globals available' }
278
-
279
- const stoppedStats = await perf?.disableFrameStats?.()
280
- const frameStats = stoppedStats || await perf?.getFrameStats?.() || {}
281
- const profile = a11y?.profile?.() || {}
282
- const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
283
- const sorted = [...recent].sort((a, b) => a - b)
284
-
285
- return {
286
- mode: 'main-thread',
287
- frames: frameStats.frames || profile.syncCount || 0,
288
- totalMs: frameStats.totalMs || 0,
289
- avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
290
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
291
- layoutTotalMs: frameStats.layoutTotalMs || 0,
292
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
293
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
294
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
295
- jankFrames: recent.filter((value) => value > 16.67).length,
296
- sampleCount: recent.length,
297
- worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
298
- }
299
- })(${JSON.stringify(je)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
300
- try { await (${B}) } catch {}
301
- try {
302
- const regs = await navigator.serviceWorker?.getRegistrations?.()
303
- await Promise.all((regs || []).map((reg) => reg.unregister()))
304
- } catch {}
305
- })()`)}async clearState(){await this.evaluate(`(async () => {
306
- await (${B})
307
- })()`)}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,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let i=r.text??r.testID??"";this.js.setCopiedText(i),this.js.putEnv("maestroCopiedText",i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}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=f.resolve(this.opts.flowDir,t.file),i=g.readFileSync(r,"utf8");this.js.evaluate(i,{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 r=await this.callTest("openDeepLink",t);if(!r?.ok)throw new Error(`openLink failed: ${r?.error||"no test bridge"}`);await p(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?De(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),i=r?r[1]:void 0;return!!(i&&typeof i=="object"&&"optional"in i&&i.optional)}async runStep(e,t){let r=Object.keys(e).find(o=>o!=="when")||Object.keys(e)[0];console.log(`[flow] step ${t+1}: ${r}`);let i;try{i=this.js.interpolateStep(e)}catch(o){if(this.isOptional(e)){console.log(`[flow] (optional, skipped: ${o.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:e[r]},o}if(i.when&&!await this.evaluateWhen(i.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let o=!!(i.extendedWaitUntil||i.waitFor||i.scrollUntilVisible||i.launchApp||i.runFlow||i.runScript),s=1e4,a=this.runStepInner(i);if(o)await a;else{let m=null,h=new Promise((S,K)=>{m=setTimeout(()=>{K(new Error(`step watchdog: ${r} made no progress in ${s}ms \u2014 bridge or bundle probably hung`))},s)});try{await Promise.race([a,h])}finally{m&&clearTimeout(m)}}let l=!!(i.assertVisible||i.assertNotVisible||i.extendedWaitUntil||i.waitFor);this.stepDelay>0&&!l&&await p(this.stepDelay)}catch(o){if(this.isOptional(i)){console.log(`[flow] (optional, skipped: ${o.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:i[r]},o}}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)await this.waitForAnimationToEnd(typeof e.waitForAnimationToEnd=="number"?e.waitForAnimationToEnd: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 p(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){let t=Number(e.repeat.times);if(!Number.isFinite(t))throw new Error(`repeat.times is not a number: ${e.repeat.times}`);for(let r=0;r<t;r++)for(let i=0;i<e.repeat.commands.length;i++)await this.runStep(e.repeat.commands[i],i)}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,i=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&&!i)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=f.resolve(this.opts.flowDir,r),l=g.readFileSync(a,"utf8"),m=this.opts.flowDir;this.opts.flowDir=f.dirname(a);try{await this.runFlow(st(l))}finally{this.opts.flowDir=m}}else if(i)for(let a=0;a<i.length;a++)await this.runStep(i[a],a)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],r=[],i=[];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}i.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(i)}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],i=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,s=Math.max(6e4,i+15e3,o+15e3);if(r.runFlow||r.launchApp){await this.runStep(r,t);continue}await Promise.race([this.runStep(r,t),new Promise((a,l)=>setTimeout(()=>l(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}}};async function at(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let r=(await ke()).find(i=>i.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function lt(){let n=await Ee(),e=n.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Ve(n){(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
308
- sootsim flow \u2014 run flows or manage a draft
309
-
310
- usage:
311
- sootsim flow <flow.yaml> [options]
312
- sootsim flow start
313
- sootsim flow keep
314
- sootsim flow end [--output <path>] [--validate] [--video]
315
- sootsim flow validate <path>
316
-
317
- options:
318
- --record record a webm artifact while the flow runs
319
- --profile capture perf stats while the flow runs
320
- --out <dir> output directory (default: /tmp/sootsim-recordings)
321
- --device <model> override the flow frontmatter device for this run
322
- --slow <ms> delay between steps for natural pacing
323
- --tail-wait <ms> hold the recording open after the last step so the
324
- final UI state is captured (default: smart idle up to
325
- 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
326
- --url <url> load this target before running the flow
327
- --screenshot-paths <mode>
328
- screenshot path mode: dir (default) or flow
329
- --no-shell capture every screenshot tenant-only (no status bar,
330
- keyboard, notification center, or other shell overlays).
331
- use for clean demo asset sets. per-step \`layers:\`
332
- still wins over this default.
333
- --shell-only inverse \u2014 capture shell chrome only
334
- --replace <m>=<f> replace a Metro module with a local file for this run
335
- --new open a fresh sim before running the flow
336
- --driver <id> when paired with --new, launch through a specific
337
- driver from the registry (e.g. playwright for
338
- hermetic CI runs); see 'sootsim list --drivers'
339
- --headless pass headless=true to the launch driver (useful
340
- with --driver playwright)
341
- --headed force a fresh, VISIBLE window for this run (implies
342
- --new; overrides --headless). use when you want to
343
- watch the flow run live even if the current sim is
344
- headless or stale
345
- --electron prefer opening the target in the desktop companion
346
- --sim <id> target a specific current sim
347
- --validate replay the drafted flow before clearing it
348
- --video replay and record the drafted flow before clearing it
349
- --preview record events+video, upload, and print /preview/<id>
350
- --preview-open open the uploaded preview link after a successful run
351
- --preview-origin <url>
352
- upload target for --preview (default: auto)
353
- --preview-public-origin <url>
354
- public link origin for --preview (default: sootsim.com
355
- for prod uploads)
356
- --owner <org> associate preview upload with a linked org repo
357
- --repo <repo> repo name for --owner; user must belong to the team
358
-
359
- frontmatter (top of flow.yaml between --- markers):
360
- app: 8081 load this target before the flow starts
361
- device: iphone-14 set the live device model for this flow run
362
- electron: true prefer the desktop companion sim for this flow
363
-
364
- default runtime:
365
- bridge-backed flow playback against the current sim
366
- if no current sim exists, flow opens the discovered target first
367
- recording and profiling both run on the same bridge-backed path
368
-
369
- examples:
370
- sootsim flow login.yaml
371
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
372
- sootsim flow demo.yaml --sim a2
373
- sootsim flow start
374
- sootsim flow keep
375
- sootsim flow end --output ./flows/draft.yaml
376
- sootsim flow end --output ./flows/draft.yaml --validate
377
- sootsim flow end --output ./flows/draft.yaml --video
378
- sootsim flow validate ./flows/draft.yaml
379
-
380
- flow extension:
381
- takeScreenshot: hero
382
- takeScreenshot:
383
- path: marketing/hero
384
- withFrame: true
385
- `),process.exit(0));let e=n[0];A.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=u=>n.find((c,y)=>n[y-1]===u),r=n.includes("--profile"),i=n.includes("--headed"),o=n.includes("--new")||i,s=t("--out")||"/tmp/sootsim-recordings",a=t("--screenshots")||(t("--out")?s:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",m=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,h=t("--device")?.trim()||"",S=n.includes("--slow")?+(t("--slow")||"500"):0,K=n.includes("--electron"),b=n.includes("--preview"),H=await Ce(t("--preview-origin")),le=t("--preview-public-origin"),Ue=n.includes("--preview-open"),ce=t("--owner")?.trim()||"",de=t("--repo")?.trim()||"",We=n.flatMap((u,c)=>n[c-1]==="--replace"?["--replace",u]:[]),Je=n.flatMap((u,c)=>n[c-1]==="--remap"?["--remap",u]:[]),$=n.includes("--record")||b,Ke=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):$?b?6e3:2e3:0,He=A.readFileSync(e,"utf8"),{frontmatter:x,steps:E}=ie(He);E.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let _=h||x.device||"",N=K||x.electron===!0,qe=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,q=await at(qe),ue={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"]},v=te(n,ue),ze=t("--url")||"";N&&!Me()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let me=N?"desktop companion":"bridge",Ge=q?` | target: ${q}`:"";console.log(`
386
- sootsim flow \u2014 ${w.basename(e)}
387
- ${E.length} steps | ${me}${Ge}${$?" | recording":""}${r?" | profiling":""}${S?` | ${S}ms delay`:""}
388
- `),b&&ye({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:E.length,mode:me,electron:N,record:$,profile:r,previewOrigin:H}});let F=ze||q||"",z=o||N&&v.simIdSource!=="flag",pe=t("--driver")||"",G=!1,Y=new Set,fe=!1;if(!F&&!z&&v.simIdSource==="none"){let u=ve(v);try{let c=await u.listSims(),y=c.find(L=>L.isPrimary&&L.readyState==="open"),j=c.find(L=>L.readyState==="open"),ge=y??j;ge&&(fe=!0,console.log(` reusing active sim: ${ge.id}`))}catch{}finally{u.close()}}if(!F&&!fe&&(z||v.simIdSource==="none")){let u=await lt();u||(console.error(" error: no current sim and no sootsim target found"),await Q(),process.exit(1)),F=u}if(F&&_){let u=new URL(await Ie(F));u.searchParams.set("device",_),F=u.toString()}if(F){let u=[F];if(u.push(...We),u.push(...Je),z&&u.push("--new"),v.simIdSource==="flag"&&v.simId&&u.push("--sim",v.simId),pe&&(u.push("--driver",pe),G=!0),n.includes("--headless")&&!i&&u.push("--headless"),await Ae(u,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),G){let c=ee();c&&Y.add(c)}}let I=te(n,ue),X=I.simIdSource==="flag"?I.simId:ee()||I.simId,Ye=I.simIdSource==="flag"?"flag":X?"saved":"none",k=re(I.wsPort,{commandTimeoutMs:I.commandTimeoutMs,simId:X,simIdSource:Ye}),d,he=async()=>{if(!_)return!1;let u=await k.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof u=="string"&&u.length>0){let c=new URL(u);c.searchParams.set("device",_),d.setSimRouteHint(c.toString())}return!!await k.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",_]})};if(d=new J(k,{screenshotDir:a,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:m,simId:X,recordingOutputDir:$?s:void 0,recordingFormat:b?"mp4":"webm",billingOriginOverride:b?H:void 0,allowGitHubRecording:$,onAfterLaunch:async()=>{await he()&&await d.waitForTree(12e4),b&&await k.send({type:"evaluate",simId:d.simId,code:`(() => {
389
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
390
- return r?.start?.() ?? false
391
- })()`})}}),S&&(d.stepDelay=S),d.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),x.env&&typeof x.env=="object")for(let[u,c]of Object.entries(x.env))d.js.putEnv(u,c);let M=null,T=null,O=null,Z=null,D=0,we=!!E[0]?.launchApp;try{await d.waitForTree(12e4),await he()&&await d.waitForTree(12e4),b&&!we&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),$&&(we?d.prepareRecording():await d.startRecording()),r&&await d.startProfile(),b&&(await k.send({type:"evaluate",simId:d.simId,code:`(() => {
392
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
393
- return r?.start?.() ?? false
394
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(E),r&&(M=await d.stopProfile()),await d.waitForRecordingTail({maxMs:Ke,smart:b}),$&&(T=await d.stopRecording(),O=d.getLastRecordingDurationMs()),b&&(Z=await k.send({type:"evaluate",simId:d.simId,code:`(() => {
395
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
396
- return r?.stop?.() ?? []
397
- })()`}),console.log(` captured ${Z.length} replay events`));let c=E.filter(y=>"takeScreenshot"in y).length;console.log(`
398
- + completed (${E.length} steps)`),c>0&&console.log(` screenshots: ${c} \u2192 ${a}`),M&&Le(M),T&&console.log(` video: ${T}`),console.log()}catch(u){if(r&&!M)try{M=await d.stopProfile()}catch{}if($&&!T)try{T=await d.stopRecording(),O=d.getLastRecordingDurationMs()}catch(c){console.warn(` recording stop failed: ${c?.message||String(c)}`)}console.error(`
399
- x failed: ${u.message}
400
- `),M&&(console.log(" partial profile:"),Le(M)),T&&console.log(` partial video: ${T}`);try{let c=d.lastFailedStep,y=c?`step-${String(c.index+1).padStart(2,"0")}-${c.kind}`:"unstaged",j=w.join(a,y);await d.captureFailureBundle(j,{error:u,stepIndex:c?.index,stepKind:c?.kind,stepTarget:c?.target}),console.log(` failure bundle: ${j}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(c){try{let y=w.join(a,"error.png");await d.captureFailureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${c instanceof Error?c.message:String(c)})`)}await Se(k,{errorsCommand:`sootsim get errors 5${d.simId?` --sim ${d.simId}`:""}`,warningsCommand:`sootsim get warnings 5${d.simId?` --sim ${d.simId}`:""}`,requestsCommand:`sootsim get requests 5${d.simId?` --sim ${d.simId}`:""}`}),D=1}finally{k.close()}if(D===0&&b)try{let u=await dt(Z??[]),c=["--origin",H,"--events",u];le&&c.push("--public-origin",le),T&&c.push("--video",T),T&&O&&Number.isFinite(O)&&c.push("--video-duration-ms",String(Math.round(O))),d.simId&&c.push("--sim",d.simId),Ue&&c.push("--open"),ce&&c.push("--owner",ce),de&&c.push("--repo",de),console.log(`
401
- preparing preview upload\u2026`);let{runUpload:y}=await import("./upload-CCWGR633.js");await y(c,{})}catch(u){console.error(` preview upload failed: ${u?.message||u}`),D=1}return G&&(d.simId&&Y.add(d.simId),await ct(v.wsPort,v.commandTimeoutMs,[...Y])),await Q(),D}async function ct(n,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let i=re(n,{commandTimeoutMs:e});try{let o=await i.listSims(),s=r.filter(l=>o.some(m=>m.id===l&&m.readyState==="open"));if(s.length===0)return;let a=await _e(i,n,e,s);await Pe(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{i.close()}}async function dt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
402
- `)+(n.length?`
403
- `:""),r=e(Buffer.from(t,"utf8")),i=w.join(Be(),`sootsim-events-${Date.now()}.jsonl.gz`);return A.writeFileSync(i,r),console.log(` events: ${n.length} written to ${i} (${r.length} bytes gz)`),i}async function ut(n){let e=n[0],t=r=>n.find((i,o)=>n[o-1]===r);switch(e){case"start":{let{path:r,state:i}=Te();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=se();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(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")||(n[1]&&!n[1].startsWith("-")?n[1]:void 0),i=n.includes("--validate")||n.includes("--video"),o=n.includes("--video"),s=se();s.active&&s.kept&&console.log(` auto-kept trailing action: ${s.candidate.summary}`);let a=$e(r||(i?pt():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(i){let l=ft(n,a.outputPath),m=await Ve(l);if(m!==0){console.error(`
404
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=m;return}oe(),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(oe(),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 r=n[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let i=ne(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let o of i)console.error(` - ${o}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function mt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function jt(n){let e=mt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await ut(e),0;let r=await Ve(e);return r!==0&&(process.exitCode=r),r}function Le(n){let e=n.avgMs>0?(1e3/n.avgMs).toFixed(1):"?",t=n.sampleCount>0?(n.jankFrames/n.sampleCount*100).toFixed(1):"0";console.log(`
405
- profile:`),console.log(` frames: ${n.frames}`),console.log(` total: ${n.totalMs.toFixed(1)}ms`),console.log(` avg: ${n.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${n.maxMs.toFixed(2)}ms`),n.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${n.layoutAvgMs.toFixed(2)}ms | render ${n.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${n.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${n.p95.toFixed(2)}ms`),console.log(` p99: ${n.p99.toFixed(2)}ms`),console.log(` jank: ${n.jankFrames}/${n.sampleCount} (${t}%) >16.67ms`);let r=Array.isArray(n.worstFrames)?n.worstFrames:[];if(r.length!==0){if(console.log(`
406
- worst frames:`),n.mode==="render-worker"){console.log(" total layout render copy t+");for(let i of r){let[o,s,a,l,m]=i;console.log(` ${s.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${m.toFixed(2).padStart(7)} ${String(o).padStart(5)}`)}return}console.log(` ${r.map(i=>i.toFixed(2)).join(", ")}`)}}function pt(){return w.join(Be(),`sootsim-flow-draft-${Date.now()}.yaml`)}function ft(n,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<n.length;r++){let i=n[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&n.includes("--video")&&t.push("--record"),t}export{lt as a,Ve as b,mt as c,jt as d};
@@ -1 +0,0 @@
1
- /*! sootsim v0.1.143 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */