agent-device 0.21.0 → 0.21.1

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 (282) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.apk → agent-device-android-ime-helper-0.21.1.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.1.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.1.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.apk → agent-device-android-snapshot-helper-0.21.1.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.1.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/README.md +58 -1
  8. package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
  9. package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
  11. package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
  12. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +14 -4
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1065 -223
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +249 -61
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +51 -43
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +83 -5
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +125 -75
  51. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +9 -9
  52. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
  53. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +4 -4
  54. package/dist/src/adapter.js +1 -1
  55. package/dist/src/adb-executor.js +1 -1
  56. package/dist/src/adb-failure.js +1 -1
  57. package/dist/src/agent-browser-process-record.js +1 -1
  58. package/dist/src/agent-browser-provider.js +1 -1
  59. package/dist/src/agent-browser-tool.js +1 -1
  60. package/dist/src/agent-device-client.js +2 -2
  61. package/dist/src/ai-sdk.d.ts +1 -1
  62. package/dist/src/ai-sdk.js +1 -1
  63. package/dist/src/alert-runtime.js +1 -1
  64. package/dist/src/android-input-ownership.js +1 -1
  65. package/dist/src/app-catalog.js +1 -1
  66. package/dist/src/app-deployment-resolution.js +1 -1
  67. package/dist/src/app-inventory-contract.js +1 -1
  68. package/dist/src/app-inventory.js +1 -1
  69. package/dist/src/app-launch.js +2 -2
  70. package/dist/src/app-lifecycle.js +3 -3
  71. package/dist/src/app-lifecycle2.js +1 -1
  72. package/dist/src/app-log-files.js +1 -1
  73. package/dist/src/app-log-runtime2.js +3 -3
  74. package/dist/src/app-resolution.js +1 -1
  75. package/dist/src/apple-runner-platform.js +1 -0
  76. package/dist/src/application-lifecycle-interaction.js +1 -1
  77. package/dist/src/archive.js +1 -1
  78. package/dist/src/artifact-download.js +1 -1
  79. package/dist/src/auth-session.js +1 -1
  80. package/dist/src/auth.js +1 -1
  81. package/dist/src/backend-snapshot-options.js +1 -1
  82. package/dist/src/boot-diagnostics.js +1 -1
  83. package/dist/src/capture.js +1 -1
  84. package/dist/src/cli-config.js +1 -1
  85. package/dist/src/cli-help.js +25 -21
  86. package/dist/src/cli-runner.js +1 -1
  87. package/dist/src/cli.js +4 -4
  88. package/dist/src/click-button.js +1 -1
  89. package/dist/src/client-metro-companion.js +1 -1
  90. package/dist/src/client-metro.js +1 -1
  91. package/dist/src/client-types.d.ts +27 -13
  92. package/dist/src/code-signature-cache.js +1 -1
  93. package/dist/src/code-signature.js +1 -1
  94. package/dist/src/command-schema.js +3 -3
  95. package/dist/src/command-tools.js +2 -2
  96. package/dist/src/command.js +1 -1
  97. package/dist/src/connection-runtime.js +1 -1
  98. package/dist/src/connection.js +3 -3
  99. package/dist/src/contracts.d.ts +1 -1
  100. package/dist/src/contracts.js +1 -1
  101. package/dist/src/daemon-client-lifecycle.js +1 -1
  102. package/dist/src/daemon.js +1 -1
  103. package/dist/src/debug-symbols-facade.js +1 -1
  104. package/dist/src/device-claim-rule.js +1 -1
  105. package/dist/src/device-inventory-context.js +1 -1
  106. package/dist/src/device-rotation.js +1 -1
  107. package/dist/src/device-selection-resolver.js +1 -1
  108. package/dist/src/device-session.js +1 -1
  109. package/dist/src/device2.js +1 -1
  110. package/dist/src/diagnostics.js +1 -1
  111. package/dist/src/dispatch-resolve.js +1 -1
  112. package/dist/src/doctor2.js +1 -1
  113. package/dist/src/error.js +1 -1
  114. package/dist/src/exec.js +1 -1
  115. package/dist/src/file.js +1 -1
  116. package/dist/src/find.js +1 -1
  117. package/dist/src/generic-settle.js +1 -1
  118. package/dist/src/gesture-plan.js +1 -1
  119. package/dist/src/gesture-runtime.js +1 -1
  120. package/dist/src/harmonyos.js +1 -1
  121. package/dist/src/hdc.js +1 -1
  122. package/dist/src/helper.js +2 -2
  123. package/dist/src/human-control-contract.js +1 -1
  124. package/dist/src/human-control.js +1 -1
  125. package/dist/src/index.d.ts +1 -1
  126. package/dist/src/index.js +1 -1
  127. package/dist/src/input-actions.js +1 -1
  128. package/dist/src/input-actions2.js +2 -2
  129. package/dist/src/install-artifact-facade.js +1 -1
  130. package/dist/src/install-source-network-transport.js +1 -1
  131. package/dist/src/install-source2.js +1 -1
  132. package/dist/src/interaction-positionals.js +1 -1
  133. package/dist/src/interaction-ref-policy.js +1 -1
  134. package/dist/src/interaction2.js +1 -1
  135. package/dist/src/interactor.js +5 -5
  136. package/dist/src/interactor2.js +1 -1
  137. package/dist/src/interactors.js +1 -1
  138. package/dist/src/internal/bin.js +1 -1
  139. package/dist/src/internal/daemon.js +2 -2
  140. package/dist/src/internal/png-worker.js +1 -1
  141. package/dist/src/internal/run-script-http-child.js +1 -1
  142. package/dist/src/inventory.js +2 -2
  143. package/dist/src/inventory2.js +1 -1
  144. package/dist/src/inventory3.js +1 -1
  145. package/dist/src/inventory5.js +1 -1
  146. package/dist/src/ios-snapshot-runtime.js +1 -1
  147. package/dist/src/ios-system-surface.js +1 -0
  148. package/dist/src/lease-scope.js +1 -1
  149. package/dist/src/lease.js +1 -1
  150. package/dist/src/limrun-runtime-dependencies.js +1 -1
  151. package/dist/src/limrun.d.ts +1 -1
  152. package/dist/src/linux.js +1 -1
  153. package/dist/src/location-coordinates.js +1 -1
  154. package/dist/src/managed-device-scope.js +1 -1
  155. package/dist/src/mechanics.js +16 -16
  156. package/dist/src/multitouch-support.js +1 -1
  157. package/dist/src/observation.js +1 -1
  158. package/dist/src/open-target-resolution.js +1 -0
  159. package/dist/src/owner-identity.js +3 -3
  160. package/dist/src/parameterized-recorded-fill.js +1 -1
  161. package/dist/src/perf-facade.js +2 -2
  162. package/dist/src/perf-process-identity.js +1 -0
  163. package/dist/src/perf-runtime-operation-builder.js +1 -1
  164. package/dist/src/perf-runtime-plan.js +1 -1
  165. package/dist/src/perf.js +1 -1
  166. package/dist/src/physical-device-control.js +1 -1
  167. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  168. package/dist/src/platform-runtime-app-log-process.js +1 -1
  169. package/dist/src/platform-runtime-host.js +1 -1
  170. package/dist/src/platform-runtime-managed-owner.js +1 -1
  171. package/dist/src/platform-runtime-open-target.js +1 -1
  172. package/dist/src/platform-runtime-operation-host.js +2 -2
  173. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  174. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  175. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  176. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  177. package/dist/src/platform-runtime-unavailable.js +1 -1
  178. package/dist/src/platform-runtime.js +1 -1
  179. package/dist/src/platform-runtime2.js +1 -1
  180. package/dist/src/png-worker-contract.js +1 -1
  181. package/dist/src/prepare-kind.js +1 -1
  182. package/dist/src/provider-device-runtime.js +1 -1
  183. package/dist/src/provider-session-ownership.js +1 -1
  184. package/dist/src/provider-webdriver.js +1 -1
  185. package/dist/src/proxy.js +1 -1
  186. package/dist/src/react-native.js +1 -1
  187. package/dist/src/record-runtime.js +1 -1
  188. package/dist/src/rect-center.js +1 -1
  189. package/dist/src/register-builtins.js +1 -1
  190. package/dist/src/registry.js +37 -36
  191. package/dist/src/remote-config2.js +1 -1
  192. package/dist/src/replay-divergence.js +1 -1
  193. package/dist/src/replay.js +2 -2
  194. package/dist/src/reporting.js +9 -8
  195. package/dist/src/request-admission.js +1 -1
  196. package/dist/src/request-cancel.js +1 -1
  197. package/dist/src/request-runtime-binding.js +1 -1
  198. package/dist/src/retry.js +1 -1
  199. package/dist/src/runner-cache-metadata.js +2 -2
  200. package/dist/src/runner-client.js +1 -1
  201. package/dist/src/runner-disposal.js +1 -1
  202. package/dist/src/runner-operations-facade.js +1 -1
  203. package/dist/src/runner.js +1 -1
  204. package/dist/src/runtime-transport-hints.js +1 -1
  205. package/dist/src/runtime.js +3 -3
  206. package/dist/src/runtime2.js +4 -4
  207. package/dist/src/runtime3.js +1 -1
  208. package/dist/src/runtime4.js +5 -4
  209. package/dist/src/runtime5.js +1 -1
  210. package/dist/src/runtime6.js +1 -1
  211. package/dist/src/runtime7.js +1 -1
  212. package/dist/src/runtime8.js +1 -1
  213. package/dist/src/runtime9.js +1 -1
  214. package/dist/src/screen-recording-live-handle.js +1 -1
  215. package/dist/src/screen-recording-options.js +1 -1
  216. package/dist/src/screen-recording-resource-recovery.js +1 -1
  217. package/dist/src/screenshot-density.js +1 -1
  218. package/dist/src/screenshot-runtime.js +1 -1
  219. package/dist/src/screenshot.js +1 -1
  220. package/dist/src/screenshot3.js +3 -3
  221. package/dist/src/script.js +1 -1
  222. package/dist/src/scroll-command.js +1 -1
  223. package/dist/src/scroll-gesture.js +1 -1
  224. package/dist/src/sdk-batch-runner.js +2 -2
  225. package/dist/src/sdk-batch.js +2 -2
  226. package/dist/src/sdk-contracts.d.ts +44 -1
  227. package/dist/src/sdk-contracts.js +2 -2
  228. package/dist/src/sdk-device.js +1 -1
  229. package/dist/src/sdk-finders.d.ts +1 -1
  230. package/dist/src/sdk-io.js +1 -1
  231. package/dist/src/sdk-remote-config.d.ts +1 -1
  232. package/dist/src/sdk-remote-config.js +1 -1
  233. package/dist/src/sdk-selectors.d.ts +69 -13
  234. package/dist/src/selector-runtime.js +1 -1
  235. package/dist/src/server.js +3 -3
  236. package/dist/src/session-allocation.js +1 -1
  237. package/dist/src/session-observation.js +1 -0
  238. package/dist/src/session-routing.js +1 -1
  239. package/dist/src/session-runtime-admission.js +1 -1
  240. package/dist/src/session-snapshot.js +1 -1
  241. package/dist/src/session-store.js +3 -3
  242. package/dist/src/session-target-evidence.js +1 -1
  243. package/dist/src/session2.js +5 -5
  244. package/dist/src/settings.js +1 -1
  245. package/dist/src/simulator.js +1 -1
  246. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  247. package/dist/src/snapshot-quality-verdict.js +1 -1
  248. package/dist/src/snapshot-runtime-binding.js +1 -1
  249. package/dist/src/snapshot-runtime.js +1 -1
  250. package/dist/src/snapshot-state.js +1 -1
  251. package/dist/src/snapshot2.js +1 -1
  252. package/dist/src/snapshot3.js +1 -1
  253. package/dist/src/snapshot4.js +1 -1
  254. package/dist/src/src.js +1 -1
  255. package/dist/src/src7.js +2 -2
  256. package/dist/src/src8.js +2 -2
  257. package/dist/src/string-enum.js +1 -1
  258. package/dist/src/takeover.js +1 -1
  259. package/dist/src/tool-provider.js +2 -2
  260. package/dist/src/tool-provider2.js +1 -1
  261. package/dist/src/tool-provider3.js +1 -1
  262. package/dist/src/toolchain-probe.js +1 -1
  263. package/dist/src/touch-reference-frame.js +1 -0
  264. package/dist/src/touch-runtime.js +1 -1
  265. package/dist/src/transport.js +1 -1
  266. package/dist/src/tv-remote.js +1 -1
  267. package/dist/src/type-text-runtime.js +1 -1
  268. package/dist/src/update-check.js +1 -1
  269. package/dist/src/verified-file.js +1 -1
  270. package/dist/src/video.js +1 -1
  271. package/dist/src/web.js +1 -1
  272. package/dist/src/web2.js +1 -1
  273. package/dist/src/webdriver-source.js +1 -1
  274. package/dist/src/window-state.js +1 -0
  275. package/package.json +3 -2
  276. package/server.json +2 -2
  277. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
  278. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
  279. package/dist/src/back-mode.js +0 -1
  280. package/dist/src/format.js +0 -2
  281. package/dist/src/platform-runtime-apple-resources.js +0 -1
  282. package/dist/src/runner-selector-query.js +0 -1
