agent-device 0.21.2 → 0.21.4

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 (164) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.apk → agent-device-android-ime-helper-0.21.4.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.4.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.manifest.json → agent-device-android-ime-helper-0.21.4.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.2.apk → agent-device-android-snapshot-helper-0.21.4.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.manifest.json +16 -0
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +39 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +9 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +10 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -124
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +46 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +229 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +15 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +4 -40
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +6 -40
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +30 -9
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/adb-executor.js +2 -2
  22. package/dist/src/adb-failure.js +1 -1
  23. package/dist/src/agent-browser-process-record.js +1 -1
  24. package/dist/src/agent-device-client.js +2 -2
  25. package/dist/src/api.js +3 -11
  26. package/dist/src/app-launch.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-reconnect.js +1 -1
  29. package/dist/src/archive.js +2 -2
  30. package/dist/src/auth.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-help.js +2 -2
  33. package/dist/src/cli.js +4 -4
  34. package/dist/src/client-metro-companion.js +1 -1
  35. package/dist/src/client-metro.js +1 -1
  36. package/dist/src/client-types.d.ts +70 -5
  37. package/dist/src/code-signature-cache.js +1 -1
  38. package/dist/src/command-schema.js +1 -1
  39. package/dist/src/command-tools.js +2 -2
  40. package/dist/src/command.js +1 -1
  41. package/dist/src/config.js +1 -1
  42. package/dist/src/connection-runtime.js +1 -1
  43. package/dist/src/connection.js +1 -1
  44. package/dist/src/contracts.js +1 -1
  45. package/dist/src/daemon-client-lifecycle.js +1 -1
  46. package/dist/src/daemon-registration.js +1 -1
  47. package/dist/src/daemon-resolution.js +1 -0
  48. package/dist/src/daemon-shutdown-report.js +1 -1
  49. package/dist/src/daemon.js +1 -1
  50. package/dist/src/device-claim-rule.js +1 -1
  51. package/dist/src/device-input-state.d.ts +10 -8
  52. package/dist/src/device-inventory-context.js +1 -1
  53. package/dist/src/device-session.js +1 -1
  54. package/dist/src/diagnostics.js +1 -1
  55. package/dist/src/error.js +2 -2
  56. package/dist/src/exec.js +1 -1
  57. package/dist/src/file.js +1 -1
  58. package/dist/src/find.js +1 -1
  59. package/dist/src/gesture-runtime.js +1 -1
  60. package/dist/src/harmonyos.js +1 -1
  61. package/dist/src/helper.js +1 -1
  62. package/dist/src/human-control-contract.js +1 -1
  63. package/dist/src/human-control.js +1 -1
  64. package/dist/src/index.js +1 -1
  65. package/dist/src/install-source-network-transport.js +1 -1
  66. package/dist/src/interaction.js +1 -1
  67. package/dist/src/interaction2.js +1 -1
  68. package/dist/src/interactor.js +4 -4
  69. package/dist/src/interactors.js +1 -1
  70. package/dist/src/internal/bin.js +1 -1
  71. package/dist/src/internal/daemon.js +2 -2
  72. package/dist/src/internal/png-worker.js +1 -1
  73. package/dist/src/ios-client.js +121 -7
  74. package/dist/src/ios-snapshot-adapter.js +1 -1
  75. package/dist/src/ios-system-surface.js +1 -1
  76. package/dist/src/lease-scope.js +1 -1
  77. package/dist/src/limrun-delta-sync-omitted.js +1 -0
  78. package/dist/src/limrun.d.ts +0 -1598
  79. package/dist/src/location-coordinates.js +1 -1
  80. package/dist/src/mechanics.js +16 -16
  81. package/dist/src/output-common.js +2 -0
  82. package/dist/src/owner-identity.js +1 -1
  83. package/dist/src/perf-runtime-operation-builder.js +1 -1
  84. package/dist/src/perf-runtime-plan.js +1 -1
  85. package/dist/src/physical-device-control.js +1 -1
  86. package/dist/src/platform-request-scope.js +1 -1
  87. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  88. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  89. package/dist/src/platform-runtime-app-log-process.js +1 -1
  90. package/dist/src/platform-runtime-host.js +1 -1
  91. package/dist/src/platform-runtime-operation-host.js +2 -2
  92. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  93. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  94. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  95. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  96. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  97. package/dist/src/platform-runtime.js +1 -1
  98. package/dist/src/process.js +1 -1
  99. package/dist/src/provider-webdriver.js +1 -1
  100. package/dist/src/proxy.js +1 -1
  101. package/dist/src/quality-warnings.js +1 -1
  102. package/dist/src/react-native.js +1 -1
  103. package/dist/src/record-runtime.js +1 -1
  104. package/dist/src/recording-stop-observation.js +1 -0
  105. package/dist/src/register-builtins.js +1 -1
  106. package/dist/src/registry.js +35 -36
  107. package/dist/src/replay-divergence.js +1 -1
  108. package/dist/src/reporting.js +11 -9
  109. package/dist/src/request-providers.js +1 -1
  110. package/dist/src/result-serialization.js +1 -1
  111. package/dist/src/runner-cache-metadata.js +2 -2
  112. package/dist/src/runner-client.js +1 -1
  113. package/dist/src/runner-disposal.js +1 -1
  114. package/dist/src/runner-operations-facade.js +1 -1
  115. package/dist/src/runner.js +1 -1
  116. package/dist/src/runtime.js +3 -3
  117. package/dist/src/runtime10.js +1 -1
  118. package/dist/src/runtime2.js +4 -4
  119. package/dist/src/runtime3.js +1 -1
  120. package/dist/src/runtime4.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime9.js +1 -1
  124. package/dist/src/screen-recording-completion.js +1 -1
  125. package/dist/src/screen-recording-resource-recovery.js +1 -1
  126. package/dist/src/screen-recording-runtime.js +1 -1
  127. package/dist/src/screenshot-result.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/sdk-batch.js +2 -2
  130. package/dist/src/sdk-contracts.js +2 -2
  131. package/dist/src/sdk-remote-config.d.ts +1 -0
  132. package/dist/src/sdk-remote-config.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +36 -24
  134. package/dist/src/selector-runtime.js +1 -1
  135. package/dist/src/session-observation.js +1 -1
  136. package/dist/src/session-routing.js +1 -1
  137. package/dist/src/session-snapshot.js +1 -1
  138. package/dist/src/session-store.js +2 -2
  139. package/dist/src/session2.js +5 -5
  140. package/dist/src/simulator.js +1 -1
  141. package/dist/src/snapshot-runtime-binding.js +1 -1
  142. package/dist/src/snapshot-runtime.js +1 -1
  143. package/dist/src/snapshot.js +1 -1
  144. package/dist/src/snapshot4.js +1 -1
  145. package/dist/src/src3.js +1 -1
  146. package/dist/src/src4.js +1 -1
  147. package/dist/src/stop-sequence.js +1 -0
  148. package/dist/src/success-text.js +1 -1
  149. package/dist/src/text-entry-focus.js +1 -0
  150. package/dist/src/tool-provider.js +1 -1
  151. package/dist/src/tool-provider2.js +1 -1
  152. package/dist/src/tool-provider3.js +1 -1
  153. package/dist/src/type-text-runtime.js +1 -1
  154. package/dist/src/video.js +2 -2
  155. package/dist/src/yauzl.js +1 -0
  156. package/package.json +2 -2
  157. package/server.json +2 -2
  158. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +0 -1
  159. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +0 -1
  160. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.manifest.json +0 -17
  161. package/dist/src/audio-probe-support.js +0 -1
  162. package/dist/src/config2.js +0 -1
  163. package/dist/src/provider-device-runtime.js +0 -1
  164. package/dist/src/screen-recording-live-handle.js +0 -1
