sootsim 0.1.65 → 0.1.67

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 (147) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-44BHCTZA.js → agent-Z45KTLTP.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-BEP5WHZR.js → agent-wrapper-EEKVEJOC.js} +2 -2
  4. package/dist-cli/chunks/{assert-SKDEGGRD.js → assert-MDYZKXZ6.js} +2 -2
  5. package/dist-cli/chunks/auto-bootstrap-YZ6C6VYO.js +2 -0
  6. package/dist-cli/chunks/beta-WXH75XUE.js +2 -0
  7. package/dist-cli/chunks/chunk-2HKCZLY7.js +372 -0
  8. package/dist-cli/chunks/{chunk-46OKLW3Z.js → chunk-2I535GZU.js} +1 -1
  9. package/dist-cli/chunks/{chunk-L2SDB6G5.js → chunk-3KVVIZ6M.js} +2 -2
  10. package/dist-cli/chunks/chunk-42NMKOVE.js +3 -0
  11. package/dist-cli/chunks/{chunk-S46M5JZP.js → chunk-4H6LBA4A.js} +1 -1
  12. package/dist-cli/chunks/{chunk-M4HI2THN.js → chunk-4QSGVTBE.js} +2 -2
  13. package/dist-cli/chunks/{chunk-MLPLYQGK.js → chunk-52RZ6TSZ.js} +3 -3
  14. package/dist-cli/chunks/{chunk-ELZHT3LB.js → chunk-5WRBVYML.js} +2 -2
  15. package/dist-cli/chunks/{chunk-NJ2ACA36.js → chunk-67566AJS.js} +2 -2
  16. package/dist-cli/chunks/chunk-6O64VUC6.js +2 -0
  17. package/dist-cli/chunks/chunk-7PQHQOCI.js +186 -0
  18. package/dist-cli/chunks/{chunk-5ZB5ZN5Z.js → chunk-AQ7YR4MO.js} +14 -14
  19. package/dist-cli/chunks/{chunk-FRANP4PR.js → chunk-ATRGAFJD.js} +1 -1
  20. package/dist-cli/chunks/{chunk-OTWUZRFZ.js → chunk-BCVVANS5.js} +2 -2
  21. package/dist-cli/chunks/chunk-CUNQTNH4.js +35 -0
  22. package/dist-cli/chunks/{chunk-JC5L5ZJX.js → chunk-DOWYG3HG.js} +2 -2
  23. package/dist-cli/chunks/{chunk-MSBMGQJE.js → chunk-EJTXYZEF.js} +128 -36
  24. package/dist-cli/chunks/{chunk-P2C3JX3D.js → chunk-F23Y4HMT.js} +1 -1
  25. package/dist-cli/chunks/{chunk-GHFA4O5B.js → chunk-F4RC4AOY.js} +1 -1
  26. package/dist-cli/chunks/chunk-GFVC6EEB.js +1 -0
  27. package/dist-cli/chunks/{chunk-TWKWXGN5.js → chunk-HW5YHSIE.js} +1 -1
  28. package/dist-cli/chunks/{chunk-VGQXIMEX.js → chunk-IB4BRND4.js} +1 -1
  29. package/dist-cli/chunks/{chunk-X75XFMI4.js → chunk-IBWN764Q.js} +2 -2
  30. package/dist-cli/chunks/chunk-JE4JBSNJ.js +119 -0
  31. package/dist-cli/chunks/{chunk-O56DABNK.js → chunk-K4PKR2EO.js} +2 -2
  32. package/dist-cli/chunks/chunk-KBJ2WHII.js +73 -0
  33. package/dist-cli/chunks/chunk-KR36VJSN.js +1 -0
  34. package/dist-cli/chunks/{chunk-UHYZO26V.js → chunk-LQ5BA5JU.js} +2 -2
  35. package/dist-cli/chunks/chunk-MIAAZSSE.js +12 -0
  36. package/dist-cli/chunks/{chunk-PTUCXL7Y.js → chunk-N4JRDJMN.js} +3 -3
  37. package/dist-cli/chunks/{chunk-U5EQ5RWL.js → chunk-NYR3Z44O.js} +2 -2
  38. package/dist-cli/chunks/{chunk-2EBGZC4A.js → chunk-O624O5MO.js} +2 -2
  39. package/dist-cli/chunks/{chunk-HNXQ2JP6.js → chunk-SH6HMUCY.js} +2 -2
  40. package/dist-cli/chunks/chunk-SVFSMAZN.js +2 -0
  41. package/dist-cli/chunks/chunk-TEMZK6Q2.js +1 -0
  42. package/dist-cli/chunks/{chunk-KKOOZPQP.js → chunk-TLTS533S.js} +1 -1
  43. package/dist-cli/chunks/chunk-U47AHSGE.js +23 -0
  44. package/dist-cli/chunks/{chunk-6GZS5TCL.js → chunk-XCRUPKWB.js} +2 -2
  45. package/dist-cli/chunks/{chunk-5MMRIGC3.js → chunk-YGQV3CUV.js} +2 -2
  46. package/dist-cli/chunks/{chunk-GZCZ4GCS.js → chunk-ZJJKYJMH.js} +2 -2
  47. package/dist-cli/chunks/{chunk-FU33BTPL.js → chunk-ZO7SGE65.js} +1 -1
  48. package/dist-cli/chunks/{chunk-UH4H5HXN.js → chunk-ZP2HMCKS.js} +1 -1
  49. package/dist-cli/chunks/cli-version-5LGQQE5P.js +2 -0
  50. package/dist-cli/chunks/{compat-MDZTV64M.js → compat-5MMZ4R3Q.js} +3 -3
  51. package/dist-cli/chunks/{config-DRGNQOYL.js → config-YWN44WJQ.js} +2 -2
  52. package/dist-cli/chunks/control-LUCFDAZI.js +2 -0
  53. package/dist-cli/chunks/{cpu-profile-JQAGHLDS.js → cpu-profile-VFGUVXU5.js} +2 -2
  54. package/dist-cli/chunks/{daemon-3RT7EABW.js → daemon-ONX5ZBXF.js} +2 -2
  55. package/dist-cli/chunks/{debug-CYINYNWV.js → debug-CPOG32OT.js} +5 -5
  56. package/dist-cli/chunks/demo-app-registry-LWT6JLU6.js +2 -0
  57. package/dist-cli/chunks/{detox-DUABQYC6.js → detox-J6NGSZR5.js} +2 -2
  58. package/dist-cli/chunks/{device-KSSSQOQC.js → device-QYOQXI2P.js} +2 -2
  59. package/dist-cli/chunks/{diagnose-NUDACXIR.js → diagnose-MMW4LJLA.js} +2 -2
  60. package/dist-cli/chunks/drivers-NRWUJJCD.js +2 -0
  61. package/dist-cli/chunks/{electron-LC3Y74FA.js → electron-IK3HIZY4.js} +3 -3
  62. package/dist-cli/chunks/flow-2MB7HINM.js +2 -0
  63. package/dist-cli/chunks/{hints-EOARRVNB.js → hints-KZOD56U5.js} +2 -2
  64. package/dist-cli/chunks/{home-paths-HOBR3K3B.js → home-paths-R2YZZTUM.js} +2 -2
  65. package/dist-cli/chunks/inspect-ZARO3HQ4.js +970 -0
  66. package/dist-cli/chunks/install-O67RTYCX.js +2 -0
  67. package/dist-cli/chunks/{install-desktop-W2OOILJG.js → install-desktop-4GH5I7SC.js} +3 -3
  68. package/dist-cli/chunks/{keys-RR43E2O3.js → keys-AXEFZUUI.js} +2 -2
  69. package/dist-cli/chunks/{launch-GAPSA5HQ.js → launch-QLE56ON7.js} +3 -3
  70. package/dist-cli/chunks/{login-IADXSJEW.js → login-J45NQQM6.js} +4 -4
  71. package/dist-cli/chunks/{logout-AT33MGA7.js → logout-ZE5OUBB7.js} +2 -2
  72. package/dist-cli/chunks/{maestro-G36ATKHQ.js → maestro-FS6CAKDD.js} +2 -2
  73. package/dist-cli/chunks/{preview-BJUMMDBL.js → preview-TSU5IXVR.js} +2 -2
  74. package/dist-cli/chunks/{profile-CEQNS53P.js → profile-ZBJ4TYWA.js} +2 -2
  75. package/dist-cli/chunks/{react-BPEDK3TN.js → react-TGZLTTYN.js} +2 -2
  76. package/dist-cli/chunks/record-JSBFUNOD.js +54 -0
  77. package/dist-cli/chunks/runtime-DGDQ7NVY.js +2 -0
  78. package/dist-cli/chunks/{runtime-delivery-IYK2HNPG.js → runtime-delivery-36UMAXOV.js} +2 -2
  79. package/dist-cli/chunks/screenshot-3CHMALUJ.js +33 -0
  80. package/dist-cli/chunks/{screenshot-mode-VUBCO7T2.js → screenshot-mode-C547UT5H.js} +2 -2
  81. package/dist-cli/chunks/{screenshots-JENURQSV.js → screenshots-XCNGSNYG.js} +2 -2
  82. package/dist-cli/chunks/{server-PVAO3OA2.js → server-W37X3IW7.js} +6 -6
  83. package/dist-cli/chunks/setup-repo-DETS5ZJT.js +2 -0
  84. package/dist-cli/chunks/{skills-4JI327YS.js → skills-OXZLDNDW.js} +2 -2
  85. package/dist-cli/chunks/{start-7YB4I5V5.js → start-N6ZQYUBP.js} +4 -4
  86. package/dist-cli/chunks/store-QOXJKJUZ.js +2 -0
  87. package/dist-cli/chunks/telemetry-74LX7WG4.js +2 -0
  88. package/dist-cli/chunks/{test-5C6NYF62.js → test-DWZ7PRSW.js} +3 -3
  89. package/dist-cli/chunks/{three-mode-C6TE63VR.js → three-mode-P2R7KA62.js} +2 -2
  90. package/dist-cli/chunks/{timeline-NFYS6IPO.js → timeline-VPES3YCN.js} +3 -3
  91. package/dist-cli/chunks/{upgrade-KROEHYG2.js → upgrade-NYQLA4UJ.js} +2 -2
  92. package/dist-cli/chunks/upload-YOMMYESV.js +2 -0
  93. package/dist-cli/chunks/{web-UTOZ7MRF.js → web-OTALJKK5.js} +2 -2
  94. package/dist-cli/chunks/what-happened-GZ73H6KF.js +22 -0
  95. package/dist-cli/chunks/{whoami-O6XVOJBF.js → whoami-UDLQK7IY.js} +2 -2
  96. package/dist-lib/agent-daemon-client.cjs +1 -1
  97. package/dist-lib/agent-events.cjs +1 -1
  98. package/dist-lib/agent-sessions.cjs +1 -1
  99. package/dist-lib/attached-projects.cjs +1 -1
  100. package/dist-lib/auth/shared-session.cjs +1 -1
  101. package/dist-lib/backend-origin.cjs +1 -1
  102. package/dist-lib/bridge-constants.cjs +1 -1
  103. package/dist-lib/cli-constants.cjs +1 -1
  104. package/dist-lib/config.cjs +1 -1
  105. package/dist-lib/dev-bundle-resolution.cjs +9 -2
  106. package/dist-lib/home-paths.cjs +1 -1
  107. package/dist-lib/host/bridge-host.cjs +23 -7
  108. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  109. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  110. package/dist-lib/index.cjs +1 -1
  111. package/dist-lib/metro.cjs +1 -1
  112. package/dist-lib/profiles.cjs +1 -1
  113. package/dist-lib/render-mode.cjs +1 -1
  114. package/dist-lib/vite-base.cjs +23 -7
  115. package/dist-lib/vite.cjs +1 -1
  116. package/package.json +1 -1
  117. package/dist-cli/chunks/auto-bootstrap-SMQMN7WS.js +0 -2
  118. package/dist-cli/chunks/beta-DEQZ2J7G.js +0 -2
  119. package/dist-cli/chunks/chunk-3HC3F7CO.js +0 -3
  120. package/dist-cli/chunks/chunk-5MRRLWSD.js +0 -1
  121. package/dist-cli/chunks/chunk-B32KMMQV.js +0 -2
  122. package/dist-cli/chunks/chunk-CBRKFAOD.js +0 -1
  123. package/dist-cli/chunks/chunk-DLSOZVYM.js +0 -1
  124. package/dist-cli/chunks/chunk-E6CRWOWO.js +0 -2
  125. package/dist-cli/chunks/chunk-FPOQPEGK.js +0 -11
  126. package/dist-cli/chunks/chunk-GHTXP5R7.js +0 -348
  127. package/dist-cli/chunks/chunk-NTEZEQSB.js +0 -100
  128. package/dist-cli/chunks/chunk-R2QEABGZ.js +0 -119
  129. package/dist-cli/chunks/chunk-TRHZBTPF.js +0 -34
  130. package/dist-cli/chunks/chunk-UXFF7AEE.js +0 -73
  131. package/dist-cli/chunks/chunk-X2IIAIAP.js +0 -3
  132. package/dist-cli/chunks/chunk-ZW3HKMLQ.js +0 -17
  133. package/dist-cli/chunks/cli-version-HH7DAYBK.js +0 -2
  134. package/dist-cli/chunks/control-NCUWAXPH.js +0 -2
  135. package/dist-cli/chunks/demo-app-registry-JGIZ7NN7.js +0 -2
  136. package/dist-cli/chunks/drivers-CKGMOVM4.js +0 -2
  137. package/dist-cli/chunks/flow-3AHNNHF7.js +0 -2
  138. package/dist-cli/chunks/inspect-QCZVODE6.js +0 -1025
  139. package/dist-cli/chunks/install-747G2O4S.js +0 -2
  140. package/dist-cli/chunks/record-73CGQ3EP.js +0 -50
  141. package/dist-cli/chunks/runtime-QR5IHGKJ.js +0 -2
  142. package/dist-cli/chunks/screenshot-GUM2U2PN.js +0 -28
  143. package/dist-cli/chunks/setup-repo-ECVECJZQ.js +0 -2
  144. package/dist-cli/chunks/store-2MXXL4QE.js +0 -2
  145. package/dist-cli/chunks/telemetry-GIA7FIKW.js +0 -2
  146. package/dist-cli/chunks/upload-OS3J5ZOS.js +0 -2
  147. package/dist-cli/chunks/what-happened-FCP2U43H.js +0 -15
