@kaeawc/auto-mobile 0.0.92 → 0.0.94

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 (257) hide show
  1. package/dist/build-info.json +12 -12
  2. package/dist/schemas/test-plan.schema.json +370 -52
  3. package/dist/src/ble-peripheral.py +153 -0
  4. package/dist/src/{chunk-r14wwk37.js → chunk-026y62r9.js} +12 -12
  5. package/dist/src/chunk-0jyfg947.js +4 -0
  6. package/dist/src/{chunk-950qcq1e.js → chunk-0zfpp1wh.js} +4 -4
  7. package/dist/src/chunk-13qxf7ym.js +7 -0
  8. package/dist/src/chunk-1scenrk7.js +4 -0
  9. package/dist/src/chunk-1vb5ph1k.js +4 -0
  10. package/dist/src/chunk-20g565q7.js +5 -0
  11. package/dist/src/chunk-21h6dhdm.js +5 -0
  12. package/dist/src/{chunk-2e6s75qv.js → chunk-25mfpthk.js} +8 -8
  13. package/dist/src/{chunk-9rkfyt6q.js → chunk-2b39zyxc.js} +3 -3
  14. package/dist/src/chunk-2gzd6wbd.js +4 -0
  15. package/dist/src/{chunk-eka89q3k.js → chunk-3dntffy9.js} +1 -1
  16. package/dist/src/chunk-3gfczcsn.js +4 -0
  17. package/dist/src/chunk-3h5jz1vb.js +9 -0
  18. package/dist/src/chunk-41zcy6b3.js +5 -0
  19. package/dist/src/chunk-47n9m2de.js +4 -0
  20. package/dist/src/chunk-4vxeq0vd.js +58 -0
  21. package/dist/src/chunk-59dx6qaf.js +4 -0
  22. package/dist/src/chunk-5sdf9y92.js +4 -0
  23. package/dist/src/chunk-5wk1t46v.js +5 -0
  24. package/dist/src/chunk-661c50hh.js +17 -0
  25. package/dist/src/chunk-68n6bjjd.js +21 -0
  26. package/dist/src/{chunk-zg67wjkh.js → chunk-69pmjdf2.js} +3 -3
  27. package/dist/src/chunk-6hrj3jt6.js +145 -0
  28. package/dist/src/{chunk-b4cxdzwy.js → chunk-6myr26wx.js} +8 -8
  29. package/dist/src/chunk-6n96k09n.js +4 -0
  30. package/dist/src/chunk-6vwrbkre.js +4 -0
  31. package/dist/src/chunk-6wk0yrab.js +4 -0
  32. package/dist/src/chunk-6yhm9een.js +4 -0
  33. package/dist/src/chunk-7k7gjg2t.js +7 -0
  34. package/dist/src/chunk-7n5fz68h.js +4 -0
  35. package/dist/src/chunk-8cvnpnbp.js +4 -0
  36. package/dist/src/chunk-8kzv7rk7.js +4 -0
  37. package/dist/src/chunk-8nj68t1v.js +167 -0
  38. package/dist/src/{chunk-r20pe1nv.js → chunk-96r3bpg7.js} +3 -3
  39. package/dist/src/chunk-97x887te.js +4 -0
  40. package/dist/src/{chunk-sz1a7p43.js → chunk-99a6tbvd.js} +1 -1
  41. package/dist/src/chunk-9p5d2994.js +5 -0
  42. package/dist/src/{chunk-w7zsh13a.js → chunk-9q265er0.js} +4 -4
  43. package/dist/src/chunk-9xgnrv5w.js +5 -0
  44. package/dist/src/chunk-9xgsmshb.js +5 -0
  45. package/dist/src/chunk-a02d1wgv.js +4 -0
  46. package/dist/src/{chunk-km0dy5vc.js → chunk-a9ps00a1.js} +10 -10
  47. package/dist/src/chunk-aewdveet.js +5 -0
  48. package/dist/src/chunk-b3tdtq7r.js +9 -0
  49. package/dist/src/chunk-bn7jx7a2.js +4 -0
  50. package/dist/src/chunk-bnyw27ja.js +4 -0
  51. package/dist/src/{chunk-s1zq65ny.js → chunk-bpwsg76p.js} +2 -2
  52. package/dist/src/chunk-bvranw3g.js +4 -0
  53. package/dist/src/chunk-c25a84zb.js +4 -0
  54. package/dist/src/chunk-c27yv1dx.js +5 -0
  55. package/dist/src/chunk-c3ewxm4x.js +5 -0
  56. package/dist/src/chunk-cb1ga9rd.js +7 -0
  57. package/dist/src/chunk-cn7fwy7k.js +4 -0
  58. package/dist/src/chunk-cnvy4a64.js +4 -0
  59. package/dist/src/chunk-cqhw4yr6.js +5 -0
  60. package/dist/src/{chunk-v90es00d.js → chunk-ctmfshjc.js} +2 -2
  61. package/dist/src/chunk-ctwmhz13.js +4 -0
  62. package/dist/src/{chunk-qv2918jt.js → chunk-d3jx9bz5.js} +2 -2
  63. package/dist/src/{chunk-wry6skrm.js → chunk-d6rb08ga.js} +1 -1
  64. package/dist/src/chunk-ddqhj4eg.js +5 -0
  65. package/dist/src/{chunk-d57432wq.js → chunk-ddrhs1c3.js} +2 -2
  66. package/dist/src/chunk-dnjnh9p6.js +4 -0
  67. package/dist/src/{chunk-ajsrz473.js → chunk-dw5rwgya.js} +3 -3
  68. package/dist/src/chunk-e0870khr.js +5 -0
  69. package/dist/src/chunk-ea3k10kj.js +4 -0
  70. package/dist/src/chunk-emv82m1w.js +7 -0
  71. package/dist/src/chunk-f3m6pdnx.js +4 -0
  72. package/dist/src/chunk-f84z32cb.js +4 -0
  73. package/dist/src/chunk-fpczgf0z.js +4 -0
  74. package/dist/src/chunk-g2js4c2v.js +971 -0
  75. package/dist/src/chunk-g3af2qbk.js +5 -0
  76. package/dist/src/chunk-gadtna7s.js +11 -0
  77. package/dist/src/{chunk-c9nk1r78.js → chunk-gcyx407v.js} +3 -3
  78. package/dist/src/{chunk-jdqvcq0a.js → chunk-gfpntwc1.js} +3 -3
  79. package/dist/src/chunk-gmnm5e3e.js +4 -0
  80. package/dist/src/chunk-gp6vb5gf.js +4 -0
  81. package/dist/src/chunk-gppgy7pa.js +4 -0
  82. package/dist/src/chunk-hegfz0ae.js +5 -0
  83. package/dist/src/chunk-hpzxdp1k.js +17 -0
  84. package/dist/src/{chunk-2v7tw1nj.js → chunk-j69g8b50.js} +3 -3
  85. package/dist/src/chunk-jvstjnqm.js +19 -0
  86. package/dist/src/chunk-jzqrv78s.js +4 -0
  87. package/dist/src/chunk-k2948b8d.js +4 -0
  88. package/dist/src/chunk-k4ftd40d.js +4 -0
  89. package/dist/src/chunk-kd9vfaxh.js +5 -0
  90. package/dist/src/{chunk-34zxqcmq.js → chunk-kdczmgwk.js} +3 -3
  91. package/dist/src/chunk-ke3wn14v.js +4 -0
  92. package/dist/src/chunk-kh5n7m6w.js +4 -0
  93. package/dist/src/{chunk-0dfnyfkh.js → chunk-khejfph4.js} +3 -3
  94. package/dist/src/chunk-kny2xemh.js +4 -0
  95. package/dist/src/chunk-knyzw9md.js +4 -0
  96. package/dist/src/chunk-mbzpt2hp.js +4 -0
  97. package/dist/src/chunk-mm8rcxad.js +4 -0
  98. package/dist/src/chunk-nc4516tx.js +4 -0
  99. package/dist/src/{chunk-stfzjr9y.js → chunk-ntfrqrqn.js} +5 -5
  100. package/dist/src/chunk-nz5h2j52.js +4 -0
  101. package/dist/src/chunk-p22s97qy.js +4 -0
  102. package/dist/src/chunk-p9kt1sgr.js +6 -0
  103. package/dist/src/{chunk-9y5bcy28.js → chunk-pf282r5g.js} +4 -4
  104. package/dist/src/chunk-pnd4mrxy.js +4 -0
  105. package/dist/src/chunk-pqqteyj6.js +4 -0
  106. package/dist/src/chunk-qj1tbnv2.js +8 -0
  107. package/dist/src/chunk-qnh9egwr.js +4 -0
  108. package/dist/src/chunk-qy3khhf8.js +8 -0
  109. package/dist/src/chunk-r0vp315h.js +11 -0
  110. package/dist/src/chunk-r4j43b9s.js +237 -0
  111. package/dist/src/{chunk-4pfftt07.js → chunk-r54cxxze.js} +3 -3
  112. package/dist/src/chunk-r6pvhj33.js +325 -0
  113. package/dist/src/chunk-rb7aa5gr.js +54 -0
  114. package/dist/src/chunk-rdj50kb4.js +4 -0
  115. package/dist/src/chunk-rnd4vcas.js +4 -0
  116. package/dist/src/chunk-s3y3zfcx.js +14 -0
  117. package/dist/src/chunk-s4g43k75.js +5 -0
  118. package/dist/src/chunk-sfqe223f.js +311 -0
  119. package/dist/src/chunk-sqdrxjw5.js +7 -0
  120. package/dist/src/{chunk-0w1spptt.js → chunk-t54k47em.js} +4 -4
  121. package/dist/src/chunk-tek4pnvv.js +26 -0
  122. package/dist/src/chunk-tn74y7af.js +4 -0
  123. package/dist/src/chunk-tvq0nzam.js +5 -0
  124. package/dist/src/chunk-tx4f0h9c.js +6 -0
  125. package/dist/src/chunk-vdqag3fj.js +5 -0
  126. package/dist/src/chunk-vz5zzs57.js +4 -0
  127. package/dist/src/chunk-w4s2vfpj.js +4 -0
  128. package/dist/src/chunk-w5yypt53.js +42 -0
  129. package/dist/src/{chunk-r0f1q783.js → chunk-w68v64vh.js} +3 -3
  130. package/dist/src/chunk-whwj0pdk.js +5 -0
  131. package/dist/src/chunk-wnmqt1dc.js +4 -0
  132. package/dist/src/{chunk-8en08r7q.js → chunk-wpe46vsa.js} +3 -3
  133. package/dist/src/chunk-wxdjeb4k.js +27 -0
  134. package/dist/src/chunk-xcqzwf9j.js +247 -0
  135. package/dist/src/chunk-xezekwwn.js +5 -0
  136. package/dist/src/chunk-xf19m15s.js +4 -0
  137. package/dist/src/chunk-xghbxha4.js +4 -0
  138. package/dist/src/{chunk-jhnbfj19.js → chunk-xn9m3xc2.js} +5 -5
  139. package/dist/src/{chunk-a4k9rt7z.js → chunk-yqfz4vts.js} +3 -3
  140. package/dist/src/chunk-z8tvs8nk.js +5 -0
  141. package/dist/src/chunk-zm2rehqb.js +5 -0
  142. package/dist/src/chunk-zs6dqm35.js +4 -0
  143. package/dist/src/daemon/processEntry.js +2 -2
  144. package/dist/src/index.js +4 -4
  145. package/dist/src/runtime/bunRuntimeGuard.js +2 -2
  146. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -2
  147. package/ios/CameraPosterInjection/Injection/CameraPosterInjection.m +466 -0
  148. package/package.json +4 -3
  149. package/schemas/test-plan.schema.json +370 -52
  150. package/dist/src/chunk-09442h7v.js +0 -4
  151. package/dist/src/chunk-0e4gm1kj.js +0 -5
  152. package/dist/src/chunk-0eb8576f.js +0 -4
  153. package/dist/src/chunk-0rjm4nx7.js +0 -5
  154. package/dist/src/chunk-1zmh2eak.js +0 -4
  155. package/dist/src/chunk-28k63ha3.js +0 -5
  156. package/dist/src/chunk-2d4wmp8b.js +0 -4
  157. package/dist/src/chunk-32jpxz2y.js +0 -323
  158. package/dist/src/chunk-3jmvqygr.js +0 -238
  159. package/dist/src/chunk-3swvfhqt.js +0 -5
  160. package/dist/src/chunk-44bt78m9.js +0 -5
  161. package/dist/src/chunk-488vt2bp.js +0 -4
  162. package/dist/src/chunk-4fgdhcwx.js +0 -5
  163. package/dist/src/chunk-4jp2se4w.js +0 -4
  164. package/dist/src/chunk-4vhr9e4t.js +0 -4
  165. package/dist/src/chunk-4xd6zs3y.js +0 -15
  166. package/dist/src/chunk-51567pg8.js +0 -4
  167. package/dist/src/chunk-5agqsfev.js +0 -4
  168. package/dist/src/chunk-5d706gmr.js +0 -4
  169. package/dist/src/chunk-5kd4rqk7.js +0 -5
  170. package/dist/src/chunk-61t538bm.js +0 -4
  171. package/dist/src/chunk-6d3mmqxt.js +0 -54
  172. package/dist/src/chunk-6hyt398x.js +0 -5
  173. package/dist/src/chunk-6mnr8kpm.js +0 -4
  174. package/dist/src/chunk-79q5xsdc.js +0 -42
  175. package/dist/src/chunk-7bdgand3.js +0 -4
  176. package/dist/src/chunk-84cp9dw5.js +0 -4
  177. package/dist/src/chunk-86f2h5ww.js +0 -5
  178. package/dist/src/chunk-8cghfzb2.js +0 -19
  179. package/dist/src/chunk-9tf2p9y9.js +0 -5
  180. package/dist/src/chunk-a2sc4jm0.js +0 -5
  181. package/dist/src/chunk-aa5ng3d1.js +0 -4
  182. package/dist/src/chunk-b3h0a6ca.js +0 -4
  183. package/dist/src/chunk-b6a737qt.js +0 -4
  184. package/dist/src/chunk-bn64x5z5.js +0 -5
  185. package/dist/src/chunk-bvh649za.js +0 -12
  186. package/dist/src/chunk-c9tyfg4j.js +0 -26
  187. package/dist/src/chunk-cfsdfqnm.js +0 -4
  188. package/dist/src/chunk-cxyf04jc.js +0 -7
  189. package/dist/src/chunk-da08tx5v.js +0 -4
  190. package/dist/src/chunk-f2tc08m2.js +0 -4
  191. package/dist/src/chunk-f8tnk179.js +0 -5
  192. package/dist/src/chunk-f9s1kkhx.js +0 -5
  193. package/dist/src/chunk-fbp8a4rx.js +0 -4
  194. package/dist/src/chunk-fd2z0sze.js +0 -4
  195. package/dist/src/chunk-fk927f4q.js +0 -54
  196. package/dist/src/chunk-fxmr3a0f.js +0 -4
  197. package/dist/src/chunk-gaqwhd44.js +0 -4
  198. package/dist/src/chunk-ggtd5x5a.js +0 -5
  199. package/dist/src/chunk-gndcfrm7.js +0 -4
  200. package/dist/src/chunk-h3n4adc6.js +0 -310
  201. package/dist/src/chunk-h5pjbb83.js +0 -4
  202. package/dist/src/chunk-hgnnh302.js +0 -4
  203. package/dist/src/chunk-hmke8nhx.js +0 -5
  204. package/dist/src/chunk-j2bx12hn.js +0 -4
  205. package/dist/src/chunk-j70y1a2g.js +0 -4
  206. package/dist/src/chunk-js1jpyxp.js +0 -6
  207. package/dist/src/chunk-kbjq0qvb.js +0 -4
  208. package/dist/src/chunk-kfwx57xd.js +0 -4
  209. package/dist/src/chunk-kzwctna2.js +0 -4
  210. package/dist/src/chunk-m9ehyehy.js +0 -4
  211. package/dist/src/chunk-mct91p1f.js +0 -4
  212. package/dist/src/chunk-mf9spd4g.js +0 -5
  213. package/dist/src/chunk-mgrcansb.js +0 -4
  214. package/dist/src/chunk-mqc1d0eb.js +0 -6
  215. package/dist/src/chunk-n1zmpk0z.js +0 -4
  216. package/dist/src/chunk-ncyjf63g.js +0 -4
  217. package/dist/src/chunk-nr64d21q.js +0 -973
  218. package/dist/src/chunk-nwm2pq5v.js +0 -168
  219. package/dist/src/chunk-pm06b05d.js +0 -9
  220. package/dist/src/chunk-q50s00ry.js +0 -4
  221. package/dist/src/chunk-qwye1958.js +0 -14
  222. package/dist/src/chunk-r8z9pfve.js +0 -5
  223. package/dist/src/chunk-rdpgkjf6.js +0 -4
  224. package/dist/src/chunk-rkr0dks9.js +0 -5
  225. package/dist/src/chunk-rn84t3sf.js +0 -11
  226. package/dist/src/chunk-s123kn7n.js +0 -4
  227. package/dist/src/chunk-s73qn3fx.js +0 -4
  228. package/dist/src/chunk-sjn0nj4p.js +0 -5
  229. package/dist/src/chunk-sns0c35v.js +0 -7
  230. package/dist/src/chunk-t4dr5c8v.js +0 -8
  231. package/dist/src/chunk-tc8k9c1j.js +0 -4
  232. package/dist/src/chunk-teznhase.js +0 -4
  233. package/dist/src/chunk-ty9xgmz4.js +0 -4
  234. package/dist/src/chunk-tyazf3sk.js +0 -145
  235. package/dist/src/chunk-v6npjrjm.js +0 -5
  236. package/dist/src/chunk-vbvtzkwz.js +0 -5
  237. package/dist/src/chunk-vefd8qee.js +0 -8
  238. package/dist/src/chunk-vs9r72ta.js +0 -17
  239. package/dist/src/chunk-w2mwa0jk.js +0 -4
  240. package/dist/src/chunk-w88k0bgr.js +0 -4
  241. package/dist/src/chunk-wzdt0enk.js +0 -4
  242. package/dist/src/chunk-xhhv854c.js +0 -4
  243. package/dist/src/chunk-y58270hd.js +0 -4
  244. package/dist/src/chunk-yk0hmbex.js +0 -4
  245. package/dist/src/chunk-ympy4fdz.js +0 -28
  246. package/dist/src/chunk-yw436axy.js +0 -4
  247. package/dist/src/chunk-z04jrpjy.js +0 -5
  248. package/dist/src/chunk-z2xznczw.js +0 -4
  249. package/dist/src/chunk-z4xnrgps.js +0 -4
  250. package/dist/src/chunk-z7csyszv.js +0 -4
  251. package/dist/src/chunk-z8t0v07j.js +0 -11
  252. package/dist/src/chunk-z916af47.js +0 -228
  253. package/dist/src/chunk-zcr8he8q.js +0 -5
  254. package/dist/src/chunk-zd9vmkzn.js +0 -9
  255. package/dist/src/chunk-zj939v0h.js +0 -5
  256. package/dist/src/chunk-zkdjwtc1.js +0 -4
  257. package/dist/src/chunk-zkv5kzt6.js +0 -4
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ import{i,l,e}from"./chunk-r0vp315h.js";import{Fte,jC,Lte,yl}from"./chunk-4vxeq0vd.js";import{B}from"./chunk-r6pvhj33.js";import{w,v,at,Ya,E}from"./chunk-sfqe223f.js";import{gn,Nn}from"./chunk-aewdveet.js";import{od}from"./chunk-b3tdtq7r.js";import{ow}from"./chunk-xn9m3xc2.js";import{o6}from"./chunk-96r3bpg7.js";import{dh,fm}from"./chunk-s3y3zfcx.js";import{$a,gg}from"./chunk-cb1ga9rd.js";import{r,t,u}from"./chunk-2b39zyxc.js";var X1=2,dI=100,Qf=200,tA=1,lI=5000,i6=3000,eh=20000,qe=50;function DX(n,o,s){let a=[];for(let[d,c]of n.points.entries()){let p=od({x:c.x,y:c.y,coordinateSpace:n.coordinateSpace},o,s,"dragPath");if("error"in p)return{error:`points[${d}]: ${p.error}`};a.push({x:p.x,y:p.y})}return{points:a}}function OX(n,o){if(n.length<X1)throw new t(`dragPath needs at least ${X1} points`);let s=o.holdMs??0,a=o.releaseHoldMs??0,d=[],c=0;for(let p=1;p<n.length;p++){let h=n[p-1],m=n[p],f=o.points[p]?.durationMs??Qf,y=Math.max(1,Math.ceil(f/qe));for(let S=1;S<=y;S++){let g=S/y;d.push({atMs:c+Math.round(f*g),x:S===y?m.x:Math.round(h.x+(m.x-h.x)*g),y:S===y?m.y:Math.round(h.y+(m.y-h.y)*g)})}c+=f}return{start:n[0],holdMs:s,moves:d,releaseHoldMs:a,totalMs:s+c+a,vertices:n}}function MX(n){let o=[{x:n.start.x,y:n.start.y,offsetMs:0}];if(n.holdMs>0)o.push({x:n.start.x,y:n.start.y,offsetMs:n.holdMs});for(let a of n.moves)o.push({x:a.x,y:a.y,offsetMs:n.holdMs+a.atMs});let s=o[o.length-1];if(n.releaseHoldMs>0)o.push({x:s.x,y:s.y,offsetMs:s.offsetMs+n.releaseHoldMs});return o}function nN(n,o,s=0){if(n>eh)throw new t(`dragPath total duration ${n} ms exceeds the ${eh} ms limit; shorten the segments or holds. No input was sent.`);if(o===void 0)return;let a=n+s+Ya;if(a>o)throw new t(`dragPath duration ${n} ms does not fit the remaining request budget (${o} ms; needs ${a} ms including dispatch headroom); no input was sent. Increase the request timeout or shorten the path.`)}function C(n){if(n.toolType!=="stylus"&&n.toolType!=="eraser")return;let o={toolType:n.toolType};if(n.pressure?.normalized)o.pressure=Math.round(n.pressure.mean*1e4)/1e4;if(n.tilt!==void 0)o.tilt=n.tilt;if(n.buttons?.length)o.buttons=n.buttons.map((s)=>s==="stylusPrimary"?"primary":"secondary");return o}var A={TOUCH_SLOP_DP:8,STROKE_PRESSURE_RANGE:0.05,PEN_MAX_SAMPLES:100,LONG_PRESS_MS:400,TAP_TIMEOUT_MS:100,DOUBLE_TAP_MS:300,DOUBLE_TAP_SLOP_DP:100,FLING_MIN_DP_PER_S:50,PINCH_MIN_SCALE_DELTA:0.1};function b(n){return Boolean(n.unknownAxes?.length)}function Je(n,o){return n.type==="tap"&&n.toolType===o.toolType&&!b(n)&&n.screenX!==void 0&&n.screenY!==void 0}function fe(n,o){if(!Je(n,o))return!1;let s=o.arrivedAt-n.arrivedAt,a=s>=0&&s<=A.DOUBLE_TAP_MS;if(o.firstTapArrivedAt!==void 0)return n.arrivedAt===o.firstTapArrivedAt&&a;let d=(o.screenX??1/0)-(n.screenX??1/0),c=(o.screenY??1/0)-(n.screenY??1/0);return a&&Math.hypot(d,c)<=A.DOUBLE_TAP_SLOP_DP}function ye(n,o){return n.kernelAtMs!==void 0&&o.kernelAtMs!==void 0?n.kernelAtMs-o.kernelAtMs:n.arrivedAt-o.arrivedAt}function X(n){let o=n.type==="stroke"?n.path:n.hover;if(n.type!=="stroke"&&n.type!=="hover"||n.toolType!=="stylus"||b(n)||!o||o.length<2)return!1;return o.reduce((a,d,c)=>a+(c>0?ye(d,o[c-1]):0),0)>eh}function ge(n){let o=n.type==="stroke"?n.path:n.hover;if(n.toolType!=="stylus"||b(n)||!o?.length||n.type==="stroke"&&o.length<2||X(n))return null;let s=et(o);return{tool:n.type==="stroke"?"dragPath":"hoverAt",params:{points:s,...n.type==="hover"?{toolType:"stylus"}:{pointer:C(n)}}}}function Ze(n,o,s){let a=Math.ceil(s/lI);return Array.from({length:a},(d,c)=>{let p=(c+1)/a,h={...o,x:n.x+(o.x-n.x)*p,y:n.y+(o.y-n.y)*p,durationMs:Math.round(s*p)-Math.round(s*c/a)};for(let m of["pressure","distance"])if(n[m]!==void 0&&o[m]!==void 0)h[m]=n[m]+(o[m]-n[m])*p;return c===a-1?{...o,durationMs:h.durationMs}:h})}function Qe(n){while(n.length>dI){let o=(p)=>p.pressure??p.distance??0,s=n.reduce((p,h,m)=>o(h)<o(n[p])?m:p,0),a=n.reduce((p,h,m)=>o(h)>o(n[p])?m:p,0),d=1/0,c=1;for(let p=1;p<n.length-1;p++){let h=n[p].durationMs+n[p+1].durationMs;if(p!==s&&p!==a&&h<d)d=h,c=p}n[c+1].durationMs=d,n.splice(c,1)}}function et(n){let o=[],s=0,a=0;for(let[d,c]of n.entries()){let{arrivedAt:p,kernelAtMs:h,...m}=c;if(d===0){o.push(m);continue}s+=Math.max(0,ye({arrivedAt:p,kernelAtMs:h},n[d-1]));let f=Math.round(s),y=f-a;if(y<tA){if(d!==n.length-1)continue;if(o.length===1)o.push({...m,durationMs:tA});else o[o.length-1]={...m,durationMs:o.at(-1).durationMs};continue}o.push(...Ze(o.at(-1),m,y)),a=f}return Qe(o),o}var tt="a pen gesture made with the eraser end was exported as an eraser step; replay injects an eraser only on a root adb shell with a uinput tool and refuses that step elsewhere",rt="a pen gesture without a known position or path was not exported: replaying it as a finger would be wrong",nt=`a stylus stroke was not exported because its duration exceeds the ${eh/1000} second replay limit; record a shorter stroke`,it=`a stylus hover was not exported because its duration exceeds the ${eh/1000} second replay limit; record a shorter hover`,ot="a pen hovered over the screen without touching it; no known position or hover distance was recorded, so nothing was exported for it",st="a stylus double tap was exported, but replay refuses stylus double taps, so that step will fail when run";function lt(n,o){if(n.toolType===void 0)return;if(n.type==="hover")return o?void 0:X(n)?it:ot;if(!o)return X(n)?nt:rt;if(o.params.pointer!==void 0&&o.params.action==="doubleTap")return st;return n.toolType==="eraser"?tt:void 0}function K(n,o,s){let a=lt(o,s);if(a)n.add(a)}var Te=0,be=1,Ae=24,xe=26,we=27,Pe=53,Ee=54,Re=58;function Z(n){let o=/^(add|remove) device \d+:\s+(\/dev\/input\/event\d+)\s*$/.exec(n);return o?{action:o[1]==="add"?"add":"remove",path:o[2]}:null}async function Me(n){let{stdout:o}=await n.executeCommand("shell getevent -p"),s=Q(o);if(s.touch===null&&s.pen.length===0)e.warn("[InputNodeDiscovery] No multitouch or pen input device found");return s}function Q(n){let o=ut(n);return{touch:o.find((s)=>s.kind==="touch")??null,pen:o.filter((s)=>s.kind==="pen")}}function ut(n){let o=[];for(let s of mt(n)){let a=s.abs.get(Pe),d=s.abs.get(Ee);if(a&&d){o.push(ve(s,a,d,{pressure:s.abs.get(Re),kind:"touch"}));continue}let c=s.abs.get(Te),p=s.abs.get(be);if(c&&p&&s.hasPenTool)o.push(ve(s,c,p,{pressure:s.abs.get(Ae),kind:"pen"}))}return o}function ve(n,o,s,{pressure:a,kind:d}){let c=n.abs.get(d==="pen"?25:59),p=n.abs.get(xe),h=n.abs.get(we);return{path:n.path,name:n.name,axisXMin:o.min,axisXMax:o.max,axisYMin:s.min,axisYMax:s.max,kind:d,...c&&c.max>c.min?{distanceRange:c}:{},...p&&h?{tiltAxes:{x:p,y:h}}:{},...a&&a.max>a.min?{pressureMin:a.min,pressureMax:a.max}:{}}}var Se=/\b(?:BTN_TOOL_PEN|BTN_TOOL_RUBBER|0140|0141)\b/,dt={ABS_X:Te,ABS_Y:be,ABS_PRESSURE:Ae,ABS_DISTANCE:25,ABS_MT_DISTANCE:59,ABS_TILT_X:xe,ABS_TILT_Y:we,ABS_MT_POSITION_X:Pe,ABS_MT_POSITION_Y:Ee,ABS_MT_PRESSURE:Re},ct=/^\s*(?:ABS\s*\(0003\):\s*)?(?:(ABS_\w+)(?:\s+\(([0-9a-f]{4})\))?|([0-9a-f]{4}))\s*:\s+value\s+-?\d+,\s*min\s+(-?\d+),\s*max\s+(-?\d+)/,pt=/^\s+(\w+)\s*\([0-9a-f]{4}\):(.*)$/;function ht(n){let o=n[2]??n[3];return o?parseInt(o,16):dt[n[1]]}function mt(n){let o=[],s=null,a={inKeyBlock:!1};for(let d of n.split(`
3
+ `)){let c=Z(d);if(c?.action==="add"){let{path:p}=c;s={path:p,name:p,abs:new Map,hasPenTool:!1},o.push(s),a.inKeyBlock=!1}else if(s)ft(s,d,a)}return o}function ft(n,o,s){let a=o.match(/^\s+name:\s+"(.+)"/);if(a){n.name=a[1],s.inKeyBlock=!1;return}let d=o.match(ct);if(d){let h=ht(d);if(h!==void 0)n.abs.set(h,yt(d,o));s.inKeyBlock=!1;return}let c=o.match(pt);if(c){if(s.inKeyBlock=c[1]==="KEY"||c[1]==="EV_KEY",s.inKeyBlock&&Se.test(c[2]))n.hasPenTool=!0;return}let p=/^\s+[\w ]+$/.test(o);if(s.inKeyBlock&&p&&Se.test(o))n.hasPenTool=!0;else if(!p)s.inKeyBlock=!1}function yt(n,o){let s=o.match(/,\s*resolution\s+(\d+)/);return{min:parseInt(n[4],10),max:parseInt(n[5],10),...s?{resolution:parseInt(s[1],10)}:{}}}var ee=500,te="display rotation could not be read; touch coordinates and swipe directions may be mapped with the wrong rotation",gt="display size could not be read after a display change; touch coordinates may be scaled with the wrong size";function vt(n,o){return`display size changed from ${n.width}x${n.height} to ${o.width}x${o.height} (fold/unfold?); touches are still read from the touch node chosen when recording started, so coordinates may refer to a different panel`}class W{axes;entries;changeReports=[];baselineDisplay;followers=[];constructor(n,o,s,a=[]){this.axes=n;this.baselineDisplay=o.display,this.entries=[this.entry(o,s,a)]}scalerAt(n){return this.entryAt(n).scaler}geometryAt(n){let{rotation:o,display:s}=this.entryAt(n),a=o%2!==0;return{deviceWidth:a?s.height:s.width,deviceHeight:a?s.width:s.height,orientation:o}}get currentRotation(){return this.entries[this.entries.length-1].rotation}get lastKnownGoodAt(){for(let n=this.entries.length-1;n>=0;n--)if(this.entries[n].caveats.length===0)return this.entries[n].reportedAt;return this.entries[0].reportedAt}noteChangeReported(n){this.changeReports.push(n);for(let o of this.followers)o.noteChangeReported(n)}follow(n){return n.entries.splice(0,n.entries.length,...this.entries.map((o)=>n.entry(o,o.reportedAt,o.caveats))),n.changeReports.splice(0,n.changeReports.length,...this.changeReports),this.followers.push(n),()=>{let o=this.followers.indexOf(n);if(o!==-1)this.followers.splice(o,1)}}apply(n,o){for(let c of this.followers)c.apply(n,o);let s=this.entries[this.entries.length-1],a=[];if(n.rotation===null)a.push(te);if(n.display===null)a.push(gt);let d={rotation:n.rotation??s.rotation,display:n.display??s.display};if(d.display.width!==this.baselineDisplay.width||d.display.height!==this.baselineDisplay.height)a.push(vt(this.baselineDisplay,d.display));this.entries.push(this.entry(d,Math.max(o,s.reportedAt),a))}warningsFor(n,o){let s=new Set(this.entryAt(n).caveats);if(this.changeReports.some((d)=>d>n&&d<=o))s.add("gesture spans a display rotation/size change; its coordinates and direction mix two geometries");else if(this.changeReports.some((d)=>d>=n-ee&&d<=o+ee))s.add(`display rotation/size changed within ${ee} ms of this gesture; its coordinates or direction may use a stale rotation`);return[...s]}entryAt(n){let o=this.entries[0];for(let s of this.entries){if(s.reportedAt>n)break;o=s}return o}entry(n,o,s){return{...n,reportedAt:o,caveats:s,scaler:Fte({...this.axes,displayWidth:n.display.width,displayHeight:n.display.height,rotation:n.rotation})}}}function Ie(n,o,s,{startedAt:a,caveats:d}){return o.map((c)=>{let p=new W({xMin:c.axisXMin,xMax:c.axisXMax,yMin:c.axisYMin,yMax:c.axisYMax},s,a,d),h=n.follow(p);return{node:c,scaler:p,stopFollowing:h}})}var St=0,_e=1000;function De(n){return{readRotation:()=>yl(n,{timeoutMs:_e}),readPhysicalSize:()=>jC(n,{timeoutMs:_e})}}function Ge(n){return n!==void 0&&Number.isInteger(n)&&n>=0&&n<=3}class re{timeline;probe;timer;refreshChain=Promise.resolve();generation=0;disposed=!1;constructor(n,o,s){this.timeline=n;this.probe=o;this.timer=s}dispose(){this.disposed=!0,this.refreshChain=Promise.resolve()}handleTransition(n){if(this.disposed||n.displayId!==St||n.change==="removed")return;let o=this.timer.now(),s=++this.generation;if(this.timeline.noteChangeReported(o),Ge(n.rotation))this.timeline.apply({rotation:n.rotation},o);let a=Ge(n.rotation);this.refreshChain=this.refreshChain.then(()=>this.refresh(o,a,s))}async settle(){let n;do n=this.refreshChain,await n;while(n!==this.refreshChain)}async verifyAtStop(){if(this.disposed)return;let n=await this.probe.readRotation().then(void 0,(s)=>{if(!this.disposed)throw s;return e.debug("[DisplayGeometryTracker] Cancelled stop-time geometry read failed",s),null});if(this.disposed)return;if(n===null)throw Error("WindowManager did not report a display rotation at stop");let o=this.timeline.currentRotation;if(n!==o)return`display rotation at stop (${n}) differs from the rotation tracked during recording (${o}); a rotation was not reported, so tapAt and swipeOn steps after it may be recorded at the wrong coordinates or direction`;return}async refresh(n,o,s){if(this.disposed||s!==this.generation)return;let a=o?void 0:await this.readRotationOrNull();if(this.disposed)return;let d=await this.readSizeOrNull();if(this.disposed||s!==this.generation)return;this.timeline.apply({rotation:a,display:d},n)}async readRotationOrNull(){try{return await this.probe.readRotation()}catch(n){return e.warn(`[DisplayGeometryTracker] Failed to read rotation after a display change: ${r(n)}`,n),null}}async readSizeOrNull(){try{return await this.probe.readPhysicalSize()}catch(n){return e.warn(`[DisplayGeometryTracker] Failed to read display size after a display change: ${r(n)}`,n),null}}}var Ne=(n,o,s)=>({type:"hover",arrivedAt:o,toolType:n,...s.samples.length?{hover:s.samples}:{}});class ne{nodeEpisode;slotEpisodes=new Map;penEntered(){this.nodeEpisode??={touched:!1,samples:[]}}penTouched(){this.nodeEpisode??={touched:!1,samples:[]},this.nodeEpisode.touched=!0}penLeft(n,o){let s=this.nodeEpisode;return this.nodeEpisode=void 0,s&&!s.touched?Ne(n,o,s):null}slotHovering(n,o,s,a){if(!this.slotEpisodes.has(n))this.slotEpisodes.set(n,{touched:!1,samples:[]});this.sample(this.slotEpisodes.get(n),o,s,a)}penHovering(n,o,s){if(this.nodeEpisode)this.sample(this.nodeEpisode,n,o,s)}sample(n,o,s,a){if(n.touched||!Number.isFinite(o.x)||!Number.isFinite(o.y)||o.distance===void 0||!Number.isFinite(o.distance))return;if(n.samples.length>=A.PEN_MAX_SAMPLES)n.samples=n.samples.filter((d,c)=>c===0||c%2===1);n.samples.push({x:o.x,y:o.y,distance:o.distance,arrivedAt:s,...a===void 0?{}:{kernelAtMs:a}})}slotTouching(n){this.slotEpisodes.set(n,{touched:!0,samples:[]})}slotReleased(n,o,s){let a=this.slotEpisodes.get(n);return this.slotEpisodes.delete(n),a&&!a.touched&&o?Ne(o,s,a):null}}var Tt={KEY_BACK:"back",KEY_HOME:"home",KEY_MENU:"menu",KEY_POWER:"power",KEY_VOLUMEUP:"volume_up",KEY_VOLUMEDOWN:"volume_down",KEY_APPSELECT:"recent"};class ie{options;slots=new Map;currentSlot=0;penPaths=new Map;releasedSlots=new Set;touchingSlots=new Set;lastEmitted=new Map;nodeTool;heldButtons=new Set;hover=new ne;kernelAtMs=0;constructor(n={}){this.options=n}emitHover(n){if(n)this.options.onHover?.(n)}feedLine(n,o){let s=n.match(/^\[\s*(\d+(?:\.\d+)?)\]\s+(\S+)\s+(\S+)\s+(\S+)\s*$/);if(!s)return null;this.kernelAtMs=Number(s[1])*1000;let a=s[2],d=s[3],c=s[4];if(a==="EV_ABS")return this.handleAbsEvent(d,c,o);if(a==="EV_SYN")return this.handleSynEvent(d,c,o);if(a==="EV_KEY"){let p=c==="DOWN"?Tt[d]:void 0;if(p)return{type:"pressButton",arrivedAt:o,button:p};this.handleKeyEvent(d,c==="DOWN"||c==="REPEAT",o)}return null}handleAbsEvent(n,o,s){let a=parseInt(o,16);switch(n){case"ABS_MT_SLOT":this.currentSlot=a;break;case"ABS_MT_TRACKING_ID":if(o==="ffffffff")this.releaseCurrentSlot(s);else{let d=this.getOrCreateSlot();if(d.trackingId>=0&&d.trackingId!==a){let c=this.endedByReplacement(d,s);return this.emitHover(this.hover.slotReleased(d.slotId,this.withPenState({...d}).toolType,s)),d.trackingId=a,c}d.trackingId=a}break;case"ABS_MT_POSITION_X":this.observeAxis("x",a);break;case"ABS_MT_POSITION_Y":this.observeAxis("y",a);break;case"ABS_MT_PRESSURE":this.getOrCreateSlot().pressure=a;break;default:this.handlePenAbsEvent(n,a);break}return null}releaseCurrentSlot(n){let o=this.slots.get(this.currentSlot);if(!o)return;if(o.trackingId>=0)this.releasedSlots.add(o.slotId),o.trackingId=-1;this.emitHover(this.hover.slotReleased(o.slotId,this.withPenState({...o}).toolType,n))}observePenSlot(n,o){if(this.options.singleTouch||n.toolType===void 0||n.trackingId<0)return;if(this.isMtPenHovering(n))this.hover.slotHovering(n.slotId,n,o,this.kernelAtMs);else this.hover.slotTouching(n.slotId)}endedByReplacement(n,o){let s=[];for(let[,a]of this.slots)if(a.slotId!==n.slotId&&a.trackingId>=0&&!this.isMtPenHovering(a)){let d=this.withPenState({...a});if(d.toolType)d.path=this.samplePen(d,o);s.push(d)}return this.releasedSlots.delete(n.slotId),this.touchingSlots.delete(n.slotId),this.lastEmitted.delete(n.slotId),this.penPaths.delete(n.slotId),{arrivedAt:o,activeSlots:s,releasedSlots:[n.slotId]}}handlePenAbsEvent(n,o){switch(n){case"ABS_MT_TOOL_TYPE":if(o===1)this.getOrCreateSlot().toolType="stylus";else delete this.getOrCreateSlot().toolType;break;case"ABS_X":case"ABS_Y":case"ABS_PRESSURE":if(this.options.singleTouch)this.handleSingleTouchAxis(n,o);break;case"ABS_TILT_X":this.getOrCreateSlot().tiltX=o|0;break;case"ABS_TILT_Y":this.getOrCreateSlot().tiltY=o|0;break;case"ABS_DISTANCE":case"ABS_MT_DISTANCE":this.getOrCreateSlot().distance=o;break;default:break}}handleSingleTouchAxis(n,o){if(this.currentSlot=0,n==="ABS_X")this.observeAxis("x",o);else if(n==="ABS_Y")this.observeAxis("y",o);else this.getOrCreateSlot().pressure=o}handleKeyEvent(n,o,s){switch(n){case"BTN_DIGI":case"BTN_TOOL_PEN":this.setNodeTool("stylus",o,s);break;case"BTN_TOOL_RUBBER":this.setNodeTool("eraser",o,s);break;case"BTN_STYLUS":this.setButton("stylusPrimary",o);break;case"BTN_STYLUS2":this.setButton("stylusSecondary",o);break;case"BTN_TOUCH":if(this.options.singleTouch){if(this.handleSingleTouchContact(o),o)this.hover.penTouched()}break;default:break}}setNodeTool(n,o,s){if(o){if(this.nodeTool=n,this.options.singleTouch)this.hover.penEntered();return}if(this.nodeTool!==n&&this.nodeTool!==void 0)return;if(this.nodeTool=void 0,this.options.singleTouch)this.handleSingleTouchContact(!1),this.emitHover(this.hover.penLeft(n,s))}setButton(n,o){if(o)this.heldButtons.add(n);else this.heldButtons.delete(n)}handleSingleTouchContact(n){if(this.currentSlot=0,n){this.getOrCreateSlot().trackingId=0;return}let o=this.slots.get(0);if(o&&o.trackingId>=0)this.releasedSlots.add(0),o.trackingId=-1}handleSynEvent(n,o,s){if(n!=="SYN_REPORT")return null;if(parseInt(o,16)!==0)return null;let d=[],c=[],p=[],h=new Set;for(let[,m]of this.slots)if(this.observePenSample(m,s),m.trackingId>=0&&!this.isMtPenHovering(m)){h.add(m.slotId);let f=this.withPenState({...m});if(f.toolType)f.path=this.samplePen(f,s);d.push(f),this.lastEmitted.set(m.slotId,{x:m.x,y:m.y})}else if(this.releasedSlots.has(m.slotId)||m.trackingId>=0&&this.touchingSlots.has(m.slotId))c.push(m.slotId),p.push(...this.takeFinalMove(m,s));for(let m of c)this.penPaths.delete(m);return this.releasedSlots.clear(),this.touchingSlots=h,p.length>0?{arrivedAt:s,activeSlots:d,releasedSlots:c,releasedFinalSamples:p}:{arrivedAt:s,activeSlots:d,releasedSlots:c}}observePenSample(n,o){if(this.observePenSlot(n,o),this.options.singleTouch&&this.nodeTool&&n.trackingId<0)this.hover.penHovering(n,o,this.kernelAtMs)}takeFinalMove(n,o){let s=this.lastEmitted.get(n.slotId);if(this.lastEmitted.delete(n.slotId),!s||s.x===n.x&&s.y===n.y)return[];let a=this.withPenState({...n}),d=this.penPaths.get(n.slotId)?.at(-1)?.pressure;if(a.toolType&&d!==void 0)a.path=this.samplePen({...a,pressure:d},o);return[a]}withPenState(n){if(!(this.options.singleTouch||n.toolType!==void 0))return delete n.tiltX,delete n.tiltY,n;if(this.options.singleTouch)n.toolType=this.nodeTool??"stylus";else if(this.nodeTool==="eraser")n.toolType=this.nodeTool;if(this.heldButtons.size>0)n.buttons=[...this.heldButtons];return n}isMtPenHovering(n){return!this.options.singleTouch&&n.toolType!==void 0&&(n.distance??0)>0}samplePen(n,o){let s=this.penPaths.get(n.slotId)??[],a={x:n.x,y:n.y,pressure:n.pressure,arrivedAt:o,kernelAtMs:this.kernelAtMs};if(s.length>=A.PEN_MAX_SAMPLES){let d=s.reduce((p,h,m)=>h.pressure<s[p].pressure?m:p,0),c=s.reduce((p,h,m)=>h.pressure>s[p].pressure?m:p,0);s=s.filter((p,h)=>h===0||h===d||h===c||h%2===1)}return s.push(a),this.penPaths.set(n.slotId,s),[...s]}getOrCreateSlot(){if(!this.slots.has(this.currentSlot))this.slots.set(this.currentSlot,{slotId:this.currentSlot,trackingId:-1,x:NaN,y:NaN,pressure:0,unknownAxes:["x","y"]});return this.slots.get(this.currentSlot)}observeAxis(n,o){let s=this.getOrCreateSlot();if(s[n]=o,s.unknownAxes=s.unknownAxes?.filter((a)=>a!==n),!s.unknownAxes?.length)delete s.unknownAxes}}class ae{scaler;densityDp;pressureRange;tiltAxes;contacts=new Map;lastTap=null;pinchState=null;inTwoFingerMode=!1;constructor(n,o,s,a){this.scaler=n;this.densityDp=o;this.pressureRange=s;this.tiltAxes=a}scalerAt(n){return"scalerAt"in this.scaler?this.scaler.scalerAt(n):this.scaler}downStamp(n){return"scalerAt"in this.scaler?{downAt:n.arrivedAt}:{}}feedFrame(n){this.updateContacts(n);let o=n.activeSlots.length;if(this.updatePinchState(n,o),n.releasedSlots.length===0)return null;if(this.inTwoFingerMode&&this.pinchState){for(let s of n.releasedSlots)this.contacts.delete(s);if(o===0){let s=this.maybeEmitPinch(n.arrivedAt);return this.inTwoFingerMode=!1,this.pinchState=null,s}return null}if(!this.inTwoFingerMode&&n.releasedSlots.length===1&&o===0)return this.completeSingleFingerGesture(n);for(let s of n.releasedSlots)this.contacts.delete(s);return null}updateContacts(n){for(let o of n.releasedFinalSamples??[]){let s=this.contacts.get(o.slotId);if(s)s.lastX=o.x,s.lastY=o.y,s.path=o.path??s.path}for(let o of n.activeSlots){let s=this.contacts.get(o.slotId);if(s){if(!Number.isFinite(s.startX))s.startX=o.x;if(!Number.isFinite(s.startY))s.startY=o.y;s.lastX=o.x,s.lastY=o.y,s.path=o.path,s.unknownAxes=oe(s.unknownAxes,o.unknownAxes),Oe(s.pen,o,this.tiltAxes)}else{let a=bt();Oe(a,o,this.tiltAxes),this.contacts.set(o.slotId,{startX:o.x,startY:o.y,arrivedAt:n.arrivedAt,lastX:o.x,lastY:o.y,scaler:this.scalerAt(n.arrivedAt),unknownAxes:o.unknownAxes,pen:a,path:o.path})}}}updatePinchState(n,o){if(o===2){this.inTwoFingerMode=!0;let[s,a]=n.activeSlots,d=oe(this.contacts.get(s.slotId)?.unknownAxes,this.contacts.get(a.slotId)?.unknownAxes),c=this.contacts.get(s.slotId)?.scaler??this.scalerAt(n.arrivedAt),p=d?.length?void 0:ke(c,s.x,s.y,{rawX2:a.x,rawY2:a.y});if(!this.pinchState)this.pinchState={initialDist:p,finalDist:p,unknownAxes:d};else this.pinchState.finalDist=p,this.pinchState.unknownAxes=oe(this.pinchState.unknownAxes,d)}}completeSingleFingerGesture(n){let o=n.releasedSlots[0],s=this.contacts.get(o);if(this.contacts.delete(o),!s)return null;if(s.unknownAxes?.length)return{...this.evaluateUnknownContact(s,n.arrivedAt),...this.penFields(s)};let{x:a,y:d}=s.scaler.toScreenPoint(s.startX,s.startY),{x:c,y:p}=s.scaler.toScreenPoint(s.lastX,s.lastY),h=n.arrivedAt-s.arrivedAt,m=z(a,d,c,p),f=A.TOUCH_SLOP_DP*this.densityDp,y=m<f?this.evaluateTapOrLongPress(a,d,h,{arrivedAt:n.arrivedAt,toolType:s.pen.toolType}):this.evaluateSwipe({x:a,y:d},{x:c,y:p},h,n.arrivedAt);return this.completeContactGesture(s,y,n.arrivedAt,h)}completeContactGesture(n,o,s,a){let d=this.penFields(n);if(o.type==="swipe"&&n.pen.toolType==="stylus"&&d.pressure?.normalized&&this.pressureRange&&(n.pen.pressureMax-n.pen.pressureMin)/(this.pressureRange.max-this.pressureRange.min)>=A.STROKE_PRESSURE_RANGE&&n.path&&n.path.length>=2){this.lastTap=null;let c=this.pressureRange,p=n.path.map((h)=>({...n.scaler.toScreenPoint(h.x,h.y),arrivedAt:h.arrivedAt,...h.kernelAtMs===void 0?{}:{kernelAtMs:h.kernelAtMs},pressure:Math.round(se((h.pressure-c.min)/(c.max-c.min))*1e4)/1e4}));return{type:"stroke",arrivedAt:s,durationMs:a,path:p,...this.downStamp(n),...d}}return{...o,...this.downStamp(n),...d}}penFields(n){let{toolType:o,buttons:s,pressureCount:a,pressureSum:d,pressureMin:c,pressureMax:p}=n.pen,h={};if(o)h.toolType=o;if(a>0){let m=this.pressureRange,f=(y)=>Math.round((m?se((y-m.min)/(m.max-m.min)):y)*1e4)/1e4;h.pressure={min:f(c),max:f(p),mean:f(d/a),normalized:m!==void 0}}if(n.pen.tiltCount>0)h.tilt=Math.min(Math.PI/2,Math.round(n.pen.tiltSum/n.pen.tiltCount*1e4)/1e4);if(s.size>0)h.buttons=[...s];return h}evaluateUnknownContact(n,o){this.lastTap=null;let s=o-n.arrivedAt,a=Number.isFinite(n.startX)?n.startX:0,d=Number.isFinite(n.startY)?n.startY:0,c=Number.isFinite(n.lastX)?n.lastX:a,p=Number.isFinite(n.lastY)?n.lastY:d;return{type:ke(n.scaler,a,d,{rawX2:c,rawY2:p})>=A.TOUCH_SLOP_DP*this.densityDp?"swipe":s>=A.LONG_PRESS_MS?"longPress":"tap",arrivedAt:o,durationMs:s,unknownAxes:n.unknownAxes}}maybeEmitPinch(n){let o=this.pinchState;if(o?.unknownAxes?.length)return this.lastTap=null,null;if(!o||o.initialDist===void 0||o.finalDist===void 0||o.initialDist===0)return null;let s=o.finalDist/o.initialDist;if(Math.abs(s-1)<A.PINCH_MIN_SCALE_DELTA)return null;return{type:"pinch",arrivedAt:n,scale:s,pinchDirection:s<1?"in":"out"}}evaluateTapOrLongPress(n,o,s,{arrivedAt:a,toolType:d}){if(s>=A.LONG_PRESS_MS)return{type:"longPress",arrivedAt:a,screenX:n,screenY:o,durationMs:s};if(this.lastTap&&this.lastTap.toolType===d){let c=a-this.lastTap.arrivedAt,p=z(n,o,this.lastTap.screenX,this.lastTap.screenY),h=A.DOUBLE_TAP_SLOP_DP*this.densityDp;if(c<=A.DOUBLE_TAP_MS&&p<=h){let m=this.lastTap.arrivedAt;return this.lastTap=null,{type:"doubleTap",arrivedAt:a,screenX:n,screenY:o,firstTapArrivedAt:m}}}return this.lastTap={screenX:n,screenY:o,arrivedAt:a,toolType:d},{type:"tap",arrivedAt:a,screenX:n,screenY:o}}evaluateSwipe(n,o,s,a){let{x:d,y:c}=n,{x:p,y:h}=o,m=p-d,f=h-c,y=z(d,c,p,h),S=Math.abs(m)>=Math.abs(f)?m>0?"right":"left":f>0?"down":"up",g=s>0?y/s*1000:0,P=A.FLING_MIN_DP_PER_S*this.densityDp,_=g>=P?"fast":"normal";return{type:"swipe",arrivedAt:a,direction:S,startX:d,startY:c,endX:p,endY:h,speed:_}}}function ke(n,o,s,{rawX2:a,rawY2:d}){let c=n.toScreenPoint(o,s),p=n.toScreenPoint(a,d);return z(c.x,c.y,p.x,p.y)}function z(n,o,s,a){return Math.sqrt((s-n)**2+(a-o)**2)}function oe(n,o){if(!n?.length&&!o?.length)return;return[...new Set([...n??[],...o??[]])]}function bt(){return{buttons:new Set,pressureCount:0,pressureSum:0,pressureMin:1/0,pressureMax:-1/0,tiltCount:0,tiltSum:0}}function Oe(n,o,s){if(o.toolType)n.toolType=o.toolType;for(let a of o.buttons??[])n.buttons.add(a);if(o.toolType==="stylus"||o.toolType==="eraser")At(n,o,s);if(o.pressure>0)n.pressureCount+=1,n.pressureSum+=o.pressure,n.pressureMin=Math.min(n.pressureMin,o.pressure),n.pressureMax=Math.max(n.pressureMax,o.pressure)}function At(n,o,s){if(s&&Be(s.x)&&Be(s.y)&&o.tiltX!==void 0&&o.tiltY!==void 0&&Number.isFinite(o.tiltX)&&Number.isFinite(o.tiltY)){let a=Ce(o.tiltX,s.x),d=Ce(o.tiltY,s.y),c=Math.cos(a)*Math.cos(d);n.tiltCount+=1,n.tiltSum+=Math.acos(se(c))}}function Ce(n,o){let s=o.resolution?1/o.resolution:Math.PI/180;return(n-(o.min+o.max)/2)*s}function Be(n){return Number.isFinite(n.min)&&Number.isFinite(n.max)&&n.max>n.min&&(n.resolution===void 0||Number.isFinite(n.resolution)&&n.resolution>=0)}function se(n){return Math.min(Math.max(n,0),1)}class le{opts;pending=[];maxSeenKernelMs=-1/0;releasePoint=-1/0;flushTimer;flushAt;windowMs;constructor(n){this.opts=n;if(this.windowMs=n.windowMs??50,!Number.isFinite(this.windowMs)||this.windowMs<0)throw RangeError("Kernel reorder window must be finite and non-negative")}push(n,o,s){let a=/^\[\s*(\d+(?:\.\d+)?)\s*\]/.exec(o),d=a?Number(a[1])*1000:NaN;if(!Number.isFinite(d)){this.opts.onLine({nodeKey:n,line:o,arrivedAt:s});return}this.maxSeenKernelMs=Math.max(this.maxSeenKernelMs,d),this.pending.push({nodeKey:n,kernelMs:d,line:o,arrivedAt:s,releaseAt:this.now()+this.windowMs}),this.pending.sort((c,p)=>c.kernelMs-p.kernelMs),this.releaseThrough(Math.max(this.releasePoint,this.maxSeenKernelMs-this.windowMs)),this.scheduleFlush()}drain(){this.cancelFlush(),this.releaseThrough(this.maxSeenKernelMs)}dropNode(n){this.pending=this.pending.filter((o)=>o.nodeKey!==n),this.scheduleFlush()}clear(){this.cancelFlush(),this.pending=[],this.maxSeenKernelMs=-1/0,this.releasePoint=-1/0}releaseThrough(n){this.releasePoint=n;while(this.pending.length>0&&this.pending[0].kernelMs<=n){let o=this.pending.shift(),{nodeKey:s,kernelMs:a,line:d,arrivedAt:c}=o;this.opts.onLine({nodeKey:s,kernelMs:a,line:d,arrivedAt:c})}}scheduleFlush(){if(this.pending.length===0){this.cancelFlush();return}let n=1/0;for(let o of this.pending)n=Math.min(n,o.releaseAt);if(this.flushAt===n)return;this.cancelFlush(),this.flushAt=n,this.flushTimer=this.opts.timer.setTimeout(()=>{this.flushTimer=void 0,this.flushAt=void 0;let o=this.now(),s=this.releasePoint;for(let a of this.pending)if(a.releaseAt<=o)s=Math.max(s,a.kernelMs);this.releaseThrough(s),this.scheduleFlush()},Math.max(0,n-this.now()))}cancelFlush(){if(this.flushTimer!==void 0)this.opts.timer.clearTimeout(this.flushTimer),this.flushTimer=void 0;this.flushAt=void 0}now(){return this.opts.timer.monotonicNow?.()??this.opts.timer.now()}}class L{handlers=new Map;buffer;constructor(n){this.buffer=new le({...n,onLine:({nodeKey:o,line:s,arrivedAt:a})=>this.handlers.get(o)?.(s,a)})}register(n,o){this.buffer.dropNode(n);let s=(a,d)=>o(a,d);return this.handlers.set(n,s),()=>{if(this.handlers.get(n)!==s)return;if(this.handlers.delete(n),this.buffer.dropNode(n),this.handlers.size===0)this.buffer.clear()}}push(n,o,s){if(this.handlers.has(n))this.buffer.push(n,o,s)}}class F{opts;children=new Set;starting=!1;generation=0;cleanups=new Set;timer;constructor(n){this.opts=n;this.timer=n.timer??i}start(n,o){if(this.children.size>0||this.starting)return;this.starting=!0;let s=++this.generation,a=this.opts.lineMerge??new L({timer:this.timer,windowMs:this.opts.kernelReorderWindowMs});this.startProcess(s,this.opts.touchNode,this.opts.scaler,{onGesture:n,onError:o,lineMerge:a});for(let{node:d,scaler:c}of this.opts.penNodes??[])this.startProcess(s,d,c,{onGesture:n,lineMerge:a,onError:(p)=>e.warn(`[GetEventReader] pen node ${d.path} stopped; finger recording continues: ${p.message}`,p)})}async startProcess(n,o,s,{onGesture:a,onError:d,lineMerge:c}){let p=new ie({singleTouch:o.kind==="pen",onHover:(T)=>{let R=T.hover,M=o.distanceRange,D=R?.[0],me=D&&"scalerAt"in s?s.scalerAt(D.arrivedAt):s;a({...T,...D?{downAt:D.arrivedAt}:{},hover:M&&R&&"toScreenPoint"in me?R.map((k)=>({...me.toScreenPoint(k.x,k.y),arrivedAt:k.arrivedAt,...k.kernelAtMs===void 0?{}:{kernelAtMs:k.kernelAtMs},distance:Math.min(1,Math.max(0,(k.distance-M.min)/(M.max-M.min)))})):void 0})}}),h=new ae(s,this.opts.density,xt(o),o.tiltAxes),m=["shell","getevent","-lt",o.path];e.debug(`[GetEventReader] Spawning: ${m.join(" ")}`);let f;try{f=await this.opts.adb.spawn(m)}catch(T){let R=T instanceof Error?T:Error(String(T));if(e.error(`[GetEventReader] spawn error: ${R.message}`),n===this.generation){if(o===this.opts.touchNode)this.starting=!1;d?.(R)}return}if(n!==this.generation){f.on("error",()=>{}),f.kill();return}if(this.children.add(f),o===this.opts.touchNode)this.starting=!1;let y="",S="",g=c.register(o.path,(T,R)=>{if(n!==this.generation)return;let M=p.feedLine(T,R);if(!M)return;if(wt(M)){let D=h.feedFrame(M);if(D)a(D)}else a(M)}),P=(T)=>{y+=T.toString();let R=y.split(`
4
+ `);y=R.pop()??"";for(let M of R){if(!M.trim()||n!==this.generation)continue;let D=this.timer.now();c.push(o.path,M,D)}},_=(T)=>{S=(S+T.toString()).slice(-4096),e.debug(`[GetEventReader] stderr: ${T.toString().trim()}`)},I=()=>{y="",f.stdout.off("data",P),f.stderr.off("data",_),f.on("error",J),f.off("error",O),f.off("exit",U),this.children.delete(f),this.cleanups.delete(I),g()},J=()=>{},O=(T)=>{I();let R=S.trim()?Error(`[GetEventReader] getevent process error: ${T.message}; stderr tail: ${S.trim()}`,{cause:T}):T;e.warn(`[GetEventReader] process error: ${R.message}`),d?.(R)},U=(T,R)=>{I();let M=Error(`[GetEventReader] getevent exited with ${R?`signal ${R}`:`code ${T}`}`+(S.trim()?`; stderr tail: ${S.trim()}`:""));e.warn(M.message),d?.(M)};this.cleanups.add(I),f.stdout.on("data",P),f.stderr.on("data",_),f.on("error",O),f.on("exit",U)}stop(){this.starting=!1,++this.generation;let n=[...this.children];for(let o of[...this.cleanups])o();for(let o of n)if(!o.killed)e.debug("[GetEventReader] Stopping getevent process"),o.kill();this.children.clear()}}function xt(n){return n.pressureMin!==void 0&&n.pressureMax!==void 0?{min:n.pressureMin,max:n.pressureMax}:void 0}function wt(n){return n!==null&&"activeSlots"in n}class ue{opts;running=!1;generation=0;pens=new Map;stopMonitor;constructor(n){this.opts=n}start(n,o){if(this.running)return;this.running=!0;let s=++this.generation,{primary:a}=this.opts;if(a.node.kind==="pen")this.pens.set(a.node.path,{controller:new AbortController,reader:a.reader});a.reader.start(n,o);for(let d of this.opts.penNodes){let c={controller:new AbortController};this.pens.set(d.path,c),this.startPen(d,c,n)}this.monitor(s,n)}startPen(n,o,s){o.reader=this.opts.createPenReader(n),o.reader.start((a)=>{if(this.pens.get(n.path)===o)s(a)},(a)=>{if(this.pens.get(n.path)!==o)return;this.removePen(n.path),e.warn(`[PenHotplugReader] pen node ${n.path} stopped; finger recording continues: ${a.message}`,a)})}async addPen(n,o){if(this.pens.has(n)||n===this.opts.primary.node.path&&this.opts.primary.node.kind!=="pen")return;let s={controller:new AbortController};this.pens.set(n,s);try{let{stdout:a}=await this.opts.adb.execute(["shell","getevent","-lp",n],{signal:s.controller.signal,timeoutMs:1000,noRetry:!0});if(this.pens.get(n)!==s)return;let d=Q(a).pen.find((c)=>c.path===n);if(d)this.startPen(d,s,o);else this.removePen(n)}catch(a){if(this.pens.get(n)!==s){e.debug(`[PenHotplugReader] discarded probe for removed node ${n}`,a);return}this.removePen(n),e.warn(`[PenHotplugReader] cannot read pen node ${n}; finger recording continues: ${r(a)}`,a)}}removePen(n){let o=this.pens.get(n);this.pens.delete(n),o?.controller.abort(),o?.reader?.stop()}async monitor(n,o){let s;try{s=await this.opts.adb.spawn(["shell","getevent","-lt"])}catch(g){if(n===this.generation)e.warn(`[PenHotplugReader] hotplug monitor failed; finger recording continues: ${r(g)}`,g);return}if(n!==this.generation){s.on("error",()=>{}),s.kill();return}let a="",d="",c=(g)=>{a+=g.toString();let P=a.split(`
5
+ `);a=P.pop()??"";for(let _ of P){let I=Z(_);if(I?.action==="add")this.addPen(I.path,o);else if(I?.action==="remove")this.removePen(I.path)}},p=(g)=>{d=(d+g.toString()).slice(-4096)},h=()=>{if(s.stdout.off("data",c),s.stderr.off("data",p),s.on("error",m),s.off("error",y),s.off("exit",S),a="",this.stopMonitor=void 0,!s.killed)s.kill()},m=()=>{},f=(g)=>{h(),e.warn(`[PenHotplugReader] hotplug monitor stopped; finger recording continues: ${g}`+(d.trim()?`; stderr tail: ${d.trim()}`:""))},y=(g)=>f(g.message),S=(g,P)=>f(P?`signal ${P}`:`code ${g}`);this.stopMonitor=h,s.stdout.on("data",c),s.stderr.on("data",p),s.on("error",y),s.on("exit",S)}stop(){this.running=!1,++this.generation,this.stopMonitor?.();for(let n of this.pens.keys())this.removePen(n);this.opts.primary.reader.stop()}}function Le({adb:n,penNode:o,timeline:s,rotation:a,display:d,caveats:c,density:p,timer:h,lineMerge:m}){let[{scaler:f,stopFollowing:y}]=Ie(s,[o],{rotation:a,display:d},{startedAt:h.now(),caveats:c}),S=new F({adb:n,touchNode:o,scaler:f,density:p,timer:h,lineMerge:m});return{start:(g,P)=>S.start(g,P),stop:()=>{S.stop(),y()}}}function Pt(n){return n?{action:"type",text:n,operation:"replace"}:{action:"clear"}}var Y=750,Et=3000,Fe="rotation/size could not be confirmed at stop; tapAt and swipeOn steps recorded after a display change may be at the wrong coordinates or direction";class j{device;gestureEmitter;a11ySource;steps=[];orderedSteps=[];latestEntry=null;pendingGestures=[];exportWarnings=new Set;bufferedInteractions=[];lastInputText=null;activeEmitter=null;unsubscribeA11y=null;activeA11y=null;stopped=!1;firstTouchTrackFailure;geometry;displaySource;unsubscribeDisplay=null;geometrySpans=new Map;finalized;get touchTrackFailure(){return this.firstTouchTrackFailure}get stepCount(){return this.steps.length}get capturedSteps(){return this.steps}get capturedExportWarnings(){return[...this.exportWarnings]}timer;constructor(n,o,s,{timer:a=i,...d}={}){this.device=n;this.gestureEmitter=o;this.a11ySource=s;this.timer=a,this.geometry=d.geometry,this.displaySource=d.displaySource}async start(){let n;if(!this.a11ySource)n=E.getInstance(this.device);let o=this.a11ySource??n;if(!await o.ensureConnected())throw Error("[DualTrackRecorder] Unable to connect to the accessibility service.");if(n)n.notifyRecordingStarted(),this.activeA11y=n;let a=this.gestureEmitter??await this.createGetEventReader();this.activeEmitter=a,a.start((d)=>this.handleGestureEvent(d),(d)=>{if(this.stopped||this.firstTouchTrackFailure)return;this.firstTouchTrackFailure={error:d,failedAt:this.timer.now()},e.warn(`[DualTrackRecorder] Touch track (getevent) failed: ${d.message}`)}),this.unsubscribeA11y=o.onInteraction((d)=>this.handleInteractionEvent(d)),this.subscribeDisplayChanges(n),e.debug("[DualTrackRecorder] Started dual-track recording")}async stop(n={}){if(n.hostOnly)this.geometry?.dispose();if(this.stopped){let s=await this.finalized??[];return this.stopResult(s)}if(this.stopped=!0,!n.hostOnly)this.activeA11y?.notifyRecordingStopped();this.activeA11y=null,this.unsubscribeA11y?.(),this.unsubscribeA11y=null,this.activeEmitter?.stop(),this.activeEmitter=null,this.flushPendingGestures(),this.finalized=(n.hostOnly?Promise.resolve(this.geometry?[Fe]:[]):this.finalizeGeometry()).finally(()=>{this.unsubscribeDisplay?.(),this.unsubscribeDisplay=null});let o=await this.finalized;return e.debug(`[DualTrackRecorder] Stopped with ${this.steps.length} steps`),this.stopResult(o)}flushPendingGestures(){for(let n of this.pendingGestures)if(!n.resolved)this.resolveGesture(n);this.pendingGestures=[]}stopResult(n){return{steps:this.steps,stepCount:this.steps.length,...this.touchTrackFailure?{touchTrackFailure:this.touchTrackFailure}:{},...n.length>0?{geometryWarnings:n}:{},...this.exportWarnings.size>0?{exportWarnings:[...this.exportWarnings]}:{}}}subscribeDisplayChanges(n){let o=this.displaySource??(n?Mt(n):void 0),s=this.geometry;if(o&&s)this.unsubscribeDisplay=o.onDisplayChange((a)=>s.handleTransition(a))}async finalizeGeometry(){let n=this.geometry;if(!n)return[];let{mismatch:o,unconfirmed:s}=await this.confirmGeometryAtStop(n),a=new Set;for(let[d,{downAt:c,upAt:p}]of this.geometrySpans){let h=n.timeline.warningsFor(c,p);if(o&&p>=n.timeline.lastKnownGoodAt)h.push(o);if(h.length>0){d.label=`Warning: ${h.join("; ")}`;for(let m of h)a.add(m)}}if(o)a.add(o);if(s)a.add(Fe);return[...a]}async confirmGeometryAtStop(n){try{return{mismatch:await l(async()=>(await n.settle(),n.verifyAtStop()),{timer:this.timer,timeoutMs:Et,label:"Confirming display geometry at stop"}),unconfirmed:!1}}catch(o){return e.warn(`[DualTrackRecorder] Could not confirm display geometry at stop: ${r(o)}`,o),{unconfirmed:!0}}}handleGestureEvent(n){if(this.stopped)return;if(n.type==="hover"){let s=Xe(n);K(this.exportWarnings,n,s),this.trackGeometrySpan(n,s),this.enqueueStep({resolved:!0,step:s??void 0});return}if(n.type==="pressButton"){this.enqueueStep({resolved:!0,step:kt(n)});return}if(n.type==="pinch"){this.enqueueStep({resolved:!0,step:Ot(n)??void 0});return}if(this.pendingGestures=this.pendingGestures.filter((s)=>!s.resolved||s.step!==void 0&&s.stepIndex===void 0||b(s.gesture)&&this.timer.now()-s.arrivedAt<=Y*2||s.gesture.type==="tap"&&n.arrivedAt-s.gesture.arrivedAt<=A.DOUBLE_TAP_MS),this.upgradeDoubleTap(n))return;let o={gesture:n,arrivedAt:this.timer.now(),resolved:!1};this.pendingGestures.push(o),this.enqueueStep(o),o.timeout=this.timer.setTimeout(()=>this.resolveGesture(o),Y)}upgradeDoubleTap(n){if(n.type!=="doubleTap"||b(n))return!1;let o=[...this.pendingGestures].reverse().find((a)=>fe(a.gesture,n)),s=o?.step;if(s&&["tapOn","tapAt"].includes(s.tool)&&s.params.action==="tap")return s.params.action="doubleTap",K(this.exportWarnings,n,s),!0;if(o&&!o.resolved){if(o.timeout)this.timer.clearTimeout(o.timeout);return o.gesture=n,o.arrivedAt=this.timer.now(),o.timeout=this.timer.setTimeout(()=>this.resolveGesture(o),Y),!0}return!1}enqueueStep(n){this.latestEntry=n,this.orderedSteps.push(n),this.flushResolvedSteps()}flushResolvedSteps(){while(this.orderedSteps[0]?.resolved){let n=this.orderedSteps.shift();if(n.step)n.stepIndex=this.steps.length,this.steps.push(n.step)}}handleInteractionEvent(n){if(this.stopped)return;if(n.type==="windowChange")return;if(n.type==="inputText"){this.handleInputText(n);return}let o={...n,receivedAt:this.timer.now()},s=this.pendingGestures.find((a)=>!a.resolved&&!b(a.gesture)&&this.isPairCandidate(a,o));if(s)this.resolveGesture(s,n);else if(!this.pendingGestures.some((a)=>a.resolved&&!b(a.gesture)&&de(a.gesture.type,n.type)&&Ye(a.gesture,n.element)))this.bufferedInteractions.push(o)}resolveGesture(n,o){if(n.resolved)return;if(n.resolved=!0,n.timeout)this.timer.clearTimeout(n.timeout);let s=this.selectInteraction(n,o),a=Gt(n.gesture,s);if(K(this.exportWarnings,n.gesture,a),n.step=a??void 0,this.trackGeometrySpan(n.gesture,a),this.flushResolvedSteps(),!a&&b(n.gesture)){We(n.gesture);return}if(!s||!V(s.element)||!a){let d=n.gesture,[c,p]=d.type==="swipe"?[d.startX,d.startY]:[d.screenX,d.screenY],h=a?`recorded ${a.tool} fallback`:"no swipe direction or missing coordinates \u2014 step skipped";e.warn(`[DualTrackRecorder] No element match for ${d.type} at (${c}, ${p}) \u2014 ${h}`)}}trackGeometrySpan(n,o){if(o&&n.downAt!==void 0&&["tapAt","swipeOn","swipeAt","dragPath","hoverAt"].includes(o.tool))this.geometrySpans.set(o,{downAt:n.downAt,upAt:n.arrivedAt})}selectInteraction(n,o){let s=this.timer.now(),a=Y*2;this.bufferedInteractions=this.bufferedInteractions.filter((h)=>s-h.receivedAt<=a);let d=this.bufferedInteractions.map((h,m)=>({event:h,index:m}));if(o)d.push({event:{...o,receivedAt:s},index:-1});let c=d.filter(({event:h})=>this.isPairCandidate(n,h));if(b(n.gesture)&&!this.isUnambiguousUnknownPair(n,c.map(({event:h})=>h)))return;let p=c.sort((h,m)=>{let f=h.event.receivedAt-n.arrivedAt,y=m.event.receivedAt-n.arrivedAt;return Number(m.event.type==="tap")-Number(h.event.type==="tap")||Number(f<0)-Number(y<0)||Math.abs(f)-Math.abs(y)})[0];if(p&&p.index>=0)this.bufferedInteractions.splice(p.index,1);return p?.event}isPairCandidate(n,o){let s=n.gesture;if(Math.abs(o.receivedAt-n.arrivedAt)>Y)return!1;if(b(s)){let a=(s.type==="tap"||s.type==="longPress")&&o.type==="scroll"&&ce(o.scrollDeltaX,o.scrollDeltaY)!==null;return Boolean((a||de(s.type,o.type,!1))&&o.element?.bounds&&V(o.element))}return de(s.type,o.type)&&Ye(s,o.element)}isUnambiguousUnknownPair(n,o){if(o.length!==1)return!1;let s=o[0];return!this.pendingGestures.some((a)=>a!==n&&(b(a.gesture)||!a.resolved)&&this.isPairCandidate(a,s))}handleInputText(n){let o=_t(n);if(n.text===void 0)return;let s=Pt(n.text);if(this.coalesceInputText(o,s))return;let a={resolved:!0,step:this.buildRecordedTextStep(s)};if(this.enqueueStep(a),o)this.lastInputText={elementKey:o,entry:a}}buildRecordedTextStep(n){return{tool:"sendKeys",params:{commands:[n]}}}coalesceInputText(n,o){let s=this.lastInputText;if(!s||!n||s.elementKey!==n||s.entry!==this.latestEntry)return!1;return this.updateCoalescedTextStep(s.entry.step,o)}updateCoalescedTextStep(n,o){let s=n?.params.commands?.[0];if(n?.tool!=="sendKeys"||s?.action!=="type"&&s?.action!=="clear")return!1;return n.params.commands=[o],!0}async createGetEventReader(){let n=v.create(this.device),{touch:o,pen:s}=await Me(n),a=o??s[0];if(!a)throw Error("[DualTrackRecorder] No multitouch input device found on this device");let d=await Lte(n),c=De(n),p=await jC(n),{rotation:h,caveats:m}=await Rt(c),f=new W({xMin:a.axisXMin,xMax:a.axisXMax,yMin:a.axisYMin,yMax:a.axisYMax},{rotation:h,display:p},this.timer.now(),m);this.geometry=new re(f,c,this.timer);let y=new L({timer:this.timer}),S=new F({adb:n,touchNode:a,scaler:f,density:d,timer:this.timer,lineMerge:y}),g=new ue({adb:n,primary:{node:a,reader:S},penNodes:o?s:s.slice(1),createPenReader:(P)=>Le({adb:n,penNode:P,timeline:f,rotation:h,display:p,caveats:m,density:d,timer:this.timer,lineMerge:y})});return Ct(g,f,this.timer)}}async function Rt(n){try{let o=await n.readRotation();if(o!==null)return{rotation:o,caveats:[]};e.warn("[DualTrackRecorder] WindowManager reported no display rotation at start")}catch(o){e.warn(`[DualTrackRecorder] Failed to read display rotation at start: ${r(o)}`,o)}return{rotation:0,caveats:[te]}}function Mt(n){return{onDisplayChange(o){let s=n.onDisplayTransition,a=(d)=>{s?.(d),o(d)};return n.onDisplayTransition=a,()=>{if(n.onDisplayTransition===a)n.onDisplayTransition=s}}}}function de(n,o,s=!0){return(n==="tap"||n==="doubleTap")&&(o==="tap"||s&&o==="stateChange")||n==="longPress"&&o==="longPress"||n==="swipe"&&(o==="scroll"||o==="swipe")}function Ye(n,o){let s=o?.bounds;if(!s)return!1;if(b(n))return!1;let a=n.screenX??n.startX,d=n.screenY??n.startY;if(typeof a!=="number"||typeof d!=="number"||!Number.isFinite(a)||!Number.isFinite(d))return!1;return It(a,d,s)}function It(n,o,s){return n>=s.left-20&&n<=s.right+20&&o>=s.top-20&&o<=s.bottom+20}function V(n){if(!n)return null;let o=n["resource-id"];if(o)return{elementId:o};let s=n.text??n["content-desc"];if(s)return{text:s};return null}function _t(n){let o=n.element;if(!o)return null;let s=o["resource-id"]??"",a=o["content-desc"]??"",d=o.class??"";if(!s&&!a&&!d)return null;return`${s}|${a}|${d}`}function ce(n,o){let s=n??0,a=o??0;if(s===0&&a===0)return null;if(Math.abs(s)>=Math.abs(a))return s>0?"left":"right";return a>0?"up":"down"}function Gt(n,o={type:"",timestamp:0}){if(n.toolType!==void 0)return Xe(n);let s=V(o.element);switch(n.type){case"tap":case"doubleTap":case"longPress":{if(n.type!=="doubleTap"&&b(n)&&o.type==="scroll")return He(n,o);if(s)return{tool:"tapOn",params:{action:n.type,...s}};return Ke(n)}case"swipe":return He(n,o);default:return null}}var Dt=0.5;function $e(n){let{startX:o,startY:s,endX:a,endY:d}=n;if(b(n)||o===void 0||s===void 0||a===void 0||d===void 0||o===a&&s===d)return null;return{from:{x:o,y:s},to:{x:a,y:d}}}function Nt({from:n,to:o}){let s=Math.abs(o.x-n.x),a=Math.abs(o.y-n.y);return Math.min(s,a)>=Math.max(s,a)*Dt}function Ue(n,o){let s={from:o.from,to:o.to},a=n.geometry?.deviceWidth,d=n.geometry?.deviceHeight;if(a&&d&&a>0&&d>0)s.from={x:fm(o.from.x,a),y:fm(o.from.y,d)},s.to={x:fm(o.to.x,a),y:fm(o.to.y,d)},s.coordinateSpace="normalized";if(n.speed==="fast")s.speed="fast";let c=C(n);if(c)s.pointer=c;return{tool:"swipeAt",params:s}}function Xe(n){if(n.toolType!=="stylus"&&n.toolType!=="eraser")return null;if(n.type==="stroke"||n.type==="hover")return ge(n);if(n.type==="swipe"){let o=$e(n);return o?Ue(n,o):null}return Ke(n)}function He(n,o){let s=V(o.element),a=b(n)?s&&ce(o.scrollDeltaX,o.scrollDeltaY):n.direction??ce(o.scrollDeltaX,o.scrollDeltaY),d=$e(n);if(d&&(!a||Nt(d)))return Ue(n,d);if(!a)return null;let c={direction:a};if(s)c.container="elementId"in s?{elementId:s.elementId}:{text:s.text};if(!b(n)&&n.speed==="fast")c.speed="fast";return{tool:"swipeOn",params:c}}function Ke(n){if(b(n)||n.screenX===void 0||n.screenY===void 0)return null;let o={x:n.screenX,y:n.screenY,action:n.type};if(n.type==="longPress"&&n.durationMs!==void 0)o.durationMs=Math.min(gg,Math.max($a,n.durationMs));let s=C(n);if(s)o.pointer=s;return{tool:"tapAt",params:o,...n.geometry?{geometry:{...n.geometry,x:n.screenX,y:n.screenY}}:{}}}function We(n){e.warn(`[DualTrackRecorder] ${n.type} has unknown axes: ${n.unknownAxes?.join(", ")} \u2014 no resolved element gesture; step skipped`)}function kt(n){return{tool:"pressButton",params:{button:n.button}}}function Ot(n){if(b(n))return We(n),null;return{tool:"pinchOn",params:{direction:n.pinchDirection,scale:n.scale}}}function Ct(n,o,s){return{start:(a,d)=>n.start((c)=>a({...c,geometry:{platform:"android",...o.geometryAt(c.downAt??s.now())}}),d),stop:()=>n.stop()}}var Bt="user-input",Lt="no_user_input_captured",je="Device gesture recordings capture input made on the device itself (touches on its touch screen or emulator window, and text changes in input fields). Taps, swipes and other gestures sent through AutoMobile tools (tapAt, tapOn, swipeOn, etc.) or adb shell input are injected and are not recorded by design; use recordToolCalls to record tool calls.";class rA extends t{reason=Lt;constructor(n){super("No recorded interactions were captured. "+je+(n?` ${n}`:""))}}var ze=1e4,x=null,N=null,G=null,Ft=16,H=new Map;function Yt(n,o){if(!n.ownerSessionUuid)return;if(H.set(n.recordingId,{owner:n.ownerSessionUuid,result:o}),H.size>Ft){let s=H.keys().next();if(!s.done)H.delete(s.value)}}function pe(n){let o=w.sessionManager();if(!o)return n;return at(n,o)??n}function uI(n,o,s=pe){let a=H.get(n);if(!a||o===void 0)return;return he(a.owner,o,s)?a.result:void 0}function he(n,o,s){if(n===void 0||o===void 0)return!1;let a=s(o);return n===o||o6(n,a)||s(n)===a}async function iN(n,o,s=pe){let a=G;if(!a||a.session.recordingId!==n||!he(a.session.ownerSessionUuid,o,s))return;return await a.promise,uI(n,o,s)}function nA(n=i){if(!x)return null;let o=n.now()-x.startedAt,s=x.recorder.stepCount;return{recordingId:x.recordingId,deviceId:x.deviceId,platform:x.platform,startedAt:new Date(x.startedAt).toISOString(),eventCount:s,durationMs:o,captureScope:Bt,...s===0?{notice:je}:{}}}function q(){return x??N?.session??G?.session??null}function NX(n,o){let s=q();if(!s||s.deviceId!==n||s.ownerSessionUuid!==void 0)return!1;return s.ownerSessionUuid=o,!0}function Z1(n,o){let s=q();return s!==null&&s.ownerSessionUuid===n&&s.deviceId===o}function oN(n,o){let s=q();return s&&Z1(n,o)?s.recordingId:void 0}var Ht=(n,o,s,{stoppedAt:a,omittedInput:d})=>{if(n.length===0)throw new rA(d);let c=new Date(o.startedAt),p=a-o.startedAt,h={name:s,description:`Recorded plan with ${n.length} interaction(s).`,steps:n,mcpVersion:gn(Nn()),metadata:{createdAt:new Date(a).toISOString(),version:"1.0.0",recording:{recordingId:o.recordingId,startedAt:c.toISOString(),stoppedAt:new Date(a).toISOString(),durationMs:p,deviceId:o.deviceId,platform:o.platform,interactionCount:n.length}}};return dh.validate(h),{plan:h,stepCount:n.length}},$t=(n)=>{if(n&&n.trim().length>0)return n.trim();return`recorded-plan-${new Date().toISOString().replace(/[:.]/g,"-")}`};function Ve(n,o,{ownerSessionUuid:s,baseSessionUuid:a}){if(n.deviceId!==o.deviceId)throw Error(`Recording already active on device ${n.deviceId} (${n.recordingId}). Stop the existing recording before starting a new one on ${o.deviceId}.`);if(!(n.ownerSessionUuid===s||he(n.ownerSessionUuid,s,a??pe)))throw new t(`A recording owned by another session is active on device ${o.deviceId}. Wait for it to stop before starting a recording.`)}async function pI(n,o=i,s=B,{recorderFactory:a=(c)=>new j(c),...d}={}){if(G)return await G.promise.catch(()=>{return}),pI(n,o,s,{recorderFactory:a,...d});let{ownerSessionUuid:c}=d;if(x)return Ve(x,n,d),e.info(`[DeviceGestureRecording] Recording already active (${x.recordingId}), returning existing session`),{recordingId:x.recordingId,startedAt:new Date(x.startedAt).toISOString(),deviceId:x.deviceId,platform:x.platform};if(N)return Ve(N.session,n,d),N.promise;if(n.platform!=="android")throw Error(`Device gesture recording is only supported on Android right now (got ${n.platform}).`);let p=s.next(),h=o.now(),m={recordingId:p,deviceId:n.deviceId,platform:n.platform,startedAt:h,timer:o,recorder:a(n),ownerSessionUuid:c},f=Promise.resolve().then(async()=>{try{return await m.recorder.start(),x=m,e.info(`[DeviceGestureRecording] Started recording ${p} on ${n.deviceId}`),{recordingId:p,startedAt:new Date(h).toISOString(),deviceId:n.deviceId,platform:n.platform}}catch(y){try{await m.recorder.stop()}catch(S){throw u(AggregateError([y,S],"Recorder startup and teardown both failed"),"Failed to start device gesture recording")}throw u(y,"Failed to start device gesture recording")}finally{if(N?.session===m)N=null}});return N={session:m,promise:f},f}function Ut(){return q()?.timer??i}async function Dy(n,o,s=Ut(),a={}){if(N)await N.promise;let d=x??G?.session??null;if(!d)throw Error("No active recording. Start a recording before stopping.");if(n&&n!==d.recordingId)throw Error(`Recording ID ${n} does not match active recording ${d.recordingId}.`);if(G?.session===d)return G.promise;x=null;let c=Wt(d,o,s,a).then((p)=>(Yt(d,p),p)).finally(()=>{if(G?.session===d)G=null});return G={session:d,promise:c},c}async function Xt(n,o,s){try{return await l(()=>n.recorder.stop(s),{timer:o,timeoutMs:ze,label:"Stopping device gesture recording",timeoutError:()=>Error(`Device gesture recording stop timed out after ${ze} ms`)})}catch(a){e.warn(`[DeviceGestureRecording] Failed to stop recording ${n.recordingId}`,a);let d=n.recorder.capturedSteps??[];if(d.length===0)throw u(a,"Failed to stop device gesture recording");return{steps:[...d],exportWarnings:[...n.recorder.capturedExportWarnings??[]],salvagedAfter:r(a)}}}function Kt(n){if(!n?.length)return;let o=`Some recorded input was left out of the plan: ${n.join("; ")}.`;return e.warn(`[DeviceGestureRecording] ${o}`),o}async function Wt(n,o,s,a){let{steps:d,touchTrackFailure:c,geometryWarnings:p,exportWarnings:h,salvagedAfter:m}=await Xt(n,s,a),f=c?`Touch track (getevent) stopped ${c.failedAt-n.startedAt} ms after recording start: ${c.error.message}. Later taps may be missing.`:void 0;if(f&&d.length===0)throw u(Error(f,{cause:c?.error}),"Failed to stop device gesture recording");if(f)e.warn(`[DeviceGestureRecording] ${f}`);let y=p?.length?`Display geometry changed or was unreadable during recording: ${p.join("; ")}. Steps labelled "Warning:" may be recorded at the wrong coordinates or direction.`:void 0;if(y)e.warn(`[DeviceGestureRecording] ${y}`);let S=Kt(h),g=m?`Stopping the recorder did not finish (${m}); the steps captured so far are returned without confirming display rotation/size, so tapAt and swipeOn steps recorded after a display change may be at the wrong coordinates or direction.`:void 0;if(g)e.warn(`[DeviceGestureRecording] ${g}`);let P=[f,y,S,g].filter(Boolean).join(" "),_=s.now(),I=$t(o),{plan:J,stepCount:O}=Ht(d,n,I,{stoppedAt:_,omittedInput:S}),U=ow(J,{indent:2,lineWidth:-1,noRefs:!0}),T=_-n.startedAt;return e.info(`[DeviceGestureRecording] Stopped recording ${n.recordingId} with ${O} steps`),{recordingId:n.recordingId,startedAt:new Date(n.startedAt).toISOString(),stoppedAt:new Date(_).toISOString(),durationMs:T,planName:I,planContent:U,stepCount:O,...P?{error:`Warning: ${P}`}:{},deviceId:n.deviceId,platform:n.platform}}
6
+ export{X1,dI,Qf,tA,lI,i6,eh,DX,OX,MX,nN,rA,uI,iN,nA,NX,Z1,oN,pI,Dy};
7
+
8
+ //# debugId=A8B07065E54EEC1164756E2164756E21
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{i,tS,oM,Ld,qf,eo,l,e}from"./chunk-r0vp315h.js";import{h,I,pt,$e,FU}from"./chunk-5wk1t46v.js";import"./chunk-r6pvhj33.js";import"./chunk-aewdveet.js";import{BA,d_,sQ,yh,jS,Ot,A0,dQ,lQ,uQ,KS,T0,Kc,f_,h_,D0,Gc,F0,RQ,Pm,AQ,TQ,L0,y_,Yc,B0,$0,dp,U0,eV,IQ,OQ,$Q,v_,UQ}from"./chunk-8nj68t1v.js";import{w,fne,ID,sb,ab,gR,cb,Cne,Dne,qB,vk,wY,ki,Ks,Vk,GR,g$}from"./chunk-sfqe223f.js";import"./chunk-4vxeq0vd.js";import{ql}from"./chunk-w5yypt53.js";import{eY}from"./chunk-69pmjdf2.js";import"./chunk-9xgnrv5w.js";import{r}from"./chunk-2b39zyxc.js";function Q(t,o){return{refresh:()=>t.refresh({fresh:!0,requireCurrent:!0,refuseUpgradePending:!0}),isAutoMobileOwned:(n)=>t.stableIdsFor("ios").has(n)||(o()?.getAssignedDevices().has(n)??!1)}}sQ(Q(BA(i),()=>w.sessionManager()));Cne({androidColdBootAdmitter:()=>yh().android,iosBootInstrumentation:()=>{let t=yh();return d_({timer:i,history:t.iosBootHistory,gate:t.ios})},assertBootCapacityAvailable:(t,o)=>jS(t,o)});var Ue=500;function U(t){return t.success&&!t.error?void 0:{code:t.errorCode??"restore_failed",reason:t.error??"Device refused saved prototype restore"}}async function Ve(t,o){let n=t.assets.filter((a)=>a.bytes===void 0||a.mimeType===void 0);if(n.length>0)return{code:"asset_unavailable",reason:`Missing mirrored assets: ${n.map((a)=>a.id).join(", ")}`};for(let a of t.assets){if(a.bytes===void 0||a.mimeType===void 0)continue;let s=U(await o.putAsset({id:a.id,mimeType:a.mimeType,bytes:a.bytes}));if(s)return s}return U(await o.save({spec:t.spec,label:t.label,icon:t.icon}))}async function We(t,o){try{return await Ve(t,o)}catch(n){return e.warn(`[PROTOTYPE] Restore failed for ${t.id}`,n),{code:"restore_failed",reason:r(n)}}}async function X(t,o,n){let a={restored:[],skipped:[],failed:[]};try{let s=await o.list(t);if(s.length===0)return a;let d=[];try{let u=await n.list();if(!U(u))d=(u.savedPrototypes??[]).filter((f)=>!f.hostOnly);else e.warn(`[PROTOTYPE] Device saved prototype list failed for ${t}`,u)}catch(u){e.warn(`[PROTOTYPE] Device saved prototype list failed for ${t}`,u)}let c=wY(s,d),p=new Set(c.map((u)=>u.id));a.skipped=s.filter((u)=>!p.has(u.id)).map((u)=>u.id);for(let u of c){let f=await We(u,n);if(f)a.failed.push({id:u.id,...f}),e.warn(`[PROTOTYPE] Restore failed for ${u.id}`,f);else a.restored.push(u.id)}}catch(s){e.warn(`[PROTOTYPE] Saved prototype restore failed for ${t}`,s),a.failed.push({id:"*",code:"restore_failed",reason:r(s)})}return a}class V{device;timer;resolveClient;timeoutMs;ready;constructor(t,o=i,n=async()=>{let{AndroidCtrlProxyClient:s}=await import("./chunk-59dx6qaf.js");return s.getExistingInstance(t.deviceId)??s.getInstance(t)},a=20000){this.device=t;this.timer=o;this.resolveClient=n;this.timeoutMs=a}async client(){if(this.ready)return{client:this.ready};let t=!1;try{let o=await l(async()=>{let n=await this.resolveClient();while(!t){let a=await n.ensureConnected().catch((s)=>(e.warn("[PROTOTYPE] Restore connection attempt failed",s),!1));if(t)break;if(a)return(await n.getSupportedCommands())?.includes(ql)?{client:n}:{failure:this.unsupported()};await this.timer.sleep(Ue)}return{failure:this.unavailable()}},{timer:this.timer,timeoutMs:this.timeoutMs,label:"Saved prototype restore connection",onTimeout:()=>{t=!0}});if(o.client)this.ready=o.client;return o}catch(o){return e.warn("[PROTOTYPE] Restore connection unavailable",o),{failure:this.unavailable(r(o))}}}unavailable(t=`Saved prototype restore connection timed out after ${this.timeoutMs}ms`){return{success:!1,errorCode:"service_unavailable",error:t}}unsupported(){return{success:!1,errorCode:"device_unsupported",error:`Device does not advertise ${ql}`}}async list(){let{client:t,failure:o}=await this.client();return t?t.requestListSavedPrototypes():o}async putAsset(t){let{client:o,failure:n}=await this.client();return o?o.requestPutPrototypeAsset(t):n}async save(t){let{client:o,failure:n}=await this.client();return o?o.requestSavePrototype(t):n}}Dne({createForeignForwardEvidence:(t)=>qB(t),savedPrototypes:()=>{let t=vk();return{list:(o)=>t.list(o),restore:(o,n)=>X(o.deviceId,t,new V(o,n))}}});function Z(t){let o=t.findIndex((a)=>["--cli","--daemon","--boot-device","--ios-network-filter","--ios-templates"].includes(a)),n=o>=0?t.slice(0,o):t;return n.includes("--help")||n.includes("-h")}function ee(t,o){if(!t)return!1;let[n]=o;return n===void 0||n==="help"||n==="--help"||n==="-h"}async function te(t){if(Z(t)){let{runCliCommand:s}=await import("./chunk-25mfpthk.js");await s(["help"]),process.exit(0)}let o=t.indexOf("--boot-device");if(o>=0){let{runBootDeviceCommand:s}=await import("./chunk-k4ftd40d.js");Ot.endPhase("moduleImports"),await s(t.slice(o+1)),process.exit(0)}let n=t.indexOf("--ios-templates");if(n>=0){let{runIosTemplatesCommand:s}=await import("./chunk-ctmfshjc.js");Ot.endPhase("moduleImports"),process.exit(await s(t.slice(n+1)))}let a=t.indexOf("--ios-network-filter");if(a>=0){let{runIosNetworkFilterCommand:s}=await import("./chunk-99a6tbvd.js");Ot.endPhase("moduleImports"),process.exit(await s(t.slice(a+1)))}}async function oe(t){let{createStdioServerTransport:o}=await import("./chunk-bnyw27ja.js"),{OutputGatedTransport:n}=await import("./chunk-3dntffy9.js"),{createMcpServer:a,registerMcpTools:s}=await import("./chunk-f84z32cb.js"),{createDaemonMcpProxy:d,createProxyMcpServer:c}=await import("./chunk-p22s97qy.js"),{logger:p,LogLevel:u}=await import("./chunk-xghbxha4.js");t(p);let{runCliCommand:f,cliCommandSkipsServerBootstrap:S}=await import("./chunk-25mfpthk.js"),{runDaemonCommand:b}=await import("./chunk-dnjnh9p6.js"),{startDaemon:y}=await import("./chunk-rb7aa5gr.js"),{guardDatabaseStartup:A}=await import("./chunk-6yhm9een.js"),{DefaultDatabaseInitializer:M}=await import("./chunk-bn7jx7a2.js"),R=await import("./chunk-c25a84zb.js"),m=await import("./chunk-f3m6pdnx.js"),g=await import("./chunk-k2948b8d.js"),P=await import("./chunk-2gzd6wbd.js"),C=await import("./chunk-5sdf9y92.js"),x=await import("./chunk-cnvy4a64.js"),{FeatureFlagService:E}=await import("./chunk-pnd4mrxy.js"),{serverConfig:D}=await import("./chunk-ke3wn14v.js"),{AndroidCtrlProxyManager:L}=await import("./chunk-6vwrbkre.js"),{IosCtrlProxyBuilder:F}=await import("./chunk-fpczgf0z.js"),{IOSCtrlProxyManager:_}=await import("./chunk-w4s2vfpj.js"),{cleanupDaemonChildProcesses:N}=await import("./chunk-gppgy7pa.js"),{stopManagedAdbServer:B}=await import("./chunk-6wk0yrab.js");return Ot.endPhase("moduleImports"),{createStdioServerTransport:o,OutputGatedTransport:n,createMcpServer:a,registerMcpTools:s,createDaemonMcpProxy:d,createProxyMcpServer:c,logger:p,LogLevel:u,runCliCommand:f,cliCommandSkipsServerBootstrap:S,runDaemonCommand:b,startDaemon:y,guardDatabaseStartup:A,DefaultDatabaseInitializer:M,startVideoRecordingSocketServer:R.startVideoRecordingSocketServer,stopVideoRecordingSocketServer:R.stopVideoRecordingSocketServer,startDeviceGestureRecordingSocketServer:m.startDeviceGestureRecordingSocketServer,stopDeviceGestureRecordingSocketServer:m.stopDeviceGestureRecordingSocketServer,startDeviceSnapshotSocketServer:g.startDeviceSnapshotSocketServer,stopDeviceSnapshotSocketServer:g.stopDeviceSnapshotSocketServer,startAppearanceSocketServer:P.startAppearanceSocketServer,createDirectModeAppearanceDeviceSource:P.createDirectModeAppearanceDeviceSource,stopAppearanceSocketServer:P.stopAppearanceSocketServer,startWebRtcStreamSocketServer:C.startWebRtcStreamSocketServer,stopWebRtcStreamSocketServer:C.stopWebRtcStreamSocketServer,stopAppearanceSyncScheduler:x.stopAppearanceSyncScheduler,FeatureFlagService:E,serverConfig:D,AndroidCtrlProxyManager:L,IosCtrlProxyBuilder:F,IOSCtrlProxyManager:_,cleanupDaemonChildProcesses:N,stopManagedAdbServer:B}}import{readFileSync as Ge}from"fs";import{parseArgs as He}from"util";var Ke=Object.fromEntries(["cli","daemon-mode","no-proxy","direct","no-daemon","debug-perf","ui-perf-debug","debug","no-ui-perf-mode","mem-perf-audit","accessibility-audit","predictive","predictive-ui","raw-element-search","embedded-sdk","network-mockable","dismiss-keyboard-after-input","tool-call-recording","no-navigation-screenshots","no-waitfor-polling-overhead","no-include-not-important-views","no-report-view-ids","no-retrieve-interactive-windows","no-occlusion","strict-port","headless"].map((t)=>[t,{type:"boolean"}])),G={...Ke,"daemon-socket-path":{type:"string"},"enable-tool":{type:"string",multiple:!0},"disable-tool":{type:"string",multiple:!0}},qe=[...Object.entries(G).filter(([,t])=>t.type==="string").map(([t])=>`--${t}`),Yc,f_,h_];function ze(t,o){return t||$e(h.HEADLESS,o)}function re(t,o,n=process.env,a=(s)=>Ge(s,"utf8")){let{values:s}=He({args:t,options:G,allowPositionals:!0,strict:!1}),d=(J)=>{let O=s[J];if(O===void 0)return!1;let j=O===!0?!0:Ks(String(O));if(j===void 0)o.warn(`Invalid value for --${J}: ${String(O)}; expected true or false`);return j===!0},{enabledTools:c,disabledTools:p}=Ye(s,n),u=d("cli"),f=d("daemon-mode"),S=d("no-proxy")||d("direct"),b=d("no-daemon"),{daemonRequested:y,daemonCommand:A,daemonArgs:M}=ct(t),R=d("debug-perf")||d("ui-perf-debug")||$e(h.DEBUG_PERF,n),m=d("debug")||$e(h.DEBUG,n),g=d("strict-port"),P=ze(d("headless"),n),C=!d("no-ui-perf-mode"),x=d("mem-perf-audit"),E=d("accessibility-audit"),D=d("predictive")||d("predictive-ui"),L=d("raw-element-search"),F=g$(t),_=d("embedded-sdk"),N=d("network-mockable"),B=d("dismiss-keyboard-after-input"),Ae=$0(t,process.env),Re=B0(t),Ce=d("tool-call-recording"),Me=!d("no-navigation-screenshots"),xe=d("no-waitfor-polling-overhead"),Oe=d("no-include-not-important-views"),ke=d("no-report-view-ids"),Te=d("no-retrieve-interactive-windows"),Ee=d("no-occlusion"),De=U0(t,process.env),Ie=D0(t,process.env,Ld()),Le=dt(n,o),Y=Je(o),{videoRecordingDefaults:Fe}=Y,_e=t.indexOf("--cli"),Ne=u?t.slice(_e+1):[],v=je(t,o,Y,Le),Be=AQ({flagValue:v.sessionConfigValue,envValue:u||f||y?void 0:n[RQ],readFile:a,hasInitialSessionUuid:v.initialSessionUuid!==void 0,noProxy:S});return{cliMode:u,cliArgs:Ne,invalidInvocation:v.invalidInvocation,daemonPort:v.daemonPort,daemonHost:v.daemonHost,initialSessionUuid:v.initialSessionUuid,livenessOwnerToken:v.livenessOwnerToken,sessionConfig:Be,debugPerf:R,debug:m,strictPort:g,headless:P,uiPerfMode:C,memPerfAuditMode:x,a11yAuditMode:E,a11yLevel:v.a11yLevel,a11yFailureMode:v.a11yFailureMode,a11yMinSeverity:v.a11yMinSeverity,a11yUseBaseline:v.a11yUseBaseline,predictiveUi:D,rawElementSearch:L,planExecutionLockScope:v.planExecutionLockScope,planExecutionLockScopeExplicit:v.planExecutionLockScopeExplicit,videoRecordingDefaults:Fe,runnerReadinessTimeoutMs:v.runnerReadinessTimeoutMs,daemonMode:f,daemonRequested:y,daemonCommand:A,daemonArgs:M,skipCtrlProxyDownload:F,embeddedSdk:_,networkMockable:N,dismissKeyboardAfterInput:B,eventAllMarkers:Ae,eventAllMarkersCliOverride:Re,toolCallRecording:Ce,navigationScreenshots:Me,noWaitForPollingOverhead:xe,noProxy:S,noDaemon:b,noA11yIncludeNotImportantViews:Oe,noA11yReportViewIds:ke,noA11yRetrieveInteractiveWindows:Te,noOcclusion:Ee,outputReduction:De,toolOutputsDir:Ie,enabledTools:c,disabledTools:p}}function Ye(t,o){let n=Object.keys(o).find((m)=>FU(m));if(n)throw Error(`${n} is retired; use AUTOMOBILE_ENABLED_TOOLS or AUTOMOBILE_DISABLED_TOOLS.`);let a=(m)=>{let g=t[m];if(Array.isArray(g))return g.filter((P)=>typeof P==="string");return typeof g==="string"?[g]:[]},s=Array.from(new Set(a("enable-tool"))),d=Array.from(new Set(a("disable-tool"))),c=new Set(d),p=s.find((m)=>c.has(m));if(p)throw Error(`Tool '${p}' cannot be both enabled and disabled by CLI defaults.`);let u=(m)=>m?.split(",").map((g)=>g.trim()).filter(Boolean)??[],f=u(I(h.ENABLED_TOOLS,o)),S=u(I(h.DISABLED_TOOLS,o)),b=new Set(S),y=f.find((m)=>b.has(m));if(y)throw Error(`Tool '${y}' cannot be both enabled and disabled by environment defaults.`);let A=new Map([...f.map((m)=>[m,!0]),...S.map((m)=>[m,!1]),...s.map((m)=>[m,!0]),...d.map((m)=>[m,!1])]),M=Array.from(A).filter(([,m])=>m).map(([m])=>m),R=Array.from(A).filter(([,m])=>!m).map(([m])=>m);return{enabledTools:M,disabledTools:R}}function Je(t){let o={},n=(d,c)=>{if(!d)return;if(!new Set(["low","medium","high"]).has(d)){t.warn(`Invalid video quality preset (${c}): ${d}`);return}o.qualityPreset=d},a=(d,c)=>{if(!d)return;if(d!=="mp4"){t.warn(`Invalid video format (${c}): ${d}`);return}o.format=d};n(I(h.VIDEO_QUALITY_PRESET),"env");let s=[[I(h.VIDEO_TARGET_BITRATE_KBPS),"video target bitrate",!1,"targetBitrateKbps"],[I(h.VIDEO_MAX_THROUGHPUT_MBPS),"video max throughput",!0,"maxThroughputMbps"],[I(h.VIDEO_FPS),"video fps",!1,"fps"],[I(h.VIDEO_MAX_ARCHIVE_MB),"video max archive size",!0,"maxArchiveSizeMb"]];for(let[d,c,p,u]of s){let f=y_(d,c,p,t);if(f!==void 0)o[u]=f}return a(I(h.VIDEO_FORMAT),"env"),{videoRecordingDefaults:o,applyQualityPreset:n,applyFormat:a}}function je(t,o,n,a){let s={a11yUseBaseline:!1,planExecutionLockScope:"session",planExecutionLockScopeExplicit:!1,runnerReadinessTimeoutMs:a},d=t.indexOf("--daemon");for(let c=0;c<t.length;c++){if(["--cli","--boot-device","--"].includes(t[c]))break;let{flag:p,inlineValue:u}=ki(t[c]),f=u!==void 0&&Qe.has(p),S=f?[p,u]:t,b=f?0:c;if(p==="--a11y-use-baseline"&&u!==void 0){let A=Ks(u);if(A===void 0)o.warn(`Invalid value for ${p}: ${u}; expected true or false`);else s.a11yUseBaseline=A;continue}let y=Xe(S,b,o,{options:s,video:n});if(y!==void 0){c=f?c:y;continue}c=Ze(t,c,d,s)}return s}var Qe=new Set(["--port","--host","--initial-session-uuid","--liveness-owner-token","--a11y-level","--a11y-failure-mode","--a11y-min-severity","--plan-execution-lock-scope",sb,"--video-quality","--video-quality-preset","--video-target-bitrate-kbps","--video-max-throughput-mbps","--video-fps","--video-format","--video-archive-size-mb"]);function Xe(t,o,n,a){let{options:s,video:d}=a,c=ot(t,o,n,s);if(c!==void 0)return Math.max(c,W(t,o));return it(t,o,n,s)??st(t,o,n,s)??at(t,o,n,d)}function W(t,o){return t[o+1]!==void 0&&!t[o+1].startsWith("--")?o+1:o}function Ze(t,o,n,a){if(qe.includes(t[o]))return W(t,o);if(n>=0&&o>=n)return o;let s=et(t[o]);if(s)a.invalidInvocation??=s;else if(t[o]!==""&&!t[o].startsWith("-"))a.invalidInvocation??=`Unexpected argument: ${t[o]}; did you mean --cli ${t[o]}?`;return tt(t[o])?W(t,o):o}function et(t){if(t.startsWith("--cli="))return"Invalid CLI invocation. Use --cli <tool> instead of --cli=<tool>.";if(t.startsWith("--daemon=")||t.startsWith("--boot-device=")){let[o,...n]=t.split("=");return`Invalid invocation. Use ${o==="--boot-device"?"--boot-device --platform <android|ios>":`${o} ${n.join("=")}`} instead of ${t}.`}return}function tt(t){return t.startsWith("-")&&!t.includes("=")&&!Object.hasOwn(G,t.replace(/^-+/,""))&&!dp.some((o)=>o.cli===t||o.disableCli===t)}function ot(t,o,n,a){let s=t[o];if(s==="--port"){let d=t[o+1],c=L0(d,n);if(c!==void 0)a.daemonPort=c,o++}else if(s==="--host"){let d=t[o+1];if(d&&!d.startsWith("--"))a.daemonHost=d,o++;else n.warn(`Invalid host: ${d}`)}else return rt(t,o,n,a);return o}function rt(t,o,n,a){let s=t[o],d=t[o+1]?.trim(),c=d!==void 0&&d.length>0&&!d.startsWith("--");if(s==="--initial-session-uuid"){if(!c)return n.warn(`Invalid initial session UUID: ${t[o+1]}`),o;return a.initialSessionUuid=t[o+1],o+1}let p=nt(t,o,a);if(p!==void 0)return p;if(s==="--liveness-owner-token"){if(!c)return n.warn("--liveness-owner-token requires a non-empty value"),o;return a.livenessOwnerToken=d,o+1}return}function nt(t,o,n){let a=t[o];if(a===F0){let s=t[o+1]?.trim();if(!s||s.startsWith("--")&&!s.startsWith("{"))throw new Pm(`${F0} requires inline JSON or a file path`);return n.sessionConfigValue=s,o+1}if(a.startsWith(`${F0}=`))return n.sessionConfigValue=a.slice(F0.length+1),o;return}function it(t,o,n,a){let s=t[o];if(s==="--a11y-level")a.a11yLevel=t[++o];else if(s==="--a11y-failure-mode")a.a11yFailureMode=t[++o];else if(s==="--a11y-min-severity")a.a11yMinSeverity=t[++o];else if(s==="--a11y-use-baseline")a.a11yUseBaseline=!0;else return;return o}function st(t,o,n,a){let s=t[o];if(s==="--plan-execution-lock-scope"){let d=t[++o];if(d==="global"||d==="session")a.planExecutionLockScope=d,a.planExecutionLockScopeExplicit=!0;else n.warn(`Invalid plan execution lock scope: ${d}. Using default: ${a.planExecutionLockScope}`)}else if(s===sb){let d=t[++o],c=cb(d);if(c!==void 0)a.runnerReadinessTimeoutMs=c;else n.warn(`Invalid runner readiness timeout: ${d}; expected an integer from ${ab} to ${gR}`)}else return;return o}function at(t,o,n,a){let s=t[o],{videoRecordingDefaults:d,applyQualityPreset:c,applyFormat:p}=a;if(s==="--video-quality"||s==="--video-quality-preset")c(t[++o],"cli");else if(s==="--video-target-bitrate-kbps")k(d,t[++o],n,{label:"video target bitrate",allowFloat:!1,key:"targetBitrateKbps"});else if(s==="--video-max-throughput-mbps")k(d,t[++o],n,{label:"video max throughput",allowFloat:!0,key:"maxThroughputMbps"});else if(s==="--video-fps")k(d,t[++o],n,{label:"video fps",allowFloat:!1,key:"fps"});else if(s==="--video-format")p(t[++o],"cli");else if(s==="--video-archive-size-mb")k(d,t[++o],n,{label:"video max archive size",allowFloat:!0,key:"maxArchiveSizeMb"});else return;return o}function k(t,o,n,a){let{label:s,allowFloat:d,key:c}=a,p=y_(o,s,d,n);if(p!==void 0)t[c]=p}function dt(t,o){let n=t[ID]??t.AUTO_MOBILE_RUNNER_READINESS_TIMEOUT_MS,a=cb(n),s=a;if(n!==void 0&&a===void 0)o.warn(`Invalid ${ID}: ${n}; expected an integer from ${ab} to ${gR}`);return s}function ct(t){let o=t.indexOf("--daemon"),n=o>=0,a=o>=0?t[o+1]||void 0:void 0,s=o>=0?t.slice(o+2):[];return{daemonRequested:n,daemonCommand:a,daemonArgs:s}}function ne(t,o){o.terminate(t.exitCode)}async function H(t){try{await t.closeAfterFlush()}catch(o){t.error(`Daemon command completed successfully, but logger teardown failed; exiting 0: ${r(o)}`),await t.flush()}}async function K(t,o){await H(t),o.exit(0)}var lt=new Set(["start","restart","restart-admitted","restart-acceptance-session"]);function ie(t){return!lt.has(t)}var se=5000;function de(t){let o=t.timer??i,n=t.logger??e;if(q("Android CtrlProxy prefetch cleanup",t.startAndroidSweep,o,n),q("native helper cleanup",t.startNativeHelperSweep,o,n),t.platform==="darwin")q("iOS CtrlProxy runner cleanup",t.startIosReap,o,n)}function q(t,o,n,a){let s;try{s=o()}catch(c){a.warn(`[STARTUP_MAINTENANCE] ${t} failed: ${ae(c)}`);return}let d=n.setTimeout(()=>{a.warn(`[STARTUP_MAINTENANCE] ${t} exceeded ${se}ms; continuing startup`)},se);d.unref?.(),s.catch((c)=>{a.warn(`[STARTUP_MAINTENANCE] ${t} failed: ${ae(c)}`)}).finally(()=>{n.clearTimeout(d)})}function ae(t){return r(t)}function ce(t,o,n){if(!n)de({platform:process.platform,startAndroidSweep:()=>t.AndroidCtrlProxyManager.sweepStalePrefetchDirsOnStartup(),startIosReap:()=>t.IOSCtrlProxyManager.startOrphanRunnerReapOnStartup(),startNativeHelperSweep:async()=>{await fne()}});ut(t,o,n),mt(t,o,n),ft(t)}function ut(t,o,n){if(n)Ot.recordPhase("androidCtrlProxyPrefetch",0);else if(o)t.logger.info(`CtrlProxy downloads disabled (${Vk} or ${GR})`),Ot.recordPhase("androidCtrlProxyPrefetch",0);else Ot.startPhase("androidCtrlProxyPrefetch"),t.AndroidCtrlProxyManager.prefetchApk().then(()=>{Ot.endPhase("androidCtrlProxyPrefetch")})}function mt(t,o,n){if(process.platform!=="darwin"||n)return;if(o){t.logger.info(`CtrlProxy iOS prefetch disabled (${Vk} or ${GR})`),Ot.recordPhase("iosCtrlProxyPrefetch",0);return}Ot.startPhase("iosCtrlProxyPrefetch"),t.IosCtrlProxyBuilder.prefetchBuild().then(()=>{Ot.endPhase("iosCtrlProxyPrefetch")})}function ft(t){if($Q(),process.platform==="darwin"&&pt(h.WEBRTC_WHIP_ENDPOINT)&&!I(h.IOS_SCREEN_CAPTURE_HELPER))Gc.getInstance().ensure().catch((o)=>{t.logger.warn(`[SCREEN_CAPTURE_HELPER] Background prefetch failed: ${r(o)}`)})}function le(t){let{eventAllMarkers:o,eventAllMarkersCliOverride:n}=t;return o.length>0||n?{eventAllMarkers:o,eventAllMarkersCliOverride:n}:{}}function ue(t,o){let{videoRecordingDefaults:n,runnerReadinessTimeoutMs:a,daemonHost:s}=t;return{port:t.daemonPort,...s!==void 0?{host:s}:{},strictPort:t.strictPort,debug:t.debug,debugPerf:t.debugPerf,planExecutionLockScope:t.planExecutionLockScope,...a!==void 0?{runnerReadinessTimeoutMs:a}:{},videoQualityPreset:n.qualityPreset,videoTargetBitrateKbps:n.targetBitrateKbps,videoMaxThroughputMbps:n.maxThroughputMbps,videoFps:n.fps,videoFormat:n.format,videoMaxArchiveSizeMb:n.maxArchiveSizeMb,toolOutputsDir:t.toolOutputsDir,networkMockable:t.networkMockable,embeddedSdk:t.embeddedSdk,enabledTools:t.enabledTools,disabledTools:t.disabledTools,dismissKeyboardAfterInput:t.dismissKeyboardAfterInput,...o,noUiPerfMode:!t.uiPerfMode,memPerfAudit:t.memPerfAuditMode,accessibilityAudit:t.a11yAuditMode,accessibilityLevel:t.a11yLevel,accessibilityFailureMode:t.a11yFailureMode,accessibilityMinSeverity:t.a11yMinSeverity,accessibilityUseBaseline:t.a11yUseBaseline,predictiveUi:t.predictiveUi,rawElementSearch:t.rawElementSearch,skipCtrlProxyDownload:t.skipCtrlProxyDownload,toolCallRecording:t.toolCallRecording,noNavigationScreenshots:!t.navigationScreenshots,noWaitForPollingOverhead:t.noWaitForPollingOverhead,noA11yIncludeNotImportantViews:t.noA11yIncludeNotImportantViews,noA11yReportViewIds:t.noA11yReportViewIds,noA11yRetrieveInteractiveWindows:t.noA11yRetrieveInteractiveWindows,noOcclusion:t.noOcclusion,...t.outputReduction}}function pe(t,o,n){return{...vt(t),...St(t),...n,...yt(t),...gt(t,o),...t.outputReduction,toolResultsNoStructuredContent:t.outputReduction.toolResultsNoStructuredContent?!0:void 0}}function vt(t){let{daemonPort:o,daemonHost:n,runnerReadinessTimeoutMs:a}=t;return{...o!==void 0?{port:o}:{},...n!==void 0?{host:n}:{},...t.strictPort?{strictPort:!0}:{},...t.debug?{debug:!0}:{},...t.debugPerf?{debugPerf:!0}:{},...t.planExecutionLockScopeExplicit?{planExecutionLockScope:t.planExecutionLockScope}:{},...a!==void 0?{runnerReadinessTimeoutMs:a}:{},...t.toolCallRecording?{toolCallRecording:!0}:{}}}function St(t){let o=t.videoRecordingDefaults;return{videoQualityPreset:o.qualityPreset,videoTargetBitrateKbps:o.targetBitrateKbps,videoMaxThroughputMbps:o.maxThroughputMbps,videoFps:o.fps,videoFormat:o.format,videoMaxArchiveSizeMb:o.maxArchiveSizeMb,toolOutputsDir:t.toolOutputsDir,...t.networkMockable?{networkMockable:!0}:{},...t.embeddedSdk?{embeddedSdk:!0}:{},...t.enabledTools.length>0?{enabledTools:t.enabledTools}:{},...t.disabledTools.length>0?{disabledTools:t.disabledTools}:{},...t.dismissKeyboardAfterInput?{dismissKeyboardAfterInput:!0}:{}}}function yt(t){return{...!t.uiPerfMode?{noUiPerfMode:!0}:{},...!t.navigationScreenshots?{noNavigationScreenshots:!0}:{},...t.noWaitForPollingOverhead?{noWaitForPollingOverhead:!0}:{},...t.noA11yIncludeNotImportantViews?{noA11yIncludeNotImportantViews:!0}:{},...t.noA11yReportViewIds?{noA11yReportViewIds:!0}:{},...t.noA11yRetrieveInteractiveWindows?{noA11yRetrieveInteractiveWindows:!0}:{},...t.noOcclusion?{noOcclusion:!0}:{}}}function gt(t,o){return{...t.memPerfAuditMode?{memPerfAudit:!0}:{},...t.a11yAuditMode?{accessibilityAudit:!0}:{},...o?{accessibilityLevel:o.level,accessibilityFailureMode:o.failureMode,accessibilityMinSeverity:o.minSeverity,accessibilityUseBaseline:o.useBaseline}:{},...t.predictiveUi?{predictiveUi:!0}:{},...t.rawElementSearch?{rawElementSearch:!0}:{},...t.skipCtrlProxyDownload?{skipCtrlProxyDownload:!0}:{}}}function me(t){return dp.filter((o)=>o.field!=="actionsCompactMetadata"&&t[o.field]===!0).map((o)=>({key:o.featureFlagKey,label:o.label}))}function fe(t){if(!t.a11yAuditMode)return null;return{level:t.a11yLevel||"AA",failureMode:t.a11yFailureMode||"report",minSeverity:t.a11yMinSeverity||(t.a11yFailureMode==="strict"?"error":"warning"),useBaseline:t.a11yUseBaseline}}function Pt(t,o){return[["debug",t.debug,"--debug"],["debug-perf",t.debugPerf,"--debug-perf/--ui-perf-debug"],["ui-perf-mode",t.uiPerfMode,"--ui-perf-mode"],["mem-perf-audit",t.memPerfAuditMode,"--mem-perf-audit"],["accessibility-audit",t.a11yAuditMode,"--accessibility-audit",o],["predictive-ui",t.predictiveUi,"--predictive/--predictive-ui"],["raw-element-search",t.rawElementSearch,"--raw-element-search"],["tool-call-recording",t.toolCallRecording,"--tool-call-recording"],...me(t.outputReduction).map(({key:n,label:a})=>[n,!0,a,void 0])]}function ve(t,o,n){let{logger:a,serverConfig:s}=o,d=o.FeatureFlagService.getInstance(),c=Pt(t,n);return async()=>{await d.initialize();for(let[p,u,f,S]of c){if(!u)continue;await d.setFlag(p,u,S),a.info(`Feature flag ${u?"enabled":"disabled"} (${f})`)}if(s.setActionsCompactMetadataEnabled(eV(t.outputReduction.actionsCompactMetadata,d.isEnabled("actions-compact-metadata"))),!t.navigationScreenshots)await d.setFlag("navigation-screenshots",!1),a.info("Navigation screenshots disabled (--no-navigation-screenshots)")}}async function Se(t,o,n){await Ot.runPhase("databasePreflight",async()=>{if(t.daemonMode){await o.guardDatabaseStartup(async()=>{await new o.DefaultDatabaseInitializer().initialize(),await n()});return}let{runDirectModeStartup:a}=await import("./chunk-6pg7bqck.js");await a({noProxy:t.noProxy,assertDbOwnership:async()=>{let{assertDirectModeDbOwnership:s,createDefaultDirectModeGuardDeps:d}=await import("./chunk-jzqrv78s.js");s(d())},applyFeatureFlagStartup:n})})}function ye(t,o){let{serverConfig:n,logger:a,LogLevel:s}=o;if(t.debug)a.setLogLevel(s.DEBUG);if(n.setPlanExecutionLockScope(t.planExecutionLockScope),t.runnerReadinessTimeoutMs!==void 0)n.setRunnerReadinessTimeoutMs(t.runnerReadinessTimeoutMs);n.setActionsCompactMetadataEnabled(eV(t.outputReduction.actionsCompactMetadata,n.isActionsCompactMetadataEnabled())),n.setVideoRecordingDefaults(t.videoRecordingDefaults),n.setToolOutputsDir(t.toolOutputsDir),n.setSkipCtrlProxyDownload(t.skipCtrlProxyDownload),n.setEmbeddedSdkEnabled(t.embeddedSdk),n.setNetworkMockableEnabled(t.networkMockable),n.setDismissKeyboardAfterInputEnabled(t.dismissKeyboardAfterInput),n.setEventAllMarkers(t.eventAllMarkers)}function ge(t,o){let n=[[!t.uiPerfMode,"UI perf mode disabled (--no-ui-perf-mode): skipping selection-state visual capture on taps and UI perf auditing"],[t.embeddedSdk,"Embedded SDK tools enabled (--embedded-sdk)"],[t.dismissKeyboardAfterInput,"Dismiss keyboard after internal text input enabled (--dismiss-keyboard-after-input)"],[t.noA11yIncludeNotImportantViews,"Accessibility includeNotImportantViews disabled (--no-include-not-important-views)"],[t.noA11yReportViewIds,"Accessibility reportViewIds disabled (--no-report-view-ids)"],[t.noA11yRetrieveInteractiveWindows,"Accessibility retrieveInteractiveWindows disabled (--no-retrieve-interactive-windows)"],[t.noOcclusion,"Observe occlusion pass disabled (--no-occlusion)"],[t.headless,"Headless prototype mode: prototype calls run on the virtual device (--headless)"]];for(let[a,s]of n)if(a)o.info(s);bt(t.eventAllMarkers,o)}function bt(t,o){if(t.length>0){o.info(`Internal text-input eventAll auto-promotion markers configured (--event-all-markers): ${JSON.stringify(t)}`);return}if(process.argv.slice(2).some((a)=>a===Yc||a.startsWith(`${Yc}=`)))o.warn(`${Yc} was provided but resolved to no markers; internal text-input eventAll auto-promotion stays disabled`)}async function Pe(t,o,n,a){let{logger:s}=o,d=!t.noProxy,c=d?void 0:Kc.createInstance();if(n.directModeActive=!d,d)s.info("Starting MCP server in proxy mode (connecting to daemon)");else s.info("Starting MCP server in direct mode (--no-proxy flag)"),await wt(o,c);let p=new o.OutputGatedTransport(o.createStdioServerTransport()),u=await ht(p),f=d&&t.sessionConfig?new(await import("./chunk-5s645vr4.js")).EarlyStartTransport(p):void 0;await f?.startEarly();let{server:S,proxyToClaimInitialSession:b}=await At(t,o,n,{launch:a,useProxyMode:d,deviceReadiness:c});try{s.info("Connecting MCP server to stdio transport"),Ot.startPhase("serverListening"),u.value=!0,await S.connect(f??p),Ot.endPhase("serverListening"),s.info("MCP server connected to stdio transport"),b?.claimInitialSession(),s.info(`AutoMobile MCP server running on stdio (${d?"proxy":"direct"} mode)`),Ot.emit("mcp-server",{transport:"stdio",mode:d?"proxy":"direct"})}catch(y){throw s.error("MCP server connect failed:",y),y}}async function wt(t,o){await t.startVideoRecordingSocketServer(),await t.startDeviceGestureRecordingSocketServer(o),await t.startDeviceSnapshotSocketServer(),await t.startAppearanceSocketServer(t.createDirectModeAppearanceDeviceSource(()=>{let n=o.getExplicitDevicePin();return n?[n]:[]})),await t.startWebRtcStreamSocketServer()}async function ht(t){let{MAX_CALLER_MCP_REQUEST_TIMEOUT_MS:o}=await import("./chunk-gp6vb5gf.js"),n={value:!1};return dQ(process.stdin,()=>n.value?t.answerReceivedThenStop("stdin closed"):t.stopSending("stdin closed"),o),lQ(process.stdout,()=>t.stopSending("stdout closed or write failed")),n}async function At(t,o,n,{launch:a,useProxyMode:s,deviceReadiness:d}){try{if(!s)return{server:o.createMcpServer({debug:t.debug,deviceReadiness:d}),proxyToClaimInitialSession:void 0};let{getDefaultSessionHeartbeatTimeoutMs:c}=await import("./chunk-zs6dqm35.js"),p=o.createDaemonMcpProxy({autoStartDaemon:!t.noDaemon,lifecycleNamespaceEnv:process.env,daemonOptions:a.daemonStartupOptions,initialSessionUuid:t.initialSessionUuid,livenessOwnerToken:t.livenessOwnerToken,heartbeatTimeoutMs:c()});n.stdioProxy=p;let u=t.sessionConfig?await Rt(p,t.sessionConfig,{launchParentPid:a.launchParentPid,ownerGenerationToken:a.ownerGenerationToken,modules:o}):void 0,f=o.createProxyMcpServer({proxy:p,...u?{session:u}:{}});return{server:f.server,proxyToClaimInitialSession:f.proxy}}catch(c){throw o.logger.error("Failed to create MCP server:",c),c}}async function Rt(t,o,{launchParentPid:n,ownerGenerationToken:a,modules:s}){let d=await Ct(n,o.executionOwnerPid,a);t.setExecutionOwnerLossProbe(()=>d.check()!==void 0);let c=await t.acquireBrokerSession(o);return s.logger.info(`[SessionBroker] Acquisition ${c.outcome}`+(c.failure?` (${c.failure.code})`:"")),c}async function Ct(t,o,n){let[{ExecutionOwnerWatch:a},{isProcessRunning:s},{defaultTimer:d},{defaultLockOwnerGenerationProbe:c},{processGenerationReadIsCheap:p}]=await Promise.all([import("./chunk-d6rb08ga.js"),import("./chunk-0jyfg947.js"),import("./chunk-wnmqt1dc.js"),import("./chunk-knyzw9md.js"),import("./chunk-1scenrk7.js")]),u=new a({launchParentPid:t,ownerPid:o,ownerGenerationToken:n,generationCheckEvery:p()?1:void 0,onOwnerLost:()=>uQ("execution-owner-lost")},{isProcessRunning:(f)=>s(f),currentParentPid:()=>process.ppid},d,c);return u.start(),u}async function be(t,o,n){let{logger:a}=t,s=re(process.argv.slice(2),a);if(s.invalidInvocation){console.error(s.invalidInvocation),process.exit(1);return}if(s.headless)IQ(process.env);let d=await Mt(s);if(await xt(s,t))return;if(await kt(s,t))return;Tt(s,t);let c=fe(s);if(await Se(s,t,ve(s,t,c)),s.noWaitForPollingOverhead)t.serverConfig.setWaitForPollingOverheadEnabled(!1),a.info("WaitFor polling overhead disabled (--no-waitfor-polling-overhead): back stack skipped during observe waitFor polling");ge(s,a);let p=le(s);if(s.daemonMode){await t.startDaemon(ue(s,p));return}if(s.daemonCommand){await Et(s,s.daemonCommand,t);return}let u=pe(s,c,p);if(s.cliMode){await we(s,t,u);return}await Pe(s,t,o,{launchParentPid:n,ownerGenerationToken:d,daemonStartupOptions:u})}async function Mt(t){let{sessionConfig:o}=t;if(t.cliMode||t.daemonMode||t.daemonRequested||o?.executionOwnerPid===void 0)return;let[{isProcessRunning:n},{defaultLockOwnerGenerationProbe:a}]=await Promise.all([import("./chunk-0jyfg947.js"),import("./chunk-knyzw9md.js")]);return TQ(o,{isProcessRunning:(s)=>n(s),probe:a})}async function xt(t,o){let{daemonCommand:n,daemonArgs:a}=t;if(t.daemonRequested&&n===void 0){let{printUnknownDaemonCommand:s}=await import("./chunk-47n9m2de.js");return s(void 0),!0}if(n&&ie(n))return await o.runDaemonCommand(n,a,{namespaceEnv:process.env}),await K(o.logger,process),!0;return!1}async function kt(t,o){if(!t.cliMode||!o.cliCommandSkipsServerBootstrap(t.cliArgs))return!1;return await we(t,o,void 0),!0}function Tt(t,o){OQ(t.enabledTools,t.disabledTools),o.registerMcpTools(t.daemonMode),ye(t,o),ce(o,t.skipCtrlProxyDownload,ee(t.cliMode,t.cliArgs))}async function Et(t,o,n){let{enabledTools:a,disabledTools:s}=t,d=a.length>0||I(h.ENABLED_TOOLS)!==void 0,c=s.length>0||I(h.DISABLED_TOOLS)!==void 0,p=d||c;await n.runDaemonCommand(o,t.daemonArgs,{namespaceEnv:process.env,...p?{startupToolDefaults:{...d?{enabledTools:a}:{},...c?{disabledTools:s}:{}}}:{}}),await K(n.logger,process)}async function we(t,o,n){let{logger:a}=o;a.info("Running in CLI mode");let s=await o.runCliCommand(t.cliArgs,n);if(await H(a),s){ne(s,{terminate:(d)=>process.exit(d)});return}process.exit(process.exitCode??0)}function he(t,o){let{logger:n}=t,a=!1;KS(async(s)=>{a=!1,n.info(`Received ${s} signal, shutting down`),await v_(UQ({directModeActive:()=>o.directModeActive,cleanupChildProcesses:()=>t.cleanupDaemonChildProcesses(),stopManagedAdbServer:()=>t.stopManagedAdbServer(),stopVideoRecordingSocketServer:()=>t.stopVideoRecordingSocketServer(),stopDeviceGestureRecordingSocketServer:()=>t.stopDeviceGestureRecordingSocketServer(),stopDeviceSnapshotSocketServer:()=>t.stopDeviceSnapshotSocketServer(),stopAppearanceSocketServer:()=>t.stopAppearanceSocketServer(),stopWebRtcStreamSocketServer:()=>t.stopWebRtcStreamSocketServer(),stopAppearanceSyncScheduler:()=>t.stopAppearanceSyncScheduler(),cleanupPrefetchedApk:()=>t.AndroidCtrlProxyManager.cleanupPrefetchedApk(),closeStdioProxy:()=>o.stdioProxy?.close({executionOwnerLost:s==="execution-owner-lost"}),drainDatabaseWrites:async(d)=>{let{getDbWriteBarrier:c}=await import("./chunk-7n5fz68h.js");if(!await c().drain(d))n.warn(`Timed out after ${d}ms draining in-flight DB writes; closing database anyway`)},settleMigrations:async(d)=>{let{awaitInFlightMigrations:c}=await import("./chunk-kny2xemh.js");if(!await c(d))n.warn(`Timed out after ${d}ms awaiting in-flight startup migration; closing database anyway`)},closeDatabase:async()=>{let{closeDatabase:d}=await import("./chunk-kny2xemh.js");await d({forShutdown:!0})},refusedDatabaseAccessCount:async()=>{let{refusedDatabaseAccessCountAfterShutdownClose:d}=await import("./chunk-kny2xemh.js");return d()},closeLogger:()=>n.closeAfterFlush(),warn:(d)=>n.warn(d)}),(d,c)=>{a=!0,n.warn(d,c)},{timer:i})},async()=>(await n.closeAfterFlush(),a?{exitCode:1}:void 0))}eY();process.env[tS]??=oM();var T;function z(t,o){let n=o instanceof Error?o.stack??o.message:String(o);if(T){if(T.error(`${t}: ${n}`),qf()==="file")eo(t,n)}else eo(t,n)}A0();T0((t)=>{if(t.type==="uncaughtException"){z("Uncaught exception",t.error);return}z("Unhandled rejection",t.reason)});async function Dt(){let t=process.ppid;Ot.mark("processEntry"),Ot.startPhase("moduleImports"),await te(process.argv.slice(2));let o=await oe((a)=>{T=a}),n={stdioProxy:void 0,directModeActive:!1};he(o,n);try{await be(o,n,t)}catch(a){throw o.logger.error("Error initializing server:",a),a}}function Tr(){Dt().catch(async(t)=>{z("Fatal error in main()",t),await T?.closeAfterFlush();let{resolveDaemonStartupExitCode:o}=await import("./chunk-6yhm9een.js");process.exit(o(t))})}export{Tr as runServerEntry};
3
+
4
+ //# debugId=976EF21065310B5B64756E2164756E21
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ import{i,zt,Bd,dr,re,qt,l,e}from"./chunk-r0vp315h.js";import{da,ar,LT,Bv,BT,qm,ua,To,ji,Pn,Km,Gm,Tc,An,ko,KT,La}from"./chunk-4vxeq0vd.js";import{dd,J,kn,z,L,li,o,lo,bd,Qo,OR,mr,dt,MR,Rr,n$,N,va,lt,wt,Nt,Ut,mn,a$,ft,js,rt,K,Ej,Eie,Ib,Ij,Dl,$u,fe,Sd,Ol,ba,wd,Ti,_b,Pr,hr,nP,Ee,Qt,gr,J$,Td,EO,M9,hn,zr,dy,xf,Ts,Zi,or,Poe,xO,p2,m2,Toe,nU,koe,hE,OO,bP,Cf,SP,qb,Dn,ur,V9,P2,A2,BO,T2,Of,x,Ce,E,Xs,Qi}from"./chunk-sfqe223f.js";import{HV,ite,sL,Lm,Bm,gp,z5}from"./chunk-661c50hh.js";import{Xp}from"./chunk-w5yypt53.js";import{Oe,jt,Tt}from"./chunk-e0870khr.js";import{FC,bL,SL,wL,RL,PL,CT,nW,vte,eg}from"./chunk-cqhw4yr6.js";import{od}from"./chunk-b3tdtq7r.js";import{Qc,HF,N5,Ev,qF,CV,hp,Wee,ed,DV,zee,wo,VF,jee,Fm,Kee,Gee,WF,vC,zF,jF,KF,GF,YF}from"./chunk-c27yv1dx.js";import{pW,ls,Na,rg,Rte,br,zi,EL,Ate}from"./chunk-vdqag3fj.js";import{XT,Ec,yg,vg,Tre,Tn,jw,Kw,Gw,cB,Kn,fa,bg,az,Wv,dB,Ha}from"./chunk-cb1ga9rd.js";import{r,t,u,Rt}from"./chunk-2b39zyxc.js";import{AsyncLocalStorage as Dt}from"async_hooks";var Fe=new Dt;function ST(n,a){return n?Fe.run(n,a):a()}function yC(){Fe.getStore()?.()}var He="Nothing is focused on tvOS; use pressButton to establish focus and observe before retrying tapOn.";function ie(n){let{left:a,top:s,right:c,bottom:d}=n.bounds;return JSON.stringify([n["resource-id"],a,s,c,d])}function Ve(n,a){return n.bounds.left===a.bounds.left&&n.bounds.top===a.bounds.top&&n.bounds.right===a.bounds.right&&n.bounds.bottom===a.bounds.bottom}function It(n,a){let s=n.bounds,c=a.bounds,d=(c.left+c.right-s.left-s.right)/2,p=(c.top+c.bottom-s.top-s.bottom)/2,h=d===0?[]:[d>0?"right":"left"],m=p===0?[]:[p>0?"down":"up"],f=s.left<c.right&&c.left<s.right;return(s.top<c.bottom&&c.top<s.bottom?!0:f?!1:Math.abs(d)>=Math.abs(p))?[...h,...m]:[...m,...h]}function Ht({maxMoves:n=30,maxSearchMoves:a=60,focusTimeoutMs:s=3000,focusPollIntervalMs:c=200}){for(let[d,p]of Object.entries({maxMoves:n,maxSearchMoves:a,focusTimeoutMs:s}))if(!Number.isInteger(p)||p<0)throw new t(`tvOS ${d} must be a non-negative integer.`);if(!Number.isInteger(c)||c<=0)throw new t("tvOS focusPollIntervalMs must be a positive integer.");return{maxMoves:n,maxSearchMoves:a,focusTimeoutMs:s,focusPollIntervalMs:c}}function Vt(n,a){let s=Object.entries(n).filter(([c,d])=>d!==void 0&&(d!==!1||c==="ensureChecked")&&!["action","elementId","text","index"].includes(c));if(n.action!=="tap"||s.length)throw new t(`tvOS tapOn supports only action tap and elementId, text, index; unsupported: ${n.action!=="tap"?n.action:s.map(([c])=>c).join(", ")}.`);if(n.index!==void 0&&(!Number.isInteger(n.index)||n.index<0))throw new t("tvOS tap index must be a non-negative integer.");return Ht(a)}function Bt(n,a){return(a.elementId!==void 0||a.text!==void 0)&&(a.elementId===void 0||n["resource-id"]===a.elementId||n["view-id"]===a.elementId)&&(a.text===void 0||n.text===a.text)}function Be(n,a){return a.reduce((s,c)=>{let d=c.bounds,p=n.bounds;return d.left<=p.left&&d.top<=p.top&&d.right>=p.right&&d.bottom>=p.bottom&&ft(d)>ft(s.bounds)?c:s},n)}function Lt(n,a){return Ve(n,a)||a.checkable==="true"&&Be(a,[n])===n}function te(n){return JSON.stringify([n["resource-id"],n["view-id"],n.text,n.class])}function De(n){return JSON.stringify([n["resource-id"],n["view-id"],n.class])}function Mt(n,a){if(!a)return"[]";let s=De(a);return JSON.stringify([ie(a),n.filter((c)=>De(c)===s).map((c)=>[ie(c),c.text])])}function _t(n,a,s){let{left:c,top:d,right:p,bottom:h}=n.bounds;return c>=0&&d>=0&&p<=a&&h<=s}async function Ie(n,a,s,c){let d=qm(await n.hierarchy(s));s?.throwIfAborted();let p=new K().flattenViewHierarchy(d).map(({element:S})=>S),h=p.find((S)=>S.focused==="true"),m=Mt(p,h),f=c?p.filter((S)=>te(S)===c.key):[];if(h&&c&&f.length!==c.count)throw new t("The tvOS tapOn target disappeared or became ambiguous; observe and retry with its current identifier or exact text.");let y=p.filter((S)=>S.bounds.right>S.bounds.left&&S.bounds.bottom>S.bounds.top&&Bt(S,a)),b=y.map((S,O)=>({element:S,windowRank:_t(S,d.screenWidth,d.screenHeight)?0:1,area:ft(S.bounds),order:O,interactive:!1})).sort(Cf).map(({element:S})=>S),T=c?f[c.ordinal]:SP(b,(S)=>Be(S,y))[a.index??0];if(!T||c)return{focus:h,target:T,identity:c,signature:m};let v=te(T),g=p.filter((S)=>te(S)===v);return{focus:h,target:T,identity:{key:v,ordinal:g.indexOf(T),count:g.length},signature:m}}function Ne(n){if(!n.focus)throw new t(He);return n.focus}async function Le({client:n,options:a,signal:s,timer:c,focusTimeoutMs:d,focusPollIntervalMs:p},h){s?.throwIfAborted();let m=await Ie(n,a,s,h),f=c.now()+d;while(!m.focus&&c.now()<f)await l(()=>c.sleep(Math.min(p,f-c.now())),{timer:c,signal:s,label:"tvOS focus settling"}),s?.throwIfAborted(),m=await l(()=>Ie(n,a,s,h),{timer:c,signal:s,timeoutMs:Math.max(0,f-c.now()),timeoutError:()=>new t(He),label:"tvOS focus settling"});return Ne(m),m}async function Wt(n,a,s){let{client:c,signal:d}=n,p=a,h=0,m=async(y)=>{if(h>=s)throw new t(`No tvOS element matched after searching ${s} focus moves; observe and check the identifier, exact text or index, or move closer with pressButton before retrying.`);h++,await c.request({type:"request_press_button",action:y},d),d?.throwIfAborted();let b=await Le(n),T=b.signature!==p.signature;return p=b,T},f=async(y)=>{while(!p.target&&await m(y));return Boolean(p.target)};for(let y of["down","up"]){do if(await f("right")||await f("left"))return p;while(await m(y));if(p.target)return p}throw new t("No tvOS element matched after searching the screen with focus moves; observe and check the identifier, exact text or index.")}function ne(n){return n["resource-id"]||n.text||ie(n)}function Gt(n,a,s){if(n>=a)throw new t(`tvOS tapOn exceeded maxMoves (${a}) before reaching ${ne(s)}; observe and move closer with pressButton before retrying.`)}async function $t(n,a,s){let{options:c}=n,d=await Le(n,a);if(!d.target&&!a){if(c.elementId===void 0&&c.text===void 0)throw new t("No tvOS element matched; observe and check the identifier, exact text or index.");d=await Wt(n,d,s)}return{focus:Ne(d),target:d.target,identity:d.identity,signature:d.signature}}async function Me(n,a,s,c={}){let{maxMoves:d,maxSearchMoves:p,focusTimeoutMs:h,focusPollIntervalMs:m}=Vt(a,c);s?.throwIfAborted();let f={client:await ua(n,s),options:a,signal:s,timer:c.timer??i,focusTimeoutMs:h,focusPollIntervalMs:m},{client:y}=f,b=new Map,T,v;for(let g=0;;g++){s?.throwIfAborted();let S=await $t(f,v,p),{focus:O,target:R}=S;if(v=S.identity,Lt(O,R))return await y.request({type:"request_press_button",action:"select"},s),{success:!0,action:"tap",element:R,...Ve(O,R)?{}:{debug:{activatedAncestor:O}}};let w=b.get(S.signature)??new Set;if(T?.signature===S.signature)w.add(T.direction),b.set(S.signature,w);let A=It(O,R).find((Q)=>!w.has(Q));if(!A)throw new t(`tvOS focus stopped making progress from ${ne(O)} toward ${ne(R)}; the target may be unreachable or in a focus trap. Observe and navigate with pressButton before retrying.`);Gt(g,d,R),await y.request({type:"request_press_button",action:A},s),T={signature:S.signature,direction:A}}}var Kt=new Set(["\b","\x7F","\uF728"]);function Xt(n,a,s){if(s.container!==void 0||s.selectionStrategy!==void 0||s.layer!==void 0||s.display!==void 0||n.length===0)throw new t("watchOS sendKeys supports only type commands into the focused field; focus it with tapOn first.");if(a!==void 0&&(a.testTag!==void 0||a.textAny!==void 0||a.elementId===void 0&&a.text===void 0))throw new t("watchOS sendKeys selector supports only exact elementId or text; focus the field with tapOn first.");return n.map((c)=>{if(c.action!=="type"||!c.text||c.operation==="replace"||c.mode!==void 0&&c.mode!=="auto"||c.keyboardProfile!==void 0)throw new t("watchOS sendKeys supports only non-empty append type commands; focus the field with tapOn first.");if([...c.text].some((d)=>Kt.has(d)))throw new t("watchOS sendKeys appends text only; text containing a delete key would erase existing content.");return c})}var _e=[50,100,200,250,250,250,250];function ze(n){return n instanceof La&&n.errorCode==="command_failed"&&n.message.startsWith("No focused text field")}async function Yt(n,a,s,c){await new kn(s).executeOrThrow(()=>n.request({type:"type",text:a},c).then(()=>{return}),{maxAttempts:_e.length+1,delays:_e,signal:c,shouldRetry:ze,expectedFailure:{reason:"sendKeys reports the focus refusal as a failed command",matches:ze}})}async function We(n,a,s,c={}){let d=Xt(a,s,c),{signal:p,timer:h}=c;p?.throwIfAborted();let m=To.require(n);if(s!==void 0)await HV(n,{action:"tap",...s},p,!0);let f=[];for(let[y,b]of d.entries()){p?.throwIfAborted();try{if(y===0&&s!==void 0)await Yt(m,b.text,h,p);else await m.request({type:"type",text:b.text},p)}catch(T){p?.throwIfAborted();let v=u(T,"watchOS text entry failed; focus a text field with tapOn first");return e.warn(v.message,T),f.push({index:y,action:"type",success:!1,resolvedMode:"xcuiTypeText",error:v.message}),{success:!1,completedCommands:y,failedIndex:y,commands:f,error:v.message}}f.push({index:y,action:"type",success:!0,textLength:[...b.text].length,resolvedMode:"xcuiTypeText"})}return{success:!0,completedCommands:f.length,commands:f}}var Jt=new Set(["\b","\x7F","\uF728"]);function Zt(n){let a=Object.entries(n).filter(([s,c])=>c!==void 0&&(c!==!1||s==="ensureChecked")&&!["action","elementId","text","index"].includes(s));if(n.action!=="tap"||a.length||n.elementId===void 0&&n.text===void 0)throw new t("visionOS tapOn supports only action tap with elementId, exact text and optional index in a window or ornament.");if(n.index!==void 0&&(!Number.isInteger(n.index)||n.index<0))throw new t("visionOS tap index must be a non-negative integer.")}function Ue(n){if(n.enabled==="false")return 4;if(n["resource-id"])return n.clickable==="true"?0:1;return n.clickable==="true"?2:3}function er(n){if(!n["resource-id"]&&!n.text)throw new t("The matched visionOS element has no accessibility identifier or text; add an accessibility label or identifier to the control, then observe again.");if(n.enabled==="false")throw new t("The matched visionOS element is disabled; observe and select an enabled control.")}async function Ge(n,a,s){return Zt(a),BT(n,s,()=>tr(n,a,s))}async function tr(n,a,s){let c=await Bv(n,s),d=LT(await c.hierarchy(s)),p=new K().flattenViewHierarchy(d).map(({element:v})=>v),m=p.filter((v)=>(a.elementId===void 0||v["resource-id"]===a.elementId||v["view-id"]===a.elementId)&&(a.text===void 0||v.text===a.text)).sort((v,g)=>Ue(v)-Ue(g))[a.index??0];if(!m)throw new t("No visionOS element matched the selector and index; observe and use its identifier or exact text.");er(m);let f=m["resource-id"]??"",y=m.text??"",b=p.filter((v)=>(v["resource-id"]??"")===f),T=b.filter((v)=>v.enabled!=="false"&&v.class===m.class&&(v.text??"")===y);if(T.length>1){let v=T.map((g)=>`className=${g.class}, text=${JSON.stringify(g.text??"")}, bounds=${JSON.stringify(g.bounds)}`);throw new t(f?`The visionOS match was ambiguous for identifier '${f}'; candidates: ${v.join("; ")}. Pass index or a distinct text/elementId to select a distinguishable target.`:`The visionOS match was ambiguous for type ${m.class} and label ${JSON.stringify(y)}; candidates: ${v.join("; ")}. Pass index to select a distinguishable type/label or add an accessibility identifier; identical type/label matches cannot be distinguished by index.`)}return s?.throwIfAborted(),await c.request({type:"request_tap_element",identifier:f,...!f||b.length>1?{label:y,elementType:Number(m.class)}:{}},s),{success:!0,action:"tap",element:m}}async function qe(n,a,s,c={}){if(s!==void 0||c.container!==void 0||c.selectionStrategy!==void 0||c.layer!==void 0||c.display!==void 0||a.length===0)throw new t("visionOS sendKeys supports only type commands into the focused field; focus it with tapOn first.");let d=a.map((f)=>{if(f.action!=="type"||!f.text||f.operation==="replace")throw new t("visionOS sendKeys supports only non-empty append type commands; focus the field with tapOn first.");if([...f.text].some((y)=>Jt.has(y)))throw new t("visionOS sendKeys appends text only; text containing a delete key would erase existing content.");return f}),{signal:p}=c,h=await Bv(n,p),m=[];for(let[f,y]of d.entries()){p?.throwIfAborted();try{await h.request({type:"request_append_text",text:y.text},p)}catch(b){p?.throwIfAborted();let T=u(b,"visionOS text entry failed; focus a text field with tapOn first");return e.warn(T.message,b),m.push({index:f,action:"type",success:!1,error:T.message}),{success:!1,completedCommands:f,failedIndex:f,commands:m,error:T.message}}m.push({index:f,action:"type",success:!0,textLength:[...y.text].length})}return{success:!0,completedCommands:m.length,commands:m}}function ae(n){return n==="watchos"||n==="tvos"||n==="visionos"}function $e(n,a,s){switch(n.platform){case"visionos":return Ge(n.deviceId,a,s);case"tvos":return Me(n.deviceId,a,s);case"watchos":return HV(n.deviceId,a,s);default:return}}function Hee(n,a,s,c={}){return(n.platform==="watchos"?We:n.platform==="visionos"?qe:Ate)(n.deviceId,a,s,c)}var P=3;function V(n,a,s,c){let d=rt(a);if(c&&d===c.source)return!0;if(!c&&Ke(n,a))return!0;if(!s||!d)return!1;let p=c?[c]:s.filter((h)=>h.element&&Ke(n,h.element));return s.some((h)=>{if(h.source!==d||!h.element)return!1;return p.some((m)=>{for(let[f,y]of[[h,m],[m,h]]){let b=f.parentIndex;while(b!==void 0){let T=s[b];if(T===y)return!0;if(Dn(T.properties))break;b=T.parentIndex}}return!1})})}function Ke(n,a){for(let s of["resource-id","view-id","test-tag"]){let c=n[s],d=a[s];if(s==="view-id"&&c!==d&&[c,d].some((p)=>String(p).startsWith("s2-")))continue;if(typeof c==="string"&&c.length>0&&typeof d==="string"&&d.length>0)return c===d}return mn(n.bounds,a.bounds,P)&&se(n,a)}function C(n,a){let s=n.text??n["content-desc"]??n["ios-accessibility-label"]??a.text??a.textAny?.[0];return typeof s==="string"&&s.length>0?JSON.stringify(s):"the matched element"}function se(n,a,s){if(n.class!==a.class)return!1;let c=["resource-id","test-tag"].filter((m)=>{let f=n[m];return typeof f==="string"&&f.length>0});if(c.length>0)return c.every((m)=>n[m]===a[m]);let d=n.text??n["content-desc"]??n["ios-accessibility-label"],p=a.text??a["content-desc"]??a["ios-accessibility-label"],h=typeof d==="string"&&d.length>0?d:s;return typeof h==="string"&&h.length>0&&h===p}function k(n){let a=[];for(let s of n){let c=a.find((d)=>d.every((p)=>p.rootGroup!==s.rootGroup&&rr(p,s)));if(c)c.push(s);else a.push([s])}return a.map((s)=>s[0])}function rr(n,a){return Boolean(n.element&&a.element&&n.className===a.className&&mn(n.element.bounds,a.element.bounds,P)&&Ha(n.element)===Ha(a.element)&&["resource-id","test-tag","view-id","text","content-desc","ios-accessibility-label"].every((s)=>n.element[s]===a.element[s]))}function oe(n,a){let s=P;return a$(n.bounds,a.bounds,s)&&Math.abs(n.bounds.right-n.bounds.left-(a.bounds.right-a.bounds.left))<=s&&Math.abs(n.bounds.bottom-n.bounds.top-(a.bounds.bottom-a.bounds.top))<=s}function je(n,a){if(!n.length||n.length!==a.length)return;let s=a[0].element.bounds.top-n[0].element.bounds.top;return n.every((d,p)=>{let h=d.element,m=a[p].element;return h.class===m.class&&oe(h,m)&&mn({...h.bounds,top:h.bounds.top+s,bottom:h.bounds.bottom+s},m.bounds,P)})?s:void 0}function Xe(n,a){let s;for(let c of["resource-id","test-tag","view-id"]){let d=n[c];if(typeof d!=="string"||d.length===0)continue;let p=k(a.filter((h)=>h.element&&Dn(h.properties)&&h.element[c]===d));if(p.length===1)return{key:c,value:d,shared:!1};if(p.length>1)s??={key:c,value:d,shared:!0}}return s}function Ye(n){if(!n.testTag)throw new t("tapOn requires non-blank text, textAny, elementId, or testTag to interact with");return n.testTag}var Rw=Symbol("tapFocusFailure"),BF=Symbol("tapResolvedLayer");function B(n,a,s){if(!ba(n))return;n=DV(a,n,s);let c=rt(a);if(!c)return;let d=new K;for(let p of["prototype","app"])if(d.flattenViewHierarchy(wd(n,p),{includeWindows:!0}).some((m)=>rt(m.element)===c))return p;return}function D(n,a){if(a!==void 0)Object.defineProperty(n,BF,{value:a,enumerable:!1,configurable:!0,writable:!0});return n}function I(n,a,s){if(n==="focus"&&s instanceof wo)Object.defineProperty(a,Rw,{value:s.reason});return a}class Nm extends t{}function U(n){return n.length?{warnings:n}:{}}function Je(n,a){return a?[...n,a]:n}class ce{host;constructor(n){this.host=n}createErrorResult(n,a,s){return I(n,PL(n,a),s)}validateOptions(n){if(n.ensureChecked!==void 0&&n.action!=="tap")return'tapOn ensureChecked requires action "tap"';if(n.ensureChecked!==void 0&&n.selectionStrategy==="random")return"tapOn ensureChecked cannot use random selection; use a unique selector or index";if([n.text,n.elementId,n.testTag,n.textAny,n.accessibilityLink].filter(Boolean).length!==1)return"tapOn requires exactly one of text, textAny, elementId, testTag, or accessibilityLink";if(n.textAny&&n.textAny.length===0)return"tapOn textAny selector must be non-empty";let s=wL(n.container,"tapOn");if(s)return s;return this.validateSemanticLinkOptions(n)}validateSemanticLinkOptions(n){if(n.layer!==void 0&&this.hasSemanticLinkTarget(n))return"tapOn layer cannot be used with accessibilityLink or subtext";if(n.selectionStrategy==="unique"&&(n.sibling||n.accessibilityLink))return"tapOn unique selection cannot use sibling or direct accessibilityLink; select a unique owner with subtext instead";if(n.relativePosition!==void 0)return"tapOn relativePosition is no longer supported; use accessibilityLink or subtext";if(!this.hasSemanticLinkTarget(n))return null;return this.semanticLinkValidationErrors(n).find(({invalid:a})=>a)?.error??null}hasSemanticLinkTarget(n){return[n.accessibilityLink,n.subtext].some((a)=>a!==void 0)}semanticLinkValidationErrors(n){return[{invalid:[n.accessibilityLink,n.subtext].every((a)=>a!==void 0),error:"tapOn accessibilityLink and subtext cannot be used together"},{invalid:n.action!=="tap",error:"tapOn semantic link activation supports only the tap action"},{invalid:n.sibling,error:"tapOn semantic link activation cannot use sibling"},{invalid:Boolean(n.retryIfNoChange??n.ensureTap),error:"tapOn semantic link activation cannot retry an acknowledged link activation"},{invalid:n.ensureChecked!==void 0,error:"tapOn semantic link activation cannot ensure checked state"},{invalid:n.searchUntil,error:"tapOn semantic link activation cannot use searchUntil"},{invalid:this.semanticLinkTextIsBlank(n),error:"tapOn semantic link text must be non-empty"},{invalid:this.semanticLinkOccurrenceIsInvalid(n),error:"tapOn semantic link occurrence must be a non-negative integer"},{invalid:n.subtext?n.index!==void 0:!1,error:"tapOn owner-scoped semantic link activation cannot use index; use a unique owner selector"},{invalid:n.subtext?n.selectionStrategy==="random":!1,error:"tapOn owner-scoped semantic link activation cannot use random selection; use a unique owner selector"}]}semanticLinkTextIsBlank(n){return(n.subtext?.text??n.accessibilityLink)?.trim().length===0}semanticLinkOccurrenceIsInvalid(n){let a=n.subtext?.occurrence??n.index??0;return![Number.isInteger(a),a>=0].every(Boolean)}async activateSemanticLink(n,a,{owner:s,viewHierarchy:c,signal:d}){let p=(h,m)=>{if(h.dispatched&&h.acknowledged!==!0)throw m(),Tn(h.error)};if(s&&!this.host.hasUniqueSemanticLinkOwner(s,c))return{success:!1,error:"Container-scoped semantic link activation requires a unique resource-id owner identity"};if(this.host.usesAndroidLinkActivation()){let h=s?Kn(s):void 0;if(s&&!h)return{success:!1,error:"Container-scoped semantic link activation requires a stable native owner identity"};let m=await this.host.accessibilityService().requestActivateAccessibilityLink({text:n,occurrence:a,selector:h,signal:d});return p(m,()=>{E.getExistingInstance(this.host.device().deviceId)?.invalidateCache()}),{success:m.success,error:m.error}}if(this.host.usesIosLinkActivation()){let h=s?.["resource-id"];if(s&&(typeof h!=="string"||h.length===0))return{success:!1,error:"Container-scoped semantic link activation requires a stable native owner identity"};let m=await x.getInstance(this.host.device()).requestActivateAccessibilityLink({text:n,occurrence:a,ownerResourceId:h,signal:d});return p(m,()=>nW(this.host.device(),{success:!0})),nW(this.host.device(),m),{success:m.success,error:m.error,warning:m.warning}}return{success:!1,error:Rt(this.host.device().platform,"tap on elements").message}}hasUniqueSemanticLinkOwner(n,a){if(!a)return!1;let s=this.host.elementParser().flattenViewHierarchy(a,{includeWindows:!0}).map(({element:d})=>d);if(this.host.usesCapturedOwnerIdentity()){let d=n["resource-id"];return typeof d==="string"&&d.length>0&&ir(s.filter((p)=>p["resource-id"]===d)).length===1}let c=Kn(n);return c!==void 0&&s.filter((d)=>Dl(d,c)).length===1}async activateAccessibilityLinkPhase(n,a,{observeResult:s,viewHierarchy:c,activationWarnings:d,signal:p}){let h=n.index??0,m=this.host.resolveContainerElement(c,this.host.withObservationScreenSize(n,s));if(n.container&&!m)return{success:!1,error:"Semantic link container is no longer present"};let f=await this.host.activateSemanticLink(a,h,{owner:m,viewHierarchy:c,signal:p});if(!f.success)return{success:!1,error:f.error};return{success:!0,action:n.action,element:{text:a,bounds:{left:0,top:0,right:0,bottom:0}},activatedSubtext:{text:a,occurrence:h},...U(Je(d,f.warning))}}async activateSubtextPhase({options:n,subtext:a,element:s,viewHierarchy:c,selectedElement:d,searchUntil:p,activationWarnings:h,signal:m}){let f=a.occurrence??0,y=await this.host.activateSemanticLink(a.text,f,{owner:s,viewHierarchy:c,signal:m});if(!y.success)return{success:!1,error:y.error};return{success:!0,action:n.action,element:s,selectedElement:d,searchUntil:p,activatedSubtext:{text:a.text,occurrence:f},...U(Je(h,y.warning))}}}function ir(n){let a=n.filter((s)=>{let c=rt(s);return!c||!n$(c)});return a.length>0?a:n}class le{host;constructor(n){this.host=n}async prepareAndroidDisplaySelection(n,a){let{target:s,signal:c}=a,d=a.selection,p=s.observation.viewHierarchy;if(!p)throw new t("Selected display has no view hierarchy");let h=await this.host.refreshEnsureCheckedSelection(n,s.observation,d,c);d=h.selection,p=h.viewHierarchy;let m={durationMs:0,requestCount:0,changeCount:0},f=d.element&&this.host.ensureCheckedBeforeTap(n,d.element,this.host.buildSelectedElementMetadata(d),m);if(f)return{result:f};if(this.host.strategy().shouldRunPreTapStability(n)){let y=await this.host.resolveAndroidStableTapTargetAfterRefreshes(n,s.observation,n.action,{requireResourceId:!1,signal:c});if(!y.ok)return{result:{success:!1,error:y.error}};this.host.replaceObservationHierarchy(s.observation,y.viewHierarchy,!0),p=y.viewHierarchy,d={...y.selection,element:y.tapElement};let b=this.host.ensureCheckedBeforeTap(n,y.selection.element??y.tapElement,this.host.buildSelectedElementMetadata(d),m);if(b)return{result:b}}return{selection:d,hierarchy:p}}async executeOnAndroidDisplay(n,a){let{target:s,signal:c}=a,d=await this.prepareAndroidDisplaySelection(n,a);if("result"in d)return d.result;let{selection:p,hierarchy:h}=d,m=p.element;if(!m?.bounds)throw new wo("Element not found on selected display","not-found");let f=this.host.buildSelectedElementMetadata(p),y=B(h,m,re(this.host.device().platform,"tapOn"));if(n.action==="focus"){if(!Dn(m))return{success:!1,action:n.action,element:m,selectedElement:f,error:`Cannot focus ${C(m,n)} because it is not an editable input`};if(Ha(m))return D({success:!0,action:n.action,element:m,selectedElement:f,wasAlreadyFocused:!0,focusChanged:!1,focusVerified:!0,...this.host.geometry().getElementCenter(m)},y)}let b=this.host.visibleTapBounds(p,h,{screenSize:s.observation.screenSize,options:n}),T=b&&this.host.resolveVisibleTapPoint(m,h,b,{options:n,screenSize:s.observation.screenSize});if(!T)throw new wo("Matched element has no visible tap area on selected display",this.host.tapPoints().visibilityFailureReason(p,h,s.observation.screenSize));let v=n.retryIfNoChange?this.host.hashViewHierarchy(h):null,g=[...a.talkBack.warnings],S=await this.androidDisplayDispatch(n,{...a,onWarning:(O)=>g.push(O)});if(yC(),await S(T),v&&this.host.strategy().retryTapIfNoChange)await this.host.retryTapIfNoChange(v,T,n.action,{longPressDuration:this.host.strategy().longPressDurationMs,tapElement:m,options:{...this.host.withObservationScreenSize(n,s.observation),verification:{refresh:n.verification.refresh,dispatch:S}},isTalkBackEnabled:!1,screenSize:s.observation.screenSize,signal:c,selection:p});return D({success:!0,action:n.action,element:m,selectedElement:f,...U(g)},y)}async resolveAndroidDisplayTalkBack(n){let a=[],s=await this.host.strategy().isAccessibilityServiceEnabled((d)=>a.push(d)),c=s?vg(n.displayId):void 0;if(c)throw c;return{enabled:s,warnings:a}}async androidDisplayDispatch(n,a){return cB(this.host.accessibilityService(),this.host.adb(),{action:n.action==="focus"?"tap":n.action,duration:n.duration},{target:a.target,signal:a.signal,onDispatched:a.onDispatched,timer:this.host.timer(),onWarning:a.onWarning,talkBack:a.talkBack.enabled?{strategy:this.host.talkBackStrategy(),driver:this.host.talkBackDriverFactory().createDriver(this.host.device())}:void 0})}selectElementOnDisplay(n,a){if(n.action==="focus"){let s=this.host.findElementInHierarchy(n,a).selection;if(s.element)return s;let c=this.host.findElementInHierarchy({...n,action:"tap"},a).selection;return c.element&&!Dn(c.element)?c:s}return this.host.findElementInHierarchy(n,a).selection}async resolveAndroidDisplaySelection(n,a,s){if(!a.viewHierarchy)throw new t("Selected display has no view hierarchy");if(n.action==="focus"){let d=this.selectElementOnDisplay(this.host.withObservationScreenSize(n,a),a.viewHierarchy);if(d.element)return{selection:d,stats:{durationMs:0,requestCount:0,changeCount:0}}}let c=await this.host.searchForElement(n,a,s);if(this.host.replaceObservationHierarchy(a,c.viewHierarchy,c.refreshedFromDevice),!c.selection.element)try{if(c.visibilityError)throw c.visibilityError;await this.host.handleElementNotFound(n,{containerFound:c.containerFound,signal:s,selection:c.selection})}catch(d){return e.warn(`tapOn display resolution failed: ${r(d)}`,d),{result:I(n.action,{...this.host.createErrorResult(n.action,r(d)),searchUntil:c.stats},d)}}return c}async observedAndroidDisplayInteraction(n,a){let{target:s,signal:c}=a,d=await this.resolveAndroidDisplayTalkBack(s),h={...n,verification:{refresh:(v)=>EL(s,this.host.hierarchyCapture(),v,{stale:()=>this.host.staleDisplay(s.observation.display.generation??this.host.displayTransitionReader().identityRevision(this.host.device().deviceId)),signal:c})}},m=await this.resolveAndroidDisplaySelection(h,s.observation,c);if("result"in m)return m.result;let{selection:f,stats:y}=m,b,T=await this.host.observedInteraction(async()=>{let v=await this.executeOnAndroidDisplay(h,{target:s,selection:f,signal:c,talkBack:d,onDispatched:()=>{b=this.host.timer().now()}});if(b!==void 0)a.onDispatchCompleted();return v},{...jt.rawCoordinateGesture,display:s.followUpDisplay,previousObservation:s.observation,signal:c,...n.ensureChecked!==void 0?{observationHostTimestampProvider:()=>b}:{}});if(T.searchUntil=y,b===void 0)s.assertCurrent();else if(this.host.checkPostActionDisplay(T,s.assertCurrent,c),T.staleDisplay)return this.host.unverifiableDisplayPostState(T,n);if(T.success&&T.skipped!=="already-checked")await this.host.applyEnsureCheckedResult(T,h,c);return this.finalizeDisplayFocusResult(T,n,f,s.observation)}unverifiableDisplayPostState(n,a){if(!n.staleDisplay||a.action!=="focus"&&a.ensureChecked===void 0)return n;return Qt({...n,success:!1,error:void 0},new hr(new Ee(n.staleDisplay)))}finalizeDisplayFocusResult(n,a,s,c){if(a.action!=="focus"||!n.success||n.wasAlreadyFocused)return n;let d=s.matchedElement!==n.element?s.matchedElement?.text:void 0;if(n.focusVerified=this.host.verifyFocusedInputTarget(a,n.element,n.observation,{labelText:d,selectedIndex:n.selectedElement?.indexInMatches,preTapHierarchy:c.viewHierarchy}),!n.focusVerified)n.success=!1,n.error=`Failed to confirm focus on editable input ${C(n.element,a)}: the focused field could not be matched to the target`;return n}async executeOnDisplay(n,a,s){let c=n.display,d=!1;if(c!==void 0)try{let p=["subtext","accessibilityLink","focusFirst","screenReaderNavigation"].find((y)=>n[y]!==void 0);if(p)throw new t(nP(p));if(n.ensureTap)n={...n,preTapStability:!0,retryIfNoChange:!0};let m=n.ensureChecked!==void 0||n.sibling!==void 0||n.textAny!==void 0||n.searchUntil!==void 0?this.host.validateOptions(n):null;if(m)return this.host.createErrorResult(n.action,m);if(n.searchUntil!==void 0)this.host.getSearchUntilDuration(n);let f=await zi(this.host.device(),c,this.host.observeScreen(),{adb:this.host.adb(),lastRenderedObservation:this.host.lastRenderedObservation(),signal:a,transitions:this.host.displayTransitionReader()});if(this.host.routesAndroidDisplay())return await this.observedAndroidDisplayInteraction(n,{target:f,signal:a,onDispatchCompleted:()=>{d=!0}})}catch(p){this.host.rethrowObservationAbort(p,a,d),this.host.rethrowKeyboardOcclusion(p,n.action,s),e.warn(`tapOn display routing failed: ${r(p)}`,p);let h=this.host.completedDisplayFailure(p,d);return Qt(this.host.createErrorResult(n.action,r(h),h),h)}return}didCompleteDisplayGesture(n,a){return a!==void 0&&n.success&&!n.skipped&&!n.wasAlreadyFocused}completedDisplayFailure(n,a){return a&&n instanceof Ee?new hr(n):n}rethrowKeyboardOcclusion(n,a,s){if(s?.throwOnKeyboardOcclusion&&this.host.strategy().rethrowsKeyboardOcclusion&&a==="focus"&&n instanceof Nm)throw e.debug(`Tap on element awaits IME recovery: ${r(n)}`,n),n}}function nr(n,a){return n.left<=a.left&&n.top<=a.top&&n.right>=a.right&&n.bottom>=a.bottom}function de(n){return`[${n.left},${n.top}][${n.right},${n.bottom}]`}function sr(n){return{x:Math.round((n.left+n.right)/2),y:Math.round((n.top+n.bottom)/2)}}function M(n){let a=n["resource-id"]??n["content-desc"]??n.text,s=[a===void 0?void 0:`"${a}"`,n.bounds?de(n.bounds):void 0].filter((c)=>c!==void 0);return s.length?s.join(" "):"(unlabelled)"}function Qe(n){if(!n.bounds)return"Observe the screen before retrying.";let{x:a,y:s}=sr(n.bounds);return`Observe the screen; if the intended control was not activated, use tapAt {x: ${a}, y: ${s}} (the matched element's center).`}function cr(n,a){if(!n?.bounds||!a.bounds||nr(a.bounds,n.bounds))return;return`The activated element ${M(a)} does not contain the matched element ${M(n)}, so a different control may have been activated. ${Qe(n)}`}function lr(n,a){let s=n??a;return`TalkBack activation is unconfirmed: the screen did not change after activating ${!!n?.bounds&&!!a.bounds&&de(n.bounds)!==de(a.bounds)&&n?`${M(a)} for the matched element ${M(n)}`:`the matched element ${M(s)}`}. `+Qe(s)}function Ze(n,a,s){if(n==="focus")return[];let c=cr(a.matchedElement??a.element??void 0,s);return c?[c]:[]}function et(n,a){if(a&&n.effect?.screenChanged===!1)n.warnings=[...n.warnings??[],lr(a.matched,n.element)]}function pr(n,a,s){if(n.warnsOnDisabledElement&&Bd(a.enabled))s.push("The matched element is disabled; the tap may have no effect.")}class pe{host;constructor(n){this.host=n}platform(){return re(this.host.device().platform,"tapOn")}async executeWithReadScope(n,a={}){let{progress:s,signal:c,recovery:d,settlePostTapEffect:p}=a,h=dB(a.deadlineMs);if(this.host.assertLongPressWithinRequestBudget(n,h),n.display!==void 0){let T=await this.host.executeOnDisplay(n,c,d);if(T)return T}if(!n.action)return this.host.createErrorResult(n.action,"tap on action is required");let m=n.action;if(n.ensureTap)n={...n,preTapStability:!0,retryIfNoChange:!0};let f=this.host.validateOptions(n);if(f)return this.host.createErrorResult(n.action,f);let y=J();y.serial("tapOnElement");let b={options:n,requestedAction:m,effectiveAction:m,signal:c,recovery:d,request:h,perf:y,previousObserveResult:null,selectionCapture:null,completedDisplayGesture:!1,settlePostTapEffect:p};try{o(c);let T=await this.host.observedInteraction((v,g)=>this.executeObservedTap(b,v,g),{queryOptions:{text:n.text??n.textAny?.[0],elementId:n.elementId,containerElementId:n.container?.elementId},...jt.selectorResolvedGesture,display:n.display,timeoutMs:Tt.gesture,progress:s,perf:y,signal:c,deferPredictionOutcome:!0,deferPostActionScreenshot:!0,...n.ensureChecked!==void 0?{observationHostTimestampProvider:()=>b.ensureCheckedTapTimestamp}:{},predictionContext:{toolName:"tapOn",toolArgs:this.host.predictionToolArgs(n)}});return await this.finalizeResult(b,T)}catch(T){return this.failureResult(b,T)}}async finalizeResult(n,a){let{options:s,requestedAction:c,signal:d,perf:p}=n;if(n.completedDisplayGesture=this.host.didCompleteDisplayGesture(a,s.display),s.display!==void 0&&a.staleDisplay)return this.host.unverifiableDisplayPostState(a,s);let h=!1;if(a.success&&a.observation&&a.element){h=!0;let m=await this.host.deriveTapEffectAfterPostTapObservation(n.previousObserveResult,a.observation,d,{settlePostTapEffect:n.settlePostTapEffect});a.effect=m.effect,a.observation=m.observation,await this.host.applyEnsureCheckedResult(a,s,d),await this.host.captureTerminalObservationScreenshot(a.observation,p,d),await this.host.recordDeferredPredictionOutcome(a,a.observation);let f=await this.host.selectionStateTracker().finalize({action:n.effectiveAction,selectionState:n.selectionCapture,currentObservation:a.observation,previousObservation:n.previousObserveResult,element:a.element,effect:m.effect,signal:d});if(f.length>0)a.observation.selectedElements=f;this.host.enforceFreshnessConsistencyWithEffect(n.previousObserveResult,a)}if(await this.host.confirmFocusAfterTap({result:a,options:s,requestedAction:c,focusTarget:n.focusTarget,focusLabelText:n.focusLabelText,preTapHierarchy:n.preTapHierarchy,signal:d}),h&&(c!=="focus"||a.focusVerified!==!0))et(a,n.screenReaderActivation);if(Gee(a,n.xrClick),n.effectiveAction==="longPress"){let m=this.host.detectLongPressMetadata(n.previousObserveResult,a.observation);return{...a,...m,...this.longClickAdvertisement(a.element)}}return a}async failureResult(n,a){let{options:s,requestedAction:c,recovery:d,perf:p}=n;p.end(),this.host.rethrowKeyboardOcclusion(a,c,d),e.warn(`Tap on element failed: ${r(a)}`,a);let h=this.host.completedDisplayFailure(a,n.completedDisplayGesture);if(h instanceof Ee||h instanceof hr)return Qt(this.host.createErrorResult(n.effectiveAction,h.message),h);let m=Tre(a)?await sL(this.host.device(),{text:s.text,resourceId:s.elementId,container:s.container}):void 0;return this.host.readScopeFailureResult(c,n.effectiveAction,a,{searchUntilStats:n.searchUntilStats,debugContext:m})}async executeObservedTap(n,a,s){let{options:c,signal:d,perf:p}=n;if(n.previousObserveResult=a,n.preTapHierarchy=a.viewHierarchy,o(d),!a.viewHierarchy)return p.end(),{success:!1,error:"Unable to get view hierarchy, cannot tap on element"};let h={observeResult:a,viewHierarchy:a.viewHierarchy,activationWarnings:[],isAccessibilityServiceEnabled:void 0};if(await this.prepareHierarchy(n,h),c.accessibilityLink)return this.host.activateAccessibilityLinkPhase(c,c.accessibilityLink,{observeResult:a,viewHierarchy:h.viewHierarchy,activationWarnings:h.activationWarnings,signal:d});let m=await this.searchCurrentTarget(n,h),f=await this.prepareSelection(n,h,m);if("result"in f)return f.result;let y=f.target,b=await this.stabilizeTarget(n,y);if(b)return b;return this.dispatchTarget(n,y,s)}async prepareHierarchy(n,a){let{signal:s}=n,{observeResult:c}=a;if(a.isAccessibilityServiceEnabled=this.host.detectsAccessibilityBeforeSearch()?await this.host.strategy().isAccessibilityServiceEnabled((d)=>a.activationWarnings.push(d)):void 0,this.host.refreshesAccessibilityHierarchyBeforeSearch()&&a.isAccessibilityServiceEnabled){let d=await Ev(this.host.tapVerificationRefresh({screenSize:c.screenSize,signal:s}),this.host.timer(),s);n.preTapHierarchy=d,this.host.replaceObservationHierarchy(c,d,!0),a.viewHierarchy=d}}async shouldRevalidateCachedTarget(n,a,s){let{options:c}=n;return Boolean(this.host.revalidatesCachedTargets()&&!a.isAccessibilityServiceEnabled&&s.selection.element&&!Gm(a.viewHierarchy)&&s.stats.requestCount===0&&c.ensureChecked===void 0&&!this.host.strategy().shouldRunPreTapStability(c)&&(this.host.canReuseAccessibilityState()||!(a.isAccessibilityServiceEnabled??=await this.host.strategy().isAccessibilityServiceEnabled())))}async searchCurrentTarget(n,a){let{options:s,signal:c,perf:d,request:p}=n,{observeResult:h}=a,m=await d.track("findElement",()=>this.host.searchForElement(s,h,c));if(await this.shouldRevalidateCachedTarget(n,a,m)){let f=await Ev(this.host.requiresFreshExtractionForCachedTarget()?(y)=>this.host.refreshViewHierarchy(y,h.screenSize,c,!0):this.host.tapVerificationRefresh({screenSize:h.screenSize,signal:c}),this.host.timer(),c,{timeoutMs:Math.min(ji,p?.requestDeadlineMs===void 0?ji:p.requestDeadlineMs-this.host.timer().now()),context:"while revalidating a cached observation",platform:this.platform()});this.host.replaceObservationHierarchy(h,f,!0),m=await this.host.searchForElement(s,h,c)}if(n.searchUntilStats=m.stats,this.host.replaceObservationHierarchy(h,m.viewHierarchy,m.refreshedFromDevice),a.viewHierarchy=m.viewHierarchy,!m.selection.element){if(m.visibilityError)throw m.visibilityError;await this.host.handleElementNotFound(s,{observeResult:h,containerFound:m.containerFound,signal:c,selection:m.selection})}return m}async prepareSelection(n,a,s){let{options:c,signal:d,perf:p}=n,{observeResult:h,activationWarnings:m}=a,f=await this.host.refreshEnsureCheckedSelection(c,h,s.selection,d);a.viewHierarchy=f.viewHierarchy,n.preTapHierarchy=a.viewHierarchy;let y=f.selection,b=y.element,T=this.host.buildSelectedElementMetadata(y),v=this.host.ensureCheckedBeforeTap(c,b,T,s.stats);if(v)return p.end(),{result:v};if(c.subtext)return{result:await this.host.activateSubtextPhase({options:c,subtext:c.subtext,element:b,viewHierarchy:a.viewHierarchy,selectedElement:T,searchUntil:s.stats,activationWarnings:m,signal:d})};let g=c.action,S=this.host.geometry().getElementCenter(b),O=this.host.getLongPressDuration(c),R={...a,searchOutcome:s,element:b,finalSelection:y,selectedElementMetadata:T,action:g,initialTapPoint:S,longPressDuration:O,tapOptions:{...c,action:g},tapElement:b,usedParent:!1},w=this.prepareFocusTarget(n,R);if(w)return{result:w};return R.tapOptions={...c,action:R.action},{target:R}}prepareFocusTarget(n,a){let{options:s,perf:c}=n,{searchOutcome:d}=a,{initialTapPoint:p}=a;if(a.action==="focus"){if(!Dn(a.element))return c.end(),{success:!1,action:a.action,element:a.element,selectedElement:a.selectedElementMetadata,searchUntil:d.stats,error:`Cannot focus ${C(a.element,s)} because it is not an editable input`};n.focusTarget=a.element;let h=d.selection.matchedElement;if(h&&h!==a.element)n.focusLabelText=h.text;if(Ha(a.element))return e.info("Element is already focused, no action needed"),c.end(),D({success:!0,action:a.action,element:a.element,selectedElement:a.selectedElementMetadata,searchUntil:d.stats,wasAlreadyFocused:!0,focusChanged:!1,focusVerified:!0,x:p.x,y:p.y},B(a.viewHierarchy,a.element,this.platform()));a.action="tap",n.effectiveAction="tap"}return}async stabilizeTarget(n,a){let{options:s,signal:c,perf:d,requestedAction:p}=n,{observeResult:h,activationWarnings:m,searchOutcome:f}=a;a.isAccessibilityServiceEnabled??=await this.host.strategy().isAccessibilityServiceEnabled((T)=>m.push(T));let y=a.isAccessibilityServiceEnabled,b=this.host.resolveTapTargetElement(a.element,a.viewHierarchy,a.action,{requireResourceId:y,scoped:s.container!==void 0});if(a.tapElement=b.element,a.usedParent=b.usedParent,this.host.strategy().shouldRunPreTapStability(s)){let T=await this.host.resolveAndroidStableTapTargetAfterRefreshes(s,h,a.action,{requireResourceId:y,signal:c});if(!T.ok)return d.end(),{success:!1,error:T.error};if(this.host.replaceObservationHierarchy(h,T.viewHierarchy,!0),T.selection.captureId)h.observationId=T.selection.captureId;a.viewHierarchy=T.viewHierarchy,n.preTapHierarchy=a.viewHierarchy,a.tapElement=T.tapElement,a.finalSelection=T.selection,a.usedParent=T.usedParent,a.selectedElementMetadata=this.host.rebuildSelectedElementMetadataAfterStability(a.selectedElementMetadata,T.selection);let v=T.selection.element;if(!v)return d.end(),{success:!1,error:"Android tap aborted: refreshed stable target selection was empty"};if(p==="focus")n.focusTarget=v,n.focusLabelText=T.selection.matchedElement!==v?T.selection.matchedElement?.text:void 0;let g=this.host.ensureCheckedBeforeTap(s,v,a.selectedElementMetadata,f.stats);if(g)return d.end(),g}return}async dispatchTarget(n,a,s){let{options:c,requestedAction:d,signal:p,perf:h}=n,{observeResult:m}=a;pr(this.host.strategy(),a.tapElement,a.activationWarnings),this.host.logClickableParentSelection(a.usedParent),a.activationWarnings.push(...Ze(d,a.finalSelection,a.tapElement));let f=await this.host.tapPoints().prototypeTapHierarchy(a.viewHierarchy,a.tapElement,d),{tapPoint:y,warning:b}=this.host.tapPoints().planVisibleTapPoint({options:a.tapOptions,requestedAction:d,observeResult:m,viewHierarchy:f,finalSelection:a.finalSelection,tapElement:a.tapElement});if(b)a.activationWarnings.push(b);let T=a.tapElement.bounds;e.info(`[TapOnElement] Tapping (${y.x}, ${y.y}) on element: text=${JSON.stringify(a.tapElement.text??c.text)}, bounds=${JSON.stringify(T)}, clickable=${a.tapElement.clickable}, usedParent=${a.usedParent}`),n.selectionCapture=await this.host.prepareSelectionCapture(a.action,m,a.tapElement,p);let v=c.retryIfNoChange?this.host.hashViewHierarchy(a.viewHierarchy):null;if(await h.track("executeTap",()=>this.dispatchPlatform(n,a,y,s)),c.ensureChecked!==void 0)n.ensureCheckedTapTimestamp=this.host.timer().now();if(v&&this.host.strategy().retryTapIfNoChange&&a.iosBackend?.backend!=="sdk")await this.host.retryTapIfNoChange(v,y,a.action,{longPressDuration:a.longPressDuration,tapElement:a.tapElement,options:{...this.host.withObservationScreenSize(a.tapOptions,m),displayFence:s},isTalkBackEnabled:a.isAccessibilityServiceEnabled,screenSize:m.screenSize,signal:p,selection:a.finalSelection});return h.end(),D({success:!0,action:a.action,element:a.tapElement,selectedElement:a.selectedElementMetadata,...fr(a.iosBackend),searchUntil:a.searchOutcome.stats,...a.screenReaderNavigation?{screenReaderNavigation:a.screenReaderNavigation}:{},...a.activationWarnings.length?{warnings:a.activationWarnings}:{}},B(a.viewHierarchy,n.focusTarget??a.tapElement,this.platform()))}async dispatchPlatform(n,a,s,c){let{signal:d}=n,{observeResult:p}=a;yC(),await this.host.runPlatformTap({android:async()=>{a.screenReaderNavigation=await this.host.executeAndroidTap(a.action,s,a.longPressDuration,{element:a.tapElement,signal:d,options:{...a.tapOptions,displayFence:c,resolvedHierarchy:a.viewHierarchy,onResolvedElement:(h,m,f)=>{if(a.tapElement=h,a.finalSelection=m??{...a.finalSelection,element:h,matchedElement:h},f)a.viewHierarchy=f,n.preTapHierarchy=f,this.host.replaceObservationHierarchy(p,f,!0);a.selectedElementMetadata=this.host.buildSelectedElementMetadata(a.finalSelection),Object.assign(s,this.host.geometry().getElementCenter(h))},onActivationWarning:(h)=>a.activationWarnings.push(h),onTalkBackActivation:()=>{n.screenReaderActivation={matched:a.finalSelection.matchedElement}},...Kee(n)},isTalkBackEnabled:a.isAccessibilityServiceEnabled})},ios:async()=>{let h=this.host.iosSdkBridgeTapper?.()??ite(this.host.device());if(a.iosBackend=await h.tap({action:n.requestedAction==="focus"?"focus":a.action,element:a.tapElement,longPressDurationMs:a.longPressDuration,signal:d})??void 0,a.iosBackend?.backend==="sdk")return;await this.host.executeiOSTap(a.action,s,a.longPressDuration,{element:a.tapElement,isVoiceOverEnabled:a.isAccessibilityServiceEnabled,displayFence:c,signal:d})}})}async confirmFocusAfterTap({result:n,options:a,requestedAction:s,focusTarget:c,focusLabelText:d,preTapHierarchy:p,signal:h}){if(s!=="focus"||!n.success||n.wasAlreadyFocused)return;let m=c??n.element;if(n.focusVerified=await this.host.verifyFocusAfterTap(n,(f)=>this.host.verifyFocusedInputTarget(a,m,f,{labelText:d,selectedIndex:n.selectedElement?.indexInMatches,preTapHierarchy:p}),h),!n.focusVerified)n.success=!1,n.error=`Failed to confirm focus on editable input ${C(m,a)}: the focused field could not be matched to the target`}assertLongPressWithinRequestBudget(n,a){if(n.action==="longPress")J$(this.host.getLongPressDuration(n),a?.requestDeadlineMs===void 0?void 0:a.requestDeadlineMs-this.host.timer().now())}predictionToolArgs(n){return{text:n.text,textAny:n.textAny,id:n.elementId,action:n.action,duration:n.duration,container:n.container,searchUntil:n.searchUntil,selectionStrategy:n.selectionStrategy,accessibilityLink:n.accessibilityLink,subtext:n.subtext,platform:this.host.device().platform}}readScopeFailureResult(n,a,s,{searchUntilStats:c,debugContext:d}){let p=r(s);return I(n,{success:!1,action:a,error:`Failed to perform tap on element: ${p}`,element:{bounds:{left:0,top:0,right:0,bottom:0}},...c?{searchUntil:c}:{},...s instanceof t&&s.containerFailure?{containerFailure:s.containerFailure}:{},...d?{debug:{elementSearch:d}}:{}},s)}longClickAdvertisement(n){if(this.host.device().platform!=="android"||!Array.isArray(n?.actions))return{};return{longClickAdvertised:Rr(n.actions,"long_click")}}detectLongPressMetadata(n,a){return this.host.longPressMetadataDetector().detect(n,a)}}function fr(n){if(!n)return{};return n.backend==="sdk"?{backend:"sdk"}:{backend:"xctest",fallbackReason:n.fallbackReason}}function _(n){return n["resource-id"]==="com.android.documentsui:id/item_root"||n["resource-id"]==="com.google.android.documentsui:id/item_root"}async function tt(n,a,{options:s,screenSize:c,signal:d}){if(await n.isAndroidXr(d))return e.info("[TapOnElement][retryIfNoChange] XR node click; skipping ghost-tap retry"),null;let p=await jF(n.timer(),n.tapVerificationRefresh({refresh:s.verification?.refresh,screenSize:c,signal:d}),(h)=>n.hashViewHierarchy(h),{preTapHash:a,signal:d});if(p.status==="unavailable")return e.warn(`[TapOnElement][retryIfNoChange] Tap hierarchy unreadable or could not be fingerprinted (post-tap refresh budget ${vC}ms) \u2014 skipping retry`),null;if(p.status==="changed")return e.info("[TapOnElement][retryIfNoChange] Hierarchy changed after tap \u2014 tap registered"),null;return p.hierarchy}function G(n,a,s){if(n.success&&s!=="longPress")a?.onTalkBackActivation?.()}class ue{host;constructor(n){this.host=n}async executeAndroidTap(n,a,s,{element:c,signal:d,options:p,isTalkBackEnabled:h}){if(await this.host.isAndroidXr(d)){await WF(()=>this.host.accessibilityService(),{action:n,element:c,signal:d,options:p,resolveContainer:(g,S)=>this.host.finder().resolveContainerElement(g,S)});return}let{x:m,y:f}=a,{displayFence:y,resolvedHierarchy:b,onActivationWarning:T}=p??{},v=typeof h==="boolean"?h:await this.host.strategy().isAccessibilityServiceEnabled(p?.onActivationWarning);if(c["hierarchy-source"]==="uiautomator"){await this.host.executeAndroidTapWithCoordinates(n,m,f,s,c,d,!0,{displayFence:y,onActivationWarning:T});return}if(ls(p)){await this.host.executeScopedAndroidTap({action:n,x:m,y:f,durationMs:s,element:c,signal:d,talkBackEnabled:v,fence:y,onActivationWarning:p?.onActivationWarning,onTalkBackActivation:p?.onTalkBackActivation});return}if(v)return this.host.executeAndroidTapWithAccessibility(n,m,f,c,s,p,d);await this.host.executeAndroidTapWithCoordinates(n,m,f,s,c,d,!1,{displayFence:y,resolvedHierarchy:b,onActivationWarning:T});return}async executeScopedAndroidTap(n){let{action:a,x:s,y:c,durationMs:d,element:p,signal:h,talkBackEnabled:m,fence:f}=n;if(m){let y=this.host.talkBackDriverFactory().createDriver(this.host.device()),b=a==="tap"?await this.host.talkBackStrategy().executePreciseTap(s,c,y,f):await this.host.talkBackStrategy().executeCoordinateFallback({x:s,y:c},a,d,{driver:y,fenceOptions:{displayFence:f}});if(b.success){G(b,n,a),this.host.reportTalkBackActivationWarning(b,n,a);return}await this.host.executeAndroidTapWithCoordinates(a,s,c,d,p,h,!0,{displayFence:f,onActivationWarning:n.onActivationWarning}),this.host.reportTalkBackActivationWarning(b,n,a);return}await this.host.executeAndroidTapWithCoordinates(a,s,c,d,p,h,!0,{displayFence:f,onActivationWarning:n.onActivationWarning})}async executeAndroidTapWithCoordinates(...[n,a,s,c,d,p,h=!1,m={}]){if(await this.host.isAndroidXr(p))throw Fm();let f=m.displayFence;if(n==="tap"){if(!h&&_(d)&&await this.host.tryDocumentsUiRowActivation(d,p))return;await this.host.dispatchCoordinateTapOrAdbFallback(a,s,d,{signal:p,fenceOptions:{displayFence:f}})}else if(n==="longPress")await this.host.executeAndroidLongPress(a,s,c,{element:d,signal:p,skipSemanticAction:h,...m});else if(n==="doubleTap")await yg({client:_(d)?void 0:this.host.accessibilityService(),point:{x:a,y:s},timer:this.host.timer(),signal:p,assertCurrent:()=>f?.assertCurrent(),onWarning:m.onActivationWarning,tap:()=>this.host.dispatchCoordinateTapOrAdbFallback(a,s,d,{signal:p,fenceOptions:{displayFence:f}})})}async tryDocumentsUiRowActivation(n,a){o(a);let s=Kn(n);if(!Rr(n.actions,"click")||!s||s.uniqueId===void 0&&(s.collectionRow===void 0||s.collectionColumn===void 0))return!1;try{if(!await this.host.accessibilityService().supportsNodeActionSelectors(void 0,a))return!1;o(a);let c=await this.host.accessibilityService().requestNodeAction("click",s,{signal:a});return o(a),c.success}catch(c){if(c instanceof Ee)throw c;return o(a),e.warn(`[TapOnElement] DocumentsUI row activation failed: ${c}`),!1}}async dispatchCoordinateTapOrAdbFallback(n,a,s,{signal:c,fenceOptions:d={}}={}){let p=d.displayFence;if(o(c),!_(s)){p?.assertCurrent(),await jw(this.host.accessibilityService(),this.host.adb(),{x:n,y:a},{durationMs:10,options:{signal:c}});return}e.info(`[TapOnElement] Using ADB input recovery for DocumentsUI row at (${n}, ${a})`),p?.assertCurrent(),await Ec(this.host.adb(),`tap ${n} ${a}`,void 0,{signal:c})}resolveEnsureCheckedRetryTarget(n,a,s,c){let d=this.host.findElementInHierarchy(n,a).selection.element;if(!d||!dt(d.checkable))return e.warn("[TapOnElement][retryIfNoChange] Toggle not found in fresh hierarchy; skipping retry"),null;if(dt(d.checked)===n.ensureChecked)return e.info("[TapOnElement][retryIfNoChange] Toggle reached requested checked state"),null;return this.host.resolveTapTargetElement(d,a,s,{requireResourceId:c,scoped:n.container!==void 0}).element}withRetryScreenSize(n,a){return{...n,screenSizeOptions:n.screenSizeOptions??{observationScreenSize:a}}}refreshedRetrySelection(n,a,s,c){if(n.text||n.textAny?.length||n.elementId||n.testTag)return this.host.findElementInHierarchy(n,a).selection;return c??{element:s,indexInMatches:-1,totalMatches:1,strategy:"first"}}resolveRefreshedRetryTarget(n,a,s,c){let{isTalkBackEnabled:d,selection:p,previousTarget:h}=c;if(n.ensureChecked!==void 0)return this.host.resolveEnsureCheckedRetryTarget(n,a,s,d);if(p.element)return this.host.resolveTapTargetElement(p.element,a,s,{requireResourceId:d,scoped:n.container!==void 0}).element;if(n.text||n.textAny?.length||n.elementId||n.testTag)return e.warn("[TapOnElement][retryIfNoChange] Target not found in refreshed hierarchy; skipping retry"),null;return h}async retryTapIfNoChange(n,a,s,{longPressDuration:c,tapElement:d,options:p,isTalkBackEnabled:h,screenSize:m,signal:f,selection:y}){let b=await tt(this.host,n,{options:p,screenSize:m,signal:f});if(!b)return;let T=this.host.withRetryScreenSize(p,m),v=this.host.refreshedRetrySelection(T,b,d,y),g=this.host.resolveRefreshedRetryTarget(T,b,s,{isTalkBackEnabled:h,selection:v,previousTarget:d});if(!g)return;let S=this.host.getScreenSizeFromHierarchy(b,T.screenSizeOptions),O=this.host.visibleTapBounds(v.element?v:y??{...v,element:g},b,{screenSize:S,options:T,tapTarget:g});if(!O){e.warn("[TapOnElement][retryIfNoChange] Refreshed target has no visible tap area; skipping retry");return}let R=hp(a,O)?a:this.host.resolveVisibleTapPoint(g,b,O,{options:p,screenSize:S});if(!R){e.warn("[TapOnElement][retryIfNoChange] Refreshed target has no unobstructed tap point; skipping retry");return}if(e.warn(`[TapOnElement][retryIfNoChange] Hierarchy unchanged after tap at (${R.x}, ${R.y}) \u2014 ghost tap detected, retrying`),await this.host.timer().sleep(zF),p.verification?.dispatch){await p.verification.dispatch(R);return}await this.host.executeAndroidTap(s,R,c,{element:g,signal:f,options:{...p,resolvedHierarchy:b},isTalkBackEnabled:h})}isScreenReaderNavigationEnabled(n){return Boolean(n?.screenReaderNavigation)||this.host.featureFlags().isEnabled("screen-reader-navigation")}reportTalkBackActivationWarning(n,a,s="tap"){if(s==="longPress"||n.method==="accessibility-action")return;let c=n.success?n.warnings??[az]:[n.unsupportedCapability==="tap_double_v1"?"TalkBack activation is unconfirmed: the connected device service does not support the single-gesture double tap (tap_double_v1). Update CtrlProxy. The plain coordinate tap path was used instead. Observe the result before retrying.":"TalkBack activation is unconfirmed: the TalkBack gesture failed, so the plain coordinate tap path was used instead. Observe the result before retrying."];for(let d of c)a?.onActivationWarning?.(d)}talkBackTargetContext(n,a,s){let c,d,p=n&&[n.text,n.textAny,n.elementId,n.testTag].some(Boolean);return{hierarchy:lt(n?.resolvedHierarchy),reResolve:p?(h)=>{let m=this.host.finder().selectElementInHierarchy(n,Ti(h,n.layer)).selection;return c=m,d=h,m.element?this.host.resolveTapTargetElement(m.element,h,a,{requireResourceId:!0,scoped:n.container!==void 0}).element:null}:void 0,onResolvedElement:(h)=>s(h,c,d)}}async executeAndroidTapWithAccessibility(...[n,a,s,c,d,p,h]){let m=this.host.readOptionalDisplayFence(p),f=this.host.talkBackDriverFactory().createDriver(this.host.device()),y,b=this.host.talkBackTargetContext(p,n,(g,S,O)=>{c=g;let R=this.host.geometry().getElementCenter(g);a=R.x,s=R.y,p?.onResolvedElement?.(g,S,O)});if(n==="longPress"){let g=await this.host.talkBackStrategy().executeLongPress({x:a,y:s},d,c,{driver:f,fenceOptions:{displayFence:m,...b}});if(!g.success){if(g.semanticActionFailure)throw new t(`Semantic long press failed for the selected element: ${g.error??"unknown error"}`);e.warn(`[TapOnElement] Long press accessibility methods failed (${g.error}), falling back to ADB tap at (${a}, ${s})`),await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!0,{displayFence:m})}return}if(this.host.isScreenReaderNavigationEnabled(p)){let g=await this.host.talkBackStrategy().executeTap(this.host.device().deviceId,c,f,{fence:m,signal:h});if(g.success)return G(g,p,n),this.host.reportTalkBackActivationWarning(g,p,n),g.screenReaderNavigation;e.warn(`[TapOnElement] Focus navigation unavailable (${g.error}); nothing was dispatched, falling back to coordinate-based tap at (${a}, ${s})`),y=g.screenReaderNavigation}else if(n==="tap"){let g=await this.host.talkBackStrategy().executeDirectActivation(c,f,b);if(g.success){G(g,p,n);return}e.warn(`[TapOnElement] Direct accessibility activation failed (${g.error}), falling back to coordinate-based tap at (${a}, ${s})`)}if(_(c))return await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!1,{displayFence:m}),y;let T=n,v=T==="tap"?await this.host.talkBackStrategy().executePreciseTap(a,s,f,m):await this.host.talkBackStrategy().executeCoordinateFallback({x:a,y:s},T,d,{driver:f,fenceOptions:{displayFence:m}});if(!v.success)e.warn(`[TapOnElement] Accessibility coordinate tap failed (${v.error}), falling back to ADB tap at (${a}, ${s})`),await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!1,{displayFence:m});return G(v,p,n),this.host.reportTalkBackActivationWarning(v,p,n),y}async executeiOSTap(n,a,s,{element:c,isVoiceOverEnabled:d,...p}={}){let{x:h,y:m}=a;if(d&&c){await this.host.executeIOSTapWithVoiceOver(n,c,{x:h,y:m},{durationMs:s,fenceOptions:p});return}let f=()=>this.host.executeiOSTapWithCoordinates(n,h,m,{durationMs:s,fenceOptions:p});if(d)await CT(f);else await f()}async executeiOSTapWithCoordinates(n,a,s,{durationMs:c,fenceOptions:d={}}){let{displayFence:p,signal:h}=d,m=n==="longPress"?c:50,f=x.getInstance(this.host.device());if(n==="doubleTap")p?.assertCurrent(),await Gw(f,{x:a,y:s},{durationMs:m,options:{signal:h}}),x.getExistingInstance(this.host.device().deviceId)?.invalidateCache();else p?.assertCurrent(),await Kw(f,{x:a,y:s},{durationMs:m,options:{signal:h}}),x.getExistingInstance(this.host.device().deviceId)?.invalidateCache()}executeIOSTapWithVoiceOver(n,a,s,{durationMs:c,fenceOptions:d}){let{x:p,y:h}=s;return vte({device:this.host.device(),action:n,element:a,point:{x:p,y:h},durationMs:c,fenceOptions:d??{},coordinateTap:(m)=>this.host.executeiOSTapWithCoordinates(n,p,h,{durationMs:c,fenceOptions:m})})}readOptionalDisplayFence(n){return n?.displayFence}getLongPressDuration(n){if(RL(n.duration),typeof n.duration==="number"&&n.duration>0)return n.duration;return this.host.strategy().longPressDurationMs}async executeAndroidLongPress(n,a,s,{element:c,signal:d,skipSemanticAction:p=!1,...h}){let m=h.displayFence;if(o(d),!p){let f=Kn(c);if(f&&await this.host.trySemanticAndroidLongPress(c,f,d,h))return}await qF({adb:this.host.adb(),x:n,y:a,durationMs:s,signal:d,assertCurrent:m?()=>m.assertCurrent():void 0,logTag:"TapOnElement"})}throwIfLongPressInterrupted(n,a,s){FC(n,a,s)}semanticAndroidLongPressTargetError(n,a,s={}){let c=lt(s.resolvedHierarchy);return bg(n,{supportsNodeActionSelectors:()=>this.host.accessibilityService().supportsNodeActionSelectors(),getAccessibilityHierarchy:()=>c?Promise.resolve(c):this.host.accessibilityService().getAccessibilityHierarchy(void 0,{skipWaitForFresh:!0,disableAllFiltering:!0,signal:a})})}async trySemanticAndroidLongPress(n,a,s,c={}){let d=fa(a),p=await this.host.semanticAndroidLongPressTargetError(a,s,c);if(o(s),p)return e.info(`[TapOnElement] ${p}; using coordinate long press`),!1;try{let h=d?await this.host.accessibilityService().requestNodeAction("long_click",a):await this.host.accessibilityService().requestAction("long_click",a.resourceId);if(h.success)return!0;let m=await XT({advertised:Rr(n.actions,"long_click"),error:h.error,needsNodeSelector:d,selected:n,readHierarchy:()=>this.host.accessibilityService().getAccessibilityHierarchy(void 0,{skipWaitForFresh:!0,disableAllFiltering:!0,signal:s})});if(o(s),m)throw new t(`Semantic long press failed for the selected element: ${h.error??"unknown error"}`);e.warn(`[TapOnElement] Accessibility long click failed: ${h.error}`)}catch(h){if(h instanceof t)throw h;e.warn(`[TapOnElement] Accessibility long click error: ${h}`)}return!1}}var yr=3,Tr=new fe;function it(n){return typeof n==="string"&&n.trim()!==""?n.trim():void 0}function vr(n,a){let s=n.bounds;if(!s||s.right<=s.left||s.bottom<=s.top)return!1;if(!a||a.width<=0||a.height<=0)return!0;return s.right>0&&s.bottom>0&&s.left<a.width&&s.top<a.height}function Sr(n){let a=it(n.properties["hint-text"]),s=it(n.displayedLabel),c=s??a,d=s!==void 0&&a!==void 0&&a!==s?a:void 0;return{...n.elementId!==void 0?{elementId:n.elementId}:{},...c!==void 0?{label:c}:{},...d!==void 0?{sublabel:d}:{}}}function nt(n,a){if(!n)return[];let s=new Set;return Tr.project(n).filter((c)=>{if(s.has(c.source))return!1;return s.add(c.source),c.affordances.includes("input")&&!$u(c)&&vr(c,a)}).toSorted((c,d)=>c.windowRank-d.windowRank||(c.bounds?.top??0)-(d.bounds?.top??0)||(c.bounds?.left??0)-(d.bounds?.left??0)).slice(0,yr).map(Sr)}function he(n,a){return a===void 0?void 0:`${n} ${JSON.stringify(a)}`}function at(n){return`On-screen inputs: ${n.map((s)=>`{${[he("elementId",s.elementId),he("label",s.label),he("sublabel",s.sublabel)].filter((c)=>c!==void 0).join(", ")}}`).join("; ")}. Select one by its elementId or label.`}function st(n){return 2}var Er=/progress_bar|loading_indicator|progress_indicator|shimmer|content_loading/i,Or=/ProgressBar$|ProgressIndicator|ShimmerFrameLayout|ContentLoadingProgressBar/i;function ot(n,a){let s=[...a.extractRootNodes(n),...a.extractWindowRootNodes(n,"topmost-first")],c=!1;for(let d of s)if(a.traverseNode(d,(p)=>{if(c)return;let h=a.extractNodeProperties(p),m=String(h["resource-id"]??h.resourceId??""),f=String(h.class??h.className??"");if(m.length>0&&Er.test(m)){c=!0;return}if(f.length>0&&Or.test(f))c=!0}),c)break;return c}var pt=2500,ut=8,me=1e4,wr=32,Ar=1000,ct=12,kr=150;function xr(n,a,s){let c=s.viewHierarchy?n.findElementInHierarchy(a,s.viewHierarchy).selection:null;return c?.matchedElement??c?.element??null}function Cr(n,a,s){if(++n.iterations>Ar)return!1;let c=a.now()-n.startTime-n.noHierarchyTimeMs,d=n.refindAttempt>=n.minProductivePolls&&c>=n.budgetMs,p=n.best!==null&&n.consecutiveStable>0&&n.consecutiveStable<s;if(!n.firstIteration&&n.consecutiveNoHierarchy===0&&d)if(p&&n.deadlineGracePolls>0)n.deadlineGracePolls--;else return!1;return!0}function Fr(n,a,s){if(n.noHierarchyTimeMs+=a.now()-s,n.consecutiveNoHierarchy++,e.warn(`[TapOnElement] Android pre-tap refresh returned no hierarchy (consecutive: ${n.consecutiveNoHierarchy}/${ct}, refind attempt: ${n.refindAttempt})`),n.consecutiveNoHierarchy>=ct)return{ok:!1,error:`Android tap aborted: accessibility service was unreachable for ${n.consecutiveNoHierarchy} consecutive attempts (ctrl-proxy WebSocket unresponsive). The device may be under heavy load or the accessibility service may need reconnection.`};n.consecutiveStable=0,n.prevBounds=null;return}function Dr(n,a,s){if(ot(s,n.elementParser)&&a.budgetMs<me)a.budgetMs=me,a.minProductivePolls=wr,e.info(`[TapOnElement] Android pre-tap: loading/progress indicators present; extending refind budget to ${a.budgetMs}ms / ${a.minProductivePolls} polls`)}function Ir(n,a,s,{selection:c,element:d}){let{original:p,options:h,observeResult:m}=a;if(p?.["resource-id"]&&p["resource-id"]!==(c.matchedElement??d)["resource-id"])return"Stale tap target: the fresh capture matched a different native ID. Observe again before acting.";return h.elementId!==void 0&&h.elementId===p?.["view-id"]?n.staleSyntheticTarget(p,m.viewHierarchy,s):void 0}function Hr({state:n,freshHierarchy:a,selection:s,refreshed:c,stableMatchesRequired:d}){let p=c.element.bounds;if(p===void 0||p===null){n.consecutiveStable=0,n.prevBounds=null;return}if(n.prevBounds!==null&&mn(n.prevBounds,p,P))n.consecutiveStable++;else n.consecutiveStable=1;n.prevBounds=p;let h=zr(a)?.captureId;if(n.best={viewHierarchy:a,tapElement:c.element,usedParent:c.usedParent,selection:h?{...s,captureId:h}:s},n.consecutiveStable>=d)return e.info(`[TapOnElement] Android tap target stable after ${n.refindAttempt} refresh(es) (bounds matched on last ${d} consecutive re-find(s), \u03B5=${P}px)`),{ok:!0,...n.best};return}function Vr(n,a,s,c){s.consecutiveNoHierarchy=0,s.refindAttempt++,Dr(n,s,c);let d=n.findElementInHierarchy(a.options,c);if(!d.selection.element){e.warn(`[TapOnElement] Android pre-tap refresh attempt ${s.refindAttempt} did not re-find tap target`),s.consecutiveStable=0,s.prevBounds=null;return}let p=Ir(n,a,c,{selection:d.selection,element:d.selection.element});if(p)return{ok:!1,error:p};let h=n.resolveTapTargetElement(d.selection.element,c,a.action,{requireResourceId:a.requireResourceId,scoped:a.options.container!==void 0});return Hr({state:s,freshHierarchy:c,selection:d.selection,refreshed:h,stableMatchesRequired:a.stableMatchesRequired})}async function ht(n,a){let{observeResult:s,action:c,requireResourceId:d,signal:p}=a,h=n.withObservationScreenSize(a.options,s),m=st(h),f=xr(n,h,s),y={options:h,observeResult:s,action:c,requireResourceId:d,original:f,stableMatchesRequired:m},b={prevBounds:null,consecutiveStable:0,best:null,startTime:n.timer.now(),noHierarchyTimeMs:0,budgetMs:pt,minProductivePolls:ut,consecutiveNoHierarchy:0,refindAttempt:0,firstIteration:!0,iterations:0,deadlineGracePolls:m};while(!0){if(o(p),!Cr(b,n.timer,m))break;if(!b.firstIteration){let S=b.consecutiveNoHierarchy>0,O=S?N5:kr;if(await n.timer.sleep(O),S)b.noHierarchyTimeMs+=O}b.firstIteration=!1;let T=n.timer.now(),v=await n.tapVerificationRefresh({refresh:h.verification?.refresh,screenSize:s.screenSize,signal:p})(HF);if(!v){let S=Fr(b,n.timer,T);if(S)return S;continue}let g=Vr(n,y,b,v);if(g)return g}return{ok:!1,error:"Android tap aborted: could not re-find the target in the accessibility hierarchy with stable bounds after repeated refreshes (refusing tap using pre-observe coordinates). The UI may still be updating (list, keyboard, loading overlay, or animation)."}}var q=2500,j=150,mt=1000;class ye{deps;constructor(n){this.deps=n}async waitForPostTapChange(n,a,s){let c=this.deps.timer.now(),d=null,p=0,h={},m=(g)=>{let S=this.deps.deriveTapEffect(n,g);if(S?.screenChanged===!0&&S.basis!=="viewHierarchy changed")return{matched:!0};let O=this.deps.timer.now();if(S?.screenChanged===!0&&h.seenAt===void 0)h.observation=g,h.seenAt=O;if(h.seenAt===void 0)return{matched:!1};let R=this.deps.hashViewHierarchy(g.viewHierarchy??null);if(R===null||R!==d)return d=R,p=O,{matched:!1};return{matched:O-p>=mt}},f={readBackStackEachPoll:!0,timeoutMs:q,pollMs:j,signal:s,initialMinTimestampMs:hn(a.viewHierarchy),skipWaitForFresh:!0,requireFreshExtraction:!0},y=await this.deps.waitForCondition().execute(m,f),b=h.observation??a;if(y.timedOut&&!y.screenOff&&h.seenAt!==void 0){let S=Math.min(c+2*q,h.seenAt+q)-this.deps.timer.now();if(S>0)o(s),y=await this.deps.waitForCondition().execute(m,{...f,timeoutMs:S,initialMinTimestampMs:hn(this.resolveSettleTimeoutObservation(n,b,y).viewHierarchy)})}let T=this.resolveSettleTimeoutObservation(n,b,y),v=this.deps.deriveTapEffect(n,y.screenOff?b:T);if(!y.matched&&v?.screenChanged!==!0)return{effect:v,observation:a};return{effect:v,observation:{...T,gfxMetrics:T.gfxMetrics??a.gfxMetrics,perfTiming:T.perfTiming??a.perfTiming}}}async settleHierarchyOnlyChange(n,a,s){let c=null,d=0,p=await this.deps.waitForCondition().execute((y)=>{let b=this.deps.deriveTapEffect(n,y);if(this.deps.compareActiveWindow(n,y)?.screenChanged===!0||b?.basis==="screenIdentity changed")return{matched:!0};let T=this.deps.hashViewHierarchy(y.viewHierarchy??null),v=this.deps.timer.now();if(T===null)return c=null,{matched:!1};if(T!==c)return c=T,d=v,{matched:!1};return{matched:v-d>=mt}},{readBackStackEachPoll:!0,timeoutMs:q,pollMs:j,signal:s,initialMinTimestampMs:hn(a.viewHierarchy),skipWaitForFresh:!0,requireFreshExtraction:!0}),h=this.resolveSettleTimeoutObservation(n,a,p);return{effect:p.screenOff===!0?{screenChanged:!0,basis:"viewHierarchy changed"}:this.deps.deriveTapEffect(n,h),observation:{...h,gfxMetrics:h.gfxMetrics??a.gfxMetrics,perfTiming:h.perfTiming??a.perfTiming}}}resolveSettleTimeoutObservation(n,a,s){let c=s.observation,d=s.screenOff===!0;if(!s.timedOut||d)return c;let p=a.freshness?.isFresh!==!1&&this.deps.deriveTapEffect(n,a)?.screenChanged===!0,h=c.freshness?.isFresh===!1||this.deps.hashViewHierarchy(c.viewHierarchy??null)===null;return p&&h?a:c}}var Br=1500,yt=50,Nr=1500,Lr=100,Mr=12000;function _r(n,a,s){let c=n.action==="focus"&&a?nt(a.viewHierarchy,a.screenSize):[];return c.length>0?{baseError:`${s}. ${at(c)}`,reason:"not-found-inputs-listed"}:{baseError:s,reason:"not-found"}}class Te{host;constructor(n){this.host=n}getSearchUntilDuration(n){return bL(n.searchUntil?.duration,{defaultMs:Nr,minMs:Lr,maxMs:Mr})}hashViewHierarchy(n){return An(n)}deriveTapEffect(n,a){return this.host.deriveInteractionEffect(n,a)}async deriveTapEffectAfterPostTapObservation(n,a,s,c){return this.host.postTapEffect().deriveEffectAfterPostTapObservation(n,a,s,c)}enforceFreshnessConsistencyWithEffect(n,a){this.host.postTapEffect().enforceFreshnessConsistency(n,a)}replaceObservationHierarchy(n,a,s){this.host.postTapEffect().replaceObservationHierarchy(n,a,s)}logClickableParentSelection(n){if(n)e.info("[TapOnElement] Using clickable parent for non-clickable element")}async prepareSelectionCapture(n,a,s,c){return this.host.selectionStateTracker().prepare({action:n,observation:a,element:s,signal:c})}withObservationScreenSize(n,a){return{...n,screenSizeOptions:{observationScreenSize:a.screenSize,display:a.viewHierarchy}}}findElementInHierarchy(n,a){a=Ti(a,n.layer);try{return this.host.finder().selectElementInHierarchy(n,a)}catch(s){if(n.action!=="focus"||!(s instanceof t)||s instanceof wo||!ls(n)&&n.index===void 0||!this.host.finder().isContainerAvailable(a,n.container))throw s;return this.host.finder().classifyFocusSelectionFailure(n,a,s)}}verifyFocusedInputTarget(n,a,s,c={}){return this.host.focusVerifier().verify(n,a,s,c)}invisibleMatchFailure(...n){return this.host.tapPoints().invisibleMatchFailure(...n)}resolveTapPoint(...n){return this.host.tapPoints().resolveTapPoint(...n)}resolveContainerElement(...n){return this.host.finder().resolveContainerElement(...n)}visibleTapBounds(...n){return this.host.tapPoints().visibleTapBounds(...n)}resolveVisibleTapPoint(...n){return this.host.tapPoints().resolveVisibleTapPoint(...n)}async verifyFocusAfterTap(n,a,s){if(a(n.observation))return!0;let c=n.observation;if(!this.host.strategy().settlesFocusChangeAfterTap||!c)return!1;let d=this.host.timer().now()+Br;while(this.host.timer().now()<d){await this.host.timer().sleep(j),o(s);let p=await this.host.refreshViewHierarchy(d-this.host.timer().now(),c.screenSize,s,!0);if(!p)continue;let h={...c};if(this.host.replaceObservationHierarchy(h,p,!0),a(h))return n.observation=h,!0}return!1}prepareViewHierarchyForResponse(n,a){if(KF(N.isRawElementSearchEnabled(),n))return n;return this.host.strategy().prepareViewHierarchyForResponse(n,this.host.viewHierarchy(),a)??n}async refreshViewHierarchy(n,a,s,c=!1){if(o(s),n<=0)return null;let d=this.host.renderedDisplayGeneration()(this.host.device().deviceId)??this.host.displayTransitionReader().identityRevision(this.host.device().deviceId),p;try{p=(await this.host.hierarchyCapture().capture({freshness:"fresh",...c?{requireFreshExtraction:!0}:{},searchRaw:N.isRawElementSearchEnabled(),timeoutMs:n,signal:s})).hierarchy}catch(h){if(h instanceof Ee)throw h;return o(s),e.warn(`[TapOnElement] Fresh capture failed: ${r(h)}`),null}if(await this.correctXrHierarchySize(p,s),Ts(a)&&this.host.strategy().verifiesRefreshedDisplay)await this.checkRefreshedDisplay(p,a,d,s);return p}tapVerificationRefresh(n){return n.refresh??((a)=>this.host.refreshViewHierarchy(a,n.screenSize,n.signal))}async correctXrHierarchySize(n,a,s){let c=this.host.xrDisplaySize?.();if(!c||this.host.device().platform!=="android")return;await c.prime(s??{},n,a);let d=s??{screenSize:{width:0,height:0}};c.applyCached(d,n)}async checkRefreshedDisplay(n,a,s,c){let d=this.host.getScreenSizeFromHierarchy(n);if(!d||d.width===a.width&&d.height===a.height&&(this.host.device().displays?.panels.length??0)<2)return;let p=await this.refreshedDisplay(n,c),h=this.host.refreshedDisplayTransitions().checkIdentity(this.host.device().deviceId,p),m=this.host.refreshedDisplayTransitions().record(this.host.device().deviceId,{display:p,screenSize:d});if(h||m)throw this.host.staleDisplay(s)}async refreshedDisplay(n,a){let s=new gr(this.host.timer()),c=await s.panelForLogicalId(this.host.device(),this.host.adb(),n.displayId,{signal:a,identity:{panelUniqueId:n.panelUniqueId,panelFingerprint:n.panelFingerprint},allowProbe:!1}),d=await s.resolve(this.host.device(),this.host.adb(),a),p=c??this.host.device().displays?.panels.find((h)=>h.key===d.display.key);return{...d.display,key:p?.key??d.display.key,role:p?.role??d.display.role,posture:await s.posture(this.host.device(),this.host.adb(),a)}}async readFreshHierarchy(n,a,s,c=!1){o(s);let d=Math.max(0,n);if(d===0)return null;return GF({device:this.host.device(),adb:this.host.adb(),timer:this.host.timer(),androidService:this.host.accessibilityService(),viewHierarchy:this.host.viewHierarchy(),prepareForResponse:(p,h)=>this.prepareViewHierarchyForResponse(p,h),actionLabel:"tap on elements"},{timeoutMs:d,screenSize:a,signal:s,forceCapture:c})}resolveAndroidStableTapTargetAfterRefreshes(n,a,s,{requireResourceId:c,signal:d}){return ht({timer:this.host.timer(),elementParser:this.host.elementParser(),findElementInHierarchy:(p,h)=>this.host.findElementInHierarchy(p,h),resolveTapTargetElement:(p,h,m,f)=>this.host.resolveTapTargetElement(p,h,m,f),staleSyntheticTarget:(p,h,m)=>this.host.staleSyntheticTarget(p,h,m),tapVerificationRefresh:(p)=>this.host.tapVerificationRefresh(p),withObservationScreenSize:(p,h)=>this.host.withObservationScreenSize(p,h)},{options:n,observeResult:a,action:s,requireResourceId:c,signal:d})}staleSyntheticTarget(n,a,s){if(!n||n["resource-id"]||!n["view-id"]||!a)return;let c=new fe,d=n["view-id"],p=c.project(a).find((y)=>y.nodeKey===d);if(!p)return"Stale tap target: the observed reference is no longer identifiable.";let h=zr(a)?.captureId??"before-refresh",m=zr(s)?.captureId??(a===s?h:"after-refresh");return new ur().resolve({id:m,nodes:c.project(s)},{elementId:d},{action:"inspect",ref:{snapshotId:h,nodeKey:d,bounds:p.bounds,label:p.label,nativeId:p.nativeId}}).error}isPrototypeWindowPending(n,a){return n.layer==="prototype"&&a.prototypeSuspended!==!0&&!ba(a)}xrChromeSearch(n){let a=this.host.device().platform==="android"?void 0:!1;return{get enabled(){return a??!1},detect:async(s)=>{if(a===void 0&&VF(s).hiddenNodes.size>0)a=await this.host.isAndroidXr(n)}}}async refreshForChromeSearch(n,a,s){let c=await this.host.tapVerificationRefresh(n)(a);if(c)await s(c);return c}findElementForSearch(n,a,s=!1){if(this.isPrototypeWindowPending(n,a))return{selection:{element:null,indexInMatches:-1,totalMatches:0,strategy:"first"},containerFound:!1};if(!s)return this.host.findElementInHierarchy(n,a);return jee(n,a,(c,d)=>this.host.findElementInHierarchy(c,d))}async searchForElement(n,a,s){let c=a.viewHierarchy;if(!c)throw new t("Unable to get view hierarchy, cannot tap on element");await this.correctXrHierarchySize(c,s,a);let d=this.xrChromeSearch(s);await d.detect(c);let p=this.host.getSearchUntilDuration(n),h=this.host.timer().now(),m=0,f=0,y=0,b,T=this.host.hashViewHierarchy(c),v=c,g=this.host.getScreenSizeFromHierarchy(v,{observationScreenSize:a.screenSize,display:a.viewHierarchy}),S=this.findElementForSearch(this.host.withObservationScreenSize(n,a),v,d.enabled);b=S.visibilityError;let O=S.selection,R=()=>this.host.invisibleMatchFailure(O,n,v,{screenSize:g}),w=O.element,A=S.containerFound;if(!w&&O.matchedElement)b=R();if(!w||this.host.isElementTapTargetOffScreen(O,v,g,n)){if(w)b=R(),e.warn(`[TapOnElement] Element found but tap target is off-screen, will retry. bounds=${JSON.stringify(w.bounds)}, screen=${g?.width}x${g?.height}`),O={...O,element:null},w=null,y+=1;m=(await YF({timer:this.host.timer(),startTime:h,durationMs:p,intervalMs:yt,pacing:"cadence",maxRequests:Math.ceil(p/yt),discardLateResult:!1,signal:s,fetch:(F)=>this.refreshForChromeSearch({refresh:n.verification?.refresh,screenSize:g,signal:s},F,d.detect),accept:(F)=>{g=this.host.getScreenSizeFromHierarchy(F,{observationScreenSize:g,display:v}),v=F;let Z=this.host.hashViewHierarchy(F);if(Z&&Z!==T)f+=1,T=Z;let ee=this.findElementForSearch({...n,screenSizeOptions:{observationScreenSize:g,display:v}},F,d.enabled);if(b=ee.visibilityError??b,O=ee.selection,w=O.element,A=A||ee.containerFound,!w&&O.matchedElement)b=R();if(w&&this.host.isElementTapTargetOffScreen(O,F,g,n))return b=R(),e.warn(`[TapOnElement] Element found but tap target is off-screen, retrying. bounds=${JSON.stringify(w.bounds)}`),O={...O,element:null},w=null,y+=1,!1;return w!==null}})).requestCount}if(this.isPrototypeWindowPending(n,v))Ti(v,n.layer);this.reportOffScreenRejections(y,w);let Q={durationMs:Math.max(0,Math.round(this.host.timer().now()-h)),requestCount:m,changeCount:f};return{selection:O,viewHierarchy:v,containerFound:A,stats:Q,refreshedFromDevice:v!==c,...b&&!w?{visibilityError:b}:{}}}reportOffScreenRejections(n,a){if(n>0&&!a)e.warn(`[TapOnElement] Element was found ${n} time(s) but had no visible tap area. Scroll it into view before retrying.`)}buildSelectedElementMetadata(n){if(!n.element)return;let a=n.element.bounds,s=this.host.geometry().getElementCenter(n.element),c=MR(n.element)??(typeof n.element.text==="string"&&n.element.text.length>0?n.element.text:typeof n.element["content-desc"]==="string"?n.element["content-desc"]:typeof n.element["ios-accessibility-label"]==="string"?n.element["ios-accessibility-label"]:""),d=typeof n.element["resource-id"]==="string"?n.element["resource-id"]:"",p=typeof n.element["test-tag"]==="string"?n.element["test-tag"]:void 0;return{...n.matchedElement?{matchedElement:n.matchedElement}:{},...n.captureId?{captureId:n.captureId}:{},text:c,resourceId:d,...p?{testTag:p}:{},bounds:{left:a.left,top:a.top,right:a.right,bottom:a.bottom,centerX:s.x,centerY:s.y},indexInMatches:n.indexInMatches,totalMatches:n.totalMatches,selectionStrategy:n.strategy}}rebuildSelectedElementMetadataAfterStability(n,a){return this.host.buildSelectedElementMetadata(a)??n}async handleElementNotFound(n,{observeResult:a,containerFound:s=!0,signal:c,selection:d}={}){this.assertContainerFound(n,s);let p=this.containerHint(n),h=this.elementNotFoundMessage(n,p),{baseError:m,reason:f}=_r(n,a,h);if(d?.onlyKeyboardKeyMatch)throw new wo(`${h}. The only match is a soft-keyboard key, which observe does not list; use sendKeys or pressButton to drive the keyboard, or dismiss the keyboard first.`,"not-found");if(this.host.visionConfig().enabled&&a){e.info("\uD83D\uDD0D Element not found after polling, trying vision fallback...");let y=await Bm(this.host.screenshotCapturer(),a.viewHierarchy,{text:n.text??n.textAny?.join(" | "),resourceId:n.elementId,description:`Interactive element for tapping (action: ${n.action})`},{visionConfig:this.host.visionConfig(),baseError:m,signal:c,visionAnalyzer:this.host.visionAnalyzer()});throw new wo(y,f)}throw new wo(m,f)}assertContainerFound(n,a){if(n.container&&!a){let s=n.container.elementId?`elementId '${n.container.elementId}'`:`text '${n.container.text}'`;throw new t(n.container.elementId?.startsWith("s2-")?`Container element id '${n.container.elementId}' is stale; re-observe and use the id from the new observation.`:`Container element not found with provided ${s}`)}}containerHint(n){return n.container?` within container ${n.container.elementId?`elementId '${n.container.elementId}'`:`text '${n.container.text}'`}`:""}siblingNotFoundMessage(n,a){if(n.sibling&&n.text)return`No clickable sibling found next to element with text '${n.text}'${a}`;else if(n.sibling&&n.elementId)return`No clickable sibling found next to element with elementId '${n.elementId}'${a}`;return}elementNotFoundMessage(n,a){let s=this.siblingNotFoundMessage(n,a);if(s!==void 0)return s;if(n.text&&n.exactText===!0)return CV(n.text,a);else if(n.text)return`Element not found with provided text '${n.text}'${a}`;else if(n.textAny)return`Element not found with any provided text '${n.textAny.join("', '")}'${a}`;else if(n.testTag)return`Element not found with provided testTag '${n.testTag}'${a}`;else if(n.accessibilityLink)return`Element not found with provided accessibilityLink '${n.accessibilityLink}'${a}`;else return n.elementId?.startsWith("s2-")?`Element id '${n.elementId}' is stale; re-observe and use the id from the new observation.${a}`:`Element not found with provided elementId '${n.elementId}'${a}`}isClickableElement(n){return dt(n.clickable)||Rr(n.actions,"click")}isLongClickableElement(n){return dt(n["long-clickable"])||dt(n.longClickable)||Rr(n.actions,"long_click")}elementAffordances(n){let a=[];if(this.host.isClickableElement(n))a.push("tap");if(this.host.isLongClickableElement(n))a.push("long-press");let s=typeof n.class==="string"?n.class:"";if(dt(n.focusable)&&(s.includes("EditText")||typeof n["input-type"]==="string"&&n["input-type"].trim()!==""))a.push("input");if(dt(n.scrollable))a.push("scroll");if(dt(n.checkable))a.push("toggle");return a}elementIdentity(n){return n.text??n["resource-id"]??n.testTag??n["test-tag"]??n["content-desc"]??"unidentified element"}ensureCheckedBeforeTap(n,a,s,c){return this.host.ensureChecked().beforeTap(n,a,s,c)}refreshEnsureCheckedSelection(n,a,s,c){return this.host.ensureChecked().refreshSelection(n,a,s,c)}applyEnsureCheckedResult(n,a,s){return this.host.ensureChecked().applyResult(n,a,s)}resolveTapTargetElement(n,a,s,c){if(typeof c!=="boolean"&&c.scoped)return{element:n,usedParent:!1};if(!a||!this.host.strategy().promotesClickableAncestor)return{element:n,usedParent:!1};let d=new fe().project(a),p=ed(d,n),h=p?qb(p,d,{action:s==="longPress"?"long-press":"tap"}):null;if(h?.element)return{element:h.element,usedParent:!Nt(h.element.bounds,n.bounds)};return{element:n,usedParent:!1}}}var Wr={tap:"tap",doubleTap:"tap",longPress:"tap",focus:"focus-input"};class be{deps;constructor(n){this.deps=n}selectVariantOrSiblingOrMiss(n,a){try{return a()}catch(s){if(!(s instanceof t))throw s;if(!(n.verification!==void 0&&s.message==="Sibling row not found"||n.textAny!==void 0&&n.selectionStrategy==="unique"&&s.message.startsWith("Target not found")))throw s;return e.debug("[TapOnElement] Text variant or display sibling not found yet",s),{element:null,totalMatches:0,indexInMatches:-1,strategy:n.selectionStrategy??"first"}}}classifyFocusSelectionFailure(n,a,s){let c=this.selectElementInHierarchy({...n,selectionStrategy:"first",index:void 0},a).selection;if(c.totalMatches===0&&!c.matchedElement)throw new wo(s.message,"not-found");let d=c.element??c.matchedElement;if(c.totalMatches===1&&d&&Dn(d)&&this.deps.tapPoints.isElementTapTargetOffScreen(c,a,this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions),n))throw new wo(s.message,this.deps.tapPoints.isCoveredByNavigationBar(c,a,this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions))?"navigation-bar":"no-visible-tap-area");throw s}selectElementInHierarchy(n,a){let s=this.isContainerAvailable(a,n.container),c=this.selectionContext(n),{text:d,elementId:p}=n,h=(m)=>({selection:m,containerFound:s});if(d)return h(n.sibling?this.selectVariantOrSiblingOrMiss(n,()=>this.selectSiblingText(n,a,d,c)):this.selectPartialText(n,a,d,c));if(n.textAny){let m=this.selectTextAny(n,a,c);if(m)return h(m)}if(p)return h(n.sibling?this.selectVariantOrSiblingOrMiss(n,()=>this.selectSiblingElementId(n,a,p,c)):this.selectElementId(n,a,p,c));return h(this.deps.elementSelector().select(a,{testTag:Ye(n)},{container:n.container,screenSizeOptions:n.screenSizeOptions,strategy:n.selectionStrategy,intentAction:c.lookupAction,selectionIntent:c.selectionIntent,index:n.index}))}selectionContext(n){let a=n.action==="longPress"?"long-press":n.action==="focus"?"focus-input":"tap",s=n.subtext?"inspect":ls(n)?a:n.action==="focus"?"focus-input":"inspect";return{intentAction:a,lookupAction:s,selectionIntent:this.selectionIntentFor(n)}}selectSiblingText(n,a,s,c){return this.deps.elementSelector().select(a,{sibling:{text:s}},{container:n.container,screenSizeOptions:n.screenSizeOptions,fuzzyMatch:!0,caseSensitive:!1,strategy:n.selectionStrategy,intentAction:c.intentAction,selectionIntent:c.selectionIntent,index:n.index})}selectPartialText(n,a,s,c){if(!(n.exactText===!0&&n.text===s))return this.selectText(n,a,{text:s,partialMatch:!0},c);try{return this.selectText(n,a,{text:s,partialMatch:!1},c)}catch(p){if(p instanceof t&&p.message.startsWith("Target not found"))throw new wo(CV(s,n.container?" within container":""),"not-found");throw p}}selectText(n,a,{text:s,partialMatch:c},d){return this.deps.elementSelector().select(a,{text:s},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:c,caseSensitive:!1,strategy:n.selectionStrategy,intentAction:d.lookupAction,allowHintFallback:n.action==="tap"||n.action==="focus",index:n.index,selectionIntent:d.selectionIntent})}selectSiblingElementId(n,a,s,c){return this.deps.elementSelector().select(a,{sibling:{elementId:s}},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:!1,strategy:n.selectionStrategy,intentAction:c.intentAction,index:n.index})}selectElementId(n,a,s,c){return this.deps.elementSelector().select(a,{elementId:s},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:!1,strategy:n.selectionStrategy,intentAction:c.lookupAction,index:n.index})}selectTextAny(n,a,s){let c=null,d=null,p=this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions);for(let h of n.textAny??[]){let m=this.selectVariantOrSiblingOrMiss(n,()=>n.sibling?this.selectSiblingText(n,a,h,s):this.selectPartialText(n,a,h,s));if(c=m,!m.element)continue;if(this.deps.tapPoints.isElementTapTargetOffScreen(m,a,p,n)){d=m;continue}return m}if(d)return{...d,element:null};if(c&&n.selectionStrategy==="unique")throw new wo(`Target not found${n.container?" within container":""}: no textAny variant matched`,"not-found");return c}selectionIntentFor(n){return n.ensureChecked!==void 0&&n.index===void 0&&!n.elementId?"toggle":Wr[n.action]}isContainerAvailable(n,a){return SL(this.deps.elementSelector(),n,a)}resolveContainerElement(n,a){let s=a.container;if(!s)return;let c=this.deps.elementSelector();if(c.resolveContainer)return c.resolveContainer(n,s,a.selectionStrategy);let d={container:s.container,index:s.index,strategy:pW(s,a.selectionStrategy).selectionStrategy};if(s.elementId)return this.deps.elementSelector().select(n,{elementId:s.elementId},{...d,intentAction:"inspect",screenSizeOptions:a.screenSizeOptions}).element;if(s.text)return this.deps.elementSelector().select(n,{text:s.text},{...d,intentAction:"inspect",screenSizeOptions:a.screenSizeOptions,caseSensitive:!1}).element;return}}function X(n,a,s){return s?.sibling||s?.action==="focus"?a:n.matchedElement??a}var Ur=25;function Gr(n){return{elementId:n.elementId??null,label:n.displayedLabel??n.label??null,className:n.className??null,bounds:n.bounds,clickable:n.categories.clickable,actionable:n.actionable,depth:n.depth,windowRank:n.windowRank}}function qee(n,a,s){let c=od(n,a,s,"hitTest");if("error"in c)throw new t(c.error);let d=a.viewHierarchy?Td(new fe().project(a.viewHierarchy)):[],p=EO(d,c).slice(0,Ur).map(Gr),h=a.screenSize,m=s==="ios"?"points":"pixels";return{method:"hierarchy-bounds",dispatchGuaranteed:!1,point:c,screenSize:{width:h.width,height:h.height,unit:m},reference:{kind:"screen",bounds:{left:0,top:0,right:h.width,bottom:h.height},unit:m,display:a.display},firstCandidate:p[0]??null,candidates:p}}function H(n,a){if(!n||!a)return!1;let s=new js,c=Ol(n).filter((h)=>h.hierarchy).flatMap((h)=>s.extractWindowRootGroups({hierarchy:{},windows:[h]})[0]),d=n.hierarchy.node&&Ij(Ib,n.hierarchy.node);for(let[h,m]of d??[])if(m)c.push(h);let p=!1;for(let h of c)s.traverseNode(h,(m)=>{p||=m===a});return p}function qr(n){if(n?.source==="ios-sdk-safe-area"&&n.safeArea){let a=n.systemChrome?.statusBar;return{top:a==="hidden"?0:n.safeArea.top,bottom:0,visibilityKnown:a==="visible"||a==="hidden"}}return}function bt(n,a=!1){let s=n.insets?.available===!1?void 0:n.insets;if(s?.systemBars){let{systemBars:p,tappableElement:h}=s;return{top:p.visible.top,bottom:p.visible.bottom,visibilityKnown:!0,...h?{bottomConsumesTouches:h.bottom>0}:{}}}let c=qr(s);if(c)return c;let d=n.systemInsets;if(a&&d?.top===0)return;return d?{top:d.top,bottom:d.bottom,visibilityKnown:!1}:void 0}function ve(n,a,s){let c=bt(n,!0);if(!a||!c?.visibilityKnown||!n.screenHeight||n.screenHeight<=0||c.top<=s.top)return s;return Ut(s,{...s,top:Math.max(0,c.top)})}var $r="The tap point is inside the gesture navigation bar area. The thin gesture bar does not consume touches, so the tap is sent, but the system's own swipe gestures can claim it: confirm the prototype control reacted (awaitEvent for its page_changed / selected event) before relying on it.",vt="The tap point is inside the system bar area and the capture does not say whether the bars are showing, so the AutoMobile prototype control there may not receive the touch.";function Kr(n,a){if(a.y<n.top)return{kind:"refuse",bar:"status bar"};if(n.bottomConsumesTouches===void 0)return{kind:"proceed",point:a,warning:vt};return n.bottomConsumesTouches?{kind:"refuse",bar:"navigation bar"}:{kind:"proceed",point:a,warning:$r}}function gt(n){let{hierarchy:a,ownedByPrototype:s,bounds:c,point:d}=n,p=a?.screenHeight,h=a&&bt(a,n.warnIfUnknown);if(!s)return{kind:"proceed",point:d};if(!h||!p||p<=0)return{kind:"proceed",point:d,...n.warnIfUnknown?{warning:"The capture does not say whether the bars are showing or where the status bar ends, so the AutoMobile prototype control may not receive the touch."}:{}};let m=p-Math.max(0,h.bottom);if(d.y>=Math.max(0,h.top)&&d.y<m)return{kind:"proceed",point:d};if(!h.visibilityKnown)return{kind:"proceed",point:d,warning:vt};let f=Math.max(c.top,h.top),y=Math.min(c.bottom,m);if(y<=f)return Kr(h,d);return{kind:"proceed",point:{x:d.x,y:Math.floor((f+y)/2)}}}function jr({coveredBy:n,coveredByKind:a}){return a==="view"?`Target is covered by ${JSON.stringify(n)} drawn over it at its only visible tap area; scroll the target clear of it with swipeOn, then retry tapOn.`:`Target is covered by ${n}; dismiss the covering window, then retry tapOn.`}class ge{deps;prototypeAgents;constructor(n){this.deps=n;this.prototypeAgents=n.prototypeAgents??{get:()=>{return}}}async prototypeTapHierarchy(n,a,s){if(s!=="tap"||this.deps.device.platform!=="ios"||!n.packageName)return n;let c=ed(new fe().project(n),a)?.source;if(!H(n,c))return n;let d=this.prototypeAgents.get(this.deps.device.deviceId,n.packageName);if(!d)return n;try{let p=await d.request("get_prototype_status",void 0,{timeoutMs:T2}),h=p.success?P2(p.status)?.safeAreaTop:void 0;if(h===void 0)return n;return{...n,insets:{available:!0,source:"ios-sdk-safe-area",units:"points",safeArea:{top:h,left:0,right:0,bottom:0},systemChrome:{visibility:"visible",statusBar:h>0?"visible":"hidden",source:"ios-status-bar-manager"}}}}catch(p){return e.debug("Prototype tap safe-area status unavailable",p),n}}resolveTapPoint(n){return this.deps.geometry().getElementCenter(n)}getImeOccluderForTap(n,a,s){let c=this.deps.device.platform;if(c!=="android"&&c!=="ios")return;let d=new Sd().collect(DV(n,a,c),c),p=d&&OO(d,n);return p&&c==="ios"?hE(p,s):p}prototypeBarTapDecision(n,a,s,c=a.bounds){if(this.deps.device.platform!=="android"&&this.deps.device.platform!=="ios")return{kind:"proceed",point:s};let d=ed(new fe().project(n),a)?.source;return gt({hierarchy:n,ownedByPrototype:H(n,d),bounds:c,point:s,warnIfUnknown:this.deps.device.platform==="ios"})}resolveImeSafeTapPoint(n,a,{options:s,screenSize:c},d=n.bounds){let p=this.getImeOccluderForTap(n,a,c);if(!p)return this.resolveTapPoint(n);let{left:h,top:m,right:f,bottom:y}=d,b=bP([h,m,f,y],p.bounds),T={left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]};if(b&&!hp(b,T))return b;let v=n.text??n["content-desc"]??n["resource-id"],g=C(n,s),S=g!=="the matched element"?g:JSON.stringify(s.elementId??s.testTag??s.accessibilityLink??"element"),O=JSON.stringify(v)??S;throw new Nm(`Target ${O} is covered by the soft keyboard; dismiss the keyboard first.`)}isElementTapTargetOffScreen(n,a,s,c){if(!Ts(s))return!1;return!this.visibleTapBounds(n,a,{screenSize:s,options:c})}invisibleMatchError(n,a,s,c){let d=n.matchedElement??n.element;if(this.isCoveredByNavigationBar(n,s,c))return`Target ${JSON.stringify(d?.text??a.text??a.elementId??"target")} is covered by the navigation bar; scroll it into view with swipeOn, then retry tapOn.`;return`Matched element ${JSON.stringify(d?.text??a.text??a.elementId??"target")} has no visible tap area (bounds ${JSON.stringify(d?.bounds)}). Scroll it into view with swipeOn, then retry tapOn.`}visibilityFailureReason(n,a,s){return this.isCoveredByNavigationBar(n,a,s)?"navigation-bar":"no-visible-tap-area"}invisibleMatchFailure(n,a,s,{screenSize:c,fallback:d}={}){let p=this.visibilityFailureReason(n,s,c);return new wo(p==="navigation-bar"||!d?this.invisibleMatchError(n,a,s,c):d,p)}navigationTapBounds(n,a,s,c){return this.deps.strategy().clipNavigationTapBounds(n,a,s,c)}isCoveredByNavigationBar(n,a,s){let c=n.element??n.matchedElement;if(!c)return!1;let d=n.matchedElement??c,p=Ut(c.bounds,d.bounds);return!!p&&!!this.navigationTapBounds(p,a,s,[d,c]).coveredBy}visibleTapBounds(n,a,{screenSize:s,options:c,tapTarget:d}={}){let p=d??n.element;if(!p?.bounds)return null;let h=X(n,p,c),m=h.bounds,f=Wee(m)?h:p,y=xf(p.bounds,s,f.bounds);if(!y||!Ts(s)||this.deps.device.platform!=="ios")return y;let b=new fe().project(a),T=p2(b,s,a);if(T&&this.prototypeBarGuardHandlesLegacyInsets(a,ed(b,p)?.source))T.statusBarTop=0;return m2({bounds:y,matched:f,target:p,nodes:b,context:T})}prototypeBarGuardHandlesLegacyInsets(n,a){return!!n.systemInsets&&(n.screenHeight??0)>0&&H(n,a)}resolveVisibleTapPoint(n,a,s,c){let d=this.resolveImeSafeTapPoint(n,a,c),p=this.getImeOccluderForTap(n,a,c.screenSize);if(this.deps.device.platform!=="ios"){let w=hp(d,s)?d:p?this.resolveImeSafeTapPoint(n,a,c,s):this.deps.geometry().getElementCenter({bounds:s}),A=M9(a,n,s,{point:w,imeBounds:p&&{left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]},ownWindows:zee(c.options.layer),views:!0});if(!A.point)throw new wo(jr(A),"no-visible-tap-area");return A.point}let h=new fe().project(a),m=ed(h,n),f=this.barSafeIosVisibleBounds(a,m,s,d),y=f!==s,b=p?bP([f.left,f.top,f.right,f.bottom],p.bounds):null,T=this.deps.geometry().getElementCenter({bounds:f}),v=c.chromeElements??[n],g=this.navigationTapBounds(n.bounds,a,c.screenSize,v).bounds;if(!g)return null;let S=Toe(h,m,n.bounds,g)?[b,T,d]:[d,b,T],O=p&&{left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]},R=nU({nodes:h,target:m,matched:v.flatMap((w)=>{let A=ed(h,w);return A?[A]:[]}),screen:c.screenSize,visibleBounds:f,candidates:S,imeBounds:O,isValid:(w)=>w!==null&&Number.isInteger(w.x)&&Number.isInteger(w.y)&&hp(w,f)&&hp(w,n.bounds)&&(!O||!hp(w,O))&&(!Ts(c.screenSize)||!Poe({point:w,hierarchy:a,screen:c.screenSize,elements:v}))});if(this.assertBarClippedIosTapPoint(y,R.point,d),R.coveredBy)throw new wo(koe(n,R.coveredBy,R.ownerInsideScrollContainer),"no-visible-tap-area");return R.point}getScreenSizeFromHierarchy(n,a={}){return Zi(n,{...a,platform:re(this.deps.device.platform,"tapOn"),iosMultiPanel:this.deps.device.platform==="ios"&&(this.deps.device.displays?.panels.length??0)>1})}hostControls(n){return new fe().project(n).flatMap((a)=>Ej(a.nativeId)&&a.bounds?[{id:a.nativeId,bounds:a.bounds}]:[])}pointClearOfHostControls(n,a,s,c){let d=this.hostControls(n);if(d.length===0)return c;let p=Eie({controls:d,targetId:a["resource-id"],visibleBounds:s,point:c});if(p.kind==="refuse")throw new t(`Cannot tap (${c.x}, ${c.y}): the AutoMobile prototype control ${p.control} covers the whole visible target and a touch there would dismiss the prototype. Move the target away from the top-end corner (or the top-centre escape pill), then retry.`);return p.point}barSafeIosVisibleBounds(n,a,s,c){let d=ve(n,H(n,a?.source),s);if(!d)throw this.prototypeBarRefusal(c,"status bar");return d}assertBarClippedIosTapPoint(n,a,s){if(n&&!a)throw this.prototypeBarRefusal(s,"status bar")}revalidateBarAdjustedIosTapPoint({viewHierarchy:n,tapElement:a,visibleBounds:s,finalSelection:c,options:d,screenSize:p,tapPoint:h}){if(this.deps.device.platform==="ios"){let m=new fe().project(n),f=ed(m,a),y=ve(n,H(n,f?.source),s);if(y!==s){let b=y&&nU({nodes:m,target:f,matched:[ed(m,X(c,a,d))].flatMap((T)=>T?[T]:[]),screen:p,visibleBounds:y,candidates:[h],isValid:(T)=>T!==null&&hp(T,y)&&hp(T,a.bounds)});if(!b?.point||b.point.x!==h.x||b.point.y!==h.y)throw this.prototypeBarRefusal(h,"status bar")}}}prototypeBarRefusal(n,a){return new t(`Cannot tap (${n.x}, ${n.y}): the AutoMobile prototype control is under the ${a} and the touch would not reach it. Move the control inside the safe area (safeAreaPadding on the node, or an offset in the floating placement), then retry.`)}planVisibleTapPoint({options:n,requestedAction:a,observeResult:s,viewHierarchy:c,finalSelection:d,tapElement:p}){let h=this.getScreenSizeFromHierarchy(c,{observationScreenSize:s.screenSize,display:s.viewHierarchy}),m=this.visibleTapBounds(d,c,{screenSize:h,options:a==="focus"?{...n,action:"focus"}:n,tapTarget:p});if(!m)throw this.invisibleMatchFailure(d,n,c,{screenSize:h,fallback:"Matched element has no visible tap area on this screen. Scroll it into view with swipeOn, then retry tapOn."});let f=this.resolveVisibleTapPoint(p,c,m,{options:n,screenSize:h,chromeElements:[X(d,p,a==="focus"?{...n,action:"focus"}:n),p]});if(!f)throw this.invisibleMatchFailure(d,n,c,{screenSize:h,fallback:"Matched element has no unobstructed visible tap area. Dismiss the keyboard or scroll it into view, then retry tapOn."});let y=this.pointClearOfHostControls(c,p,m,f),b=this.getImeOccluderForTap(p,c,h);if(b&&y!==f&&hp(y,{left:b.bounds[0],top:b.bounds[1],right:b.bounds[2],bottom:b.bounds[3]}))throw new Nm("Target is covered by the soft keyboard and a host dismiss control; dismiss the keyboard first.");let T=this.prototypeBarTapDecision(c,p,y,m);if(T.kind==="refuse")throw this.prototypeBarRefusal(y,T.bar);let v=T.point;this.revalidateBarAdjustedIosTapPoint({viewHierarchy:c,tapElement:p,visibleBounds:m,finalSelection:d,options:n,screenSize:h,tapPoint:v});let g=this.hostControls(c).find((S)=>!Ej(p["resource-id"])&&hp(v,S.bounds));if(g)throw new t(`Cannot tap (${v.x}, ${v.y}): the AutoMobile prototype control ${g.id} covers the visible target once the system bars are avoided and a touch there would dismiss the prototype. Move the target away from the top-end corner (or the top-centre escape pill), then retry.`);return _b(c,n.layer,v,"tap"),{tapPoint:v,...T.warning?{warning:T.warning}:{}}}}import{posix as Yr}from"path";var St="Library/AutoMobile/prototype-endpoint.json";function Xr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function Et(n){let a;try{a=JSON.parse(n)}catch{throw new t("The viewer wrote an invalid endpoint file: expected JSON.")}if(!Xr(a))throw new t("The viewer wrote an invalid endpoint file: expected a plain object.");if(typeof a.port!=="number"||!Number.isInteger(a.port)||a.port<1||a.port>65535)throw new t("The viewer wrote an invalid endpoint file: port must be an integer in 1..65535.");if(typeof a.token!=="string"||a.token.length<16||a.token.length>256||/[\s\p{Cc}]/u.test(a.token))throw new t("The viewer wrote an invalid endpoint file: token must contain 16..256 characters without whitespace or control characters.");return{port:a.port,token:a.token}}class Y{records=new Map;get(n,a){let s=this.records.get(n);return a===void 0||s?.bundleId===a?s?.client:void 0}release(n,a){let s=this.get(n,a);if(s!==void 0)this.records.delete(n),s.close()}releaseDevice(n){this.release(n)}record(n,a){let s=this.records.get(n);if(this.records.set(n,a),a.client.onClosed(()=>{if(this.records.get(n)===a)this.records.delete(n)}),s!==void 0&&s.client!==a.client)s.client.close()}}var Ot=256;class W{client;events=[];listeners=new Set;buffering=!0;replayDelivered=!1;closedError;closedListeners=new Set;constructor(n){this.client=n;let a=n.onEvent((s)=>{if(this.buffering){if(this.events.length===256)this.events.shift();this.events.push(s)}else this.listeners.forEach((c)=>c(s))});n.onClosed((s)=>{this.closedError=s,a(),this.events.length=0,this.listeners.clear(),this.closedListeners.forEach((c)=>c(s)),this.closedListeners.clear()})}get handshake(){return this.client.handshake}request(n,a,s){return this.client.request(n,a,s)}onEvent(n){if(this.listeners.add(n),!this.replayDelivered){this.replayDelivered=!0;while(this.events.length>0)n(this.events.shift());this.buffering=!1}return()=>this.listeners.delete(n)}onClosed(n){if(this.closedError!==void 0)n(this.closedError);else this.closedListeners.add(n);return()=>this.closedListeners.delete(n)}attachRequestHost(n){this.client.attachRequestHost?.(n)}attachChannelHost(n){this.client.attachChannelHost?.(n)}close(){this.client.close()}}class Se{socket;lines=[];firstFrame=!0;released=!1;dataListener;closeListener;failure;framer=new dd(V9,{onLine:(n)=>{if(this.failure!==void 0||!n.trim())return;if(this.firstFrame||this.released)this.firstFrame=!1,this.dataListener?.(`${n}
3
+ `);else{if(this.lines.length===Ot)this.lines.shift();this.lines.push(n)}},onOverflow:()=>{this.failure=new t("Prototype viewer response frame exceeded the client limit; reconnect to the viewer."),this.lines.length=0,this.socket.end(),this.closeListener?.(this.failure)}});constructor(n){this.socket=n}write(n){this.socket.write(n)}end(){this.lines.length=0,this.socket.end()}onData(n){this.dataListener=n,this.socket.onData((a)=>this.framer.push(a))}onClose(n){this.closeListener=n,this.socket.onClose((a)=>{this.failure=a??new t("Prototype viewer closed the connection."),this.lines.length=0,n(this.failure)})}release(){if(this.failure!==void 0)throw this.failure;while(this.lines.length>0)this.dataListener?.(`${this.lines.shift()}
4
+ `);this.released=!0}}class xV{viewer;injected;constructor(n,a){this.viewer=n;this.injected=a}get(n){return this.viewer.get(n)??this.injected.get(n)}}var{join:Jr}=Yr,wT=new Y;class At{deps;inFlight=new Map;constructor(n){this.deps=n}attach(n,a){let s=JSON.stringify([n.deviceId,a]),c=this.inFlight.get(s);if(c!==void 0)return c;let d=this.attachViewer(n,a).finally(()=>this.inFlight.delete(s));return this.inFlight.set(s,d),d}async attachViewer(n,a){if(n.platform!=="ios"||z(n)!=="simulator")throw new t("Prototype viewers run on simulators only; choose a booted iOS simulator.");let s=this.deps.connections.get(n.deviceId,a);if(s!==void 0)return s;let c=(await this.deps.containers.dataContainer(n.deviceId,a)).trim();if(!c)throw new t("No data container for the prototype viewer; install it on this simulator and retry.");let d=await this.deps.files.readText(Jr(c,St));if(d===void 0)throw new t("no endpoint file: the viewer is not running or has exited cleanly; open it from the home screen (launchApp) and retry");let{port:p,token:h}=Et(d);this.deps.connections.releaseDevice(n.deviceId);let m;try{m=await this.deps.connect(p,h)}catch(y){throw new t("Could not attach to the prototype viewer: the token may be stale (viewer relaunched) or another host is already attached (the viewer accepts one host at a time). Open the viewer and retry.",{cause:y})}if(!m.handshake.capabilities.includes(Xp))throw m.close(),new t("The endpoint is not a prototype viewer: missing prototype_persistence_replay_v1; open the viewer and retry.");let f=m instanceof W?m:new W(m);return this.deps.connections.record(n.deviceId,{bundleId:a,client:f}),f}}function Vee(n={}){let a=n.simctl??new L,s=n.files??new Pr,c=n.connector??new BO;return new At({containers:{dataContainer:async(d,p)=>{try{return await Qo({...n.containerOwnership,deviceId:d,bundleId:p,run:(h)=>a.executeCommandArgs(h)})}catch(h){if(h instanceof lo)return e.debug("Simulator returned an empty prototype viewer data container path"),"";if(h instanceof bd)throw h;throw new t("Could not resolve the prototype viewer data container; check that it is installed on this simulator.",{cause:h})}}},files:{readText:async(d)=>{if(!s.existsSync(d))return;try{return await s.readFile(d,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&p.code==="ENOENT"){e.debug("Prototype viewer endpoint disappeared before it could be read.");return}throw new t("Could not read the prototype viewer endpoint file; check its permissions and retry.",{cause:p})}}},connect:async(d,p)=>{let h=new Se(await c.connect(d));try{let m=await A2({port:d,token:p,connector:{connect:async()=>h},timer:n.timer??i}),f=new W(m);return h.release(),f}catch(m){throw h.end(),new t("Prototype viewer authentication failed; reopen the viewer and retry.",{cause:m})}},connections:n.connections??wT})}function Pt(n,a){let s=[];for(let c=n.parentIndex;c!==void 0;c=a[c].parentIndex){let d=a[c].properties,p=d["resource-id"]||d["test-tag"];if(p&&s[0]!==p)s.unshift(p)}return s}function Qr(n,a){return n.length===a.length&&n.every((s,c)=>s===a[c])}function Zr(n,a){for(let s=n.parentIndex;s!==void 0;s=a[s].parentIndex)if(a[s].className==="WKWebView")return!0;return!1}function ei(n,a){let s=P,c=n.bounds,d=a.bounds;return d.left<=c.left+s&&d.top<=c.top+s&&d.right>=c.right-s&&d.bottom>=c.bottom-s&&(d.right-d.left>c.right-c.left+s||d.bottom-d.top>c.bottom-c.top+s)}function ti(n,a,s,c){let d=P,p=c!==void 0&&s.some((m)=>m.className==="UIKeyboard"&&m.bounds!==void 0&&m.bounds.top<c&&a.bounds.bottom<=m.bounds.top+d),h=["resource-id","view-id"].some((m)=>{let f=n[m];return f&&!(m==="view-id"&&f.startsWith("s2-"))&&f===a[m]});return p&&(a.bounds.right-a.bounds.left>n.bounds.right-n.bounds.left+d||h&&mn(n.bounds,a.bounds,d))}function ri(n,a,s,c){let d=k(a.filter((f)=>f.element&&Dn(f.properties)&&!Zr(f,a))),p=d.filter((f)=>f.className===n.class);if(p.length!==1)return;let h=p[0].element;if(!ei(n,h)&&!ti(n,h,a,s)||d.some((f)=>f.element!==h&&Ha(f.element)))return;let m=c??n.text;return typeof m==="string"&&m.length>0&&typeof h.text==="string"&&h.text.length>0&&m!==h.text?void 0:h}class Re{deps;constructor(n){this.deps=n}preTapProjections=new WeakMap;findSoleFocusedFieldByStableIdentity(n,a,s,c){let d=a.filter((m)=>m.element&&Dn(m.properties)&&Ha(m.element)),p=k(d);if(p.length!==1)return;let h=p[0].element;return h&&(this.deps.device.platform==="android"&&!h.text?this.hasEmptyTextFocusIdentity(n,h,a,{labelText:s,preTapHierarchy:c}):se(n,h,s))&&a$(n.bounds,h.bounds,P)?h:void 0}findSoleFocusedFieldAtTargetBounds(n,a,s){if(this.deps.device.platform!=="ios")return;let c=k(a.filter((p)=>p.element&&Dn(p.properties)&&Ha(p.element))),d=c.length===1?c[0].element:void 0;return d&&mn(n.bounds,d.bounds,P)&&!this.focusIdentitySignals(n,d,s).conflict?d:void 0}focusProjection=new fe;attachedFocusLabels=new WeakMap;attachedFocusLabel(n){let a=rt(n);if(!a)return;if(this.attachedFocusLabels.has(a))return this.attachedFocusLabels.get(a);let s=this.focusProjection.project({hierarchy:{node:a}}).filter((d)=>d.parentIndex===0&&!Dn(d.properties)).map((d)=>d.textSources.text).filter((d)=>typeof d==="string"&&d.trim().length>0),c=s.length?s.join(`
5
+ `):void 0;return this.attachedFocusLabels.set(a,c),c}focusIdentitySignals(n,a,s){if(!Dn(n)||n.class!==a.class||!oe(n,a)||["resource-id","test-tag","view-id"].some((d)=>[n[d],a[d]].some((p)=>p&&!(d==="view-id"&&p.startsWith("s2-")))&&n[d]!==a[d]))return{conflict:!0,matched:!1};let c=[...["hint-text","hint","placeholder","content-desc","test-tag"].map((d)=>[n[d],a[d]]),[this.attachedFocusLabel(n)??s??n.text,this.attachedFocusLabel(a)]].filter((d)=>d.every((p)=>typeof p==="string"&&p.trim().length>0));return{conflict:c.some(([d,p])=>d!==p),matched:c.some(([d,p])=>d===p)}}hasEmptyTextFocusIdentity(n,a,s,{labelText:c,preTapHierarchy:d}){let p=this.focusIdentitySignals(n,a,c);if(p.conflict)return!1;let h=k(s.filter((A)=>A.element&&Dn(A.properties)));if(h.filter((A)=>mn(A.element.bounds,a.bounds,P)).length!==1)return!1;let f=d?this.focusProjection.project(lt(d)):[],y=k(f.filter((A)=>A.element&&Dn(A.properties))),b=y.filter((A)=>A.source===rt(n)||A.className===n.class&&mn(A.element.bounds,n.bounds,P)),T=b.length===1?y.indexOf(b[0]):-1,v=h.findIndex((A)=>A.element===a);if(T>=0&&T!==v)return!1;let g=je(y,h),S=g??0,O={...n.bounds,top:n.bounds.top+S,bottom:n.bounds.bottom+S},R=mn(O,a.bounds,P),w=h.filter((A)=>A.className===n.class&&!A.element.text);return p.matched||R&&(w.length===1||T>=0&&g!==void 0)}verifyIndexedFocusTarget(n,a,s,{identifier:c,selectedIndex:d}){let p=this.focusProjection.project(s),h=this.findIndexedFocusSelection(n,s,p,{identifier:c,selectedIndex:d}),m=h&&rt(h),f=p.find((y)=>y.source===m);return Boolean(h&&Dn(h)&&f&&p.some((y)=>y.element&&Dn(y.properties)&&Ha(y.element)&&V(h,y.element,p,f))&&h[c.key]===c.value&&a.class===h.class&&a$(a.bounds,h.bounds,P))}findIndexedFocusSelection(n,a,s,{identifier:c,selectedIndex:d}){let p=c.key==="view-id"&&n.elementId===c.value&&s.filter((m)=>m.nodeKey===c.value&&!m.nativeId).length>1,h=(m)=>({windowRank:m.windowRank,area:m.bounds?ft(m.bounds):1/0,order:m.index,interactive:!0});if(p)return s.filter((m)=>m.nodeKey===c.value&&!m.nativeId&&m.element&&Dn(m.properties)).sort((m,f)=>Cf(h(m),h(f)))[n.index??d??0]?.element??null;return this.deps.findElementInHierarchy({...n,index:n.index??(n.selectionStrategy==="unique"?void 0:d)},a).selection.element}isFocusedMatchingNode(n,a,s){return Boolean(a.element&&Dn(a.properties)&&Ha(a.element)&&V(n,a.element,s))}isRefoundFocusTarget(n,a,s){let c=this.deps.findElementInHierarchy(n,s).selection.element;return Boolean(c&&Dn(c)&&Ha(c)&&V(a,c,this.focusProjection.project(s)))}verify(n,a,s,c={}){let{labelText:d,selectedIndex:p,preTapHierarchy:h}=c;if(!s?.viewHierarchy)return!1;let m=lt(s.viewHierarchy)??s.viewHierarchy,f=this.focusProjection.project(m);if(this.isFocusedInPreTapScope(a,f,d,h))return!0;try{return this.matchFocusedInputTarget(n,this.deps.withObservationScreenSize(n,s),a,{viewHierarchy:s.viewHierarchy,nodes:f,labelText:d,selectedIndex:p,preTapHierarchy:h,screenHeight:s.screenSize?.height??s.viewHierarchy.screenHeight})}catch(y){return e.debug(`[TapOnElement] focus check could not resolve the target: ${r(y)}`),!1}}isFocusedInPreTapScope(n,a,s,c){let d=rt(n);if(!c||!d)return!1;let p=this.projectPreTapHierarchy(c),h=p.find((T)=>T.source===d),m=h?Pt(h,p):[];if(m.length===0)return!1;let f=(T,v)=>Boolean(T.element&&Dn(T.properties)&&!this.focusIdentitySignals(n,T.element,s).conflict&&Qr(Pt(T,v),m));if(k(p.filter((T)=>f(T,p))).length!==1)return!1;let y=a.filter((T)=>f(T,a)),b=a.filter((T)=>T.element&&Dn(T.properties)&&Ha(T.element));return k(y).length===1&&y.every((T)=>Ha(T.element))&&b.every((T)=>y.includes(T))}projectPreTapHierarchy(n){let a=this.preTapProjections.get(n);if(a)return a;let s=this.focusProjection.project(lt(n)??n);return this.preTapProjections.set(n,s),s}matchFocusedInputTarget(n,a,s,{viewHierarchy:c,nodes:d,labelText:p,selectedIndex:h,preTapHierarchy:m,screenHeight:f}){let y=Xe(s,d);if(y?.shared)return this.verifyIndexedFocusTarget(a,s,c,{identifier:y,selectedIndex:h});let b=()=>this.deps.device.platform==="ios"&&Boolean(ri(s,d,f,p));if(y)return d.some((v)=>v.element&&Dn(v.properties)&&Ha(v.element)&&v.element[y.key]===y.value&&V(s,v.element,d))||b();if(d.find((v)=>this.isFocusedMatchingNode(s,v,d)))return!0;if(this.findSoleFocusedFieldByStableIdentity(s,d,p,m))return!0;if(this.findSoleFocusedFieldAtTargetBounds(s,d,p))return!0;if(b())return!0;if(!n.testTag&&!(n.elementId&&s["resource-id"]))return!1;return this.isRefoundFocusTarget(a,s,c)}}var kt=[50,100,200,400],ii=zt(kt),ni=kt.reduce((n,a)=>n+a,0);class we{host;constructor(n){this.host=n}beforeTap(n,a,s,c){if(n.ensureChecked===void 0)return;if(!dt(a.checkable)){let d=this.host.elementAffordances(a);throw new t(`tapOn ensureChecked requires a toggle element; ${this.host.elementIdentity(a)} has affordances: ${d.join(", ")||"none"}`)}if(dt(a.checked)!==n.ensureChecked)return;return{success:!0,action:n.action,element:a,selectedElement:s,searchUntil:c,skipped:"already-checked"}}async refreshSelection(n,a,s,c){if(n.ensureChecked===void 0)return{selection:s,viewHierarchy:a.viewHierarchy};let d=await this.host.tapVerificationRefresh({refresh:n.verification?.refresh,screenSize:a.screenSize,signal:c})(vC);if(!d)throw new t("tapOn ensureChecked: unable to refresh toggle before tapping");let p=this.host.findElementInHierarchy(this.host.withObservationScreenSize(n,a),d).selection;if(!p.element)throw new t("tapOn ensureChecked: toggle not found in fresh hierarchy");return this.host.replaceObservationHierarchy(a,d,!0),{selection:p,viewHierarchy:d}}async afterTap(n,a,s){if(n.ensureChecked===void 0)return;let c=()=>{let p=a.viewHierarchy?this.host.findElementInHierarchy(this.host.withObservationScreenSize(n,a),a.viewHierarchy).selection.element:void 0;return p?dt(p.checked):"not found"},d=c();if(d!==n.ensureChecked)d=await this.pollAfterTap(c,n.ensureChecked,a,{signal:s,refresh:n.verification?.refresh});return d===n.ensureChecked?void 0:`tapOn ensureChecked: tapped element but checked is now ${d} (expected ${n.ensureChecked})`}async applyResult(n,a,s){if(a.ensureChecked===void 0)return;let c=n.observation;if(c===void 0)return;let d=await this.afterTap(a,c,s);if(d!==void 0)n.success=!1,n.error=d}async pollAfterTap(n,a,s,c={}){let{signal:d}=c,p=this.host.timer.now()+ni,h=n();for(let m=1;this.host.timer.now()<p;m++){o(d);let f=Math.min(ii.delayForAttempt(m),p-this.host.timer.now());await this.host.timer.sleep(f);let y=p-this.host.timer.now();if(y<=0)break;let b=await this.host.tapVerificationRefresh({refresh:c.refresh,screenSize:s.screenSize,signal:d})(Math.min(vC,y));if(!b)continue;if(this.host.replaceObservationHierarchy(s,b,!0),h=n(),h===a)return h}return h}}function ai(n){let{freshness:a,viewHierarchy:s}=n,c=hn(s);if(s!==void 0&&typeof s.hierarchy==="object"&&s.hierarchy!==null&&!("error"in s.hierarchy)&&s.ctrlProxyIncomplete!==!0&&s.fresh!==!1&&c!==void 0&&a?.isFresh===!1&&a.category==="cache_age")n.freshness={...a,isFresh:!0,verified:!0,actualTimestamp:c,ageMs:0,staleDurationMs:void 0,warning:void 0,category:void 0}}class Ae{host;constructor(n){this.host=n}async deriveEffectAfterPostTapObservation(n,a,s,c){let d=this.host.deriveTapEffect(n,a);if(c?.settlePostTapEffect===!1||!this.host.settlesPostTapChange()||!n)return{effect:d,observation:a};if(d?.screenChanged!==!0)return this.host.settler().waitForPostTapChange(n,a,s);if(d.basis!=="viewHierarchy changed")return{effect:d,observation:a};return this.host.settler().settleHierarchyOnlyChange(n,a,s)}enforceFreshnessConsistency(n,a){if(!n||!a.observation||a.effect?.screenChanged!==!0)return;if(a.observation.wakefulness==="Asleep")return;if(this.host.deriveTapEffect(n,a.observation)?.screenChanged===!0)return;let c=a.observation.freshness;a.observation.freshness={...c??{isFresh:!0},verified:!1,isFresh:!1,category:"effect_inconsistent",warning:"effect.screenChanged is true, but this observation's own capture still matches the "+"pre-action screen \u2014 it predates the detected transition. Call observe again for the "+"current, post-action state."}}replaceObservationHierarchy(n,a,s){let c=this.host.getScreenSizeFromHierarchy(a,{observationScreenSize:n.screenSize,display:n.viewHierarchy});n.viewHierarchy=a;let d=hn(a);if(d!==void 0)n.updatedAt=d;if(c)n.screenSize=c;else if(n.screenSize)n.screenSize={width:0,height:0};if(this.host.applyRefreshedObservationRotation(n,a.rotation),s)ai(n)}}var si=Qc,oi=150;class $F{observeScreen;timer;constructor(n,a=i){this.observeScreen=n;this.timer=a}async execute(n,a={}){let s=a.timeoutMs??si,c=a.pollMs??oi,d={matched:!1,candidates:[]},p=await KT(this.observeScreen,this.timer,{timeoutMs:s,pollMs:c,signal:a.signal,initialMinTimestampMs:a.initialMinTimestampMs,skipWaitForFresh:a.skipWaitForFresh,requireFreshExtraction:a.requireFreshExtraction,readBackStackEachPoll:a.readBackStackEachPoll},(h)=>(d=n(h),d.matched));if(p.stopped)return{matched:!0,matchedElement:d.matchedElement,candidates:[],observation:p.observation,polls:p.polls,waitMs:p.waitMs,timedOut:!1};return{matched:!1,matchedElement:void 0,candidates:d.candidates??[],...d.diagnostic?{diagnostic:d.diagnostic}:{},observation:p.observation,polls:p.polls,waitMs:p.waitMs,timedOut:!0,screenOff:p.terminalReason==="screen_off"?!0:void 0}}}class Pe{elementParser;constructor(n){this.elementParser=n}detect(n,a){let s=n?.viewHierarchy,c=a?.viewHierarchy,d=this.detectContextMenuOpened(s,c),p=this.detectSelectionStarted(c),h=this.detectNewWindow(s,c);return{pressRecognized:d||p||h,contextMenuOpened:d,selectionStarted:p}}detectContextMenuOpened(n,a){if(!a)return!1;let s=this.getRootSignatures(n),c=this.elementParser.extractRootNodes(a);for(let d of c){let p=this.getRootSignature(d);if(s.has(p))continue;if(this.containsMenuIndicators(d))return!0}return!1}detectNewWindow(n,a){if(!a)return!1;let s=this.getRootSignatures(n),c=this.elementParser.extractRootNodes(a);if(c.length===0)return!1;return c.some((d)=>!s.has(this.getRootSignature(d)))}detectSelectionStarted(n){if(!n)return!1;let a=this.elementParser.extractRootNodes(n),s=!1,c=[["textSelectionStart","textSelectionEnd"],["selectionStart","selectionEnd"]];for(let d of a)if(this.elementParser.traverseNode(d,(p)=>{if(s)return;let h=this.elementParser.extractNodeProperties(p);for(let[m,f]of c){let y=h?.[m]??h?.[m.toLowerCase()],b=h?.[f]??h?.[f.toLowerCase()];if(!this.isActiveSelectionRange(y,b))continue;s=!0;return}}),s)break;return s}isActiveSelectionRange(n,a){if(n===void 0||a===void 0)return!1;let s=typeof n==="string"?parseInt(n,10):Number(n),c=typeof a==="string"?parseInt(a,10):Number(a);return!Number.isNaN(s)&&!Number.isNaN(c)&&c>s}getRootSignatures(n){if(!n)return new Set;let a=this.elementParser.extractRootNodes(n);return new Set(a.map((s)=>this.getRootSignature(s)))}getRootSignature(n){let a=this.elementParser.extractNodeProperties(n),s=mr(a),c=a.class??a.className??"",d=wt(qt(n)),p=d?`${d.left},${d.top},${d.right},${d.bottom}`:"",h=OR(a,["text","content-desc"]);return`${s}|${c}|${p}|${h}`}containsMenuIndicators(n){let a=!1;return this.elementParser.traverseNode(n,(s)=>{if(a)return;let c=this.elementParser.extractNodeProperties(s),d=mr(c).toLowerCase(),p=(c.class??c.className??"").toLowerCase(),h=OR(c,["text","content-desc"]).toLowerCase();if(this.hasMenuIndicator(d,p,h))a=!0}),a}hasMenuIndicator(n,a,s){return n.includes("menu")||n.includes("popup")||a.includes("menu")||a.includes("popup")||s.includes("menu")||s.includes("popup")}}class ke{device;adb;accessibilityDetector;featureFlags;longPressDurationMs=500;retryTapIfNoChange=!0;warnsOnDisabledElement=!0;settlesPostTapChange=!0;verifiesRefreshedDisplay=!0;promotesClickableAncestor=!0;settlesFocusChangeAfterTap=!1;rethrowsKeyboardOcclusion=!0;applyRefreshedObservationRotation(){}constructor(n,a,s=li,c){this.device=n;this.adb=a;this.accessibilityDetector=s;this.featureFlags=c}prepareViewHierarchyForResponse(n,a,s){let c=a.filterViewHierarchy(n);return va(c,n),c}clipNavigationTapBounds(n,a,s,c){return{bounds:n}}async isAccessibilityServiceEnabled(n){let{talkBack:a,unconfirmed:s}=await rg(this.accessibilityDetector,this.device.deviceId,this.adb,this.featureFlags);if(s)n?.(Na);return a===!0}shouldRunPreTapStability(n){return Boolean(n.preTapStability)}}class xe{device;iosVoiceOverDetector;featureFlags;longPressDurationMs=1000;retryTapIfNoChange=!1;warnsOnDisabledElement=!1;settlesPostTapChange=!1;verifiesRefreshedDisplay=!1;promotesClickableAncestor=!1;settlesFocusChangeAfterTap=!0;rethrowsKeyboardOcclusion=!1;applyRefreshedObservationRotation(n,a){n.rotation=Tc(a,n.screenSize)}constructor(n,a=ko,s){this.device=n;this.iosVoiceOverDetector=a;this.featureFlags=s}prepareViewHierarchyForResponse(n,a,s){if(!s?.width||!s?.height)return null;let c=a.filterOffscreenNodes(n,s.width,s.height);return va(c,n),c}clipNavigationTapBounds(n,a,s,c){if(!Ts(s))return{bounds:n};return xO({bounds:n,hierarchy:a,screen:s,elements:c,regions:["navigation bar"],forTapTarget:!0})}async isAccessibilityServiceEnabled(){let n=x.getInstance(this.device);return this.iosVoiceOverDetector.isVoiceOverActiveOrUnknown(this.device.deviceId,n,{featureFlags:this.featureFlags})}shouldRunPreTapStability(n){return!1}}function xt(n,a,s,{iosVoiceOverDetector:c,featureFlags:d}){if(n.platform==="ios")return new xe(n,c,d);return new ke(n,a,s,d)}function Ct(n,a){let{device:s,adbFactory:c,adb:d,timer:p,accessibilityDetector:h}=a,m=n.talkBackDriverFactory??new eg(c),f=n.talkBackStrategy??new Wv({timer:p,driverFactory:m}),y=n.iosVoiceOverDetector??ko,b=n.featureFlags??ar.getInstance(),T=n.tapStrategy??xt(s,d,h,{iosVoiceOverDetector:y,featureFlags:b});return{talkBackDriverFactory:m,talkBackStrategy:f,iosVoiceOverDetector:y,featureFlags:b,strategy:T}}var ci={android:{tapDispatch:"android",androidLinkActivation:!0,iosLinkActivation:!1,capturedOwnerIdentity:!1,routesAndroidDisplay:!0,detectsAccessibilityBeforeSearch:!0,refreshesAccessibilityHierarchyBeforeSearch:!0,revalidatesCachedTargets:!0,canReuseAccessibilityState:!0,requiresFreshExtractionForCachedTarget:!1,panelAwareSelection:!1},ios:{tapDispatch:"ios",androidLinkActivation:!1,iosLinkActivation:!0,capturedOwnerIdentity:!0,routesAndroidDisplay:!1,detectsAccessibilityBeforeSearch:!1,refreshesAccessibilityHierarchyBeforeSearch:!1,revalidatesCachedTargets:!0,canReuseAccessibilityState:!1,requiresFreshExtractionForCachedTarget:!0,panelAwareSelection:!0}},di={tapDispatch:void 0,androidLinkActivation:!1,iosLinkActivation:!1,capturedOwnerIdentity:!1,routesAndroidDisplay:!1,detectsAccessibilityBeforeSearch:!1,refreshesAccessibilityHierarchyBeforeSearch:!1,revalidatesCachedTargets:!1,canReuseAccessibilityState:!0,requiresFreshExtractionForCachedTarget:!1,panelAwareSelection:!1};function Ft(n){return dr(n)?ci[n]:di}class bc extends Oe{semanticLinks=new ce({usesAndroidLinkActivation:()=>this.platformTraits.androidLinkActivation,usesIosLinkActivation:()=>this.platformTraits.iosLinkActivation,usesCapturedOwnerIdentity:()=>this.platformTraits.capturedOwnerIdentity,accessibilityService:()=>this.accessibilityService,activateSemanticLink:(...n)=>this.activateSemanticLink(...n),device:()=>this.device,elementParser:()=>this.elementParser,hasUniqueSemanticLinkOwner:(...n)=>this.hasUniqueSemanticLinkOwner(...n),resolveContainerElement:(...n)=>this.resolveContainerElement(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});targets=new Te({xrDisplaySize:()=>this.xrDisplaySize??this.observeScreen.xrDisplaySize,accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),deriveInteractionEffect:(...n)=>this.deriveInteractionEffect(...n),device:()=>this.device,displayTransitionReader:()=>this.displayTransitionReader,elementParser:()=>this.elementParser,ensureChecked:()=>this.ensureChecked,findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),finder:()=>this.finder,focusVerifier:()=>this.focusVerifier,geometry:()=>this.geometry,getScreenSizeFromHierarchy:(...n)=>this.getScreenSizeFromHierarchy(...n),getSearchUntilDuration:(...n)=>this.getSearchUntilDuration(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),hierarchyCapture:()=>this.hierarchyCapture,invisibleMatchFailure:(...n)=>this.invisibleMatchFailure(...n),isAndroidXr:(n)=>da({device:this.device,adb:this.adb,signal:n},this.xrDetector),isClickableElement:(...n)=>this.isClickableElement(...n),isElementTapTargetOffScreen:(...n)=>this.isElementTapTargetOffScreen(...n),isLongClickableElement:(...n)=>this.isLongClickableElement(...n),postTapEffect:()=>this.postTapEffect,refreshViewHierarchy:(...n)=>this.refreshViewHierarchy(...n),refreshedDisplayTransitions:()=>this.refreshedDisplayTransitions,renderedDisplayGeneration:()=>this.renderedDisplayGeneration,replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),screenshotCapturer:()=>this.screenshotCapturer,selectionStateTracker:()=>this.selectionStateTracker,staleDisplay:(...n)=>this.staleDisplay(...n),staleSyntheticTarget:(...n)=>this.staleSyntheticTarget(...n),strategy:()=>this.strategy,tapPoints:()=>this.tapPoints,tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,viewHierarchy:()=>this.viewHierarchy,visionAnalyzer:()=>this.visionAnalyzer,visionConfig:()=>this.visionConfig,withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});displayRouter=new le({routesAndroidDisplay:()=>this.platformTraits.routesAndroidDisplay,accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,applyEnsureCheckedResult:(...n)=>this.applyEnsureCheckedResult(...n),buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),checkPostActionDisplay:(...n)=>this.checkPostActionDisplay(...n),completedDisplayFailure:(...n)=>this.completedDisplayFailure(...n),createErrorResult:(...n)=>this.createErrorResult(...n),device:()=>this.device,displayTransitionReader:()=>this.displayTransitionReader,ensureCheckedBeforeTap:(...n)=>this.ensureCheckedBeforeTap(...n),findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),geometry:()=>this.geometry,getSearchUntilDuration:(...n)=>this.getSearchUntilDuration(...n),handleElementNotFound:(...n)=>this.handleElementNotFound(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),hierarchyCapture:()=>this.hierarchyCapture,lastRenderedObservation:()=>this.lastRenderedObservation,observeScreen:()=>this.observeScreen,observedInteraction:(...n)=>this.observedInteraction(...n),refreshEnsureCheckedSelection:(...n)=>this.refreshEnsureCheckedSelection(...n),replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveAndroidStableTapTargetAfterRefreshes:(...n)=>this.resolveAndroidStableTapTargetAfterRefreshes(...n),resolveVisibleTapPoint:(...n)=>this.resolveVisibleTapPoint(...n),rethrowKeyboardOcclusion:(...n)=>this.rethrowKeyboardOcclusion(...n),rethrowObservationAbort:(...n)=>this.rethrowObservationAbort(...n),retryTapIfNoChange:(...n)=>this.retryTapIfNoChange(...n),searchForElement:(...n)=>this.searchForElement(...n),staleDisplay:(...n)=>this.staleDisplay(...n),strategy:()=>this.strategy,talkBackDriverFactory:()=>this.talkBackDriverFactory,talkBackStrategy:()=>this.talkBackStrategy,tapPoints:()=>this.tapPoints,timer:()=>this.timer,unverifiableDisplayPostState:(...n)=>this.unverifiableDisplayPostState(...n),validateOptions:(...n)=>this.validateOptions(...n),verifyFocusedInputTarget:(...n)=>this.verifyFocusedInputTarget(...n),visibleTapBounds:(...n)=>this.visibleTapBounds(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});execution=new pe({runPlatformTap:async(n)=>{let a=this.platformTraits.tapDispatch;if(a===void 0)throw Rt(this.device.platform,"tap on elements");return n[a]()},detectsAccessibilityBeforeSearch:()=>this.platformTraits.detectsAccessibilityBeforeSearch,refreshesAccessibilityHierarchyBeforeSearch:()=>this.platformTraits.refreshesAccessibilityHierarchyBeforeSearch,revalidatesCachedTargets:()=>this.platformTraits.revalidatesCachedTargets,canReuseAccessibilityState:()=>this.platformTraits.canReuseAccessibilityState,requiresFreshExtractionForCachedTarget:()=>this.platformTraits.requiresFreshExtractionForCachedTarget,activateAccessibilityLinkPhase:(...n)=>this.activateAccessibilityLinkPhase(...n),activateSubtextPhase:(...n)=>this.activateSubtextPhase(...n),applyEnsureCheckedResult:(...n)=>this.applyEnsureCheckedResult(...n),assertLongPressWithinRequestBudget:(...n)=>this.assertLongPressWithinRequestBudget(...n),buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),captureTerminalObservationScreenshot:(...n)=>this.captureTerminalObservationScreenshot(...n),completedDisplayFailure:(...n)=>this.completedDisplayFailure(...n),confirmFocusAfterTap:(...n)=>this.confirmFocusAfterTap(...n),createErrorResult:(...n)=>this.createErrorResult(...n),deriveTapEffectAfterPostTapObservation:(...n)=>this.deriveTapEffectAfterPostTapObservation(...n),detectLongPressMetadata:(...n)=>this.detectLongPressMetadata(...n),device:()=>this.device,didCompleteDisplayGesture:(...n)=>this.didCompleteDisplayGesture(...n),enforceFreshnessConsistencyWithEffect:(...n)=>this.enforceFreshnessConsistencyWithEffect(...n),ensureCheckedBeforeTap:(...n)=>this.ensureCheckedBeforeTap(...n),executeAndroidTap:(...n)=>this.executeAndroidTap(...n),executeOnDisplay:(...n)=>this.executeOnDisplay(...n),executeiOSTap:(...n)=>this.executeiOSTap(...n),geometry:()=>this.geometry,getLongPressDuration:(...n)=>this.getLongPressDuration(...n),handleElementNotFound:(...n)=>this.handleElementNotFound(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),logClickableParentSelection:(...n)=>this.logClickableParentSelection(...n),longPressMetadataDetector:()=>this.longPressMetadataDetector,observedInteraction:(...n)=>this.observedInteraction(...n),predictionToolArgs:(...n)=>this.predictionToolArgs(...n),prepareSelectionCapture:(...n)=>this.prepareSelectionCapture(...n),readScopeFailureResult:(...n)=>this.readScopeFailureResult(...n),rebuildSelectedElementMetadataAfterStability:(...n)=>this.rebuildSelectedElementMetadataAfterStability(...n),recordDeferredPredictionOutcome:(...n)=>this.recordDeferredPredictionOutcome(...n),refreshEnsureCheckedSelection:(...n)=>this.refreshEnsureCheckedSelection(...n),refreshViewHierarchy:(...n)=>this.refreshViewHierarchy(...n),replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveAndroidStableTapTargetAfterRefreshes:(...n)=>this.resolveAndroidStableTapTargetAfterRefreshes(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),rethrowKeyboardOcclusion:(...n)=>this.rethrowKeyboardOcclusion(...n),retryTapIfNoChange:(...n)=>this.retryTapIfNoChange(...n),searchForElement:(...n)=>this.searchForElement(...n),selectionStateTracker:()=>this.selectionStateTracker,strategy:()=>this.strategy,tapPoints:()=>this.tapPoints,tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,unverifiableDisplayPostState:(...n)=>this.unverifiableDisplayPostState(...n),validateOptions:(...n)=>this.validateOptions(...n),verifyFocusAfterTap:(...n)=>this.verifyFocusAfterTap(...n),verifyFocusedInputTarget:(...n)=>this.verifyFocusedInputTarget(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});gestureDispatcher=new ue({accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,device:()=>this.device,isAndroidXr:(n)=>da({device:this.device,adb:this.adb,signal:n},this.xrDetector),dispatchCoordinateTapOrAdbFallback:(...n)=>this.dispatchCoordinateTapOrAdbFallback(...n),executeAndroidLongPress:(...n)=>this.executeAndroidLongPress(...n),executeAndroidTap:(...n)=>this.executeAndroidTap(...n),executeAndroidTapWithAccessibility:(...n)=>this.executeAndroidTapWithAccessibility(...n),executeAndroidTapWithCoordinates:(...n)=>this.executeAndroidTapWithCoordinates(...n),executeIOSTapWithVoiceOver:(...n)=>this.executeIOSTapWithVoiceOver(...n),executeScopedAndroidTap:(...n)=>this.executeScopedAndroidTap(...n),executeiOSTapWithCoordinates:(...n)=>this.executeiOSTapWithCoordinates(...n),featureFlags:()=>this.featureFlags,findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),finder:()=>this.finder,geometry:()=>this.geometry,getScreenSizeFromHierarchy:(...n)=>this.getScreenSizeFromHierarchy(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),isScreenReaderNavigationEnabled:(...n)=>this.isScreenReaderNavigationEnabled(...n),readOptionalDisplayFence:(...n)=>this.readOptionalDisplayFence(...n),refreshedRetrySelection:(...n)=>this.refreshedRetrySelection(...n),reportTalkBackActivationWarning:(...n)=>this.reportTalkBackActivationWarning(...n),resolveEnsureCheckedRetryTarget:(...n)=>this.resolveEnsureCheckedRetryTarget(...n),resolveRefreshedRetryTarget:(...n)=>this.resolveRefreshedRetryTarget(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),resolveVisibleTapPoint:(...n)=>this.resolveVisibleTapPoint(...n),semanticAndroidLongPressTargetError:(...n)=>this.semanticAndroidLongPressTargetError(...n),strategy:()=>this.strategy,talkBackDriverFactory:()=>this.talkBackDriverFactory,talkBackStrategy:()=>this.talkBackStrategy,talkBackTargetContext:(...n)=>this.talkBackTargetContext(...n),tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,tryDocumentsUiRowActivation:(...n)=>this.tryDocumentsUiRowActivation(...n),trySemanticAndroidLongPress:(...n)=>this.trySemanticAndroidLongPress(...n),visibleTapBounds:(...n)=>this.visibleTapBounds(...n),withRetryScreenSize:(...n)=>this.withRetryScreenSize(...n)});refreshedDisplayTransitions;lastRenderedObservation;focusVerifier=new Re({device:this.device,findElementInHierarchy:(n,a)=>this.findElementInHierarchy(n,a),withObservationScreenSize:(n,a)=>this.withObservationScreenSize(n,a)});tapPoints=new ge({device:this.device,geometry:()=>this.geometry,strategy:()=>this.strategy,prototypeAgents:{get:(n,a)=>this.prototypeAgents.get(n,a)}});prototypeAgents;finder=new be({device:this.device,elementSelector:()=>this.elementSelector,tapPoints:this.tapPoints});settler=new ye({timer:this.timer,waitForCondition:()=>this.waitForCondition,hashViewHierarchy:(n)=>this.hashViewHierarchy(n),deriveTapEffect:(n,a)=>this.deriveTapEffect(n,a),compareActiveWindow:(n,a)=>this.compareActiveWindow(n,a)});postTapEffect=new Ae({applyRefreshedObservationRotation:(n,a)=>this.strategy.applyRefreshedObservationRotation(n,a),settlesPostTapChange:()=>this.strategy.settlesPostTapChange,settler:()=>this.settler,deriveTapEffect:(n,a)=>this.deriveTapEffect(n,a),getScreenSizeFromHierarchy:(n,a)=>this.getScreenSizeFromHierarchy(n,a)});ensureChecked=new we({timer:this.timer,tapVerificationRefresh:(n)=>this.tapVerificationRefresh(n),findElementInHierarchy:(n,a)=>this.findElementInHierarchy(n,a),withObservationScreenSize:(n,a)=>this.withObservationScreenSize(n,a),replaceObservationHierarchy:(n,a,s)=>this.replaceObservationHierarchy(n,a,s),elementAffordances:(n)=>this.elementAffordances(n),elementIdentity:(n)=>this.elementIdentity(n)});geometry;elementParser;accessibilityService;visionConfig;screenshotCapturer;visionAnalyzer;selectionStateTracker;accessibilityDetector;elementSelector;viewHierarchy;hierarchyCapture;talkBackStrategy;featureFlags;talkBackDriverFactory;iosVoiceOverDetector;strategy;longPressMetadataDetector;waitForCondition;xrDisplaySize;xrDetector;constructor(n,a=null,s={}){super(n,{adb:a,timer:s.timer,displayFence:s});this.xrDisplaySize=s.xrDisplaySize,this.refreshedDisplayTransitions=s.displayTransitions??Ce,this.lastRenderedObservation=s.lastRenderedObservation,this.prototypeAgents=s.prototypeAgents??{get:(d,p)=>wT.get(d,p)??Of.getRecord(d,p)?.client},this.waitForCondition=s.waitForCondition??new $F(this.observeScreen,this.timer),this.geometry=new or,this.elementParser=new K,this.accessibilityService=Xs(n,this.adbFactory),this.visionConfig=s.visionConfig||Lm,this.screenshotCapturer=s.screenshotCapturer??new gp(n,this.adbFactory),this.visionAnalyzer=s.visionAnalyzer,this.viewHierarchy=new Qi(n,this.adbFactory),this.hierarchyCapture=s.hierarchyCapture??new dy(n.platform,{readCached:(d)=>this.viewHierarchy.getViewHierarchy({},{skipWaitForFresh:!0,minTimestamp:d.minTimestamp,signal:d.signal,timeoutMs:d.timeoutMs}),readFresh:async(d)=>{if(d.displayId!==void 0)return(await Pn(n,{adbFactory:this.adbFactory,timer:this.timer}).capture(d)).hierarchy;let p=await this.readFreshHierarchy(d.timeoutMs??HF,void 0,d.signal,d.requireFreshExtraction);if(!p)throw new t("Unable to retrieve a fresh tap hierarchy");return p},projectVisible:(d)=>this.viewHierarchy.projectActionableHierarchy(d)},this.timer),this.selectionStateTracker=s.selectionStateTracker??new z5({screenshotCapturer:this.screenshotCapturer}),this.accessibilityDetector=s.accessibilityDetector||li,this.xrDetector=s.xrDetector,this.elementSelector=this.createElementSelector(s);let c=Ct(s,{device:n,adbFactory:this.adbFactory,adb:this.adb,timer:this.timer,accessibilityDetector:this.accessibilityDetector});this.talkBackDriverFactory=c.talkBackDriverFactory,this.talkBackStrategy=c.talkBackStrategy,this.iosVoiceOverDetector=c.iosVoiceOverDetector,this.featureFlags=c.featureFlags,this.strategy=c.strategy,this.longPressMetadataDetector=new Pe(this.elementParser)}get platformTraits(){return Ft(this.device.platform)}createElementSelector(n){return n.elementSelector??new br(void 0,void 0,{platform:ae(this.device.platform)?"ios":re(this.device.platform,"tapOn"),iosMultiPanel:!ae(this.device.platform)&&this.platformTraits.panelAwareSelection&&(this.device.displays?.panels.length??0)>1})}get testHooks(){return{validateOptions:this.validateOptions.bind(this),hasUniqueSemanticLinkOwner:this.hasUniqueSemanticLinkOwner.bind(this),hashViewHierarchy:this.hashViewHierarchy.bind(this),replaceObservationHierarchy:this.replaceObservationHierarchy.bind(this),verifyFocusedInputTarget:this.verifyFocusedInputTarget.bind(this),handleElementNotFound:this.handleElementNotFound.bind(this),executeAndroidLongPress:this.executeAndroidLongPress.bind(this),executeiOSTap:this.executeiOSTap.bind(this),executeiOSTapWithCoordinates:this.executeiOSTapWithCoordinates.bind(this),executeIOSTapWithVoiceOver:this.executeIOSTapWithVoiceOver.bind(this),setValidateOptions:(n)=>{this.validateOptions=n},setIosCoordinateTap:(n)=>{this.executeiOSTapWithCoordinates=n},setTerminalScreenshotCapture:(n)=>{this.captureTerminalObservationScreenshot=n},setDeferredPredictionRecorder:(n)=>{this.recordDeferredPredictionOutcome=n}}}createErrorResult(...n){return this.semanticLinks.createErrorResult(...n)}validateOptions(...n){return this.semanticLinks.validateOptions(...n)}activateSemanticLink(...n){return this.semanticLinks.activateSemanticLink(...n)}hasUniqueSemanticLinkOwner(...n){return this.semanticLinks.hasUniqueSemanticLinkOwner(...n)}getSearchUntilDuration(...n){return this.targets.getSearchUntilDuration(...n)}hashViewHierarchy(...n){return this.targets.hashViewHierarchy(...n)}deriveTapEffect(...n){return this.targets.deriveTapEffect(...n)}deriveTapEffectAfterPostTapObservation(...n){return this.targets.deriveTapEffectAfterPostTapObservation(...n)}enforceFreshnessConsistencyWithEffect(...n){return this.targets.enforceFreshnessConsistencyWithEffect(...n)}replaceObservationHierarchy(...n){return this.targets.replaceObservationHierarchy(...n)}logClickableParentSelection(...n){return this.targets.logClickableParentSelection(...n)}prepareSelectionCapture(...n){return this.targets.prepareSelectionCapture(...n)}withObservationScreenSize(...n){return this.targets.withObservationScreenSize(...n)}findElementInHierarchy(...n){return this.targets.findElementInHierarchy(...n)}verifyFocusedInputTarget(...n){return this.targets.verifyFocusedInputTarget(...n)}invisibleMatchFailure(...n){return this.targets.invisibleMatchFailure(...n)}resolveTapPoint(...n){return this.targets.resolveTapPoint(...n)}resolveContainerElement(...n){return this.targets.resolveContainerElement(...n)}isElementTapTargetOffScreen=(...n)=>this.tapPoints.isElementTapTargetOffScreen(...n);visibleTapBounds=(...n)=>this.targets.visibleTapBounds(...n);resolveVisibleTapPoint=(...n)=>this.targets.resolveVisibleTapPoint(...n);getScreenSizeFromHierarchy=(...n)=>this.tapPoints.getScreenSizeFromHierarchy(...n);verifyFocusAfterTap=(...n)=>this.targets.verifyFocusAfterTap(...n);refreshViewHierarchy(...n){return this.targets.refreshViewHierarchy(...n)}tapVerificationRefresh(...n){return this.targets.tapVerificationRefresh(...n)}readFreshHierarchy(...n){return this.targets.readFreshHierarchy(...n)}resolveAndroidStableTapTargetAfterRefreshes(...n){return this.targets.resolveAndroidStableTapTargetAfterRefreshes(...n)}staleSyntheticTarget(...n){return this.targets.staleSyntheticTarget(...n)}searchForElement(...n){return this.targets.searchForElement(...n)}buildSelectedElementMetadata(...n){let a=this.targets.buildSelectedElementMetadata(...n);return Rte(this.device.platform,n[0],a)}rebuildSelectedElementMetadataAfterStability(...n){return this.targets.rebuildSelectedElementMetadataAfterStability(...n)}handleElementNotFound(...n){return this.targets.handleElementNotFound(...n)}isClickableElement(...n){return this.targets.isClickableElement(...n)}isLongClickableElement(...n){return this.targets.isLongClickableElement(...n)}elementAffordances(...n){return this.targets.elementAffordances(...n)}elementIdentity(...n){return this.targets.elementIdentity(...n)}ensureCheckedBeforeTap(...n){return this.targets.ensureCheckedBeforeTap(...n)}refreshEnsureCheckedSelection(...n){return this.targets.refreshEnsureCheckedSelection(...n)}applyEnsureCheckedResult(...n){return this.targets.applyEnsureCheckedResult(...n)}resolveTapTargetElement(...n){return this.targets.resolveTapTargetElement(...n)}unverifiableDisplayPostState(...n){return this.displayRouter.unverifiableDisplayPostState(...n)}executeOnDisplay(...n){return this.displayRouter.executeOnDisplay(...n)}didCompleteDisplayGesture(...n){return this.displayRouter.didCompleteDisplayGesture(...n)}completedDisplayFailure(...n){return this.displayRouter.completedDisplayFailure(...n)}rethrowKeyboardOcclusion(...n){return this.displayRouter.rethrowKeyboardOcclusion(...n)}async execute(n,a={}){let s=$e(this.device,n,a.signal);if(s)return s;return Km(()=>this.executeWithReadScope(n,a))}executeWithReadScope(...n){return this.execution.executeWithReadScope(...n)}activateAccessibilityLinkPhase(...n){return this.semanticLinks.activateAccessibilityLinkPhase(...n)}activateSubtextPhase(...n){return this.semanticLinks.activateSubtextPhase(...n)}confirmFocusAfterTap(...n){return this.execution.confirmFocusAfterTap(...n)}assertLongPressWithinRequestBudget(...n){return this.execution.assertLongPressWithinRequestBudget(...n)}predictionToolArgs(...n){return this.execution.predictionToolArgs(...n)}readScopeFailureResult(...n){return this.execution.readScopeFailureResult(...n)}executeAndroidTap(...n){return this.gestureDispatcher.executeAndroidTap(...n)}executeScopedAndroidTap(...n){return this.gestureDispatcher.executeScopedAndroidTap(...n)}executeAndroidTapWithCoordinates(...n){return this.gestureDispatcher.executeAndroidTapWithCoordinates(...n)}tryDocumentsUiRowActivation(...n){return this.gestureDispatcher.tryDocumentsUiRowActivation(...n)}dispatchCoordinateTapOrAdbFallback(...n){return this.gestureDispatcher.dispatchCoordinateTapOrAdbFallback(...n)}resolveEnsureCheckedRetryTarget(...n){return this.gestureDispatcher.resolveEnsureCheckedRetryTarget(...n)}withRetryScreenSize(...n){return this.gestureDispatcher.withRetryScreenSize(...n)}refreshedRetrySelection(...n){return this.gestureDispatcher.refreshedRetrySelection(...n)}resolveRefreshedRetryTarget(...n){return this.gestureDispatcher.resolveRefreshedRetryTarget(...n)}retryTapIfNoChange(...n){return this.gestureDispatcher.retryTapIfNoChange(...n)}isScreenReaderNavigationEnabled(...n){return this.gestureDispatcher.isScreenReaderNavigationEnabled(...n)}reportTalkBackActivationWarning(...n){return this.gestureDispatcher.reportTalkBackActivationWarning(...n)}talkBackTargetContext(...n){return this.gestureDispatcher.talkBackTargetContext(...n)}executeAndroidTapWithAccessibility(...n){return this.gestureDispatcher.executeAndroidTapWithAccessibility(...n)}executeiOSTap(...n){return this.gestureDispatcher.executeiOSTap(...n)}executeiOSTapWithCoordinates(...n){return this.gestureDispatcher.executeiOSTapWithCoordinates(...n)}executeIOSTapWithVoiceOver(...n){return this.gestureDispatcher.executeIOSTapWithVoiceOver(...n)}readOptionalDisplayFence(...n){return this.gestureDispatcher.readOptionalDisplayFence(...n)}getLongPressDuration(...n){return this.gestureDispatcher.getLongPressDuration(...n)}executeAndroidLongPress(...n){return this.gestureDispatcher.executeAndroidLongPress(...n)}throwIfLongPressInterrupted(...n){return this.gestureDispatcher.throwIfLongPressInterrupted(...n)}semanticAndroidLongPressTargetError(...n){return this.gestureDispatcher.semanticAndroidLongPressTargetError(...n)}trySemanticAndroidLongPress(...n){return this.gestureDispatcher.trySemanticAndroidLongPress(...n)}detectLongPressMetadata(...n){return this.execution.detectLongPressMetadata(...n)}}
6
+ export{ST,yC,Hee,Rw,BF,Nm,qee,xV,wT,Vee,$F,bc};
7
+
8
+ //# debugId=44E25F102E98B43464756E2164756E21