@@ -1 +1 @@
1
- import{A as e,C as t}from"./sdk-contracts.js";import{Br as n,zr as r}from"./sdk-batch.js";import{c as i,r as a}from"./diagnostics.js";import{C as o,f as s,x as c}from"./owner-identity.js";import{c as l,l as u,r as d}from"./exec.js";import{t as f}from"./file.js";import"./diagnostics2.js";import"./command.js";import{n as p}from"./retry.js";import{n as m}from"./version.js";import"./process.js";import{C as ee,D as te,c as ne,f as re,h as ie,n as ae,o as oe,w as se,y as ce}from"./host-file.js";import{t as le}from"./apple-runner-platform.js";import{t as ue}from"./snapshot-process.js";import h from"node:path";import{createHash as g,randomUUID as _}from"node:crypto";import de from"node:net";import{Buffer as v}from"node:buffer";const fe={unsupported:`UNSUPPORTED_OPERATION`,"malformed-tree":`COMMAND_FAILED`,"stale-target":`COMMAND_FAILED`,timeout:`COMMAND_FAILED`,cancelled:`COMMAND_FAILED`,"process-crash":`COMMAND_FAILED`,"transport-failure":`COMMAND_FAILED`};var y=class extends t{failureKind;failureCode;constructor(e,t,n=`iOS Simulator snapshot source ${e}: ${t}`,r={},i){super(fe[e],n,{...r,bridgeFailure:e,bridgeFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`SnapshotSourceError`,this.failureKind=e,this.failureCode=t}};function b(e,t,n={},r){return new y(e,t,void 0,n,r)}function x(n){return n instanceof y?n:e(n)?b(`cancelled`,`abort-signal`,{},n):n instanceof t&&typeof n.details?.timeoutMs==`number`?b(`timeout`,`host-operation-timeout`,{timeoutMs:n.details.timeoutMs},n):b(`transport-failure`,`unexpected-host-error`,{error:n instanceof Error?n.message:String(n)},n)}function pe(e,t,n=Date.now){if(t?.aborted)throw b(`cancelled`,`abort-signal`);return{clock:p.fromTimeoutMs(e,n()),now:n,signal:t}}function S(e,t){if(e.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw b(`timeout`,t);return Math.max(1,Math.floor(n))}async function C(e,t,n){let r=Math.min(t,S(e,n));await new Promise((t,n)=>{let i=!1,a=setTimeout(()=>s(t),r),o=()=>{s(()=>n(b(`cancelled`,`abort-signal`)))},s=t=>{i||(i=!0,clearTimeout(a),e.signal?.removeEventListener(`abort`,o),t())};e.signal?.addEventListener(`abort`,o,{once:!0}),e.signal?.aborted&&o()})}const w=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeRuntime.h`,`SnapshotBridgeCapture.h`,`SnapshotBridgeCapture.m`],me=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeCapture.m`];async function he(e,t,n){let r=g(`sha256`);for(let i of w){let a=h.join(t,i);if(S(n,`native-source-fingerprint-deadline`),!e.exists(a))throw b(`unsupported`,`native-source-missing`,{filePath:a});r.update(i),r.update(`\0`),r.update(await e.readBinary(a)),r.update(`\0`)}return r.digest(`hex`)}async function ge(e,t,n){let r=await T(e,`xcodebuild`,[`-version`],n),i=await T(e,`sw_vers`,[`-productVersion`],n),a=await T(e,`sw_vers`,[`-buildVersion`],n),o=await T(e,`uname`,[`-m`],n),s=await T(e,`xcrun`,[`--sdk`,`iphonesimulator`,`--show-sdk-version`],n),c=t.trim();if(!c)throw b(`unsupported`,`simulator-runtime-missing`);if(o!==`arm64`&&o!==`x86_64`)throw b(`unsupported`,`simulator-architecture-unsupported`,{architecture:o});return{xcode:r,macosProductVersion:i,macosBuild:a,architecture:o,simulatorSdk:s,simulatorRuntime:c}}async function T(e,t,n,r){let i=await _e(e,t,n,r);if(i.exitCode!==0)throw b(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw b(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function _e(e,t,n,r){try{return await E(e,t,n,r)}catch(i){if(!d(i))throw i;if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);if(r.clock.remainingMs(r.now())<=0)throw i;return await E(e,t,n,r)}}function E(e,t,n,r){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:Math.min(le,S(r,`toolchain-probe-deadline`))})}const D=`agent-device-simulator-ax-v1.5.5`;Object.freeze([`verb`,`requestId`,`pid`,`generation`,`snapshotTree`,`automationMode`,`maxDepth`,`maxNodes`,`maxDurationMs`,`maxResponseBytes`,`nativeLevelsHint`]),Object.freeze([`protocolVersion`,`sourceVersion`,`requestId`,`generation`,`ok`,`pid`,`tree`,`truncated`,`automationEnabled`,`recovery`,`error_kind`,`error_code`,`error`]),Object.freeze([`XC_kAXXCAttributeElementType`,`XC_kAXXCAttributeElementBaseType`,`XC_kAXXCAttributeLabel`,`XC_kAXXCAttributeValue`,`XC_kAXXCAttributeIdentifier`,`XC_kAXXCAttributeFrame`,`XC_kAXXCAttributeAutomationType`,`XC_kAXXCAttributeChildren`]);const ve=[`requests`,`rejected`,`continuations`,`acceptedLevels`];function ye(e){let t=e.recovery;if(!P(t))throw b(`malformed-tree`,`recovery-invalid`);let n=ve.map(e=>[e,t[e]]);if(n.some(([,e])=>!Number.isSafeInteger(e)||e<0))throw b(`malformed-tree`,`recovery-invalid`);return Object.freeze(Object.fromEntries(n))}function be(e,t){let n;try{n=v.from(JSON.stringify(e),`utf8`)}catch(e){throw b(`malformed-tree`,`request-not-json`,{},e)}let r=n.length+4;if(r>t.maxRequestBytes)throw b(`transport-failure`,`request-limit-exceeded`,{frameBytes:r,maxRequestBytes:t.maxRequestBytes});let i=v.alloc(4);return i.writeUInt32BE(n.length,0),v.concat([i,n])}var O=class{header=v.alloc(4);headerBytes=0;chunks=[];payloadBytes=0;expectedBodyBytes;frame;maxFrameBytes;constructor(e){if(!Number.isSafeInteger(e)||e<=0)throw b(`malformed-tree`,`frame-limit-invalid`,{maxFrameBytes:e});this.maxFrameBytes=e}push(e){if(this.frame)return this.acceptTrailingChunk(e);let t=this.readHeader(e);if(t&&(this.appendPayload(e,t.offset,t.bodyBytes),this.payloadBytes===t.bodyBytes))return this.frame=v.concat(this.chunks,t.bodyBytes),this.frame}acceptTrailingChunk(e){if(e.length>0)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:e.length});return this.frame}readHeader(e){if(this.headerBytes===4)return{offset:0,bodyBytes:this.expectedBodyBytes};let t=Math.min(4-this.headerBytes,e.length);if(e.copy(this.header,this.headerBytes,0,t),this.headerBytes+=t,this.headerBytes<4)return;let n=this.header.readUInt32BE(0);if(n===0||n>this.maxFrameBytes)throw b(`malformed-tree`,`frame-limit-exceeded`,{bodyBytes:n,maxFrameBytes:this.maxFrameBytes});return this.expectedBodyBytes=n,{offset:t,bodyBytes:n}}appendPayload(e,t,n){let r=n-this.payloadBytes,i=e.length-t;if(i>r)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:i-r});i!==0&&(this.chunks.push(e.subarray(t)),this.payloadBytes+=i)}finish(){if(this.frame)return this.frame;throw b(`transport-failure`,`bridge-frame-incomplete`,{headerBytes:this.headerBytes,payloadBytes:this.payloadBytes,expectedBodyBytes:this.expectedBodyBytes})}};function k(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch(e){throw b(`malformed-tree`,`response-not-json`,{},e)}if(!P(t))throw b(`malformed-tree`,`response-not-object`);return t}function A(e){return Object.freeze({verb:`describe`,requestId:e.requestId,pid:e.pid,generation:e.generation,snapshotTree:!0,automationMode:!0,maxDepth:e.maxDepth,maxNodes:e.maxNodes,maxDurationMs:e.maxDurationMs,maxResponseBytes:e.maxResponseBytes,...e.nativeLevelsHint===void 0?{}:{nativeLevelsHint:e.nativeLevelsHint}})}function j(e,t){if(e.protocolVersion!==1)throw b(`transport-failure`,`protocol-version-mismatch`,{expected:1,observed:e.protocolVersion});if(e.sourceVersion!==`agent-device-simulator-ax-v1.5.5`)throw b(`transport-failure`,`source-version-mismatch`,{expected:D,observed:e.sourceVersion});if(e.requestId!==t)throw b(`transport-failure`,`request-id-mismatch`,{expected:t,observed:e.requestId})}function M(e,t){if(typeof e.pid!=`number`||e.pid!==t.pid)throw b(`stale-target`,`bridge-pid-mismatch`,{expectedPid:t.pid,observedPid:e.pid});if(e.generation!==t.generation)throw b(`stale-target`,`bridge-generation-mismatch`,{expectedGeneration:t.generation,observedGeneration:e.generation})}function N(e){let t=e.error_kind,n=typeof e.error_code==`string`?e.error_code:`guest-error`,r=typeof e.error==`string`?e.error:void 0,i=r?{guestMessage:r.slice(0,1024)}:{};throw b(t===`unsupported`?`unsupported`:t===`malformed_tree`?`malformed-tree`:t===`application_not_responding`?`timeout`:t===`application_unavailable`?`transport-failure`:t===`bad_request`?`malformed-tree`:`transport-failure`,n,i)}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const F=`snapshot-bridge`,I=`manifest.json`;async function xe(e){let t=e.deadline,n=e.sourceRoot??Se(e.host),r=await he(e.host,n,t),i=await ge(e.host,e.runtime,t),a=we({schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,toolchain:i}),o=e.cacheRoot??h.join(e.host.homeDirectory(),`.agent-device`,`snapshot-source`),s=h.join(o,a),c=await e.host.acquireLock(h.join(o,`${a}.lock`),{deadline:t});try{let c=await Ce(e.host,s,{sourceHash:r,cacheKey:a,toolchain:i},t);if(c)return c;S(t,`native-build-deadline`),e.host.exists(s)&&await e.host.remove(s),S(t,`native-build-deadline`),await e.host.ensureDirectory(o);let l=h.join(o,`.${a}.${e.host.processId()}.tmp`);S(t,`native-build-deadline`),await e.host.remove(l);try{S(t,`native-build-deadline`),await e.host.ensureDirectory(l);let o=h.join(l,F),c=await e.host.run(`xcrun`,[`--sdk`,`iphonesimulator`,`clang`,`-arch`,i.architecture,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Werror`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`CoreGraphics`,...me.map(e=>h.join(n,e)),`-o`,o],{signal:t.signal,timeoutMs:Math.min(12e4,S(t,`native-build-deadline`)),allowFailure:!0});if(c.exitCode!==0||!e.host.exists(o))throw b(`unsupported`,`native-build-failed`,{exitCode:c.exitCode,stderr:c.stderr.slice(0,4096)});S(t,`native-build-deadline`),await e.host.chmod(o,493);let u=await L(e.host,o,t),d={schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,cacheKey:a,toolchain:i,binarySha256:u};return await e.host.writeText(h.join(l,I),`${JSON.stringify(d,null,2)}\n`),S(t,`native-build-deadline`),await e.host.rename(l,s),{path:h.join(s,F),sourceHash:r,cacheKey:a,protocolVersion:1,sourceVersion:D}}catch(t){throw await e.host.remove(l),t}}finally{await c()}}function Se(e){let t=e.projectRoot(),n=h.join(t,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(n,t))))return n;let r=h.join(t,`dist`,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(r,t))))return r;throw b(`unsupported`,`native-source-missing`,{projectRoot:t})}async function Ce(e,t,n,r){let i=h.join(t,F);if(!(!e.exists(i)||!e.exists(h.join(t,I))))try{let a=JSON.parse(await e.readText(h.join(t,I)));return a.schemaVersion!==1||a.protocolVersion!==1||a.sourceVersion!==`agent-device-simulator-ax-v1.5.5`||a.sourceHash!==n.sourceHash||a.cacheKey!==n.cacheKey||JSON.stringify(a.toolchain)!==JSON.stringify(n.toolchain)||typeof a.binarySha256!=`string`||await L(e,i,r)!==a.binarySha256?void 0:{path:i,sourceHash:n.sourceHash,cacheKey:n.cacheKey,protocolVersion:1,sourceVersion:D}}catch(e){if(e instanceof y&&(e.failureKind===`cancelled`||e.failureKind===`timeout`))throw e;return}}async function L(e,t,n){return S(n,`native-cache-hash-deadline`),g(`sha256`).update(await e.readBinary(t)).digest(`hex`)}function we(e){return g(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,32)}var Te=class{entries=new Map;probeBackAfterUses;constructor(e=8){this.probeBackAfterUses=e}consume(e,t,n){if(n)return{nativeLevels:void 0,reason:`explicit-depth`};let r=this.currentEntry(e);return r===`unidentified`?{nativeLevels:void 0,reason:`unidentified-target`}:!r||r.nativeLevels>=t?{nativeLevels:void 0,reason:`no-hint`}:r.remainingUses<=0?{nativeLevels:void 0,reason:`probe-back`}:(--r.remainingUses,{nativeLevels:r.nativeLevels,reason:`hinted`})}learn(e,t,n,r){return n||!e.targetId?`ignored`:r.rejected>0&&r.acceptedLevels<t?(this.remember(e.targetId,{generation:e.generation,nativeLevels:r.acceptedLevels,remainingUses:this.probeBackAfterUses}),`learned`):r.rejected===0&&r.acceptedLevels>=t?this.entries.delete(e.targetId)?`forgotten`:`ignored`:this.currentEntry(e)?`kept`:`ignored`}currentEntry(e){if(!e.targetId)return`unidentified`;let t=this.entries.get(e.targetId);if(t){if(t.generation!==e.generation){this.entries.delete(e.targetId);return}return t}}remember(e,t){if(this.entries.delete(e),this.entries.size>=32){let e=this.entries.keys().next().value;e!==void 0&&this.entries.delete(e)}this.entries.set(e,t)}};const R=65536;function Ee(){return{projectRoot:m,homeDirectory:re,run:async(e,t,n)=>await l(e,t,n),start:De,connect:z,readText:ce,readBinary:ie,writeText:te,ensureDirectory:oe,chmod:ae,exists:ne,rename:se,remove:ee,acquireLock:Oe,emitDiagnostic:a,withDiagnosticTimer:i,processId:s,readTargetProcessStartTime:ue}}function De(e,t,n,r={}){if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);let i=u(`xcrun`,[`simctl`,`spawn`,e,t,`serve`,n,`--idle-timeout`,`60`,`--exit-on-disconnect`,`false`],{allowFailure:!0,captureOutput:!1,detached:!0}),a=i.child.pid??0;if(a<=0)throw b(`transport-failure`,`bridge-process-pid-missing`);let s=``;return i.child.stderr?.setEncoding(`utf8`),i.child.stderr?.on(`data`,e=>{s=ke(s,String(e))}),{pid:a,wait:i.wait,isAlive:()=>i.child.exitCode===null&&i.child.signalCode===null,signal:e=>{o(a,e)||i.child.kill(e)},readLog:()=>s}}async function z(e,t){if(t.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=Math.max(1,Math.floor(t.timeoutMs));return await new Promise((r,i)=>{let a=de.createConnection({path:e}),o=!1,s=!1,c=setTimeout(()=>{p(b(`timeout`,`bridge-connect-timeout`)),a.destroy()},n),l=()=>{p(b(`cancelled`,`abort-signal`)),a.destroy()},u=()=>{o=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`error`,d),a.off(`close`,f),a.setTimeout(0),r(a)},d=e=>{p(e),a.destroy()},f=()=>{o||p(b(`transport-failure`,`bridge-closed-before-connect`))},p=e=>{s||o||(s=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`connect`,u),a.off(`error`,d),a.off(`close`,f),i(e))};a.once(`connect`,u),a.once(`error`,d),a.once(`close`,f),t.signal?.addEventListener(`abort`,l,{once:!0}),t.signal?.aborted&&l()})}async function Oe(e,t){let n=s(),r=t.deadline,i=f({lockDirPath:e,owner:{pid:n,startTime:c(n),acquiredAtMs:Date.now()},timeoutMs:S(r,`cache-lock-deadline`),pollMs:100,ownerGraceMs:5e3,description:`iOS Simulator snapshot bridge cache`}),a=r.signal;if(!a)return await i;let o=!1,l,u=new Promise((e,t)=>{l=()=>{o=!0,t(b(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,l,{once:!0}),a.aborted&&l()});try{return await Promise.race([i,u])}catch(e){throw o&&i.then(e=>e(),()=>void 0),r.clock.isExpired()&&!(e instanceof y&&e.failureKind===`cancelled`)?b(`timeout`,`cache-lock-deadline`):e}finally{a.removeEventListener(`abort`,l)}}function ke(e,t){let n=e+t;return n.length<=R?n:n.slice(n.length-R)}function Ae(e,t,n){let r=g(`sha256`).update(t).digest(`hex`).slice(0,12),i=g(`sha256`).update(n).digest(`hex`).slice(0,12);return h.join(`/tmp`,`agent-device-ax-${r}-${e.processId()}-${i}`,`snapshot.sock`)}const B=new WeakSet;async function V(e,t){let n;try{n=(await t.wait).exitCode}catch{n=void 0}return B.has(t)||(B.add(t),e.emitDiagnostic({level:`error`,phase:`ios.snapshot-source.bridge-process-exit`,data:{pid:t.pid,...n===void 0?{}:{exitCode:n},stderr:je(t.readLog())}})),b(`process-crash`,`bridge-exited`,{pid:t.pid,...n===void 0?{}:{exitCode:n}})}function je(e){let t=v.from(e);return t.length<=65536?e:t.subarray(-65536).toString(`utf8`)}async function Me(e){let t=new O(e.limits.maxResponseBytes-4),n=S(e.deadline,`bridge-request-deadline`);return await new Promise((r,i)=>{let a=!1,o=!1,s=setTimeout(()=>{p(b(`timeout`,`bridge-request-deadline`,{dispatched:o})),e.socket.destroy()},n),c=()=>{p(b(`cancelled`,`abort-signal`,{dispatched:o})),e.socket.destroy()},l=n=>{try{if(!Buffer.isBuffer(n))throw b(`transport-failure`,`bridge-data-invalid`);let r=t.push(n);if(r){let t=k(r);if(j(t,e.requestId),M(t,{pid:e.expectedPid,generation:e.expectedGeneration}),t.ok!==!0&&N(t),typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);f(t);return}}catch(t){p(t),e.socket.destroy()}},u=e=>p(x(e)),d=()=>{a||(e.process.isAlive()?p(b(`transport-failure`,`bridge-connection-closed`)):V(e.host,e.process).then(p))};e.process.wait.then(()=>{a||V(e.host,e.process).then(p)},e=>{a||p(x(e))});let f=e=>m(()=>r(e)),p=e=>m(()=>i(e)),m=t=>{a||(a=!0,clearTimeout(s),e.deadline.signal?.removeEventListener(`abort`,c),e.socket.off(`data`,l),e.socket.off(`error`,u),e.socket.off(`close`,d),t())};e.socket.on(`data`,l),e.socket.on(`error`,u),e.socket.on(`close`,d),e.deadline.signal?.addEventListener(`abort`,c,{once:!0});try{if(e.deadline.signal?.aborted)throw b(`cancelled`,`abort-signal`);o=!0,e.socket.write(e.frame)}catch(t){p(x(t)),e.socket.destroy()}})}var Ne=class{sessions=new Map;requestQueues=new Map;ownerId=_();closed=!1;host;constructor(e){this.host=e}async request(e){if(this.closed)throw b(`unsupported`,`source-closed`);return await this.withSimulatorLock(e.target.udid,e.deadline,()=>this.requestInSimulator(e))}async requestInSimulator(e){if(this.closed)throw b(`unsupported`,`source-closed`);let t=e.deadline;S(t,`bridge-request-deadline`);let n=this.sessions.get(e.target.udid),r=await this.ensureSession(e,t);try{let n=await this.readTargetStartTime(e.target,t),i=await this.exchange(r,e,t);return await this.assertTargetStillCurrent(e.target,n,t),i}catch(e){throw await this.handleRequestFailure(e,r,n)}}async handleRequestFailure(e,t,n){let r=x(e);return Fe(r,t,n)?await this.removeSession(t,!0):r.failureKind===`process-crash`?await this.removeSession(t,!1):r.failureKind===`transport-failure`&&(t.socket?.destroy(),t.socket=void 0),r}async withSimulatorLock(e,t,n){let r=this.requestQueues.get(e)??Promise.resolve(),i,a=new Promise(e=>{i=e}),o=r.then(()=>a);this.requestQueues.set(e,o);try{return await Pe(r,t),await n()}finally{i(),this.requestQueues.get(e)===o&&this.requestQueues.delete(e)}}async close(){if(this.closed)return;this.closed=!0;let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async e=>await this.dispose(e,!0)))}async ensureSession(e,t){let n=e.target.udid,r=this.sessions.get(n);if(r&&r.bridgePath===e.bridge.path&&r.process.isAlive())return(!r.socket||r.socket.destroyed)&&(r.socket=await this.connectUntilReady(r,t)),r;r&&await this.removeSession(r,!0);let i=Ae(this.host,e.target.udid,this.ownerId);await this.host.ensureDirectory(h.dirname(i)),await this.host.remove(i);let a=this.host.start(e.target.udid,e.bridge.path,i,{signal:t.signal}),o={udid:e.target.udid,bridgePath:e.bridge.path,socketPath:i,process:a};this.sessions.set(n,o);try{return o.socket=await this.connectUntilReady(o,t),o}catch(e){throw await this.removeSession(o,!0),x(e)}}async connectUntilReady(e,t){let n;for(;;){let r=S(t,`bridge-connect-deadline`);if(!e.process.isAlive())throw await V(this.host,e.process);try{return await this.host.connect(e.socketPath,{signal:t.signal,timeoutMs:Math.min(250,r)})}catch(e){if(n=e,e instanceof y&&e.failureKind===`cancelled`)throw e;let r=Math.min(20,S(t,`bridge-connect-deadline`));try{await C(t,r,`bridge-connect-deadline`)}catch(e){throw x(e)}}if(n instanceof y&&n.failureKind===`timeout`)throw n}}async exchange(e,t,n){(!e.socket||e.socket.destroyed)&&(e.socket=await this.connectUntilReady(e,n));let r=_(),i=be(A({requestId:r,pid:t.target.pid,generation:t.target.generation,maxDepth:Math.min(t.limits.maxTraversalDepth,t.maxDepth),maxNodes:t.limits.maxNodes,maxDurationMs:S(n,`bridge-request-deadline`),maxResponseBytes:t.limits.maxResponseBytes,...t.nativeLevelsHint===void 0?{}:{nativeLevelsHint:t.nativeLevelsHint}}),t.limits);return await Me({process:e.process,socket:e.socket,frame:i,requestId:r,deadline:n,limits:t.limits,expectedPid:t.target.pid,expectedGeneration:t.target.generation,host:this.host})}async readTargetStartTime(e,t){let n=await this.host.readTargetProcessStartTime(e.pid,{signal:t.signal,timeoutMs:S(t,`target-identity-deadline`)});if(!n)throw b(`stale-target`,`target-process-unavailable`,{pid:e.pid,generation:e.generation});if(e.processStartTime!==void 0&&e.processStartTime!==n)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:e.processStartTime,observedStartTime:n});return n}async assertTargetStillCurrent(e,t,n){let r=await this.host.readTargetProcessStartTime(e.pid,{signal:n.signal,timeoutMs:S(n,`target-identity-deadline`)});if(r!==t)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:t,observedStartTime:r})}async removeSession(e,t){this.sessions.get(e.udid)===e&&this.sessions.delete(e.udid),await this.dispose(e,t)}async dispose(e,t){e.socket?.destroy(),e.socket=void 0,t&&e.process.isAlive()&&(e.process.signal(`SIGTERM`),await H(e.process,500),e.process.isAlive()&&(e.process.signal(`SIGKILL`),await H(e.process,500))),await this.host.remove(e.socketPath)}};async function Pe(e,t){let n=S(t,`bridge-request-deadline`);await Promise.race([e,C(t,n,`bridge-request-deadline`).then(()=>{throw b(`timeout`,`bridge-request-deadline`)})])}function Fe(e,t,n){return(e.failureKind===`cancelled`||e.failureKind===`timeout`)&&(e.details?.dispatched===!0||n!==t)}async function H(e,t){await Promise.race([e.wait.catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}const U=16777216,W=12e4,G=1e4,Ie=Object.freeze({maxRequestBytes:65536,maxResponseBytes:4194304,maxNodes:5e3,maxTraversalDepth:64,maxDurationMs:5e3});function Le(e){let n={...Ie,...e??{}};for(let[e,r]of Object.entries(n))if(!Number.isSafeInteger(r)||r<=0)throw new t(`INVALID_ARGS`,`Snapshot source limit ${e} must be a positive integer`,{name:e,value:r});if(n.maxRequestBytes>n.maxResponseBytes)throw new t(`INVALID_ARGS`,`Snapshot source request bytes cannot exceed response bytes`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});if(n.maxRequestBytes>U||n.maxResponseBytes>U)throw new t(`INVALID_ARGS`,`Snapshot source frame limits exceed the bridge bound`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes,maximumFrameBytes:U});if(n.maxNodes>G||n.maxTraversalDepth>128)throw new t(`INVALID_ARGS`,`Snapshot source tree limits exceed the bridge bound`,{maxNodes:n.maxNodes,maxTraversalDepth:n.maxTraversalDepth,maximumNodes:G,maximumDepth:128});if(n.maxDurationMs>W)throw new t(`INVALID_ARGS`,`Snapshot source duration exceeds the bridge bound`,{maxDurationMs:n.maxDurationMs,maximumDurationMs:W});if(n.maxRequestBytes<=4||n.maxResponseBytes<=4)throw new t(`INVALID_ARGS`,`Snapshot source frame limits must leave room for a body`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});return Object.freeze(n)}const K=Object.freeze({elementType:`XC_kAXXCAttributeElementType`,elementBaseType:`XC_kAXXCAttributeElementBaseType`,label:`XC_kAXXCAttributeLabel`,value:`XC_kAXXCAttributeValue`,identifier:`XC_kAXXCAttributeIdentifier`,frame:`XC_kAXXCAttributeFrame`,automationType:`XC_kAXXCAttributeAutomationType`,children:`XC_kAXXCAttributeChildren`}),q=`Other.Other.Application.Group.Window.Sheet.Drawer.Alert.Dialog.Button.RadioButton.RadioGroup.CheckBox.DisclosureTriangle.PopUpButton.ComboBox.MenuButton.ToolbarButton.Popover.Keyboard.Key.NavigationBar.TabBar.TabGroup.Toolbar.StatusBar.Table.TableRow.TableColumn.Outline.OutlineRow.Browser.CollectionView.Slider.PageIndicator.ProgressIndicator.ActivityIndicator.SegmentedControl.Picker.PickerWheel.Switch.Toggle.Link.Image.Icon.SearchField.ScrollView.ScrollBar.StaticText.TextField.SecureTextField.DatePicker.TextView.Menu.MenuItem.MenuBar.MenuBarItem.Map.WebView.IncrementArrow.DecrementArrow.Timeline.RatingIndicator.ValueIndicator.SplitGroup.Splitter.RelevanceIndicator.ColorWell.HelpTag.Matte.DockItem.Ruler.RulerMarker.Grid.LevelIndicator.Cell.LayoutArea.LayoutItem.Handle.Stepper.Tab.TouchBar.StatusItem`.split(`.`),J={UIApplication:`Application`,UIWindow:`Window`},Re=new Set(Object.values(K));function ze(e,t,n){let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(e=>!P(e)))throw b(`malformed-tree`,`guest-tree-root-invalid`);let i=[],a=[],o=0;for(let e of r)c(e,void 0,0,!1);if(i.length>n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{nodeCount:i.length,maxNodes:n.maxNodes});if(o>n.maxTraversalDepth)throw b(`malformed-tree`,`traversal-depth-exceeded`,{maxTraversalDepth:o,maxAllowedDepth:n.maxTraversalDepth});if(typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let s=We(i.find(e=>e.type===`Application`||e.type===`Window`));return{nodes:i,maxTraversalDepth:o,viewport:s,opaqueRemoteElements:a.filter(e=>He(e,s)).length};function c(e,t,r,s){if(i.length>=n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{maxNodes:n.maxNodes});for(let t of Object.keys(e))if(!Re.has(t))throw b(`malformed-tree`,`node-contains-unknown-field`,{key:t});let l=e[K.children];if(!Array.isArray(l))throw b(`malformed-tree`,`children-invalid`);let u=i.length,d=Be(e,u,t,r);i.push(d),o=Math.max(o,r),Ve(d,l.length,s)&&a.push(d.rect);let f=s||d.type===`WebView`;for(let e of l){if(!P(e))throw b(`malformed-tree`,`child-invalid`);c(e,u,r+1,f)}}}function Be(e,t,n,r){let i=X(e[K.elementType]),a=X(e[K.elementBaseType]),o=Ge(e[K.automationType]),s=Ue(e[K.frame]);return{index:t,...n===void 0?{}:{parentIndex:n},...Y(i,o)?{type:Y(i,o)}:{},...i?{role:i}:{},...a&&a!==i?{subrole:a}:{},...X(e[K.label])?{label:X(e[K.label])}:{},...Z(e[K.value])?{value:Z(e[K.value])}:{},...X(e[K.identifier])?{identifier:X(e[K.identifier])}:{},...s?{rect:s}:{},depth:r}}function Y(e,t){if(e!==void 0&&J[e])return J[e];if(e!==void 0&&q.includes(e))return e;if(t!==void 0)return q[t]??`Other`}function Ve(e,t,n){return n&&e.role===`AXRemoteElement`&&t===0}function He(e,t){return e===void 0?!0:r(e)?t.kind!==`reported`||n(e,t.rect):!1}function Ue(e){if(e===void 0)return;if(!P(e))throw b(`malformed-tree`,`frame-invalid`);let t=[`X`,`Y`,`Width`,`Height`].map(t=>e[t]);if(!t.every(e=>typeof e==`number`&&Number.isFinite(e)))throw b(`malformed-tree`,`frame-invalid`);let[n,r,i,a]=t;if(i<0||a<0)throw b(`malformed-tree`,`frame-invalid`);return{x:n,y:r,width:i,height:a}}function We(e){return!e||e.type!==`Application`&&e.type!==`Window`?{kind:`missing`,reason:`not-provided`}:r(e.rect)?{kind:`reported`,rect:e.rect}:{kind:`missing`,reason:e.rect?`invalid`:`not-provided`}}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`string`)return e.length>0?e:void 0;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e!=null)throw b(`malformed-tree`,`scalar-invalid`)}function Ge(e){if(e!=null){if(!Number.isSafeInteger(e))throw b(`malformed-tree`,`automation-type-invalid`);return e}}const Q=`simulator-ax-bridge`;function Ke(e={}){let t=e.host??Ee(),n=new Ne(t),r=new Te,i=new Map,a=!1,o=async n=>{if(a)throw b(`unsupported`,`source-closed`);let r=i.get(n.runtime);if(r)return r;let o=await t.withDiagnosticTimer(`ios.snapshot-source.prepare`,async()=>await xe({host:t,runtime:n.runtime,limits:n.limits,deadline:n.deadline,sourceRoot:e.sourceRoot,cacheRoot:e.cacheRoot}),{producer:Q});return i.set(n.runtime,o),o};return{acquire:async i=>{try{if(a)throw b(`unsupported`,`source-closed`);qe(i);let s=Le({...e.limits,...i.limits}),c=pe(s.maxDurationMs,i.signal),l=Ye(i.hint,s.maxTraversalDepth),u=l+1,d=i.hint.rawTraversalDepth!==null;return await t.withDiagnosticTimer(`ios.snapshot-source.acquire`,async()=>{let e=await o({runtime:i.target.runtime,limits:s,deadline:c}),a=r.consume(i.target,u,d),f=await n.request({target:i.target,bridge:e,limits:s,maxDepth:l,nativeLevelsHint:a.nativeLevels,deadline:c});S(c,`snapshot-decode-deadline`);let p=Xe(i.hint,i.target,f,s);return Je(t,r,i.target,u,d,a,f),{stage:`acquired`,acquisition:p}},{producer:Q})}catch(e){let t=x(e);return{stage:`failed`,failure:{kind:t.failureKind,code:t.failureCode,...t.details?{details:t.details}:{}}}}},close:async()=>{a||(a=!0,await n.close())}}}function qe(e){if(!e.target.udid.trim()||!e.target.runtime.trim()||!e.target.generation.trim()||!Number.isSafeInteger(e.target.pid)||e.target.pid<=0)throw new t(`INVALID_ARGS`,`Simulator snapshot source target identity is incomplete`);let n=e.hint;if(n.projection!==`raw`&&n.projection!==`regular`||![`full`,`surface-observation`].includes(n.acquisitionIntent)||typeof n.interactiveOnly!=`boolean`||typeof n.customActions!=`boolean`||!$(n.rawTraversalDepth)||!$(n.regularPresentedDepth))throw new t(`INVALID_ARGS`,`Simulator snapshot source capture hint is invalid`)}function Je(e,t,n,r,i,a,o){let s=ye(o),c=o.truncated===!0,l=t.learn(n,r,i,s);e.emitDiagnostic({level:`debug`,phase:`ios_snapshot_source_recovery`,data:{producer:Q,...n.targetId?{targetId:n.targetId}:{},generation:n.generation,requestedLevels:r,hint:a.reason,...a.nativeLevels===void 0?{}:{hintedLevels:a.nativeLevels},...s,truncated:c,learning:l}})}function Ye(e,n){let r=e.rawTraversalDepth??n;if(r>n)throw new t(`INVALID_ARGS`,`Simulator snapshot source depth exceeds its bound`,{requested:r,maximum:n});return r}function $(e){return e===null||Number.isSafeInteger(e)&&e>=0}function Xe(e,t,n,r){if(n.automationEnabled!==!0)throw b(`unsupported`,`automation-mode-unavailable`);let i=n.tree,a=n.truncated;if(typeof a!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let o=ze(i,{truncated:a},r),s=n.generation;if(typeof s!=`string`||!s)throw b(`malformed-tree`,`generation-invalid`);if(o.opaqueRemoteElements>0)throw b(`unsupported`,`remote-content-boundary`,{remoteElements:o.opaqueRemoteElements});let c=Object.freeze(o.nodes.map(e=>Object.freeze({...e,pid:t.pid}))),l=Ze(e,a,o.viewport),u=Object.freeze({...t.targetId?{targetId:t.targetId}:{},generation:s}),d={producer:Q,nodes:c,truncated:a,viewport:o.viewport,lineage:u,residue:l};return e.acquisitionIntent===`full`?{...d,intent:`full`,hint:{...e,acquisitionIntent:`full`}}:{...d,intent:`surface-observation`,hint:{...e,acquisitionIntent:`surface-observation`}}}function Ze(e,t,n){return Object.freeze([{kind:`unavailable-fact`,fact:`hittability`},...e.interactiveOnly?[{kind:`unavailable-fact`,fact:`interactive-query`}]:[],...t?[{kind:`truncated`}]:[],...n.kind===`missing`?[{kind:`missing-viewport`,reason:n.reason}]:[]])}export{Ke as createSimulatorSnapshotSource};
1
+ import{C as e,j as t}from"./sdk-contracts.js";import{Br as n,zr as r}from"./sdk-batch.js";import{c as i,r as a}from"./diagnostics.js";import{f as o,x as s}from"./owner-identity.js";import{c,l,m as u,r as d}from"./exec.js";import{t as f}from"./file.js";import"./diagnostics2.js";import"./command.js";import{n as p}from"./retry.js";import{n as m}from"./version.js";import"./process.js";import{C as ee,D as te,c as ne,f as re,h as ie,n as ae,o as oe,w as se,y as ce}from"./host-file.js";import{t as le}from"./apple-runner-platform.js";import{t as ue}from"./snapshot-process.js";import h from"node:path";import{createHash as g,randomUUID as _}from"node:crypto";import de from"node:net";import{Buffer as v}from"node:buffer";const fe={unsupported:`UNSUPPORTED_OPERATION`,"malformed-tree":`COMMAND_FAILED`,"stale-target":`COMMAND_FAILED`,timeout:`COMMAND_FAILED`,cancelled:`COMMAND_FAILED`,"process-crash":`COMMAND_FAILED`,"transport-failure":`COMMAND_FAILED`};var y=class extends e{failureKind;failureCode;constructor(e,t,n=`iOS Simulator snapshot source ${e}: ${t}`,r={},i){super(fe[e],n,{...r,bridgeFailure:e,bridgeFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`SnapshotSourceError`,this.failureKind=e,this.failureCode=t}};function b(e,t,n={},r){return new y(e,t,void 0,n,r)}function x(n){return n instanceof y?n:t(n)?b(`cancelled`,`abort-signal`,{},n):n instanceof e&&typeof n.details?.timeoutMs==`number`?b(`timeout`,`host-operation-timeout`,{timeoutMs:n.details.timeoutMs},n):b(`transport-failure`,`unexpected-host-error`,{error:n instanceof Error?n.message:String(n)},n)}function pe(e,t,n=Date.now){if(t?.aborted)throw b(`cancelled`,`abort-signal`);return{clock:p.fromTimeoutMs(e,n()),now:n,signal:t}}function S(e,t){if(e.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw b(`timeout`,t);return Math.max(1,Math.floor(n))}async function C(e,t,n){let r=Math.min(t,S(e,n));await new Promise((t,n)=>{let i=!1,a=setTimeout(()=>s(t),r),o=()=>{s(()=>n(b(`cancelled`,`abort-signal`)))},s=t=>{i||(i=!0,clearTimeout(a),e.signal?.removeEventListener(`abort`,o),t())};e.signal?.addEventListener(`abort`,o,{once:!0}),e.signal?.aborted&&o()})}const w=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeRuntime.h`,`SnapshotBridgeCapture.h`,`SnapshotBridgeCapture.m`],me=[`SnapshotBridge.m`,`SnapshotBridgeRuntime.m`,`SnapshotBridgeCapture.m`];async function he(e,t,n){let r=g(`sha256`);for(let i of w){let a=h.join(t,i);if(S(n,`native-source-fingerprint-deadline`),!e.exists(a))throw b(`unsupported`,`native-source-missing`,{filePath:a});r.update(i),r.update(`\0`),r.update(await e.readBinary(a)),r.update(`\0`)}return r.digest(`hex`)}async function ge(e,t,n){let r=await T(e,`xcodebuild`,[`-version`],n),i=await T(e,`sw_vers`,[`-productVersion`],n),a=await T(e,`sw_vers`,[`-buildVersion`],n),o=await T(e,`uname`,[`-m`],n),s=await T(e,`xcrun`,[`--sdk`,`iphonesimulator`,`--show-sdk-version`],n),c=t.trim();if(!c)throw b(`unsupported`,`simulator-runtime-missing`);if(o!==`arm64`&&o!==`x86_64`)throw b(`unsupported`,`simulator-architecture-unsupported`,{architecture:o});return{xcode:r,macosProductVersion:i,macosBuild:a,architecture:o,simulatorSdk:s,simulatorRuntime:c}}async function T(e,t,n,r){let i=await _e(e,t,n,r);if(i.exitCode!==0)throw b(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw b(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function _e(e,t,n,r){try{return await E(e,t,n,r)}catch(i){if(!d(i))throw i;if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);if(r.clock.remainingMs(r.now())<=0)throw i;return await E(e,t,n,r)}}function E(e,t,n,r){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:Math.min(le,S(r,`toolchain-probe-deadline`))})}const D=`agent-device-simulator-ax-v1.5.5`;Object.freeze([`verb`,`requestId`,`pid`,`generation`,`snapshotTree`,`automationMode`,`maxDepth`,`maxNodes`,`maxDurationMs`,`maxResponseBytes`,`nativeLevelsHint`]),Object.freeze([`protocolVersion`,`sourceVersion`,`requestId`,`generation`,`ok`,`pid`,`tree`,`truncated`,`automationEnabled`,`recovery`,`error_kind`,`error_code`,`error`]),Object.freeze([`XC_kAXXCAttributeElementType`,`XC_kAXXCAttributeElementBaseType`,`XC_kAXXCAttributeLabel`,`XC_kAXXCAttributeValue`,`XC_kAXXCAttributeIdentifier`,`XC_kAXXCAttributeFrame`,`XC_kAXXCAttributeAutomationType`,`XC_kAXXCAttributeChildren`]);const ve=[`requests`,`rejected`,`continuations`,`acceptedLevels`];function ye(e){let t=e.recovery;if(!P(t))throw b(`malformed-tree`,`recovery-invalid`);let n=ve.map(e=>[e,t[e]]);if(n.some(([,e])=>!Number.isSafeInteger(e)||e<0))throw b(`malformed-tree`,`recovery-invalid`);return Object.freeze(Object.fromEntries(n))}function be(e,t){let n;try{n=v.from(JSON.stringify(e),`utf8`)}catch(e){throw b(`malformed-tree`,`request-not-json`,{},e)}let r=n.length+4;if(r>t.maxRequestBytes)throw b(`transport-failure`,`request-limit-exceeded`,{frameBytes:r,maxRequestBytes:t.maxRequestBytes});let i=v.alloc(4);return i.writeUInt32BE(n.length,0),v.concat([i,n])}var O=class{header=v.alloc(4);headerBytes=0;chunks=[];payloadBytes=0;expectedBodyBytes;frame;maxFrameBytes;constructor(e){if(!Number.isSafeInteger(e)||e<=0)throw b(`malformed-tree`,`frame-limit-invalid`,{maxFrameBytes:e});this.maxFrameBytes=e}push(e){if(this.frame)return this.acceptTrailingChunk(e);let t=this.readHeader(e);if(t&&(this.appendPayload(e,t.offset,t.bodyBytes),this.payloadBytes===t.bodyBytes))return this.frame=v.concat(this.chunks,t.bodyBytes),this.frame}acceptTrailingChunk(e){if(e.length>0)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:e.length});return this.frame}readHeader(e){if(this.headerBytes===4)return{offset:0,bodyBytes:this.expectedBodyBytes};let t=Math.min(4-this.headerBytes,e.length);if(e.copy(this.header,this.headerBytes,0,t),this.headerBytes+=t,this.headerBytes<4)return;let n=this.header.readUInt32BE(0);if(n===0||n>this.maxFrameBytes)throw b(`malformed-tree`,`frame-limit-exceeded`,{bodyBytes:n,maxFrameBytes:this.maxFrameBytes});return this.expectedBodyBytes=n,{offset:t,bodyBytes:n}}appendPayload(e,t,n){let r=n-this.payloadBytes,i=e.length-t;if(i>r)throw b(`malformed-tree`,`multiple-frames`,{trailingBytes:i-r});i!==0&&(this.chunks.push(e.subarray(t)),this.payloadBytes+=i)}finish(){if(this.frame)return this.frame;throw b(`transport-failure`,`bridge-frame-incomplete`,{headerBytes:this.headerBytes,payloadBytes:this.payloadBytes,expectedBodyBytes:this.expectedBodyBytes})}};function k(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch(e){throw b(`malformed-tree`,`response-not-json`,{},e)}if(!P(t))throw b(`malformed-tree`,`response-not-object`);return t}function A(e){return Object.freeze({verb:`describe`,requestId:e.requestId,pid:e.pid,generation:e.generation,snapshotTree:!0,automationMode:!0,maxDepth:e.maxDepth,maxNodes:e.maxNodes,maxDurationMs:e.maxDurationMs,maxResponseBytes:e.maxResponseBytes,...e.nativeLevelsHint===void 0?{}:{nativeLevelsHint:e.nativeLevelsHint}})}function j(e,t){if(e.protocolVersion!==1)throw b(`transport-failure`,`protocol-version-mismatch`,{expected:1,observed:e.protocolVersion});if(e.sourceVersion!==`agent-device-simulator-ax-v1.5.5`)throw b(`transport-failure`,`source-version-mismatch`,{expected:D,observed:e.sourceVersion});if(e.requestId!==t)throw b(`transport-failure`,`request-id-mismatch`,{expected:t,observed:e.requestId})}function M(e,t){if(typeof e.pid!=`number`||e.pid!==t.pid)throw b(`stale-target`,`bridge-pid-mismatch`,{expectedPid:t.pid,observedPid:e.pid});if(e.generation!==t.generation)throw b(`stale-target`,`bridge-generation-mismatch`,{expectedGeneration:t.generation,observedGeneration:e.generation})}function N(e){let t=e.error_kind,n=typeof e.error_code==`string`?e.error_code:`guest-error`,r=typeof e.error==`string`?e.error:void 0,i=r?{guestMessage:r.slice(0,1024)}:{};throw b(t===`unsupported`?`unsupported`:t===`malformed_tree`?`malformed-tree`:t===`application_not_responding`?`timeout`:t===`application_unavailable`?`transport-failure`:t===`bad_request`?`malformed-tree`:`transport-failure`,n,i)}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const F=`snapshot-bridge`,I=`manifest.json`;async function xe(e){let t=e.deadline,n=e.sourceRoot??Se(e.host),r=await he(e.host,n,t),i=await ge(e.host,e.runtime,t),a=we({schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,toolchain:i}),o=e.cacheRoot??h.join(e.host.homeDirectory(),`.agent-device`,`snapshot-source`),s=h.join(o,a),c=await e.host.acquireLock(h.join(o,`${a}.lock`),{deadline:t});try{let c=await Ce(e.host,s,{sourceHash:r,cacheKey:a,toolchain:i},t);if(c)return c;S(t,`native-build-deadline`),e.host.exists(s)&&await e.host.remove(s),S(t,`native-build-deadline`),await e.host.ensureDirectory(o);let l=h.join(o,`.${a}.${e.host.processId()}.tmp`);S(t,`native-build-deadline`),await e.host.remove(l);try{S(t,`native-build-deadline`),await e.host.ensureDirectory(l);let o=h.join(l,F),c=await e.host.run(`xcrun`,[`--sdk`,`iphonesimulator`,`clang`,`-arch`,i.architecture,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Werror`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`CoreGraphics`,...me.map(e=>h.join(n,e)),`-o`,o],{signal:t.signal,timeoutMs:Math.min(12e4,S(t,`native-build-deadline`)),allowFailure:!0});if(c.exitCode!==0||!e.host.exists(o))throw b(`unsupported`,`native-build-failed`,{exitCode:c.exitCode,stderr:c.stderr.slice(0,4096)});S(t,`native-build-deadline`),await e.host.chmod(o,493);let u=await L(e.host,o,t),d={schemaVersion:1,protocolVersion:1,sourceVersion:D,sourceHash:r,cacheKey:a,toolchain:i,binarySha256:u};return await e.host.writeText(h.join(l,I),`${JSON.stringify(d,null,2)}\n`),S(t,`native-build-deadline`),await e.host.rename(l,s),{path:h.join(s,F),sourceHash:r,cacheKey:a,protocolVersion:1,sourceVersion:D}}catch(t){throw await e.host.remove(l),t}}finally{await c()}}function Se(e){let t=e.projectRoot(),n=h.join(t,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(n,t))))return n;let r=h.join(t,`dist`,`apple`,`snapshot-bridge`);if(w.every(t=>e.exists(h.join(r,t))))return r;throw b(`unsupported`,`native-source-missing`,{projectRoot:t})}async function Ce(e,t,n,r){let i=h.join(t,F);if(!(!e.exists(i)||!e.exists(h.join(t,I))))try{let a=JSON.parse(await e.readText(h.join(t,I)));return a.schemaVersion!==1||a.protocolVersion!==1||a.sourceVersion!==`agent-device-simulator-ax-v1.5.5`||a.sourceHash!==n.sourceHash||a.cacheKey!==n.cacheKey||JSON.stringify(a.toolchain)!==JSON.stringify(n.toolchain)||typeof a.binarySha256!=`string`||await L(e,i,r)!==a.binarySha256?void 0:{path:i,sourceHash:n.sourceHash,cacheKey:n.cacheKey,protocolVersion:1,sourceVersion:D}}catch(e){if(e instanceof y&&(e.failureKind===`cancelled`||e.failureKind===`timeout`))throw e;return}}async function L(e,t,n){return S(n,`native-cache-hash-deadline`),g(`sha256`).update(await e.readBinary(t)).digest(`hex`)}function we(e){return g(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,32)}var Te=class{entries=new Map;probeBackAfterUses;constructor(e=8){this.probeBackAfterUses=e}consume(e,t,n){if(n)return{nativeLevels:void 0,reason:`explicit-depth`};let r=this.currentEntry(e);return r===`unidentified`?{nativeLevels:void 0,reason:`unidentified-target`}:!r||r.nativeLevels>=t?{nativeLevels:void 0,reason:`no-hint`}:r.remainingUses<=0?{nativeLevels:void 0,reason:`probe-back`}:(--r.remainingUses,{nativeLevels:r.nativeLevels,reason:`hinted`})}learn(e,t,n,r){return n||!e.targetId?`ignored`:r.rejected>0&&r.acceptedLevels<t?(this.remember(e.targetId,{generation:e.generation,nativeLevels:r.acceptedLevels,remainingUses:this.probeBackAfterUses}),`learned`):r.rejected===0&&r.acceptedLevels>=t?this.entries.delete(e.targetId)?`forgotten`:`ignored`:this.currentEntry(e)?`kept`:`ignored`}currentEntry(e){if(!e.targetId)return`unidentified`;let t=this.entries.get(e.targetId);if(t){if(t.generation!==e.generation){this.entries.delete(e.targetId);return}return t}}remember(e,t){if(this.entries.delete(e),this.entries.size>=32){let e=this.entries.keys().next().value;e!==void 0&&this.entries.delete(e)}this.entries.set(e,t)}};const R=65536;function Ee(){return{projectRoot:m,homeDirectory:re,run:async(e,t,n)=>await c(e,t,n),start:De,connect:z,readText:ce,readBinary:ie,writeText:te,ensureDirectory:oe,chmod:ae,exists:ne,rename:se,remove:ee,acquireLock:Oe,emitDiagnostic:a,withDiagnosticTimer:i,processId:o,readTargetProcessStartTime:ue}}function De(e,t,n,r={}){if(r.signal?.aborted)throw b(`cancelled`,`abort-signal`);let i=l(`xcrun`,[`simctl`,`spawn`,e,t,`serve`,n,`--idle-timeout`,`60`,`--exit-on-disconnect`,`false`],{allowFailure:!0,captureOutput:!1,detached:!0}),a=i.child.pid??0;if(a<=0)throw b(`transport-failure`,`bridge-process-pid-missing`);let o=``;return i.child.stderr?.setEncoding(`utf8`),i.child.stderr?.on(`data`,e=>{o=ke(o,String(e))}),{pid:a,wait:i.wait,isAlive:()=>i.child.exitCode===null&&i.child.signalCode===null,signal:e=>{u(a,e)||i.child.kill(e)},readLog:()=>o}}async function z(e,t){if(t.signal?.aborted)throw b(`cancelled`,`abort-signal`);let n=Math.max(1,Math.floor(t.timeoutMs));return await new Promise((r,i)=>{let a=de.createConnection({path:e}),o=!1,s=!1,c=setTimeout(()=>{p(b(`timeout`,`bridge-connect-timeout`)),a.destroy()},n),l=()=>{p(b(`cancelled`,`abort-signal`)),a.destroy()},u=()=>{o=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`error`,d),a.off(`close`,f),a.setTimeout(0),r(a)},d=e=>{p(e),a.destroy()},f=()=>{o||p(b(`transport-failure`,`bridge-closed-before-connect`))},p=e=>{s||o||(s=!0,clearTimeout(c),t.signal?.removeEventListener(`abort`,l),a.off(`connect`,u),a.off(`error`,d),a.off(`close`,f),i(e))};a.once(`connect`,u),a.once(`error`,d),a.once(`close`,f),t.signal?.addEventListener(`abort`,l,{once:!0}),t.signal?.aborted&&l()})}async function Oe(e,t){let n=o(),r=t.deadline,i=f({lockDirPath:e,owner:{pid:n,startTime:s(n),acquiredAtMs:Date.now()},timeoutMs:S(r,`cache-lock-deadline`),pollMs:100,ownerGraceMs:5e3,description:`iOS Simulator snapshot bridge cache`}),a=r.signal;if(!a)return await i;let c=!1,l,u=new Promise((e,t)=>{l=()=>{c=!0,t(b(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,l,{once:!0}),a.aborted&&l()});try{return await Promise.race([i,u])}catch(e){throw c&&i.then(e=>e(),()=>void 0),r.clock.isExpired()&&!(e instanceof y&&e.failureKind===`cancelled`)?b(`timeout`,`cache-lock-deadline`):e}finally{a.removeEventListener(`abort`,l)}}function ke(e,t){let n=e+t;return n.length<=R?n:n.slice(n.length-R)}function Ae(e,t,n){let r=g(`sha256`).update(t).digest(`hex`).slice(0,12),i=g(`sha256`).update(n).digest(`hex`).slice(0,12);return h.join(`/tmp`,`agent-device-ax-${r}-${e.processId()}-${i}`,`snapshot.sock`)}const B=new WeakSet;async function V(e,t){let n;try{n=(await t.wait).exitCode}catch{n=void 0}return B.has(t)||(B.add(t),e.emitDiagnostic({level:`error`,phase:`ios.snapshot-source.bridge-process-exit`,data:{pid:t.pid,...n===void 0?{}:{exitCode:n},stderr:je(t.readLog())}})),b(`process-crash`,`bridge-exited`,{pid:t.pid,...n===void 0?{}:{exitCode:n}})}function je(e){let t=v.from(e);return t.length<=65536?e:t.subarray(-65536).toString(`utf8`)}async function Me(e){let t=new O(e.limits.maxResponseBytes-4),n=S(e.deadline,`bridge-request-deadline`);return await new Promise((r,i)=>{let a=!1,o=!1,s=setTimeout(()=>{p(b(`timeout`,`bridge-request-deadline`,{dispatched:o})),e.socket.destroy()},n),c=()=>{p(b(`cancelled`,`abort-signal`,{dispatched:o})),e.socket.destroy()},l=n=>{try{if(!Buffer.isBuffer(n))throw b(`transport-failure`,`bridge-data-invalid`);let r=t.push(n);if(r){let t=k(r);if(j(t,e.requestId),M(t,{pid:e.expectedPid,generation:e.expectedGeneration}),t.ok!==!0&&N(t),typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);f(t);return}}catch(t){p(t),e.socket.destroy()}},u=e=>p(x(e)),d=()=>{a||(e.process.isAlive()?p(b(`transport-failure`,`bridge-connection-closed`)):V(e.host,e.process).then(p))};e.process.wait.then(()=>{a||V(e.host,e.process).then(p)},e=>{a||p(x(e))});let f=e=>m(()=>r(e)),p=e=>m(()=>i(e)),m=t=>{a||(a=!0,clearTimeout(s),e.deadline.signal?.removeEventListener(`abort`,c),e.socket.off(`data`,l),e.socket.off(`error`,u),e.socket.off(`close`,d),t())};e.socket.on(`data`,l),e.socket.on(`error`,u),e.socket.on(`close`,d),e.deadline.signal?.addEventListener(`abort`,c,{once:!0});try{if(e.deadline.signal?.aborted)throw b(`cancelled`,`abort-signal`);o=!0,e.socket.write(e.frame)}catch(t){p(x(t)),e.socket.destroy()}})}var Ne=class{sessions=new Map;requestQueues=new Map;ownerId=_();closed=!1;host;constructor(e){this.host=e}async request(e){if(this.closed)throw b(`unsupported`,`source-closed`);return await this.withSimulatorLock(e.target.udid,e.deadline,()=>this.requestInSimulator(e))}async requestInSimulator(e){if(this.closed)throw b(`unsupported`,`source-closed`);let t=e.deadline;S(t,`bridge-request-deadline`);let n=this.sessions.get(e.target.udid),r=await this.ensureSession(e,t);try{let n=await this.readTargetStartTime(e.target,t),i=await this.exchange(r,e,t);return await this.assertTargetStillCurrent(e.target,n,t),i}catch(e){throw await this.handleRequestFailure(e,r,n)}}async handleRequestFailure(e,t,n){let r=x(e);return Fe(r,t,n)?await this.removeSession(t,!0):r.failureKind===`process-crash`?await this.removeSession(t,!1):r.failureKind===`transport-failure`&&(t.socket?.destroy(),t.socket=void 0),r}async withSimulatorLock(e,t,n){let r=this.requestQueues.get(e)??Promise.resolve(),i,a=new Promise(e=>{i=e}),o=r.then(()=>a);this.requestQueues.set(e,o);try{return await Pe(r,t),await n()}finally{i(),this.requestQueues.get(e)===o&&this.requestQueues.delete(e)}}async close(){if(this.closed)return;this.closed=!0;let e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(async e=>await this.dispose(e,!0)))}async ensureSession(e,t){let n=e.target.udid,r=this.sessions.get(n);if(r&&r.bridgePath===e.bridge.path&&r.process.isAlive())return(!r.socket||r.socket.destroyed)&&(r.socket=await this.connectUntilReady(r,t)),r;r&&await this.removeSession(r,!0);let i=Ae(this.host,e.target.udid,this.ownerId);await this.host.ensureDirectory(h.dirname(i)),await this.host.remove(i);let a=this.host.start(e.target.udid,e.bridge.path,i,{signal:t.signal}),o={udid:e.target.udid,bridgePath:e.bridge.path,socketPath:i,process:a};this.sessions.set(n,o);try{return o.socket=await this.connectUntilReady(o,t),o}catch(e){throw await this.removeSession(o,!0),x(e)}}async connectUntilReady(e,t){let n;for(;;){let r=S(t,`bridge-connect-deadline`);if(!e.process.isAlive())throw await V(this.host,e.process);try{return await this.host.connect(e.socketPath,{signal:t.signal,timeoutMs:Math.min(250,r)})}catch(e){if(n=e,e instanceof y&&e.failureKind===`cancelled`)throw e;let r=Math.min(20,S(t,`bridge-connect-deadline`));try{await C(t,r,`bridge-connect-deadline`)}catch(e){throw x(e)}}if(n instanceof y&&n.failureKind===`timeout`)throw n}}async exchange(e,t,n){(!e.socket||e.socket.destroyed)&&(e.socket=await this.connectUntilReady(e,n));let r=_(),i=be(A({requestId:r,pid:t.target.pid,generation:t.target.generation,maxDepth:Math.min(t.limits.maxTraversalDepth,t.maxDepth),maxNodes:t.limits.maxNodes,maxDurationMs:S(n,`bridge-request-deadline`),maxResponseBytes:t.limits.maxResponseBytes,...t.nativeLevelsHint===void 0?{}:{nativeLevelsHint:t.nativeLevelsHint}}),t.limits);return await Me({process:e.process,socket:e.socket,frame:i,requestId:r,deadline:n,limits:t.limits,expectedPid:t.target.pid,expectedGeneration:t.target.generation,host:this.host})}async readTargetStartTime(e,t){let n=await this.host.readTargetProcessStartTime(e.pid,{signal:t.signal,timeoutMs:S(t,`target-identity-deadline`)});if(!n)throw b(`stale-target`,`target-process-unavailable`,{pid:e.pid,generation:e.generation});if(e.processStartTime!==void 0&&e.processStartTime!==n)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:e.processStartTime,observedStartTime:n});return n}async assertTargetStillCurrent(e,t,n){let r=await this.host.readTargetProcessStartTime(e.pid,{signal:n.signal,timeoutMs:S(n,`target-identity-deadline`)});if(r!==t)throw b(`stale-target`,`target-process-changed`,{pid:e.pid,generation:e.generation,expectedStartTime:t,observedStartTime:r})}async removeSession(e,t){this.sessions.get(e.udid)===e&&this.sessions.delete(e.udid),await this.dispose(e,t)}async dispose(e,t){e.socket?.destroy(),e.socket=void 0,t&&e.process.isAlive()&&(e.process.signal(`SIGTERM`),await H(e.process,500),e.process.isAlive()&&(e.process.signal(`SIGKILL`),await H(e.process,500))),await this.host.remove(e.socketPath)}};async function Pe(e,t){let n=S(t,`bridge-request-deadline`);await Promise.race([e,C(t,n,`bridge-request-deadline`).then(()=>{throw b(`timeout`,`bridge-request-deadline`)})])}function Fe(e,t,n){return(e.failureKind===`cancelled`||e.failureKind===`timeout`)&&(e.details?.dispatched===!0||n!==t)}async function H(e,t){await Promise.race([e.wait.catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}const U=16777216,W=12e4,G=1e4,Ie=Object.freeze({maxRequestBytes:65536,maxResponseBytes:4194304,maxNodes:5e3,maxTraversalDepth:64,maxDurationMs:5e3});function Le(t){let n={...Ie,...t??{}};for(let[t,r]of Object.entries(n))if(!Number.isSafeInteger(r)||r<=0)throw new e(`INVALID_ARGS`,`Snapshot source limit ${t} must be a positive integer`,{name:t,value:r});if(n.maxRequestBytes>n.maxResponseBytes)throw new e(`INVALID_ARGS`,`Snapshot source request bytes cannot exceed response bytes`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});if(n.maxRequestBytes>U||n.maxResponseBytes>U)throw new e(`INVALID_ARGS`,`Snapshot source frame limits exceed the bridge bound`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes,maximumFrameBytes:U});if(n.maxNodes>G||n.maxTraversalDepth>128)throw new e(`INVALID_ARGS`,`Snapshot source tree limits exceed the bridge bound`,{maxNodes:n.maxNodes,maxTraversalDepth:n.maxTraversalDepth,maximumNodes:G,maximumDepth:128});if(n.maxDurationMs>W)throw new e(`INVALID_ARGS`,`Snapshot source duration exceeds the bridge bound`,{maxDurationMs:n.maxDurationMs,maximumDurationMs:W});if(n.maxRequestBytes<=4||n.maxResponseBytes<=4)throw new e(`INVALID_ARGS`,`Snapshot source frame limits must leave room for a body`,{maxRequestBytes:n.maxRequestBytes,maxResponseBytes:n.maxResponseBytes});return Object.freeze(n)}const K=Object.freeze({elementType:`XC_kAXXCAttributeElementType`,elementBaseType:`XC_kAXXCAttributeElementBaseType`,label:`XC_kAXXCAttributeLabel`,value:`XC_kAXXCAttributeValue`,identifier:`XC_kAXXCAttributeIdentifier`,frame:`XC_kAXXCAttributeFrame`,automationType:`XC_kAXXCAttributeAutomationType`,children:`XC_kAXXCAttributeChildren`}),q=`Other.Other.Application.Group.Window.Sheet.Drawer.Alert.Dialog.Button.RadioButton.RadioGroup.CheckBox.DisclosureTriangle.PopUpButton.ComboBox.MenuButton.ToolbarButton.Popover.Keyboard.Key.NavigationBar.TabBar.TabGroup.Toolbar.StatusBar.Table.TableRow.TableColumn.Outline.OutlineRow.Browser.CollectionView.Slider.PageIndicator.ProgressIndicator.ActivityIndicator.SegmentedControl.Picker.PickerWheel.Switch.Toggle.Link.Image.Icon.SearchField.ScrollView.ScrollBar.StaticText.TextField.SecureTextField.DatePicker.TextView.Menu.MenuItem.MenuBar.MenuBarItem.Map.WebView.IncrementArrow.DecrementArrow.Timeline.RatingIndicator.ValueIndicator.SplitGroup.Splitter.RelevanceIndicator.ColorWell.HelpTag.Matte.DockItem.Ruler.RulerMarker.Grid.LevelIndicator.Cell.LayoutArea.LayoutItem.Handle.Stepper.Tab.TouchBar.StatusItem`.split(`.`),J={UIApplication:`Application`,UIWindow:`Window`},Re=new Set(Object.values(K));function ze(e,t,n){let r=Array.isArray(e)?e:[e];if(r.length===0||r.some(e=>!P(e)))throw b(`malformed-tree`,`guest-tree-root-invalid`);let i=[],a=[],o=0;for(let e of r)c(e,void 0,0,!1);if(i.length>n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{nodeCount:i.length,maxNodes:n.maxNodes});if(o>n.maxTraversalDepth)throw b(`malformed-tree`,`traversal-depth-exceeded`,{maxTraversalDepth:o,maxAllowedDepth:n.maxTraversalDepth});if(typeof t.truncated!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let s=We(i.find(e=>e.type===`Application`||e.type===`Window`));return{nodes:i,maxTraversalDepth:o,viewport:s,opaqueRemoteElements:a.filter(e=>He(e,s)).length};function c(e,t,r,s){if(i.length>=n.maxNodes)throw b(`malformed-tree`,`node-limit-exceeded`,{maxNodes:n.maxNodes});for(let t of Object.keys(e))if(!Re.has(t))throw b(`malformed-tree`,`node-contains-unknown-field`,{key:t});let l=e[K.children];if(!Array.isArray(l))throw b(`malformed-tree`,`children-invalid`);let u=i.length,d=Be(e,u,t,r);i.push(d),o=Math.max(o,r),Ve(d,l.length,s)&&a.push(d.rect);let f=s||d.type===`WebView`;for(let e of l){if(!P(e))throw b(`malformed-tree`,`child-invalid`);c(e,u,r+1,f)}}}function Be(e,t,n,r){let i=X(e[K.elementType]),a=X(e[K.elementBaseType]),o=Ge(e[K.automationType]),s=Ue(e[K.frame]);return{index:t,...n===void 0?{}:{parentIndex:n},...Y(i,o)?{type:Y(i,o)}:{},...i?{role:i}:{},...a&&a!==i?{subrole:a}:{},...X(e[K.label])?{label:X(e[K.label])}:{},...Z(e[K.value])?{value:Z(e[K.value])}:{},...X(e[K.identifier])?{identifier:X(e[K.identifier])}:{},...s?{rect:s}:{},depth:r}}function Y(e,t){if(e!==void 0&&J[e])return J[e];if(e!==void 0&&q.includes(e))return e;if(t!==void 0)return q[t]??`Other`}function Ve(e,t,n){return n&&e.role===`AXRemoteElement`&&t===0}function He(e,t){return e===void 0?!0:r(e)?t.kind!==`reported`||n(e,t.rect):!1}function Ue(e){if(e===void 0)return;if(!P(e))throw b(`malformed-tree`,`frame-invalid`);let t=[`X`,`Y`,`Width`,`Height`].map(t=>e[t]);if(!t.every(e=>typeof e==`number`&&Number.isFinite(e)))throw b(`malformed-tree`,`frame-invalid`);let[n,r,i,a]=t;if(i<0||a<0)throw b(`malformed-tree`,`frame-invalid`);return{x:n,y:r,width:i,height:a}}function We(e){return!e||e.type!==`Application`&&e.type!==`Window`?{kind:`missing`,reason:`not-provided`}:r(e.rect)?{kind:`reported`,rect:e.rect}:{kind:`missing`,reason:e.rect?`invalid`:`not-provided`}}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`string`)return e.length>0?e:void 0;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e!=null)throw b(`malformed-tree`,`scalar-invalid`)}function Ge(e){if(e!=null){if(!Number.isSafeInteger(e))throw b(`malformed-tree`,`automation-type-invalid`);return e}}const Q=`simulator-ax-bridge`;function Ke(e={}){let t=e.host??Ee(),n=new Ne(t),r=new Te,i=new Map,a=!1,o=async n=>{if(a)throw b(`unsupported`,`source-closed`);let r=i.get(n.runtime);if(r)return r;let o=await t.withDiagnosticTimer(`ios.snapshot-source.prepare`,async()=>await xe({host:t,runtime:n.runtime,limits:n.limits,deadline:n.deadline,sourceRoot:e.sourceRoot,cacheRoot:e.cacheRoot}),{producer:Q});return i.set(n.runtime,o),o};return{acquire:async i=>{try{if(a)throw b(`unsupported`,`source-closed`);qe(i);let s=Le({...e.limits,...i.limits}),c=pe(s.maxDurationMs,i.signal),l=Ye(i.hint,s.maxTraversalDepth),u=l+1,d=i.hint.rawTraversalDepth!==null;return await t.withDiagnosticTimer(`ios.snapshot-source.acquire`,async()=>{let e=await o({runtime:i.target.runtime,limits:s,deadline:c}),a=r.consume(i.target,u,d),f=await n.request({target:i.target,bridge:e,limits:s,maxDepth:l,nativeLevelsHint:a.nativeLevels,deadline:c});S(c,`snapshot-decode-deadline`);let p=Xe(i.hint,i.target,f,s);return Je(t,r,i.target,u,d,a,f),{stage:`acquired`,acquisition:p}},{producer:Q})}catch(e){let t=x(e);return{stage:`failed`,failure:{kind:t.failureKind,code:t.failureCode,...t.details?{details:t.details}:{}}}}},close:async()=>{a||(a=!0,await n.close())}}}function qe(t){if(!t.target.udid.trim()||!t.target.runtime.trim()||!t.target.generation.trim()||!Number.isSafeInteger(t.target.pid)||t.target.pid<=0)throw new e(`INVALID_ARGS`,`Simulator snapshot source target identity is incomplete`);let n=t.hint;if(n.projection!==`raw`&&n.projection!==`regular`||![`full`,`surface-observation`].includes(n.acquisitionIntent)||typeof n.interactiveOnly!=`boolean`||typeof n.customActions!=`boolean`||!$(n.rawTraversalDepth)||!$(n.regularPresentedDepth))throw new e(`INVALID_ARGS`,`Simulator snapshot source capture hint is invalid`)}function Je(e,t,n,r,i,a,o){let s=ye(o),c=o.truncated===!0,l=t.learn(n,r,i,s);e.emitDiagnostic({level:`debug`,phase:`ios_snapshot_source_recovery`,data:{producer:Q,...n.targetId?{targetId:n.targetId}:{},generation:n.generation,requestedLevels:r,hint:a.reason,...a.nativeLevels===void 0?{}:{hintedLevels:a.nativeLevels},...s,truncated:c,learning:l}})}function Ye(t,n){let r=t.rawTraversalDepth??n;if(r>n)throw new e(`INVALID_ARGS`,`Simulator snapshot source depth exceeds its bound`,{requested:r,maximum:n});return r}function $(e){return e===null||Number.isSafeInteger(e)&&e>=0}function Xe(e,t,n,r){if(n.automationEnabled!==!0)throw b(`unsupported`,`automation-mode-unavailable`);let i=n.tree,a=n.truncated;if(typeof a!=`boolean`)throw b(`malformed-tree`,`truncated-invalid`);let o=ze(i,{truncated:a},r),s=n.generation;if(typeof s!=`string`||!s)throw b(`malformed-tree`,`generation-invalid`);if(o.opaqueRemoteElements>0)throw b(`unsupported`,`remote-content-boundary`,{remoteElements:o.opaqueRemoteElements});let c=Object.freeze(o.nodes.map(e=>Object.freeze({...e,pid:t.pid}))),l=Ze(e,a,o.viewport),u=Object.freeze({...t.targetId?{targetId:t.targetId}:{},generation:s}),d={producer:Q,nodes:c,truncated:a,viewport:o.viewport,lineage:u,residue:l};return e.acquisitionIntent===`full`?{...d,intent:`full`,hint:{...e,acquisitionIntent:`full`}}:{...d,intent:`surface-observation`,hint:{...e,acquisitionIntent:`surface-observation`}}}function Ze(e,t,n){return Object.freeze([{kind:`unavailable-fact`,fact:`hittability`},...e.interactiveOnly?[{kind:`unavailable-fact`,fact:`interactive-query`}]:[],...t?[{kind:`truncated`}]:[],...n.kind===`missing`?[{kind:`missing-viewport`,reason:n.reason}]:[]])}export{Ke as createSimulatorSnapshotSource};
@@ -1,2 +1,2 @@
1
- import{C as e}from"./sdk-contracts.js";import{a as t,r as n}from"./adb-host.js";import{n as r,s as i}from"./adb-failure.js";import a from"node:path";import{AsyncLocalStorage as o}from"node:async_hooks";const s=new WeakSet;function c(e){return l(typeof e==`function`?{exec:e}:e)}function l(e){if(s.has(e))return e;let t={...e,exec:i(u(e.exec)),...e.pull?{pull:i(u(e.pull))}:{},...e.install?{install:i(u(e.install))}:{},...e.installBundle?{installBundle:i(e.installBundle)}:{}};return s.add(t),t}function u(e){return async(...t)=>n().coerceAdbResult(await e(...t))}const d=new WeakSet;function f(t){let n=c(t);if(n.reverse&&d.has(n.reverse))return n.reverse;let r=n.reverse??p(n.exec),i=new Map,a={async ensure(t,n){let a=i.get(t.local);if(a&&a.ownerId!==t.ownerId)throw new e(`COMMAND_FAILED`,`Android port reverse ${t.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:t});a?.remote!==t.remote&&(await r.ensure(t,n),i.set(t.local,{...t}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}};return d.add(a),a}function p(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,i){let a=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:i?.signal,timeoutMs:i?.timeoutMs});if(a.exitCode!==0&&!h(a.stdout,a.stderr))throw r(`Failed to remove Android port reverse ${n}`,a,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?m(r.stdout,t):[]}}}function m(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
2
- `).map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>{let r=e;return{local:r,remote:t,ownerId:n.get(r)}})}function h(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`listener`)&&n.includes(`not found`)}function g(e){let{replace:t,allowTestPackages:n,allowDowngrade:r,grantPermissions:i,...a}=e??{},o=[];return t&&o.push(`-r`),n&&o.push(`-t`),r&&o.push(`-d`),i&&o.push(`-g`),{installArgs:o,execOptions:a}}const _=new o;function v(e,t={}){return y(e.id,t.serverPort)}function y(e,t){return i(async(r,i)=>{let a=N(e,t);return await n().execSerialAdb(e,r,a===void 0?i:{...i,serverPort:a})})}function b(e,t){return(r,i)=>{let a=N(e,t);return n().spawnSerialAdb(e,r,a===void 0?i:{...i,serverPort:a})}}function x(e,t={}){let n=v(e,t);return{exec:n,spawn:b(e.id,t.serverPort),reverse:p(n),pull:async(e,t,r)=>await n([`pull`,e,t],r),install:async(e,t)=>{let{installArgs:r,execOptions:i}=g(t);return await n([`install`,...r,e],i)}}}function S(e,t){let n=j(e);return t||(n?.serial===e.id?n.provider.exec:v(e))}function C(e,t){let n=j(e);return t?c(t):n?.serial===e.id?c(n.provider):x(e)}function w(e){let t=j(e);return t?.serial===e.id?{mode:`transport-composed`,...t.provider.spawn?{spawn:t.provider.spawn}:{}}:{mode:`local`}}function T(e){let t=j(e);return t?.serial===e.id?t.provider.text:void 0}function E(e){let t=j(e);return t?.serial===e.id&&t.provider.touch?t.provider:void 0}function D(e,t){if(t)return c(t);if(e)return C(e);let n=_.getStore();if(n)return c(n.provider)}async function O(e,r,i){if(!e)return await i();let a={provider:c(e),serial:r.serial,...r.serverPort===void 0?{}:{serverPort:r.serverPort}},o=k(a),s=async()=>await _.run(a,async()=>await n().withAdbCommandExecutorOverride(o,i));return r.serverPort===void 0?await s():await t(A(a),s)}function k(e){return(t,r,i)=>{if(!P(t)||e.serverPort===void 0&&t!==`adb`)return;let a=F(r);if(M(e,a),!(a&&a!==e.serial)){if(a===e.serial){let t=L(r,e.serial);return t?n().withoutAdbCommandExecutorOverride(async()=>await e.provider.exec(t,i)):void 0}if(e.serverPort!==void 0)return n().withoutAdbCommandExecutorOverride(async()=>await n().execHostAdb([`-s`,e.serial,...r],{...i,allowFailure:!0,serverPort:e.serverPort}))}}}function A(e){return async(t,r)=>{let i=F(t);M(e,i);let a=n();return await a.withoutAdbCommandExecutorOverride(async()=>await a.execHostAdb(i===void 0?[`-s`,e.serial,...t]:t,{...r,allowFailure:!0,serverPort:e.serverPort}))}}function j(e){let t=_.getStore();return M(t,e.id),t}function M(t,n){if(t?.serverPort!==void 0&&n!==void 0&&n!==t.serial)throw new e(`COMMAND_FAILED`,`Managed ADB transport cannot address another device.`,{reason:`managed-device-transport-mismatch`})}function N(t,n){let r=_.getStore();if(M(r,t),r?.serverPort===void 0)return n;if(n!==void 0&&n!==r.serverPort)throw new e(`COMMAND_FAILED`,`Managed ADB transport cannot select another server.`,{reason:`managed-device-transport-mismatch`});return r.serverPort}function P(e){return a.basename(e).replace(/\.(?:com|exe|bat|cmd)$/i,``)===`adb`}function F(e){let t=I(e);return t===void 0?void 0:e[t+1]}function I(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`-s`)return t;if(n===`-P`||n===`-H`||n===`-L`){t+=2;continue}if(n===`-a`||n===`-d`||n===`-e`){t+=1;continue}return}}function L(e,t){let n=I(e);if(n!==void 0&&e[n+1]===t)return[...e.slice(0,n),...e.slice(n+2)]}async function R(t,r,i){let{device:a,provider:o,...s}=i??{},c=D(a,o),l=c?.pull,u=n();if(l)return await u.withoutAdbCommandExecutorOverride(async()=>await l(t,r,s));let d=c?.exec;if(!d)throw new e(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await u.withoutAdbCommandExecutorOverride(async()=>await d([`pull`,t,r],s))}async function z(t,r){let{device:i,provider:a,...o}=r??{},s=D(i,a),c=s?.install,l=n();if(c)return await l.withoutAdbCommandExecutorOverride(async()=>await c(t,o));let u=s?.exec;if(!u)throw new e(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:d,execOptions:f}=g(o);return await l.withoutAdbCommandExecutorOverride(async()=>await u([`install`,...d,t],f))}export{S as a,E as c,f as d,x as i,w as l,R as n,C as o,v as r,T as s,z as t,O as u};
1
+ import{C as e}from"./sdk-contracts.js";import{a as t,r as n}from"./adb-host.js";import{c as r,n as i}from"./adb-failure.js";import a from"node:path";import{AsyncLocalStorage as o}from"node:async_hooks";const s=new WeakSet;function c(e){return l(typeof e==`function`?{exec:e}:e)}function l(e){if(s.has(e))return e;let t={...e,exec:r(u(e.exec)),...e.pull?{pull:r(u(e.pull))}:{},...e.install?{install:r(u(e.install))}:{},...e.installBundle?{installBundle:r(e.installBundle)}:{}};return s.add(t),t}function u(e){return async(...t)=>n().coerceAdbResult(await e(...t))}const d=new WeakSet;function f(t){let n=c(t);if(n.reverse&&d.has(n.reverse))return n.reverse;let r=n.reverse??p(n.exec),i=new Map,a={async ensure(t,n){let a=i.get(t.local);if(a&&a.ownerId!==t.ownerId)throw new e(`COMMAND_FAILED`,`Android port reverse ${t.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:t});a?.remote!==t.remote&&(await r.ensure(t,n),i.set(t.local,{...t}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}};return d.add(a),a}function p(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,r){let a=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:r?.signal,timeoutMs:r?.timeoutMs});if(a.exitCode!==0&&!h(a.stdout,a.stderr))throw i(`Failed to remove Android port reverse ${n}`,a,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?m(r.stdout,t):[]}}}function m(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
2
+ `).map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>{let r=e;return{local:r,remote:t,ownerId:n.get(r)}})}function h(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`listener`)&&n.includes(`not found`)}function g(e){let{replace:t,...n}=e??{};return{installArgs:t?[`-r`]:[],execOptions:n}}const _=new o;function v(e,t={}){return y(e.id,t.serverPort)}function y(e,t){return r(async(r,i)=>{let a=N(e,t);return await n().execSerialAdb(e,r,a===void 0?i:{...i,serverPort:a})})}function b(e,t){return(r,i)=>{let a=N(e,t);return n().spawnSerialAdb(e,r,a===void 0?i:{...i,serverPort:a})}}function x(e,t={}){let n=v(e,t);return{exec:n,spawn:b(e.id,t.serverPort),reverse:p(n),pull:async(e,t,r)=>await n([`pull`,e,t],r),install:async(e,t)=>{let{installArgs:r,execOptions:i}=g(t);return await n([`install`,...r,e],i)}}}function S(e,t){let n=j(e);return t||(n?.serial===e.id?n.provider.exec:v(e))}function C(e,t){let n=j(e);return t?c(t):n?.serial===e.id?c(n.provider):x(e)}function w(e){let t=j(e);return t?.serial===e.id?{mode:`transport-composed`,...t.provider.spawn?{spawn:t.provider.spawn}:{}}:{mode:`local`}}function T(e){let t=j(e);return t?.serial===e.id?t.provider.text:void 0}function E(e){let t=j(e);return t?.serial===e.id&&t.provider.touch?t.provider:void 0}function D(e,t){if(t)return c(t);if(e)return C(e);let n=_.getStore();if(n)return c(n.provider)}async function O(e,r,i){if(!e)return await i();let a={provider:c(e),serial:r.serial,...r.serverPort===void 0?{}:{serverPort:r.serverPort}},o=k(a),s=async()=>await _.run(a,async()=>await n().withAdbCommandExecutorOverride(o,i));return r.serverPort===void 0?await s():await t(A(a),s)}function k(e){return(t,r,i)=>{if(!P(t)||e.serverPort===void 0&&t!==`adb`)return;let a=F(r);if(M(e,a),!(a&&a!==e.serial)){if(a===e.serial){let t=L(r,e.serial);return t?n().withoutAdbCommandExecutorOverride(async()=>await e.provider.exec(t,i)):void 0}if(e.serverPort!==void 0)return n().withoutAdbCommandExecutorOverride(async()=>await n().execHostAdb([`-s`,e.serial,...r],{...i,allowFailure:!0,serverPort:e.serverPort}))}}}function A(e){return async(t,r)=>{let i=F(t);M(e,i);let a=n();return await a.withoutAdbCommandExecutorOverride(async()=>await a.execHostAdb(i===void 0?[`-s`,e.serial,...t]:t,{...r,allowFailure:!0,serverPort:e.serverPort}))}}function j(e){let t=_.getStore();return M(t,e.id),t}function M(t,n){if(t?.serverPort!==void 0&&n!==void 0&&n!==t.serial)throw new e(`COMMAND_FAILED`,`Managed ADB transport cannot address another device.`,{reason:`managed-device-transport-mismatch`})}function N(t,n){let r=_.getStore();if(M(r,t),r?.serverPort===void 0)return n;if(n!==void 0&&n!==r.serverPort)throw new e(`COMMAND_FAILED`,`Managed ADB transport cannot select another server.`,{reason:`managed-device-transport-mismatch`});return r.serverPort}function P(e){return a.basename(e).replace(/\.(?:com|exe|bat|cmd)$/i,``)===`adb`}function F(e){let t=I(e);return t===void 0?void 0:e[t+1]}function I(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`-s`)return t;if(n===`-P`||n===`-H`||n===`-L`){t+=2;continue}if(n===`-a`||n===`-d`||n===`-e`){t+=1;continue}return}}function L(e,t){let n=I(e);if(n!==void 0&&e[n+1]===t)return[...e.slice(0,n),...e.slice(n+2)]}async function R(t,r,i){let{device:a,provider:o,...s}=i??{},c=D(a,o),l=c?.pull,u=n();if(l)return await u.withoutAdbCommandExecutorOverride(async()=>await l(t,r,s));let d=c?.exec;if(!d)throw new e(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await u.withoutAdbCommandExecutorOverride(async()=>await d([`pull`,t,r],s))}async function z(t,r){let{device:i,provider:a,...o}=r??{},s=D(i,a),c=s?.install,l=n();if(c)return await l.withoutAdbCommandExecutorOverride(async()=>await c(t,o));let u=s?.exec;if(!u)throw new e(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:d,execOptions:f}=g(o);return await l.withoutAdbCommandExecutorOverride(async()=>await u([`install`,...d,t],f))}export{S as a,E as c,f as d,x as i,w as l,R as n,C as o,v as r,T as s,z as t,O as u};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";var n=e({androidAdbResultError:()=>c,androidDiscoveryCommandError:()=>u,attachAdbFailureHint:()=>o,attachAndroidDiscoveryTimeout:()=>d,classifyAndroidAdbFailure:()=>a,withAdbFailureHints:()=>l});const r=[[/device unauthorized|device still authorizing/,{reason:`device_unauthorized`,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`}],[/device offline/,{reason:`device_offline`,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0}],[/more than one (?:device\/emulator|device and emulator)/,{reason:`multiple_devices`,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`}],[/no devices\/emulators found|no devices found/,{reason:`no_devices`,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`}],[/device (?:'[^']*' )?not found/,{reason:`device_not_found`,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0}],[/adb server version \(\d+\) doesn't match this client/,{reason:`server_version_mismatch`,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0}],[/transport error|connection reset|broken pipe|protocol fault/,{reason:`connection_dropped`,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0}],[/install_failed_insufficient_storage/,{reason:`install_insufficient_storage`,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`},!0],[/install_failed_update_incompatible/,{reason:`install_update_incompatible`,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`},!0],[/install_failed_version_downgrade/,{reason:`install_version_downgrade`,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`},!0],[/install_failed_\w+|install_parse_failed_\w+/,{reason:`install_failed`,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`},!0]],i=Object.freeze({reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`});function a(e,t=``){let n=e.toLowerCase(),i=t.toLowerCase();for(let[e,t,a]of r)if(e.test(n)||a&&e.test(i))return t}function o(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return e;let n=s(e);return n&&(e.details={...e.details,adbFailure:n.reason,...typeof e.details?.hint==`string`?{}:{hint:n.hint},...n.retriable!==void 0&&e.details?.retriable===void 0?{retriable:n.retriable}:{}}),e}function s(e){return typeof e.details?.timeoutMs==`number`?i:a(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function c(e,n,r){let i=n.exitCode===0?{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,...r}:{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,processExitError:!0,...r};return o(new t(`COMMAND_FAILED`,e,i))}function l(e){return async(...t)=>{try{return await e(...t)}catch(e){throw o(e)}}}function u(e,n,r){let i=a(n.stderr,n.stdout);return new t(`COMMAND_FAILED`,e,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,processExitError:!0,hint:i?.hint??r,...i?{adbFailure:i.reason}:{},...i?.retriable===void 0?{}:{retriable:i.retriable}})}function d(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`||typeof e.details?.timeoutMs!=`number`||(e.details={...e.details,adbFailure:i.reason,...typeof e.details.hint==`string`?{}:{hint:i.hint}}),e}export{d as a,o as i,c as n,a as o,u as r,l as s,n as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{r as n}from"./exec.js";import"./command.js";var r=e({androidAdbResultError:()=>u,androidDiscoveryCommandError:()=>f,attachAdbFailureHint:()=>s,attachAndroidDiscoveryTimeout:()=>p,attachAndroidHelperInstallTimeoutHint:()=>c,classifyAndroidAdbFailure:()=>o,withAdbFailureHints:()=>d});const i=[[/device unauthorized|device still authorizing/,{reason:`device_unauthorized`,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`}],[/device offline/,{reason:`device_offline`,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0}],[/more than one (?:device\/emulator|device and emulator)/,{reason:`multiple_devices`,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`}],[/no devices\/emulators found|no devices found/,{reason:`no_devices`,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`}],[/device (?:'[^']*' )?not found/,{reason:`device_not_found`,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0}],[/adb server version \(\d+\) doesn't match this client/,{reason:`server_version_mismatch`,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0}],[/transport error|connection reset|broken pipe|protocol fault/,{reason:`connection_dropped`,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0}],[/install_failed_insufficient_storage/,{reason:`install_insufficient_storage`,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`},!0],[/install_failed_update_incompatible/,{reason:`install_update_incompatible`,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`},!0],[/install_failed_version_downgrade/,{reason:`install_version_downgrade`,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`},!0],[/install_failed_\w+|install_parse_failed_\w+/,{reason:`install_failed`,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`},!0]],a=Object.freeze({reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`});function o(e,t=``){let n=e.toLowerCase(),r=t.toLowerCase();for(let[e,t,a]of i)if(e.test(n)||a&&e.test(r))return t}function s(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return e;let n=l(e);return n&&(e.details={...e.details,adbFailure:n.reason,...typeof e.details?.hint==`string`?{}:{hint:n.hint},...n.retriable!==void 0&&e.details?.retriable===void 0?{retriable:n.retriable}:{}}),e}function c(e){if(!n(e))return e;let t=e.details?.hint;if(typeof t==`string`&&t!==a.hint)return e;let r=s(e);return r.details={...r.details,hint:`The helper install timed out — some OEM builds (ColorOS is one) hold the first install of each package behind a system install-confirmation dialog and adb waits for it. Check the device screen, confirm any pending install prompt, then retry; if none is showing, run adb kill-server && adb start-server and retry.`},r}function l(e){return typeof e.details?.timeoutMs==`number`?a:o(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function u(e,n,r){let i=n.exitCode===0?{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,...r}:{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,processExitError:!0,...r};return s(new t(`COMMAND_FAILED`,e,i))}function d(e){return async(...t)=>{try{return await e(...t)}catch(e){throw s(e)}}}function f(e,n,r){let i=o(n.stderr,n.stdout);return new t(`COMMAND_FAILED`,e,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,processExitError:!0,hint:i?.hint??r,...i?{adbFailure:i.reason}:{},...i?.retriable===void 0?{}:{retriable:i.retriable}})}function p(e){return n(e)&&(e.details={...e.details,adbFailure:a.reason,...typeof e.details?.hint==`string`?{}:{hint:a.hint}}),e}export{p as a,d as c,s as i,u as n,c as o,f as r,o as s,r as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{rr as t}from"./sdk-batch.js";import{f as n,g as r,o as i,x as a,y as o}from"./owner-identity.js";import{g as s}from"./exec.js";import"./command.js";import"./process.js";import c from"node:path";import l from"node:crypto";var u=e({agentBrowserChromeLaunchMarker:()=>d,appendAgentDeviceChromeArgs:()=>f,inspectManagedAgentBrowserProcesses:()=>_,matchAgentBrowserChromeProcess:()=>p,recordManagedAgentBrowserProcesses:()=>v,summarizeAgentBrowserProcesses:()=>m,summarizeManagedAgentBrowserProcesses:()=>g});function d(e){let t=l.createHash(`sha256`);return t.update(c.resolve(e.stateDir)),t.update(`\0`),t.update(c.resolve(e.installDir)),`--agent-device-managed-web=${t.digest(`hex`).slice(0,16)}`}function f(e,t){let n=d(t),r=e?.trim();return r?x(r).includes(n)?r:`${r},${n}`:n}function p(e,t){if(!(e.pid===n()||!S(e.command))){if(e.command.includes(d(t)))return{process:e,reason:`launch-marker`};if(w(t).some(t=>T(e,t)))return{process:e,reason:`managed-browser-home`}}}function m(e,t){return b(e,e=>p(e,t))}function h(e,t){return p(e,t)??C(e,t)}function g(e,t){return b(e,e=>h(e,t))}async function _(e){return m(await y(),e)}async function v(e,t){let n=await y(),r=g(n,e),s=i(r.pids,n),c={count:s.length,pids:s.map(({pid:e})=>e),processes:s.map(t=>({process:t,reason:h(t,e)?.reason??`descendant`}))},l=c.processes.flatMap(({process:e})=>{let t=a(e.pid),n=o(e.pid);return t&&n?[{pid:e.pid,startTime:t,command:n,purpose:`managed-web-browser`}]:[]});return l.length>0&&t.replace({kind:`daemon`},l),c}async function y(){return await s(async()=>await r({timeoutMs:1500}))}function b(e,t){let n=e.flatMap(e=>{let n=t(e);return n?[n]:[]});return{count:n.length,pids:n.map(e=>e.process.pid),processes:n}}function x(e){return e.split(/[,\n]/).map(e=>e.trim()).filter(Boolean)}function S(e){return/\b(?:Google Chrome for Testing|Chrome for Testing|Chromium|chrome|chrome\.exe|chromium|chromium-browser|headless_shell)\b/i.test(e)}function C(e,t){if(e.pid===n()||S(e.command))return;let r=E(e.command),i=E(c.resolve(t.installDir));return r.includes(`${i}/`)?{process:e,reason:`agent-browser-daemon`}:void 0}function w(e){return t([c.join(e.homeDir,`.agent-browser`,`browsers`),c.join(e.runtimeHomeDir,`.agent-browser`,`browsers`)])}function T(e,t){let n=E(e.command),r=`${E(c.resolve(t)).replace(/\/+$/,``)}/`;return n.includes(r)}function E(e){return e.replaceAll(`\\`,`/`)}export{v as i,f as n,_ as r,u as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{rr as t}from"./sdk-batch.js";import{f as n,g as r,o as i,x as a,y as o}from"./owner-identity.js";import{_ as s}from"./exec.js";import"./command.js";import"./process.js";import c from"node:path";import l from"node:crypto";var u=e({agentBrowserChromeLaunchMarker:()=>d,appendAgentDeviceChromeArgs:()=>f,inspectManagedAgentBrowserProcesses:()=>_,matchAgentBrowserChromeProcess:()=>p,recordManagedAgentBrowserProcesses:()=>v,summarizeAgentBrowserProcesses:()=>m,summarizeManagedAgentBrowserProcesses:()=>g});function d(e){let t=l.createHash(`sha256`);return t.update(c.resolve(e.stateDir)),t.update(`\0`),t.update(c.resolve(e.installDir)),`--agent-device-managed-web=${t.digest(`hex`).slice(0,16)}`}function f(e,t){let n=d(t),r=e?.trim();return r?x(r).includes(n)?r:`${r},${n}`:n}function p(e,t){if(!(e.pid===n()||!S(e.command))){if(e.command.includes(d(t)))return{process:e,reason:`launch-marker`};if(w(t).some(t=>T(e,t)))return{process:e,reason:`managed-browser-home`}}}function m(e,t){return b(e,e=>p(e,t))}function h(e,t){return p(e,t)??C(e,t)}function g(e,t){return b(e,e=>h(e,t))}async function _(e){return m(await y(),e)}async function v(e,t){let n=await y(),r=g(n,e),s=i(r.pids,n),c={count:s.length,pids:s.map(({pid:e})=>e),processes:s.map(t=>({process:t,reason:h(t,e)?.reason??`descendant`}))},l=c.processes.flatMap(({process:e})=>{let t=a(e.pid),n=o(e.pid);return t&&n?[{pid:e.pid,startTime:t,command:n,purpose:`managed-web-browser`}]:[]});return l.length>0&&t.replace({kind:`daemon`},l),c}async function y(){return await s(async()=>await r({timeoutMs:1500}))}function b(e,t){let n=e.flatMap(e=>{let n=t(e);return n?[n]:[]});return{count:n.length,pids:n.map(e=>e.process.pid),processes:n}}function x(e){return e.split(/[,\n]/).map(e=>e.trim()).filter(Boolean)}function S(e){return/\b(?:Google Chrome for Testing|Chrome for Testing|Chromium|chrome|chrome\.exe|chromium|chromium-browser|headless_shell)\b/i.test(e)}function C(e,t){if(e.pid===n()||S(e.command))return;let r=E(e.command),i=E(c.resolve(t.installDir));return r.includes(`${i}/`)?{process:e,reason:`agent-browser-daemon`}:void 0}function w(e){return t([c.join(e.homeDir,`.agent-browser`,`browsers`),c.join(e.runtimeHomeDir,`.agent-browser`,`browsers`)])}function T(e,t){let n=E(e.command),r=`${E(c.resolve(t)).replace(/\/+$/,``)}/`;return n.includes(r)}function E(e){return e.replaceAll(`\\`,`/`)}export{v as i,f as n,_ as r,u as t};
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime.js";import{B as t,C as n,L as r,a as i,o as a}from"./sdk-contracts.js";import"./capture.js";import{n as o}from"./snapshot-capture-annotations.js";import{C as s,D as c,S as l,T as u,b as d,g as f,h as p,w as m,x as h,y as g}from"./sdk-batch-runner.js";import{n as _}from"./snapshot-diagnostics.js";import{c as v,m as y,p as ee,s as te}from"./sdk-device.js";import{f as ne,i as b}from"./lease-scope.js";import{tn as x,w as S}from"./sdk-batch.js";import{n as C,t as w}from"./catalog.js";import{T as re,i as ie,m as ae,w as oe}from"./registry.js";import{c as T,n as se,r as ce}from"./diagnostics.js";import{t as E}from"./command-metadata.js";import"./diagnostics2.js";import{a as le,c as ue,i as de,l as fe,n as pe,o as me,r as he,s as ge,t as _e}from"./daemon-client-lifecycle.js";import{n as D}from"./config.js";import{r as ve}from"./session-paths.js";import{n as ye,t as be}from"./client-metro.js";import{t as xe}from"./screenshot-result.js";import O from"node:path";import k from"node:fs";function A(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function j(e,t,n){return{deviceId:t,deviceName:n,...y(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function M(e,t){let n=h(e,`bundleId`),r=h(e,`package`);return{app:u(e,`app`),appPath:u(e,`appPath`),platform:m(e,`platform`),appId:n??r,bundleId:n,package:r,identifiers:A({session:t,bundleId:n,packageName:r})}}function Se(e,t){let r=h(e,`bundleId`),i=h(e,`packageName`),a=r??i??h(e,`appId`),o=h(e,`launchTarget`)??i??r??a;if(!o)throw new n(`COMMAND_FAILED`,`Daemon response is missing "launchTarget".`,{response:e});return{appName:h(e,`appName`),appId:a,bundleId:r,packageName:i,launchTarget:o,installablePath:h(e,`installablePath`),archivePath:h(e,`archivePath`),materializationId:h(e,`materializationId`),materializationExpiresAt:h(e,`materializationExpiresAt`),identifiers:A({session:t,bundleId:r,packageName:i,appId:a})}}function Ce(e){return{released:e.released===!0,materializationId:u(e,`materializationId`),identifiers:{}}}function N(e){let{record:t,platform:n,id:r,name:i,target:a}=F(e,`name`),o=P(t);return{platform:n,target:a,kind:l(t,`kind`),id:r,name:i,booted:typeof t.booted==`boolean`?t.booted:void 0,...v(n)&&o?{appleOs:o}:{},identifiers:j(n,r,i),...we(t),...I(n,r)}}function we(e){let t=e.claimedBy;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r=n.session,i=n.workspace;return typeof r!=`string`||typeof i!=`string`?{}:{claimedBy:{session:r,workspace:i}}}function Te(e){let{record:t,platform:n,id:r,name:i,target:a}=F(e,`name`),o=u(t,`device`),c=P(t),l={session:i,...j(n,r,o)};return{name:i,address:h(t,`address`),createdAt:s(t,`createdAt`),sessionStateDir:h(t,`sessionStateDir`),runnerLogPath:h(t,`runnerLogPath`),device:{platform:n,target:a,id:r,name:o,...c?{appleOs:c}:{},identifiers:l,...I(n,r,{simulatorSetPath:d(t,`ios_simulator_device_set`)})},identifiers:l}}function P(e){let t=e.appleOs;return te(t)?t:void 0}function F(e,t){let n=p(e);return{record:n,platform:m(n,`platform`),id:u(n,`id`),name:u(n,t),target:g(n,`target`)}}function I(e,t,n={}){if(e===`ios`)return{ios:{udid:t,...n.simulatorSetPath===void 0?{}:{simulatorSetPath:n.simulatorSetPath}}};if(!y(e))return{};let r=n.serial??t;return e===`android`?{android:{serial:r}}:e===`harmonyos`?{harmonyos:{serial:r}}:{vega:{serial:r}}}function Ee(e){if(!f(e))return;let t=e.platform,n=h(e,`metroHost`),r=typeof e.metroPort==`number`?e.metroPort:void 0,i=h(e,`bundleUrl`),o=h(e,`launchUrl`);return{platform:a(t)?t:void 0,metroHost:n,metroPort:r,bundleUrl:i,launchUrl:o}}function De(e){let t=e.platform,n=h(e,`id`),r=h(e,`device`);if(!ee(t)||!n||!r)return;let i=g(e,`target`),a=y(t)?h(e,`serial`)??n:void 0;return{platform:t,target:i,id:n,name:r,identifiers:{...j(t,n,r),...a?{serial:a}:{}},...I(t,t===`ios`?h(e,`device_udid`)??n:n,{simulatorSetPath:d(e,`ios_simulator_device_set`),serial:a})}}const Oe=[`explicit-selector`,`existing-session`,`single-booted-local`,`single-bootable-local`,`single-app-installed-local`,`preferred-local`,`single-provider-device`],ke=[`session`,`local`,`provider`];function Ae(e){if(!f(e))return;let{reason:t,source:n,candidateCount:r,bootOccurred:i}=e;if(!(!Oe.includes(t)||!ke.includes(n)||typeof r!=`number`||!Number.isInteger(r)||r<0||typeof i!=`boolean`))return{reason:t,source:n,candidateCount:r,bootOccurred:i}}function je(e){if(f(e)&&typeof e.durationMs==`number`&&typeof e.measuredAt==`string`&&typeof e.method==`string`)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:h(e,`appTarget`),appBundleId:h(e,`appBundleId`)}}function L(e){if(!f(e)||typeof e.success!=`boolean`||typeof e.exitCode!=`number`||typeof e.stdout!=`string`||typeof e.stderr!=`string`)return;let t=R(e.error);return{success:e.success,exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr,...t?{error:t}:{}}}const Me=[`hint`,`diagnosticId`,`logPath`,`supportedOn`];function R(e){if(!f(e)||typeof e.code!=`string`||typeof e.message!=`string`)return;let t={code:e.code,message:e.message};Object.assign(t,Ne(e.cause));for(let n of Me){let r=e[n];typeof r==`string`&&(t[n]=r)}return f(e.details)&&(t.details=e.details),typeof e.retriable==`boolean`&&(t.retriable=e.retriable),t}function Ne(e){let n=t(e);return n?{cause:n}:void 0}function Pe(e){let t=R(e.initialSnapshotError);return{...e.snapshot&&typeof e.snapshot==`object`?{snapshot:e.snapshot}:{},...t?{initialSnapshotError:t}:{}}}function Fe(e){return Array.isArray(e)?e:[]}function Ie(e){let t=b(e);return c({requestId:e.requestId,cwd:e.cwd,sessionExplicit:e.session!==void 0,debug:e.debug,includeCost:e.cost,responseLevel:e.responseLevel,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform,...ne(t),sessionIsolation:e.sessionIsolation,installSource:e.installSource,retainMaterializedPaths:e.retainMaterializedPaths,materializedPathRetentionMs:e.materializedPathRetentionMs,materializationId:e.materializationId})}function z(e){return e??`default`}const B={...ie(),batch:ae(Le)};async function Le(e,t,r){let i=B[e];if(!i)throw Error(`Missing daemon writer for batch command: ${e}`);let a=E(e);if(!a)throw Error(`Missing command metadata for batch command: ${e}`);try{return await V(i,a,a.readInput(t))}catch(t){let i=t instanceof Error?t.message:String(t);throw new n(`INVALID_ARGS`,`Batch step ${r} ${e} input is invalid: ${i}`,void 0,t)}}async function Re(e,t){let n=B[e];if(!n)throw Error(`Missing daemon writer for command: ${e}`);return await V(n,E(e),t)}async function V(e,t,n){let r=await e(n);return{...r,...t?{metadataFlags:re(t,r.options)}:{}}}async function H(e,t={}){let n=e.meta?.requestId??se(),r=!!(e.meta?.debug||e.flags?.verbose),i=e.flags,{daemonAuthToken:a,...o}=i??{},s=i?{...e,flags:o}:e,c=ge(s,t.authToken??a),l=x(S(s.command),s),u=await T(`daemon_startup`,async()=>await de(c),{requestId:n,session:e.session}),d=u.info,f=await fe(s,d);Ke(s.command);let p=ze(s,f,d.token,n,r);return ce({level:`info`,phase:`daemon_request_prepare`,data:{requestId:n,command:s.command,session:s.session}}),await Ue(s,u,c,async()=>Ge(We(await T(`daemon_request`,async()=>await ue(d,p,c.transportPreference,c.paths,l,t.onProgress?{onProgress:t.onProgress}:void 0),{requestId:n,command:e.command}),c),s,c))}function ze(e,t,n,r,i){return{...e,positionals:t.positionals,flags:t.flags,token:n,meta:Be(e,t,r,i)}}function Be(e,t,n,r){let i=e.meta??{};return{...i,requestId:n,debug:r,...Ve(i,e.flags),...He(t)}}function Ve(e,t){return{includeCost:e.includeCost,cwd:e.cwd,sessionExplicit:e.sessionExplicit,tenantId:e.tenantId??t?.tenant,runId:e.runId??t?.runId,leaseId:e.leaseId??t?.leaseId,sessionIsolation:e.sessionIsolation??t?.sessionIsolation,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform}}function He(e){return{...e.uploadedArtifactId?{uploadedArtifactId:e.uploadedArtifactId}:{},...e.clientArtifactPaths?{clientArtifactPaths:e.clientArtifactPaths}:{},...e.installSource?{installSource:e.installSource}:{}}}async function Ue(e,t,r,i){let a,o=!1,s;try{a=await i()}catch(e){o=!0,s=e}let c=await he(e,t,r,a);if(o)throw s;if(!c)throw new n(`COMMAND_FAILED`,`Daemon request produced no response after cleanup`);return c}function We(e,t){return e.ok||!t.ownedStateDir||!me(e)?e:pe(e,t.paths.baseDir)}function Ge(e,t,n){return!e.ok||!le(t,e)?e:_e(e,n.ownedStateDir?n.paths.baseDir:void 0)}function Ke(e){!qe(e)||process.stderr.isTTY!==!0||process.env.CI||process.stderr.write(e===C.reinstall?`Reinstalling...
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t,R as n,V as r,a as i,o as a}from"./sdk-contracts.js";import"./capture.js";import{n as o}from"./snapshot-capture-annotations.js";import{C as s,D as c,S as l,T as u,b as d,g as f,h as p,w as m,x as h,y as g}from"./sdk-batch-runner.js";import{n as ee}from"./snapshot-diagnostics.js";import{c as _,m as v,p as te,s as ne}from"./sdk-device.js";import{f as re,i as y}from"./lease-scope.js";import{tn as b,w as x}from"./sdk-batch.js";import{n as S,t as C}from"./catalog.js";import{T as ie,i as ae,m as oe,w as se}from"./registry.js";import{n as ce}from"./success-text.js";import{c as w,n as le,r as ue}from"./diagnostics.js";import{t as T}from"./command-metadata.js";import"./diagnostics2.js";import{a as de,c as fe,i as pe,l as me,n as he,o as ge,r as _e,s as ve,t as ye}from"./daemon-client-lifecycle.js";import{t as E}from"./daemon-resolution.js";import{r as be}from"./session-paths.js";import{n as xe,t as Se}from"./client-metro.js";import{t as D}from"./screenshot-result.js";import O from"node:path";import k from"node:fs";function A(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function j(e,t,n){return{deviceId:t,deviceName:n,...v(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function M(e,t){let n=h(e,`bundleId`),r=h(e,`package`);return{app:u(e,`app`),appPath:u(e,`appPath`),platform:m(e,`platform`),appId:n??r,bundleId:n,package:r,identifiers:A({session:t,bundleId:n,packageName:r})}}function Ce(e,n){let r=h(e,`bundleId`),i=h(e,`packageName`),a=r??i??h(e,`appId`),o=h(e,`launchTarget`)??i??r??a;if(!o)throw new t(`COMMAND_FAILED`,`Daemon response is missing "launchTarget".`,{response:e});return{appName:h(e,`appName`),appId:a,bundleId:r,packageName:i,launchTarget:o,installablePath:h(e,`installablePath`),archivePath:h(e,`archivePath`),materializationId:h(e,`materializationId`),materializationExpiresAt:h(e,`materializationExpiresAt`),identifiers:A({session:n,bundleId:r,packageName:i,appId:a})}}function we(e){return{released:e.released===!0,materializationId:u(e,`materializationId`),identifiers:{}}}function N(e){let{record:t,platform:n,id:r,name:i,target:a}=F(e,`name`),o=P(t);return{platform:n,target:a,kind:l(t,`kind`),id:r,name:i,booted:typeof t.booted==`boolean`?t.booted:void 0,..._(n)&&o?{appleOs:o}:{},identifiers:j(n,r,i),...Te(t),...I(n,r)}}function Te(e){let t=e.claimedBy;if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r=n.session,i=n.workspace;return typeof r!=`string`||typeof i!=`string`?{}:{claimedBy:{session:r,workspace:i}}}function Ee(e){let{record:t,platform:n,id:r,name:i,target:a}=F(e,`name`),o=u(t,`device`),c=P(t),l={session:i,...j(n,r,o)};return{name:i,address:h(t,`address`),createdAt:s(t,`createdAt`),sessionStateDir:h(t,`sessionStateDir`),runnerLogPath:h(t,`runnerLogPath`),device:{platform:n,target:a,id:r,name:o,...c?{appleOs:c}:{},identifiers:l,...I(n,r,{simulatorSetPath:d(t,`ios_simulator_device_set`)})},identifiers:l}}function P(e){let t=e.appleOs;return ne(t)?t:void 0}function F(e,t){let n=p(e);return{record:n,platform:m(n,`platform`),id:u(n,`id`),name:u(n,t),target:g(n,`target`)}}function I(e,t,n={}){if(e===`ios`)return{ios:{udid:t,...n.simulatorSetPath===void 0?{}:{simulatorSetPath:n.simulatorSetPath}}};if(!v(e))return{};let r=n.serial??t;return e===`android`?{android:{serial:r}}:e===`harmonyos`?{harmonyos:{serial:r}}:{vega:{serial:r}}}function De(e){if(!f(e))return;let t=e.platform,n=h(e,`metroHost`),r=typeof e.metroPort==`number`?e.metroPort:void 0,i=h(e,`bundleUrl`),o=h(e,`launchUrl`);return{platform:a(t)?t:void 0,metroHost:n,metroPort:r,bundleUrl:i,launchUrl:o}}function Oe(e){let t=e.platform,n=h(e,`id`),r=h(e,`device`);if(!te(t)||!n||!r)return;let i=g(e,`target`),a=v(t)?h(e,`serial`)??n:void 0;return{platform:t,target:i,id:n,name:r,identifiers:{...j(t,n,r),...a?{serial:a}:{}},...I(t,t===`ios`?h(e,`device_udid`)??n:n,{simulatorSetPath:d(e,`ios_simulator_device_set`),serial:a})}}const ke=[`explicit-selector`,`existing-session`,`single-booted-local`,`single-bootable-local`,`single-app-installed-local`,`preferred-local`,`single-provider-device`],Ae=[`session`,`local`,`provider`];function je(e){if(!f(e))return;let{reason:t,source:n,candidateCount:r,bootOccurred:i}=e;if(!(!ke.includes(t)||!Ae.includes(n)||typeof r!=`number`||!Number.isInteger(r)||r<0||typeof i!=`boolean`))return{reason:t,source:n,candidateCount:r,bootOccurred:i}}function Me(e){if(f(e)&&typeof e.durationMs==`number`&&typeof e.measuredAt==`string`&&typeof e.method==`string`)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:h(e,`appTarget`),appBundleId:h(e,`appBundleId`)}}function L(e){if(!f(e)||typeof e.success!=`boolean`||typeof e.exitCode!=`number`||typeof e.stdout!=`string`||typeof e.stderr!=`string`)return;let t=R(e.error);return{success:e.success,exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr,...t?{error:t}:{}}}const Ne=[`hint`,`diagnosticId`,`logPath`,`supportedOn`];function R(e){if(!f(e)||typeof e.code!=`string`||typeof e.message!=`string`)return;let t={code:e.code,message:e.message};Object.assign(t,Pe(e.cause));for(let n of Ne){let r=e[n];typeof r==`string`&&(t[n]=r)}return f(e.details)&&(t.details=e.details),typeof e.retriable==`boolean`&&(t.retriable=e.retriable),t}function Pe(e){let t=r(e);return t?{cause:t}:void 0}function Fe(e){let t=R(e.initialSnapshotError);return{...e.snapshot&&typeof e.snapshot==`object`?{snapshot:e.snapshot}:{},...t?{initialSnapshotError:t}:{}}}function Ie(e){return Array.isArray(e)?e:[]}function Le(e){let t=y(e);return c({requestId:e.requestId,cwd:e.cwd,sessionExplicit:e.session!==void 0,debug:e.debug,includeCost:e.cost,responseLevel:e.responseLevel,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform,...re(t),sessionIsolation:e.sessionIsolation,installSource:e.installSource,retainMaterializedPaths:e.retainMaterializedPaths,materializedPathRetentionMs:e.materializedPathRetentionMs,materializationId:e.materializationId})}function z(e){return e??`default`}const B={...ae(),batch:oe(Re)};async function Re(e,n,r){let i=B[e];if(!i)throw Error(`Missing daemon writer for batch command: ${e}`);let a=T(e);if(!a)throw Error(`Missing command metadata for batch command: ${e}`);try{return await V(i,a,a.readInput(n))}catch(n){let i=n instanceof Error?n.message:String(n);throw new t(`INVALID_ARGS`,`Batch step ${r} ${e} input is invalid: ${i}`,void 0,n)}}async function ze(e,t){let n=B[e];if(!n)throw Error(`Missing daemon writer for command: ${e}`);return await V(n,T(e),t)}async function V(e,t,n){let r=await e(n);return{...r,...t?{metadataFlags:ie(t,r.options)}:{}}}async function H(e,t={}){let n=e.meta?.requestId??le(),r=!!(e.meta?.debug||e.flags?.verbose),i=e.flags,{daemonAuthToken:a,...o}=i??{},s=i?{...e,flags:o}:e,c=ve(s,t.authToken??a),l=b(x(s.command),s),u=await w(`daemon_startup`,async()=>await pe(c),{requestId:n,session:e.session}),d=u.info,f=await me(s,d);qe(s.command);let p=Be(s,f,d.token,n,r);return ue({level:`info`,phase:`daemon_request_prepare`,data:{requestId:n,command:s.command,session:s.session}}),await We(s,u,c,async()=>Ke(Ge(await w(`daemon_request`,async()=>await fe(d,p,c.transportPreference,c.paths,l,t.onProgress?{onProgress:t.onProgress}:void 0),{requestId:n,command:e.command}),c),s,c))}function Be(e,t,n,r,i){return{...e,positionals:t.positionals,flags:t.flags,token:n,meta:Ve(e,t,r,i)}}function Ve(e,t,n,r){let i=e.meta??{};return{...i,requestId:n,debug:r,...He(i,e.flags),...Ue(t)}}function He(e,t){return{includeCost:e.includeCost,cwd:e.cwd,sessionExplicit:e.sessionExplicit,tenantId:e.tenantId??t?.tenant,runId:e.runId??t?.runId,leaseId:e.leaseId??t?.leaseId,sessionIsolation:e.sessionIsolation??t?.sessionIsolation,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform}}function Ue(e){return{...e.uploadedArtifactId?{uploadedArtifactId:e.uploadedArtifactId}:{},...e.clientArtifactPaths?{clientArtifactPaths:e.clientArtifactPaths}:{},...e.installSource?{installSource:e.installSource}:{}}}async function We(e,n,r,i){let a,o=!1,s;try{a=await i()}catch(e){o=!0,s=e}let c=await _e(e,n,r,a);if(o)throw s;if(!c)throw new t(`COMMAND_FAILED`,`Daemon request produced no response after cleanup`);return c}function Ge(e,t){return e.ok||!t.ownedStateDir||!ge(e)?e:he(e,t.paths.baseDir)}function Ke(e,t,n){return!e.ok||!de(t,e)?e:ye(e,n.ownedStateDir?n.paths.baseDir:void 0)}function qe(e){!Je(e)||process.stderr.isTTY!==!0||process.env.CI||process.stderr.write(e===S.reinstall?`Reinstalling...
2
2
  `:`Installing...
3
- `)}function qe(e){return e===C.install||e===C.reinstall||e===w.installSource}function U(e,t){return O.join(e,`metro-sessions`,`${ve(t)}.json`)}function W(e){let t=U(e.stateDir,e.session);k.mkdirSync(O.dirname(t),{recursive:!0}),k.writeFileSync(t,`${JSON.stringify(e.hints,null,2)}\n`,`utf8`)}function Je(e){let t=U(e.stateDir,e.session),n;try{n=k.readFileSync(t,`utf8`)}catch{return}let r;try{r=JSON.parse(n)}catch{return}if(!r||typeof r!=`object`||Array.isArray(r))return;let i=r,a={};return typeof i.metroHost==`string`&&i.metroHost&&(a.metroHost=i.metroHost),typeof i.metroPort==`number`&&Number.isInteger(i.metroPort)&&(a.metroPort=i.metroPort),typeof i.bundleUrl==`string`&&i.bundleUrl&&(a.bundleUrl=i.bundleUrl),Object.keys(a).length>0?a:void 0}function G(e){k.rmSync(U(e.stateDir,e.session),{force:!0})}function Ye(e){let t=async(t,n)=>await e(w.humanControl,t,n);return{allocate:async t=>q(await e(w.leaseAllocate,[],{...t,leaseId:void 0})),heartbeat:async t=>q(await e(w.leaseHeartbeat,[],t)),release:async t=>{let n=await e(w.leaseRelease,[],t);return{released:n.released===!0,provider:f(n.provider)?n.provider:void 0}},humanControl:{list:async e=>{let r=await t([`list`],e);if(!Array.isArray(r.holds))throw new n(`COMMAND_FAILED`,`Daemon did not return human-control holds.`);return r.holds.map(K)},put:async(e,n={},r)=>K((await t([`put`,e,JSON.stringify(n)],r)).hold),remove:async(e,n)=>(await t([`remove`,e],n)).released===!0}}}function K(e){if(!f(e)||!f(e.scope)||e.state!==`active`&&e.state!==`activating`||typeof e.createdAt!=`number`||typeof e.updatedAt!=`number`)throw new n(`COMMAND_FAILED`,`Daemon returned an invalid human-control hold.`);return{id:u(e,`id`),scope:{backend:u(e.scope,`backend`),leaseProvider:h(e.scope,`leaseProvider`),deviceKey:u(e.scope,`deviceKey`)},state:e.state,reason:h(e,`reason`),createdAt:e.createdAt,updatedAt:e.updatedAt,...typeof e.expiresAt==`number`?{expiresAt:e.expiresAt}:{}}}function q(e){let t=e.lease;if(!f(t))throw Error(`Invalid lease response from daemon`);return{leaseId:u(t,`leaseId`),tenantId:u(t,`tenantId`),runId:u(t,`runId`),backend:u(t,`backend`),leaseProvider:h(t,`leaseProvider`),clientId:h(t,`clientId`),deviceKey:h(t,`deviceKey`),createdAt:typeof t.createdAt==`number`?t.createdAt:void 0,heartbeatAt:typeof t.heartbeatAt==`number`?t.heartbeatAt:void 0,expiresAt:typeof t.expiresAt==`number`?t.expiresAt:void 0}}var Xe=e({createAgentDeviceClient:()=>J});function J(e={},t={}){let a=t.transport??H,o=t=>i(t.responseLevel??e.responseLevel),s=async(t,n=[],i={},o,s)=>{let c=Q(e,i),l={session:z(c.session),command:t,positionals:n,...s?{input:s}:{},flags:oe(c,o),runtime:c.runtime,meta:Ie(c)},u=await a(l,{authToken:c.daemonAuthToken});return u.ok||r(u.error),u.data??{}},c=async(e={})=>{let t=await s(w.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(Te)},l=async(e,t={})=>{let n=await Re(e,t);return await s(n.command,n.positionals,n.options,n.metadataFlags,n.input)},d=(t={})=>z(Q(e,t).session);return{command:{wait:async e=>await l(`wait`,e),alert:async(e={})=>await l(`alert`,e),appState:async(e={})=>await l(`appstate`,e),back:async(e={})=>await l(`back`,e),home:async(e={})=>await l(`home`,e),orientation:async e=>await l(`orientation`,e),appSwitcher:async(e={})=>await l(`app-switcher`,e),keyboard:async(e={})=>await l(`keyboard`,e),clipboard:async e=>await l(`clipboard`,e),tvRemote:async e=>await l(`tv-remote`,e),reactNative:async e=>await l(`react-native`,e),doctor:async(e={})=>await l(`doctor`,e),prepare:async e=>await l(`prepare`,e),viewport:async e=>await l(`viewport`,e)},devices:{list:async(e={})=>{let t=await l(`devices`,e);return(Array.isArray(t.devices)?t.devices:[]).map(N)},capabilities:async(e={})=>{let t=await l(`capabilities`,e),n=Array.isArray(t.availableCommands)?t.availableCommands.filter(e=>typeof e==`string`):[];return{device:N(t.device),availableCommands:n}},boot:async(e={})=>await l(`boot`,e),shutdown:async(e={})=>await l(`shutdown`,e)},sessions:{list:async(e={})=>await c(e),stateDir:async(t={})=>{let n=Q(e,t);return D(n.stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir},close:async(t={})=>{let n=d(t);try{let e=await l(`close`,t);return{session:n,shutdown:L(e.shutdown),provider:Z(e.provider),savedScript:h(e,`savedScript`),identifiers:{session:n}}}finally{lt(e,t)}},saveScript:async(e={})=>{let t=await s(w.sessionSaveScript,e.path===void 0?[]:[e.path],e,{force:e.force}),r=t.actionCount;if(typeof r!=`number`||!Number.isInteger(r)||r<0)throw new n(`COMMAND_FAILED`,`Daemon returned an invalid saved-script action count.`);let i=u(t,`session`);return{session:i,savedScript:u(t,`savedScript`),actionCount:r,identifiers:{session:i}}},artifacts:async(e={})=>await l(`artifacts`,e)},apps:{install:async e=>M(await l(`install`,e),d(e)),reinstall:async e=>M(await l(`reinstall`,e),d(e)),installFromSource:async e=>Se(await l(`install-from-source`,e),d(e)),list:async(e={})=>{let t=await l(`apps`,e);return Array.isArray(t.apps)?t.apps.filter(e=>typeof e==`string`):[]},open:async t=>{let n=d(t),r=await l(`open`,t);ct({config:e,options:t,runtime:Q(e,t).runtime,sessionReused:r.sessionReused===!0});let i=De(r),a=h(r,`appBundleId`),o=a,s=Array.isArray(r.warnings)?r.warnings.filter(e=>typeof e==`string`):[];return{session:n,...s.length>0?{warnings:s}:{},sessionStateDir:h(r,`sessionStateDir`),runnerLogPath:h(r,`runnerLogPath`),requestLogPath:h(r,`requestLogPath`),eventLogPath:h(r,`eventLogPath`),appName:h(r,`appName`),appBundleId:a,appId:o,selection:Ae(r.selection),startup:je(r.startup),runtime:Ee(r.runtime),device:i,...Pe(r),identifiers:{session:n,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:o,appBundleId:a}}},close:async(e={})=>{let t=d(e),n=await l(`close`,e);return{session:t,closedApp:e.app,shutdown:L(n.shutdown),savedScript:h(n,`savedScript`),identifiers:{session:t}}},push:async e=>await l(`push`,e),triggerEvent:async e=>await l(`trigger-app-event`,e)},materializations:{release:async e=>Ce(await s(w.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:Ye(s),metro:{prepare:async t=>{let n=await be({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath});return at(e,n),n},reload:async(t={})=>await ye({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime??ot(e),timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{let t=d(e),n=await l(`snapshot`,e);return o(e)?n:rt(n,t)},screenshot:async(e={})=>{let t=d(e),n=await l(`screenshot`,e);return o(e)?n:xe(n,t)},diff:async e=>await l(`diff`,e)},interactions:{click:async e=>await l(`click`,e),press:async e=>await l(`press`,e),longPress:async e=>await l(`longpress`,e),hover:async e=>await l(`hover`,e),swipe:async e=>await l(`swipe`,e),pan:async e=>await l(`gesture`,Ze(e)),drag:async e=>await l(`gesture`,Qe(e)),fling:async e=>await l(`gesture`,Y(e)),swipeGesture:async e=>await l(`gesture`,$e(e)),focus:async e=>await l(`focus`,e),type:async e=>await l(`type`,e),fill:async e=>await l(`fill`,e),scroll:async e=>await l(`scroll`,e),pinch:async e=>await l(`gesture`,et(e)),rotateGesture:async e=>await l(`gesture`,tt(e)),transformGesture:async e=>await l(`gesture`,nt(e)),get:async e=>await l(`get`,e),is:async e=>await l(`is`,e),find:async e=>await l(`find`,e)},replay:{run:async e=>await l(`replay`,e),test:async e=>await l(`test`,e)},batch:{run:async e=>await l(`batch`,e)},observability:{perf:async e=>await l(`perf`,e),logs:async(e={})=>await l(`logs`,e),events:async(e={})=>await l(`events`,e),network:async(e={})=>await l(`network`,e),audio:async(e={})=>await l(`audio`,e)},debug:{symbols:async t=>{let{symbolicateCrashArtifact:n}=await import(`./debug-symbols-facade.js`);return n({cwd:t.cwd??e.cwd,...t})}},recording:{record:async e=>await l(`record`,e),trace:async e=>await l(`trace`,e)},settings:{update:async e=>await l(`settings`,e)}}}function Ze(e){let{x:t,y:n,dx:r,dy:i,...a}=e;return{...a,kind:`pan`,origin:{x:t,y:n},delta:{x:r,y:i}}}function Qe(e){return{...e,kind:`drag`}}function Y(e){let{x:t,y:n,...r}=e;return{...r,kind:`fling`,origin:{x:t,y:n}}}function $e(e){return{...e,kind:`swipe`}}function et(e){let{x:t,y:n,...r}=e;return X(t,n,`pinch`),{...r,kind:`pinch`,...t===void 0&&n===void 0?{}:{origin:{x:t,y:n}}}}function tt(e){let{x:t,y:n,...r}=e;return X(t,n,`rotate`),{...r,kind:`rotate`,...t===void 0&&n===void 0?{}:{origin:{x:t,y:n}}}}function nt(e){let{x:t,y:n,dx:r,dy:i,...a}=e;return{...a,kind:`transform`,origin:{x:t,y:n},delta:{x:r,y:i}}}function X(e,t,r){if(e===void 0!=(t===void 0))throw new n(`INVALID_ARGS`,`gesture ${r} center requires both x and y`)}function rt(e,t){let n=h(e,`appBundleId`);return{nodes:Fe(e.nodes),...typeof e.truncated==`boolean`?{truncated:e.truncated}:{},appName:h(e,`appName`),appBundleId:n,...it(e),identifiers:{session:t,appId:n,appBundleId:n}}}function it(e){let t=Z(e.visibility),n=Z(e.unchanged),r=_(e.snapshotDiagnostics);return{...t?{visibility:t}:{},...o(e),...n?{unchanged:n}:{},...r?{snapshotDiagnostics:r}:{},...typeof e.fallbackScreenshotPath==`string`?{fallbackScreenshotPath:e.fallbackScreenshotPath}:{},...typeof e.refsGeneration==`number`?{refsGeneration:e.refsGeneration}:{}}}function Z(e){return f(e)?e:void 0}function Q(e,t){return{...e,...t}}function $(e,t={}){let n=Q(e,t);return{stateDir:D(n.stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,session:z(n.session)}}function at(e,t){try{let n=new URL(t.statusUrl),r=Number.parseInt(n.port,10);if(!n.hostname||!Number.isInteger(r))return;let i=t.bridge?void 0:t.iosRuntime.bundleUrl??t.androidRuntime.bundleUrl;W({...$(e),hints:{metroHost:n.hostname,metroPort:r,bundleUrl:i}})}catch{}}function ot(e){try{return Je($(e))}catch{return}}function st(e){if(!e)return;let{metroHost:t,metroPort:n,bundleUrl:r}=e;if(t!==void 0||n!==void 0||r!==void 0)return{metroHost:t,metroPort:n,bundleUrl:r}}function ct(e){try{let t=$(e.config,e.options),n=st(e.runtime);if(n){W({...t,hints:n});return}e.sessionReused||G(t)}catch{}}function lt(e,t){try{G($(e,t))}catch{}}export{J as n,H as r,Xe as t};
3
+ `)}function Je(e){return e===S.install||e===S.reinstall||e===C.installSource}function U(e,t){return O.join(e,`metro-sessions`,`${be(t)}.json`)}function W(e){let t=U(e.stateDir,e.session);k.mkdirSync(O.dirname(t),{recursive:!0}),k.writeFileSync(t,`${JSON.stringify(e.hints,null,2)}\n`,`utf8`)}function Ye(e){let t=U(e.stateDir,e.session),n;try{n=k.readFileSync(t,`utf8`)}catch{return}let r;try{r=JSON.parse(n)}catch{return}if(!r||typeof r!=`object`||Array.isArray(r))return;let i=r,a={};return typeof i.metroHost==`string`&&i.metroHost&&(a.metroHost=i.metroHost),typeof i.metroPort==`number`&&Number.isInteger(i.metroPort)&&(a.metroPort=i.metroPort),typeof i.bundleUrl==`string`&&i.bundleUrl&&(a.bundleUrl=i.bundleUrl),Object.keys(a).length>0?a:void 0}function G(e){k.rmSync(U(e.stateDir,e.session),{force:!0})}function Xe(e){let n=async(t,n)=>await e(C.humanControl,t,n);return{allocate:async t=>q(await e(C.leaseAllocate,[],{...t,leaseId:void 0})),heartbeat:async t=>q(await e(C.leaseHeartbeat,[],t)),release:async t=>{let n=await e(C.leaseRelease,[],t);return{released:n.released===!0,provider:f(n.provider)?n.provider:void 0}},humanControl:{list:async e=>{let r=await n([`list`],e);if(!Array.isArray(r.holds))throw new t(`COMMAND_FAILED`,`Daemon did not return human-control holds.`);return r.holds.map(K)},put:async(e,t={},r)=>K((await n([`put`,e,JSON.stringify(t)],r)).hold),remove:async(e,t)=>(await n([`remove`,e],t)).released===!0}}}function K(e){if(!f(e)||!f(e.scope)||e.state!==`active`&&e.state!==`activating`||typeof e.createdAt!=`number`||typeof e.updatedAt!=`number`)throw new t(`COMMAND_FAILED`,`Daemon returned an invalid human-control hold.`);return{id:u(e,`id`),scope:{backend:u(e.scope,`backend`),leaseProvider:h(e.scope,`leaseProvider`),deviceKey:u(e.scope,`deviceKey`)},state:e.state,reason:h(e,`reason`),createdAt:e.createdAt,updatedAt:e.updatedAt,...typeof e.expiresAt==`number`?{expiresAt:e.expiresAt}:{}}}function q(e){let t=e.lease;if(!f(t))throw Error(`Invalid lease response from daemon`);return{leaseId:u(t,`leaseId`),tenantId:u(t,`tenantId`),runId:u(t,`runId`),backend:u(t,`backend`),leaseProvider:h(t,`leaseProvider`),clientId:h(t,`clientId`),deviceKey:h(t,`deviceKey`),createdAt:typeof t.createdAt==`number`?t.createdAt:void 0,heartbeatAt:typeof t.heartbeatAt==`number`?t.heartbeatAt:void 0,expiresAt:typeof t.expiresAt==`number`?t.expiresAt:void 0}}var Ze=e({createAgentDeviceClient:()=>J});function J(e={},r={}){let a=r.transport??H,o=t=>i(t.responseLevel??e.responseLevel),s=async(t,r=[],i={},o,s)=>{let c=Q(e,i),l={session:z(c.session),command:t,positionals:r,...s?{input:s}:{},flags:se(c,o),runtime:c.runtime,meta:Le(c)},u=await a(l,{authToken:c.daemonAuthToken});return u.ok||n(u.error),u.data??{}},c=async(e={})=>{let t=await s(C.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(Ee)},l=async(e,t={})=>{let n=await ze(e,t);return await s(n.command,n.positionals,n.options,n.metadataFlags,n.input)},d=(t={})=>z(Q(e,t).session);return{command:{wait:async e=>await l(`wait`,e),alert:async(e={})=>await l(`alert`,e),appState:async(e={})=>await l(`appstate`,e),back:async(e={})=>await l(`back`,e),home:async(e={})=>await l(`home`,e),orientation:async e=>await l(`orientation`,e),appSwitcher:async(e={})=>await l(`app-switcher`,e),keyboard:async(e={})=>await l(`keyboard`,e),clipboard:async e=>await l(`clipboard`,e),tvRemote:async e=>await l(`tv-remote`,e),reactNative:async e=>await l(`react-native`,e),doctor:async(e={})=>await l(`doctor`,e),prepare:async e=>await l(`prepare`,e),viewport:async e=>await l(`viewport`,e)},devices:{list:async(e={})=>{let t=await l(`devices`,e);return(Array.isArray(t.devices)?t.devices:[]).map(N)},capabilities:async(e={})=>{let t=await l(`capabilities`,e),n=Array.isArray(t.availableCommands)?t.availableCommands.filter(e=>typeof e==`string`):[];return{device:N(t.device),availableCommands:n}},boot:async(e={})=>await l(`boot`,e),shutdown:async(e={})=>await l(`shutdown`,e)},sessions:{list:async(e={})=>await c(e),stateDir:async(t={})=>{let n=Q(e,t);return E(n.stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir},close:async(t={})=>{let n=d(t);try{let e=await l(`close`,t);return{session:n,shutdown:L(e.shutdown),provider:Z(e.provider),savedScript:h(e,`savedScript`),identifiers:{session:n}}}finally{ut(e,t)}},saveScript:async(e={})=>{let n=await s(C.sessionSaveScript,e.path===void 0?[]:[e.path],e,{force:e.force}),r=n.actionCount;if(typeof r!=`number`||!Number.isInteger(r)||r<0)throw new t(`COMMAND_FAILED`,`Daemon returned an invalid saved-script action count.`);let i=u(n,`session`);return{session:i,savedScript:u(n,`savedScript`),actionCount:r,identifiers:{session:i}}},artifacts:async(e={})=>await l(`artifacts`,e)},apps:{install:async e=>M(await l(`install`,e),d(e)),reinstall:async e=>M(await l(`reinstall`,e),d(e)),installFromSource:async e=>Ce(await l(`install-from-source`,e),d(e)),list:async(e={})=>{let t=await l(`apps`,e);return Array.isArray(t.apps)?t.apps.filter(e=>typeof e==`string`):[]},open:async t=>{let n=d(t),r=await l(`open`,t);lt({config:e,options:t,runtime:Q(e,t).runtime,sessionReused:r.sessionReused===!0});let i=Oe(r),a=h(r,`appBundleId`),o=a,s=ce(r);return{session:n,...s.length>0?{warnings:s}:{},sessionStateDir:h(r,`sessionStateDir`),runnerLogPath:h(r,`runnerLogPath`),requestLogPath:h(r,`requestLogPath`),eventLogPath:h(r,`eventLogPath`),appName:h(r,`appName`),appBundleId:a,appId:o,selection:je(r.selection),startup:Me(r.startup),runtime:De(r.runtime),device:i,...Fe(r),identifiers:{session:n,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:o,appBundleId:a}}},close:async(e={})=>{let t=d(e),n=await l(`close`,e);return{session:t,closedApp:e.app,shutdown:L(n.shutdown),savedScript:h(n,`savedScript`),identifiers:{session:t}}},push:async e=>await l(`push`,e),triggerEvent:async e=>await l(`trigger-app-event`,e)},materializations:{release:async e=>we(await s(C.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:Xe(s),metro:{prepare:async t=>{let n=await Se({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath});return ot(e,n),n},reload:async(t={})=>await xe({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime??st(e),timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{let t=d(e),n=await l(`snapshot`,e);return o(e)?n:it(n,t)},screenshot:async(e={})=>{let t=d(e),n=await l(`screenshot`,e);return o(e)?n:D(n,t)},diff:async e=>await l(`diff`,e)},interactions:{click:async e=>await l(`click`,e),press:async e=>await l(`press`,e),longPress:async e=>await l(`longpress`,e),hover:async e=>await l(`hover`,e),swipe:async e=>await l(`swipe`,e),pan:async e=>await l(`gesture`,Qe(e)),drag:async e=>await l(`gesture`,$e(e)),fling:async e=>await l(`gesture`,et(e)),swipeGesture:async e=>await l(`gesture`,tt(e)),focus:async e=>await l(`focus`,e),type:async e=>await l(`type`,e),fill:async e=>await l(`fill`,e),scroll:async e=>await l(`scroll`,e),pinch:async e=>await l(`gesture`,Y(e)),rotateGesture:async e=>await l(`gesture`,nt(e)),transformGesture:async e=>await l(`gesture`,rt(e)),get:async e=>await l(`get`,e),is:async e=>await l(`is`,e),find:async e=>await l(`find`,e)},replay:{run:async e=>await l(`replay`,e),test:async e=>await l(`test`,e)},batch:{run:async e=>await l(`batch`,e)},observability:{perf:async e=>await l(`perf`,e),logs:async(e={})=>await l(`logs`,e),events:async(e={})=>await l(`events`,e),network:async(e={})=>await l(`network`,e),audio:async(e={})=>await l(`audio`,e)},debug:{symbols:async t=>{let{symbolicateCrashArtifact:n}=await import(`./debug-symbols-facade.js`);return n({cwd:t.cwd??e.cwd,...t})}},recording:{record:async e=>await l(`record`,e),trace:async e=>await l(`trace`,e)},settings:{update:async e=>await l(`settings`,e)}}}function Qe(e){let{x:t,y:n,dx:r,dy:i,...a}=e;return{...a,kind:`pan`,origin:{x:t,y:n},delta:{x:r,y:i}}}function $e(e){return{...e,kind:`drag`}}function et(e){let{x:t,y:n,...r}=e;return{...r,kind:`fling`,origin:{x:t,y:n}}}function tt(e){return{...e,kind:`swipe`}}function Y(e){let{x:t,y:n,...r}=e;return X(t,n,`pinch`),{...r,kind:`pinch`,...t===void 0&&n===void 0?{}:{origin:{x:t,y:n}}}}function nt(e){let{x:t,y:n,...r}=e;return X(t,n,`rotate`),{...r,kind:`rotate`,...t===void 0&&n===void 0?{}:{origin:{x:t,y:n}}}}function rt(e){let{x:t,y:n,dx:r,dy:i,...a}=e;return{...a,kind:`transform`,origin:{x:t,y:n},delta:{x:r,y:i}}}function X(e,n,r){if(e===void 0!=(n===void 0))throw new t(`INVALID_ARGS`,`gesture ${r} center requires both x and y`)}function it(e,t){let n=h(e,`appBundleId`);return{nodes:Ie(e.nodes),...typeof e.truncated==`boolean`?{truncated:e.truncated}:{},appName:h(e,`appName`),appBundleId:n,...at(e),identifiers:{session:t,appId:n,appBundleId:n}}}function at(e){let t=Z(e.visibility),n=Z(e.unchanged),r=ee(e.snapshotDiagnostics);return{...t?{visibility:t}:{},...o(e),...n?{unchanged:n}:{},...r?{snapshotDiagnostics:r}:{},...typeof e.fallbackScreenshotPath==`string`?{fallbackScreenshotPath:e.fallbackScreenshotPath}:{},...typeof e.refsGeneration==`number`?{refsGeneration:e.refsGeneration}:{}}}function Z(e){return f(e)?e:void 0}function Q(e,t){return{...e,...t}}function $(e,t={}){let n=Q(e,t);return{stateDir:E(n.stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,session:z(n.session)}}function ot(e,t){try{let n=new URL(t.statusUrl),r=Number.parseInt(n.port,10);if(!n.hostname||!Number.isInteger(r))return;let i=t.bridge?void 0:t.iosRuntime.bundleUrl??t.androidRuntime.bundleUrl;W({...$(e),hints:{metroHost:n.hostname,metroPort:r,bundleUrl:i}})}catch{}}function st(e){try{return Ye($(e))}catch{return}}function ct(e){if(!e)return;let{metroHost:t,metroPort:n,bundleUrl:r}=e;if(t!==void 0||n!==void 0||r!==void 0)return{metroHost:t,metroPort:n,bundleUrl:r}}function lt(e){try{let t=$(e.config,e.options),n=ct(e.runtime);if(n){W({...t,hints:n});return}e.sessionReused||G(t)}catch{}}function ut(e,t){try{G($(e,t))}catch{}}export{J as n,H as r,Ze as t};
package/dist/src/api.js CHANGED
@@ -1,11 +1,3 @@
1
- import{a as e,i as t,t as n}from"./rolldown-runtime.js";import{a as r,i,r as a}from"./ios-client.js";import{promises as o}from"fs";import s from"os";import c,{basename as l}from"path";import u,{createHash as d}from"crypto";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let m=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return m=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function h(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const g=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var _=class extends Error{},v=class e extends _{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new b({message:r,cause:g(n)});let a=n;return t===400?new S(t,a,r,i):t===401?new C(t,a,r,i):t===403?new w(t,a,r,i):t===404?new T(t,a,r,i):t===409?new E(t,a,r,i):t===422?new D(t,a,r,i):t===429?new O(t,a,r,i):t>=500?new k(t,a,r,i):new e(t,a,r,i)}},y=class extends v{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},b=class extends v{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},x=class extends b{constructor({message:e}={}){super({message:e??`Request timed out.`})}},S=class extends v{},C=class extends v{},w=class extends v{},T=class extends v{},E=class extends v{},D=class extends v{},O=class extends v{},k=class extends v{};const A=/^[a-z][a-z0-9+.-]*:/i,ee=e=>A.test(e);let j=e=>(j=Array.isArray,j(e)),M=j;function N(e){return typeof e==`object`?e??{}:{}}function P(e){if(!e)return!0;for(let t in e)return!1;return!0}function te(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const ne=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new _(`${e} must be an integer`);if(t<0)throw new _(`${e} must be a positive integer`);return t},re=e=>{try{return JSON.parse(e)}catch{return}},ie=e=>new Promise(t=>setTimeout(t,e)),F=`0.24.5`;function ae(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const oe=()=>{let e=ae();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":F,"X-Stainless-OS":le(Deno.build.os),"X-Stainless-Arch":ce(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":F,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":F,"X-Stainless-OS":le(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ce(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=se();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":F,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":F,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function se(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const ce=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,le=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let ue;const de=()=>ue??=oe();function fe(){if(typeof fetch<`u`)return r.fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Limrun({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pe(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function me(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return pe({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function he(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const ge=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function _e(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new _(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}const I={off:0,error:200,warn:300,info:400,debug:500},ve=(e,t,n)=>{if(e){if(te(I,e))return e;z(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(I))}`)}};function L(){}function R(e,t,n){return!t||I[e]>I[n]?L:t[e].bind(t)}const ye={error:L,warn:L,info:L,debug:L};let be=new WeakMap;function z(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return ye;let r=be.get(t);if(r&&r[0]===n)return r[1];let i={error:R(`error`,t,n),warn:R(`warn`,t,n),info:R(`info`,t,n),debug:R(`debug`,t,n)};return be.set(t,[n,i]),i}const B=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function xe(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return z(e).debug(`[${r}] response parsed`,B({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var V,Se=class e extends Promise{constructor(e,t,n=xe){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,V.set(this,void 0),f(this,V,e,`f`)}_thenUnwrap(t){return new e(p(this,V,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(p(this,V,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};V=new WeakMap;var H,Ce=class{constructor(e,t,n,r){H.set(this,void 0),f(this,H,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,H,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(H=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},we=class extends Se{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await xe(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},U=class extends Ce{constructor(e,t,n,r){super(e,t,n,r),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.getPaginatedItems();if(!(typeof this.options.query==`object`&&`endingBefore`in(this.options.query||{}))){let t=e[e.length-1]?.metadata.id;return t?{...this.options,query:{...N(this.options.query),startingAfter:t}}:null}let t=e[0]?.metadata.id;return t?{...this.options,query:{...N(this.options.query),endingBefore:t}}:null}};const Te=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function W(e,t,n){return Te(),new File(e,t??`unknown_file`,n)}function Ee(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const De=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Oe=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,ke=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Oe(e),Ae=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function je(e,t,n){if(Te(),e=await e,ke(e))return e instanceof File?e:W([await e.arrayBuffer()],e.name);if(Ae(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),W(await G(r),t,n)}let r=await G(e);if(t||=Ee(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return W(r,t,n)}async function G(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Oe(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(De(e))for await(let n of e)t.push(...await G(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Me(e)}`)}return t}function Me(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var K=class{constructor(e){this._client=e}};const Ne=Symbol(`brand.privateNullableHeaders`);function*Pe(e){if(!e)return;if(Ne in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():M(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=M(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Pe(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ne]:!0,values:t,nulls:n}};function Fe(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ie=Object.freeze(Object.create(null)),J=((e=Fe)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Ie)??Ie)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new _(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
2
- `)}\n${a}\n${t}`)}return a})(Fe);var Le=class extends K{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/android_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/android_instances`,U,{query:e,...t})}delete(e,t){return this._client.delete(J`/v1/android_instances/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(J`/v1/android_instances/${e}`,t)}},Re=class extends K{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/ios_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/ios_instances`,U,{query:e,...t})}delete(e,t){return this._client.delete(J`/v1/ios_instances/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(J`/v1/ios_instances/${e}`,t)}},ze=class extends K{list(e={},t){return this._client.get(`/v1/assets`,{query:e,...t})}delete(e,t){return this._client.delete(J`/v1/assets/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}get(e,t={},n){return this._client.get(J`/v1/assets/${e}`,{query:t,...n})}getOrCreate(e,t){return this._client.put(`/v1/assets`,{body:e,...t})}},Be=class extends ze{async getOrUpload(e,t){let n=await this.getOrCreate({name:e.name??l(e.path)},t),i=await o.readFile(e.path),a=d(`md5`).update(i).digest(`hex`);if(n.md5&&n.md5===a)return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,md5:n.md5};let s=await r.fetch(n.signedUploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":`application/octet-stream`},method:`PUT`,body:i});if(s.status!==200)throw Error(`Failed to upload asset: ${s.status} ${await s.text()}`);return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,md5:a}}},Ve=class extends K{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/xcode_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/xcode_instances`,U,{query:e,...t})}delete(e,t){return this._client.delete(J`/v1/xcode_instances/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(J`/v1/xcode_instances/${e}`,t)}},He=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function n(e){}function r(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:r=n,onError:o=n,onRetry:s=n,onComment:c,maxBufferSize:l}=e,u=[],d=0,f=!0,p,m=``,h=0,g,_=!1;function v(e){if(_)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(f&&(f=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),u.length===0){let t=b(e);t!==``&&(u.push(t),d=t.length),y();return}if(e.indexOf(`
3
- `)===-1&&e.indexOf(`\r`)===-1){u.push(e),d+=e.length,y();return}u.push(e);let t=u.join(``);u.length=0,d=0;let n=b(t);n!==``&&(u.push(n),d=n.length),y()}function y(){l!==void 0&&(d+m.length<=l||(_=!0,u.length=0,d=0,p=void 0,m=``,h=0,g=void 0,o(new t(`Buffered data exceeded max buffer size of ${l} characters`,{type:`max-buffer-size-exceeded`}))))}function b(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
4
- `,t);for(;n!==-1;){if(t===n){h>0&&r({id:p,event:g,data:m}),p=void 0,m=``,h=0,g=void 0,t=n+1,n=e.indexOf(`
5
- `,t);continue}let o=e.charCodeAt(t);if(i(e,t,o)){let i=e.charCodeAt(t+5)===32?t+6:t+5,a=e.slice(i,n);if(h===0&&e.charCodeAt(n+1)===10){r({id:p,event:g,data:a}),p=void 0,m=``,g=void 0,t=n+2,n=e.indexOf(`
6
- `,t);continue}m=h===0?a:`${m}
7
- ${a}`,h++}else a(e,t,o)?g=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0:x(e,t,n);t=n+1,n=e.indexOf(`
8
- `,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
9
- `,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;x(e,t,i),t=i+1,e.charCodeAt(t-1)===13&&e.charCodeAt(t)===10&&t++}return e.slice(t)}function x(e,t,n){if(t===n){C();return}let r=e.charCodeAt(t);if(i(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);m=h===0?i:`${m}
10
- ${i}`,h++;return}if(a(e,t,r)){g=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);p=r.includes(`\0`)?void 0:r;return}if(r===58){if(c){let r=e.slice(t,n);c(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let o=e.slice(t,n),s=o.indexOf(`:`);if(s===-1){S(o,``,o);return}let l=o.slice(0,s),u=o.charCodeAt(s+1)===32?2:1;S(l,o.slice(s+u),o)}function S(e,n,r){switch(e){case`event`:g=n||void 0;break;case`data`:m=h===0?n:`${m}
11
- ${n}`,h++;break;case`id`:p=n.includes(`\0`)?void 0:n;break;case`retry`:/^\d+$/.test(n)?s(parseInt(n,10)):o(new t(`Invalid \`retry\` value: "${n}"`,{type:`invalid-retry`,value:n,line:r}));break;default:o(new t(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:n,line:r}))}}function C(){h>0&&r({id:p,event:g,data:m}),p=void 0,m=``,h=0,g=void 0}function w(e={}){if(e.consume&&u.length>0){let e=u.join(``);x(e,0,e.length)}f=!0,p=void 0,m=``,h=0,g=void 0,u.length=0,d=0,_=!1}return{feed:v,reset:w}}function i(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function a(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}e.ParseError=t,e.createParser=r}));const Ue=e(n((e=>{Object.defineProperty(e,"__esModule",{value:!0});var n=t(`node:stream`),r=He();let i=`connecting`,a=`open`,o=`closed`,s=()=>{};function c(e,{getStream:t}){let n=typeof e==`string`||e instanceof URL?{url:e}:e,{onMessage:c,onComment:u=s,onConnect:d=s,onDisconnect:f=s,onScheduleReconnect:p=s}=n,{fetch:m,url:h,initialLastEventId:g}=l(n),_={...n.headers},v=[],y=c?[c]:[],b=e=>y.forEach(t=>t(e)),x=r.createParser({onEvent:N,onRetry:P,onComment:u}),S,C=h.toString(),w=new AbortController,T=g,E=2e3,D,O=o;return k(),{close:A,connect:k,[Symbol.iterator]:()=>{throw Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:ee,get lastEventId(){return T},get url(){return C},get readyState(){return O}};function k(){S||=(O=i,w=new AbortController,m(h,te()).then(M).catch(e=>{S=null,!(e.name===`AbortError`||e.type===`aborted`||w.signal.aborted)&&j()}))}function A(){O=o,w.abort(),x.reset(),clearTimeout(D),v.forEach(e=>e())}function ee(){let e=[],t=[];function n(){return new Promise(n=>{let r=t.shift();r?n({value:r,done:!1}):e.push(n)})}let r=function(n){let r=e.shift();r?r({value:n,done:!1}):t.push(n)};function i(){for(y.splice(y.indexOf(r),1);e.shift(););for(;t.shift(););}function a(){let t=e.shift();t&&(t({done:!0,value:void 0}),i())}return v.push(a),y.push(r),{next(){return O===o?this.return():n()},return(){return i(),Promise.resolve({done:!0,value:void 0})},throw(e){return i(),Promise.reject(e)},[Symbol.asyncIterator](){return this}}}function j(){p({delay:E}),!w.signal.aborted&&(O=i,D=setTimeout(k,E))}async function M(e){d(),x.reset();let{body:n,redirected:r,status:i}=e;if(i===204){f(),A();return}if(!n)throw Error(`Missing response body`);r&&(C=e.url);let o=t(n),s=new TextDecoder,c=o.getReader(),l=!0;O=a;do{let{done:e,value:t}=await c.read();t&&x.feed(s.decode(t,{stream:!e})),e&&(l=!1,S=null,x.reset(),j(),f())}while(l)}function N(e){typeof e.id==`string`&&(T=e.id),b(e)}function P(e){E=e}function te(){let{mode:e,credentials:t,body:r,method:i,redirect:a,referrer:o,referrerPolicy:s}=n;return{mode:e,credentials:t,body:r,method:i,redirect:a,referrer:o,referrerPolicy:s,headers:{Accept:`text/event-stream`,..._,...T?{"Last-Event-ID":T}:void 0},cache:`no-store`,signal:w.signal}}}function l(e){let t=e.fetch||globalThis.fetch;if(!u(t))throw Error(`No fetch implementation provided, and one was not found on the global object.`);if(typeof AbortController!=`function`)throw Error(`Missing AbortController implementation`);let{url:n,initialLastEventId:r}=e;if(typeof n!=`string`&&!(n instanceof URL))throw Error(`Invalid URL provided - must be string or URL instance`);if(typeof r!=`string`&&r!==void 0)throw Error(`Invalid initialLastEventId provided - must be string or undefined`);return{fetch:t,url:n,initialLastEventId:r}}function u(e){return typeof e==`function`}let d={getStream:p};function f(e){return c(e,d)}function p(e){if(`getReader`in e)return e;if(typeof e.pipe!=`function`||typeof e.on!=`function`)throw Error(`Invalid response body, expected a web or node.js stream`);if(typeof n.Readable.toWeb!=`function`)throw Error("Node.js 18 or higher required (`Readable.toWeb()` not defined)");return n.Readable.toWeb(n.Readable.from(e))}e.CLOSED=o,e.CONNECTING=i,e.OPEN=a,e.createEventSource=f}))(),1).createEventSource;var Y=class{constructor(){this.dataListeners=[],this.closeListeners=[],this.closed=!1}on(e,t){return e===`data`?this.dataListeners.push(t):e===`close`&&this.closeListeners.push(t),this}emit(e,t){if(e===`data`&&typeof t==`string`)for(let e of this.dataListeners)e(t);else if(e===`close`&&!this.closed){this.closed=!0;for(let e of this.closeListeners)e()}}},We=class{constructor(e,t){this.command=new Y,this.stdout=new Y,this.stderr=new Y,this.exitListeners=[],this.abortController=new AbortController,this.sseConnection=null,this.killed=!1,this.options=t,this.log=t.log??(()=>{}),this.resultPromise=e instanceof Promise?e.then(e=>this.run(e)):this.run(e)}then(e,t){return this.resultPromise.then(e,t)}catch(e){return this.resultPromise.catch(e)}finally(e){return this.resultPromise.finally(e)}on(e,t){return e===`exit`&&this.exitListeners.push(t),this}async kill(){if(this.killed=!0,this.abortController.abort(),this.sseConnection&&=(this.sseConnection.close(),null),!this.execId){this.log(`warn`,`Failed to cancel build: execId is not set`);return}try{await r.fetch(`${this.options.apiUrl}/exec/${this.execId}/cancel`,{method:`POST`,headers:{Authorization:`Bearer ${this.options.token}`}}),this.log(`info`,`Build cancelled`)}catch(e){this.log(`warn`,`Failed to cancel build: ${e}`)}}async run(e){let{log:t}=this,{apiUrl:n,token:i}=this.options,a;try{a=await r.fetch(`${n}/exec`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${i}`},body:JSON.stringify(e),signal:this.abortController.signal})}catch(e){if(this.killed){this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`);for(let e of this.exitListeners)e(-1);return{exitCode:-1,execId:``,status:`CANCELLED`}}throw e}if(!a.ok){let e=await a.text();throw Error(`exec failed: ${a.status} ${e}`)}let o=await a.json();this.execId=o.execId,t(`debug`,`Build started: ${this.execId}`);let s=`${n}/exec/${this.execId}/events`,c,l;try{c=await Promise.race([this.connectSSE(s),new Promise((e,t)=>{l=setTimeout(()=>t(Error(`SSE timeout`)),36e5)})])}catch{this.killed?(t(`debug`,`Build killed`),c=-1):(t(`warn`,`SSE completion timeout`),c=1)}finally{clearTimeout(l),this.sseConnection&&=(this.sseConnection.close(),null)}this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`);for(let e of this.exitListeners)e(c);let u=c===0?`SUCCEEDED`:c===-1?`CANCELLED`:`FAILED`,d={exitCode:c,execId:this.execId,status:u,...e.additionalMetadata??{}};return this.log(`debug`,`Build finished: ${d.status} (exit ${d.exitCode})`),d}connectSSE(e){return new Promise((t,n)=>{if(this.abortController.signal.aborted){n(Error(`killed`));return}try{let i=Ue({url:e,fetch:r.fetch,headers:{Authorization:`Bearer ${this.options.token}`},onMessage:e=>{let n=typeof e.data==`string`?e.data:String(e.data??``),r=e.event;if(r===`command`)this.command.emit(`data`,n);else if(r===`stdout`)this.stdout.emit(`data`,n);else if(r===`stderr`)this.stderr.emit(`data`,n);else if(r===`exitCode`){let e=parseInt(n,10);if(Number.isNaN(e)){this.log(`warn`,`SSE exitCode event has invalid data: ${n}`);return}this.log(`debug`,`Build completed via SSE: exitCode=${e}`),t(e)}},onDisconnect:()=>{this.killed||this.log(`warn`,`SSE disconnected`)}});this.sseConnection=i,this.abortController.signal.addEventListener(`abort`,()=>n(Error(`killed`)),{once:!0})}catch(e){this.killed||this.log(`warn`,`SSE setup failed: ${e}`),n(e)}})}};function Ge(e,t){return new We(e,t)}function Ke(e){let t=t=>{let n=[`none`,`error`,`warn`,`info`,`debug`];return n.indexOf(e)>=n.indexOf(t)};return(e,n)=>{if(!t(e))return;let r=`[XcodeInstance]`;e===`error`||e===`warn`?console[e](r,n):console.log(r,n)}}var qe=class extends Ve{async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=e.instance.status.token}else t=e.apiUrl,n=e.token;let o=Ke(e.logLevel??`info`),l=this._client;return{async sync(e,r){let l=c.resolve(e),d=`limsync-cache-${c.basename(l)}-${u.createHash(`sha1`).update(l).digest(`hex`).slice(0,8)}`,f=r?.basisCacheDir??c.join(s.tmpdir(),d),p={apiUrl:t,token:n,udid:d,install:r?.install??!0,ignoreFn:await a(e,{basisCacheDir:f,additional:e=>!!(e.startsWith(`build/`)||e.startsWith(`.build/`)||e.startsWith(`DerivedData/`)||e.startsWith(`Index.noindex/`)||e.startsWith(`ModuleCache.noindex/`)||e.startsWith(`.index-build/`)||e.startsWith(`.swiftpm/`)||e.startsWith(`Pods/`)||e.startsWith(`Carthage/Build/`)||e.includes(`/xcuserdata/`)||e.includes(`.dSYM/`)||r?.ignore?.(e))}),basisCacheDir:f,watch:r?.watch??!0,maxPatchBytes:r?.maxPatchBytes??4194304,launchMode:`ForegroundIfRunning`,log:o},m=await i(e,p);return m.stopWatching?{stopWatching:m.stopWatching}:{}},xcodebuild(e,r){let i={command:`xcodebuild`,...e&&{xcodebuild:e}};if(r?.upload){let e=r.upload.assetName;return Ge(l.assets.getOrCreate({name:e}).then(e=>(i.signedUploadUrl=e.signedUploadUrl,i.additionalMetadata={signedDownloadUrl:e.signedDownloadUrl},i)).catch(t=>{throw Error(`Failed to create upload URL for artifact '${e}': ${t instanceof Error?t.message:t}`)}),{apiUrl:t,token:n,log:o})}return Ge(i,{apiUrl:t,token:n,log:o})},async attachSimulator(e){let i,a;if(`status`in e){if(!e.status.apiUrl)throw Error(`Simulator instance not ready: apiUrl is not available`);i=e.status.apiUrl,a=e.status.token}else i=e.apiUrl,a=e.token;let o=await r.fetch(`${t}/simulator`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({apiUrl:i,token:a})});if(!o.ok){let e=await o.text();throw Error(`POST /simulator failed: ${o.status} ${e}`)}}}}};const X=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var Z,Je,Q,Ye,$=class{constructor({baseURL:e=X(`LIMRUN_BASE_URL`),apiKey:t=X(`LIM_API_KEY`)??null,...n}={}){Z.add(this),Q.set(this,void 0),this.androidInstances=new Le(this),this.assets=new Be(this),this.iosInstances=new Re(this),this.xcodeInstances=new qe(this);let r={apiKey:t,...n,baseURL:e||`https://api.limrun.com`};this.baseURL=r.baseURL,this.timeout=r.timeout??Je.DEFAULT_TIMEOUT,this.logger=r.logger??console;let i=`warn`;this.logLevel=i,this.logLevel=ve(r.logLevel,`ClientOptions.logLevel`,this)??ve(X(`LIMRUN_LOG`),`process.env['LIMRUN_LOG']`,this)??i,this.fetchOptions=r.fetchOptions,this.maxRetries=r.maxRetries??2,this.fetch=r.fetch??fe(),f(this,Q,ge,`f`),this._options=r,this.apiKey=t}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted`)}async authHeaders(e){if(this.apiKey!=null)return q([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return _e(e)}getUserAgent(){return`${this.constructor.name}/JS ${F}`}defaultIdempotencyKey(){return`stainless-node-retry-${m()}`}makeStatusError(e,t,n,r){return v.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,Z,`m`,Ye).call(this)&&n||this.baseURL,i=ee(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!P(a)||!P(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Se(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(z(this).debug(`[${c}] sending request`,B({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new y;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(g),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new y;let i=h(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return z(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),z(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,B({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw z(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),z(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,B({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new x:new b({cause:f})}let m=`[${c}${l}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await he(f.body),z(this).info(`${m} - ${e}`),z(this).debug(`[${c}] response error (${e})`,B({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;z(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>g(e).message),o=re(a),s=o?void 0:a;throw z(this).debug(`[${c}] response error (${i})`,B({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return z(this).info(m),z(this).debug(`[${c}] response start`,B({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new we(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ie(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ne(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=q([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...de()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=q([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:me(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,Q,`f`).call(this,{body:e,headers:n})}};Je=$,Q=new WeakMap,Z=new WeakSet,Ye=function(){return this.baseURL!==`https://api.limrun.com`},$.Limrun=Je,$.DEFAULT_TIMEOUT=3e5,$.LimrunError=_,$.APIError=v,$.APIConnectionError=b,$.APIConnectionTimeoutError=x,$.APIUserAbortError=y,$.NotFoundError=T,$.ConflictError=E,$.RateLimitError=O,$.BadRequestError=S,$.AuthenticationError=C,$.InternalServerError=k,$.PermissionDeniedError=w,$.UnprocessableEntityError=D,$.toFile=je,$.AndroidInstances=Le,$.Assets=Be,$.IosInstances=Re,$.XcodeInstances=qe;export{T as n,$ as t};
1
+ import{C as e,D as t,E as n,S as r,T as i,_ as a,a as o,b as s,c,d as l,f as u,g as d,h as f,i as p,l as m,m as h,o as g,p as ee,r as _,s as v,u as y,v as te,w as ne,x as b,y as re}from"./ios-client.js";import{promises as ie}from"fs";import"net";import ae from"os";import x,{basename as oe}from"path";import se,{createHash as ce}from"crypto";import"child_process";function S(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function C(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let w=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return w=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};const le=/^[a-z][a-z0-9+.-]*:/i,ue=e=>le.test(e);let T=e=>(T=Array.isArray,T(e)),E=T;function D(e){return typeof e==`object`?e??{}:{}}function de(e){if(!e)return!0;for(let t in e)return!1;return!0}function fe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const pe=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new b(`${e} must be an integer`);if(t<0)throw new b(`${e} must be a positive integer`);return t},me=e=>{try{return JSON.parse(e)}catch{return}},O=`0.49.3`;function he(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const ge=()=>{let e=he();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":O,"X-Stainless-OS":ye(Deno.build.os),"X-Stainless-Arch":ve(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":O,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":O,"X-Stainless-OS":ye(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ve(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=_e();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":O,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":O,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function _e(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const ve=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ye=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let be;const xe=()=>be??=ge();function Se(){if(typeof fetch<`u`)return l.fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Limrun({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ce(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function we(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ce({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function Te(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ee=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function De(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new b(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}const k={off:0,error:200,warn:300,info:400,debug:500},A=(e,t,n)=>{if(e){if(fe(k,e))return e;P(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(k))}`)}};function j(){}function M(e,t,n){return!t||k[e]>k[n]?j:t[e].bind(t)}const Oe={error:j,warn:j,info:j,debug:j};let N=new WeakMap;function P(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Oe;let r=N.get(t);if(r&&r[0]===n)return r[1];let i={error:M(`error`,t,n),warn:M(`warn`,t,n),info:M(`info`,t,n),debug:M(`debug`,t,n)};return N.set(t,[n,i]),i}const F=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function I(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return P(e).debug(`[${r}] response parsed`,F({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var L,ke=class e extends Promise{constructor(e,t,n=I){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,L.set(this,void 0),S(this,L,e,`f`)}_thenUnwrap(t){return new e(C(this,L,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(C(this,L,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};L=new WeakMap;var R,Ae=class{constructor(e,t,n,r){R.set(this,void 0),S(this,R,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,R,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(R=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},je=class extends ke{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await I(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},z=class extends Ae{constructor(e,t,n,r){super(e,t,n,r),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.getPaginatedItems();if(!(typeof this.options.query==`object`&&`endingBefore`in(this.options.query||{}))){let t=e[e.length-1]?.metadata.id;return t?{...this.options,query:{...D(this.options.query),startingAfter:t}}:null}let t=e[0]?.metadata.id;return t?{...this.options,query:{...D(this.options.query),endingBefore:t}}:null}};const Me=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function B(e,t,n){return Me(),new File(e,t??`unknown_file`,n)}function Ne(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Pe=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Fe=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ie=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Fe(e),Le=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Re(e,t,n){if(Me(),e=await e,Ie(e))return e instanceof File?e:B([await e.arrayBuffer()],e.name);if(Le(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),B(await V(r),t,n)}let r=await V(e);if(t||=Ne(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return B(r,t,n)}async function V(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Fe(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Pe(e))for await(let n of e)t.push(...await V(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${ze(e)}`)}return t}function ze(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var H=class{constructor(e){this._client=e}},Be=class extends H{get(e,t){return this._client.get(`/v1/analytics`,{query:e,...t})}getInstances(e,t){return this._client.get(`/v1/analytics/instances`,{query:e,...t})}};const Ve=Symbol(`brand.privateNullableHeaders`);function*He(e){if(!e)return;if(Ve in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():E(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=E(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const U=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of He(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ve]:!0,values:t,nulls:n}};function Ue(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const We=Object.freeze(Object.create(null)),W=((e=Ue)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??We)??We)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new b(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
2
+ `)}\n${a}\n${t}`)}return a})(Ue);var G=class extends H{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/gradle_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/gradle_instances`,z,{query:e,...t})}delete(e,t){return this._client.delete(W`/v1/gradle_instances/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(W`/v1/gradle_instances/${e}`,t)}},Ge=class extends H{create(e,t){return this._client.post(`/v1/scoped_tokens`,{body:e,...t})}},Ke=class extends H{list(e={},t){return this._client.get(`/v1/assets`,{query:e,...t})}delete(e,t){return this._client.delete(W`/v1/assets/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}get(e,t={},n){return this._client.get(W`/v1/assets/${e}`,{query:t,...n})}getOrCreate(e,t){return this._client.put(`/v1/assets`,{body:e,...t})}};function qe(e,t){if(!t)return{body:e};let n=0;return{body:new ReadableStream({pull(r){if(n>=e.length){r.close();return}let i=e.subarray(n,Math.min(n+262144,e.length));n+=i.length,r.enqueue(i),t(n,e.length)}}),duplex:`half`}}var Je=class extends Ke{async getOrUpload(e,t){let n=await this.getOrCreate({name:e.name??oe(e.path),kind:e.kind??`App`,...e.platform&&{platform:e.platform},...e.ttl&&{ttl:e.ttl},...e.uploadOptions},t),r=await ie.readFile(e.path),i=ce(`md5`).update(r).digest(`hex`);if(n.md5&&n.md5===i)return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,kind:n.kind,...n.platform&&{platform:n.platform},md5:n.md5,...n.expiresAt&&{expiresAt:n.expiresAt}};let a=await l.fetch(n.signedUploadUrl,{headers:{...e.onUploadProgress&&{"Content-Length":r.length.toString()},"Content-Type":`application/octet-stream`},method:`PUT`,...qe(r,e.onUploadProgress)});if(a.status!==200)throw Error(`Failed to upload asset: ${a.status} ${await a.text()}`);return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,kind:n.kind,...n.platform&&{platform:n.platform},md5:i,...n.expiresAt&&{expiresAt:n.expiresAt}}}},Ye=class extends H{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/ios_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/ios_instances`,z,{query:e,...t})}delete(e,t){return this._client.delete(W`/v1/ios_instances/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(W`/v1/ios_instances/${e}`,t)}},Xe=class extends Ye{listSessionArtifacts(e,t,n){return this._client.get(W`/v1/ios_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}},Ze=class extends H{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/android_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/android_instances`,z,{query:e,...t})}delete(e,t){return this._client.delete(W`/v1/android_instances/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(W`/v1/android_instances/${e}`,t)}},Qe=class extends Ze{listSessionArtifacts(e,t,n){return this._client.get(W`/v1/android_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}},$e=class extends H{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/xcode_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/xcode_instances`,z,{query:e,...t})}delete(e,t){return this._client.delete(W`/v1/xcode_instances/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}get(e,t){return this._client.get(W`/v1/xcode_instances/${e}`,t)}},et=class extends Error{constructor(e){super(`Instance ${e} was gone before it reported any cache status`),this.instanceId=e,this.name=`XcodeCacheGoneError`}},tt=class extends Error{constructor(e,t,n){super(`Timed out after ${Math.round(t/1e3)}s waiting for the cache ${e} to finish`+(n?` (last phase: ${n[e].phase})`:``)),this.side=e,this.timeoutMs=t,this.cache=n,this.name=`XcodeCacheTimeoutError`}};const nt={restore:12e5,save:72e4};function rt(e){return e===`disabled`||e===`unsupported`||e===`restored`||e===`skipped`||e===`failed`}function it(e){return e===`disabled`||e===`published`||e===`skipped`||e===`failed`||e===`timed_out`}function at(e,t){return t===`restore`?rt(e.restore.phase):it(e.save.phase)}function ot(e,t={}){let n=t.side??`restore`,r=t.timeoutMs??nt[n],i=e.baseURL;for(;i.endsWith(`/`);)i=i.slice(0,-1);let a=`${i}/v1/xcode_instances/${encodeURIComponent(e.instanceId)}/cache`;return new Promise((i,o)=>{let s,c=``,u=!1,d=e=>{if(!u){u=!0,clearTimeout(f),t.signal?.removeEventListener(`abort`,p);try{g.close()}catch{}e()}},f=setTimeout(()=>d(()=>o(new tt(n,r,s))),r),p=()=>d(()=>o(t.signal?.reason??Error(`aborted`))),m=!1,h=()=>{m||u||(m=!0,l.fetch(a,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`application/json`}}).then(async t=>{if(m=!1,t.status!==404){await t.text().catch(()=>void 0);return}d(()=>s?i({cache:s,gone:!0}):o(new et(e.instanceId)))}).catch(()=>{m=!1}))},g=y({url:a,fetch:async(t,n)=>{let r=await l.fetch(t,n);return r.status===404&&d(()=>s?i({cache:s,gone:!0}):o(new et(e.instanceId))),r},onConnect:()=>t.onOpen?.(),headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`text/event-stream`},onMessage:e=>{if(e.event!==`cache`&&e.event!==`gone`)return;let r;try{r=JSON.parse(typeof e.data==`string`?e.data:String(e.data))}catch(e){d(()=>o(Error(`Cache stream sent unreadable data: ${e}`)));return}if(s=r,e.event===`gone`){h();return}let a=`${r.restore.phase}/${r.restore.reason??``}|${r.save.phase}/${r.save.reason??``}`;a!==c&&(c=a,t.onUpdate?.(r)),at(r,n)&&d(()=>i({cache:r,gone:!1}))}});if(t.signal?.aborted){p();return}t.signal?.addEventListener(`abort`,p,{once:!0})})}function st(e,t){let n=x.resolve(e),r=`limsync-cache-${x.basename(n)}-${se.createHash(`sha1`).update(n).digest(`hex`).slice(0,8)}`;return{cacheKey:r,basisCacheDir:t??x.join(ae.tmpdir(),r)}}function K(e,t,n,r){return e.getOrCreate({name:t,ttl:n||`336h`,...r}).catch(e=>{let n=`Failed to create upload URL for asset '${t}': ${e instanceof Error?e.message:e}`;throw Error(n,{cause:e})})}const ct=[`none`,`error`,`warn`,`info`,`debug`];function lt(e,t){let n=ct.indexOf(t),r=e=>n>=ct.indexOf(e);return(t,n)=>{r(t)&&(t===`error`||t===`warn`?console[t](e,n):console.log(e,n))}}const ut=/^[A-Z0-9_]+$/,dt=4096,ft=65536;function pt(e){let t=Object.entries(e);if(t.length>32)throw Error(`too many build settings: got ${t.length}, max 32`);let n=0;for(let[e,r]of t){if(!ut.test(e))throw Error(`invalid build setting key "${e}": keys must match ^[A-Z0-9_]+$`);if(typeof r!=`string`)throw Error(`invalid build setting value for "${e}": value must be a string`);let t=Buffer.byteLength(r,`utf8`);if(t>dt)throw Error(`build setting value for "${e}" is too large: got ${t} bytes, max ${dt} bytes`);if(n+=Buffer.byteLength(e,`utf8`)+t,n>ft)throw Error(`build settings payload is too large: max ${ft} bytes`)}}const mt=e=>new Promise(t=>setTimeout(t,e)),ht=/failed: (?:502|503|504)\b|\bEOF\b|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed/i;function gt(e){let t=e instanceof Error?e.message:String(e);return ht.test(t)}async function _t(e,t={}){let n=t.sleep??mt,r=t.attempts??5,i=t.retryOn??gt,a;for(let o=1;o<=r;o++)try{return await e()}catch(e){if(!i(e))throw e;if(a=e,o<r){let r=e instanceof Error?e.message:String(e);t.log?.(`Retrying after error (${r.trim()})...`),await n(2e3*o)}}throw a}function vt(e){if(e===``||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`))throw Error(`invalid sandbox home path from server: ${e}`);let t=e.split(`/`);if(t.some(e=>e===``||e===`.`||e===`..`))throw Error(`invalid sandbox home path from server: ${e}`);return t.join(`/`)}async function yt(e,t){let n=await J(await l.fetch(`${e}/info`,{method:`GET`,headers:{Authorization:`Bearer ${t}`}}),`GET /info`);if(!n.homeDir)throw Error(`GET /info response is missing homeDir`);return{homeDir:vt(n.homeDir),...n.xcode?{xcode:n.xcode}:{}}}function bt(e){let t=new URL(e);if(t.protocol===`https:`)t.protocol=`wss:`;else if(t.protocol===`http:`)t.protocol=`ws:`;else throw Error(`Unsupported apiUrl protocol for rbe tunnel: ${t.protocol}`);return t.pathname=`${t.pathname.replace(/\/+$/,``)}/rbe/tunnel`,t.search=``,t.hash=``,t.toString()}var xt=class extends b{constructor(e){super(`Remote build execution is not available on this Xcode instance (${e} returned 404). Its limbuild may predate RBE support, or you may be targeting the wrong environment (for example production instead of staging).`),this.name=`RbeUnsupportedError`}},St=class extends b{constructor(e){super(`Xcode version selection is not available on this sandbox (${e} returned 404): its daemon predates Xcode selection. Create a new sandbox, or omit the Xcode version to build with its default.`),this.name=`XcodeSelectionUnsupportedError`}};function Ct(e,t){return wt(e,t,e=>new St(e))}function q(e,t){return wt(e,t,e=>new xt(e))}async function wt(e,t,n){if(e.status===404)throw await e.text().catch(()=>void 0),n(t);return J(e,t)}async function J(e,t){let n=await e.text();if(!e.ok)throw g(t,e.status,n,e.headers);if(!n.trim())throw Error(`${t} returned an empty response`);return JSON.parse(n)}var Tt=class extends $e{listBuildLogs(e,t){return this._client.get(W`/v1/xcode_instances/${e}/build_logs`,t)}listBazelBuildLogs(e,t){return this._client.get(W`/v1/xcode_instances/${e}/bazel_build_logs`,t)}create(e,t){return super.create(e,t)}getCache(e,t){return this._client.get(W`/v1/xcode_instances/${e}/cache`,t)}bindCacheKey(e,t,n){return this._client.put(W`/v1/xcode_instances/${e}/cache`,{body:{key:t},...n})}followCache(e,t){let n=this._client.apiKey;if(!n)throw Error(`Following cache status needs an API key on the client`);return ot({baseURL:this._client.baseURL,apiKey:n,instanceId:e},t)}async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=e.instance.status.token}else t=e.apiUrl,n=e.token;let r=lt(`[XcodeInstance]`,e.logLevel??`info`),i=this._client,a,s=()=>(a??=yt(t,n),a),u=async e=>{let r,i;if(`status`in e){if(!e.status.apiUrl)throw Error(`Simulator instance not ready: apiUrl is not available`);r=e.status.apiUrl,i=e.status.token}else r=e.apiUrl,i=e.token;return J(await l.fetch(`${t}/simulator`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({apiUrl:r,token:i})}),`POST /simulator`)},d=async e=>{try{return await i.iosInstances.delete(e),!0}catch{return!1}};return{async sync(e,i){let{cacheKey:a,basisCacheDir:c}=st(e,i?.basisCacheDir),l=i?.additionalFiles&&i.additionalFiles.length>0?await s():void 0,u=i?.additionalFiles?.map(e=>({localPath:e.localPath,remotePath:l&&e.remotePath.startsWith(`~/`)?`${l.homeDir}/${e.remotePath.slice(2)}`:e.remotePath})),d={apiUrl:t,token:n,udid:a,install:i?.install??!0,ignoreFn:await p(e,{basisCacheDir:c,log:r,xcodeDefaults:!0,...i?.include?{include:i.include}:{},...i?.ignore?{additional:i.ignore}:{}}),basisCacheDir:c,watch:i?.watch??!0,launchMode:`ForegroundIfRunning`,log:r,syncSymlinks:!0,...u?{additionalFiles:u}:{},...i?.onSyncComplete?{onSyncComplete:i.onSyncComplete}:{}},f=await o(e,d),m={};return f.bytesSent!==void 0&&(m.bytesSent=f.bytesSent),f.stopWatching&&(m.stopWatching=f.stopWatching),m},xcodebuild(e,a){if(a?.reactNative?.devServerURL&&e?.configuration===`Release`)throw Error(`reactNative.devServerURL is only supported for Debug builds`);if(e?.onlyTesting?.length&&e?.skipTesting?.length)throw Error(`onlyTesting and skipTesting are mutually exclusive; pass one`);if((e?.onlyTesting?.length||e?.skipTesting?.length)&&e?.action!==`build-for-testing`)throw Error(`onlyTesting/skipTesting require action: 'build-for-testing'`);if(e?.runTests===!1&&e?.action!==`build-for-testing`)throw Error(`runTests: false requires action: 'build-for-testing'`);if(e?.action===`build-for-testing`&&e.sdk!==void 0&&e.sdk!==`iphonesimulator`)throw Error(`action: 'build-for-testing' requires the iphonesimulator sdk`);a?.buildSettings&&pt(a.buildSettings);let o={command:`xcodebuild`,...e&&{xcodebuild:e},...a?.xcodegen&&{xcodegen:a.xcodegen},...a?.reactNative&&{reactNative:a.reactNative},...a?.signing&&{signing:a.signing},...a?.cloudSigning&&{cloudSigning:a.cloudSigning},...a?.appstore&&{testflight:a.appstore},...a?.buildSettings&&{buildSettings:a.buildSettings},...a?.env?.length&&{env:a.env},...a?.gitInit!==void 0&&{gitInit:a.gitInit},...a?.logProcessor&&{logProcessor:a.logProcessor},...a?.webhook&&{webhook:a.webhook}},s={apiUrl:t,token:n,log:r,...a?.onXctestEvent&&{onXctestEvent:a.onXctestEvent}};if(a?.upload&&`assetName`in a.upload){let e=K(i.assets,a.upload.assetName,a.upload.ttl,a.upload.uploadOptions).then(e=>(o.signedUploadUrl=e.signedUploadUrl,o.assetId=e.id,o.additionalMetadata={signedDownloadUrl:e.signedDownloadUrl},o));return c(e,s)}return a?.upload&&`signedUploadUrl`in a.upload&&(o.signedUploadUrl=a.upload.signedUploadUrl),c(o,s)},run(e,i){if(e.trim()===``)throw Error(`commandLine must not be empty`);if(i?.timeoutSeconds!==void 0&&(!Number.isInteger(i.timeoutSeconds)||i.timeoutSeconds<1||i.timeoutSeconds>21600))throw Error(`timeoutSeconds must be an integer between 1 and 21600`);let a={command:`run`,commandLine:e,cwd:i?.cwd??`.`,...i?.env&&{env:i.env},...i?.timeoutSeconds!==void 0&&{timeoutSeconds:i.timeoutSeconds}};return c(a,{apiUrl:t,token:n,log:r})},async getSimulator(){return J(await l.fetch(`${t}/simulator`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /simulator`)},attachSimulator:u,attachNewSimulator:async()=>{let e=await i.iosInstances.create({wait:!0});try{await u(e)}catch(t){throw await d(e.metadata.id),t}return{iosInstanceId:e.metadata.id,simulator:e}},deleteSimulator:d,async getXcode(){return Ct(await l.fetch(`${t}/xcode`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /xcode`)},async setXcode(e){return Ct(await l.fetch(`${t}/xcode`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({version:e})}),`POST /xcode`)},getInfo:()=>yt(t,n),async startRbe(e){return q(await l.fetch(`${t}/rbe`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify(e??{})}),`POST /rbe`)},async getRbe(){return q(await l.fetch(`${t}/rbe`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe`)},async stopRbe(){return q(await l.fetch(`${t}/rbe`,{method:`DELETE`,headers:{Authorization:`Bearer ${n}`}}),`DELETE /rbe`)},async startRbeTunnel(r){return _(bt(t),n,r?.host??`127.0.0.1`,r?.port??8980,{mode:`multiplexed`,logLevel:r?.logLevel??e.logLevel??`info`})},async uploadLatestRbeBuild(e){let r,a;if(e.assetName!==void 0){if(!e.assetName)throw Error(`assetName must not be empty`);let t=await K(i.assets,e.assetName,e.ttl);r=t.signedUploadUrl,a=t.signedDownloadUrl}else r=e.signedUploadUrl;return{...await _t(async()=>{let e=await l.fetchLongRequest(`${t}/rbe/upload`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({signedUploadUrl:r})});if(e.status===404)throw await e.text().catch(()=>void 0),Error(`POST /rbe/upload returned 404: the instance may no longer exist, or its limbuild predates RBE upload support. Recreate the instance and retry.`);return J(e,`POST /rbe/upload`)},{retryOn:e=>gt(e)||v(e,400)&&/no successful RBE app build/i.test(e.body)}),...a&&{signedDownloadUrl:a}}},async getActiveRbeBuilds(){return q(await l.fetch(`${t}/rbe/builds/active`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe/builds/active`)},async getRecentRbeBuilds(){return q(await l.fetch(`${t}/rbe/builds/recent`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe/builds/recent`)},waitForRbeBuildEnd(e,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(Error(`waiting for build ${e} was aborted`));return}let o=!1,s=()=>{f.close(),r?.signal?.removeEventListener(`abort`,d)},c=e=>{o||(o=!0,s(),i(e))},u=e=>{o||(o=!0,s(),a(e))},d=()=>u(Error(`waiting for build ${e} was aborted`)),f=y({url:`${t}/exec/${e}/events`,fetch:m(l.fetch,t=>u(Error(`build event stream for ${e} is unreachable: ${t instanceof Error?t.message:t}`))),headers:{Authorization:`Bearer ${n}`},onMessage:t=>{if(t.event!==`end`)return;let n;try{n=JSON.parse(t.data)}catch(t){u(Error(`invalid build end event for ${e}: ${t}`));return}c(n)},onDisconnect:()=>{u(Error(`build event stream for ${e} ended without a terminal event (the build may have finished and its live stream been removed)`))}});r?.signal?.addEventListener(`abort`,d,{once:!0})})}}}};function Et(e){let t=e.endsWith(`/`)?e.slice(0,-1):e,n=t.split(`/`);return n[n.length-1]===`local.properties`||n.length===1&&(t===`.gradle`||t===`.kotlin`||t===`build`)}var Dt=class extends G{listBuildLogs(e,t){return this._client.get(W`/v1/gradle_instances/${e}/build_logs`,t)}async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=e.instance.status.token}else t=e.apiUrl,n=e.token;let r=lt(`[GradleInstance]`,e.logLevel??`info`),i=this._client;return{async sync(e,i){let{cacheKey:a,basisCacheDir:s}=st(e,i?.basisCacheDir),c=i?.ignore,l={apiUrl:t,token:n,udid:a,install:!1,ignoreFn:await p(e,{basisCacheDir:s,log:r,xcodeDefaults:!1,nestedGitignore:!0,additional:c?e=>Et(e)||c(e):Et,...i?.include?{include:i.include}:{}}),basisCacheDir:s,watch:!1,launchMode:`ForegroundIfRunning`,log:r,syncSymlinks:!0},u=await o(e,l),d={};return u.bytesSent!==void 0&&(d.bytesSent=u.bytesSent),d},gradlebuild(e){let a={command:`gradlebuild`,...e?.tasks?.length&&{tasks:e.tasks},...e?.projectPath&&{projectPath:e.projectPath},...e?.reactNative&&{reactNative:e.reactNative},...e?.signing&&{signing:e.signing},...e?.webhook&&{webhook:e.webhook},...e?.playstore&&{playstore:e.playstore}};if(e?.upload&&`assetName`in e.upload){let o=K(i.assets,e.upload.assetName,e.upload.ttl).then(e=>(a.signedUploadUrl=e.signedUploadUrl,a.additionalMetadata={signedDownloadUrl:e.signedDownloadUrl},a));return c(o,{apiUrl:t,token:n,log:r})}return e?.upload&&`signedUploadUrl`in e.upload&&(a.signedUploadUrl=e.upload.signedUploadUrl),c(a,{apiUrl:t,token:n,log:r})}}}};G.prototype.listBuildLogs=Dt.prototype.listBuildLogs,G.prototype.createClient=Dt.prototype.createClient;const Y=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var X,Z,Q,Ot,$=class{constructor({baseURL:e=Y(`LIMRUN_BASE_URL`),apiKey:t=Y(`LIM_API_KEY`)??null,...n}={}){X.add(this),Q.set(this,void 0),this.androidInstances=new Qe(this),this.assets=new Je(this),this.iosInstances=new Xe(this),this.xcodeInstances=new Tt(this),this.gradleInstances=new G(this),this.analytics=new Be(this),this.scopedTokens=new Ge(this);let r={apiKey:t,...n,baseURL:e||`https://api.limrun.com`};this.baseURL=r.baseURL,this.timeout=r.timeout??Z.DEFAULT_TIMEOUT,this.logger=r.logger??console;let i=`warn`;this.logLevel=i,this.logLevel=A(r.logLevel,`ClientOptions.logLevel`,this)??A(Y(`LIMRUN_LOG`),`process.env['LIMRUN_LOG']`,this)??i,this.fetchOptions=r.fetchOptions,this.maxRetries=r.maxRetries??2,this.fetch=r.fetch??Se(),S(this,Q,Ee,`f`);let a=Y(`LIMRUN_CUSTOM_HEADERS`);if(a){let e={};for(let t of a.split(`
3
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}r.defaultHeaders={...e,...r.defaultHeaders}}this._options=r,this.apiKey=t}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted`)}async authHeaders(e){if(this.apiKey!=null)return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return De(e)}getUserAgent(){return`${this.constructor.name}/JS ${O}`}defaultIdempotencyKey(){return`stainless-node-retry-${w()}`}makeStatusError(e,t,n,r){return f.generate(e,t,n,r)}buildURL(e,t,n){let r=!C(this,X,`m`,Ot).call(this)&&n||this.baseURL,i=ue(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!de(a)||!de(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,r,i){let a=await e,o=a.maxRetries??this.maxRetries;r??=o,await this.prepareOptions(a);let{req:s,url:c,timeout:l}=await this.buildRequest(a,{retryCount:o-r});await this.prepareRequest(s,{url:c,options:a});let u=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),f=i===void 0?``:`, retryOf: ${i}`,p=Date.now();if(P(this).debug(`[${u}] sending request`,F({retryOfRequestLogID:i,method:a.method,url:c,options:a,headers:s.headers})),a.signal?.aborted)throw new d;let m=new AbortController,g=await this.fetchWithTimeout(c,s,l,m).catch(n),_=Date.now();if(g instanceof globalThis.Error){let e=`retrying, ${r} attempts remaining`;if(a.signal?.aborted)throw new d;let n=t(g)||/timed? ?out/i.test(String(g)+(`cause`in g?String(g.cause):``));if(r)return P(this).info(`[${u}] connection ${n?`timed out`:`failed`} - ${e}`),P(this).debug(`[${u}] connection ${n?`timed out`:`failed`} (${e})`,F({retryOfRequestLogID:i,url:c,durationMs:_-p,message:g.message})),this.retryRequest(a,r,i??u);throw P(this).info(`[${u}] connection ${n?`timed out`:`failed`} - error; no more retries left`),P(this).debug(`[${u}] connection ${n?`timed out`:`failed`} (error; no more retries left)`,F({retryOfRequestLogID:i,url:c,durationMs:_-p,message:g.message})),n?new h:new ee({cause:g})}let v=`[${u}${f}] ${s.method} ${c} ${g.ok?`succeeded`:`failed`} with status ${g.status} in ${_-p}ms`;if(!g.ok){let e=await this.shouldRetry(g);if(r&&e){let e=`retrying, ${r} attempts remaining`;return await Te(g.body),P(this).info(`${v} - ${e}`),P(this).debug(`[${u}] response error (${e})`,F({retryOfRequestLogID:i,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),this.retryRequest(a,r,i??u,g.headers)}let t=e?`error; no more retries left`:`error; not retryable`;P(this).info(`${v} - ${t}`);let o=await g.text().catch(e=>n(e).message),s=me(o),c=s?void 0:o;throw P(this).debug(`[${u}] response error (${t})`,F({retryOfRequestLogID:i,url:g.url,status:g.status,headers:g.headers,message:c,durationMs:Date.now()-p})),this.makeStatusError(g.status,s,c,g.headers)}return P(this).info(v),P(this).debug(`[${u}] response start`,F({retryOfRequestLogID:i,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),{response:g,options:a,controller:m,requestLogID:u,retryOfRequestLogID:i,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new je(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await u(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&pe(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=U([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...xe()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?C(this,Q,`f`).call(this,{body:t,headers:U([n])}):{bodyHeaders:void 0,body:void 0};let r=U([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:we(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:C(this,Q,`f`).call(this,{body:t,headers:r})}};Z=$,Q=new WeakMap,X=new WeakSet,Ot=function(){return this.baseURL!==`https://api.limrun.com`},$.Limrun=Z,$.DEFAULT_TIMEOUT=3e5,$.LimrunError=b,$.APIError=f,$.APIConnectionError=ee,$.APIConnectionTimeoutError=h,$.APIUserAbortError=d,$.NotFoundError=r,$.ConflictError=re,$.RateLimitError=ne,$.BadRequestError=te,$.AuthenticationError=a,$.InternalServerError=s,$.PermissionDeniedError=e,$.UnprocessableEntityError=i,$.toFile=Re,$.AndroidInstances=Qe,$.Assets=Je,$.IosInstances=Xe,$.XcodeInstances=Tt,$.GradleInstances=G,$.Analytics=Be,$.ScopedTokens=Ge,process.platform;export{$ as t};
@@ -1,2 +1,2 @@
1
- import{C as e}from"./sdk-contracts.js";import{a as t,i as n,r}from"./sdk-batch-runner.js";import{l as i,u as a}from"./sdk-device.js";import{n as o,t as s}from"./launch-console.js";import"./observability.js";import{r as c}from"./diagnostics.js";import{n as l}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{i as u,n as d}from"./retry.js";import{D as f,o as p}from"./host-file.js";import{f as m,t as h}from"./config2.js";import{a as g,o as _}from"./tool-provider.js";import{t as v}from"./physical-device-control.js";import{t as y}from"./simctl.js";import{n as b,r as x}from"./apps-simctl.js";import{m as S}from"./runner-client.js";import{t as C}from"./simulator.js";import{a as w,l as T,u as E}from"./app-resolution.js";import D from"node:path";function O(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=t.details??{};if(n.exitCode!==4)return!1;let r=String(n.stderr??``).toLowerCase();return r.includes(`fbsopenapplicationserviceerrordomain`)&&r.includes(`the request to open`)}async function k(e,t){let n=await _(y(e,[`get_app_container`,e.id,t]),{allowFailure:!0});if(n.exitCode!==0)return{installed:!1};let r=n.stdout.trim();if(!r)return{installed:!1};let i=await g(`plutil`,[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,`${r}/Info.plist`],{allowFailure:!0});if(i.exitCode!==0||!i.stdout.trim())return{installed:!0};let a=`${r}/${i.stdout.trim()}`,o=await g(`otool`,[`-l`,a],{allowFailure:!0});if(o.exitCode!==0)return{installed:!0};let s=o.stdout.toLowerCase();return{installed:!0,simulatorCompatible:s.includes(`iossimulator`)||s.includes(`platform 7`)}}function A(e){return e.installed?e.simulatorCompatible===!1?`ARCH_MISMATCH`:`PERSISTENT_LAUNCH_FAIL`:`APP_NOT_INSTALLED`}function j(e){switch(e){case`ARCH_MISMATCH`:return`The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.`;case`APP_NOT_INSTALLED`:return`The app bundle is not installed on this simulator. Run install before open.`;case`PERSISTENT_LAUNCH_FAIL`:return`The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.`;default:return`The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details.`}}const M=25e3;async function N(c,l,u){let d=u?.launchConsole?.trim(),f=u?.launchArgs;if(d&&(!i(c)||c.kind!==`simulator`))throw new e(`UNSUPPORTED_OPERATION`,o);if(a(c)){if(f&&f.length>0)throw new e(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on macOS; launch arguments are currently iOS-only.`);await E(c,l,u);return}let p=u?.url?.trim();if(p){if(d)throw new e(`INVALID_ARGS`,s);if(!r(p))throw new e(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(c.kind===`simulator`){let e=!!f||n(p);if(u?.terminateRunningApp||e){let t=u?.appBundleId??await w(c,l);e?await z(c,t,{...f?{launchArgs:f}:{},...u?.terminateRunningApp?{terminateRunningApp:!0}:{}}):await R(c,t)}await P(c,p,void 0);return}let i=u?.appBundleId??await w(c,l),a=t(i,p);if(!a)throw new e(`INVALID_ARGS`,`Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.`);await W(c,a,{payloadUrl:p,launchArgs:f,runnerOptions:u?.runnerOptions});return}let m=l.trim();if(r(m)){if(d)throw new e(`INVALID_ARGS`,s);if(c.kind===`simulator`){await P(c,m,f);return}let n=t(u?.appBundleId,m);if(!n)throw new e(`INVALID_ARGS`,`Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.`);await W(c,n,{payloadUrl:m,launchArgs:f,runnerOptions:u?.runnerOptions});return}let h=u?.appBundleId??await w(c,l);if(c.kind===`simulator`){await z(c,h,{...d?{launchConsole:d}:{},...f?{launchArgs:f}:{},...u?.terminateRunningApp?{terminateRunningApp:!0}:{}});return}await W(c,h,{launchArgs:f,runnerOptions:u?.runnerOptions})}async function P(t,n,r){if(r&&r.length>0)throw new e(`INVALID_ARGS`,`--launch-args is not supported with iOS simulator URL opens (simctl openurl ignores launch args). Launch the app first with --launch-args, then issue the URL open in a separate call.`);await C(t),await b(t,[`openurl`,t.id,n])}async function F(e){a(e)||e.kind===`simulator`&&await C(e)}async function I(e,t,n){if(a(e)){await T(e,t);return}let r=await w(e,t);if(e.kind===`simulator`){await R(e,r);return}await L(r),await v(e).terminateApp(e,r,{runnerOptions:n,runRunnerCommand:S})}async function L(t){let{isIosSystemSurfaceHost:n,iosSystemSurfaceOpenRefusal:r}=await import(`./ios-system-surface.js`).then(e=>e.i);if(n(t))throw new e(`UNSUPPORTED_OPERATION`,r(t),{reason:`system-surface-host-not-openable`,appBundleId:t})}async function R(t,n){await L(n),await C(t);let r=x(t,[`terminate`,t.id,n]),i=await _(r,{allowFailure:!0,timeoutMs:m});if(i.exitCode!==0&&!i.stderr.toLowerCase().includes(`found nothing to terminate`))throw new e(`COMMAND_FAILED`,`xcrun exited with code ${i.exitCode}`,l(i,{cmd:`xcrun`,args:r}))}async function z(t,n,r){await L(n),await C(t);let i=0,a=d.fromTimeoutMs(h);try{await u(async({deadline:i})=>{if(i?.isExpired())throw new e(`COMMAND_FAILED`,`App launch deadline exceeded`,{timeoutMs:h});let a=x(t,B(t.id,n,r)),o=r?.launchConsole?await V(a,r.launchConsole):await _(a,{allowFailure:!0});if(o.exitCode!==0)throw new e(`COMMAND_FAILED`,`xcrun exited with code ${o.exitCode}`,l(o,{cmd:`xcrun`,args:a}))},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry(e){return O(e)?(i+=1,i<3):!1}},{deadline:a})}catch(e){if(O(e)){let r=e,i=A(await k(t,n));r.details={...r.details,hint:j(i)}}throw e}}function B(e,t,n){let r=[`launch`];return n?.launchConsole&&r.push(`--console-pty`),n?.terminateRunningApp&&r.push(`--terminate-running-process`),r.push(e,t),n?.launchArgs&&n.launchArgs.length>0&&r.push(...n.launchArgs),r}async function V(t,n){await p(D.dirname(n));try{let e=await _(t,{allowFailure:!0,timeoutMs:M});return await H(n,e.stdout,e.stderr),e}catch(t){let r=(t instanceof e?t:void 0)?.details;if(r?.timeoutMs===M){let e=typeof r.stdout==`string`?r.stdout:``,t=typeof r.stderr==`string`?r.stderr:``;return await H(n,e,t),c({level:`warn`,phase:`ios_simulator_launch_console_capture_timeout`,data:{timeoutMs:M,logPath:n,stdoutBytes:Buffer.byteLength(e),stderrBytes:Buffer.byteLength(t)}}),{stdout:e,stderr:t,exitCode:0}}throw t}}async function H(e,t,n){await f(e,U(t,n))}function U(e,t){return!e||!t||e.endsWith(`
1
+ import{C as e}from"./sdk-contracts.js";import{a as t,i as n,r}from"./sdk-batch-runner.js";import{l as i,u as a}from"./sdk-device.js";import{n as o,t as s}from"./launch-console.js";import"./observability.js";import{r as c}from"./diagnostics.js";import{n as l}from"./exec.js";import"./diagnostics2.js";import"./command.js";import{i as u,n as d}from"./retry.js";import{D as f,o as p}from"./host-file.js";import{f as m,t as h}from"./config.js";import{a as g,o as _}from"./tool-provider.js";import{t as v}from"./physical-device-control.js";import{t as y}from"./simctl.js";import{n as b,r as x}from"./apps-simctl.js";import{h as S}from"./runner-client.js";import{t as C}from"./simulator.js";import{a as w,l as T,u as E}from"./app-resolution.js";import D from"node:path";function O(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=t.details??{};if(n.exitCode!==4)return!1;let r=String(n.stderr??``).toLowerCase();return r.includes(`fbsopenapplicationserviceerrordomain`)&&r.includes(`the request to open`)}async function k(e,t){let n=await _(y(e,[`get_app_container`,e.id,t]),{allowFailure:!0});if(n.exitCode!==0)return{installed:!1};let r=n.stdout.trim();if(!r)return{installed:!1};let i=await g(`plutil`,[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,`${r}/Info.plist`],{allowFailure:!0});if(i.exitCode!==0||!i.stdout.trim())return{installed:!0};let a=`${r}/${i.stdout.trim()}`,o=await g(`otool`,[`-l`,a],{allowFailure:!0});if(o.exitCode!==0)return{installed:!0};let s=o.stdout.toLowerCase();return{installed:!0,simulatorCompatible:s.includes(`iossimulator`)||s.includes(`platform 7`)}}function A(e){return e.installed?e.simulatorCompatible===!1?`ARCH_MISMATCH`:`PERSISTENT_LAUNCH_FAIL`:`APP_NOT_INSTALLED`}function j(e){switch(e){case`ARCH_MISMATCH`:return`The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.`;case`APP_NOT_INSTALLED`:return`The app bundle is not installed on this simulator. Run install before open.`;case`PERSISTENT_LAUNCH_FAIL`:return`The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.`;default:return`The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details.`}}const M=25e3;async function N(c,l,u){let d=u?.launchConsole?.trim(),f=u?.launchArgs;if(d&&(!i(c)||c.kind!==`simulator`))throw new e(`UNSUPPORTED_OPERATION`,o);if(a(c)){if(f&&f.length>0)throw new e(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on macOS; launch arguments are currently iOS-only.`);await E(c,l,u);return}let p=u?.url?.trim();if(p){if(d)throw new e(`INVALID_ARGS`,s);if(!r(p))throw new e(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(c.kind===`simulator`){let e=!!f||n(p);if(u?.terminateRunningApp||e){let t=u?.appBundleId??await w(c,l);e?await z(c,t,{...f?{launchArgs:f}:{},...u?.terminateRunningApp?{terminateRunningApp:!0}:{}}):await R(c,t)}await P(c,p,void 0);return}let i=u?.appBundleId??await w(c,l),a=t(i,p);if(!a)throw new e(`INVALID_ARGS`,`Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.`);await W(c,a,{payloadUrl:p,launchArgs:f,runnerOptions:u?.runnerOptions});return}let m=l.trim();if(r(m)){if(d)throw new e(`INVALID_ARGS`,s);if(c.kind===`simulator`){await P(c,m,f);return}let n=t(u?.appBundleId,m);if(!n)throw new e(`INVALID_ARGS`,`Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.`);await W(c,n,{payloadUrl:m,launchArgs:f,runnerOptions:u?.runnerOptions});return}let h=u?.appBundleId??await w(c,l);if(c.kind===`simulator`){await z(c,h,{...d?{launchConsole:d}:{},...f?{launchArgs:f}:{},...u?.terminateRunningApp?{terminateRunningApp:!0}:{}});return}await W(c,h,{launchArgs:f,runnerOptions:u?.runnerOptions})}async function P(t,n,r){if(r&&r.length>0)throw new e(`INVALID_ARGS`,`--launch-args is not supported with iOS simulator URL opens (simctl openurl ignores launch args). Launch the app first with --launch-args, then issue the URL open in a separate call.`);await C(t),await b(t,[`openurl`,t.id,n])}async function F(e){a(e)||e.kind===`simulator`&&await C(e)}async function I(e,t,n){if(a(e)){await T(e,t);return}let r=await w(e,t);if(e.kind===`simulator`){await R(e,r);return}await L(r),await v(e).terminateApp(e,r,{runnerOptions:n,runRunnerCommand:S})}async function L(t){let{iosSystemSurfaceHost:n,iosSystemSurfaceOpenRefusal:r}=await import(`./ios-system-surface.js`).then(e=>e.a);if(n(t))throw new e(`UNSUPPORTED_OPERATION`,r(t),{reason:`system-surface-host-not-openable`,appBundleId:t})}async function R(t,n){await L(n),await C(t);let r=x(t,[`terminate`,t.id,n]),i=await _(r,{allowFailure:!0,timeoutMs:m});if(i.exitCode!==0&&!i.stderr.toLowerCase().includes(`found nothing to terminate`))throw new e(`COMMAND_FAILED`,`xcrun exited with code ${i.exitCode}`,l(i,{cmd:`xcrun`,args:r}))}async function z(t,n,r){await L(n),await C(t);let i=0,a=d.fromTimeoutMs(h);try{await u(async({deadline:i})=>{if(i?.isExpired())throw new e(`COMMAND_FAILED`,`App launch deadline exceeded`,{timeoutMs:h});let a=x(t,B(t.id,n,r)),o=r?.launchConsole?await V(a,r.launchConsole):await _(a,{allowFailure:!0});if(o.exitCode!==0)throw new e(`COMMAND_FAILED`,`xcrun exited with code ${o.exitCode}`,l(o,{cmd:`xcrun`,args:a}))},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry(e){return O(e)?(i+=1,i<3):!1}},{deadline:a})}catch(e){if(O(e)){let r=e,i=A(await k(t,n));r.details={...r.details,hint:j(i)}}throw e}}function B(e,t,n){let r=[`launch`];return n?.launchConsole&&r.push(`--console-pty`),n?.terminateRunningApp&&r.push(`--terminate-running-process`),r.push(e,t),n?.launchArgs&&n.launchArgs.length>0&&r.push(...n.launchArgs),r}async function V(t,n){await p(D.dirname(n));try{let e=await _(t,{allowFailure:!0,timeoutMs:M});return await H(n,e.stdout,e.stderr),e}catch(t){let r=(t instanceof e?t:void 0)?.details;if(r?.timeoutMs===M){let e=typeof r.stdout==`string`?r.stdout:``,t=typeof r.stderr==`string`?r.stderr:``;return await H(n,e,t),c({level:`warn`,phase:`ios_simulator_launch_console_capture_timeout`,data:{timeoutMs:M,logPath:n,stdoutBytes:Buffer.byteLength(e),stderrBytes:Buffer.byteLength(t)}}),{stdout:e,stderr:t,exitCode:0}}throw t}}async function H(e,t,n){await f(e,U(t,n))}function U(e,t){return!e||!t||e.endsWith(`
2
2
  `)||e.endsWith(`\r`)?`${e}${t}`:`${e}\n${t}`}async function W(e,t,n){await L(t),await v(e).launchApp(e,t,{...n,runRunnerCommand:S})}export{N as n,F as r,I as t};