@@ -1 +1 @@
1
- import{C as e,y as t}from"./sdk-contracts.js";import{a as n,v as r}from"./sdk-device.js";import{qt as i}from"./sdk-batch.js";import{l as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{i as s,r as c}from"./device-rotation.js";import{s as l}from"./exec.js";import"./command.js";import{r as u}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as ee}from"./webdriver-source.js";import{t as m}from"./providers.js";import h from"node:path";import te from"node:fs";import ne from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function re(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:ae(e?.launchTarget,n,r)}}function ie(e){return e===`ios`?`xctest`:`android`}function ae(...e){return e.find(e=>e!==void 0)}function oe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await ce(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),re(s,i)};return Object.freeze({fact:t=>se(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function se(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function ce(e,n,i,a,o,s,c){if(!p(n.capabilities,`install`))throw new t(`UNSUPPORTED_OPERATION`,f(n.capabilities,`install`),{provider:e.provider,deviceId:i.id,platform:r(i)});let l=n.prepared.uploadApp??e.uploadApp;if(l)return await l({provider:e.provider,lease:n.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(e,n){if(!e)throw new t(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{packageName:e.packageName}:{},...e.appName?{appName:e.appName}:{},...e.launchTarget??n?{launchTarget:e.launchTarget??n}:{}}}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function le(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(n,r){try{await r()}catch(r){n instanceof t&&(n.details={...n.details,cleanupError:e(r)})}}function ue(e,t){return typeof e==`function`?e(t):e}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function de(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function fe(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function pe(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}const S=`webdriver_request_timeout`;function C(e){return e instanceof t&&e.details?.reason===S}var me=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=pe(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return await this.requestValueWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??this.requestPolicy.retryAttempts,timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestValueWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestValueOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!he(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestValueOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?_e(s):{};if(!a)throw ve(o,c);return ge(c)}async fetchWebDriver(e,t,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a;try{let r=await fetch(new URL(de(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:o});return{ok:r.ok,status:r.status,text:await r.text()}}catch(n){throw a.aborted&&!i?.aborted?ye(e,t,r,n):n}}};function he(e,t,n,r){return!r?.aborted&&be(e)&&t<n}function ge(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function _e(e){try{return JSON.parse(e)}catch(n){throw new t(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},n)}}function ve(e,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return new t(`COMMAND_FAILED`,i,{status:e,response:n})}function ye(e,n,r,i){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} timed out after ${r}ms.`,{reason:S,method:e,path:n,timeoutMs:r},i instanceof Error?i:void 0)}function be(e){if(C(e))return!0;if(e instanceof t){let t=e.details?.status;return typeof t==`number`&&t>=500}return e instanceof TypeError}var xe=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new me(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Ce(await this.requestValue(`POST`,`/session`,{capabilities:Se(e)},{retryAttempts:0,timeoutMs:De(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(k(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=Ee(await this.sessionRequest(`GET`,`/element/active`,void 0,E(t)))}catch(e){if(k(e))return`unsupported`;if(O(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,E(t));return{id:n,rect:w(e)}}catch(e){if(k(e))return`unsupported`;if(O(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(){let e=await this.sessionRequest(`GET`,`/source`);if(typeof e!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof e});return e}async screenshot(e){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ne.writeFile(e,Buffer.from(n,`base64`))}async windowRect(){return w(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new t(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function w(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=e,r={x:T(n,`x`),y:T(n,`y`),width:T(n,`width`),height:T(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function T(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Se(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Ce(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=e,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new t(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}const we=new Set([405,501]),Te=new Set([`unknown command`,`unknown method`]);function Ee(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function E(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:D(e)}}function De(e,t){return t===void 0?e:Math.min(e,D(t))}function D(e){return Math.max(0,e-Date.now())}function O(e){return e instanceof t&&A(e).toLowerCase()===`no such element`}function k(e){if(!(e instanceof t))return!1;let n=e.details?.status;return typeof n==`number`&&we.has(n)?!0:Te.has(A(e).toLowerCase())}function A(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function Oe(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function ke(e){return j(ee(e,`android`).nodes)}function Ae(e){return j(ee(e).nodes)}function j(e){let t=e.flatMap(e=>je(e)&&Me(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function je(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Me(e){return!!e&&e.width>=50&&e.height>=50}async function Ne(e,n,r){let i=[];for(let t of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Re(e,t,r);return}catch(e){if(!Ie(e))throw e;i.push({transport:t,error:e instanceof Error?e.message:String(e)})}throw new t(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}const Pe=new Set([`unknown command`,`unknown method`]),Fe=new Set([404,405]);function Ie(e){if(!(e instanceof t)||e.code===`SESSION_NOT_FOUND`)return!1;let n=Le(e.details?.response);if(n)return Pe.has(n);let r=e.details?.status;return typeof r==`number`&&Fe.has(r)}function Le(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function Re(e,t,n){if(t===`rotation`){await e.setRotation(s(n));return}await e.setOrientation(c(n))}const M=1500;function ze(e){return new Promise(t=>setTimeout(t,e))}function N(e,n,r){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function Be(e,n){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:e,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ve(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function He(e){return new Ue(e.client,e.backend,e.capabilities,e.targetId)}var Ue=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new t(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(e,n);let o=await this.awaitTextEntryReadiness(a,e,n);return await this.type(r),{backend:`webdriver`,x:e,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(Ge(e)),await this.client.performActions(e.pointers.map(e=>Oe(`gesture-pointer-${e.pointerId}`,We(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){if(this.requireSupport(`snapshot`),this.backend===`xctest`){let{captureWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return await e(this.client,this.targetId)}let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:t(await this.client.source(),`android`).nodes}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Ne(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async readAlert(){this.unsupported(`alert`)}async awaitAlert(){this.unsupported(`alert`)}async acceptAlert(){this.unsupported(`alert`)}async dismissAlert(){this.unsupported(`alert`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ve(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw N(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Be(t,n);if(r)throw N(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw N(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(M),this.client.activeElement(M)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(M,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await ze(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([Oe(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ae(e):ke(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new t(`UNSUPPORTED_OPERATION`,f(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function We(e){let n=e[0];if(!n)throw new t(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function Ge(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}var Ke=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new xe({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:He({client:r,backend:ie(n.platform),capabilities:s,targetId:a.id})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=C(e)?qe(e,this.options.provider,n,t):e;throw await b(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:P(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...n(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(t){let n=[],r;try{await t.client.deleteSession()}catch(t){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:e(t)})}try{r=await t.prepared.cleanup?.()}catch(t){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:e(t)})}return{cleanup:r,warnings:n}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return le({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function P(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function qe(e,n,r,i){let a=e.details?.timeoutMs;return new t(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}function F(e){return new Je(e)}var Je=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new Ke(e),this.deployment=oe({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};async function I(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Xe(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function Ye(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Xe(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:Ze(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function Ze(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}m.awsDeviceFarm;const Qe={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function L(e){let t=R(e);return{createRemoteAccessSession:async e=>z(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>z(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>z(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>Ye(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function $e(e){return async({lease:n,req:r,base:i})=>{let a=await e.client.createRemoteAccessSession({projectArn:e.projectArn,deviceArn:e.deviceArn,appArn:e.appArn,name:ue(e.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:e.interactionMode,configuration:e.configuration}),o,s;try{if(o=await nt(a.arn,e,r),s=et(o),!s)throw new t(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(t){throw await b(t,()=>e.client.stopRemoteAccessSession(a.arn)),t}let c=o.device?.name??e.deviceName,l=typeof e.webdriverCapabilities==`function`?e.webdriverCapabilities(n):e.webdriverCapabilities??{};return{...i,endpoint:s,platform:e.platform,deviceName:c,webdriverCapabilities:P(e.platform,c,l),cleanup:async()=>(await e.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function et(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?tt(n):void 0}function tt(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function nt(e,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(e);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;it(c),await g(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(e)}throw new t(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:e,status:c.status,result:c.result,timeoutMs:o-a})}const rt=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function it(e){if(!(!e.status||!rt.has(e.status)))throw new t(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:e.arn,status:e.status,result:e.result})}async function at(e,n,r){let i=await e(n,r);try{return JSON.parse(i.stdout)}catch(e){throw new t(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,e)}}function R(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await at(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function z(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:e});let n=e.remoteAccessSession;if(!n||typeof n!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:e});return n}const B=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function ot(e,t){ft(e);let n={};for(let r of B){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(dt(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function st(e){return B.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function V(e,n){let r=st(e);if(r.length===0)return;let i=r.length!==1;throw new t(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function ct(e){let t={};for(let n of B){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&lt(t,n,r)}return t}function lt(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=ut(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function ut(e,n){let r=o.find(e=>e===n);if(r)return r;throw new t(`INVALID_ARGS`,`Invalid ${e.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:e.flag,capability:e.capability})}function dt(e,n){if(!(!e.platform||e.platform===n))throw new t(`INVALID_ARGS`,`${e.flag} applies to ${e.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${e.flag} or connect with --platform ${e.platform}.`,flag:e.flag,capability:e.capability,platform:n})}function ft(e){if(!(!e.providerNetworkProfile||!e.providerCustomNetwork))throw new t(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:e.providerNetworkProfile,customNetwork:e.providerCustomNetwork})}m.browserStack;const pt={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function H(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:vt(e,t,await _t(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function U(e,n,r){r?.throwIfAborted();let i=await ne.readFile(e),a=new FormData;a.set(`file`,new Blob([i]),h.basename(e));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:x(n)},body:a,signal:r}),s=await o.json(),c=yt(s);if(!o.ok||!c)throw new t(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function mt(e){return async({appPath:t,options:n,signal:r})=>({appReference:await U(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function ht(e){let{"bstack:options":t,...n}=e.configured??{};return{device:e.deviceName,os_version:e.osVersion,...e.app?{app:e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...gt(t)}}}function gt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function _t(e,n){let r=new URL(`${fe(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${e}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:x(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new t(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function vt(e,t,n){return[W(e,t,n,`video_url`,`video`,`Session video`),W(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),W(e,t,n,`device_logs_url`,`device-log`,`Device logs`),W(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),W(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function W(e,t,n,r,i,a){let o=n[r];if(typeof o==`string`&&o.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function yt(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function G(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function bt(e,n){let r=R({runHostCommand:n,region:e.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,e.projectArn]),r(`get-device`,[`--arn`,e.deviceArn]),e.appArn?r(`get-upload`,[`--arn`,e.appArn]):void 0]),s=K(i,`project`),c=K(a,`device`),l=St(c.platform);if(l!==e.platform)throw new t(`INVALID_ARGS`,`AWS Device Farm device "${q(c.name)??e.deviceArn}" is ${l}, not ${e.platform}.`);let u=e.appArn?xt(K(o,`upload`),e):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:e.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:q(s.name),reference:e.projectArn},device:{status:`verified`,name:q(c.name)??e.deviceArn,reference:e.deviceArn,platform:l,osVersion:q(c.os),availability:q(c.availability)},app:u}}function xt(e,n){let r=q(e.status);if(r!==`SUCCEEDED`)throw new t(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=q(e.type);if(a!==i)throw new t(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:q(e.name),reference:n.appArn}}function K(e,n){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=e[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new t(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function St(e){if(e===`ANDROID`)return`android`;if(e===`IOS`)return`ios`;throw new t(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(e)}.`)}function q(e){return typeof e==`string`&&e.length>0?e:void 0}async function Ct(e,n){let r={username:e.username,accessKey:e.accessKey},i=Et(await J(e.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(t=>t.device===e.deviceName&&t.os.toLowerCase()===e.platform&&Tt(t.osVersion,e.osVersion));if(!i)throw new t(`INVALID_ARGS`,`BrowserStack device "${e.deviceName}" with ${e.platform} ${e.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await wt(e,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:e.platform,osVersion:i.osVersion},app:a}}async function wt(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Dt(await J(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:h.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function J(e,n,r){try{let i=await fetch(e,{headers:{...y(r),Authorization:x(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let e=i.status===401||i.status===403;throw new t(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:e?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(e){throw e instanceof t?e:new t(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},e)}}function Tt(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Et(e){if(!Array.isArray(e))throw new t(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return e.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Dt(e){let n=Y(e);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(e))throw new t(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return e.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Ot(e,t){return e.provider===`browserstack`?await Ct(e,t.clientVersion):await bt(e,t.runHostCommand)}function kt(e){return[{provider:m.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:pt,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Mt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await At({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:mt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:ht({deviceName:l,osVersion:u,app:d,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:ot(ct(a.flags),c),configured:P(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:Qe,listArtifacts:async({provider:n,providerSessionId:r})=>await I(n,r,L({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??G(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`AWS Device Farm`);V(a.flags,m.awsDeviceFarm);let o=Mt(a,`AWS Device Farm`);return await $e({client:L({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Nt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Nt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:Pt(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=L({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??G(t)});return await I(m.awsDeviceFarm,t,r)}}]}async function At(e){if(jt(e.app))return e.app;let n=h.resolve(e.cwd??process.cwd(),e.app);if(!te.existsSync(n))throw new t(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:e.app});return await U(n,{clientVersion:e.clientVersion,username:e.username,accessKey:e.accessKey,endpoint:e.uploadEndpoint},e.signal)}function jt(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function X(e,n){if(e)return e;throw new t(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Mt(e,n){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new t(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(e,n,r){let i=Q(e,n);if(i)return i;throw new t(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(e,n,r){let i=e[n];if(i)return i;throw new t(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Nt(e,n,r,i,a){let o=Q(e,r)??n[i]??n[a];if(o)return o;throw new t(`INVALID_ARGS`,`AWS Device Farm requires --${Ft(String(r))} or ${a}.`)}function Pt(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function Ft(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function It(e){let t=kt(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await Ot(t,e)}}const Lt=It({clientVersion:u(),runHostCommand:async(e,t)=>({stdout:(await l(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{G as n,V as r,Lt as t};
1
+ import{C as e,D as t}from"./sdk-contracts.js";import{a as n,v as r}from"./sdk-device.js";import{qt as i}from"./sdk-batch.js";import{u as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{i as s,r as c}from"./device-rotation.js";import{c as l}from"./exec.js";import"./command.js";import{r as u}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as ee}from"./webdriver-source.js";import{t as m}from"./providers.js";import h from"node:path";import te from"node:fs";import ne from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function re(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:ae(e?.launchTarget,n,r)}}function ie(e){return e===`ios`?`xctest`:`android`}function ae(...e){return e.find(e=>e!==void 0)}function oe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await ce(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),re(s,i)};return Object.freeze({fact:t=>se(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function se(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function ce(t,n,i,a,o,s,c){if(!p(n.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,f(n.capabilities,`install`),{provider:t.provider,deviceId:i.id,platform:r(i)});let l=n.prepared.uploadApp??t.uploadApp;if(l)return await l({provider:t.provider,lease:n.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function le(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(n,r){try{await r()}catch(r){n instanceof e&&(n.details={...n.details,cleanupError:t(r)})}}function ue(e,t){return typeof e==`function`?e(t):e}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function de(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function fe(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function pe(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}const S=`webdriver_request_timeout`;function C(t){return t instanceof e&&t.details?.reason===S}var me=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=pe(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return await this.requestValueWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??this.requestPolicy.retryAttempts,timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestValueWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestValueOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!he(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestValueOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?_e(s):{};if(!a)throw ve(o,c);return ge(c)}async fetchWebDriver(e,t,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a;try{let r=await fetch(new URL(de(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:o});return{ok:r.ok,status:r.status,text:await r.text()}}catch(n){throw a.aborted&&!i?.aborted?ye(e,t,r,n):n}}};function he(e,t,n,r){return!r?.aborted&&be(e)&&t<n}function ge(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function _e(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function ve(t,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${t}.`;return new e(`COMMAND_FAILED`,i,{status:t,response:n})}function ye(t,n,r,i){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} timed out after ${r}ms.`,{reason:S,method:t,path:n,timeoutMs:r},i instanceof Error?i:void 0)}function be(t){if(C(t))return!0;if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return t instanceof TypeError}var xe=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new me(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Ce(await this.requestValue(`POST`,`/session`,{capabilities:Se(e)},{retryAttempts:0,timeoutMs:De(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(k(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=Ee(await this.sessionRequest(`GET`,`/element/active`,void 0,E(t)))}catch(e){if(k(e))return`unsupported`;if(O(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,E(t));return{id:n,rect:w(e)}}catch(e){if(k(e))return`unsupported`;if(O(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(){let t=await this.sessionRequest(`GET`,`/source`);if(typeof t!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ne.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return w(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new e(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function w(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:T(n,`x`),y:T(n,`y`),width:T(n,`width`),height:T(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function T(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Se(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Ce(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}const we=new Set([405,501]),Te=new Set([`unknown command`,`unknown method`]);function Ee(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function E(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:D(e)}}function De(e,t){return t===void 0?e:Math.min(e,D(t))}function D(e){return Math.max(0,e-Date.now())}function O(t){return t instanceof e&&A(t).toLowerCase()===`no such element`}function k(t){if(!(t instanceof e))return!1;let n=t.details?.status;return typeof n==`number`&&we.has(n)?!0:Te.has(A(t).toLowerCase())}function A(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function Oe(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function ke(e){return j(ee(e,`android`).nodes)}function Ae(e){return j(ee(e).nodes)}function j(e){let t=e.flatMap(e=>je(e)&&Me(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function je(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Me(e){return!!e&&e.width>=50&&e.height>=50}async function Ne(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Re(t,e,r);return}catch(t){if(!Ie(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}const Pe=new Set([`unknown command`,`unknown method`]),Fe=new Set([404,405]);function Ie(t){if(!(t instanceof e)||t.code===`SESSION_NOT_FOUND`)return!1;let n=Le(t.details?.response);if(n)return Pe.has(n);let r=t.details?.status;return typeof r==`number`&&Fe.has(r)}function Le(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function Re(e,t,n){if(t===`rotation`){await e.setRotation(s(n));return}await e.setOrientation(c(n))}const M=1500;function ze(e){return new Promise(t=>setTimeout(t,e))}function N(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function Be(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ve(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function He(e){return new Ue(e.client,e.backend,e.capabilities,e.targetId)}var Ue=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(t,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new e(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(t,n);let o=await this.awaitTextEntryReadiness(a,t,n);return await this.type(r),{backend:`webdriver`,x:t,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(Ge(e)),await this.client.performActions(e.pointers.map(e=>Oe(`gesture-pointer-${e.pointerId}`,We(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){if(this.requireSupport(`snapshot`),this.backend===`xctest`){let{captureWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return await e(this.client,this.targetId)}let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:t(await this.client.source(),`android`).nodes}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Ne(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async readAlert(){this.unsupported(`alert`)}async awaitAlert(){this.unsupported(`alert`)}async acceptAlert(){this.unsupported(`alert`)}async dismissAlert(){this.unsupported(`alert`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ve(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw N(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Be(t,n);if(r)throw N(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw N(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(M),this.client.activeElement(M)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(M,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await ze(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([Oe(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ae(e):ke(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,f(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function We(t){let n=t[0];if(!n)throw new e(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function Ge(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}var Ke=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new xe({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:He({client:r,backend:ie(n.platform),capabilities:s,targetId:a.id})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=C(e)?qe(e,this.options.provider,n,t):e;throw await b(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:P(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...n(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return le({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function P(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function qe(t,n,r,i){let a=t.details?.timeoutMs;return new e(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},t)}function F(e){return new Je(e)}var Je=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new Ke(e),this.deployment=oe({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};async function I(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Xe(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function Ye(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Xe(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:Ze(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function Ze(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}m.awsDeviceFarm;const Qe={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function L(e){let t=R(e);return{createRemoteAccessSession:async e=>z(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>z(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>z(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>Ye(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function $e(t){return async({lease:n,req:r,base:i})=>{let a=await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:ue(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration}),o,s;try{if(o=await nt(a.arn,t,r),s=et(o),!s)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(e){throw await b(e,()=>t.client.stopRemoteAccessSession(a.arn)),e}let c=o.device?.name??t.deviceName,l=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{};return{...i,endpoint:s,platform:t.platform,deviceName:c,webdriverCapabilities:P(t.platform,c,l),cleanup:async()=>(await t.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function et(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?tt(n):void 0}function tt(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function nt(t,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(t);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;it(c),await g(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:c.status,result:c.result,timeoutMs:o-a})}const rt=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function it(t){if(!(!t.status||!rt.has(t.status)))throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t.arn,status:t.status,result:t.result})}async function at(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function R(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await at(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function z(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const B=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function ot(e,t){ft(e);let n={};for(let r of B){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(dt(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function st(e){return B.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function V(t,n){let r=st(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function ct(e){let t={};for(let n of B){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&lt(t,n,r)}return t}function lt(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=ut(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function ut(t,n){let r=o.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:t.flag,capability:t.capability})}function dt(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function ft(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}m.browserStack;const pt={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function H(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:vt(e,t,await _t(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function U(t,n,r){r?.throwIfAborted();let i=await ne.readFile(t),a=new FormData;a.set(`file`,new Blob([i]),h.basename(t));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:x(n)},body:a,signal:r}),s=await o.json(),c=yt(s);if(!o.ok||!c)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function mt(e){return async({appPath:t,options:n,signal:r})=>({appReference:await U(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function ht(e){let{"bstack:options":t,...n}=e.configured??{};return{device:e.deviceName,os_version:e.osVersion,...e.app?{app:e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...gt(t)}}}function gt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function _t(t,n){let r=new URL(`${fe(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:x(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function vt(e,t,n){return[W(e,t,n,`video_url`,`video`,`Session video`),W(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),W(e,t,n,`device_logs_url`,`device-log`,`Device logs`),W(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),W(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function W(e,t,n,r,i,a){let o=n[r];if(typeof o==`string`&&o.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function yt(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function G(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function bt(t,n){let r=R({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=K(i,`project`),c=K(a,`device`),l=St(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${q(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?xt(K(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:q(s.name),reference:t.projectArn},device:{status:`verified`,name:q(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:q(c.os),availability:q(c.availability)},app:u}}function xt(t,n){let r=q(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=q(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:q(t.name),reference:n.appArn}}function K(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function St(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function q(e){return typeof e==`string`&&e.length>0?e:void 0}async function Ct(t,n){let r={username:t.username,accessKey:t.accessKey},i=Et(await J(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&Tt(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await wt(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function wt(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Dt(await J(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:h.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function J(t,n,r){try{let i=await fetch(t,{headers:{...y(r),Authorization:x(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function Tt(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Et(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Dt(t){let n=Y(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function Ot(e,t){return e.provider===`browserstack`?await Ct(e,t.clientVersion):await bt(e,t.runHostCommand)}function kt(e){return[{provider:m.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:pt,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Mt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await At({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:mt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:ht({deviceName:l,osVersion:u,app:d,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:ot(ct(a.flags),c),configured:P(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:Qe,listArtifacts:async({provider:n,providerSessionId:r})=>await I(n,r,L({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??G(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`AWS Device Farm`);V(a.flags,m.awsDeviceFarm);let o=Mt(a,`AWS Device Farm`);return await $e({client:L({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Nt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Nt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:Pt(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=L({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??G(t)});return await I(m.awsDeviceFarm,t,r)}}]}async function At(t){if(jt(t.app))return t.app;let n=h.resolve(t.cwd??process.cwd(),t.app);if(!te.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await U(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint},t.signal)}function jt(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function X(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Mt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(t,n,r){let i=Q(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Nt(t,n,r,i,a){let o=Q(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${Ft(String(r))} or ${a}.`)}function Pt(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function Ft(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function It(e){let t=kt(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await Ot(t,e)}}const Lt=It({clientVersion:u(),runHostCommand:async(e,t)=>({stdout:(await l(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{G as n,V as r,Lt as t};
package/dist/src/proxy.js CHANGED
@@ -1,2 +1,2 @@
1
- import{O as e,y as t}from"./sdk-contracts.js";import{a as n,c as r,d as i,f as a,l as o,m as s,o as c,r as l,s as u,u as d}from"./transport.js";import{i as f,s as p}from"./daemon-client-lifecycle.js";import{r as m}from"./version.js";import{t as h}from"./shared.js";import{n as ee,t as te}from"./color.js";import{randomBytes as ne,randomUUID as g}from"node:crypto";import{Readable as _}from"node:stream";import{pipeline as v}from"node:stream/promises";import y from"node:http";function b(e){let t=S(e);if(!t)return!1;let n=T(t.meta);return C(n)?!1:w(t.source)||w(n?.installSource)}function x(n,r){let i=new t(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});n.statusCode=400,n.setHeader(`content-type`,`application/json`),n.end(JSON.stringify({jsonrpc:`2.0`,id:r,error:{code:-32602,message:i.message,data:e(i)}}))}function S(e){if(e)try{return T(T(JSON.parse(e))?.params)}catch{return}}function C(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function w(e){return T(e)?.kind===`path`}function T(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const E=`${c}/`,D=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,o],O=[`content-type`,`content-disposition`,`x-request-id`];function k(e){let t=V(e);return y.createServer((e,n)=>{A(e,n,t).catch(e=>{de(n,e)})})}async function A(e,t,n){let r=W(e.url??`/`);if(e.method===`GET`&&r===`/health`){await j(t,n);return}if(!G(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await l(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!ae(e,n.clientToken,i)){ue(t,r,Z(i));return}if(b(i)){x(t,Z(i));return}await N({req:e,res:t,route:r,options:n,rpcBody:i})}async function j(e,t){let n=await M(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,m(),{upstream:n})))}async function M(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:X({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function N(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=Y(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=X(t,i.upstreamToken,r),l=ie(t,r,a,i.upstreamToken);await F({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:P(t,n,i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}function P(e,n,r){let i=new AbortController,a=()=>{n.writableFinished||i.signal.aborted||i.abort(new t(`COMMAND_FAILED`,`Proxy client disconnected before the upstream response ended`))};return e.on(`aborted`,a),n.on(`close`,a),AbortSignal.any([i.signal,AbortSignal.timeout(r)])}async function F(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,I(i,n),L(t,n),J(r)){await R({req:t,res:n,response:i,clientToken:a});return}await B(i,n)}function I(e,t){for(let n of O){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function L(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,le(e))}async function R(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(z(a,t,i))}function z(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let a=r;if(!a.upload||typeof a.upload.url!=`string`)return e;let o=re(a.upload.url,t);if(!o)return e;let s=a.upload.headers&&typeof a.upload.headers==`object`?{...a.upload.headers}:{};return Object.assign(s,i(n)),JSON.stringify({...r,upload:{...a.upload,url:o,headers:s}})}function re(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function B(e,t){if(!e.body){t.end();return}await v(_.fromWeb(e.body),t)}function V(e){return{upstreamBaseUrl:H(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:U(e.upstreamToken,`upstreamToken`),clientToken:U(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function H(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function U(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function W(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(E)?`/${t.slice(E.length)}`:t}function G(e,t){return e===`/rpc`?t===`POST`:q(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)||K(e)?t===`GET`:!1}function K(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function q(e,t){return e===`/upload`||J(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function J(e){return e===`/upload/preflight`}function Y(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function X(e,t,n){let a=new Headers;for(let t of D){let n=e.headers[t];typeof n==`string`&&n.trim()&&a.set(t,n)}n===`/rpc`&&!a.has(`content-type`)&&a.set(`content-type`,`application/json`),n===`/rpc`&&a.set(u,r);for(let[e,n]of Object.entries(i(t)))a.set(e,n);return a}function ie(e,t,n,r){if(e.method!==`GET`&&e.method!==`HEAD`)return t===`/rpc`?se(n??``,r):e}function ae(e,t,r){let i=oe(e,r);return i.length>0&&n(i,t)}function oe(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=ce(t);if(e)return e}return``}function se(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function ce(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Z(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function le(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function ue(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function de(t,n){if(t.destroyed)return;if(t.headersSent){t.destroy(n instanceof Error?n:void 0);return}let r=e(n);t.statusCode=r.code===`INVALID_ARGS`?400:500,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const fe=async({positionals:e,flags:n})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await pe(n);return await h(n,r,()=>_e(r)),await ve(),!0};async function pe(e){let n=p({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:e.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await f(n),i=me(r.info.httpPort),o=Q(e),s=k({upstreamBaseUrl:i,upstreamToken:r.info.token,clientToken:o});await he(s,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let c=s.address();if(!c||typeof c==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let l=`http://${ge(c.address)}:${c.port}`;return{proxyBaseUrl:l,agentDeviceBaseUrl:a(l),token:o,upstreamBaseUrl:i,stateDir:n.paths.baseDir}}function me(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function Q(e){return e.daemonAuthToken?.trim()||ne(32).toString(`hex`)}function he(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ge(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function _e(e,t={}){let n=t.useColor??ee(),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(`
1
+ import{C as e,M as t}from"./sdk-contracts.js";import{a as n,c as r,d as i,f as a,l as o,m as s,o as c,r as l,s as u,u as d}from"./transport.js";import{i as f,s as p}from"./daemon-client-lifecycle.js";import{r as m}from"./version.js";import{t as h}from"./shared.js";import{n as ee,t as te}from"./color.js";import{randomBytes as ne,randomUUID as g}from"node:crypto";import{Readable as _}from"node:stream";import{pipeline as v}from"node:stream/promises";import y from"node:http";function b(e){let t=S(e);if(!t)return!1;let n=T(t.meta);return C(n)?!1:w(t.source)||w(n?.installSource)}function x(n,r){let i=new e(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});n.statusCode=400,n.setHeader(`content-type`,`application/json`),n.end(JSON.stringify({jsonrpc:`2.0`,id:r,error:{code:-32602,message:i.message,data:t(i)}}))}function S(e){if(e)try{return T(T(JSON.parse(e))?.params)}catch{return}}function C(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function w(e){return T(e)?.kind===`path`}function T(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const E=`${c}/`,D=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,o],O=[`content-type`,`content-disposition`,`x-request-id`];function k(e){let t=V(e);return y.createServer((e,n)=>{A(e,n,t).catch(e=>{de(n,e)})})}async function A(e,t,n){let r=W(e.url??`/`);if(e.method===`GET`&&r===`/health`){await j(t,n);return}if(!G(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await l(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!ae(e,n.clientToken,i)){ue(t,r,Z(i));return}if(b(i)){x(t,Z(i));return}await N({req:e,res:t,route:r,options:n,rpcBody:i})}async function j(e,t){let n=await M(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,m(),{upstream:n})))}async function M(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:X({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function N(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=Y(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=X(t,i.upstreamToken,r),l=ie(t,r,a,i.upstreamToken);await F({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:P(t,n,i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}function P(t,n,r){let i=new AbortController,a=()=>{n.writableFinished||i.signal.aborted||i.abort(new e(`COMMAND_FAILED`,`Proxy client disconnected before the upstream response ended`))};return t.on(`aborted`,a),n.on(`close`,a),AbortSignal.any([i.signal,AbortSignal.timeout(r)])}async function F(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,I(i,n),L(t,n),J(r)){await R({req:t,res:n,response:i,clientToken:a});return}await B(i,n)}function I(e,t){for(let n of O){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function L(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,le(e))}async function R(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(z(a,t,i))}function z(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let a=r;if(!a.upload||typeof a.upload.url!=`string`)return e;let o=re(a.upload.url,t);if(!o)return e;let s=a.upload.headers&&typeof a.upload.headers==`object`?{...a.upload.headers}:{};return Object.assign(s,i(n)),JSON.stringify({...r,upload:{...a.upload,url:o,headers:s}})}function re(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function B(e,t){if(!e.body){t.end();return}await v(_.fromWeb(e.body),t)}function V(e){return{upstreamBaseUrl:H(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:U(e.upstreamToken,`upstreamToken`),clientToken:U(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function H(t,n){try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`unsupported protocol`);return e.toString().replace(/\/+$/,``)}catch(r){throw new e(`INVALID_ARGS`,`Invalid ${n}`,{[n]:t},r)}}function U(t,n){let r=t.trim();if(!r)throw new e(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function W(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(E)?`/${t.slice(E.length)}`:t}function G(e,t){return e===`/rpc`?t===`POST`:q(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)||K(e)?t===`GET`:!1}function K(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function q(e,t){return e===`/upload`||J(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function J(e){return e===`/upload/preflight`}function Y(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function X(e,t,n){let a=new Headers;for(let t of D){let n=e.headers[t];typeof n==`string`&&n.trim()&&a.set(t,n)}n===`/rpc`&&!a.has(`content-type`)&&a.set(`content-type`,`application/json`),n===`/rpc`&&a.set(u,r);for(let[e,n]of Object.entries(i(t)))a.set(e,n);return a}function ie(e,t,n,r){if(e.method!==`GET`&&e.method!==`HEAD`)return t===`/rpc`?se(n??``,r):e}function ae(e,t,r){let i=oe(e,r);return i.length>0&&n(i,t)}function oe(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=ce(t);if(e)return e}return``}function se(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function ce(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Z(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function le(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function ue(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:t(new e(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function de(e,n){if(e.destroyed)return;if(e.headersSent){e.destroy(n instanceof Error?n:void 0);return}let r=t(n);e.statusCode=r.code===`INVALID_ARGS`?400:500,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const fe=async({positionals:t,flags:n})=>{if(t.length>0)throw new e(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await pe(n);return await h(n,r,()=>_e(r)),await ve(),!0};async function pe(t){let n=p({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:t.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await f(n),i=me(r.info.httpPort),o=Q(t),s=k({upstreamBaseUrl:i,upstreamToken:r.info.token,clientToken:o});await he(s,t.proxyHost?.trim()||`127.0.0.1`,t.proxyPort??0);let c=s.address();if(!c||typeof c==`string`)throw new e(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let l=`http://${ge(c.address)}:${c.port}`;return{proxyBaseUrl:l,agentDeviceBaseUrl:a(l),token:o,upstreamBaseUrl:i,stateDir:n.paths.baseDir}}function me(t){if(!t)throw new e(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${t}`}function Q(e){return e.daemonAuthToken?.trim()||ne(32).toString(`hex`)}function he(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ge(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function _e(e,t={}){let n=t.useColor??ee(),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(`
2
2
  `)}function $(e,t,n){return n?te(e,t,{validateStream:!1}):e}function ve(){return new Promise(()=>{})}export{fe as proxyCommand};
@@ -1 +1 @@
1
- import{O as e}from"./sdk-contracts.js";import{D as t}from"./sdk-batch-runner.js";import{E as n}from"./runtime.js";import{n as r}from"./catalog.js";import{n as i}from"./success-text.js";import{a,i as o}from"./request-runtime-binding.js";import{C as s,d as c,u as l}from"./session-snapshot.js";import{i as u}from"./platform-runtime-apple-resources.js";import{t as d}from"./snapshot-quality-verdict.js";import{o as f}from"./interaction-ref-policy.js";import{captureSnapshotForSession as p}from"./interaction.js";async function m(t){let{req:i,sessionName:s,sessionStore:l}=t;if(i.command!==r.reactNative)return null;let u=h(i.positionals??[]);if(!u.ok)return u.response;let f=l.get(s);if(!f)return a();let m=await c({device:f.device,command:`press`,requiresCapture:!1,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice,unavailableResponse:e=>o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`,void 0,e.hint?{hint:e.hint}:void 0)});if(!m.ok)return m.response;try{let e=await p(f,i.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(d(e.snapshotQuality))return _(e.snapshotQuality);let r=n(e.nodes),a=r.primaryAction;return a?await v(t,f,e,a,m.runtime):g(r.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:o(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?o(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...i(`No React Native overlay detected`)}}}function _(e){return o(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,r,a,c){let{req:d,sessionStore:p}=e,m=e.contextFromFlags(d.flags,n.appBundleId,n.trace?.outPath),h=l(c,m).tapPoint;if(!h)return o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`);let g=Date.now();s(n);let _=await h(a.point),v=Date.now(),x=await y(e,n),S=t({...u(r.nodes),..._,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:x.verified,verificationRequired:!x.verified,verificationWarning:x.verificationWarning,nextCommand:x.nextCommand,...i(b(x))});return f({session:n,sessionStore:p,command:d.command,positionals:d.positionals??[],flags:d.flags,result:S,responseData:S,actionStartedAt:g,actionFinishedAt:v})}async function y(e,t){let{req:r,sessionStore:i}=e,a=await p(t,r.flags,i,e.contextFromFlags,{interactiveOnly:!0});return d(a.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:n(a.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
1
+ import{M as e}from"./sdk-contracts.js";import{D as t}from"./sdk-batch-runner.js";import{C as n}from"./runtime.js";import{n as r}from"./catalog.js";import{n as i}from"./success-text.js";import{a,i as o}from"./request-runtime-binding.js";import{T as s,d as c,u as l}from"./session-snapshot.js";import{n as u}from"./touch-reference-frame.js";import{t as d}from"./snapshot-quality-verdict.js";import{o as f}from"./interaction-ref-policy.js";import{captureSnapshotForSession as p}from"./interaction.js";async function m(t){let{req:i,sessionName:s,sessionStore:l}=t;if(i.command!==r.reactNative)return null;let u=h(i.positionals??[]);if(!u.ok)return u.response;let f=l.get(s);if(!f)return a();let m=await c({device:f.device,command:`press`,requiresCapture:!1,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice,unavailableResponse:e=>o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`,void 0,e.hint?{hint:e.hint}:void 0)});if(!m.ok)return m.response;try{let e=await p(f,i.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(d(e.snapshotQuality))return _(e.snapshotQuality);let r=n(e.nodes),a=r.primaryAction;return a?await v(t,f,e,a,m.runtime):g(r.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:o(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?o(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...i(`No React Native overlay detected`)}}}function _(e){return o(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,r,a,c){let{req:d,sessionStore:p}=e,m=e.contextFromFlags(d.flags,n.appBundleId,n.trace?.outPath),h=l(c,m).tapPoint;if(!h)return o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`);let g=Date.now();s(n);let _=await h(a.point),v=Date.now(),x=await y(e,n),S=t({...u(r.nodes),..._,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:x.verified,verificationRequired:!x.verified,verificationWarning:x.verificationWarning,nextCommand:x.nextCommand,...i(b(x))});return f({session:n,sessionStore:p,command:d.command,positionals:d.positionals??[],flags:d.flags,result:S,responseData:S,actionStartedAt:g,actionFinishedAt:v})}async function y(e,t){let{req:r,sessionStore:i}=e,a=await p(t,r.flags,i,e.contextFromFlags,{interactiveOnly:!0});return d(a.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:n(a.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
@@ -1 +1 @@
1
- import{O as e,y as t}from"./sdk-contracts.js";import{l as n}from"./capture.js";import{D as r,w as i}from"./sdk-device.js";import{D as a,E as o,T as s}from"./sdk-batch.js";import{n as c,r as l}from"./recording-export-quality.js";import{r as u}from"./back-mode.js";import{c as d}from"./session-store.js";import{i as f}from"./output-path.js";import{n as p}from"./dispatch-resolve.js";import{n as m}from"./request-runtime-binding.js";import{a as h,t as g}from"./session-routing.js";import{a as _,i as v,o as y,s as b,t as x}from"./screen-recording-resource-recovery.js";import{t as S}from"./telemetry.js";import C from"node:path";function w(e){let r=n(`record`,e.flags);if(r)throw new t(`INVALID_ARGS`,r);let i=e.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new t(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=l(e.flags?.quality);if(e.flags?.quality!==void 0&&a===void 0)throw new t(`INVALID_ARGS`,`quality must be one of: ${c.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:T(e.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:e.flags?.hideTouches!==!0,hideTouchesRequested:e.flags?.hideTouches===!0}}function T(e){if(e===void 0)return`app`;if(e===`app`||e===`device`||e===`system`)return e;throw new t(`INVALID_ARGS`,`record scope must be app, device, or system`)}function E(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:g(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function D(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function O(e){return{action:`start`,...e.clientOutPath?{requestedFileName:C.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function k(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function A(e){let t=[j(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?S(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:C.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function j(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.outPath)}}async function M(t){try{return await N(t)}catch(t){return{ok:!1,error:e(t)}}}async function N(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=P(t,i);if(a.kind===`start`&&!u(o)&&!i)return E(t);let s=await F(e,i),{session:c}=s;return a.kind===`start`?await I(e,c,w(t),a.use,s.needsReadiness):await B(e,c,a.kind,s.needsReadiness)}function P(e,t){let n=T(e.flags?.recordingScope);return{scope:n,plan:s({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function F(e,t){let n=t?.device??await p(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t?{session:t,needsReadiness:!1}:{session:U(e,n),needsReadiness:!0}}async function I(e,t,n,r,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=await e.bindDevice(t.device,o);i&&await m(a);let s=a.facts.screenRecordingStart;if(!s.available)return k(s);let c=await e.bindDevice(t.device,r),{fence:l,outputPaths:u}=L(e,t),f=await c.operations.screenRecordingStart(R(e,t,n,l,u.outputPath));await v({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:c.owner,fence:l,...f,throwIfCanceled:e.throwIfCanceled});let p=e.sessionStore.get(e.sessionName)?.screenRecording;if(!p)throw TypeError(`Screen recording adoption did not publish a live handle`);let h=p.handle.inspect();return d(e.sessionStore,t,e.req,e.req.command,O(h)),D(h,e.sessionStore.ensureSessionDir(e.sessionName),u.requestedPath)}function L(e,t){let n=b.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName));return{fence:b.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:f({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function R(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:z(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function z(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function B(e,t,n,r){let i;try{i=n===`stop-live`?await _({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}):await H(e,t,r)}catch(n){throw V(e,t),n}let a=A(i);return d(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:i.outPath,...i.clientOutPath?{requestedFileName:C.basename(i.clientOutPath)}:{},showTouches:i.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),a}function V(e,t){if(!t.recordOnlySession)return;let n=b.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),r=b.store.read(n);r.status===`decoded`&&r.envelope.lifecycle===`completed`&&e.sessionStore.delete(e.sessionName)}async function H(e,n,o){let s=b.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),c=b.store.read(s);if(c.status!==`decoded`||c.envelope.lifecycle!==`open`)throw new t(`INVALID_ARGS`,`no active recording`);if(c.envelope.sessionId!==e.sessionName)throw new t(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!r(c.envelope.device,i(n.device)))throw new t(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`});return await y({resourcePath:s,scope:e.requestScope,acquireControl:async(t,r)=>{let i=await e.bindExactDevice(n.device,t.owner,t.fence,a,r);return o&&await m(i),x({runtime:i,dispose:async()=>{}})}})}function U(e,t){return{name:e.sessionName,sessionScope:h(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{M as t};
1
+ import{C as e,M as t}from"./sdk-contracts.js";import{c as n}from"./capture.js";import{H as r}from"./registry.js";import{D as i,w as a}from"./sdk-device.js";import{D as o,E as s,T as c}from"./sdk-batch.js";import{n as l,r as u}from"./recording-export-quality.js";import{c as d}from"./session-store.js";import{i as f}from"./output-path.js";import{n as p}from"./dispatch-resolve.js";import{n as m}from"./request-runtime-binding.js";import{a as h,t as g}from"./session-routing.js";import{a as _,i as v,o as y,s as b,t as x}from"./screen-recording-resource-recovery.js";import{t as S}from"./telemetry.js";import C from"node:path";function w(t){let r=n(`record`,t.flags);if(r)throw new e(`INVALID_ARGS`,r);let i=t.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new e(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(t.flags?.quality);if(t.flags?.quality!==void 0&&a===void 0)throw new e(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:T(t.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:t.flags?.hideTouches!==!0,hideTouchesRequested:t.flags?.hideTouches===!0}}function T(t){if(t===void 0)return`app`;if(t===`app`||t===`device`||t===`system`)return t;throw new e(`INVALID_ARGS`,`record scope must be app, device, or system`)}function E(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:g(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function D(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function O(e){return{action:`start`,...e.clientOutPath?{requestedFileName:C.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function k(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function A(e){let t=[j(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?S(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:C.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function j(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.outPath)}}async function M(e){try{return await N(e)}catch(e){return{ok:!1,error:t(e)}}}async function N(e){let{req:t,sessionName:n,sessionStore:i}=e,a=i.get(n),{plan:o,scope:s}=P(t,a);if(o.kind===`start`&&!r(s)&&!a)return E(t);let c=await F(e,a),{session:l}=c;return o.kind===`start`?await I(e,l,w(t),o.use,c.needsReadiness):await B(e,l,o.kind,c.needsReadiness)}function P(e,t){let n=T(e.flags?.recordingScope);return{scope:n,plan:c({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function F(e,t){let n=t?.device??await p(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t?{session:t,needsReadiness:!1}:{session:U(e,n),needsReadiness:!0}}async function I(e,t,n,r,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=await e.bindDevice(t.device,s);i&&await m(a);let o=a.facts.screenRecordingStart;if(!o.available)return k(o);let c=await e.bindDevice(t.device,r),{fence:l,outputPaths:u}=L(e,t),f=await c.operations.screenRecordingStart(R(e,t,n,l,u.outputPath));await v({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:c.owner,fence:l,...f,throwIfCanceled:e.throwIfCanceled});let p=e.sessionStore.get(e.sessionName)?.screenRecording;if(!p)throw TypeError(`Screen recording adoption did not publish a live handle`);let h=p.handle.inspect();return d(e.sessionStore,t,e.req,e.req.command,O(h)),D(h,e.sessionStore.ensureSessionDir(e.sessionName),u.requestedPath)}function L(e,t){let n=b.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName));return{fence:b.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:f({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function R(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:z(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function z(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function B(e,t,n,r){let i;try{i=n===`stop-live`?await _({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}):await H(e,t,r)}catch(n){throw V(e,t),n}let a=A(i);return d(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:i.outPath,...i.clientOutPath?{requestedFileName:C.basename(i.clientOutPath)}:{},showTouches:i.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),a}function V(e,t){if(!t.recordOnlySession)return;let n=b.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),r=b.store.read(n);r.status===`decoded`&&r.envelope.lifecycle===`completed`&&e.sessionStore.delete(e.sessionName)}async function H(t,n,r){let s=b.store.resolvePath(t.sessionStore.resolveSessionDir(t.sessionName)),c=b.store.read(s);if(c.status!==`decoded`||c.envelope.lifecycle!==`open`)throw new e(`INVALID_ARGS`,`no active recording`);if(c.envelope.sessionId!==t.sessionName)throw new e(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!i(c.envelope.device,a(n.device)))throw new e(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`});return await y({resourcePath:s,scope:t.requestScope,acquireControl:async(e,i)=>{let a=await t.bindExactDevice(n.device,e.owner,e.fence,o,i);return r&&await m(a),x({runtime:a,dispose:async()=>{}})}})}function U(e,t){return{name:e.sessionName,sessionScope:h(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{M as t};
@@ -1 +1 @@
1
- import{d as e}from"./sdk-contracts.js";const t=[`x`,`y`,`width`,`height`];function n(t){let n=r(t);if(!n)return null;let i=e(n);return!Number.isFinite(i.x)||!Number.isFinite(i.y)?null:i}function r(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function i(e,n){return!e||!n?!1:t.every(t=>Math.abs(e[t]-n[t])<=.5)}function a(e){return{x:o(e.x,e.width),y:o(e.y,e.height)}}function o(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}export{n as i,r as n,a as r,i as t};
1
+ import{p as e}from"./sdk-contracts.js";const t=[`x`,`y`,`width`,`height`];function n(t){let n=r(t);if(!n)return null;let i=e(n);return!Number.isFinite(i.x)||!Number.isFinite(i.y)?null:i}function r(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function i(e,n){return!e||!n?!1:t.every(t=>Math.abs(e[t]-n[t])<=.5)}function a(e){return{x:o(e.x,e.width),y:o(e.y,e.height)}}function o(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}export{n as i,r as n,a as r,i as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{t}from"./src2.js";import{i as n}from"./src4.js";const r=new Map;function i(e){for(let t of e.platforms){if(r.has(t))throw Error(`PlatformPlugin already registered for platform "${t}"`);r.set(t,e)}}function a(t){let n=r.get(t);if(!n)throw new e(`UNSUPPORTED_PLATFORM`,`Unsupported platform: ${t}`);return n}function o(e){return r.get(e)}const s=[t,{id:`android`,platforms:[`android`],providers:{platformGatedResolvers:[`androidAdbProvider`]},createInteractor:async(e,t)=>{let{createAndroidInteractor:n}=await import(`./android.js`).then(e=>e.t);return n(e,void 0,t)}},{id:`harmonyos`,platforms:[`harmonyos`],createInteractor:async(e,t)=>{let{createHarmonyInteractor:n}=await import(`./harmonyos.js`);return n(e,t)}},n,{id:`linux`,platforms:[`linux`],providers:{platformGatedResolvers:[`linuxToolProvider`]},createInteractor:async()=>{let{createLinuxInteractor:e}=await import(`./linux.js`);return e()}},{id:`web`,platforms:[`web`],providers:{platformGatedResolvers:[`webProvider`]},createInteractor:async()=>{let{createWebInteractor:e}=await import(`./web2.js`);return await e()}}];let c=!1;function l(){if(!c){for(let e of s)i(e);c=!0}}export{a as n,o as r,l as t};
1
+ import{C as e}from"./sdk-contracts.js";import{t}from"./src2.js";import{i as n}from"./src4.js";const r=new Map;function i(e){for(let t of e.platforms){if(r.has(t))throw Error(`PlatformPlugin already registered for platform "${t}"`);r.set(t,e)}}function a(t){let n=r.get(t);if(!n)throw new e(`UNSUPPORTED_PLATFORM`,`Unsupported platform: ${t}`);return n}function o(e){return r.get(e)}const s=[t,{id:`android`,platforms:[`android`],providers:{platformGatedResolvers:[`androidAdbProvider`]},createInteractor:async(e,t)=>{let{createAndroidInteractor:n}=await import(`./android.js`).then(e=>e.t);return n(e,void 0,t)}},{id:`harmonyos`,platforms:[`harmonyos`],createInteractor:async(e,t)=>{let{createHarmonyInteractor:n}=await import(`./harmonyos.js`);return n(e,t)}},n,{id:`linux`,platforms:[`linux`],providers:{platformGatedResolvers:[`linuxToolProvider`]},createInteractor:async()=>{let{createLinuxInteractor:e}=await import(`./linux.js`);return e()}},{id:`web`,platforms:[`web`],providers:{platformGatedResolvers:[`webProvider`]},createInteractor:async()=>{let{createWebInteractor:e}=await import(`./web2.js`);return await e()}}];let c=!1;function l(){if(!c){for(let e of s)i(e);c=!0}}export{a as n,o as r,l as t};