@@ -1,348 +0,0 @@
1
- /*! sootsim v0.1.65 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as Se}from"./chunk-M4HI2THN.js";import{a as Te}from"./chunk-HNXQ2JP6.js";import{a as xe}from"./chunk-UXFF7AEE.js";import{a as R,b as pe,c as fe,d as q,e as G,f as we,g as Y,i as X,j as ge}from"./chunk-MSBMGQJE.js";import{f as be,m as ve}from"./chunk-FPOQPEGK.js";import{e as he}from"./chunk-O56DABNK.js";import{b as me}from"./chunk-TRHZBTPF.js";import{a as ye}from"./chunk-FU33BTPL.js";import{a as le,b as H}from"./chunk-JC5L5ZJX.js";import{f as ae}from"./chunk-U5EQ5RWL.js";import{c as z,d as ce,e as ue}from"./chunk-ZW3HKMLQ.js";import{c as de}from"./chunk-VGQXIMEX.js";import*as A from"fs";import{tmpdir as Me}from"os";import*as h from"path";import*as w from"fs";import*as f from"path";var V=1e4,B=393,_=852,Fe="__sootsimCliPerf",Oe="maestroCopiedText",$e=new Map;function p(o){return new Promise(e=>setTimeout(e,o))}function Ne(o){return o?f.basename(o)===".maestro"?f.dirname(o):o:process.cwd()}function Re(o,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():Ne(t.flowDir);return f.resolve(i,r)}return f.join(o,r)}function Ve(o){if(typeof o=="string")return{path:o,withFrame:!1};let e=o.path?.trim()||o.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:o.withFrame===!0}}function Q(o){let[e,t]=o.split(",").map(i=>i.trim()),r=(i,s)=>i.endsWith("%")?Number.parseFloat(i)/100*s:Number.parseFloat(i);return{x:r(e,B),y:r(t,_)}}function Be(o){let e=o.split(/^---$/m),t=e.length>1?e[e.length-1]:o,r=fe(pe.parse(t),$e);return Array.isArray(r)?r:[]}var U=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;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(a=>a.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(a=>a.id===this.opts.simId&&a.readyState==="open")||!this.simRouteHint)return;let i=this.simRouteHint&&e.find(a=>a.readyState==="open"&&this.normalizeSimRoute(a.url||a.origin)===this.simRouteHint);if(!i)return;let s=e.find(a=>a.isPrimary&&a.readyState==="open"),n=e.find(a=>a.readyState==="open"),l=i??s??n;l&&(this.opts.simId=l.id,console.log(` [flow] sim rotated to ${l.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=V){let t=Date.now()+e,r=Date.now(),i=null,s=0,n=0;for(;Date.now()<t;){try{let a=await this.evaluate(`(async () => {
3
- const test = window.__sootsimTest
4
- if (!test) return { count: 0, loading: true }
5
- const count = (await test.getNodeCount?.()) || 0
6
- const external = globalThis.__sootsimExternalAppState
7
- if (external?.error) {
8
- return { count, loading: false, error: String(external.error) }
9
- }
10
- if (external) {
11
- return {
12
- count,
13
- loading: !external.ready,
14
- error: null,
15
- }
16
- }
17
- const loadingNode = await test.findByText?.('loading')
18
- const capturingNode = await test.findByText?.('capturing')
19
- const openingAppNode = await test.findByText?.('opening app')
20
- const isLoading = !!loadingNode || !!capturingNode || !!openingAppNode || count < 5
21
- return { count, loading: isLoading, error: null }
22
- })()`,8e3);if(s=0,a?.error)throw new Error(`app failed to load: ${a.error}`);if(a&&a.count>10&&!a.loading)return}catch(a){if(i=a instanceof Error?a:new Error(String(a)),i.message.startsWith("app failed to load:"))throw i;if(s++,s>=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 l=Date.now()-r;l-n>=5e3&&(n=l,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(l/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 Te("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
23
- const rec = window.__sootsimRecorder
24
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
25
- if (rec.state() === 'recording') return { ok: true, format: 'webm' }
26
- return rec.start({ format: 'webm', fps: 24 })
27
- })()`);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 n=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!n||(r.push(Buffer.from(n.data,"base64")),i=n.offset,n.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");w.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=f.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.webm`);return w.writeFileSync(s,Buffer.concat(r)),s}async findElement(e){return this.evaluate(`(async () => {
28
- const test = window.__sootsimTest
29
- if (!test) return null
30
- let node = null
31
- if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
32
- if (!node && ${JSON.stringify(!!e.id)}) {
33
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
34
- }
35
- if (!node || !node.absolutePosition || !node.layout) return null
36
- return {
37
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
38
- id: node.id || null,
39
- testID: node.testID || null,
40
- text: node.text || null,
41
- absolutePosition: node.absolutePosition,
42
- layout: node.layout,
43
- isTextInput: !!node.isTextInput,
44
- }
45
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
46
- const test = window.__sootsimTest
47
- if (!test?.resolveTapTarget) return null
48
- return await test.resolveTapTarget(${e})
49
- })()`)}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 () => {
50
- const test = window.__sootsimTest
51
- if (!test) return null
52
- 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||"")})`}
53
- let point = null
54
- if (node?.absolutePosition && node?.layout) {
55
- point = {
56
- x: node.absolutePosition.x + node.layout.width / 2,
57
- y: node.absolutePosition.y + node.layout.height / 2,
58
- }
59
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
60
- const resolved = await test.resolveTapTarget(node.nodeId)
61
- if (
62
- resolved &&
63
- Number.isFinite(resolved.cx) &&
64
- Number.isFinite(resolved.cy)
65
- ) {
66
- point = { x: resolved.cx, y: resolved.cy }
67
- }
68
- }
69
- }
70
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
71
- if (direct?.ok && point) {
72
- window.dispatchEvent(
73
- new CustomEvent('sootsim:agentAction', {
74
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
75
- }),
76
- )
77
- }
78
- return direct || null
79
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
80
- const test = window.__sootsimTest
81
- if (!test?.activatePressAt) return null
82
- const direct = await test.activatePressAt(${e}, ${t})
83
- if (direct?.ok) {
84
- window.dispatchEvent(
85
- new CustomEvent('sootsim:agentAction', {
86
- detail: { type: 'tap', x: ${e}, y: ${t} },
87
- }),
88
- )
89
- }
90
- return direct
91
- })()`)}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 a=Q(t.point);(await this.activatePressAt(a.x,a.y))?.ok||await this.tap(a.x,a.y),await p(300);return}let r=5e3,i=150,s=Date.now()+r,n=await this.findElement({text:t.text,id:t.id});for(;!n&&Date.now()<s;)await p(i),n=await this.findElement({text:t.text,id:t.id});if(n){let a=typeof n.nodeId=="number"?await this.resolveTapTarget(n.nodeId):null,m=a?.cx??n.absolutePosition.x+n.layout.width/2,g=a?.cy??n.absolutePosition.y+n.layout.height/2;if((await this.tap(m,g,{id:t.id??a?.target?.id??n.id??null,testID:t.id??a?.target?.testID??n.testID??null,text:t.text??a?.target?.text??a?.target?.accessibilityLabel??n.text??n.accessibilityLabel??null,type:a?.target?.type??n.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 () => {
92
- const interact = window.__sootsimInteract
93
- if (interact?.doubleTap) {
94
- return !!(await interact.doubleTap(${e}, ${t}, ${i}))
95
- }
96
- if (!interact?.tap) return false
97
- const first = await interact.tap(${e}, ${t})
98
- if (!first || first.hit === false) return false
99
- await new Promise((resolve) => setTimeout(resolve, ${i}))
100
- const second = await interact.tap(${e}, ${t})
101
- return !!second && second.hit !== false
102
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await p(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let r=0;r<15;r++){if(await this.isElementVisible(t))return;await p(200)}throw new Error(`assertVisible: ${JSON.stringify(t)} not found or off-screen`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t))throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible`)}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<_)}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(`(() => {
103
- const keyboard =
104
- window.__sootsimKeyboard ??
105
- window.SootSim?.bridges?.keyboard ??
106
- null
107
- const test = window.__sootsimTest
108
- return {
109
- visible: !!keyboard?.isVisible?.(),
110
- focused: !!test?.isTextInputFocused?.(),
111
- }
112
- })()`);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||V);for(;Date.now()<t;){if(await this.findElement(e))return;await p(200)}throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||V}ms`)}async takeScreenshot(e){await p(250);let t=Ve(e),r=Re(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});w.mkdirSync(f.dirname(r),{recursive:!0});let s=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,""),n=Buffer.from(s,"base64");if(t.withFrame){let l=await this.readCurrentDeviceModel();if(!l)throw new Error("could not read current device model for framed screenshot");let a=await Se(n,l);w.writeFileSync(r,a),console.log(`[flow] screenshot: ${r} (frame: ${l})`);return}w.writeFileSync(r,n),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 ae)?null:t}async captureFailureScreenshot(e){w.mkdirSync(f.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");w.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){w.mkdirSync(e,{recursive:!0});let r=(m,g)=>{try{w.writeFileSync(f.join(e,m),g)}catch{}},i=async m=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:m})}catch{return null}};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()},null,2));try{let g=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(g,"base64"))}catch{}let s=await i(`(async () => {
113
- const t = window.__sootsimTest
114
- const mainShell = window.SootSim?.bridges?.mainShell
115
- if (!t) return { error: 'no test bridge' }
116
- let shell = null
117
- try {
118
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
119
- } catch {}
120
- const all = await t.queryAll({ pruneHidden: true })
121
- return { shell, nodes: all, url: location.href, title: document.title }
122
- })()`);s&&r("describe.json",JSON.stringify(s,null,2));let n=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof n=="string"&&r("a11y.txt",n);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let a=await i(`(() => {
123
- const c = window.__sootsimConsole
124
- return {
125
- errors: c?.getErrors?.() ?? [],
126
- warnings: c?.getWarnings?.() ?? [],
127
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
128
- }
129
- })()`);return a&&r("console.json",JSON.stringify(a,null,2)),e}async swipe(e="UP",t=300){let r=B/2,i=_/2,s=200,n=r,l=i,a=r,m=i;switch(e.toUpperCase()){case"UP":l+=s,m-=s;break;case"DOWN":l-=s,m+=s;break;case"LEFT":n+=s,a-=s;break;case"RIGHT":n-=s,a+=s;break}let g=Math.max(10,Math.round(t/16));await this.drag(n,l,a,m,g,16)}async drag(e,t,r,i,s=12,n=16){if(!(await this.evaluate(`(async () => {
130
- const interact = window.__sootsimInteract
131
- if (!interact?.drag) return { ok: false }
132
- const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(s))}, ${Math.max(0,Math.round(n))})
133
- return { ok: !!value, value }
134
- })()`))?.ok)throw new Error("drag failed");await p(300)}async swipeCoords(e,t,r=300){let i=Q(e),s=Q(t),n=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,s.x,s.y,n,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 s=i.absolutePosition.x+i.layout.width/2,n=i.absolutePosition.y+i.layout.height/2,l=180,a=s,m=n;switch(t.toUpperCase()){case"UP":m-=l;break;case"DOWN":m+=l;break;case"LEFT":a-=l;break;case"RIGHT":a+=l;break}let g=Math.max(10,Math.round(r/16));await this.drag(s,n,a,m,g,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 () => {
135
- const interact = window.__sootsimInteract
136
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
137
- const ok = await interact.pinch(
138
- ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
139
- ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
140
- ${e.steps||12}, ${e.stepMs||16}
141
- )
142
- return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
143
- })()`);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 s=await this.findElement({text:e.element});if(s&&s.absolutePosition.y>=0&&s.absolutePosition.y+s.layout.height>0&&s.absolutePosition.y<_-50){if(e.centerElement){let n=_/2,l=s.absolutePosition.y-n;if(Math.abs(l)>100){let a=Math.min(150,Math.abs(l)*.5),m=l>0?n-a:n+a;await this.drag(B/2,n,B/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||V);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();let t=!!(e&&typeof e=="object"&&e.clearState);if(t&&await this.evaluate(`(async () => {
144
- await (${R})
145
- try {
146
- const regs = await navigator.serviceWorker?.getRegistrations?.()
147
- await Promise.all((regs || []).map((reg) => reg.unregister()))
148
- } catch {}
149
- })()`),!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) => {
150
- requestAnimationFrame(() => {
151
- requestAnimationFrame(() => {
152
- requestAnimationFrame(() => {
153
- setTimeout(resolve, 180)
154
- })
155
- })
156
- })
157
- })`)}catch{await p(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
158
- const host = window.__sootsimRenderHost
159
- if (host?.startPerfSession) {
160
- host.startPerfSession(sessionKey)
161
- window[sessionKey] = {
162
- active: true,
163
- mode: 'render-worker',
164
- startedAt: performance.now(),
165
- }
166
- return
167
- }
168
-
169
- const perf = window.__sootsimPerf
170
- const a11y = window.__sootsimA11y
171
- perf?.enableFrameStats?.()
172
- perf?.resetFrameStats?.()
173
- a11y?.resetProfile?.()
174
- window[sessionKey] = {
175
- active: true,
176
- mode: 'main-thread',
177
- startedAt: performance.now(),
178
- }
179
- })(${JSON.stringify(Fe)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
180
- const host = window.__sootsimRenderHost
181
- if (host?.stopPerfSession) {
182
- const stopped = await host.stopPerfSession(sessionKey)
183
- if (!stopped || !Array.isArray(stopped.samples)) {
184
- return { error: 'no render-worker perf samples available' }
185
- }
186
- const samples = stopped.samples
187
- const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0).filter((value) => value > 0)
188
- const sorted = [...frameTimes].sort((a, b) => a - b)
189
- const worstFrames = samples
190
- .slice()
191
- .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
192
- .slice(0, 10)
193
- .map((sample) => [
194
- Number(sample?.[0]) || 0,
195
- Number(sample?.[1]) || 0,
196
- Number(sample?.[2]) || 0,
197
- Number(sample?.[3]) || 0,
198
- Number(sample?.[4]) || 0,
199
- ])
200
-
201
- return {
202
- mode: 'render-worker',
203
- frames: Number(stopped.frameCount) || frameTimes.length,
204
- totalMs: Number(stopped.totalMs) || frameTimes.reduce((sum, value) => sum + value, 0),
205
- avgMs: Number(stopped.avgMs) || (frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0),
206
- maxMs: Number(stopped.maxMs) || (sorted[sorted.length - 1] || 0),
207
- layoutTotalMs: Number(stopped.layoutTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
208
- renderTotalMs: Number(stopped.renderTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
209
- copyTotalMs: Number(stopped.copyTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
210
- layoutAvgMs: Number(stopped.layoutAvgMs) || 0,
211
- renderAvgMs: Number(stopped.renderAvgMs) || 0,
212
- copyAvgMs: Number(stopped.copyAvgMs) || 0,
213
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
214
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
215
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
216
- jankFrames: frameTimes.filter((value) => value > 16.67).length,
217
- sampleCount: frameTimes.length,
218
- worstFrames,
219
- }
220
- }
221
-
222
- const perf = window.__sootsimPerf
223
- const a11y = window.__sootsimA11y
224
- if (!perf && !a11y) return { error: 'no perf globals available' }
225
-
226
- const frameStats = perf?.getFrameStats?.() || {}
227
- const profile = a11y?.profile?.() || {}
228
- const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
229
- const sorted = [...recent].sort((a, b) => a - b)
230
- perf?.disableFrameStats?.()
231
-
232
- return {
233
- mode: 'main-thread',
234
- frames: frameStats.frames || profile.syncCount || 0,
235
- totalMs: frameStats.totalMs || 0,
236
- avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
237
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
238
- layoutTotalMs: frameStats.layoutTotalMs || 0,
239
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
240
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
241
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
242
- jankFrames: recent.filter((value) => value > 16.67).length,
243
- sampleCount: recent.length,
244
- worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
245
- }
246
- })(${JSON.stringify(Fe)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
247
- try { await (${R}) } catch {}
248
- try {
249
- const regs = await navigator.serviceWorker?.getRegistrations?.()
250
- await Promise.all((regs || []).map((reg) => reg.unregister()))
251
- } catch {}
252
- })()`)}async clearState(){await this.evaluate(`(async () => {
253
- await (${R})
254
- })()`)}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??"";$e.set(Oe,i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}async evalScript(e){let r=await this.evaluate(`(async () => {
255
- try {
256
- return { ok: true, value: await (async () => { ${e} })() }
257
- } catch (err) {
258
- return { ok: false, error: err && err.message ? err.message : String(err) }
259
- }
260
- })()`);if(!r.ok)throw new Error(`evalScript failed: ${r.error}`);r.value!==void 0&&console.log("[flow] evalScript ->",r.value)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");await this.evaluate(`window.location.href = ${JSON.stringify(t)}`),await p(300),await this.refreshSimId(),await this.waitForTree(3e4)}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()==="ios":e.true!==void 0?e.true.toLowerCase()!=="false":!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([s])=>s!=="when"&&s!=="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(i=>i!=="when")||Object.keys(e)[0];if(console.log(`[flow] step ${t+1}: ${r}`),e.when&&!await this.evaluateWhen(e.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let i=!!(e.extendedWaitUntil||e.waitFor||e.scrollUntilVisible||e.launchApp||e.runFlow),s=1e4,n=this.runStepInner(e);if(i)await n;else{let a=null,m=new Promise((g,y)=>{a=setTimeout(()=>{y(new Error(`step watchdog: ${r} made no progress in ${s}ms \u2014 bridge or bundle probably hung`))},s)});try{await Promise.race([n,m])}finally{a&&clearTimeout(a)}}let l=!!(e.assertVisible||e.assertNotVisible||e.extendedWaitUntil||e.waitFor);this.stepDelay>0&&!l&&await p(this.stepDelay)}catch(i){if(this.isOptional(e)){console.log(`[flow] (optional, skipped: ${i.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:e[r]},i}}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)for(let t=0;t<e.repeat.times;t++)for(let r=0;r<e.repeat.commands.length;r++)await this.runStep(e.repeat.commands[r],r);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")await this.evalScript(e.evalScript);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.when;if(i&&!await this.evaluateWhen(i)){console.log(`[flow] runFlow skipped (when predicate false): ${r}`);return}let s=f.resolve(this.opts.flowDir,r),n=w.readFileSync(s,"utf8"),l=this.opts.flowDir;this.opts.flowDir=f.dirname(s),await this.runFlow(Be(n)),this.opts.flowDir=l}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],r=[],i=[];for(let n of e){let l=Object.keys(n);if(l.length===1&&l[0]==="onFlowStart"&&Array.isArray(n.onFlowStart)){t.push(...n.onFlowStart);continue}if(l.length===1&&l[0]==="onFlowComplete"&&Array.isArray(n.onFlowComplete)){r.push(...n.onFlowComplete);continue}i.push(n)}if(t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let n=0;n<t.length;n++)await this.runStep(t[n],n)}let s=null;try{await this.runFlowBody(i)}catch(n){s=n instanceof Error?n:new Error(String(n))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let n=0;n<r.length;n++)try{await this.runStep(r[n],n)}catch(l){console.warn(`[flow] onFlowComplete step ${n+1} failed: ${l instanceof Error?l.message:l}`)}}if(s)throw s}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],i=typeof r.wait=="number"?r.wait:0,s=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,n=Math.max(6e4,i+15e3,s+15e3);if(r.runFlow){await this.runStep(r,t);continue}await Promise.race([this.runStep(r,t),new Promise((l,a)=>setTimeout(()=>a(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${n}ms deadline`)),n))])}}};async function Ue(){let o=await he(),e=o.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=o[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Ie(o){(o.length===0||o.includes("--help")||o.includes("-h"))&&(console.log(`
261
- sootsim flow \u2014 run flows or manage a draft
262
-
263
- usage:
264
- sootsim flow <flow.yaml> [options]
265
- sootsim flow start
266
- sootsim flow keep
267
- sootsim flow end [--output <path>] [--validate] [--video]
268
- sootsim flow validate <path>
269
-
270
- options:
271
- --record record a webm artifact while the flow runs
272
- --profile capture perf stats while the flow runs
273
- --out <dir> output directory (default: /tmp/sootsim-recordings)
274
- --device <model> override the flow frontmatter device for this run
275
- --slow <ms> delay between steps for natural pacing
276
- --tail-wait <ms> hold the recording open after the last step so the
277
- final UI state is captured (default 2000ms when --record
278
- is on, 0 otherwise)
279
- --url <url> load this target before running the flow
280
- --screenshot-paths <mode>
281
- screenshot path mode: dir (default) or flow
282
- --replace <m>=<f> replace a Metro module with a local file for this run
283
- --new open a fresh sim before running the flow
284
- --driver <id> when paired with --new, launch through a specific
285
- driver from the registry (e.g. playwright for
286
- hermetic CI runs); see 'sootsim list --drivers'
287
- --headless pass headless=true to the launch driver (useful
288
- with --driver playwright)
289
- --electron prefer opening the target in the desktop companion
290
- --sim <id> target a specific current sim
291
- --validate replay the drafted flow before clearing it
292
- --video replay and record the drafted flow before clearing it
293
- --preview record events+video, upload, and print /preview/<id>
294
- --preview-open open the uploaded preview link after a successful run
295
- --preview-origin <url>
296
- upload target for --preview (default: auto)
297
- --preview-public-origin <url>
298
- public link origin for --preview (default: sootsim.com
299
- for prod uploads)
300
-
301
- frontmatter (top of flow.yaml between --- markers):
302
- app: 8081 load this target before the flow starts
303
- device: iphone-14 set the live device model for this flow run
304
- electron: true prefer the desktop companion sim for this flow
305
-
306
- default runtime:
307
- bridge-backed flow playback against the current sim
308
- if no current sim exists, flow opens the discovered target first
309
- recording and profiling both run on the same bridge-backed path
310
-
311
- examples:
312
- sootsim flow login.yaml
313
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
314
- sootsim flow demo.yaml --sim a2
315
- sootsim flow start
316
- sootsim flow keep
317
- sootsim flow end --output ./flows/draft.yaml
318
- sootsim flow end --output ./flows/draft.yaml --validate
319
- sootsim flow end --output ./flows/draft.yaml --video
320
- sootsim flow validate ./flows/draft.yaml
321
-
322
- flow extension:
323
- takeScreenshot: hero
324
- takeScreenshot:
325
- path: marketing/hero
326
- withFrame: true
327
- `),process.exit(0));let e=o[0];A.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=u=>o.find((d,v)=>o[v-1]===u),r=o.includes("--profile"),i=o.includes("--new"),s=t("--out")||"/tmp/sootsim-recordings",n=t("--screenshots")||"/tmp/sootsim-flow",l=t("--screenshot-paths")==="flow"?"flow":"dir",a=t("--device")?.trim()||"",m=o.includes("--slow")?+(t("--slow")||"500"):0,g=o.includes("--electron"),y=o.includes("--preview"),W=await xe(t("--preview-origin")),Z=t("--preview-public-origin"),Ae=o.includes("--preview-open"),Pe=o.flatMap((u,d)=>o[d-1]==="--replace"?["--replace",u]:[]),S=o.includes("--record")||y,ee=o.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):S?2e3:0,Ee=A.readFileSync(e,"utf8"),{frontmatter:$,steps:M}=q(Ee,{resolveEnv:!0});M.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let P=a||$.device||"",C=g||$.electron===!0,L=$.app===void 0||$.app===null?"":typeof $.app=="number"?String($.app):$.app,te={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver"]},x=z(o,te),_e=t("--url")||"";C&&!ye()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let re=C?"desktop companion":"bridge",Ce=L?` | target: ${L}`:"";console.log(`
328
- sootsim flow \u2014 ${h.basename(e)}
329
- ${M.length} steps | ${re}${Ce}${S?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
330
- `),y&&le({event:"preview_flow_started",properties:{flowName:h.basename(e),stepCount:M.length,mode:re,electron:C,record:S,profile:r,previewOrigin:W}});let T=_e||L||"",j=i||C&&x.simIdSource!=="flag",ie=!1;if(!T&&!j&&x.simIdSource==="none"){let u=ue(x);try{let d=await u.listSims(),v=d.find(N=>N.isPrimary&&N.readyState==="open"),O=d.find(N=>N.readyState==="open"),se=v??O;se&&(ie=!0,console.log(` reusing active sim: ${se.id}`))}catch{}finally{u.close()}}if(!T&&!ie&&(j||x.simIdSource==="none")){let u=await Ue();u||(console.error(" error: no current sim and no sootsim target found"),await H(),process.exit(1)),T=u}if(T&&P){let u=new URL(await be(T));u.searchParams.set("device",P),T=u.toString()}if(T){let u=[T];u.push(...Pe),j&&u.push("--new"),x.simIdSource==="flag"&&x.simId&&u.push("--sim",x.simId);let d=t("--driver");d&&u.push("--driver",d),o.includes("--headless")&&u.push("--headless"),await ve(u,{port:x.wsPort,timeoutMs:x.commandTimeoutMs})}let I=z(o,te),K=I.simIdSource==="flag"?I.simId:de()||I.simId,De=I.simIdSource==="flag"?"flag":K?"saved":"none",F=ce(I.wsPort,{commandTimeoutMs:I.commandTimeoutMs,simId:K,simIdSource:De,fallbackOnMissingSimId:!1}),c,oe=async()=>{if(!P)return!1;let u=await F.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof u=="string"&&u.length>0){let d=new URL(u);d.searchParams.set("device",P),c.setSimRouteHint(d.toString())}return!!await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",P]})};c=new U(F,{screenshotDir:n,flowDir:h.dirname(h.resolve(e)),screenshotPathMode:l,simId:K,recordingOutputDir:S?s:void 0,billingOriginOverride:y?W:void 0,allowGitHubRecording:S,onAfterLaunch:async()=>{await oe()&&await c.waitForTree(12e4),y&&await F.send({type:"evaluate",simId:c.simId,code:`(() => {
331
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
332
- return r?.start?.() ?? false
333
- })()`})}}),m&&(c.stepDelay=m);let k=null,b=null,E=null,J=null,D=0,ne=!!M[0]?.launchApp;try{await c.waitForTree(12e4),await oe()&&await c.waitForTree(12e4),y&&!ne&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),S&&(ne?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),y&&(await F.send({type:"evaluate",simId:c.simId,code:`(() => {
334
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
335
- return r?.start?.() ?? false
336
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(M),r&&(k=await c.stopProfile()),S&&ee>0&&await new Promise(d=>setTimeout(d,ee)),S&&(b=await c.stopRecording(),E=c.getLastRecordingDurationMs()),y&&(J=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
337
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
338
- return r?.stop?.() ?? []
339
- })()`}),console.log(` captured ${J.length} replay events`)),console.log(`
340
- + completed (${M.length} steps)`),k&&ke(k),b&&console.log(` video: ${b}`),console.log()}catch(u){if(r&&!k)try{k=await c.stopProfile()}catch{}if(S&&!b)try{b=await c.stopRecording(),E=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}console.error(`
341
- x failed: ${u.message}
342
- `),k&&(console.log(" partial profile:"),ke(k)),b&&console.log(` partial video: ${b}`);try{let d=c.lastFailedStep,v=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",O=h.join(n,v);await c.captureFailureBundle(O,{error:u,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),console.log(` failure bundle: ${O}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let v=h.join(n,"error.png");await c.captureFailureScreenshot(v),console.log(` error screenshot: ${v}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await me(F,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),D=1}finally{F.close()}if(D===0&&y)try{let u=await We(J??[]),d=["--origin",W,"--events",u];Z&&d.push("--public-origin",Z),b&&d.push("--video",b),b&&E&&Number.isFinite(E)&&d.push("--video-duration-ms",String(Math.round(E))),c.simId&&d.push("--sim",c.simId),Ae&&d.push("--open"),console.log(`
343
- preparing preview upload\u2026`);let{runUpload:v}=await import("./upload-OS3J5ZOS.js");await v(d,{})}catch(u){console.error(` preview upload failed: ${u?.message||u}`),D=1}return await H(),D}async function We(o){let{gzipSync:e}=await import("zlib"),t=o.map(s=>JSON.stringify(s)).join(`
344
- `)+(o.length?`
345
- `:""),r=e(Buffer.from(t,"utf8")),i=h.join(Me(),`sootsim-events-${Date.now()}.jsonl.gz`);return A.writeFileSync(i,r),console.log(` events: ${o.length} written to ${i} (${r.length} bytes gz)`),i}async function Le(o){let e=o[0],t=r=>o.find((i,s)=>o[s-1]===r);switch(e){case"start":{let{path:r,state:i}=we();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=X();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")||(o[1]&&!o[1].startsWith("-")?o[1]:void 0),i=o.includes("--validate")||o.includes("--video"),s=o.includes("--video"),n=X();n.active&&n.kept&&console.log(` auto-kept trailing action: ${n.candidate.summary}`);let l=ge(r||(i?Ke():void 0));if(l.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!l.valid){console.error(" flow draft is not valid:");for(let a of l.issues)console.error(` - ${a}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim flow start` to reset"),process.exit(1)}if(i){let a=Je(o,l.outputPath),m=await Ie(a);if(m!==0){console.error(`
346
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=m;return}Y(),console.log(` flow draft validated (${l.stepCount} step${l.stepCount===1?"":"s"})`),l.outputPath&&console.log(` saved: ${l.outputPath}`),s&&console.log(" video: recorded during validation run");return}if(Y(),console.log(` flow draft ended (${l.stepCount} step${l.stepCount===1?"":"s"})`),l.outputPath){console.log(` saved: ${l.outputPath}`),console.log(` next: sootsim flow ${l.outputPath} --record`);return}console.log(""),process.stdout.write(l.yaml);return}case"validate":{let r=o[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let i=G(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let s of i)console.error(` - ${s}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function je(o){return o[0]==="--sim"&&o.length>=2?[...o.slice(2),"--sim",o[1]]:o}async function ut(o){let e=je(o),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Le(e),0;let r=await Ie(e);return r!==0&&(process.exitCode=r),r}function ke(o){let e=o.avgMs>0?(1e3/o.avgMs).toFixed(1):"?",t=o.sampleCount>0?(o.jankFrames/o.sampleCount*100).toFixed(1):"0";console.log(`
347
- profile:`),console.log(` frames: ${o.frames}`),console.log(` total: ${o.totalMs.toFixed(1)}ms`),console.log(` avg: ${o.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${o.maxMs.toFixed(2)}ms`),o.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${o.layoutAvgMs.toFixed(2)}ms | render ${o.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${o.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${o.p95.toFixed(2)}ms`),console.log(` p99: ${o.p99.toFixed(2)}ms`),console.log(` jank: ${o.jankFrames}/${o.sampleCount} (${t}%) >16.67ms`);let r=Array.isArray(o.worstFrames)?o.worstFrames:[];if(r.length!==0){if(console.log(`
348
- worst frames:`),o.mode==="render-worker"){console.log(" total layout render copy t+");for(let i of r){let[s,n,l,a,m]=i;console.log(` ${n.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${m.toFixed(2).padStart(7)} ${String(s).padStart(5)}`)}return}console.log(` ${r.map(i=>i.toFixed(2)).join(", ")}`)}}function Ke(){return h.join(Me(),`sootsim-flow-draft-${Date.now()}.yaml`)}function Je(o,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<o.length;r++){let i=o[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&o.includes("--video")&&t.push("--record"),t}export{Ue as a,Ie as b,je as c,ut as d};
@@ -1,100 +0,0 @@
1
- /*! sootsim v0.1.65 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as c,b as p}from"./chunk-FU33BTPL.js";import{a as m,c as h}from"./chunk-ELZHT3LB.js";import{a as l,b as u,c as d}from"./chunk-UH4H5HXN.js";function O(){let e=l();return e?{available:!0,reason:null,detail:e}:{available:!1,reason:"no chromium-family browser found (chrome, chromium, edge, brave, arc)"}}async function P(e){if(e.headless)return{launched:!1,message:"the chromium driver launches a visible browser window and cannot run headless \u2014 a headless `chrome --headless=new` process exits immediately and the sim never connects. for headless automation use `--driver playwright`."};let r=l();if(!r)return{launched:!1,message:"chromium not found \u2014 install chrome or run `sootsim list --drivers`"};if(!e.url)return{launched:!1,message:"chromium driver requires a target url"};if(e.profileId||e.ephemeralProfile)return{launched:!1,message:"profiles require electron or playwright; browser tabs use your current Chrome profile"};try{let t=await d(e.url,{detached:e.detached??!0});return{launched:!0,message:`chromium launched \u2192 ${e.url}`,pid:t.pid,target:t.target??r,attachUrl:e.url}}catch(t){return{launched:!1,message:`chromium spawn failed: ${t instanceof Error?t.message:String(t)}`}}}var f={id:"chromium",name:"chromium",description:"system chrome / chromium / edge \u2014 visible window (headless: use playwright)",kind:"browser",availability:O,launch:P};function x(){let e=c();return e?{available:!0,reason:null,detail:`${e.kind} @ ${e.path}`}:{available:!1,reason:"sootsim desktop app not installed (run `sootsim install-desktop`)"}}async function k(e){let r=c();if(!r)return{launched:!1,message:"sootsim desktop app not installed"};try{let t=await p(e.url,r,{device:e.device,profileId:e.profileId,ephemeralProfile:e.ephemeralProfile});return t.launched?{launched:!0,message:e.url?`electron launched via ${t.via} \u2192 ${e.url}`:`electron launched via ${t.via}`,target:t.target,attachUrl:e.url}:{launched:!1,message:"desktop companion failed to start"}}catch(t){return{launched:!1,message:`electron launch failed: ${t instanceof Error?t.message:String(t)}`}}}var v={id:"electron",name:"electron",description:"sootsim desktop companion app (native window, menu bar)",kind:"native",availability:x,launch:k};import{spawn as I}from"child_process";import{closeSync as L,mkdtempSync as _,openSync as R,readFileSync as A}from"fs";import{createRequire as M}from"module";import{tmpdir as g}from"os";import{join as w}from"path";var $=`
3
- const modulePath = process.env.SOOTSIM_PW_MODULE;
4
- const url = process.env.SOOTSIM_PW_URL;
5
- const headless = process.env.SOOTSIM_PW_HEADLESS === '1';
6
- const userDataDir = process.env.SOOTSIM_PW_USERDATADIR || '';
7
- (async () => {
8
- const pw = require(modulePath);
9
- let browser = null;
10
- let context;
11
- let keepAlive = null;
12
- let connectTimer = null;
13
- let connected = false;
14
- let shuttingDown = false;
15
- const clearConnectTimer = () => {
16
- if (connectTimer) {
17
- clearTimeout(connectTimer);
18
- connectTimer = null;
19
- }
20
- };
21
- const shutdown = async (code = 0) => {
22
- if (shuttingDown) return;
23
- shuttingDown = true;
24
- clearConnectTimer();
25
- if (keepAlive) clearInterval(keepAlive);
26
- try {
27
- if (context) await context.close().catch(() => {});
28
- } catch {}
29
- try {
30
- if (browser) await browser.close().catch(() => {});
31
- } catch {}
32
- process.exit(code);
33
- };
34
- process.once('SIGTERM', () => { void shutdown(0); });
35
- process.once('SIGINT', () => { void shutdown(0); });
36
- // use the real Google Chrome install, not Playwright's bundled Chromium /
37
- // Chrome for Testing builds. local SootSim sessions should look like the
38
- // user's browser and must not leave behind a pile of "Chrome for Testing"
39
- // processes. NOTE: this is NOT enough to make \`sootsim cpu-profile\`
40
- // work \u2014 that profiles the tenant *worker*, and the JS Self-Profiler API
41
- // cannot be constructed in a dedicated worker by any means (see
42
- // worker-handlers/cpu-profile.ts). cpu-profile needs a CDP-based profiler
43
- // instead.
44
- const launchOpts = { headless, channel: 'chrome' };
45
- if (userDataDir) {
46
- context = await pw.chromium.launchPersistentContext(userDataDir, launchOpts);
47
- } else {
48
- browser = await pw.chromium.launch(launchOpts);
49
- context = await browser.newContext();
50
- }
51
- const hostMeta = {
52
- sootsimHostDriver: 'playwright',
53
- sootsimHostPid: process.pid,
54
- sootsimHostStartedAt: Date.now(),
55
- };
56
- await context.addInitScript({
57
- content: 'Object.defineProperty(window, "__sootsimHostMeta", { value: ' + JSON.stringify(hostMeta) + ', configurable: true });',
58
- });
59
- await context.exposeBinding('__sootsimHostClose', async () => {
60
- await shutdown(0);
61
- });
62
- await context.exposeBinding('__sootsimHostConnected', async () => {
63
- connected = true;
64
- clearConnectTimer();
65
- });
66
- const connectTimeoutMs = Number(process.env.SOOTSIM_PW_CONNECT_TIMEOUT_MS || 120000);
67
- connectTimer = setTimeout(() => {
68
- if (connected) return;
69
- process.stderr.write('[connect-timeout] sim did not register with the bridge within ' + connectTimeoutMs + 'ms; closing playwright host\\n');
70
- void shutdown(2);
71
- }, Number.isFinite(connectTimeoutMs) && connectTimeoutMs > 0 ? connectTimeoutMs : 120000);
72
- if (typeof connectTimer.unref === 'function') connectTimer.unref();
73
- const page = await context.newPage();
74
- // surface page-side failures (engine boot crash, failed WS registration)
75
- // to stderr so a sim that never connects produces a real diagnostic
76
- // instead of a silent "timed out waiting for opened sim to connect".
77
- page.on('pageerror', (e) => {
78
- process.stderr.write('[pageerror] ' + ((e && e.stack) || e) + '\\n');
79
- });
80
- page.on('console', (m) => {
81
- if (m.type() === 'error') {
82
- process.stderr.write('[console.error] ' + m.text() + '\\n');
83
- }
84
- });
85
- page.on('crash', () => process.stderr.write('[page] renderer crashed\\n'));
86
- try {
87
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
88
- } catch (err) {
89
- process.stderr.write('[goto] ' + String((err && err.message) || err) + '\\n');
90
- }
91
- keepAlive = setInterval(() => {}, 1 << 30);
92
- if (browser) browser.on('disconnected', () => { void shutdown(0); });
93
- context.on('close', () => { void shutdown(0); });
94
- page.on('close', () => { void shutdown(0); });
95
- })().catch((err) => {
96
- process.stderr.write(String((err && err.stack) || err) + '\\n');
97
- process.exit(1);
98
- });
99
- `;function y(){let e=[process.cwd()+"/"];try{process.argv[1]&&e.push(process.argv[1])}catch{}for(let r of e)try{let t=M(r);for(let i of["playwright","playwright-chromium","playwright-core"])try{return{spec:i,modulePath:t.resolve(i)}}catch{}}catch{}return null}function C(){let e=y();return e?{available:!0,reason:null,detail:`resolved via ${e.spec}`}:{available:!1,reason:"playwright not installed in the current workspace"}}function E(e){return e.profileId?m(h(e.profileId).id):e.ephemeralProfile?_(w(g(),"sootsim-playwright-profile-")):""}async function U(e){let r=y();if(!r)return{launched:!1,message:"playwright not installed \u2014 run `bun add -D playwright` first"};if(!e.url)return{launched:!1,message:"playwright driver requires a target url"};let t=w(g(),`sootsim-playwright-host-${Date.now().toString(36)}-${process.pid}.log`),i=R(t,"a");try{let n=I(process.execPath,["-e",$],{detached:!0,stdio:["ignore","ignore",i],env:{...process.env,SOOTSIM_PW_MODULE:r.modulePath,SOOTSIM_PW_URL:e.url,SOOTSIM_PW_HEADLESS:e.headless??!0?"1":"0",SOOTSIM_PW_USERDATADIR:E(e)}});n.unref();let s=await new Promise(o=>{let S=setTimeout(()=>o(null),4e3);n.once("exit",T=>{clearTimeout(S),o(T??0)})});if(s!==null&&s!==0){let o=A(t,"utf8").trim();return{launched:!1,message:`playwright host exited early (code ${s}) \u2014 host log ${t}${o?`:
100
- ${o}`:""}`}}return{launched:!0,message:`playwright chrome launched \u2192 ${e.url}`,pid:n.pid,target:r.spec,attachUrl:e.url}}catch(n){return{launched:!1,message:`playwright launch failed: ${n instanceof Error?n.message:String(n)}`}}finally{L(i)}}var D={id:"playwright",name:"playwright",description:"programmatic chromium via the playwright package \u2014 headless default",kind:"automation",availability:C,launch:U};function W(){return process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32"?{available:!1,reason:`unsupported platform: ${process.platform}`}:{available:!0,reason:null,detail:process.platform==="darwin"?"open(1)":process.platform==="win32"?"cmd /c start":"xdg-open(1)"}}async function H(e){if(e.headless)return{launched:!1,message:"system driver does not support --headless; use chromium or playwright"};if(!e.url)return{launched:!1,message:"system driver requires a target url"};if(e.profileId||e.ephemeralProfile)return{launched:!1,message:"profiles require electron or playwright; browser tabs use your current browser profile"};try{let r=await u(e.url,{detached:e.detached??!0,newWindow:e.newWindow});return{launched:!0,message:`${r.via} launch \u2192 ${e.url}`,pid:r.pid,target:r.target,attachUrl:e.url}}catch(r){return{launched:!1,message:`system launch failed: ${r instanceof Error?r.message:String(r)}`}}}var b={id:"system",name:"system",description:"shared browser launcher \u2014 system default or chromium window",kind:"delegate",availability:W,launch:H};var a=[f,v,D,b];function ie(){return a}function ne(e){return a.find(r=>r.id===e)??null}function oe(e,r){if(e)return a.find(i=>i.id===e)??null;for(let t of r){let i=a.find(n=>n.id===t);if(i&&i.availability().available)return i}return null}function ae(){return a.map(e=>{let r=e.availability();return{id:e.id,name:e.name,kind:e.kind,description:e.description,available:r.available,reason:r.reason,detail:r.detail??null}})}export{f as a,v as b,D as c,b as d,a as e,ie as f,ne as g,oe as h,ae as i};