agent-device 0.18.0 → 0.18.2

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 (159) hide show
  1. package/README.md +3 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.0.apk → agent-device-android-multitouch-helper-0.18.2.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.2.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.0.manifest.json → agent-device-android-multitouch-helper-0.18.2.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.0.apk → agent-device-android-snapshot-helper-0.18.2.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.2.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.0.manifest.json → agent-device-android-snapshot-helper-0.18.2.manifest.json} +6 -6
  8. package/apple-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +156 -0
  9. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +10 -16
  10. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -0
  11. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +3 -1
  12. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +2 -0
  13. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +2 -4
  14. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +9 -36
  15. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +2 -0
  16. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +2 -0
  17. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -0
  18. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +2 -0
  19. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +0 -1
  20. package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +2 -1
  21. package/dist/src/1986.js +1 -0
  22. package/dist/src/2748.js +1 -1
  23. package/dist/src/2948.js +21 -21
  24. package/dist/src/314.js +1 -1
  25. package/dist/src/3340.js +8 -7
  26. package/dist/src/4418.js +1 -1
  27. package/dist/src/4428.js +3 -3
  28. package/dist/src/485.js +1 -0
  29. package/dist/src/495.js +5 -0
  30. package/dist/src/5484.js +1 -1
  31. package/dist/src/587.js +1 -1
  32. package/dist/src/5913.js +4 -0
  33. package/dist/src/6849.js +1 -0
  34. package/dist/src/6918.js +1 -1
  35. package/dist/src/6967.js +1 -0
  36. package/dist/src/760.js +1 -0
  37. package/dist/src/7871.js +1 -0
  38. package/dist/src/8184.js +1 -1
  39. package/dist/src/8225.js +1 -1
  40. package/dist/src/8391.js +1 -0
  41. package/dist/src/8404.js +2 -0
  42. package/dist/src/8414.js +2 -0
  43. package/dist/src/8875.js +4 -1
  44. package/dist/src/8936.js +1 -1
  45. package/dist/src/9581.js +3 -3
  46. package/dist/src/9624.js +1 -1
  47. package/dist/src/9722.js +37 -32
  48. package/dist/src/android-adb.d.ts +19 -54
  49. package/dist/src/android-adb.js +1 -1
  50. package/dist/src/android.js +5 -5
  51. package/dist/src/apps.js +9 -11
  52. package/dist/src/audio-probe.js +1 -0
  53. package/dist/src/batch.d.ts +34 -26
  54. package/dist/src/batch.js +1 -1
  55. package/dist/src/cli-help.js +61 -9
  56. package/dist/src/cli.js +34 -22
  57. package/dist/src/contracts.d.ts +33 -123
  58. package/dist/src/contracts.js +1 -1
  59. package/dist/src/debug-symbols.js +3 -0
  60. package/dist/src/devices.js +1 -1
  61. package/dist/src/devices~1.js +1 -1
  62. package/dist/src/devices~2.js +1 -1
  63. package/dist/src/find.js +1 -1
  64. package/dist/src/finders.d.ts +2 -6
  65. package/dist/src/finders.js +1 -1
  66. package/dist/src/generic.js +1 -9
  67. package/dist/src/handler-utils.js +1 -0
  68. package/dist/src/index.d.ts +474 -180
  69. package/dist/src/index.js +1 -1
  70. package/dist/src/input-actions.js +1 -1
  71. package/dist/src/input-actions~1.js +1 -1
  72. package/dist/src/install-source.d.ts +0 -26
  73. package/dist/src/install-source.js +1 -1
  74. package/dist/src/interaction.js +1 -1
  75. package/dist/src/interactor.js +1 -0
  76. package/dist/src/internal/bin.js +1 -1
  77. package/dist/src/internal/companion-tunnel.js +1 -1
  78. package/dist/src/internal/png-worker.js +1 -1
  79. package/dist/src/lease.js +1 -1
  80. package/dist/src/linux.js +1 -1
  81. package/dist/src/metro.d.ts +10 -134
  82. package/dist/src/metro.js +1 -1
  83. package/dist/src/notifications.js +1 -1
  84. package/dist/src/react-native.js +1 -1
  85. package/dist/src/record-trace-recording.js +3 -3
  86. package/dist/src/record-trace.js +1 -1
  87. package/dist/src/remote-config.d.ts +15 -17
  88. package/dist/src/remote-config.js +1 -1
  89. package/dist/src/runner-sequence.js +1 -0
  90. package/dist/src/selector-runtime.js +1 -1
  91. package/dist/src/selectors.d.ts +15 -7
  92. package/dist/src/selectors.js +1 -1
  93. package/dist/src/server.js +2 -2
  94. package/dist/src/session.js +11 -11
  95. package/dist/src/simulator.js +2 -2
  96. package/dist/src/snapshot.js +2 -2
  97. package/dist/src/web.js +1 -1
  98. package/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +297 -0
  99. package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +30 -0
  100. package/package.json +15 -11
  101. package/server.json +2 -2
  102. package/android-multitouch-helper/README.md +0 -41
  103. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.0.apk.sha256 +0 -1
  104. package/android-snapshot-helper/README.md +0 -88
  105. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.0.apk.sha256 +0 -1
  106. package/dist/src/1848.js +0 -4
  107. package/dist/src/2577.js +0 -1
  108. package/dist/src/2954.js +0 -2
  109. package/dist/src/4291.js +0 -1
  110. package/dist/src/432.js +0 -4
  111. package/dist/src/4723.js +0 -1
  112. package/dist/src/5341.js +0 -1
  113. package/dist/src/5910.js +0 -2
  114. package/dist/src/6024.js +0 -1
  115. package/dist/src/733.js +0 -1
  116. package/dist/src/7394.js +0 -6
  117. package/dist/src/8275.js +0 -2
  118. package/dist/src/9919.js +0 -6
  119. package/dist/src/android-snapshot-helper.d.ts +0 -359
  120. package/dist/src/android-snapshot-helper.js +0 -1
  121. package/dist/src/apple.js +0 -1
  122. package/dist/src/device-ready.js +0 -2
  123. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.swift +0 -17
  124. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AccentColor.colorset/Contents.json +0 -11
  125. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/Contents.json +0 -36
  126. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/logo.jpg +0 -0
  127. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Contents.json +0 -6
  128. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/Contents.json +0 -21
  129. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/logo.jpg +0 -0
  130. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/Contents.json +0 -21
  131. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/powered-by.png +0 -0
  132. package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/ContentView.swift +0 -34
  133. package/ios-runner/README.md +0 -53
  134. package/ios-runner/RUNNER_PROTOCOL.md +0 -76
  135. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
  136. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
  137. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
  138. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
  139. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
  140. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
  141. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
  142. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
  143. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
  144. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
  145. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
  146. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
  147. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
  148. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
  149. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
  150. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
  151. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
  152. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +0 -0
  153. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
  154. /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
  155. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
  156. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
  157. /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
  158. /package/dist/src/{4069.js → 4917.js} +0 -0
  159. /package/dist/src/{9836.js → 893.js} +0 -0
@@ -1,88 +0,0 @@
1
- # Android Snapshot Helper
2
-
3
- Small instrumentation APK used to capture Android accessibility snapshots without relying on
4
- `uiautomator dump`'s fixed idle wait behavior. The helper enables Android's interactive-window
5
- retrieval flag and serializes every accessible window root returned by `UiAutomation.getWindows()`
6
- so keyboards and system overlays can appear in the same snapshot. If interactive window roots are
7
- unavailable, it falls back to the active-window root.
8
-
9
- The helper is intentionally provider-neutral. Local `adb`, cloud ADB tunnels, and remote device
10
- providers can all install and run the same APK as long as they can execute ADB-style operations.
11
- Released helper APKs use the committed `debug.keystore`; do not rotate it casually, because Android
12
- requires a stable signing certificate for `adb install -r` upgrades.
13
-
14
- ## Build
15
-
16
- ```sh
17
- VERSION="$(node -p 'require("./package.json").version')"
18
- sh ./scripts/build-android-snapshot-helper.sh "$VERSION" .tmp/android-snapshot-helper
19
- ```
20
-
21
- The build uses Android SDK command-line tools directly. It expects `ANDROID_HOME` or
22
- `ANDROID_SDK_ROOT` to point at an SDK with `platforms/android-36` and matching build tools.
23
- `pnpm prepack` builds the npm-bundled helper into `android-snapshot-helper/dist`; npm users get
24
- that APK in the package and the first helper-backed `snapshot` installs it automatically when
25
- missing or outdated.
26
-
27
- ## Run
28
-
29
- ```sh
30
- VERSION="$(node -p 'require("./package.json").version')"
31
- adb install -r -t ".tmp/android-snapshot-helper/agent-device-android-snapshot-helper-$VERSION.apk"
32
- adb shell am instrument -w \
33
- -e waitForIdleTimeoutMs 500 \
34
- -e waitForIdleQuietMs 100 \
35
- -e timeoutMs 8000 \
36
- -e maxDepth 128 \
37
- -e maxNodes 5000 \
38
- com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation
39
- ```
40
-
41
- `maxDepth` also caps recursive traversal depth inside the helper.
42
- The `-t` install flag is required because the helper is a test-only instrumentation APK.
43
- Devices or providers that block test-package installs must allow this package before helper capture
44
- can run.
45
-
46
- `waitForIdleTimeoutMs` defaults to `500`, which is a maximum wait, not a fixed sleep. Direct helper
47
- invocations can pass `0` when immediate capture during ongoing animation is preferred.
48
-
49
- ## Output Contract
50
-
51
- The APK emits instrumentation status records using
52
- `agentDeviceProtocol=android-snapshot-helper-v1`.
53
-
54
- The XML node attributes intentionally mirror fields consumed by the host parser, including
55
- `visible-to-user`, `drawing-order`, bounds, text/description/id, interaction booleans, and window
56
- metadata on window roots. `drawing-order` lets the host suppress covered same-window surfaces that
57
- the helper traversal can receive even when they are not user-reachable. The helper emits
58
- `drawing-order` on Android API 24+ and omits it on API 23, where the platform API is unavailable.
59
-
60
- Each XML chunk is sent with:
61
-
62
- - `outputFormat=uiautomator-xml`
63
- - `chunkIndex`
64
- - `chunkCount`
65
- - `payloadBase64`
66
-
67
- The final instrumentation result includes:
68
-
69
- - `ok=true`
70
- - `helperApiVersion=1`
71
- - `waitForIdleTimeoutMs`
72
- - `waitForIdleQuietMs`
73
- - `timeoutMs`
74
- - `maxDepth`
75
- - `maxNodes`
76
- - `rootPresent`
77
- - `captureMode` (`interactive-windows` or `active-window`)
78
- - `windowCount`
79
- - `nodeCount`
80
- - `truncated`
81
- - `elapsedMs`
82
-
83
- Failures return `ok=false`, `errorType`, and `message` in the final result.
84
-
85
- The release manifest is a stable provider contract for the current helper protocol. Providers should
86
- resolve the APK from `apkUrl`, verify `sha256`, install using `installArgs`, and run
87
- `instrumentationRunner`. `installArgs` must start with `install`; extra arguments are limited to the
88
- allowlisted adb install flags `-r`, `-t`, `-d`, and `-g`, and the consumer appends the APK path.
@@ -1 +0,0 @@
1
- 1cb010ec7665c1610619f128504fc514b7cc53c04788e081e044bf755a518886 agent-device-android-snapshot-helper-0.18.0.apk
package/dist/src/1848.js DELETED
@@ -1,4 +0,0 @@
1
- import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./9612.js";import{readVersion as s,findProjectRoot as i}from"./1404.js";import{parseRect as a,parsePoint as l,isRecord as u}from"./5341.js";function f(s,a={}){var l,u;let c,p=(l=s,u=a,(c=(l??"").trim())?r(c,{env:u.env}):function(r={}){var s;let a,l,u,f=n.join(o("~",{env:r.env}),".agent-device"),c=r.projectRoot??i();return(s=c,t.existsSync(n.join(s,"package.json"))&&t.existsSync(n.join(s,"src","daemon.ts")))?n.join(f,"dev",(a=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(c),l=n.basename(a).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),u=e.createHash("sha1").update(a).digest("hex").slice(0,12),`${l||"agent-device"}-${u}`)):f}(u));return{baseDir:p,infoPath:n.join(p,"daemon.json"),lockPath:n.join(p,"daemon.lock"),logPath:n.join(p,"daemon.log"),sessionsDir:n.join(p,"sessions")}}function c(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function p(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function m(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function h(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let d=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,g=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,v=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function M(){let e=process.argv[1];return e?y(e):"unknown"}function y(r,o=i()){try{let s=n.resolve(o),i=[n.resolve(r)],a=new Set,l=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;l.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let u=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return S(e,d,t),S(e,g,t),[...t]}(u)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=j(r);if(o)return o;for(let e of v){let t=j(`${r}${e}`);if(t)return t}for(let e of v){let t=j(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let u=l.sort().join("|"),f=e.createHash("sha1").update(u).digest("hex");return`graph:${l.length}:${f}`}catch{return"unknown"}}function S(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function j(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let x=/^[A-Za-z0-9_@%+=:,./-]+$/;function b(e){return`'${e.replaceAll("'","'\\''")}'`}function $(e){return x.test(e)?e:b(e)}function D(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function _(e){return e.meta?.requestProgress==="replay-test"}function k(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function w(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function P(e){return`${JSON.stringify({type:"progress",event:e})}
2
- `}function R(e){return`${JSON.stringify({type:"response",response:e})}
3
- `}function z(e){return`${JSON.stringify({type:"response",response:e})}
4
- `}function A(e,t={}){return{ok:!0,service:e,version:s(),rpcProtocolVersion:1,...void 0!==t.upstream?{upstream:t.upstream}:{}}}function C(e){if(!u(e))return;let t="string"==typeof e.path?e.path:void 0,n=Array.isArray(e.overlayRefs)?e.overlayRefs.filter(E).flatMap(e=>{let t=function(e){if("string"!=typeof e.ref||0===e.ref.length)return;let t=function(e){let t=a(e.rect);if(!t)return;let n=a(e.overlayRect);if(!n)return;let r=l(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}(e);if(t){var n;return{ref:e.ref,..."string"==typeof(n=e).label&&n.label.length>0?{label:n.label}:{},...t}}}(e);return t?[t]:[]}):void 0;return{...t?{path:t}:{},...n?{overlayRefs:n}:{}}}function E(e){return u(e)}function O(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function T(e){let t=e?.snapshotDiagnostics?.samples;if(t&&0!==t.length)return N(t)}function N(e){if(0===e.length)return;let t=I(e);return{stats:t,...t.p95Ms>=1500?{warning:F(t)}:{}}}function H(e){let t=e.flatMap(e=>(function(e){if(!e||e.count<=0)return[];let t=e.platform;return 1===e.count?[{durationMs:e.maxMs,platform:t}]:2===e.count?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]})(e?.stats));if(0===t.length)return;let n=I(t);return{stats:n,...n.p95Ms>=1500?{warning:F(n)}:{}}}function K(e){if(!u(e))return;let t=function(e){if(!u(e))return;let t=function(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>"number"!=typeof e))return t}(e);if(t){var n;let r,o,s;return{...t,...(o="string"==typeof(n=e).platform?n.platform:void 0,s=u(n.backends)&&(r=Object.entries(n.backends).filter(e=>"number"==typeof e[1])).length>0?Object.fromEntries(r):void 0,{...o?{platform:o}:{},...s?{backends:s}:{}})}}}(e.stats);if(!t)return;let n="string"==typeof e.warning?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function I(e){let t,n=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:n.length,p50Ms:L(n,50),p95Ms:L(n,95),maxMs:n[n.length-1]??0,slowThresholdMs:1500,...1===new Set(t=e.map(e=>e.platform).filter(e=>!!e)).size?{platform:t[0]}:{},...function(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}(e)}}function L(e,t){if(0===e.length)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function F(e){let t=e.platform?`${e.platform} `:"";return`Warning: ${t}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}export{A as buildDaemonHealthPayload,y as computeDaemonCodeSignature,D as consumeTextLines,k as isDaemonProgressEnvelope,w as isDaemonResponseEnvelope,H as mergeSnapshotDiagnostics,h as normalizeTenantId,C as readScreenshotResultData,K as readSnapshotDiagnosticsSummary,O as recordSnapshotTiming,M as resolveDaemonCodeSignature,f as resolveDaemonPaths,c as resolveDaemonServerMode,p as resolveDaemonTransportPreference,m as resolveSessionIsolationMode,P as serializeDaemonProgressEnvelope,R as serializeDaemonResponseEnvelope,z as serializeDaemonRpcResponseEnvelope,b as shellQuote,$ as shellQuoteIfNeeded,_ as shouldStreamRequestProgress,T as summarizeSnapshotDiagnostics,N as summarizeSnapshotTimingSamples};
package/dist/src/2577.js DELETED
@@ -1 +0,0 @@
1
- import e from"node:crypto";import t,{promises as n}from"node:fs";import a from"node:path";import{Worker as r}from"node:worker_threads";import{fileURLToPath as i}from"node:url";import s from"node:os";import{buildMobileSnapshotPresentation as o,isSparseSnapshotQualityVerdict as l,renderSnapshotQualityWarnings as d,formatRole as u,isNodeVisibleInEffectiveViewport as c,publicSnapshotCaptureAnnotations as p,now as h,formatSnapshotLine as f,sleep as m,scrollCommand as w,appendScreenshotScriptFlags as g,successText as b,longPressCommand as y,displayLabel as k,focusCommand as v,swipeCommand as x,resolveInteractionTarget as A,toBackendResult as M,recordingQualityInputToExportQuality as S,toBackendContext as I,snapshotCaptureAnnotationsFrom as R,requireIntInRange as P,formatReactNativeOverlayWarning as N,pinchCommand as D,buildSnapshotDisplayLines as _}from"./2948.js";import{emitDiagnostic as O}from"./432.js";import{asAppError as E,toAppErrorCode as T,AppError as C}from"./733.js";import{computeScreenshotDiffPixels as U,PNG as L,toBuffer as $,decodePng as B}from"./4418.js";import{expandRect as q,intersectArea as G,unionRects as X,rectCenter as Y,clamp as F,normalizedRect as K,squaredDistance as j}from"./6024.js";import{whichCmd as H,runCmd as V}from"./8875.js";import{normalizeRef as z,findNodeByRef as W,buildSnapshotPresentationKey as J,usesMobileSnapshotPresentation as Z}from"./4291.js";import{findSelectorChainMatch as Q,extractNodeText as ee,findSnapshotAncestor as et,buildSelectorChainForNode as en,resolveSelectorChain as ea,findNodeByLabel as er,resolveRefLabel as ei,isNodeVisible as es,extractReadableText as eo,buildSnapshotNodeByIndex as el,formatSelectorFailure as ed,normalizeType as eu,isNodeEditable as ec,isFillableType as ep}from"./9836.js";import{parseFindSelectorExpression as eh,findBestMatchesByLocator as ef,parseSelectorChain as em}from"./587.js";import{isProcessAlive as ew,readProcessStartTime as eg}from"./9414.js";import{sleep as eb}from"./5560.js";import{resolveAppsFilter as ey,assertResolvedAppsFilter as ek}from"./2748.js";let ev=/^-?\d+(\.\d+)?$/,ex=/^[^\s"\\]+$/,eA=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),eM=new Map([["--count","count"],["--pause-ms","pauseMs"]]),eS=new Map([["--delay-ms","delayMs"]]);function eI(e){return"click"===e||"press"===e}function eR(e){return eI(e)||"longpress"===e}function eP(e){return"type"===e||"fill"===e}function eN(e){return e_(e,eO)}function eD(e){return JSON.stringify(e)}function e_(e,t){return t(e)?e:eD(e)}function eO(e){return eE(e)&&e.startsWith("@")||ev.test(e)}function eE(e){return ex.test(e)}function eT(e){let t=(e.positionals??[]).map(e=>eN(e));return[e.command,...t].join(" ")}function eC(e,t){let n=t.flags??{};if(eI(t.command)){"number"==typeof n.count&&e.push("--count",String(n.count)),"number"==typeof n.intervalMs&&e.push("--interval-ms",String(n.intervalMs)),"number"==typeof n.holdMs&&e.push("--hold-ms",String(n.holdMs)),"number"==typeof n.jitterPx&&e.push("--jitter-px",String(n.jitterPx)),!0===n.doubleTap&&e.push("--double-tap");let t=n.clickButton;t&&"primary"!==t&&e.push("--button",t);return}if("swipe"===t.command){"number"==typeof n.count&&e.push("--count",String(n.count)),"number"==typeof n.pauseMs&&e.push("--pause-ms",String(n.pauseMs)),("one-way"===n.pattern||"ping-pong"===n.pattern)&&e.push("--pattern",n.pattern);return}eP(t.command)&&"number"==typeof n.delayMs&&e.push("--delay-ms",String(n.delayMs))}function eU(e,t){t&&(("ios"===t.platform||"android"===t.platform)&&e.push("--platform",t.platform),"string"==typeof t.metroHost&&t.metroHost.length>0&&e.push("--metro-host",e_(t.metroHost,eE)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",e_(t.bundleUrl,eE)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",e_(t.launchUrl,eE)))}function eL(e,t){let n=[],a={},r=eI(e)?eA:"swipe"===e?eM:eP(e)?eS:void 0;for(let i=0;i<t.length;i+=1){let s=t[i];if(eI(e)&&"--double-tap"===s){a.doubleTap=!0;continue}let o=t[i+1];if(eI(e)&&"--button"===s&&void 0!==o){("primary"===o||"secondary"===o||"middle"===o)&&(a.clickButton=o),i+=1;continue}let l=r?.get(s);if(l&&void 0!==o){let e=eB(o);if(null!==e){a[l]=e,i+=1;continue}}if("swipe"===e&&"--pattern"===s&&void 0!==o){("one-way"===o||"ping-pong"===o)&&(a.pattern=o),i+=1;continue}n.push(s)}return{positionals:n,flags:a}}function e$(e){let t=[],n={};for(let a=0;a<e.length;a+=1){let r=e[a],i=e[a+1];if("--platform"===r&&void 0!==i){("ios"===i||"android"===i)&&(n.platform=i),a+=1;continue}if("--metro-host"===r&&void 0!==i){n.metroHost=i,a+=1;continue}if("--metro-port"===r&&void 0!==i){let e=eB(i);null!==e&&(n.metroPort=e),a+=1;continue}if("--bundle-url"===r&&void 0!==i){n.bundleUrl=i,a+=1;continue}if("--launch-url"===r&&void 0!==i){n.launchUrl=i,a+=1;continue}t.push(r)}return{positionals:t,flags:n}}function eB(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function eq(e){var t;let n=[],a={};for(let t of e){if("--relaunch"===t){a.relaunch=!0;continue}n.push(t)}let r=e$(n);return{positionals:r.positionals,flags:a,runtime:(t=r.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?r.flags:void 0}}function eG(e,t={}){let n=[e.command];if("snapshot"===e.command)e.flags?.snapshotInteractiveOnly&&n.push("-i"),"number"==typeof e.flags?.snapshotDepth&&n.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&n.push("-s",eN(e.flags.snapshotScope)),e.flags?.snapshotRaw&&n.push("--raw");else if("open"===e.command){for(let t of e.positionals??[])n.push(eN(t));e.flags?.relaunch&&n.push("--relaunch"),eU(n,e.runtime)}else if("runtime"===e.command)!function(e,t,n={}){let a=t.positionals??[];for(let t of n.includeAllPositionals?a:a.slice(0,1))e.push(e_(t,eE));eU(e,t.flags)}(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals});else if("record"===e.command)!function(e,t){let[n,...a]=t.positionals??[];for(let t of(n&&e.push(e_(n,eE)),a))e.push(eN(t));"number"==typeof t.flags?.fps&&e.push("--fps",String(t.flags.fps)),"number"==typeof t.flags?.screenshotMaxSize&&e.push("--max-size",String(t.flags.screenshotMaxSize)),("number"==typeof t.flags?.quality||"string"==typeof t.flags?.quality)&&e.push("--quality",String(t.flags.quality)),t.flags?.hideTouches&&e.push("--hide-touches")}(n,e);else if("screenshot"===e.command){for(let t of e.positionals??[])n.push(eN(t));g(n,e.flags)}else{for(let t of e.positionals??[])n.push(eN(t));eC(n,e)}return n.join(" ")}function eX(t,n){let a=e.createHash("sha256").update(t).digest(),r=e.createHash("sha256").update(n).digest();return e.timingSafeEqual(a,r)}let eY=["status","get","dismiss","enter","return"];function eF(e){return eY.includes(e)}function eK(e){let t=e?.trim().split(/\s+/,1)[0];if(!t||!t.startsWith("@")||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}class ej extends Error{}let eH=null,eV=!1,ez=!1,eW=0,eJ=new Map;function eZ(e){eV=!0,ez||(ez=!0,O({level:"warn",phase:"png_worker_unavailable",data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function eQ(e){let t=eJ.get(e.id);t&&(eJ.delete(e.id),e2(),e.ok?t.resolve(e.result):t.reject(new C(T(e.error.code),e.error.message,e.error.details)))}function e0(e,t){eH===e&&(eZ(t.message),eH=null,e.terminate().catch(()=>{}),e1(new ej(`PNG worker failed: ${t.message}`)))}function e1(e){let t=[...eJ.values()];for(let n of(eJ.clear(),t))n.reject(e)}function e2(){eH&&(eJ.size>0?eH.ref():eH.unref())}function e4(){if(eV)return null;if(eH)return eH;let e=function(e,n){try{let r=i(e),s=a.extname(r)||".js";return[a.join(a.dirname(r),`${n}${s}`),a.join(a.dirname(r),"internal",`${n}${s}`)].find(e=>t.existsSync(e))??null}catch{return null}}(import.meta.url,"png-worker");if(!e)return eZ("worker entry module not found next to the current module"),null;try{let t=new r(e,{execArgv:e.endsWith(".ts")?["--experimental-strip-types"]:[]});return t.on("message",eQ),t.on("error",e=>{e0(t,e)}),t.on("exit",e=>{e0(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),eH=t,t}catch(e){return eZ(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}async function e3(e,t){try{return await function(e){let t=e4();if(!t)return Promise.reject(new ej("PNG worker is unavailable"));let n=eW+=1;return new Promise((a,r)=>{eJ.set(n,{resolve:a,reject:r}),e2();try{t.postMessage({...e,id:n})}catch(e){eJ.delete(n),e2(),r(new ej(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}(e)}catch(e){if(e instanceof ej)return t();throw e}}function e5(){e4()}async function e8(){let e=eH;eH=null,e1(new ej("PNG worker terminated")),e&&await e.terminate()}async function e6(e,t){let n=await e3({kind:"decode",png:e,label:t},()=>{let n=B(e,t);return{kind:"decode",width:n.width,height:n.height,data:n.data}});return new L({width:n.width,height:n.height,data:$(n.data)})}async function e9(e){return $((await e3({kind:"encode",width:e.width,height:e.height,data:e.data},()=>({kind:"encode",png:L.sync.write(e)}))).png)}async function e7(e){let{kind:t,...n}=await e3({kind:"diff-pixels",...e},()=>({kind:"diff-pixels",...U(e)}));return{...n,diffData:$(n.diffData)}}let te=[0,187,255,255];function tt(e,t,n,a){if(t<0||t>=e.width||n<0||n>=e.height)return;let r=(n*e.width+t)*4;e.data[r]=a[0],e.data[r+1]=a[1],e.data[r+2]=a[2],e.data[r+3]=a[3]}function tn(e,t,n){return Math.min(Math.max(e,t),n)}let ta=[{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}];function tr(e){let{mask:t,width:n,height:a,hooks:r}=e,i=new Uint8Array(t.length),s=new Int32Array(t.length),o=[];for(let e=0;e<t.length;e+=1){var l,d;if(!ti(t,i,e))continue;let u=0,c=(l=s,i[d=e]=1,l[0]=d,1),p=r.create(e);for(;u<c;){let e=s[u];u+=1,r.visit(p,e),c=function(e){let{mask:t,visited:n,queue:a,width:r,height:i,pixelIndex:s}=e,o=s%r,l=Math.floor(s/r),d=e.queueEnd;for(let e of ta){var u,c,p,h;let s=o+e.x,f=l+e.y;if(u=s,c=f,p=r,h=i,!(u>=0)||!(u<p)||!(c>=0)||!(c<h))continue;let m=f*r+s;ti(t,n,m)&&(d=function(e,t,n,a){return t[a]=1,e[n]=a,n+1}(a,n,d,m))}return d}({mask:t,visited:i,queue:s,queueEnd:c,width:n,height:a,pixelIndex:e})}o.push(p)}return o}function ti(e,t,n){return 1===e[n]&&1!==t[n]}let ts={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},to={leading:20,trailing:20,separator:10,unknown:0,background:-30};function tl(e){return"background"!==e.likelyKind}function td(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function tu(e,t){let n,a=0;for(let r of t){let t=tm(e,r.rect);t<=a||(a=t,n=r)}return n}function tc(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,a;return t=e.rect,tm(t,a=n.rect)>0||Math.abs(Y(t).y-Y(a).y)<=.5*Math.max(t.height,a.height)});if(!e){t.push({rect:n.rect,blocks:[n]});continue}e.blocks.push(n),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=X([e.rect,n.rect])}return t}function tp(e,t){let n,a=Y(e);for(let e of t){let t=Math.sqrt(j(a,Y(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function th(e){let t=tf(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function tf(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function tm(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function tw(e){if(await H("tesseract"))try{let[t,n]=await Promise.all([tb(e.baselinePath),tb(e.currentPath)]);if(0!==t.exitCode||0!==n.exitCode)return;let a=tg(t.stdout,e.width,e.height),r=tg(n.stdout,e.width,e.height),i=function(e,t){let n=new Set,a=[];for(let i of e){var r;let e=tM(i.text),s=function(e,t,n,a){let r=null,i=1/0;for(let s=0;s<n.length;s+=1){if(a.has(s))continue;let o=n[s];if(tM(o.text)!==t)continue;let l=Y(e.normalizedRect),d=j(l,Y(o.normalizedRect));d>=i||(r=s,i=d)}return r}(i,e,t,n);if(null===s)continue;n.add(s);let o=function(e,t){let n={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},a=tR(t.rect.width/e.rect.width),r=tR(t.rect.height/e.rect.height),i=Math.abs(a-1)>=.08||Math.abs(r-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:n,confidence:Math.round(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:i}}(i,t[s]);r=o,(Math.abs(r.delta.x)>=2||Math.abs(r.delta.y)>=2||Math.abs(r.delta.width)>=2||Math.abs(r.delta.height)>=2||r.possibleTextMetricMismatch)&&a.push(o)}return a.sort((e,t)=>ty(t)-ty(e)).slice(0,12)}(a,r),s=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(n.delta.x-tS(e.map(e=>e.delta.x))));e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(tk).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>tv(t)-tv(e)).slice(0,4)}(i);if(0===a.length&&0===r.length)return;return{provider:"tesseract",baselineBlocks:a.length,currentBlocks:r.length,baselineBlocksRaw:a,currentBlocksRaw:r,matches:i,...s.length>0?{movementClusters:s}:{}}}catch{return}}function tg(e,t,n){let[a,...r]=e.split(/\r?\n/);if(!a)return[];let i=new Map(a.split(" ").map((e,t)=>[e,t])),s=[];for(let e of r){var o;if(!e.trim())continue;let t=e.split(" "),n=tA(t,i,"level"),a=tx(t,i,"text").trim(),r=tA(t,i,"conf");if(5!==n||(o=a,!/[\p{L}\p{N}]/u.test(o))||r<0)continue;let l=tA(t,i,"left"),d=tA(t,i,"top"),u=tA(t,i,"width"),c=tA(t,i,"height");u<=0||c<=0||s.push({key:[tx(t,i,"page_num"),tx(t,i,"block_num"),tx(t,i,"par_num"),tx(t,i,"line_num")].join(":"),text:a,confidence:r,rect:{x:l,y:d,width:u,height:c}})}let l=new Map;for(let e of s){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),n=[],a=[];for(let e of t){let t=a.at(-1);if(!t){a.push(e);continue}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){n.push(a),a=[e];continue}a.push(e)}return a.length>0&&n.push(a),n})(e)).map(e=>(function(e,t,n){if(0===e.length)return null;let a=[...e].sort((e,t)=>e.rect.x-t.rect.x),r=X(a.map(e=>e.rect)),i=Math.round(100*tS(a.map(e=>e.confidence)))/100;return{text:a.map(e=>e.text).join(" "),confidence:i,rect:r,normalizedRect:K({x:tI(r.x/t),y:tI(r.y/n),width:tI(r.width/t),height:tI(r.height/n)})}})(e,t,n)).filter(e=>null!==e)}function tb(e){return V("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function ty(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function tk(e){let t=e.map(e=>e.delta.x),n=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...n),max:Math.max(...n)}}}function tv(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function tx(e,t,n){let a=t.get(n);return void 0===a?"":e[a]??""}function tA(e,t,n){let a=Number(tx(e,t,n));return Number.isFinite(a)?a:0}function tM(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function tS(e){return e.reduce((e,t)=>e+t,0)/e.length}function tI(e){return Math.round(100*e*100)/100}function tR(e){return Math.round(1e3*e)/1e3}function tP(e,t,n,a){return{r:Math.round(e/a),g:Math.round(t/a),b:Math.round(n/a)}}function tN(e){return .2126*e.r+.7152*e.g+.0722*e.b}function tD(e){return`#${t_(e.r)}${t_(e.g)}${t_(e.b)}`}function t_(e){return e.toString(16).padStart(2,"0")}function tO(e){return Math.round(100*e*100)/100}let tE=255*Math.sqrt(3);async function tT(e,t,r={}){var i,s,o,l,d;let u,c,p,h;await tC(e,"Baseline image not found"),await tC(t,"Current screenshot not found");let f=r.outputPath,[m,w]=await Promise.all([n.readFile(e),n.readFile(t)]),[g,b]=await Promise.all([e6(m,"baseline screenshot"),e6(w,"current screenshot")]);tU(g.width,g.height,"baseline screenshot",r.maxPixels),tU(b.width,b.height,"current screenshot",r.maxPixels);let y=r.threshold??.1;if(g.width!==b.width||g.height!==b.height){let e=g.width*g.height;return await tL(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:g.width,height:g.height},actual:{width:b.width,height:b.height}}}}let k=g.width*g.height,{diffData:v,diffMask:x,differentPixels:A}=await e7({width:g.width,height:g.height,baselineData:g.data,currentData:b.data,maxColorDistance:y*tE}),M=A>0?(s=(u=function(e){let{diffMask:t,baseline:n,current:a}=e,{width:r,height:i}=n;return tr({mask:t,width:r,height:i,hooks:{create:e=>{var t,n;let a,i;return a=(t=e)%(n=r),{minX:a,minY:i=Math.floor(t/n),maxX:a,maxY:i,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}},visit:(e,t)=>{var i,s,o,l,d;let u,c,p;return i=e,s=t,o=r,l=n,d=a,u=s%o,c=Math.floor(s/o),p=4*s,void(i.minX=Math.min(i.minX,u),i.minY=Math.min(i.minY,c),i.maxX=Math.max(i.maxX,u),i.maxY=Math.max(i.maxY,c),i.differentPixels+=1,i.baselineRed+=l.data[p],i.baselineGreen+=l.data[p+1],i.baselineBlue+=l.data[p+2],i.currentRed+=d.data[p],i.currentGreen+=d.data[p+1],i.currentBlue+=d.data[p+2])}}})}(i={diffMask:x,baseline:g,current:b,totalPixels:k,differentPixels:A,maxRegions:r.maxRegions})).length<=2e3?function(e){let t=[];for(let r of e.sort((e,t)=>{let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX})){var n,a;let e=t.find(e=>{var t,n,a;return t=e,n=r,a=12,t.minX-a<=n.maxX&&n.minX-a<=t.maxX&&t.minY-a<=n.maxY&&n.minY-a<=t.maxY});if(!e){t.push({...r});continue}n=e,a=r,n.minX=Math.min(n.minX,a.minX),n.minY=Math.min(n.minY,a.minY),n.maxX=Math.max(n.maxX,a.maxX),n.maxY=Math.max(n.maxY,a.maxY),n.differentPixels+=a.differentPixels,n.baselineRed+=a.baselineRed,n.baselineGreen+=a.baselineGreen,n.baselineBlue+=a.baselineBlue,n.currentRed+=a.currentRed,n.currentGreen+=a.currentGreen,n.currentBlue+=a.currentBlue}return t}(u):u,s.flatMap(e=>{var t,n,a;let r;return(t=e,n=i.baseline.width,a=i.baseline.height,r=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*a))&&r>=.35*n)?function(e,t,n){var a;let r=function(e,t){let n=[],a=null;for(let r=0;r<e.length;r+=1){if(e[r]<=t){a??=r;continue}null!==a&&(r-a>=6&&n.push([a,r-1]),a=null)}return null!==a&&e.length-a>=6&&n.push([a,e.length-1]),n}((a=function(e,t,n){let a=[];for(let r=e.minY;r<=e.maxY;r+=1){let i=0;for(let a=e.minX;a<=e.maxX;a+=1)1===t[r*n+a]&&(i+=1);a.push(i)}return a}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let n=0,r=0,i=Math.max(0,t-3),s=Math.min(a.length-1,t+3);for(let e=i;e<=s;e+=1)n+=a[e],r+=1;return Math.round(n/r)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),i=function(e,t,n){let a=[],r=e.minY;for(let[i,s]of t){let t=e.minY+Math.round((i+s)/2);t-r+1<n||e.maxY-t<n||(a.push([r,t]),r=t+1)}return a.push([r,e.maxY]),a}(e,r,n);if(i.length<=1)return[e];let s=i.map(([n,a])=>(function(e,t,n,a){let r=null;for(let o=t;o<=n;o+=1)for(let t=e.minX;t<=e.maxX;t+=1){var i,s;let e=o*a.baseline.width+t;1===a.diffMask[e]&&function(e,t,n,a,r,i){let s=4*t;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,a),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,a),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=i.data[s],e.currentGreen+=i.data[s+1],e.currentBlue+=i.data[s+2]}(r??={minX:i=t,minY:s=o,maxX:i,maxY:s,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,o,a.baseline,a.current)}return r})(e,n,a,t)).filter(e=>null!==e);return s.length>1?s:[e]}(e,i,Math.max(24,Math.round(.03*i.baseline.height))):[e]})).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(0!==n)return n;let a=e.minY-t.minY;return 0!==a?a:e.minX-t.minX}).slice(0,Math.max(0,i.maxRegions??8)).map((e,t)=>{var n,a,r,s,o,l,d,u,c,p,h;let f,m,w,g,b,y,k,v,x,A,M,S,I,R,P,N,D;return n=e,a=t+1,r={width:i.baseline.width,height:i.baseline.height,totalPixels:i.totalPixels,differentPixels:i.differentPixels},y={x:n.minX,y:n.minY,width:n.maxX-n.minX+1,height:n.maxY-n.minY+1},k={x:Math.round(n.minX+y.width/2),y:Math.round(n.minY+y.height/2)},v=tP(n.baselineRed,n.baselineGreen,n.baselineBlue,n.differentPixels),x=tP(n.currentRed,n.currentGreen,n.currentBlue,n.differentPixels),A=y.width*y.height,M=tO(n.differentPixels/A),S=Math.round(tN(v)),I=Math.round(tN(x)),R=(s=y,o=r.width,l=r.height,s.width>=.55*o&&s.height>=.12*l?"large-area":s.width>=2.5*s.height?"horizontal-band":s.height>=2.5*s.width?"vertical-band":"compact"),P=(f=A/r.totalPixels)>=.04?"large":f>=.01?"medium":"small",N=(d=v,u=x,m=tN(d),Math.abs(w=tN(u)-m)>=12?w>0?"brighter":"darker":Math.max(Math.abs(u.r-d.r),Math.abs(u.g-d.g),Math.abs(u.b-d.b))>=12?"color-shift":"mixed"),D=(c=k,p=r.width,h=r.height,g=c.x<p/3?"left":c.x>2*p/3?"right":"center",b=c.y<h/3?"top":c.y>2*h/3?"bottom":"middle","center"===g&&"middle"===b?"center":`${b}-${g}`),{index:a,rect:y,normalizedRect:K({x:tO(y.x/r.width),y:tO(y.y/r.height),width:tO(y.width/r.width),height:tO(y.height/r.height)}),differentPixels:n.differentPixels,shareOfDiffPercentage:tO(n.differentPixels/r.differentPixels),densityPercentage:M,shape:R,size:P,location:D,averageBaselineColorHex:tD(v),averageCurrentColorHex:tD(x),baselineLuminance:S,currentLuminance:I,dominantChange:N}}):[];if(A>0&&f){let e=new L({width:g.width,height:g.height,data:v});for(let t of M)t.rect.width<4||t.rect.height<4||function(e,t){let n=tn(t.x,0,e.width-1),a=tn(t.y,0,e.height-1),r=tn(t.x+t.width-1,0,e.width-1),i=tn(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let s=n;s<=r;s+=1)tt(e,s,a+t,te),tt(e,s,i-t,te);for(let s=a;s<=i;s+=1)tt(e,n+t,s,te),tt(e,r-t,s,te)}}(e,t.rect);await n.mkdir(a.dirname(f),{recursive:!0}),await n.writeFile(f,await e9(e))}else await tL(r.outputPath);let S=A>0?await tw({baselinePath:e,currentPath:t,width:g.width,height:g.height}):void 0,I=S&&(S.matches.length>0||(S.movementClusters?.length??0)>0)?{provider:S.provider,baselineBlocks:S.baselineBlocks,currentBlocks:S.currentBlocks,matches:S.matches,...S.movementClusters?{movementClusters:S.movementClusters}:{}}:void 0,R=A>0&&S?(c=function(e){let t=[];for(let n of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,a,r;return t=e,a=n,r=10,t.minX-r<=a.maxX&&a.minX-r<=t.maxX&&t.minY-r<=a.maxY&&a.minY-r<=t.maxY});if(!e){t.push({...n});continue}e.minX=Math.min(e.minX,n.minX),e.minY=Math.min(e.minY,n.minY),e.maxX=Math.max(e.maxX,n.maxX),e.maxY=Math.max(e.maxY,n.maxY),e.differentPixels+=n.differentPixels}return t}((l=function(e,t,n,a){let r=new Uint8Array(e);if(!a)return r;for(let e of[...a.baselineBlocksRaw,...a.currentBlocksRaw])!function(e,t,n,a){let r=F(Math.floor(a.x),0,t-1),i=F(Math.floor(a.y),0,n-1),s=F(Math.ceil(a.x+a.width),0,t),o=F(Math.ceil(a.y+a.height),0,n);for(let n=i;n<o;n+=1)for(let a=r;a<s;a+=1)e[n*t+a]=0}(r,t,n,q(e.rect,8));return r}((o={diffMask:x,width:g.width,height:g.height,regions:M,ocr:S}).diffMask,o.width,o.height,o.ocr),d=o.width,tr({mask:l,width:d,height:o.height,hooks:{create:e=>{var t,n;let a,r;return a=(t=e)%(n=d),{minX:a,minY:r=Math.floor(t/n),maxX:a,maxY:r,differentPixels:0}},visit:(e,t)=>{var n,a,r;let i,s;return n=e,i=(a=t)%(r=d),s=Math.floor(a/r),void(n.minX=Math.min(n.minX,i),n.minY=Math.min(n.minY,s),n.maxX=Math.max(n.maxX,i),n.maxY=Math.max(n.maxY,s),n.differentPixels+=1)}}}))),p=tc(o.ocr?.currentBlocksRaw??[]),h=tc(o.ocr?.baselineBlocksRaw??[]),c.filter(th).map(e=>{var t,n,a,r,i,s,l,d,u,c,f;let m,w,g,b,y,k,v,x,A,M;return t=e,n=o,a=p,r=h,b=function(e,t){let n,a=0;for(let r of t){let t=G(e,r.rect);t<=a||(a=t,n=r)}return n?.index}(g=tf(t),n.regions),y=function(e,t,n){let a=tu(e,t);if(a)return tp(e,a.blocks);let r=tu(e,n);return r?tp(e,r.blocks):void 0}(g,a,r),k=function(e,t,n){if(e.height<=3&&e.width>=.12*n)return"separator";if(!t)return e.width>=.4*n?"background":"unknown";if(e.width>=.4*n)return"background";let a=e.x+e.width/2,r=t.x+t.width/2;return a<r-t.width/2?"leading":a>r+t.width/2?"trailing":e.width>=.35*n?"background":"unknown"}(g,y?.block.rect,n.width),v=(i=g,s=k,l=t.differentPixels,d=n,m=i.width/i.height,w=l/(i.width*i.height),"separator"===s?"separator":"background"===s?"background":"trailing"===s&&m>=1.5&&m<=3.8&&w>=.35?"toggle":"trailing"===s&&i.width<=.06*d.width&&i.height<=.04*d.height?"chevron":"leading"===s&&m>=.55&&m<=1.8?"icon":td(i,d)?"background":"visual"),x={...b?{regionIndex:b}:{},slot:k,likelyKind:v,rect:g},{...b?{regionIndex:b}:{},slot:k,likelyKind:v,rect:g,...y?{nearestText:y.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(u=x,c=t.differentPixels,f=n,A=td(u.rect,f)?-35:0,M=20*!!u.regionIndex,ts[u.likelyKind]+to[u.slot]+M+A+Math.min(20,c/200))}}).filter(e=>e.rect.y>=.08*o.height).filter(tl).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,o.maxDeltas??12)).map((e,t)=>{var n;return n=e,{index:t+1,...n.regionIndex?{regionIndex:n.regionIndex}:{},slot:n.slot,likelyKind:n.likelyKind,rect:n.rect,...n.nearestText?{nearestText:n.nearestText}:{}}})):[],P=k>0?Math.round(A/k*1e4)/100:0;return{...A>0&&f?{diffPath:f}:{},...M.length>0?{regions:M}:{},...I?{ocr:I}:{},...R.length>0?{nonTextDeltas:R}:{},totalPixels:k,differentPixels:A,mismatchPercentage:P,match:0===A}}async function tC(e,t){try{await n.access(e)}catch{throw new C("INVALID_ARGS",`${t}: ${e}`)}}function tU(e,t,n,a){if(null==a||a<=0)return;let r=e*t;if(!(r<=a))throw new C("INVALID_ARGS",`${n} is ${r} pixels, which exceeds the configured maxImagePixels limit of ${a}`)}async function tL(e){if(e)try{await n.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function t$(e){return e.width*e.height}function tB(e){return Math.round(100*e*100)/100}async function tq(e,t,n){if("path"===t.kind&&!e.policy.allowLocalInputPaths)throw new C("INVALID_ARGS",`Local ${n.field??"input"} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,n)}catch(e){throw E(e)}}async function tG(e,t,n){if(t?.kind==="path"&&!e.policy.allowLocalOutputPaths)throw new C("INVALID_ARGS","Local output paths are not allowed by command policy");try{return await e.artifacts.reserveOutput(t,{...n,visibility:n.visibility??"client-visible",requestedClientPath:t?.kind==="downloadableArtifact"?t.clientPath??n.requestedClientPath:n.requestedClientPath})}catch(e){throw E(e)}}async function tX(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw E(e)}}let tY=async(e,t)=>{let n,a,r;if(!t.baseline)throw new C("INVALID_ARGS","diff screenshot requires a baseline image");let i=function(e){if(null==e||""===e)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new C("INVALID_ARGS","--threshold must be a number between 0 and 1");return t}(t.threshold),s=t.current??{kind:"live"};if(t.overlayRefs&&!tW(s))throw new C("INVALID_ARGS","diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs");let o=await tq(e,t.baseline,{usage:"diff screenshot baseline",field:"baseline"}),l=[];try{let d;d=tW(s)?(a=await tF(e,t)).path:(n=await tq(e,s,{usage:"diff screenshot current",field:"current"})).path,r=t.out?await tG(e,t.out,{field:"diffPath",ext:".png"}):void 0;let u=await tT(o.path,d,{threshold:i,outputPath:r?.path,maxPixels:e.policy.maxImagePixels});tW(s)&&(u=await tK(e,t,r?.path,u,l));let c=u.diffPath?await r?.publish():void 0;return c&&l.push(c),u.diffPath||await r?.cleanup?.(),{...u,...l.length>0?{artifacts:l}:{}}}catch(e){throw await r?.cleanup?.(),e}finally{await o.cleanup?.(),await n?.cleanup?.(),await a?.cleanup?.()}};async function tF(e,t){let n=await tX(e,{prefix:"agent-device-diff-current",ext:".png"});try{await tj(e,t,n.path,tH(t))}catch(e){throw await n.cleanup(),e}return n}async function tK(e,t,n,a,r){var i,s,o,l;if(!t.overlayRefs)return a;if(a.match||a.dimensionMismatch)return n&&await tz(n),a;let d=(i=t,s=n,i.currentOverlayOut?i.currentOverlayOut:i.out?.kind==="path"?{kind:"path",path:tV(s??i.out.path)}:i.out?.kind==="downloadableArtifact"?{kind:"downloadableArtifact",...i.out.clientPath?{clientPath:tV(i.out.clientPath)}:{},...i.out.fileName?{fileName:tV(i.out.fileName)}:{}}:void 0),u=await tG(e,d,{field:"currentOverlayPath",ext:".png"});try{let n=await tj(e,t,u.path,{overlayRefs:!0,...tH(t)}),i=await u.publish();return i&&r.push(i),{...a,currentOverlayPath:n.path??u.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...a.regions&&n.overlayRefs?{regions:(o=a.regions,l=n.overlayRefs,o.map(e=>{var t,n;let a,r=(t=e,n=l,a=t$(t.rect),n.map(e=>{let n=e.overlayRect,r=G(t.rect,n);return r<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:n,overlayCoveragePercentage:tB(r/t$(n)),regionCoveragePercentage:tB(r/a)}}).filter(e=>null!==e).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==n?n:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return r.length>0?{...e,currentOverlayMatches:r}:e}))}:{}}}catch(e){throw await u.cleanup?.(),e}}async function tj(e,t,n,a={}){if(!e.backend.captureScreenshot)throw new C("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},n,a)??{}}function tH(e){return e.surface?{surface:e.surface}:{}}function tV(e){let t=a.extname(e),n=t?e.slice(0,-t.length):e;return`${n}.current-overlay${t||".png"}`}async function tz(e){try{await n.unlink(tV(e))}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function tW(e){return"live"===e.kind}async function tJ(e,t){if(!Number.isInteger(t)||t<1)throw new C("INVALID_ARGS","Screenshot max size must be a positive integer");let a=await e6(await n.readFile(e),"screenshot"),r=Math.max(a.width,a.height);if(r<=t)return;let i=t/r,s=Math.max(1,Math.round(a.width*i)),o=Math.max(1,Math.round(a.height*i)),l=function(e,t,n){let a=new L({width:t,height:n});for(let r=0;r<n;r+=1){let i=r*e.height/n,s=(r+1)*e.height/n;for(let n=0;n<t;n+=1){let o=n*e.width/t,l=(n+1)*e.width/t,d=0,u=0,c=0,p=0,h=0;for(let t=Math.floor(i);t<Math.ceil(s);t+=1){let n=Math.min(t+1,s)-Math.max(t,i);for(let a=Math.floor(o);a<Math.ceil(l);a+=1){let r=n*(Math.min(a+1,l)-Math.max(a,o)),i=(t*e.width+a)*4;d+=(e.data[i]??0)*r,u+=(e.data[i+1]??0)*r,c+=(e.data[i+2]??0)*r,p+=(e.data[i+3]??0)*r,h+=r}}let f=(r*a.width+n)*4;a.data[f]=Math.round(d/h),a.data[f+1]=Math.round(u/h),a.data[f+2]=Math.round(c/h),a.data[f+3]=Math.round(p/h)}}return a}(a,s,o);await n.writeFile(e,await e9(l))}let tZ=async(e,t)=>{let n;if(!e.backend.captureScreenshot)throw new C("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");let a=await tG(e,t.out,{field:"path",ext:".png"});try{await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,appId:t.appId,appBundleId:t.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},a.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,stabilize:t.stabilize,surface:t.surface}),void 0!==t.maxSize&&await tJ(a.path,t.maxSize),n=await a.publish()}catch(e){throw await a.cleanup?.(),e}return{path:a.path,...n?{artifacts:[n]}:{},...b(`Saved screenshot: ${a.path}`)}};function tQ(e,t){let n=u(e.type??"Element"),a=k(e,n),r=!1===e.enabled?"disabled":"enabled",i=!0===e.selected?"selected":"unselected",s=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),n,a,r,i,s].join("|")}function t0(e,t){return t.flatten?e.map(e=>({text:f(e,0,!1),comparable:tQ(e,0)})):_(e).map(e=>({text:e.text,comparable:tQ(e.node,e.depth)}))}function t1(e,t){return e.get(t)??0}function t2(e){return e.map(e=>({index:e.index,depth:e.depth,parentIndex:e.parentIndex,type:e.type,role:e.role,subrole:e.subrole,label:e.label,value:e.value,identifier:e.identifier,enabled:e.enabled,selected:e.selected,focused:e.focused,hittable:e.hittable,rect:e.rect,bundleId:e.bundleId,appName:e.appName,windowTitle:e.windowTitle,surface:e.surface,hiddenContentAbove:e.hiddenContentAbove,hiddenContentBelow:e.hiddenContentBelow,interactionBlocked:e.interactionBlocked,presentationHints:e.presentationHints}))}let t4=async(e,t)=>{var n;let a,r,i=await t5(e,t),s=function(e){var t,n,a,r,i;let{previous:s,current:o,options:l,identity:d}=e;if(!0===l.forceFull||!0===l.raw||!s||!1===s.comparisonSafe||!1===o.comparisonSafe||(t=s,n=o,a=d,t.backend&&n.backend&&t.backend!==n.backend||a?.previousAppBundleId&&a.currentAppBundleId&&a.previousAppBundleId!==a.currentAppBundleId)||!s.presentationKey||s.presentationKey!==o.presentationKey||(r=s,i=o,r.truncated!==i.truncated||JSON.stringify(t2(r.nodes))!==JSON.stringify(t2(i.nodes))))return;let u=l.scope?.trim();return{ageMs:Math.max(0,o.createdAt-s.createdAt),nodeCount:o.nodes.length,...!0===l.interactiveOnly?{interactiveOnly:!0}:{},...u?{scope:u}:{}}}({previous:i.session?.snapshot,current:i.snapshot,options:t,identity:{previousAppBundleId:i.session?.appBundleId,currentAppBundleId:i.result.appBundleId??i.session?.appBundleId}});return await e.sessions.set(t8(t.session,i)),{nodes:i.snapshot.nodes,truncated:i.snapshot.truncated??!1,visibility:function(e){let{nodes:t,backend:n,snapshotRaw:a}=e;if(a||!Z(n))return{partial:!1,visibleNodeCount:t.length,totalNodeCount:t.length,reasons:[]};let r=o(t),i=new Set;return r.hiddenCount>0&&i.add("offscreen-nodes"),r.nodes.some(e=>e.hiddenContentAbove)&&i.add("scroll-hidden-above"),r.nodes.some(e=>e.hiddenContentBelow)&&i.add("scroll-hidden-below"),{partial:i.size>0,visibleNodeCount:r.nodes.length,totalNodeCount:t.length,reasons:[...i]}}({nodes:i.snapshot.nodes,backend:i.snapshot.backend,snapshotRaw:t.raw}),...p({...i.annotations,warnings:i.warnings}),...s?{unchanged:s}:{},...i.result.snapshotDiagnostics?{snapshotDiagnostics:i.result.snapshotDiagnostics}:{},...(a=(n=i).result.appName??n.session?.appName,r=n.result.appBundleId??n.session?.appBundleId,{...a||r?{appName:a??r}:{},...r?{appBundleId:r}:{}})}},t3=async(e,t)=>{let n=await t5(e,t),a=!0===t.interactiveOnly,r=n.session?.snapshot,i=t8(t.session,n);if(!r){let t=function(e,t={}){return t0(e,t).length}(n.snapshot.nodes,{flatten:a});return await e.sessions.set(i),{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let s=function(e,t,n={}){let a=function(e,t){let n=e.length,a=t.length,r=n+a,i=new Map,s=[];i.set(1,0);for(let o=0;o<=r;o+=1){s.push(new Map(i));for(let r=-o;r<=o;r+=2){let l=r===-o||r!==o&&t1(i,r-1)<t1(i,r+1)?t1(i,r+1):t1(i,r-1)+1,d=l-r;for(;l<n&&d<a&&e[l].comparable===t[d].comparable;)l+=1,d+=1;if(i.set(r,l),l>=n&&d>=a)return function(e,t,n,a,r){let i=[],s=a,o=r;for(let a=e.length-1;a>=0;a-=1){let r=e[a],l=s-o,d=l===-a||l!==a&&t1(r,l-1)<t1(r,l+1)?l+1:l-1,u=t1(r,d),c=u-d;for(;s>u&&o>c;)i.push({kind:"unchanged",text:n[o-1].text}),s-=1,o-=1;if(0===a)break;s===u?(i.push({kind:"added",text:n[c].text}),o=c):(i.push({kind:"removed",text:t[u].text}),s=u)}return i.reverse(),i}(s,e,t,n,a)}}return[]}(t0(e,n),t0(t,n)),r={additions:0,removals:0,unchanged:0};for(let e of a)"added"===e.kind&&(r.additions+=1),"removed"===e.kind&&(r.removals+=1),"unchanged"===e.kind&&(r.unchanged+=1);return{summary:r,lines:a}}(r.nodes,n.snapshot.nodes,{flatten:a});return await e.sessions.set(i),{mode:"snapshot",baselineInitialized:!1,summary:s.summary,lines:s.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}};async function t5(e,t){var n,a,r,i,s,o,l;let u,c,p,f,m;if(!e.backend.captureSnapshot)throw new C("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let w=t.session??"default",g=await e.sessions.get(w),b=await e.backend.captureSnapshot({session:w,requestId:t.requestId,appId:g?.appId,appBundleId:g?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,depth:t.depth,scope:t.scope,raw:t.raw}),y=(a=b,r=e,n=a.snapshot?a.snapshot:{nodes:a.nodes??[],truncated:a.truncated,backend:a.backend,createdAt:h(r)},n.presentationKey?n:{...n,presentationKey:J(t)}),k=R(b),v=h(e);return{snapshot:y,result:b,session:g,annotations:k,warnings:(u=[...(i={result:b,annotations:k,snapshot:y,options:t,session:g,capturedAt:y.createdAt??v,runtimeNow:v}).annotations.warnings??[]],i.annotations.quality&&u.push(...d(i.annotations.quality,i.snapshot.nodes)),u.push(...function(e){let t=e.annotations.analysis;if("android"!==e.snapshot.backend||!0!==e.options.interactiveOnly||e.snapshot.nodes.length>0||!t||(t.rawNodeCount??0)<12)return[];let n=[`Interactive snapshot is empty after filtering ${t.rawNodeCount} raw Android nodes. Likely causes: the app content is not accessibility-visible yet, a transient route change, or depth/filter options hid the target.`];return"number"==typeof e.options.depth&&"number"==typeof t.maxDepth&&t.maxDepth>=e.options.depth+2&&n.push(`Interactive output is empty at depth ${e.options.depth}; retry without -d.`),n}(i)),i.annotations.quality||(u.push(...function(e){if("xctest"!==e.snapshot.backend||!0!==e.options.interactiveOnly||1!==e.snapshot.nodes.length)return[];let t=e.snapshot.nodes[0];return t?.type!=="Application"?[]:["iOS interactive snapshot exposed only the application root. XCTest accessibility queries can fail to enumerate some simulator UI trees even when screenshots and direct gestures still work. Use screenshot as visual truth, try a scoped/full snapshot for diagnostics, and prefer direct selectors when known."]}(i)),u.push(...(c=new Set((s=i.snapshot.nodes).map(e=>e.parentIndex).filter(e=>void 0!==e)),s.filter(e=>!(c.has(e.index)||(e.type?.toLowerCase()??"").includes("text"))&&(e.label??"").split(", ").length>10).map(e=>{let t=(e.label??"").split(", ").length,n=e.identifier?` (${e.identifier})`:"";return`@${e.ref} [${e.type??"element"}]${n} merges ~${t} labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`})))),(p=function(e){if(e?.backend!=="uiautomator-dump")return;let t=e.fallbackReason?` Reason: ${e.fallbackReason}`:"";return`Android snapshot helper unavailable; using stock UIAutomator dump, which can time out on busy React Native UIs.${t}`}(i.annotations.androidSnapshot))&&u.push(p),(f=N(i.snapshot.nodes))&&u.push(f),(m=function(e){var t,n,a,r,i,s;let o=e.session?.snapshot;if(!e.annotations.freshness&&o&&(t=o,n=e.snapshot,void 0===t.presentationKey||void 0===n.presentationKey||t.presentationKey===n.presentationKey)&&(a=o,r=e.capturedAt,[r,e.runtimeNow].some(e=>{let t=e-a.createdAt;return t>=0&&t<=2e3}))&&(i=o.nodes.length,s=e.snapshot.nodes.length,!(i<12)&&s<=Math.floor(.2*i)))return t6}(i))&&u.push(m),u.push(...(o=i.annotations.freshness,l=i.snapshot.backend,o?.staleAfterRetries&&"android"===l?"stuck-route"===o.reason?[`Recent ${o.action} was followed by a nearly identical snapshot after ${o.retryCount} automatic retr${1===o.retryCount?"y":"ies"}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`]:"sharp-drop"===o.reason?[t6]:[]:[])),Array.from(new Set(u)))}}function t8(e,t){let n=t.session?.name??e??"default";return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}let t6="Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.",t9=async(e,t)=>await nn(e,t,"press"),t7=async(e,t)=>await nn(e,t,"click"),ne=async(e,t)=>{var n;if(!t.text)throw new C("INVALID_ARGS","fill requires text");let a=await ni(e,t);if(a)return a;let r=await A(e,t,{action:"fill",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.fill)throw new C("UNSUPPORTED_OPERATION","fill is not supported by this backend");let i=na(r),s=M(await e.backend.fill(I(e,t),i,t.text,{delayMs:t.delayMs})),o="node"in r?r.node?.type??"":"",l=o&&!ep(o,e.backend.platform)?`fill target ${n=r,n.target?.kind==="ref"?n.target.ref:n.target?.kind==="selector"?n.target.selector:"point"} resolved to "${o}", attempting fill anyway.`:void 0;return{...r,text:t.text,...l?{warning:l}:{},...s?{backendResult:s}:{}}},nt=async(e,t)=>{let n=t.text;if(!n)throw new C("INVALID_ARGS","type requires text");let a=eK(n);if(a)throw new C("INVALID_ARGS",`type does not accept a target ref like "${a}"`,{hint:`Use fill ${a} "text" to target that field, or press ${a} then type "text" to append.`});if(!e.backend.typeText)throw new C("UNSUPPORTED_OPERATION","type is not supported by this backend");let r=P(t.delayMs??0,"delay-ms",0,1e4),i=M(await e.backend.typeText(I(e,t),n,{delayMs:r}));return{kind:"text",text:n,delayMs:r,...i?{backendResult:i}:{},...b(`Typed ${Array.from(n).length} chars`)}};async function nn(e,t,n){let a=await nr(e,t,n);if(a)return a;let r=await A(e,t,{action:n,requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.tap)throw new C("UNSUPPORTED_OPERATION","tap is not supported by this backend");let i=na(r),s=M(await e.backend.tap(I(e,t),i,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return{...r,...s?{backendResult:s}:{}}}function na(e){if(!e.point)throw new C("COMMAND_FAILED","Interaction target resolved without coordinates");return e.point}async function nr(e,t,n){var a;if("click"!==n||"ref"!==t.target.kind||!e.backend.tapTarget||void 0!==(a=t).count||void 0!==a.intervalMs||void 0!==a.holdMs||void 0!==a.jitterPx||void 0!==a.doubleTap||void 0!==a.button&&"primary"!==a.button)return null;let r=M(await e.backend.tapTarget(I(e,t),{kind:"ref",ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}}));return{kind:"ref",target:{kind:"ref",ref:t.target.ref},...r?{backendResult:r}:{}}}async function ni(e,t){if("ref"!==t.target.kind||!e.backend.fillTarget)return null;let n=M(await e.backend.fillTarget(I(e,t),{kind:"ref",ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}},t.text,{delayMs:t.delayMs}));return{kind:"ref",target:{kind:"ref",ref:t.target.ref},text:t.text,...n?{backendResult:n}:{}}}function ns(e){return["visible","hidden","exists","editable","selected","text"].includes(e)}function no(e){let{predicate:t,node:n,nodes:a,expectedText:r,platform:i}=e,s=ee(n),o=ec(n,i),l=!0===n.selected,d="text"===t?es(n):function(e,t,n){var a,r,i;let s;if("android"===n&&!1===e.visibleToUser)return!1;if(nl(e.rect))return function(e,t){return c(e,t)}(e,t);if(e.rect)return!1;if("android"!==n&&!0===e.hittable)return!0;let o=(a=e,r=t,i=n,s=el(r),et(r,a,s,e=>!function(e,t){if("android"===t&&!1===e.visibleToUser)return!1;let n=eu(e.type??"");return!(n.includes("application")||n.includes("window")||n.includes("scrollview")||n.includes("tableview")||n.includes("collectionview"))&&"table"!==n&&"list"!==n&&"listview"!==n&&("android"===t?!0===e.hittable&&nl(e.rect):!0===e.hittable||nl(e.rect))}(e,i)?null:e));return!!o&&(nl(o.rect)?function(e,t){return c(e,t)}(o,t):"android"!==n&&!0===o.hittable)}(n,a,i),u=!1;switch(t){case"visible":u=d;break;case"hidden":u=!d;break;case"editable":u=o;break;case"selected":u=l;break;case"text":u=s===(r??"")}let p="text"===t?`expected="${r??""}" actual="${s}"`:`actual=${JSON.stringify({visible:d,editable:o,selected:l})}`;return{pass:u,actualText:s,details:p}}function nl(e){return!!(e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&e.width>0&&e.height>0)}async function nd(e,t){let n=t??"default",a=await e.sessions.get(n);if(!a)throw new C("SESSION_NOT_FOUND","No active session. Run open first.");if(!a.snapshot)throw new C("INVALID_ARGS","No snapshot in session. Run snapshot first.");return{sessionName:n,session:a,snapshot:a.snapshot}}async function nu(e,t,n={updateSession:!0}){let a=e.backend.captureSnapshot;if(!a)throw new C("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",i=await e.sessions.get(r),s=await a(I(e,t),{interactiveOnly:!1,depth:t.depth,scope:n.scope??t.scope,raw:t.raw,includeRects:n.includeRects}),o=s.snapshot??{nodes:s.nodes??[],truncated:s.truncated,backend:s.backend,...s.quality?{snapshotQuality:s.quality}:{},createdAt:h(e)};return n.updateSession&&i&&!l(o.snapshotQuality)&&await e.sessions.set({...i,snapshot:o}),{sessionName:r,session:i,snapshot:o}}async function nc(e,t,n){if(e.backend.readText){let a=await e.backend.readText(I(e,{session:t.sessionName}),n);if(a.text.trim())return a.text}return eo(n)}let np=async(e,t)=>{let n=t.locator??"any";if(!t.query)throw new C("INVALID_ARGS","find requires a value");if("wait"===t.action)return await nv(e,t,n);let{capture:a,match:r}=await nx(e,t,n);if(!r)throw new C("COMMAND_FAILED","find did not match any element");if("exists"===t.action)return{kind:"found",found:!0};let i=`@${r.ref}`;return"get_attrs"===t.action?{kind:"attrs",ref:i,node:r}:{kind:"text",ref:i,text:await nc(e,a,r),node:r}},nh=async(e,t)=>{if("ref"===t.target.kind){let n=await nd(e,t.session),a=function(e,t,n){let a=z(t);if(!a)throw new C("INVALID_ARGS",n.invalidRefMessage);let r=W(e,a)??(n.fallbackLabel.length>0?er(e,n.fallbackLabel):null);if(!r)throw new C("COMMAND_FAILED",n.notFoundMessage);return{ref:a,node:r}}(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??"",invalidRefMessage:"get text requires a ref like @e2",notFoundMessage:`Ref ${t.target.ref} not found`}),r=en(a.node,e.backend.platform,{action:"get"}),i={kind:"ref",ref:`@${a.ref}`};return"attrs"===t.property?{kind:"attrs",target:i,node:a.node,selectorChain:r}:{kind:"text",target:i,text:await nc(e,n,a.node),node:a.node,selectorChain:r}}let n=await nI(e,t,t.session??"default",{selector:t.target.selector,disambiguateAmbiguous:"text"===t.property}),a=en(n.node,e.backend.platform,{action:"get"});if("attrs"===t.property)return{kind:"attrs",target:{kind:"selector",selector:n.selector},node:n.node,selectorChain:a};let r=await nc(e,n.capture,n.node);return{kind:"text",target:{kind:"selector",selector:n.selector},text:r,node:n.node,selectorChain:a}},nf=async(e,t)=>{let n=await nh(e,{...t,property:"text",target:t.target});if("text"!==n.kind)throw new C("COMMAND_FAILED","getText returned non-text result");return n},nm=async(e,t)=>{let n=await nh(e,{...t,property:"attrs",target:t.target});if("attrs"!==n.kind)throw new C("COMMAND_FAILED","getAttrs returned non-attrs result");return n},nw=async(e,t)=>{var n;if(!ns(t.predicate))throw new C("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");if("text"===t.predicate&&!t.expectedText)throw new C("INVALID_ARGS","is text requires expected text value");let a="visible"===(n=t.predicate)||"hidden"===n,r=await nu(e,t,{updateSession:!0,includeRects:a}),i=em(t.selector);if("exists"===t.predicate){let n=Q(r.snapshot.nodes,i,{platform:e.backend.platform});if(!n)throw new C("COMMAND_FAILED",ed(i,[],{unique:!1}));return{predicate:t.predicate,pass:!0,selector:n.selector.raw,matches:n.matches,selectorChain:i.selectors.map(e=>e.raw)}}let s=ea(r.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!s)throw new C("COMMAND_FAILED",ed(i,[],{unique:!0}),{command:"is",reason:"selector_not_found",predicate:t.predicate,selector:i.raw});let o=no({predicate:t.predicate,node:s.node,nodes:r.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!o.pass)throw new C("COMMAND_FAILED",`is ${t.predicate} failed for selector ${s.selector.raw}: ${o.details}`,{command:"is",reason:"predicate_failed",predicate:t.predicate,selector:s.selector.raw,predicateDetails:o.details});return{predicate:t.predicate,pass:!0,selector:s.selector.raw,..."text"===t.predicate?{text:o.actualText}:{},selectorChain:i.selectors.map(e=>e.raw)}},ng=async(e,t)=>await nw(e,{...t,predicate:"visible",selector:t.target.selector}),nb=async(e,t)=>await nw(e,{...t,predicate:"hidden",selector:t.target.selector}),ny=async(e,t)=>{if("sleep"===t.target.kind)return await m(e,t.target.durationMs),{kind:"sleep",waitedMs:t.target.durationMs};if("ref"===t.target.kind){let n=await nd(e,t.session),a=z(t.target.ref);if(!a)throw new C("INVALID_ARGS",`Invalid ref: ${t.target.ref}`);let r=W(n.snapshot.nodes,a),i=r?ei(r,n.snapshot.nodes):void 0;if(!i)throw new C("COMMAND_FAILED",`Ref ${t.target.ref} not found or has no label`);return await nM(e,t,i,t.target.timeoutMs)}if("selector"===t.target.kind)return await nA(e,t,t.target.selector,t.target.timeoutMs);if(!t.target.text)throw new C("INVALID_ARGS","wait requires text");return await nM(e,t,t.target.text,t.target.timeoutMs)},nk=async(e,t)=>{let n=await ny(e,{...t,target:{kind:"text",text:t.text,timeoutMs:t.timeoutMs}});if("text"!==n.kind)throw new C("COMMAND_FAILED","waitForText returned non-text result");return n};async function nv(e,t,n){let a=t.timeoutMs??1e4,r=h(e);for(;h(e)-r<a;){let{match:a}=await nx(e,t,n);if(a)return{kind:"found",found:!0,waitedMs:h(e)-r};await m(e,300)}throw new C("COMMAND_FAILED","find wait timed out")}async function nx(e,t,n){let a=eh(n,t.query),r=await nu(e,t,{updateSession:!0,scope:function(e,t,n,a){if(!a&&"web"!==e.backend.platform)return"text"===t||"label"===t||"any"===t?n:void 0}(e,n,t.query,a)});if(l(r.snapshot.snapshotQuality))throw new C("COMMAND_FAILED","find could not read the current accessibility tree",{reason:r.snapshot.snapshotQuality.reason,hint:"The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen."});if(a){let t=ea(r.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!1,requireUnique:!1});return{capture:r,match:t?.node}}let i=ef(r.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0];return{capture:r,match:i}}async function nA(e,t,n,a){let r=a??1e4,i=h(e),s=em(n);for(;h(e)-i<r;){let n=Q((await nu(e,t,{updateSession:!0})).snapshot.nodes,s,{platform:e.backend.platform});if(n)return{kind:"selector",selector:n.selector.raw,waitedMs:h(e)-i};await m(e,300)}throw new C("COMMAND_FAILED",`wait timed out for selector: ${n}`)}async function nM(e,t,n,a){let r=a??1e4,i=h(e);for(;h(e)-i<r;){if(e.backend.findText?(await e.backend.findText(I(e,t),n)).found:await nS(e,t,n))return{kind:"text",text:n,waitedMs:h(e)-i};await m(e,300)}throw new C("COMMAND_FAILED",`wait timed out for text: ${n}`)}async function nS(e,t,n){return!!er((await nu(e,t,{updateSession:!0})).snapshot.nodes,n)}async function nI(e,t,n,a){let r=await nu(e,{...t,session:n},{updateSession:!0}),i=em(a.selector),s=ea(r.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:a.disambiguateAmbiguous});if(!s)throw new C("COMMAND_FAILED",ed(i,[],{unique:!0}));return{capture:r,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}function nR(e,t){if(void 0!==e)return nP(e,t)}function nP(e,t){let n=e?.trim();if(!n)throw new C("INVALID_ARGS",`${t} must be a non-empty string`);return n}let nN=async(e,t={})=>{if(!e.backend.listDevices)throw new C("UNSUPPORTED_OPERATION","admin.devices is not supported by this backend");return{kind:"adminDevices",devices:await e.backend.listDevices(I(e,t),t.filter)}},nD=async(e,t={})=>{if(!e.backend.bootDevice)throw new C("UNSUPPORTED_OPERATION","admin.boot is not supported by this backend");let n=nB(t.target),a=M(await e.backend.bootDevice(I(e,t),n));return{kind:"deviceBooted",...n?{target:n}:{},...a?{backendResult:a}:{},...b("Booted device")}},n_=async(e,t={})=>{if(!e.backend.shutdownDevice)throw new C("UNSUPPORTED_OPERATION","admin.shutdown is not supported by this backend");let n=nB(t.target),a=M(await e.backend.shutdownDevice(I(e,t),n));return{kind:"deviceShutdown",...n?{target:n}:{},...a?{backendResult:a}:{},...b("Shutdown device")}},nO=async(e,t)=>await nC(e,t,"install"),nE=async(e,t)=>await nC(e,t,"reinstall"),nT=async(e,t)=>await nC(e,t,"installFromSource");async function nC(e,t,n){let a="reinstall"===n?"reinstallApp":"installApp",r=e.backend[a];if(!r)throw new C("UNSUPPORTED_OPERATION",`admin.${n} is not supported by this backend`);let i="app"in t&&void 0!==t.app?nP(t.app,"app"):void 0;if("installFromSource"!==n&&!i)throw new C("INVALID_ARGS",`admin.${n} requires app`);let s=I(e,t),o=await nU(e,s,t.source);try{var l,d,u,c,p;let t,a,h,f,m,w,g,y,k=await r.call(e.backend,s,{...i?{app:i}:{},source:o.source});return l=n,d=i,u=o.source,c=k,t=M(c),a=nq(c,"appName"),h=nq(c,"appId"),f=nq(c,"bundleId"),m=nq(c,"packageName"),w=nq(c,"launchTarget"),g=nq(c,"installablePath"),y=nq(c,"archivePath"),{kind:"reinstall"===l?"appReinstalled":"installFromSource"===l?"appInstalledFromSource":"appInstalled",...d?{app:d}:{},source:u,...h?{appId:h}:{},...a?{appName:a}:{},...f?{bundleId:f}:{},...m?{packageName:m}:{},...w?{launchTarget:w}:{},...g?{installablePath:g}:{},...y?{archivePath:y}:{},...t?{backendResult:t}:{},...b(`${"reinstall"===l?"Reinstalled":"Installed"}: ${a??w??d??(p=u,"path"===p.kind?p.path:"uploadedArtifact"===p.kind?p.id:p.url)}`)}}finally{await o.cleanup?.()}}async function nU(e,t,n){let a=n$(n),r=await nL(e,a);try{let n=e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source;return{source:n$(n),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function nL(e,t){if("url"===t.kind)return{source:t};let n=await tq(e,t,{usage:"admin.install",field:"source"});return{source:{kind:"path",path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function n$(e){if(!e||"object"!=typeof e)throw new C("INVALID_ARGS","install source is required");if("path"===e.kind)return{kind:"path",path:nP(e.path,"source.path")};if("uploadedArtifact"===e.kind)return{kind:"uploadedArtifact",id:nP(e.id,"source.id")};if("url"===e.kind){let t=nP(e.url,"source.url");return function(e){let t;try{t=new URL(e)}catch{throw new C("INVALID_ARGS",`Invalid install source URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new C("INVALID_ARGS","Install source URL must use http or https")}(t),{kind:"url",url:t}}throw new C("INVALID_ARGS","install source kind must be path, uploadedArtifact, or url")}function nB(e){if(!e)return;let t=nR(e.id,"target.id"),n=nR(e.name,"target.name"),a={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...void 0!==e.headless?{headless:e.headless}:{}};return Object.keys(a).length>0?a:void 0}function nq(e,t){let n=e[t];return"string"==typeof n&&n.length>0?n:void 0}let nG=/^[A-Za-z0-9_.:-]{1,64}$/,nX=async(e,t)=>{var n;if(!e.backend.openApp)throw new C("UNSUPPORTED_OPERATION","apps.open is not supported by this backend");let a=function(e){var t;let n=nR(e.app,"app"),a=nR(e.appId,"appId"),r=nR(e.bundleId,"bundleId"),i=nR(e.packageName,"packageName"),s=nR(e.url,"url"),o=nR(e.activity,"activity"),l={...n?{app:n}:{},...a?{appId:a}:{},...r?{bundleId:r}:{},...i?{packageName:i}:{},...s?{url:s}:{},...o?{activity:o}:{}};if(!((t=l).app??t.appId??t.bundleId??t.packageName??t.url??t.activity))throw new C("INVALID_ARGS","apps.open requires app, appId, bundleId, packageName, url, or activity");return l}(t),r=M(await e.backend.openApp(nW(e,t),a,{launchArgs:t.launchArgs,relaunch:t.relaunch}));return{kind:"appOpened",target:a,relaunch:!0===t.relaunch,...r?{backendResult:r}:{},...b(`Opened: ${(n=a).app??n.appId??n.bundleId??n.packageName??n.url??n.activity??"app"}`)}},nY=async(e,t={})=>{if(!e.backend.closeApp)throw new C("UNSUPPORTED_OPERATION","apps.close is not supported by this backend");let n=nR(t.app,"app"),a=M(await e.backend.closeApp(nW(e,t),n));return{kind:"appClosed",...n?{app:n}:{},...a?{backendResult:a}:{},...b(n?`Closed: ${n}`:"Closed app")}},nF=async(e,t={})=>{if(!e.backend.listApps)throw new C("UNSUPPORTED_OPERATION","apps.list is not supported by this backend");return{kind:"appsList",apps:await e.backend.listApps(nW(e,t),ek(t.filter))}},nK=async(e,t)=>{if(!e.backend.getAppState)throw new C("UNSUPPORTED_OPERATION","apps.state is not supported by this backend");let n=nP(t.app,"app"),a=await e.backend.getAppState(nW(e,t),n);return{kind:"appState",app:n,state:a}},nj=async(e,t)=>{if(!e.backend.pushFile)throw new C("UNSUPPORTED_OPERATION","apps.push is not supported by this backend");let n=nP(t.app,"app"),a=await nV(e,t.input);try{let r=await e.backend.pushFile(nW(e,t),a.backendInput,n),i=M(r);return{kind:"appPushed",app:n,inputKind:a.inputKind,...i?{backendResult:i}:{},...b(`Pushed to ${n}`)}}finally{await a.cleanup?.()}},nH=async(e,t)=>{var n,a;if(!e.backend.triggerAppEvent)throw new C("UNSUPPORTED_OPERATION","apps.triggerEvent is not supported by this backend");let r=function(e){let t=nP(e,"name");if(!nG.test(t))throw new C("INVALID_ARGS",`Invalid apps.triggerEvent name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});return t}(t.name);n=t.payload,a=`apps.triggerEvent payload for "${r}"`,void 0!==n&&nz(n,a,8192);let i=M(await e.backend.triggerAppEvent(nW(e,t),{name:r,...t.payload?{payload:t.payload}:{}}));return{kind:"appEventTriggered",name:r,...t.payload?{payload:t.payload}:{},...i?{backendResult:i}:{},...b(`Triggered app event: ${r}`)}};async function nV(e,t){if(!t||"object"!=typeof t)throw new C("INVALID_ARGS","apps.push requires an input");if("json"===t.kind)return nz(t.payload,"apps.push JSON payload",8192),{backendInput:{kind:"json",payload:t.payload},inputKind:"json"};let n=await tq(e,t,{usage:"apps.push",field:"input"});return{backendInput:{kind:"file",path:n.path},inputKind:"file",...n.cleanup?{cleanup:n.cleanup}:{}}}function nz(e,t,n){if(function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new C("INVALID_ARGS",`${t} must be a JSON object`)}(e,t),Buffer.byteLength(function(e,t){try{let n=JSON.stringify(e);if("string"!=typeof n)throw new C("INVALID_ARGS",`${t} must be JSON-serializable`);return n}catch{throw new C("INVALID_ARGS",`${t} must be JSON-serializable`)}}(e,t),"utf8")>n)throw new C("INVALID_ARGS",`${t} exceeds ${n} bytes`)}function nW(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}let nJ=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,nZ=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function nQ(e){var t,n;let a=!1,r=e;return{value:(t=r=(r=(r=(r=(r=r.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,t)=>(a=!0,`${String(t)}=[REDACTED]`))).replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,t,n,r)=>(a=!0,`${String(t)}[REDACTED]${String(r)}`))).replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,t)=>(a=!0,`${String(t)}[REDACTED]`))).replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,t)=>(a=!0,`${String(t)}[REDACTED]`))).replaceAll(nZ,()=>(a=!0,"[REDACTED]")),n=()=>{a=!0},r=/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(t)?t.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let t=n0(e);return t?(t.redacted&&n(),t.value):e}):t),redacted:a}}function n0(e){try{let t=new URL(e),n=function(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))nJ.test(n)&&(e.searchParams.set(n,"[REDACTED]"),t=!0);return t}(t);return(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED",n=!0),{value:t.toString(),redacted:n}}catch{return}}let n1=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function n2(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[a,r]of Object.entries(e))if(n1.test(a))n[a]="[REDACTED]",t=!0;else{let e=n8(r,2048);n[a]=e.value??"",t||=e.redacted}return{value:n,redacted:t}}function n4(e){return void 0===e?{redacted:!1}:function(e){try{let t=JSON.parse(e),n=n5(t,nQ);return n6(JSON.stringify(n.value),2048,n.redacted)}catch{return}}(e)??n8(e,2048)}function n3(e){return n5(e,e=>n8(e,2048))}function n5(e,t){if(void 0===e)return{redacted:!1};if("string"==typeof e)return t(e);if(!e||"object"!=typeof e)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let a=n5(e,t);return n||=a.redacted,a.value}),redacted:n}}let n=!1,a={};for(let[r,i]of Object.entries(e)){if(n1.test(r)){a[r]="[REDACTED]",n=!0;continue}let e=n5(i,t);a[r]=e.value,n||=e.redacted}return{value:a,redacted:n}}function n8(e,t){if(void 0===e)return{redacted:!1};let n=nQ(e);return n6(n.value,t,n.redacted)}function n6(e,t,n){if(void 0===e)return{redacted:n};let a=e;return a.length>t&&(a=`${a.slice(0,t)}...[truncated]`,n=!0),{value:a,redacted:n}}let n9=async(e,t={})=>{var n,a;let r;if(!e.backend.readLogs)throw new C("UNSUPPORTED_OPERATION","diagnostics.logs is not supported by this backend");return r=!0===(n=await e.backend.readLogs(await at(e,t),{...an(a=t,100,500,"logs limit"),...void 0!==a.levels?{levels:ar(a.levels,"levels")}:{},...void 0!==a.search?{search:nP(a.search,"search")}:{},...void 0!==a.source?{source:nP(a.source,"source")}:{}})).redacted,{kind:"diagnosticsLogs",entries:n.entries.map(e=>{let t=n8(e.message,4096),n=n3(e.metadata);return r||=t.redacted||n.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:t.value??"",...e.source?{source:e.source}:{},...n.value?{metadata:n.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:r,...n.notes?{notes:n.notes}:{}}},n7=async(e,t={})=>{var n,a,r;let i;if(!e.backend.dumpNetwork)throw new C("UNSUPPORTED_OPERATION","diagnostics.network is not supported by this backend");let s={...an(r=t,25,200,"network limit"),include:function(e){if(void 0===e)return"summary";if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new C("INVALID_ARGS","network include must be summary, headers, body, or all")}(r.include)};return n=await e.backend.dumpNetwork(await at(e,t),s),a=s.include??"summary",i=!0===n.redacted,{kind:"diagnosticsNetwork",entries:n.entries.map(e=>{var t;let n=e.url?n0(t=e.url)??n8(t,2048):void 0,r="headers"===a||"all"===a?n2(e.requestHeaders):void 0,s="headers"===a||"all"===a?n2(e.responseHeaders):void 0,o="body"===a||"all"===a?n4(e.requestBody):void 0,l="body"===a||"all"===a?n4(e.responseBody):void 0,d=n3(e.metadata);return i||=(n?.redacted??!1)||(r?.redacted??!1)||(s?.redacted??!1)||(o?.redacted??!1)||(l?.redacted??!1)||d.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...n?{url:n.value}:{},...void 0!==e.status?{status:e.status}:{},...void 0!==e.durationMs?{durationMs:e.durationMs}:{},...r?.value?{requestHeaders:r.value}:{},...s?.value?{responseHeaders:s.value}:{},...o?.value!==void 0?{requestBody:o.value}:{},...l?.value!==void 0?{responseBody:l.value}:{},...d.value?{metadata:d.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:i,...n.notes?{notes:n.notes}:{}}},ae=async(e,t={})=>{var n,a;let r;if(!e.backend.measurePerf)throw new C("UNSUPPORTED_OPERATION","diagnostics.perf is not supported by this backend");return r=!0===(n=await e.backend.measurePerf(await at(e,t),{...aa(a=t),...void 0!==a.sampleMs?{sampleMs:P(a.sampleMs,"sampleMs",100,6e4)}:{},...void 0!==a.metrics?{metrics:ar(a.metrics,"metrics",20)}:{}})).redacted,{kind:"diagnosticsPerf",metrics:n.metrics.map(e=>{let t=n8(e.message,4096),n=n3(e.metadata);return r||=t.redacted||n.redacted,{name:e.name,...void 0!==e.value?{value:e.value}:{},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...void 0!==t.value?{message:t.value}:{},...n.value?{metadata:n.value}:{}}}),...n.startedAt?{startedAt:n.startedAt}:{},...n.endedAt?{endedAt:n.endedAt}:{},...n.backend?{backend:n.backend}:{},redacted:r,...n.notes?{notes:n.notes}:{}}};async function at(e,t){let n=I(e,t),a=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??a?.appId?{appId:t.appId??a?.appId}:{},...t.appBundleId??a?.appBundleId?{appBundleId:t.appBundleId??a?.appBundleId}:{}}}function an(e,t,n,a){return{...aa(e),...void 0!==e.cursor?{cursor:nP(e.cursor,"cursor")}:{},limit:void 0===e.limit?t:P(e.limit,a,1,n)}}function aa(e){return{...void 0!==e.since?{since:nP(e.since,"since")}:{},...void 0!==e.until?{until:nP(e.until,"until")}:{}}}function ar(e,t,n=50){if(!Array.isArray(e))throw new C("INVALID_ARGS",`${t} must be an array of strings`);if(e.length>n)throw new C("INVALID_ARGS",`${t} must contain at most ${n} entries`);return e.map((e,n)=>nP(e,`${t}[${n}]`))}let ai=async(e,t)=>{let n=ao(t.action,"record"),a="start"===n?e.backend.startRecording:e.backend.stopRecording;if(!a)throw new C("UNSUPPORTED_OPERATION",`record ${n} is not supported by this backend`);let r=t.out?await tG(e,t.out,{field:"path",ext:".mp4"}):void 0;try{var i,s,o,l,d,u,c;let p,h,f,m,w=(i=t,s=r?.path,p={},s&&(p.outPath=s),h=(o=i.fps,void 0===o?void 0:P(o,"fps",1,60)),void 0!==h&&(p.fps=h),f=(l=i.maxSize,void 0===l?void 0:P(l,"maxSize",1,Number.MAX_SAFE_INTEGER)),void 0!==f&&(p.maxSize=f),m=function(e){if(void 0===e)return;let t=S(e);if(void 0===t)throw new C("INVALID_ARGS","quality must be one of: medium, high (legacy numeric values 5-10 are accepted)");return t}(i.quality),void 0!==m&&(p.quality=m),void 0!==i.hideTouches&&(p.showTouches=!0!==i.hideTouches),p),g=await a.call(e.backend,I(e,t),w),b=await r?.publish();return d=n,u=g,c=b,{..."string"==typeof u.path?{path:u.path}:{},..."string"==typeof u.telemetryPath?{telemetryPath:u.telemetryPath}:{},..."string"==typeof u.warning?{warning:u.warning}:{},...al(d,u,c,{startKind:"recordingStarted",stopKind:"recordingStopped",startMessage:"Recording started",stopMessage:"Recording stopped"})}}catch(e){throw await r?.cleanup?.(),e}},as=async(e,t)=>{let n=ao(t.action,"trace"),a="start"===n?e.backend.startTrace:e.backend.stopTrace;if(!a)throw new C("UNSUPPORTED_OPERATION",`trace ${n} is not supported by this backend`);let r=t.out?await tG(e,t.out,{field:"outPath",ext:".trace"}):void 0;try{var i,s,o;let l={...r?.path?{outPath:r.path}:{}},d=await a.call(e.backend,I(e,t),l),u=await r?.publish();return i=n,s=d,o=u,{..."string"==typeof s.outPath?{outPath:s.outPath}:{},...al(i,s,o,{startKind:"traceStarted",stopKind:"traceStopped",startMessage:"Trace started",stopMessage:"Trace stopped"})}}catch(e){throw await r?.cleanup?.(),e}};function ao(e,t){if("start"===e||"stop"===e)return e;throw new C("INVALID_ARGS",`${t} action must be start or stop`)}function al(e,t,n,a){return{kind:"start"===e?a.startKind:a.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...b("start"===e?a.startMessage:a.stopMessage)}}let ad=async(e,t={})=>{if(!e.backend.pressBack)throw new C("UNSUPPORTED_OPERATION","system.back is not supported by this backend");let n=t.mode??"in-app";if("in-app"!==n&&"system"!==n)throw new C("INVALID_ARGS","system.back mode must be in-app or system");let a=M(await e.backend.pressBack(I(e,t),{mode:n}));return{kind:"systemBack",mode:n,...a?{backendResult:a}:{},...b("Back")}},au=async(e,t={})=>{if(!e.backend.pressHome)throw new C("UNSUPPORTED_OPERATION","system.home is not supported by this backend");let n=M(await e.backend.pressHome(I(e,t)));return{kind:"systemHome",...n?{backendResult:n}:{},...b("Home")}},ac=async(e,t)=>{if(!e.backend.rotate)throw new C("UNSUPPORTED_OPERATION","system.rotate is not supported by this backend");let n=function(e){switch(e){case"portrait":case"portrait-upside-down":case"landscape-left":case"landscape-right":return e;default:throw new C("INVALID_ARGS","system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right")}}(t.orientation),a=M(await e.backend.rotate(I(e,t),n));return{kind:"systemRotated",orientation:n,...a?{backendResult:a}:{},...b(`Rotated to ${n}`)}},ap=async(e,t={})=>{var n,a,r,i,s,o,l;if(!e.backend.setKeyboard)throw new C("UNSUPPORTED_OPERATION","system.keyboard is not supported by this backend");let d=t.action??"status";if(!eF(d))throw new C("INVALID_ARGS","system.keyboard action must be status, get, dismiss, enter, or return");let u=await e.backend.setKeyboard(I(e,t),{action:d}),c=M(u),p=(n=u)&&"object"==typeof n?u:{};return"enter"===d||"return"===d?{kind:"keyboardEnterPressed",action:"enter",state:p,...(a=c)?{backendResult:a}:{},...b("Keyboard enter pressed")}:"dismiss"===d?(r=d,{kind:"keyboardDismissed",action:r,state:i=p,...(s=c)?{backendResult:s}:{},...b(!1===i.dismissed?"Keyboard already hidden":"Keyboard dismissed")}):(o=d,{kind:"keyboardState",action:o,state:p,...(l=c)?{backendResult:l}:{}})},ah=async(e,t)=>{if("read"===t.action){if(!e.backend.getClipboard)throw new C("UNSUPPORTED_OPERATION","system.clipboard read is not supported by this backend");let n=await e.backend.getClipboard(I(e,t));return{kind:"clipboardText",action:"read",text:"string"==typeof n?n:n.text}}if("write"!==t.action)throw new C("INVALID_ARGS","system.clipboard action must be read or write");if(!e.backend.setClipboard)throw new C("UNSUPPORTED_OPERATION","system.clipboard write is not supported by this backend");if("string"!=typeof t.text)throw new C("INVALID_ARGS","system.clipboard write requires text");let n=M(await e.backend.setClipboard(I(e,t),t.text));return{kind:"clipboardUpdated",action:"write",textLength:Array.from(t.text).length,...n?{backendResult:n}:{},...b("Clipboard updated")}},af=async(e,t={})=>{if(!e.backend.openSettings)throw new C("UNSUPPORTED_OPERATION","system.settings is not supported by this backend");let n=nR(t.target,"target"),a=M(await e.backend.openSettings(I(e,t),n));return{kind:"settingsOpened",...n?{target:n}:{},...a?{backendResult:a}:{},...b(n?`Opened settings: ${n}`:"Opened settings")}},am=async(e,t={})=>{var n,a;if(!e.backend.handleAlert)throw new C("UNSUPPORTED_OPERATION","system.alert is not supported by this backend");let r=t.action??"get";if("get"!==r&&"accept"!==r&&"dismiss"!==r&&"wait"!==r)throw new C("INVALID_ARGS","system.alert action must be get, accept, dismiss, or wait");let i=void 0===t.timeoutMs?void 0:P(t.timeoutMs,"timeoutMs",0,12e4),s=await e.backend.handleAlert(I(e,t),r,{timeoutMs:i});return n=r,a=s,"get"===n?function(e){if("alertStatus"!==e.kind)throw new C("COMMAND_FAILED","system.alert get returned an invalid backend result");return{kind:"alertStatus",action:"get",alert:e.alert}}(a):"wait"===n?function(e){if("alertWait"!==e.kind)throw new C("COMMAND_FAILED","system.alert wait returned an invalid backend result");return{kind:"alertWait",action:"wait",alert:e.alert,...void 0!==e.waitedMs?{waitedMs:e.waitedMs}:{},...void 0!==e.timedOut?{timedOut:e.timedOut}:{},...b(e.alert?"Alert visible":"Alert wait timed out")}}(a):function(e,t){if("alertHandled"!==t.kind)throw new C("COMMAND_FAILED",`system.alert ${e} returned an invalid backend result`);return{kind:"alertHandled",action:e,handled:t.handled,...t.alert?{alert:t.alert}:{},...t.button?{button:t.button}:{},...b(t.handled?`Alert ${e}ed`:"No alert handled")}}(n,a)},aw=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new C("UNSUPPORTED_OPERATION","system.appSwitcher is not supported by this backend");let n=M(await e.backend.openAppSwitcher(I(e,t)));return{kind:"appSwitcherOpened",...n?{backendResult:n}:{},...b("Opened app switcher")}};function ag(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??function(e=[]){let t=new Map(e.map(e=>[e.name,ab(e)]));return{get:e=>ab(t.get(e)),set:e=>{t.set(e.name,ab(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>ab(e))}}(),policy:e.policy??function(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,capture:{screenshot:e=>tZ(t,e),diffScreenshot:e=>tY(t,e),snapshot:e=>t4(t,e),diffSnapshot:e=>t3(t,e)},selectors:{find:e=>np(t,e),get:e=>nh(t,e),getText:(e,n={})=>nf(t,{...n,target:e}),getAttrs:(e,n={})=>nm(t,{...n,target:e}),is:e=>nw(t,e),isVisible:(e,n={})=>ng(t,{...n,target:e}),isHidden:(e,n={})=>nb(t,{...n,target:e}),wait:e=>ny(t,e),waitForText:(e,n={})=>nk(t,{...n,text:e})},interactions:{click:(e,n={})=>t7(t,{...n,target:e}),press:(e,n={})=>t9(t,{...n,target:e}),fill:(e,n,a={})=>ne(t,{...a,target:e,text:n}),typeText:(e,n={})=>nt(t,{...n,text:e}),focus:(e,n={})=>v(t,{...n,target:e}),longPress:(e,n={})=>y(t,{...n,target:e}),swipe:e=>x(t,e),scroll:e=>w(t,e),pinch:e=>D(t,e)},system:{back:e=>ad(t,e),home:e=>au(t,e),rotate:e=>ac(t,e),keyboard:e=>ap(t,e),clipboard:e=>ah(t,e),settings:e=>af(t,e),alert:e=>am(t,e),appSwitcher:e=>aw(t,e)},apps:{open:e=>nX(t,e),close:e=>nY(t,e),list:(e={})=>nF(t,{...e,filter:ey(e.filter)}),state:e=>nK(t,e),push:e=>nj(t,e),triggerEvent:e=>nH(t,e)},admin:{devices:e=>nN(t,e),boot:e=>nD(t,e),shutdown:e=>n_(t,e),install:e=>nO(t,e),reinstall:e=>nE(t,e),installFromSource:e=>nT(t,e)},recording:{record:e=>ai(t,e),trace:e=>as(t,e)},observability:{logs:e=>n9(t,e),network:e=>n7(t,e),perf:e=>ae(t,e)}}}function ab(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function ay(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}async function ak(e){let{lockDirPath:n,owner:r}=e,i=a.join(n,"owner.json"),s=Date.now()+(e.timeoutMs??3e4),o=e.pollMs??100,l=e.ownerGraceMs??5e3,d=e.description??"process lock";for(t.mkdirSync(a.dirname(n),{recursive:!0});Date.now()<s;)try{t.mkdirSync(n),function(e,n){let a=`${e}.${process.pid}.${Date.now()}.tmp`;t.writeFileSync(a,JSON.stringify(n),"utf8"),t.renameSync(a,e)}(i,r);let e=!1;return async()=>{e||(e=!0,t.rmSync(n,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,n,a){let r=null;try{r=t.statSync(e)}catch{return!0}let i=av(n);if(i){var s;return!(Number.isInteger((s=i).pid)&&!(s.pid<=0)&&ew(s.pid)&&(!s.startTime||eg(s.pid)===s.startTime))&&(t.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<a)&&(t.rmSync(e,{recursive:!0,force:!0}),!0)}(n,i,l))continue;await eb(o)}throw new C("COMMAND_FAILED",`Timed out waiting for ${d}`,{lockDirPath:n,...function(e,n){let a,r=Date.now(),i=av(n);try{a=Math.max(0,Math.round(r-t.statSync(e).mtimeMs))}catch{}return{...void 0!==a?{lockAgeMs:a}:{},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs))}:{}}}(n,i)})}function av(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return null}}let ax="0.27.1",aA="agent-browser";async function aM(e){let t=aR(e);if(t.installed){var n=t;if(!n.installed)throw a_(n);return{command:n.binaryPath,env:aD(n,process.env)}}throw a_(t)}async function aS(e){let n=aR(e);var r,i=n.nodeMajor;if(!(i>=24))throw new C("UNSUPPORTED_OPERATION","Web automation requires Node 24 or newer.",{currentNode:process.version,requiredNodeMajor:24,hint:"Run agent-device with Node 24+ for web setup and web automation."});let s=await ak({lockDirPath:a.join(n.installDir,"..",".agent-browser-install.lock"),owner:{pid:process.pid,startTime:eg(process.pid),acquiredAtMs:Date.now()},timeoutMs:3e5,description:"managed agent-browser setup"});try{let n=aR(e);if(n.installed)return n;return t.mkdirSync(n.installDir,{recursive:!0}),await aP(n),await aN(n,["install"],{timeoutMs:3e5}),await aN(n,["doctor","--offline","--quick"],{timeoutMs:6e4}),r=n,t.writeFileSync(a.join(r.installDir,"manifest.json"),JSON.stringify({package:aA,version:ax,node:process.version,installedAt:new Date().toISOString()},null,2),"utf8"),aR(e)}finally{await s()}}async function aI(e){let t=aR(e);if(!t.installed)throw a_(t);let n=await aN(t,["doctor","--offline","--quick"],{timeoutMs:6e4,allowFailure:!0});return{status:t,...n}}function aR(n){var r,i,o;let l,d,u=n.stateDir??process.env.AGENT_DEVICE_STATE_DIR??a.join(process.env.HOME??process.cwd(),".agent-device"),c=a.join(u,"tools","agent-browser",ax),p=(r=c,l=a.join(r,"package"),a.join(l,"node_modules",".bin","win32"===process.platform?"agent-browser.cmd":"agent-browser")),h=a.join(c,"home"),f=function(t){if("win32"===process.platform)return a.join(t,"home");let n=e.createHash("sha1").update(t).digest("hex").slice(0,12);return a.join(s.tmpdir(),"agent-device-web",n)}(c),m=(i=c,d=e.createHash("sha1").update(i).digest("hex").slice(0,12),a.join(s.tmpdir(),"adw",d)),w=function(e){try{return t.accessSync(e,t.constants.X_OK),!0}catch{return!1}}(p)&&(o=c,t.existsSync(a.join(o,"manifest.json"))),g=Number.parseInt(process.versions.node.split(".")[0]??"0",10);return{version:ax,stateDir:u,installDir:c,binaryPath:p,homeDir:h,runtimeHomeDir:f,socketDir:m,installed:w,nodeMajor:g,nodeSupported:g>=24}}async function aP(e){let n=a.join(e.installDir,"package");t.mkdirSync(n,{recursive:!0}),await V("npm",["install","--prefix",n,"--no-audit","--no-fund","--no-save",`${aA}@${ax}`],{env:process.env,timeoutMs:3e5})}async function aN(e,t,n){return await V(e.binaryPath,t,{allowFailure:n.allowFailure,env:aD(e,process.env),timeoutMs:n.timeoutMs})}function aD(e,n){return t.mkdirSync(e.homeDir,{recursive:!0}),function(e){if(e.runtimeHomeDir!==e.homeDir){t.mkdirSync(a.dirname(e.runtimeHomeDir),{recursive:!0});try{let n=t.lstatSync(e.runtimeHomeDir);if(n.isSymbolicLink()&&t.readlinkSync(e.runtimeHomeDir)===e.homeDir||n.isDirectory())return;n.isSymbolicLink()&&t.unlinkSync(e.runtimeHomeDir)}catch(e){var n;if(!("object"==typeof(n=e)&&null!==n&&"code"in n&&"ENOENT"===n.code))throw e}try{t.symlinkSync(e.homeDir,e.runtimeHomeDir,"dir")}catch{t.mkdirSync(e.runtimeHomeDir,{recursive:!0})}}}(e),t.mkdirSync(e.socketDir,{recursive:!0}),{...n,HOME:e.runtimeHomeDir,AGENT_BROWSER_SOCKET_DIR:e.socketDir}}function a_(e){return new C("TOOL_MISSING","Managed web browser backend is not installed.",{version:ax,installDir:e.installDir,hint:!1===e.nodeSupported?`Web automation requires Node 24+; current Node is ${process.version}.`:"Run `agent-device web setup` to install the managed web backend."})}function aO(e){let t=E(e);return"TOOL_MISSING"!==t.code?t:new C(t.code,t.message,{...t.details??{},hint:"string"==typeof t.details?.hint?t.details.hint:"Run `agent-device web setup` to install the managed web backend."})}export{ak as acquireProcessLock,eC as appendScriptSeriesFlags,ag as createAgentDevice,e6 as decodePngAsync,aI as doctorManagedAgentBrowser,e9 as encodePngAsync,no as evaluateIsPredicate,eK as findMistargetedTypeRefToken,eG as formatPortableActionLine,eT as formatScriptActionSummary,eN as formatScriptArg,eD as formatScriptStringLiteral,eI as isClickLikeCommand,eF as isKeyboardAction,ns as isSupportedPredicate,eR as isTouchTargetCommand,ay as localCommandPolicy,aO as mapManagedAgentBrowserError,eq as parseReplayOpenFlags,e$ as parseReplayRuntimeFlags,eL as parseReplaySeriesFlags,e5 as prewarmPngWorker,aM as resolveAgentBrowserTool,aS as setupManagedAgentBrowser,e8 as terminatePngWorker,eX as timingSafeStringEqual};
package/dist/src/2954.js DELETED
@@ -1,2 +0,0 @@
1
- import{AsyncLocalStorage as e}from"node:async_hooks";import{runCmdBackground as r,withoutCommandExecutorOverride as t,runCmd as i,withCommandExecutorOverride as n}from"./8875.js";import{AppError as a}from"./733.js";let o=new e;function l(e){return async(r,n)=>await t(async()=>await i("adb",["-s",e,...r],{...n,detached:"win32"!==process.platform}))}function s(e){var t;let i=l(e.id);return{exec:i,spawn:(t=e.id,(e,i)=>{let n=r("adb",["-s",t,...e],{...i,allowFailure:!0,captureOutput:!1});return n.wait.catch(()=>{}),n.child}),reverse:g(i),pull:async(e,r,t)=>await i(["pull",e,r],t),install:async(e,r)=>{let{installArgs:t,execOptions:n}=h(r);return await i(["install",...t,e],n)}}}function d(e,r){let t=o.getStore();return r?r:t?.serial===e.id?t.provider.exec:l(e.id)}function u(e,r){if(r)return v(r);let t=o.getStore();return t?.serial===e.id?v(t.provider):s(e)}function c(e){let r=o.getStore();return r?.serial===e.id?r.provider.text:void 0}function w(e){let r=o.getStore();return r?.serial===e.id?r.provider.touch:void 0}function f(e){let r=v(e),t=r.reverse??g(r.exec),i=new Map;return{async ensure(e,r){let n=i.get(e.local);if(n&&n.ownerId!==e.ownerId)throw new a("COMMAND_FAILED",`Android port reverse ${e.local} is already owned by ${n.ownerId??"another session"}`,{current:n,requested:e});n?.remote!==e.remote&&(await t.ensure(e,r),i.set(e.local,{...e}))},async remove(e,r){i.has(e)?(await t.remove(e,r),i.delete(e)):await t.remove(e,r)},async removeAllOwned(e,r){let n=[...i.values()].filter(r=>r.ownerId===e).map(e=>e.local);if(0===n.length)return void await t.removeAllOwned(e,r);for(let e of n)await t.remove(e,r),i.delete(e)},list:async e=>t.list?await t.list(e):[...i.values()]}}function v(e){return"function"==typeof e?{exec:e}:e}async function p(e,r,i){let{device:n,provider:o,...l}=i??{},s=A(n,o),d=s?.pull;if(d)return await t(async()=>await d(e,r,l));let u=s?.exec;if(!u)throw new a("COMMAND_FAILED","Android adb pull requires an adb provider");return await t(async()=>await u(["pull",e,r],l))}async function m(e,r){let{device:i,provider:n,...o}=r??{},l=A(i,n),s=l?.install;if(s)return await t(async()=>await s(e,o));let d=l?.exec;if(!d)throw new a("COMMAND_FAILED","Android adb install requires an adb provider");let{installArgs:u,execOptions:c}=h(o);return await t(async()=>await d(["install",...u,e],c))}function A(e,r){if(r)return v(r);if(e)return u(e);let t=o.getStore();if(t)return v(t.provider)}async function y(e,r,i){var a;if(!e)return await i();let l={provider:"function"==typeof e?{exec:e}:e,serial:r.serial},s=(a=l,(e,r,i)=>{if("adb"!==e)return;let n=function(e,r){if("-s"===e[0]&&e[1]&&e[1]===r)return e.slice(2)}(r,a.serial);if(n)return t(async()=>await a.provider.exec(n,i))});return await o.run(l,async()=>await n(s,i))}function g(e){let r=new Map;return{async ensure(t,i){if(await e(["reverse",t.local,t.remote],{allowFailure:!1,signal:i?.signal,timeoutMs:i?.timeoutMs}),t.ownerId){let e=r.get(t.ownerId)??new Set;e.add(t.local),r.set(t.ownerId,e)}},async remove(t,i){var n,a;let o,l=await e(["reverse","--remove",t],{allowFailure:!0,signal:i?.signal,timeoutMs:i?.timeoutMs});if(0!==l.exitCode&&(n=l.stdout,a=l.stderr,!((o=`${n}
2
- ${a}`.toLowerCase()).includes("listener")&&o.includes("not found"))))throw Error(`Failed to remove Android port reverse ${t}: ${l.stderr}`);for(let e of r.values())e.delete(t)},async removeAllOwned(e,t){for(let i of[...r.get(e)??[]])await this.remove(i,t);r.delete(e)},async list(t){let i=await e(["reverse","--list"],{allowFailure:!0,signal:t?.signal,timeoutMs:t?.timeoutMs});return 0!==i.exitCode?[]:function(e,r){let t=new Map;for(let[e,i]of r)for(let r of i)t.set(r,e);return e.split("\n").map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,r])=>({local:e,remote:r,ownerId:t.get(e)}))}(i.stdout,r)}}}function h(e){let{replace:r,allowTestPackages:t,allowDowngrade:i,grantPermissions:n,...a}=e??{},o=[];return r&&o.push("-r"),t&&o.push("-t"),i&&o.push("-d"),n&&o.push("-g"),{installArgs:o,execOptions:a}}export{f as createAndroidPortReverseManager,s as createLocalAndroidAdbProvider,m as installAndroidAdbPackage,p as pullAndroidAdbFile,d as resolveAndroidAdbExecutor,u as resolveAndroidAdbProvider,c as resolveAndroidTextInjector,w as resolveAndroidTouchInjector,y as withAndroidAdbProvider};
package/dist/src/4291.js DELETED
@@ -1 +0,0 @@
1
- import"./733.js";import{PLATFORM_SELECTORS as t}from"./5910.js";function e(t){return"xctest"===t||"android"===t||"macos-helper"===t||"linux-atspi"===t||"web"===t}function n(t){return void 0===t||"xctest"===t||"android"===t}function a(t){return t.map((t,e)=>({...t,ref:`e${e+1}`}))}function r(t){let e=t.trim();return e.startsWith("@")?e.slice(1)||null:e.startsWith("e")?e:null}function i(t,e){return t.find(t=>t.ref===e)??null}function o(t){return JSON.stringify({interactiveOnly:t?.interactiveOnly===!0,depth:"number"==typeof t?.depth?t.depth:null,scope:t?.scope?.trim()||null,raw:t?.raw===!0})}function s(t){if(t)return{depth:t.snapshotDepth,interactiveOnly:t.snapshotInteractiveOnly,raw:t.snapshotRaw,scope:t.snapshotScope}}function d(t){return{x:Math.round(t.x+t.width/2),y:Math.round(t.y+t.height/2)}}let l=["reject","strip"],c=["ios-simulator","ios-instance","android-instance"],u=["socket","http","dual"],m=["auto","socket","http"],f=["none","tenant"],p=["summary","headers","body","all"];function h(t){return{parse:e=>t(e,"$")}}function $(t,e){throw Error(`${t}: ${e}`)}function I(t,e){return(!t||"object"!=typeof t||Array.isArray(t))&&$(e,"Expected an object"),t}function E(t,e){return"string"!=typeof t&&$(e,"Expected a string"),t}function v(t,e){let n=E(t,e).trim();return n||$(e,"Expected a non-empty string"),n}function S(t,e){return Number.isInteger(t)||$(e,"Expected an integer"),t}function b(t,e,n){let a=t[e];return void 0===a?void 0:E(a,`${n}.${e}`)}function y(t,e,n){let a=b(t,e,n);if(void 0!==a)return a.trim()&&!(a.length>256)&&/^[\x20-\x7E]+$/.test(a)||$(`${n}.${e}`,"Expected 1-256 printable characters"),a}function P(t,e,n,a){let r=b(t,e,n);if(void 0!==r)return(r.length<1||r.length>a||!/^[a-zA-Z0-9._-]+$/.test(r))&&$(`${n}.${e}`,`Expected 1-${String(a)} chars: letters, numbers, dot, underscore, hyphen`),r}function x(t,e,n){let a=t[e];if(void 0!==a)return"boolean"!=typeof a&&$(`${n}.${e}`,"Expected a boolean"),a}function M(t,e,n){let a=t[e];return void 0===a?void 0:S(a,`${n}.${e}`)}function g(t,e,n){let a=t[e];return void 0===a?void 0:I(a,`${n}.${e}`)}function k(t,e,n,a){let r=t[e];if(void 0!==r)return"string"==typeof r&&n.includes(r)||$(`${a}.${e}`,`Expected one of: ${n.join(", ")}`),r}function N(t,e){let n=I(t,e),a={};for(let[t,r]of Object.entries(n))a[t]=E(r,`${e}.${t}`);return a}let _=h((t,e)=>{let n=I(t,e);return{platform:k(n,"platform",["ios","android"],e),metroHost:b(n,"metroHost",e),metroPort:M(n,"metroPort",e),bundleUrl:b(n,"bundleUrl",e),launchUrl:b(n,"launchUrl",e)}}),A=h((e,n)=>{var a,r;let i=I(e,n),o=(a=i.positionals,r=`${n}.positionals`,Array.isArray(a)||$(r,"Expected an array"),a),s=g(i,"meta",n);return{token:b(i,"token",n),session:b(i,"session",n),command:E(i.command,`${n}.command`),positionals:o.map((t,e)=>E(t,`${n}.positionals[${String(e)}]`)),flags:g(i,"flags",n),runtime:void 0===i.runtime?void 0:_.parse(i.runtime),meta:void 0===s?void 0:{requestId:b(s,"requestId",`${n}.meta`),debug:x(s,"debug",`${n}.meta`),cwd:b(s,"cwd",`${n}.meta`),sessionExplicit:x(s,"sessionExplicit",`${n}.meta`),tenantId:b(s,"tenantId",`${n}.meta`),runId:b(s,"runId",`${n}.meta`),leaseId:b(s,"leaseId",`${n}.meta`),leaseTtlMs:M(s,"leaseTtlMs",`${n}.meta`),leaseBackend:k(s,"leaseBackend",c,`${n}.meta`),leaseProvider:P(s,"leaseProvider",`${n}.meta`,64),deviceKey:y(s,"deviceKey",`${n}.meta`),clientId:P(s,"clientId",`${n}.meta`,128),sessionIsolation:k(s,"sessionIsolation",f,`${n}.meta`),uploadedArtifactId:b(s,"uploadedArtifactId",`${n}.meta`),clientArtifactPaths:void 0===s.clientArtifactPaths?void 0:N(s.clientArtifactPaths,`${n}.meta.clientArtifactPaths`),installSource:void 0===s.installSource?void 0:function(t,e){let n=I(t,e),a=E(n.kind,`${e}.kind`);if("url"===a){let t=E(n.url,`${e}.url`),r=void 0===n.headers?void 0:N(n.headers,`${e}.headers`);return r?{kind:a,url:t,headers:r}:{kind:a,url:t}}if("path"===a)return{kind:a,path:E(n.path,`${e}.path`)};if("github-actions-artifact"===a){let t,a,r,i,o;return t=v(n.owner,`${e}.owner`),a=v(n.repo,`${e}.repo`),r=void 0!==n.artifactId,i=void 0!==n.runId,o=void 0!==n.artifactName,(r&&(i||o)&&$(`${e}`,"Expected either artifactId or artifactName, not both"),r||!i||o||$(`${e}`,"Expected artifactName when runId is specified"),r||o||$(`${e}`,"Expected artifactId or artifactName"),r)?{kind:"github-actions-artifact",owner:t,repo:a,artifactId:S(n.artifactId,`${e}.artifactId`)}:{kind:"github-actions-artifact",owner:t,repo:a,...i?{runId:S(n.runId,`${e}.runId`)}:{},artifactName:v(n.artifactName,`${e}.artifactName`)}}$(`${e}.kind`,'Expected "url", "path", or "github-actions-artifact"')}(s.installSource,`${n}.meta.installSource`),retainMaterializedPaths:x(s,"retainMaterializedPaths",`${n}.meta`),materializedPathRetentionMs:M(s,"materializedPathRetentionMs",`${n}.meta`),materializationId:b(s,"materializationId",`${n}.meta`),lockPolicy:k(s,"lockPolicy",l,`${n}.meta`),lockPlatform:k(s,"lockPlatform",t,`${n}.meta`)}}});function O(t,e){return{token:b(t,"token",e),session:b(t,"session",e),tenantId:b(t,"tenantId",e),tenant:b(t,"tenant",e),runId:b(t,"runId",e),leaseProvider:P(t,"leaseProvider",e,64),deviceKey:y(t,"deviceKey",e),clientId:P(t,"clientId",e,128)}}let R=h((t,e)=>{let n=I(t,e);return{...O(n,e),ttlMs:M(n,"ttlMs",e),backend:k(n,"backend",c,e)}}),w=h((t,e)=>{let n,a={record:n=I(t,e),leaseId:b(n,"leaseId",e),ttlMs:M(n,"ttlMs",e)};return{...O(a.record,e),leaseId:a.leaseId,ttlMs:a.ttlMs,backend:k(a.record,"backend",c,e)}}),K=h((t,e)=>{let n=I(t,e);return void 0!==n.ttlMs&&$(`${e}.ttlMs`,"Unexpected field"),{...O(n,e),leaseId:b(n,"leaseId",e),backend:k(n,"backend",c,e)}}),C=h((t,e)=>{let n,a=I(t,e);return{jsonrpc:b(a,"jsonrpc",e),id:(null==(n=a.id)||"string"!=typeof n&&"number"!=typeof n&&$(`${e}.id`,"Expected a string, number, or null"),n),method:b(a,"method",e),params:a.params}});export{l as DAEMON_LOCK_POLICIES,u as DAEMON_SERVER_MODES,m as DAEMON_TRANSPORT_PREFERENCES,c as LEASE_BACKENDS,p as NETWORK_INCLUDE_MODES,f as SESSION_ISOLATION_MODES,a as attachRefs,o as buildSnapshotPresentationKey,d as centerOfRect,A as daemonCommandRequestSchema,_ as daemonRuntimeSchema,i as findNodeByRef,e as isSnapshotBackend,C as jsonRpcRequestSchema,R as leaseAllocateSchema,w as leaseHeartbeatSchema,K as leaseReleaseSchema,r as normalizeRef,s as snapshotPresentationOptionsFromFlags,n as usesMobileSnapshotPresentation};
package/dist/src/432.js DELETED
@@ -1,4 +0,0 @@
1
- import{AsyncLocalStorage as t}from"node:async_hooks";import e from"node:crypto";import n from"node:fs";import o from"node:os";import i from"node:path";import{redactDiagnosticData as r}from"./733.js";let s=new t;function a(){return e.randomBytes(8).toString("hex")}async function c(t,n){let o={...t,diagnosticId:`${Date.now().toString(36)}-${e.randomBytes(4).toString("hex")}`,events:[],liveWrittenEventCount:0};return await s.run(o,n)}function l(t){let e=s.getStore();e&&Object.assign(e,t)}function d(){let t=s.getStore();return t?{diagnosticId:t.diagnosticId,requestId:t.requestId,session:t.session,command:t.command,debug:t.debug}:{}}function g(t){let e=s.getStore();if(!e)return;let n={ts:new Date().toISOString(),level:t.level??"info",phase:t.phase,session:e.session,requestId:e.requestId,command:e.command,durationMs:t.durationMs,data:t.data?r(t.data):void 0};if(e.events.push(n),!e.debug)return;let o=`${JSON.stringify(n)}
2
- `;try{e.logPath&&(f(e.logPath,o),e.liveWrittenEventCount=e.events.length),e.traceLogPath&&f(e.traceLogPath,o),e.logPath||e.traceLogPath||process.stderr.write(`[agent-device][diag] ${o}`)}catch{}}async function u(t,e,n){let o=Date.now();try{let i=await e();return g({level:"info",phase:t,durationMs:Date.now()-o,data:n}),i}catch(e){throw g({level:"error",phase:t,durationMs:Date.now()-o,data:{...n??{},error:e instanceof Error?e.message:String(e)}}),e}}function m(t={}){let e=s.getStore();if(!e||!t.force&&!e.debug||0===e.events.length)return null;try{if(e.logPath){let t=e.events.slice(e.liveWrittenEventCount);if(t.length>0){let n=t.map(t=>JSON.stringify(r(t)));f(e.logPath,`${n.join("\n")}
3
- `)}let n=e.logPath;return e.events=[],e.liveWrittenEventCount=0,n}let t=(e.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),s=new Date().toISOString().slice(0,10),a=i.join(o.homedir(),".agent-device","logs",t,s);n.mkdirSync(a,{recursive:!0});let c=new Date().toISOString().replace(/[:.]/g,"-"),l=i.join(a,`${c}-${e.diagnosticId}.ndjson`),d=e.events.map(t=>JSON.stringify(r(t)));return n.writeFileSync(l,`${d.join("\n")}
4
- `),e.events=[],l}catch{return null}}function f(t,e){n.mkdirSync(i.dirname(t),{recursive:!0}),n.appendFileSync(t,e,"utf8")}export{a as createRequestId,g as emitDiagnostic,m as flushDiagnosticsToSessionFile,d as getDiagnosticsMeta,l as updateDiagnosticsScope,u as withDiagnosticTimer,c as withDiagnosticsScope};
package/dist/src/4723.js DELETED
@@ -1 +0,0 @@
1
- import e from"node:fs";import t from"node:path";import{AppError as n}from"./733.js";import{PLATFORM_SELECTORS as r}from"./5910.js";import{resolveUserPath as o}from"./9612.js";let i=new Set(["1","true","yes","on"]),a=new Set(["0","false","no","off"]);function s(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function l(e,t,r,o){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>l({...e,multiple:!1},t,r,o));if("boolean"===e.type){var i=t,a=r,s=o;if("boolean"==typeof i)return i;if("string"==typeof i){let e=u(i);if(void 0!==e)return e}throw new n("INVALID_ARGS",`Invalid value for "${s}" in ${a}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==u(t))return u(t);if("string"==typeof t&&t.trim().length>0)return t;throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var y=e,f=t,p=r,m=o;let i=y.setValue;if(f===i)return i;if("string"==typeof f){let e=f.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===f)return i;if(!1!==f)throw new n("INVALID_ARGS",`Invalid value for "${m}" in ${p}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let g="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(g)||!Number.isInteger(g))throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected integer.`);if("number"==typeof e.min&&g<e.min)throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&g>e.max)throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Must be <= ${e.max}.`);return g}function u(e){let t=e.trim().toLowerCase();return!!i.has(t)||!a.has(t)&&void 0}let y=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"leaseBackend",type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"]},{key:"platform",type:"enum",enumValues:r},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,env:!1},{key:"androidDeviceAllowlist",type:"string"},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string"},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],f=[...y,{key:"leaseProvider",type:"string",env:!1},{key:"deviceKey",type:"string",env:!1},{key:"clientId",type:"string",env:!1}],p=new Map(f.map(e=>[e.key,e]));function m(e){let t=e.env??process.env;return o(e.configPath,{cwd:e.cwd,env:t})}function g(r){let i=function(r){let i,a,s=r.env??process.env,u=m(r);if(!e.existsSync(u))throw new n("INVALID_ARGS",`Remote config file not found: ${u}`);try{i=e.readFileSync(u,"utf8")}catch(e){throw new n("INVALID_ARGS",`Failed to read remote config file: ${u}`,{cause:e instanceof Error?e.message:String(e)})}try{a=JSON.parse(i)}catch(e){throw new n("INVALID_ARGS",`Invalid JSON in remote config file: ${u}`,{cause:e instanceof Error?e.message:String(e)})}if(!a||"object"!=typeof a||Array.isArray(a))throw new n("INVALID_ARGS",`Remote config file must contain a JSON object: ${u}`);let y={},f=a,g=t.dirname(u);for(let[e,t]of Object.entries(f)){let r=p.get(e);if(!r)throw new n("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${u}.`);let i=l(r,t,`remote config file ${u}`,e);y[r.key]="string"==typeof i&&"path"in r&&r.path?o(i,{cwd:g,env:s}):i}return{resolvedPath:u,profile:y}}(r);return{resolvedPath:i.resolvedPath,profile:function(...e){let t={};for(let n of e)if(n)for(let e of f){let r=n[e.key];void 0!==r&&(t[e.key]=r)}return t}(function(e=process.env){let t={};for(let n of f){let r=(function(e){let t=p.get(e);return t?.env===!1?[]:[s(e)]})(n.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);r&&(t[n.key]=l(n,r.value,`environment variable ${r.name}`,r.name))}return t}(r.env),i.profile)}}export{y as REMOTE_CONFIG_FIELD_SPECS,s as buildPrimaryEnvVarName,l as parseSourceValue,m as resolveRemoteConfigPath,g as resolveRemoteConfigProfile};
package/dist/src/5341.js DELETED
@@ -1 +0,0 @@
1
- import{AppError as e}from"./733.js";let t={alert:"alert",appState:"appstate",appSwitcher:"app-switcher",apps:"apps",back:"back",batch:"batch",boot:"boot",click:"click",close:"close",clipboard:"clipboard",devices:"devices",diff:"diff",fill:"fill",find:"find",focus:"focus",gesture:"gesture",get:"get",home:"home",install:"install",installFromSource:"install-from-source",is:"is",keyboard:"keyboard",logs:"logs",longPress:"longpress",network:"network",open:"open",perf:"perf",prepare:"prepare",press:"press",push:"push",record:"record",reactNative:"react-native",reinstall:"reinstall",replay:"replay",rotate:"rotate",scroll:"scroll",screenshot:"screenshot",settings:"settings",shutdown:"shutdown",snapshot:"snapshot",swipe:"swipe",test:"test",trace:"trace",triggerAppEvent:"trigger-app-event",type:"type",viewport:"viewport",wait:"wait"},r={installSource:"install_source",leaseAllocate:"lease_allocate",leaseHeartbeat:"lease_heartbeat",leaseRelease:"lease_release",releaseMaterializedPaths:"release_materialized_paths",runtime:"runtime",sessionList:"session_list"},n={cdp:"cdp",auth:"auth",connect:"connect",connection:"connection",debug:"debug",disconnect:"disconnect",mcp:"mcp",metro:"metro",proxy:"proxy",reactDevtools:"react-devtools",session:"session",web:"web"},o=["pan","fling","swipe","pinch","rotate","transform"],i=`gesture requires one of: ${o.join(", ")}`,s=a(n.auth,n.cdp,n.connect,n.connection,n.disconnect,n.mcp,n.proxy,n.reactDevtools,n.web,t.prepare);function a(...e){return new Set(e)}function c(){return[...Object.values(t),...Object.values(n)].sort()}function l(e){return Object.values(t).includes(e)||e===n.debug||e===n.metro||e===n.session}function u(){return c().filter(e=>!s.has(e))}function p(t,r,n,o){let i=n(t[r]);if(void 0===i)throw new e("COMMAND_FAILED",o,{response:t});return i}function d(e,t){return p(e,t,A,`Daemon response is missing "${t}".`)}function f(e,t){return A(e[t])}function m(e,t){var r;let n;return r=A,null===(n=e[t])?null:r(n)}function h(e,t){return p(e,t,N,`Daemon response is missing numeric "${t}".`)}function g(e,t){return p(e,t,D,`Daemon response has invalid "${t}".`)}function v(e,t){return p(e,t,C,`Daemon response has invalid "${t}".`)}function b(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function w(e){if(!E(e))return;let t=_(e,"x"),r=_(e,"y"),n=_(e,"width"),o=_(e,"height");if(void 0!==t&&void 0!==r&&void 0!==n&&void 0!==o)return{x:t,y:r,width:n,height:o}}function S(e){if(!E(e))return;let t=_(e,"x"),r=_(e,"y");if(void 0!==t&&void 0!==r)return{x:t,y:r}}function _(e,t){let r=e[t];return"number"==typeof r?r:void 0}function A(e){return"string"==typeof e&&e.length>0?e:void 0}function N(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function D(e){return"ios"===e||"macos"===e||"android"===e||"linux"===e||"web"===e?e:void 0}function C(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}a(n.auth,n.cdp,n.connect,n.connection,n.debug,n.disconnect,n.mcp,n.metro,n.proxy,n.reactDevtools,n.session,n.web,t.appState,t.prepare,t.batch,t.devices,t.gesture,t.replay,t.test,t.trace);function y(t){if(!E(t))throw new e("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:t});return t}function E(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function R(e){let t={};for(let[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function M(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}let O=[t.devices,t.boot,t.shutdown,t.apps,t.open,t.close,t.install,t.reinstall,t.installFromSource,t.push,t.triggerAppEvent,t.snapshot,t.screenshot,t.diff,t.wait,t.alert,t.settings,t.click,t.press,t.longPress,t.swipe,t.focus,t.type,t.fill,t.scroll,t.get,t.gesture,t.is,t.find,t.perf,t.logs,t.network,t.record,t.trace,t.test,t.appState,t.back,t.home,t.rotate,t.appSwitcher,t.keyboard,t.clipboard,t.reactNative],k=new Set(["batch","replay"]),T=["command","positionals","flags","runtime"],B=["platform","target","device","udid","serial","verbose","out"],I=new Set(O);function L(e){return"string"==typeof e?e.trim().toLowerCase():""}function x(t,r){let n=L(t);if(I.has(n))return n;throw new e("INVALID_ARGS",`Batch step ${r} command is not available through command batch: ${String(t)}`)}function P(t,r){if(k.has(t))throw new e("INVALID_ARGS",`Batch step ${r} cannot run ${t}.`)}export{k as BATCH_BLOCKED_COMMANDS,T as BATCH_DAEMON_STEP_KEYS,o as GESTURE_KINDS,i as GESTURE_SUBCOMMAND_ERROR,B as INHERITED_PARENT_FLAG_KEYS,r as INTERNAL_COMMANDS,t as PUBLIC_COMMANDS,O as STRUCTURED_BATCH_COMMAND_NAMES,y as asRecord,P as assertBatchRuntimeCommandAllowed,l as isClientBackedCliCommandName,E as isRecord,c as listCliCommandNames,u as listMcpExposedCommandNames,L as normalizeBatchCommandName,S as parsePoint,w as parseRect,b as readDeviceTarget,m as readNullableString,f as readOptionalString,v as readRequiredDeviceKind,h as readRequiredNumber,g as readRequiredPlatform,d as readRequiredString,x as readStructuredBatchCommandName,M as splitNonEmptyTrimmedLines,R as stripUndefined};
package/dist/src/5910.js DELETED
@@ -1,2 +0,0 @@
1
- import{AppError as e}from"./733.js";let t=["ios","macos","android","linux","web","apple"],i=["mobile","tv","desktop"];function r(e){return e}function o(e){return"apple"===e||"ios"===e||"macos"===e}function l(e,t){return!t||("apple"===t?o(e):e===t)}function a(e){return"macos"===e||"desktop"===e?"macOS":"tv"===e?"tvOS":"iOS"}function n(e){let{simulatorSetPath:t,platform:i,target:r}=e;if(t&&"macos"!==i&&"desktop"!==r)return t}async function m(t,i,r={}){let a=t,n=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(i.platform&&(a=a.filter(e=>l(e.platform,i.platform))),i.target&&(a=a.filter(e=>(e.target??"mobile")===i.target)),i.udid){let t=a.find(e=>e.id===i.udid&&o(e.platform));if(!t)throw new e("DEVICE_NOT_FOUND",`No Apple device with UDID ${i.udid}`);return t}if(i.serial){let t=a.find(e=>e.id===i.serial&&"android"===e.platform);if(!t)throw new e("DEVICE_NOT_FOUND",`No Android device with serial ${i.serial}`);return t}if(i.deviceName){let t=n(i.deviceName),r=a.find(e=>n(e.name)===t);if(!r)throw new e("DEVICE_NOT_FOUND",`No device named ${i.deviceName}`);return r}let d=a[0];if(void 0!==d&&1===a.length)return d;if(0===a.length){var f;let t=r.simulatorSetPath;if(t&&(!(f=i.platform)||"apple"===f||"ios"===f))throw new e("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:t,hint:`The simulator set at "${t}" appears to be empty. Create a simulator first:
2
- xcrun simctl --set "${t}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:i});throw new e("DEVICE_NOT_FOUND","No devices found",{selector:i})}let p=a.filter(e=>"device"!==e.kind);p.length>0&&(a=p);let c=a.filter(e=>e.booted),s=c[0];if(void 0!==s&&1===c.length)return s;let u=c[0]??a[0];if(void 0===u)throw new e("DEVICE_NOT_FOUND","No devices found",{selector:i});return u}export{i as DEVICE_TARGETS,t as PLATFORM_SELECTORS,o as isApplePlatform,l as matchesPlatformSelector,r as normalizePlatformSelector,a as resolveApplePlatformName,n as resolveAppleSimulatorSetPathForSelector,m as resolveDevice};
package/dist/src/6024.js DELETED
@@ -1 +0,0 @@
1
- function t(t){let e=`${t??""}`.toLowerCase();return e.includes("scroll")||e.includes("recyclerview")||e.includes("listview")||e.includes("gridview")||e.includes("collectionview")||"table"===e}function e(e){return!!t(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function i(t){return t}function n(t){let e=1/0,i=1/0,n=-1/0,r=-1/0;for(let h of t)e=Math.min(e,h.x),i=Math.min(i,h.y),n=Math.max(n,h.x+h.width),r=Math.max(r,h.y+h.height);return{x:e,y:i,width:n-e,height:r-i}}function r(t,e){return{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e}}function h(t,e){let i=Math.max(t.x,e.x),n=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),h=Math.min(t.y+t.height,e.y+e.height);return r<=i||h<=n?0:(r-i)*(h-n)}function c(t){return{x:t.x+t.width/2,y:t.y+t.height/2}}function l(t,e){return(t.x-e.x)**2+(t.y-e.y)**2}function o(t,e,i){return Math.min(Math.max(t,e),i)}export{o as clamp,r as expandRect,h as intersectArea,e as isScrollableNodeLike,t as isScrollableType,i as normalizedRect,c as rectCenter,l as squaredDistance,n as unionRects};
package/dist/src/733.js DELETED
@@ -1 +0,0 @@
1
- let e=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key|user[_-]?code|device[_-]?code|refresh[_-]?credential)/i,t=/\b(?:bearer\s+[a-z0-9._-]+|adc_(?:agent|live|refresh|cli)_[a-z0-9._-]+)\b/gi,r=/\b([a-z0-9_-]*(?:api[_-]?key|token|secret|password|user[_-]?code|device[_-]?code|refresh[_-]?credential)[a-z0-9_-]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi,n=/https?:\/\/[^\s"'<>]+/gi;function i(i){return function i(a,o,s){if(null==a)return a;if("string"==typeof a){var c=a,d=s;let i=c.trim();if(!i)return c;if(d&&e.test(d))return"[REDACTED]";let o=i.replace(n,e=>(function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}})(e)??e);return(o=(o=o.replace(t,"[REDACTED]")).replace(r,(e,t,r,n,i,a)=>{var o;return function(e){if("token"!==e.key.toLowerCase()||!e.separator.includes(":"))return!1;try{let t=new URL(e.rawValue);if("/api-keys"!==t.pathname.replace(/\/+$/,""))return!1;return/(?:^|\b)(?:service\/)?api\s+$/i.test(e.input.slice(0,e.offset))}catch{return!1}}({key:t,separator:r,rawValue:n,offset:i,input:a})||(o=n,/^adc_(?:agent|live|refresh|cli)_\.\.\.$/i.test(o))?e:`${t}${r}[REDACTED]`}))!==i?o:i.length>400?`${i.slice(0,200)}...<truncated>`:i}if("object"!=typeof a)return a;if(o.has(a))return"[Circular]";if(o.add(a),Array.isArray(a))return a.map(e=>i(e,o));let l={};for(let[t,r]of Object.entries(a)){if(e.test(t)){l[t]="[REDACTED]";continue}l[t]=i(r,o,t)}return l}(i,new WeakSet)}function a(e,t="COMMAND_FAILED"){return"string"==typeof e&&e.length>0?e:t}class o extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function s(e){return e instanceof o?e:e instanceof Error?new o("UNKNOWN",e.message,void 0,e):new o("UNKNOWN","Unknown error",{err:e})}function c(e){return e instanceof o}function d(e,t={}){return l(e,t)}function l(e,t={}){let r=s(e),n=r.details?i(r.details):void 0,a=n&&"string"==typeof n.hint?n.hint:void 0,o=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,c=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,d=a??u(r.code),f=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),p=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:p,hint:d,diagnosticId:o,logPath:c,details:f}}function u(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"NOT_IMPLEMENTED":return"This command is part of the planned API but is not implemented yet.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}export{o as AppError,s as asAppError,u as defaultHintForCode,c as isAgentDeviceError,d as normalizeAgentDeviceError,l as normalizeError,i as redactDiagnosticData,a as toAppErrorCode};
package/dist/src/7394.js DELETED
@@ -1,6 +0,0 @@
1
- import e from"node:crypto";import t from"node:fs";import r from"node:fs/promises";import n from"node:os";import i from"node:path";import o from"node:net";import{AppError as a}from"./733.js";import{intersectArea as s,isScrollableType as l}from"./6024.js";import{emitDiagnostic as u}from"./432.js";import{installAndroidAdbPackage as d}from"./2954.js";let c="android-snapshot-helper",h="com.callstack.agentdevice.snapshothelper",p="com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",f="android-snapshot-helper-v1",w="uiautomator-xml",m={"-r":"replace","-t":"allowTestPackages","-d":"allowDowngrade","-g":"grantPermissions"};async function A(e){let t=await y(e.apkPath);if(t!==e.manifest.sha256)throw new a("COMMAND_FAILED","Android snapshot helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function M(e){let t=e.fetch??fetch,o=await t(e.manifestUrl);if(!o.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper manifest",{manifestUrl:e.manifestUrl,status:o.status,statusText:o.statusText});let s=g(JSON.parse((await v(o,65536,"Android snapshot helper manifest")).toString("utf8")));if(!s.apkUrl)throw new a("COMMAND_FAILED","Android snapshot helper manifest does not include apkUrl",{manifestUrl:e.manifestUrl});let l=e.cacheDir??i.join(n.tmpdir(),`agent-device-android-snapshot-helper-${s.version}`),u=!e.cacheDir;await r.mkdir(l,{recursive:!0});let d=s.assetName??`agent-device-android-snapshot-helper-${s.version}.apk`,c=i.join(l,d),h=await t(s.apkUrl);if(!h.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper APK",{apkUrl:s.apkUrl,status:h.status,statusText:h.statusText});await r.writeFile(c,await v(h,0x1400000,"Android snapshot helper APK"));let p={apkPath:c,manifest:s};return await A(p),{...p,cleanup:async()=>{await r.rm(u?l:c,{recursive:u,force:!0})}}}function g(e){var t,r;if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS","Android snapshot helper manifest must be an object.");return{name:C(e.name,"name",c),version:x(e.version,"version"),releaseTag:I(e.releaseTag),assetName:I(e.assetName),apkUrl:(t=e.apkUrl,r="apkUrl",null===t?null:x(t,r)),sha256:function(e){let t=x(e,"sha256").trim().toLowerCase();if(64!==t.length||!function(e){for(let t of e){let e=t.charCodeAt(0),r=e>=48&&e<=57,n=e>=97&&e<=102;if(!r&&!n)return!1}return!0}(t))throw new a("INVALID_ARGS","Android snapshot helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),checksumName:I(e.checksumName),packageName:x(e.packageName,"packageName"),versionCode:D(e.versionCode,"versionCode"),instrumentationRunner:x(e.instrumentationRunner,"instrumentationRunner"),minSdk:D(e.minSdk,"minSdk"),targetSdk:void 0===e.targetSdk?void 0:D(e.targetSdk,"targetSdk"),outputFormat:C(e.outputFormat,"outputFormat",w),statusProtocol:C(e.statusProtocol,"statusProtocol",f),installArgs:N(e.installArgs)}}async function v(e,t,r){let n=e.headers.get("content-length");if(null!==n){let e=Number(n);if(Number.isFinite(e)&&e>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:e,maxBytes:t})}if(!e.body){let n=Buffer.from(await e.arrayBuffer());if(n.length>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:n.length,maxBytes:t});return n}let i=e.body.getReader(),o=[],s=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if((s+=n.byteLength)>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:s,maxBytes:t});o.push(Buffer.from(n))}}finally{i.releaseLock()}return Buffer.concat(o,s)}function N(e){let t=function(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be a string array.`);return e}(e,"installArgs");if("install"!==t[0])throw new a("INVALID_ARGS",'Android snapshot helper manifest installArgs must start with "install".');if(t.some(e=>e.includes("\0")))throw new a("INVALID_ARGS","Android snapshot helper manifest installArgs must not contain null bytes.");let r=t.slice(1).find(e=>void 0===b(e));if(r)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);return t}async function y(r){return await new Promise((n,i)=>{let o=e.createHash("sha256"),a=t.createReadStream(r);a.on("error",i),a.on("data",e=>o.update(e)),a.on("end",()=>n(o.digest("hex")))})}function x(e,t){if("string"!=typeof e||0===e.trim().length)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} is required.`);return e}function I(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function D(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be an integer.`);return e}function C(e,t,r){if(e!==r)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be "${r}".`);return r}function b(e){if(Object.hasOwn(m,e))return m[e]}function*S(e){let t=/<node\b[^>]*>/g,r=t.exec(e);for(;r;)yield _(r[0]),r=t.exec(e)}function _(e){let t,r,n,i,o,a=(t=function(e){let t=new Map,r=e.indexOf(" "),n=e.lastIndexOf(">");if(r<0||n<=r)return t;let i=r;for(;i<n;){let r=function(e,t,r){var n,i;if((t=k(e,t,r))>=r||"/"===(n=e[t])||">"===n)return;let o=t;t=function(e,t,r){for(var n;t<r&&!("="===(n=e[t]??"")||"/"===n||">"===n||L(n));)t+=1;return t}(e,t,r);let a=e.slice(o,t);if(t=k(e,t,r),!a||"="!==e[t])return;t=k(e,t+1,r);let s=e[t];if('"'!==(i=s)&&"'"!==i)return;let l=t+1,u=e.indexOf(s,l);if(!(u<0)&&!(u>=r))return{name:a,value:function(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("&",r);if(n<0){t+=e.slice(r);break}t+=e.slice(r,n);let i=e.indexOf(";",n+1);if(i<0){t+=e.slice(n);break}t+=function(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:return function(e){if(!e.startsWith("#"))return;let t=e[1]?.toLowerCase()==="x"?16:10,r=16===t?e.slice(2):e.slice(1);if(!r||!function(e,t){for(let r of e){let e=r.charCodeAt(0),n=e>=48&&e<=57;if(10===t){if(!n)return!1;continue}let i=e>=65&&e<=70,o=e>=97&&e<=102;if(!n&&!i&&!o)return!1}return!0}(r,t))return;let n=Number.parseInt(r,t);if(Number.isFinite(n))try{return String.fromCodePoint(n)}catch{return}}(e)}}(e.slice(n+1,i))??e.slice(n,i+1),r=i+1}return t}(e.slice(l,u)),nextCursor:u+1}}(e,i,n);if(!r)break;t.set(r.name,r.value),i=r.nextCursor}return t}(e),r=e=>{let r=O(t,e);if(null!==r)return"true"===r},n=(e,r)=>{let n=(e=>{let r=O(t,e);if(null===r||""===r.trim())return;let n=Number(r);return Number.isFinite(n)?n:void 0})(r);return void 0===n?{}:{[e]:n}},i=(e,t)=>{let n=r(t);return void 0===n?{}:{[e]:n}},{text:O(t,"text"),desc:O(t,"content-desc"),resourceId:O(t,"resource-id"),packageName:O(t,"package"),className:O(t,"class"),bounds:O(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused"),password:r("password"),...i("visibleToUser","visible-to-user"),...n("drawingOrder","drawing-order"),...i("scrollable","scrollable"),...i("canScrollForward","can-scroll-forward"),...i("canScrollBackward","can-scroll-backward"),...n("windowIndex","window-index"),...n("windowType","window-type"),...n("windowLayer","window-layer"),...i("windowActive","window-active"),...i("windowFocused","window-focused"),...void 0===(o=E(O(t,"window-bounds")))?{}:{windowRect:o}}),s=E(a.bounds);return{...a,...s?{rect:s}:{}}}function T(e,t,r){let{sourceNodes:n,...i}=F(P(e),t,r);return i}function F(e,t,r){let n={nodes:[],sourceNodes:[],...void 0!==t?{maxNodes:t}:{},maxDepth:r.depth??1/0,options:r,analysis:function(e){let t=0,r=0,n=[...e.children];for(;n.length>0;){let e=n.pop();t+=1,r=Math.max(r,e.depth),n.push(...e.children)}return{rawNodeCount:t,maxDepth:r}}(e),interactiveDescendantMemo:new Map,truncated:!1},i=r.scope?function(e,t){let r=t.toLowerCase(),n=[...e.children],i=0;for(;i<n.length;){let e=n[i++],t=e.label?.toLowerCase()??"",o=e.value?.toLowerCase()??"",a=e.identifier?.toLowerCase()??"";if(t.includes(r)||o.includes(r)||a.includes(r))return e;n.push(...e.children)}return null}(e,r.scope):null;for(let t of i?[i]:e.children)if(function e(t,r,n,i,o=!1,a=!1){if(void 0!==t.maxNodes&&t.nodes.length>=t.maxNodes){t.truncated=!0;return}if(n>t.maxDepth)return;let s=t.options.raw||function(e,t,r,n,i){var o,a,s;if(!1===e.visibleToUser)return!1;let u=function(e){let t=V(e.type),r=!!(e.label&&e.label.trim().length>0),n=!!(e.identifier&&e.identifier.trim().length>0);return{type:t,hasMeaningfulText:r&&!B(e.label??""),hasMeaningfulId:n&&!B(e.identifier??""),isStructural:function(e){let t=e.split(".").pop()??e;return t.includes("layout")||"viewgroup"===t||"view"===t}(t),isVisual:"imageview"===t||"imagebutton"===t}}(e);return t.interactiveOnly?function(e,t,r,n,i){var o,a,s,u,d;return!((o=e).rect&&(o.rect.width<=0||o.rect.height<=0))&&(!!(e.hittable||l(t.type)&&n)||(a=t,s=r,u=n,d=i,(!!a.hasMeaningfulText||!!a.hasMeaningfulId)&&!a.isVisual&&(!a.isStructural||!!d)&&(s||u||d)))}(e,u,r,n,i):!u.isStructural&&!u.isVisual||(o=e,a=u,s=n,!!o.hittable||!!a.hasMeaningfulText||!!a.hasMeaningfulId||s)}(r,t.options,o,function e(t,r){let n=t.interactiveDescendantMemo.get(r);if(void 0!==n)return n;for(let n of r.children)if(!1!==n.visibleToUser&&(n.hittable||e(t,n)))return t.interactiveDescendantMemo.set(r,!0),!0;return t.interactiveDescendantMemo.set(r,!1),!1}(t,r),a)?function(e,t,r,n){let i=e.nodes.length;return e.sourceNodes.push(t),e.nodes.push({index:i,type:t.type??void 0,label:t.label??void 0,value:t.value??void 0,identifier:t.identifier??void 0,bundleId:t.packageName??void 0,rect:t.rect,enabled:t.enabled,visibleToUser:t.visibleToUser,hittable:t.hittable,depth:r,parentIndex:n,...t.hiddenContentAbove?{hiddenContentAbove:!0}:{},...t.hiddenContentBelow?{hiddenContentBelow:!0}:{}}),i}(t,r,n,i):i,u=o||!!r.hittable,d=a||function(e){if(!e)return!1;let t=V(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(r.type);for(let i of r.children)if(e(t,i,n+1,s,u,d),t.truncated)return}(n,t,0),n.truncated)break;let o={nodes:n.nodes,sourceNodes:n.sourceNodes,analysis:n.analysis};return n.truncated?{...o,truncated:!0}:o}function k(e,t,r){for(;t<r&&L(e[t]??"");)t+=1;return t}function L(e){return" "===e||"\n"===e||"\r"===e||" "===e}function O(e,t){return e.get(t)??null}function E(e){if(!e)return;let t=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),n=Number(t[2]);return{x:r,y:n,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-n)}}function P(e){let t={type:null,label:null,value:null,identifier:null,packageName:null,depth:-1,children:[]},r=[t],n=/<node\b[^>]*>|<\/node>/g,i=n.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=n.exec(e);continue}let o=_(t),a=r[r.length-1],s={type:o.className,label:o.text||o.desc,value:o.text,identifier:o.resourceId,packageName:o.packageName,rect:o.rect,enabled:o.enabled,visibleToUser:o.visibleToUser,drawingOrder:o.drawingOrder,hittable:o.clickable??o.focusable,scrollable:o.scrollable,canScrollForward:o.canScrollForward,canScrollBackward:o.canScrollBackward,windowIndex:o.windowIndex,windowType:o.windowType,windowLayer:o.windowLayer,windowActive:o.windowActive,windowFocused:o.windowFocused,windowRect:o.windowRect,depth:a.depth+1,parentIndex:void 0,children:[]};a.children.push(s),t.endsWith("/>")||r.push(s),i=n.exec(e)}return function e(t){let r=0;for(let n of t.children)!1!==n.visibleToUser&&(e(n),t.children[r]=n,r+=1);r<t.children.length&&(t.children.length=r)}(t),function(e){let t,r=e.children.filter(U);if(r.length<2)return;let n=r.filter(e=>$(e)&&H(e));if(0===n.length)return;let i=(t=n.map(e=>e.windowLayer).filter(e=>void 0!==e)).length>0?Math.max(...t):void 0;e.children=e.children.filter(e=>!$(e)||!!H(e)&&(void 0===i||e.windowLayer===i))}(t),function e(t,r){for(let n of t.children)e(n,r);if(t.children.length<2)return;let n=t.children,i=n.filter(e=>{var t,n;return t=e,n=r,!1!==t.visibleToUser&&void 0!==t.drawingOrder&&R(t)&&(function(e){if(!1===e.visibleToUser)return!1;if(e.hittable)return!0;let t=e.label?.trim()??"";if(t&&!B(t))return!0;let r=e.identifier?.trim()??"";return!(!r||B(r))}(t)||function e(t,r){let n=r.actionableContentMemo.get(t);if(void 0!==n)return n;let i=t.children.some(t=>!1!==t.visibleToUser&&(!!t.hittable||e(t,r)));return r.actionableContentMemo.set(t,i),i}(t,n))});0!==i.length&&(t.children=n.filter(e=>!function(e,t){if(!1===e.visibleToUser||void 0===e.drawingOrder||!R(e))return!1;for(let r of t)if(r!==e&&!(r.drawingOrder<=e.drawingOrder)&&function(e,t){let r=t.width*t.height;return r<=0?0:s(e,t)/r}(r.rect,e.rect)>=.9)return!0;return!1}(e,i)))}(t,{actionableContentMemo:new WeakMap}),function(e){let t=[...e.children];for(;t.length>0;){let e=t.pop();t.push(...e.children),function(e){if(!e.scrollable||!l(e.type)||`${e.type??""}`.toLowerCase().includes("horizontalscrollview"))return!1;let t=function(e){if(!e.rect||0===e.children.length)return null;let t=e.children.map(e=>e.rect).filter(e=>void 0!==e);if(0===t.length)return null;let r=Math.min(...t.map(e=>e.x)),n=Math.max(...t.map(e=>e.x+e.width)),i=Math.min(...t.map(e=>e.y)),o=Math.max(...t.map(e=>e.y+e.height));return{horizontal:Math.max(0,n-r-e.rect.width),vertical:Math.max(0,o-i-e.rect.height)}}(e);return!t||!(t.horizontal>t.vertical)||!(t.horizontal>16)}(e)&&(e.canScrollBackward&&(e.hiddenContentAbove=!0),e.canScrollForward&&(e.hiddenContentBelow=!0))}}(t),t}function R(e){return!!(e.rect&&e.rect.width>0&&e.rect.height>0)}function U(e){return void 0!==e.windowIndex||void 0!==e.windowType}function $(e){return 1===e.windowType}function H(e){return!0===e.windowActive||!0===e.windowFocused}function V(e){return e?e.toLowerCase():""}function B(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function K(e){let t=G(e),r=await e.adb(W(t),{allowFailure:!0,timeoutMs:t.commandTimeoutMs}),{output:n,cleanupDone:i}=await X(e,t,r);if(t.outputPath&&!i&&await J(e.adb,t.outputPath),0!==r.exitCode)throw new a("COMMAND_FAILED","Android snapshot helper failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,helper:n.metadata});return n}function G(e){let t=Q(e.timeoutMs,8e3),r=Q(e.packageName,h);return{waitForIdleTimeoutMs:Q(e.waitForIdleTimeoutMs,500),waitForIdleQuietMs:Q(e.waitForIdleQuietMs,100),timeoutMs:t,commandTimeoutMs:Q(e.commandTimeoutMs,t+5e3),maxDepth:Q(e.maxDepth,128),maxNodes:Q(e.maxNodes,5e3),packageName:r,runner:Q(e.instrumentationRunner,`${r}/.SnapshotInstrumentation`),...e.outputPath?{outputPath:e.outputPath}:{},...void 0!==e.emitChunks?{emitChunks:e.emitChunks}:{}}}function Q(e,t){return void 0===e?t:e}function W(e){return["shell","am","instrument","-w","-e","waitForIdleTimeoutMs",String(e.waitForIdleTimeoutMs),"-e","waitForIdleQuietMs",String(e.waitForIdleQuietMs),"-e","timeoutMs",String(e.timeoutMs),"-e","maxDepth",String(e.maxDepth),"-e","maxNodes",String(e.maxNodes),...e.outputPath?["-e","outputPath",e.outputPath]:[],...void 0!==e.emitChunks?["-e","emitChunks",String(e.emitChunks)]:[],e.runner]}async function X(e,t,r){try{return{output:Y(`${r.stdout}
2
- ${r.stderr}`),cleanupDone:!1}}catch(n){return await z(e,t,r,n)}}async function z(e,t,r,n){if(n instanceof a&&0!==r.exitCode&&n.details?.helper)throw n;let i=await j(e,t,r);if(i)return{output:i,cleanupDone:!0};throw new a("COMMAND_FAILED",0===r.exitCode?"Android snapshot helper output could not be parsed":"Android snapshot helper failed before returning parseable output",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode},n)}async function j(e,t,r){if(0===r.exitCode&&t.outputPath){var n;return await q(e.adb,t.outputPath,function(e){try{let t=er(e);return et(ee(t.results))}catch{return null}}(`${r.stdout}
3
- ${r.stderr}`)??{outputFormat:w,waitForIdleTimeoutMs:(n=t).waitForIdleTimeoutMs,waitForIdleQuietMs:n.waitForIdleQuietMs,timeoutMs:n.timeoutMs,maxDepth:n.maxDepth,maxNodes:n.maxNodes,transport:"instrumentation"})}}async function q(e,t,r){let n;try{var i;n=await e((i=t,["shell","sh","-c",'cat "$1"; status=$?; rm -f "$1"; exit "$status"',"agent-device-snapshot-helper-output",i]),{allowFailure:!0,timeoutMs:5e3})}catch{return}if(0!==n.exitCode)return;let o=n.stdout.trim();if(o.includes("<hierarchy")&&o.includes("</hierarchy>"))return{xml:o,metadata:r}}async function J(e,t){try{await e(["shell","rm","-f",t],{allowFailure:!0,timeoutMs:5e3})}catch{}}function Y(e){let t=er(e),r=ee(t.results);return{xml:function(e,t){if(0===e.length)throw new a("COMMAND_FAILED","Android snapshot helper did not return XML chunks",{helper:t});let r=function(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{expectedChunks:t,actualChunks:e.length});return t}(e),n=Buffer.concat(function(e,t){let r=[];for(let n=0;n<t;n+=1){let i=e.get(n);if(void 0===i)throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{missingChunkIndex:n,expectedChunks:t});r.push(Buffer.from(i,"base64"))}return r}(function(e,t){let r=new Map;for(let n of e){if(void 0===n.index||n.index<0||n.index>=t)throw new a("COMMAND_FAILED","Android snapshot helper returned invalid chunk index",{chunkIndex:n.index,expectedChunks:t});if(r.has(n.index))throw new a("COMMAND_FAILED","Android snapshot helper returned duplicate XML chunks",{chunkIndex:n.index});r.set(n.index,n.payloadBase64)}return r}(e,r),r)).toString("utf8");if(!n.includes("<hierarchy")||!n.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper output did not contain XML",{xml:n});return n}(function(e){let t=[];for(let r of e){if(r.agentDeviceProtocol!==f||r.outputFormat!==w)continue;let{payloadBase64:e}=r;void 0!==e&&t.push({index:el(r.chunkIndex),count:el(r.chunkCount),payloadBase64:e})}return t}(t.status),r),metadata:{...et(r),transport:"instrumentation"}}}function Z(e,t={outputFormat:w},r={},n){return{...T(e,n,r),metadata:t}}function ee(e){let t=e.find(e=>e.agentDeviceProtocol===f);if(!t)throw new a("COMMAND_FAILED","Android snapshot helper did not return a final result");if("true"!==t.ok){var r;throw new a("COMMAND_FAILED",(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android snapshot helper returned an error",{errorType:t.errorType,helper:t})}return t}function et(e){var t;return{helperApiVersion:e.helperApiVersion,outputFormat:w,waitForIdleTimeoutMs:el(e.waitForIdleTimeoutMs),waitForIdleQuietMs:el(e.waitForIdleQuietMs),timeoutMs:el(e.timeoutMs),maxDepth:el(e.maxDepth),maxNodes:el(e.maxNodes),rootPresent:eu(e.rootPresent),captureMode:"interactive-windows"===(t=e.captureMode)||"active-window"===t?t:void 0,windowCount:el(e.windowCount),nodeCount:el(e.nodeCount),truncated:eu(e.truncated),elapsedMs:el(e.elapsedMs)}}function er(e){var t;let r={status:[],results:[],currentStatus:null,currentResult:null};for(let t of e.split(/\r?\n/))!function(e,t){if(e.startsWith("INSTRUMENTATION_STATUS: ")){t.currentStatus??={},eo(e.slice(24),t.currentStatus);return}if(e.startsWith("INSTRUMENTATION_STATUS_CODE: "))return en(t);if(e.startsWith("INSTRUMENTATION_RESULT: ")){t.currentResult??={},eo(e.slice(24),t.currentResult);return}e.startsWith("INSTRUMENTATION_CODE: ")&&ei(t)}(t,r);return en(t=r),ei(t),{status:r.status,results:r.results}}function en(e){e.currentStatus&&(e.status.push(e.currentStatus),e.currentStatus=null)}function ei(e){e.currentResult&&(e.results.push(e.currentResult),e.currentResult=null)}function eo(e,t){let r=e.indexOf("=");r<0||(t[e.slice(0,r)]=e.slice(r+1))}function ea(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function es(e){return"true"===e||"false"!==e&&void 0}let el=ea,eu=es,ed=new Map,ec=new Map;async function eh(e){var t,r,n;let i;if(!(void 0===(i=process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION)||!/^(0|false|no|off)$/i.test(i))||!e.adbProvider?.spawn)return;let o=G(e),a=e.deviceKey??"android:default",s=(t=a,r=o,n=e,JSON.stringify({deviceKey:t,packageName:r.packageName,runner:r.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,waitForIdleTimeoutMs:r.waitForIdleTimeoutMs,waitForIdleQuietMs:r.waitForIdleQuietMs,timeoutMs:r.timeoutMs,maxDepth:r.maxDepth,maxNodes:r.maxNodes}));if(ec.get(a)===s)return;let l=ed.get(a);if(l&&l.identity!==s&&(await ep(a),l=void 0),!l)try{l=await em({deviceKey:a,identity:s,options:e,resolved:o})}catch(e){ec.set(a,s),u({level:"warn",phase:"android_snapshot_helper_session_disabled",data:{deviceKey:a,reason:e instanceof Error?e.message:String(e)}});return}try{let e=l.capturedCount>0,t=await eM(l,o);return l.capturedCount+=1,{xml:t.xml,metadata:{...t.metadata,transport:"persistent-session",sessionReused:e}}}catch(e){throw await ep(a),e}}async function ep(e){let t=ed.get(e);if(t){ed.delete(e);try{await eg(t,`quit ${Date.now()}`,1e3)}catch{}try{await t.process.kill("SIGTERM")}catch{}await eA(t.process,2e3);try{await ev(t)}catch{}u({phase:"android_snapshot_helper_session_stop",data:{deviceKey:e,port:t.port,capturedCount:t.capturedCount,lifetimeMs:Date.now()-t.startedAtMs}})}}async function ef(e){await ep(ew(e))}function ew(e){return`${e.platform}:${e.id}`}async function em(e){let t=await new Promise((e,t)=>{let r=o.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(!n||"string"==typeof n)return void r.close(()=>t(Error("Failed to allocate a local TCP port")));let i=n.port;r.close(()=>e(i))})});await e.options.adb(["forward",`tcp:${t}`,`tcp:${t}`],{allowFailure:!1,timeoutMs:5e3});let r=W({...e.resolved,outputPath:void 0,emitChunks:!1}),n=r[r.length-1];if(!n)throw new a("INVALID_ARGS","Android snapshot helper runner was not resolved");let i=[...r.slice(0,-1),"-e","sessionPort",String(t),n],s=e.options.adbProvider.spawn(i,{allowFailure:!0,captureOutput:!1}),l={identity:e.identity,deviceKey:e.deviceKey,port:t,adb:e.options.adb,process:s,startedAtMs:Date.now(),capturedCount:0};try{var d;return await (d=s,new Promise((e,t)=>{let r="",n=setTimeout(()=>{t(new a("COMMAND_FAILED","Android snapshot helper session did not become ready",{output:r,timeoutMs:1e4}))},1e4),i=t=>{(r+=t.toString()).includes(`agentDeviceProtocol=${f}`)&&r.includes("sessionReady=true")&&(clearTimeout(n),e())};d.stdout?.on("data",i),d.stderr?.on("data",i),d.once("exit",(e,i)=>{clearTimeout(n),t(new a("COMMAND_FAILED","Android snapshot helper session exited before ready",{output:r,exitCode:e,signal:i}))}),d.on("error",e=>{clearTimeout(n),t(e)})})),ed.set(e.deviceKey,l),u({phase:"android_snapshot_helper_session_ready",data:{deviceKey:e.deviceKey,port:t,packageName:e.resolved.packageName,runner:e.resolved.runner}}),l}catch(e){await ev(l);try{s.kill("SIGTERM")}catch{}throw await eA(s,2e3),e}}function eA(e,t){return new Promise(r=>{let n=setTimeout(r,t);e.once("close",()=>{clearTimeout(n),r()}),e.once("exit",()=>{clearTimeout(n),r()})})}async function eM(e,t){let r=`snapshot-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=Math.min(t.commandTimeoutMs,Math.max(t.timeoutMs+1e4,3e3));return function(e,t){var r;let{headers:n,xml:i}=function(e){let t=e.indexOf("\n\n");if(t<0)throw new a("COMMAND_FAILED","Android snapshot helper session returned malformed output",{response:e});return{headers:function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.indexOf("=");e<0||(t[r.slice(0,e)]=r.slice(e+1))}return t}(e.slice(0,t)),xml:e.slice(t+2)}}(e);return function(e,t){if(e.agentDeviceProtocol!==f)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong protocol",{headers:e});if(e.outputFormat!==w)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong output format",{headers:e});if(e.requestId!==t)throw new a("COMMAND_FAILED","Android snapshot helper session returned stale output",{headers:e,requestId:t});if("true"!==e.ok)throw new a("COMMAND_FAILED",e.message||e.errorType||"Android snapshot helper session returned an error",{helper:e})}(n,t),function(e,t){let r=ea(e.byteLength);if(void 0!==r&&Buffer.byteLength(t,"utf8")!==r)throw new a("COMMAND_FAILED","Android snapshot helper session returned truncated XML",{headers:e,actualByteLength:Buffer.byteLength(t,"utf8")});if(!t.includes("<hierarchy")||!t.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper session did not return XML",{headers:e,xml:t})}(n,i),{xml:i,metadata:{helperApiVersion:(r=n).helperApiVersion,outputFormat:w,waitForIdleTimeoutMs:ea(r.waitForIdleTimeoutMs),waitForIdleQuietMs:ea(r.waitForIdleQuietMs),timeoutMs:ea(r.timeoutMs),maxDepth:ea(r.maxDepth),maxNodes:ea(r.maxNodes),rootPresent:es(r.rootPresent),captureMode:"interactive-windows"===r.captureMode||"active-window"===r.captureMode?r.captureMode:void 0,windowCount:ea(r.windowCount),nodeCount:ea(r.nodeCount),truncated:es(r.truncated),elapsedMs:ea(r.elapsedMs)}}}(await eg(e,`snapshot ${r}`,n),r)}function eg(e,t,r){return new Promise((n,i)=>{let s=o.connect({host:"127.0.0.1",port:e.port}),l=[],u=setTimeout(()=>{s.destroy(),i(new a("COMMAND_FAILED","Android snapshot helper session request timed out",{command:t,timeoutMs:r,port:e.port}))},r);s.on("connect",()=>{s.write(`${t}
4
- `)}),s.on("data",e=>{l.push(Buffer.from(e))}),s.on("error",e=>{clearTimeout(u),i(e)}),s.on("close",()=>{clearTimeout(u),n(Buffer.concat(l).toString("utf8"))})})}async function ev(e){await e.process.stdin?.end(),await e.process.stdout?.destroy(),await e.process.stderr?.destroy(),await eN(e)}async function eN(e){await e.adb(["forward","--remove",`tcp:${e.port}`],{allowFailure:!0,timeoutMs:5e3})}let ey=new Map;function ex(e){eD(eI(e.deviceKey,e.packageName,e.versionCode))}function eI(e,t,r){return e?`${e}\0${t}\0${r}`:void 0}function eD(e){e&&ey.delete(e)}async function eC(e){var t,r,n;let{adb:i,artifact:o}=e,s=e.installPolicy??"missing-or-outdated",l=o.manifest.packageName,u=o.manifest.versionCode;if("never"===s)return{packageName:l,versionCode:u,installed:!1,reason:"skipped"};let d=eI(e.deviceKey,l,u),c=d?ey.get(d):void 0;if(d&&"always"!==s&&void 0!==c)return{packageName:l,versionCode:u,installedVersionCode:c,installed:!1,reason:"current"};let h=await eb(i,l,e.timeoutMs),p=(t=s,r=h,n=u,"never"===t?"skipped":"always"===t?"forced":void 0===r?"missing":r<n?"outdated":"current");if("current"===p){if(void 0===h)throw Error("Expected installed versionCode for current Android snapshot helper");return d&&ey.set(d,h),{packageName:l,versionCode:u,installedVersionCode:h,installed:!1,reason:p}}await A(o);let f=await eS(i,e.adbProvider??i,o.apkPath,function(e){let t={};for(let r of e.slice(1)){let e=b(r);if(!e)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);t[e]=!0}return t}(N(o.manifest.installArgs)),{packageName:l,timeoutMs:e.timeoutMs});if(0!==f.exitCode)throw eD(d),new a("COMMAND_FAILED","Failed to install Android snapshot helper",{packageName:l,versionCode:u,stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode});return d&&ey.set(d,u),{packageName:l,versionCode:u,installedVersionCode:h,installed:!0,reason:p}}async function eb(e,t,r){let n=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:r});if(0===n.exitCode){var i=`${n.stdout}
5
- ${n.stderr}`,o=t;let e=`package:${o}`;for(let t of i.split(/\r?\n/)){if(!t.startsWith(e)||t.length>e.length&&!/\s/.test(t[e.length]??""))continue;let r=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(r)return Number(r[1])}return}}async function eS(e,t,r,n,i){var o;let a=async()=>await d(r,{allowFailure:!0,provider:t,...n,timeoutMs:i.timeoutMs}),s=await a();if(0===s.exitCode||(o=s,!`${o.stdout}
6
- ${o.stderr}`.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")))return s;let l=await e(["uninstall",i.packageName],{allowFailure:!0,timeoutMs:i.timeoutMs}),u=await a();return 0===u.exitCode?u:{...u,stderr:[u.stderr,l.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${l.stderr}`:""].filter(Boolean).join("\n")}}export{c as ANDROID_SNAPSHOT_HELPER_NAME,w as ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT,h as ANDROID_SNAPSHOT_HELPER_PACKAGE,f as ANDROID_SNAPSHOT_HELPER_PROTOCOL,p as ANDROID_SNAPSHOT_HELPER_RUNNER,S as androidUiNodes,F as buildUiHierarchySnapshot,K as captureAndroidSnapshotWithHelper,eh as captureAndroidSnapshotWithHelperSession,eC as ensureAndroidSnapshotHelper,ex as forgetAndroidSnapshotHelperInstall,ew as getAndroidSnapshotHelperSessionDeviceKey,g as parseAndroidSnapshotHelperManifest,Y as parseAndroidSnapshotHelperOutput,Z as parseAndroidSnapshotHelperXml,T as parseUiHierarchy,P as parseUiHierarchyTree,M as prepareAndroidSnapshotHelperArtifactFromManifestUrl,ep as stopAndroidSnapshotHelperSession,ef as stopAndroidSnapshotHelperSessionForDevice,A as verifyAndroidSnapshotHelperArtifact};
package/dist/src/8275.js DELETED
@@ -1,2 +0,0 @@
1
- import e from"node:fs";import t from"node:path";import{createHash as r}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdDetached as o,runCmdSync as i}from"./8875.js";import{readProcessCommand as a,waitForProcessExit as s,isProcessAlive as l,readProcessStartTime as u}from"./9414.js";import{normalizeBaseUrl as c,ENV_COMPANION_TUNNEL_BEARER_TOKEN as d,ENV_COMPANION_TUNNEL_SERVER_BASE_URL as p,ENV_COMPANION_TUNNEL_STATE_PATH as m,ENV_COMPANION_TUNNEL_LAUNCH_URL as h,ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID as f,ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID as g,ENV_COMPANION_TUNNEL_DEVICE_PORT as y,buildBundleUrl as b,METRO_COMPANION_RUN_ARG as P,ENV_COMPANION_TUNNEL_SESSION as S,ENV_COMPANION_TUNNEL_SCOPE_RUN_ID as w,ENV_COMPANION_TUNNEL_REGISTER_PATH as _,ENV_COMPANION_TUNNEL_LOCAL_BASE_URL as E,ENV_COMPANION_TUNNEL_UNREGISTER_PATH as v}from"./4069.js";import{AppError as U}from"./733.js";import{resolveUserPath as M}from"./9612.js";import{resolveRuntimeTransportHints as I}from"./8936.js";import{sleep as k}from"./5560.js";let T="companion-tunnel";function A(e){return r("sha256").update(e).digest("hex")}function N(e){return e?.trim()?e.trim():void 0}function R(e,r,n,o){let i=o??t.join(e,".agent-device");if(!n)return{statePath:t.join(i,`${r.slug}.json`),logPath:t.join(i,`${r.slug}.log`)};let a=A(n).slice(0,12),s=t.join(i,r.slug);return{statePath:t.join(s,`${r.slug}-${a}.json`),logPath:t.join(s,`${r.slug}-${a}.log`)}}function $(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:N("string"==typeof r.launchUrl?r.launchUrl:void 0),registerPath:N("string"==typeof r.registerPath?r.registerPath:void 0),unregisterPath:N("string"==typeof r.unregisterPath?r.unregisterPath:void 0),devicePort:Number.isInteger(r.devicePort)?Number(r.devicePort):void 0,session:N("string"==typeof r.session?r.session:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(r.bridgeScope),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function x(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
2
- `,"utf8")}function j(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function B(r,n){let o=t.dirname(r.statePath),i=t.dirname(r.logPath);var a=r.statePath;try{e.unlinkSync(a)}catch{}var s=r.logPath;try{e.unlinkSync(s)}catch{}j(o),i!==o&&j(i),t.basename(o)===n.slug&&j(t.dirname(o))}function C(e,t){return e.includes(t.runArg)}function D(e){return N(e.consumerKey)??N(e.profileKey)??null}function H(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function K(e,t){if(!l(e.pid))return;let r=a(e.pid);if(r&&C(r,t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await s(e.pid,1e3)}}}async function O(r){var i;let s,b=D(r),P=R(r.projectRoot,r.definition,r.profileKey,r.stateDir),U=$(P.statePath);if(U&&function(e,t){var r,n;if(!l(e.pid))return!1;if(e.startTime){let t=u(e.pid);if(!t||t!==e.startTime)return!1}let o=a(e.pid);return!!o&&!!C(o,t.definition)&&!!e.bridgeScope&&e.serverBaseUrl===c(t.serverBaseUrl)&&e.localBaseUrl===c(t.localBaseUrl)&&e.launchUrl===N(t.launchUrl)&&e.registerPath===N(t.registerPath)&&e.unregisterPath===N(t.unregisterPath)&&e.devicePort===t.devicePort&&e.session===N(t.session)&&(r=e.bridgeScope,n=t.bridgeScope,r.tenantId===n.tenantId&&r.runId===n.runId&&r.leaseId===n.leaseId)&&e.tokenHash===A(t.bearerToken)}(U,r)){let e=H(U,b);return e!==U&&x(P.statePath,e),{pid:U.pid,spawned:!1,statePath:P.statePath,logPath:P.logPath}}U&&(await K(U,r.definition),B(P,r.definition)),i=P.statePath,e.mkdirSync(t.dirname(i),{recursive:!0}),e.closeSync(e.openSync(i,"a"));try{s=function(r,i){let s=function(r){let o=n(import.meta.url),i=t.extname(o)||".js",a=[t.join(t.dirname(o),`${T}${i}`),t.join(t.dirname(o),"internal",`${T}${i}`)].find(t=>e.existsSync(t));if(!a)throw Error(`${r.displayName} entrypoint not found. Rebuild the package to include the companion worker entry.`);return a}(r.definition),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(i),{recursive:!0});let b=e.openSync(i,"a"),P=0;try{let e;P=o(process.execPath,[...l,s,r.definition.runArg],{env:((e={...r.env??process.env})[p]=c(r.serverBaseUrl),e[d]=r.bearerToken,e[E]=c(r.localBaseUrl),e[m]=R(r.projectRoot,r.definition,r.profileKey,r.stateDir).statePath,e[g]=r.bridgeScope.tenantId,e[w]=r.bridgeScope.runId,e[f]=r.bridgeScope.leaseId,r.launchUrl?.trim()?e[h]=r.launchUrl.trim():delete e[h],r.registerPath?.trim()?e[_]=r.registerPath.trim():delete e[_],r.unregisterPath?.trim()?e[v]=r.unregisterPath.trim():delete e[v],void 0!==r.devicePort?e[y]=String(r.devicePort):delete e[y],r.session?.trim()?e[S]=r.session.trim():delete e[S],e),stdio:["ignore",b,b]})}finally{e.closeSync(b)}if(!Number.isInteger(P)||P<=0)throw Error(`Failed to start ${r.definition.displayName} process.`);return{pid:P,startTime:u(P)??void 0,command:a(P)??void 0,serverBaseUrl:c(r.serverBaseUrl),localBaseUrl:c(r.localBaseUrl),launchUrl:N(r.launchUrl),registerPath:N(r.registerPath),unregisterPath:N(r.unregisterPath),devicePort:r.devicePort,session:N(r.session),bridgeScope:r.bridgeScope,tokenHash:A(r.bearerToken),consumers:[]}}(r,P.logPath),x(P.statePath,H(s,b))}catch(e){throw s&&await K(s,r.definition).catch(()=>{}),B(P,r.definition),e}return{pid:s.pid,spawned:!0,statePath:P.statePath,logPath:P.logPath}}async function L(e){let t=D(e),r=R(e.projectRoot,e.definition,e.profileKey,e.stateDir),n=$(r.statePath);if(!n)return B(r,e.definition),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(x(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await K(n,e.definition),B(r,e.definition),{stopped:!0,statePath:r.statePath})}let G={slug:"metro-companion",runArg:P,displayName:"Metro companion"};async function F(e){return await O({...e,definition:G,registerPath:e.registerPath??"/api/metro/companion/register"})}async function J(e){return await L({...e,definition:G})}function V(e){return"string"==typeof e&&e.trim()?c(e.trim()):""}function q(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function W(e,t,r){return M(e,{env:t,cwd:r})}function z(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function Q(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function X(e,t){if(null==e||""===e)return t;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new U("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}function Y(e,t){return{platform:t,bundleUrl:b(e,t)}}function Z(e,t){return{platform:t,metroHost:q(e?.metro_host),metroPort:e?.metro_port,bundleUrl:q(e?.metro_bundle_url),launchUrl:q(e?.launch_url)}}async function ee(e){await k(e)}async function et(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function er(e,t){try{let r=await et(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function en(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await s(e,1e3)}}}function eo(e,t){let r=Error(e);return r.retryable=t,r}function ei(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}function ea(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function es(e){let t;try{var r,n;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...r.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw eo(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw eo(t instanceof Error?t.message:String(t),!0)}let o=function(e,t,r){if(!e)return{};try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Expected a JSON object");return t}catch(i){let n=e.slice(0,200),o=i instanceof Error?i.message:String(i);throw eo(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${o}. body=${JSON.stringify(n)}`,ei(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw eo(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(o)}`,ei(t.status,o));var i=o;let a=i.data??i;if(!a||"object"!=typeof a||Array.isArray(a))throw eo("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:a.enabled,baseUrl:a.base_url,statusUrl:a.status_url??"",bundleUrl:a.bundle_url??"",iosRuntime:Z(a.ios_runtime,"ios"),androidRuntime:Z(a.android_runtime,"android"),upstream:{bundleUrl:a.upstream.bundle_url??"",host:a.upstream.host??"",port:a.upstream.port??0,statusUrl:a.upstream.status_url??""},probe:{reachable:a.probe.reachable,statusCode:a.probe.status_code,latencyMs:a.probe.latency_ms,detail:a.probe.detail}}}catch(e){throw eo(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function el(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function eu(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await er(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await ee(o)}return!1}async function ec(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await es({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!ea(e))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await ee(o)}throw Error(el(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function ed(r){let n=`http://${r.statusHost}:${r.metroPort}/status`;if(r.reuseExisting&&await er(n,r.probeTimeoutMs))return{started:!1,reused:!0,pid:0,statusUrl:n};let i=function(r,n,i,a,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(i)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(i)]};e.mkdirSync(t.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=o(u.command,u.installArgs,{cwd:r,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(r.projectRoot,r.kind,r.metroPort,r.listenHost,r.logPath,r.env);if(await eu(n,r.startupTimeoutMs,r.probeTimeoutMs))return{started:!0,reused:!1,pid:i.pid,statusUrl:n};throw await en(i.pid).catch(()=>{}),Error(`Metro did not become ready at ${n} within ${r.startupTimeoutMs}ms. Check ${r.logPath}.`)}async function ep(e,t){let r=t.bridgeScope;if(!r)return null;let n=null,o=null;try{n=await es({baseUrl:t.proxyBaseUrl,bearerToken:t.proxyBearerToken,scope:r,timeoutMs:t.probeTimeoutMs})}catch(e){if(!ea(e))throw e;o=e instanceof Error?e.message:String(e)}n&&!1!==n.probe.reachable||(n=await em(e,t,r,n,o));var i=t.proxyBaseUrl,a=n;if(!a?.iosRuntime.bundleUrl)throw Error(el(i,"bridge descriptor is missing ios_runtime.metro_bundle_url",a));return n}async function em(e,t,r,n,o){let i;try{i=(await F({projectRoot:t.projectRoot,serverBaseUrl:t.proxyBaseUrl,bearerToken:t.proxyBearerToken,bridgeScope:r,localBaseUrl:`http://${t.statusHost}:${t.metroPort}`,launchUrl:q(e.launchUrl),profileKey:q(e.companionProfileKey),consumerKey:q(e.companionConsumerKey),env:t.env})).logPath}catch(e){throw Error(el(t.proxyBaseUrl,e instanceof Error?e.message:String(e),n,o))}try{return await ec({baseUrl:t.proxyBaseUrl,bearerToken:t.proxyBearerToken,scope:r,probeTimeoutMs:t.probeTimeoutMs,startupTimeoutMs:t.startupTimeoutMs,initialBridgeError:o,companionLogPath:i})}catch(e){throw e instanceof Error?e:Error(String(e))}}async function eh(r={}){var n,o;let a=function(r){let n=r.env??process.env,o=process.cwd(),i=W(r.projectRoot??o,n,o),a=V(r.publicBaseUrl),s=V(r.proxyBaseUrl);if(!a&&!s)throw new U("INVALID_ARGS","metro prepare requires --public-base-url <url> or --proxy-base-url <url>.");let{proxyEnabled:l,proxyBaseUrl:u,proxyBearerToken:c}=function(e,t,r){let n=t||q(r.AGENT_DEVICE_METRO_BEARER_TOKEN)||"",o=n||e&&q(r.AGENT_DEVICE_DAEMON_AUTH_TOKEN)||"";if(e&&!o)throw new U("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_METRO_BEARER_TOKEN or AGENT_DEVICE_DAEMON_AUTH_TOKEN.");if(!e&&n)throw new U("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&o),proxyBaseUrl:e,proxyBearerToken:o}}(s,q(r.proxyBearerToken)??"",n);return{env:n,projectRoot:i,kind:function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!z(n))throw new U("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),metroPort:X(r.metroPort??8081,8081),listenHost:q(r.listenHost)??"0.0.0.0",statusHost:q(r.statusHost)??"127.0.0.1",publicBaseUrl:a,proxyBaseUrl:u,proxyBearerToken:c,bridgeScope:l?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new U("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(r.bridgeScope):null,startupTimeoutMs:Q(r.startupTimeoutMs,18e4,3e4),probeTimeoutMs:Q(r.probeTimeoutMs,1e4,1e3),reuseExisting:r.reuseExisting??!0,installProjectDeps:r.installDependenciesIfNeeded??!0,runtimeFilePath:r.runtimeFilePath?W(r.runtimeFilePath,n,o):null,logPath:W(r.logPath??t.join(i,".agent-device","metro.log"),n,o)}}(r),s=a.installProjectDeps?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=z(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:z(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return i(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(a.projectRoot,a.env):{installed:!1},l=await ed(a),{baseIosRuntime:u,baseAndroidRuntime:c}={baseIosRuntime:(n=a.publicBaseUrl)?Y(n,"ios"):{platform:"ios"},baseAndroidRuntime:n?Y(n,"android"):{platform:"android"}},d=await ep(r,a),p=d?.iosRuntime??u,m=d?.androidRuntime??c,h={projectRoot:a.projectRoot,kind:a.kind,dependenciesInstalled:s.installed,packageManager:s.packageManager??null,started:l.started,reused:l.reused,pid:l.pid,logPath:a.logPath,statusUrl:l.statusUrl,runtimeFilePath:a.runtimeFilePath,iosRuntime:p,androidRuntime:m,bridge:d};return o=a.runtimeFilePath,o&&(e.mkdirSync(t.dirname(o),{recursive:!0}),e.writeFileSync(o,JSON.stringify(h,null,2))),h}async function ef(e={}){let t=Q(e.timeoutMs,1e4,1e3),r=function(e){var t;let r,n=q(e.bundleUrl),o=n??e.runtime?.bundleUrl,i=!!n,a=!!q(o),s=I({metroHost:q(e.metroHost)??(i?void 0:q(e.runtime?.metroHost))??(a?void 0:"localhost"),metroPort:void 0!==e.metroPort?X(e.metroPort,8081):i?void 0:e.runtime?.metroPort??(a?void 0:8081),bundleUrl:o});if(!s)throw new U("INVALID_ARGS","Unable to resolve Metro host and port for reload.");return t=function(e){let t=q(e);if(!t)return"/reload";let r=new URL(t).pathname.replace(/\/+$/,"");return r.endsWith("/index.bundle")?`${r.slice(0,-13)}/reload`:"/reload"}(o),(r=new URL(`${s.scheme}://localhost`)).hostname=s.host,r.port=String(s.port),r.pathname=t,r.toString()}(e),n=await et(r,t);if(!n.ok)throw new U("COMMAND_FAILED",`Metro reload failed (${n.status}).`,{reloadUrl:r,status:n.status,body:n.body,hint:"Verify Metro is running and the target React Native app is connected to this Metro instance."});return{reloaded:!0,reloadUrl:r,status:n.status,body:n.body}}export{Y as buildMetroRuntimeHints,O as ensureCompanionTunnel,F as ensureMetroCompanion,eh as prepareMetroRuntime,ef as reloadMetro,L as stopCompanionTunnel,J as stopMetroCompanion};