agent-device 0.21.20 → 0.21.22

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 (357) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.20.apk → agent-device-android-ime-helper-0.21.22.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.22.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.20.manifest.json → agent-device-android-ime-helper-0.21.22.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.20.manifest.json → agent-device-android-snapshot-helper-0.21.22.manifest.json} +6 -6
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift +73 -0
  8. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +557 -0
  9. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift +141 -0
  10. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +107 -3
  11. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +136 -22
  12. package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift +88 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +121 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +10 -2
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +36 -9
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +28 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +27 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +6 -1
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +7 -2
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +21 -7
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +121 -17
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +179 -6
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +119 -0
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +8 -1
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +23 -11
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +59 -6
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +112 -23
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +25 -12
  29. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +6 -1
  30. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +43 -13
  31. package/dist/src/adapter.js +1 -1
  32. package/dist/src/adb-executor.js +2 -2
  33. package/dist/src/adb-failure.js +1 -1
  34. package/dist/src/adb-transport.js +1 -1
  35. package/dist/src/agent-browser-lifecycle.js +1 -1
  36. package/dist/src/agent-browser-process-record.js +1 -1
  37. package/dist/src/agent-browser-provider.js +1 -1
  38. package/dist/src/agent-browser-tool.js +1 -1
  39. package/dist/src/agent-device-client.js +2 -2
  40. package/dist/src/ai-sdk.js +1 -1
  41. package/dist/src/alert-runtime.js +1 -1
  42. package/dist/src/alert.js +1 -1
  43. package/dist/src/android-adb.d.ts +12 -0
  44. package/dist/src/android-input-ownership.js +1 -1
  45. package/dist/src/app-backend.js +1 -0
  46. package/dist/src/app-catalog.js +1 -1
  47. package/dist/src/app-deployment-resolution.js +1 -1
  48. package/dist/src/app-inventory.js +1 -1
  49. package/dist/src/app-launch.js +1 -1
  50. package/dist/src/app-lifecycle.js +2 -2
  51. package/dist/src/app-lifecycle2.js +1 -1
  52. package/dist/src/app-log-files.js +1 -1
  53. package/dist/src/app-log-reconnect.js +1 -1
  54. package/dist/src/app-log-runtime2.js +3 -3
  55. package/dist/src/app-log-session-resource.js +1 -0
  56. package/dist/src/app-resolution.js +2 -2
  57. package/dist/src/apple-runner-platform.js +1 -1
  58. package/dist/src/application-lifecycle-interaction.js +1 -1
  59. package/dist/src/archive.js +2 -2
  60. package/dist/src/artifact-download.js +1 -1
  61. package/dist/src/auth-session.js +1 -1
  62. package/dist/src/auth.js +1 -1
  63. package/dist/src/back-mode.js +1 -1
  64. package/dist/src/backend-snapshot-options.js +1 -1
  65. package/dist/src/boot-diagnostics.js +1 -1
  66. package/dist/src/cache.js +1 -1
  67. package/dist/src/capabilities.js +1 -1
  68. package/dist/src/capture.js +1 -1
  69. package/dist/src/cli-config.js +1 -1
  70. package/dist/src/cli-help.js +13 -5
  71. package/dist/src/cli.js +4 -4
  72. package/dist/src/click-button.js +1 -1
  73. package/dist/src/client-metro-companion.js +1 -1
  74. package/dist/src/client-metro.js +1 -1
  75. package/dist/src/client-options.js +3 -0
  76. package/dist/src/client-types.d.ts +88 -5
  77. package/dist/src/clipboard-shell-response.js +1 -1
  78. package/dist/src/cloud-artifacts.d.ts +7 -2
  79. package/dist/src/code-signature-cache.js +1 -1
  80. package/dist/src/code-signature.js +1 -1
  81. package/dist/src/command-schema.js +1 -1
  82. package/dist/src/command-tools.js +2 -2
  83. package/dist/src/connection-runtime.js +1 -1
  84. package/dist/src/connection.js +5 -5
  85. package/dist/src/contracts.d.ts +1 -1
  86. package/dist/src/contracts.js +1 -1
  87. package/dist/src/daemon-artifacts.js +1 -0
  88. package/dist/src/daemon-client-lease-beat.js +1 -1
  89. package/dist/src/daemon-client-lifecycle.js +1 -1
  90. package/dist/src/daemon-client-liveness-probe.js +1 -0
  91. package/dist/src/daemon-client-transport.js +1 -1
  92. package/dist/src/daemon-http.js +1 -0
  93. package/dist/src/daemon-policy-file.js +1 -1
  94. package/dist/src/daemon-registration-owner.js +1 -0
  95. package/dist/src/daemon-registration.js +1 -1
  96. package/dist/src/daemon-resolution.js +1 -1
  97. package/dist/src/daemon-shutdown-report.js +1 -1
  98. package/dist/src/daemon.js +2 -2
  99. package/dist/src/debug-symbols-facade.js +1 -1
  100. package/dist/src/device-claim-inspection.js +1 -1
  101. package/dist/src/device-claim-rule.js +1 -1
  102. package/dist/src/device-inventory-context.js +1 -1
  103. package/dist/src/device-readiness-runtime.js +1 -1
  104. package/dist/src/device-release.js +1 -1
  105. package/dist/src/device-rotation.js +1 -1
  106. package/dist/src/device-selection-resolver.js +1 -1
  107. package/dist/src/device-session.js +1 -1
  108. package/dist/src/device-shell.js +1 -1
  109. package/dist/src/device.js +1 -1
  110. package/dist/src/device2.js +1 -3
  111. package/dist/src/device3.js +3 -0
  112. package/dist/src/devicectl.js +1 -1
  113. package/dist/src/diagnostics.js +3 -3
  114. package/dist/src/dispatch-resolve.js +4 -1
  115. package/dist/src/display-inventory.js +1 -1
  116. package/dist/src/doctor-facade.js +1 -1
  117. package/dist/src/doctor2.js +1 -1
  118. package/dist/src/durable-capture-resource.js +1 -0
  119. package/dist/src/engine-eval-script.js +1 -1
  120. package/dist/src/error.js +1 -1
  121. package/dist/src/exec.js +1 -1
  122. package/dist/src/file.js +1 -1
  123. package/dist/src/find.js +1 -1
  124. package/dist/src/generic-settle.js +1 -1
  125. package/dist/src/generic.js +1 -1
  126. package/dist/src/gesture-admission.js +1 -1
  127. package/dist/src/gesture-plan.js +1 -1
  128. package/dist/src/gesture-runtime.js +1 -1
  129. package/dist/src/harmonyos.js +1 -1
  130. package/dist/src/hdc.js +1 -1
  131. package/dist/src/helper.js +2 -2
  132. package/dist/src/host-file.js +1 -1
  133. package/dist/src/host.js +1 -1
  134. package/dist/src/human-control-contract.js +1 -1
  135. package/dist/src/human-control.js +1 -1
  136. package/dist/src/index.d.ts +1 -1
  137. package/dist/src/index.js +1 -1
  138. package/dist/src/input-actions.js +1 -1
  139. package/dist/src/input-actions2.js +2 -2
  140. package/dist/src/install-artifact-facade.js +1 -1
  141. package/dist/src/install-source-network-transport.js +1 -1
  142. package/dist/src/install-source.d.ts +5 -0
  143. package/dist/src/install-source2.js +1 -1
  144. package/dist/src/instance-client.js +1 -0
  145. package/dist/src/interaction-positionals.js +1 -1
  146. package/dist/src/interaction-ref-policy.js +1 -1
  147. package/dist/src/interaction.js +1 -1
  148. package/dist/src/interaction2.js +1 -1
  149. package/dist/src/interactor-operation-binding.js +1 -1
  150. package/dist/src/interactor.js +5 -5
  151. package/dist/src/interactor2.js +1 -1
  152. package/dist/src/interactors.js +1 -1
  153. package/dist/src/internal/bin.js +1 -1
  154. package/dist/src/internal/daemon.js +1 -2
  155. package/dist/src/internal/png-worker.js +1 -1
  156. package/dist/src/internal/run-script-http-child.js +1 -1
  157. package/dist/src/inventory.js +4 -4
  158. package/dist/src/inventory2.js +1 -1
  159. package/dist/src/inventory3.js +1 -1
  160. package/dist/src/inventory5.js +1 -1
  161. package/dist/src/ios-client.js +4 -30
  162. package/dist/src/ios-settings.js +1 -0
  163. package/dist/src/ios-snapshot-engine.js +1 -1
  164. package/dist/src/ios-snapshot-runtime.js +1 -1
  165. package/dist/src/launch-confirmation.js +1 -1
  166. package/dist/src/lease-context.js +1 -1
  167. package/dist/src/lease-registry-scope.js +1 -0
  168. package/dist/src/lease-scope.js +1 -1
  169. package/dist/src/lease.js +1 -1
  170. package/dist/src/legacy-xctest-device-set.js +1 -1
  171. package/dist/src/limrun-download-file.js +1 -1
  172. package/dist/src/limrun-runtime-dependencies.js +1 -1
  173. package/dist/src/limrun.d.ts +28 -2
  174. package/dist/src/limrun.js +1 -1
  175. package/dist/src/linux.js +1 -1
  176. package/dist/src/load.js +1 -0
  177. package/dist/src/location-coordinates.js +1 -1
  178. package/dist/src/macos-facade.js +1 -1
  179. package/dist/src/managed-device-scope.js +1 -1
  180. package/dist/src/mechanics.js +16 -16
  181. package/dist/src/observation.js +1 -1
  182. package/dist/src/observe-until.js +1 -1
  183. package/dist/src/overlay.js +2 -2
  184. package/dist/src/owner-identity.js +3 -3
  185. package/dist/src/path-resolution.js +1 -1
  186. package/dist/src/perf-facade.js +1 -1
  187. package/dist/src/perf-runtime-operation-builder.js +1 -1
  188. package/dist/src/perf-runtime-plan.js +1 -1
  189. package/dist/src/perf-target.js +1 -1
  190. package/dist/src/perf.js +1 -1
  191. package/dist/src/physical-device-control.js +1 -1
  192. package/dist/src/platform-request-scope.js +1 -1
  193. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  194. package/dist/src/platform-runtime-app-log-process.js +1 -1
  195. package/dist/src/platform-runtime-host.js +1 -1
  196. package/dist/src/platform-runtime-managed-owner.js +1 -1
  197. package/dist/src/platform-runtime-open-target.js +1 -1
  198. package/dist/src/platform-runtime-operation-host.js +2 -2
  199. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  200. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  201. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  202. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  203. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  204. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  205. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  206. package/dist/src/platform-runtime-unavailable.js +1 -1
  207. package/dist/src/platform-runtime.js +1 -1
  208. package/dist/src/platform-runtime2.js +1 -1
  209. package/dist/src/plugins.d.ts +9 -0
  210. package/dist/src/plugins.js +1 -0
  211. package/dist/src/plugins2.js +2 -0
  212. package/dist/src/png-crop-bytes.js +1 -1
  213. package/dist/src/png-size.js +1 -1
  214. package/dist/src/png-worker-client.js +1 -1
  215. package/dist/src/png.js +1 -1
  216. package/dist/src/prepare-kind.js +1 -1
  217. package/dist/src/process.js +1 -1
  218. package/dist/src/project-runtime.js +1 -1
  219. package/dist/src/provider-credential-fingerprint.js +1 -0
  220. package/dist/src/provider-device-admission.js +1 -1
  221. package/dist/src/provider-device-runtimes.js +1 -0
  222. package/dist/src/provider-limrun-credentials.js +1 -0
  223. package/dist/src/provider-profile-fields.js +1 -0
  224. package/dist/src/provider-session-ownership.js +2 -2
  225. package/dist/src/provider-webdriver.js +2 -1
  226. package/dist/src/providers.js +1 -1
  227. package/dist/src/proxy.js +1 -1
  228. package/dist/src/quality-warnings.js +1 -1
  229. package/dist/src/react-native.js +1 -1
  230. package/dist/src/record-runtime.js +1 -1
  231. package/dist/src/record-trace.js +1 -1
  232. package/dist/src/recording.js +1 -1
  233. package/dist/src/rect-center.js +1 -1
  234. package/dist/src/register-builtins.js +1 -1
  235. package/dist/src/registry.js +39 -39
  236. package/dist/src/remote-config2.js +1 -1
  237. package/dist/src/replay-divergence.js +1 -1
  238. package/dist/src/replay.js +2 -2
  239. package/dist/src/reporting.js +5 -5
  240. package/dist/src/request-admission.js +1 -1
  241. package/dist/src/request-cancel.js +1 -1
  242. package/dist/src/request-cancellation.js +1 -1
  243. package/dist/src/request-runtime-binding.js +1 -1
  244. package/dist/src/result-serialization.js +1 -1
  245. package/dist/src/retry.js +1 -1
  246. package/dist/src/runner-artifact-manifest.js +1 -1
  247. package/dist/src/runner-cache-metadata.js +3 -3
  248. package/dist/src/runner-client.js +1 -1
  249. package/dist/src/runner-dev-tools-security.js +1 -1
  250. package/dist/src/runner-device-readiness.js +1 -1
  251. package/dist/src/runner-disposal.js +1 -1
  252. package/dist/src/runner-error-classification.js +2 -2
  253. package/dist/src/runner-exchange.js +1 -1
  254. package/dist/src/runner-operations-facade.js +1 -1
  255. package/dist/src/runner-session-types.js +1 -1
  256. package/dist/src/runner-start-budget.js +1 -1
  257. package/dist/src/runner.js +1 -1
  258. package/dist/src/runtime-admission.js +1 -1
  259. package/dist/src/runtime-transport-hints.js +1 -1
  260. package/dist/src/runtime.js +1 -1
  261. package/dist/src/runtime10.js +2 -2
  262. package/dist/src/runtime2.js +3 -3
  263. package/dist/src/runtime3.js +1 -1
  264. package/dist/src/runtime4.js +5 -5
  265. package/dist/src/runtime5.js +1 -1
  266. package/dist/src/runtime6.js +1 -1
  267. package/dist/src/runtime7.js +1 -1
  268. package/dist/src/runtime8.js +1 -1
  269. package/dist/src/runtime9.js +1 -1
  270. package/dist/src/screen-recording-admission-ledger.js +1 -1
  271. package/dist/src/screen-recording-completion.js +1 -1
  272. package/dist/src/screen-recording-options.js +1 -1
  273. package/dist/src/screen-recording-resource-recovery.js +1 -1
  274. package/dist/src/screen-recording-transport.js +1 -1
  275. package/dist/src/screenshot-density.js +1 -1
  276. package/dist/src/screenshot-image.js +1 -1
  277. package/dist/src/screenshot-result.js +1 -1
  278. package/dist/src/screenshot-runtime.js +1 -1
  279. package/dist/src/screenshot.js +1 -1
  280. package/dist/src/screenshot3.js +1 -1
  281. package/dist/src/script.js +1 -1
  282. package/dist/src/scroll-command.js +1 -1
  283. package/dist/src/scroll-gesture.js +1 -1
  284. package/dist/src/sdk-batch-runner.js +2 -2
  285. package/dist/src/sdk-batch.js +2 -2
  286. package/dist/src/sdk-contracts.d.ts +45 -2
  287. package/dist/src/sdk-contracts.js +2 -2
  288. package/dist/src/sdk-device.js +1 -1
  289. package/dist/src/sdk-io.js +1 -1
  290. package/dist/src/sdk-remote-config.js +1 -1
  291. package/dist/src/sdk-selectors.d.ts +33 -4
  292. package/dist/src/selection.js +0 -0
  293. package/dist/src/selector-runtime.js +1 -1
  294. package/dist/src/selectors.d.ts +2 -2
  295. package/dist/src/selectors.js +1 -1
  296. package/dist/src/server.js +1 -1
  297. package/dist/src/session-allocation.js +1 -1
  298. package/dist/src/session-artifact-paths.js +1 -1
  299. package/dist/src/session-repair-tombstone.js +1 -1
  300. package/dist/src/session-routing.js +1 -1
  301. package/dist/src/session-runtime-admission.js +1 -1
  302. package/dist/src/session-snapshot.js +1 -1
  303. package/dist/src/session-stream.js +27 -0
  304. package/dist/src/session.js +1 -1
  305. package/dist/src/session2.js +5 -5
  306. package/dist/src/settings.js +1 -1
  307. package/dist/src/settings2.js +1 -1
  308. package/dist/src/simctl-settings-facade.js +1 -0
  309. package/dist/src/simctl-settings.js +1 -0
  310. package/dist/src/simctl.js +1 -1
  311. package/dist/src/simulator.js +1 -1
  312. package/dist/src/snapshot-diagnostics.js +1 -1
  313. package/dist/src/snapshot-runtime-binding.js +1 -1
  314. package/dist/src/snapshot-runtime.js +1 -1
  315. package/dist/src/snapshot-state.js +1 -1
  316. package/dist/src/snapshot2.js +1 -1
  317. package/dist/src/snapshot3.js +1 -1
  318. package/dist/src/snapshot4.js +1 -1
  319. package/dist/src/src.js +1 -1
  320. package/dist/src/src7.js +1 -1
  321. package/dist/src/src8.js +2 -2
  322. package/dist/src/store.js +1 -0
  323. package/dist/src/string-enum.js +1 -1
  324. package/dist/src/surface-snapshot.js +1 -1
  325. package/dist/src/takeover.js +1 -1
  326. package/dist/src/target-evidence.js +1 -1
  327. package/dist/src/telemetry.js +1 -1
  328. package/dist/src/text-entry-focus.js +1 -1
  329. package/dist/src/tool-provider.js +1 -1
  330. package/dist/src/tool-provider2.js +1 -1
  331. package/dist/src/toolchain-probe.js +2 -2
  332. package/dist/src/touch-runtime.js +1 -1
  333. package/dist/src/touch-runtime2.js +1 -1
  334. package/dist/src/transport.js +2 -2
  335. package/dist/src/tv-remote.js +1 -1
  336. package/dist/src/type-text-runtime.js +1 -1
  337. package/dist/src/update-check.js +1 -1
  338. package/dist/src/vars.js +1 -1
  339. package/dist/src/verified-file.js +1 -1
  340. package/dist/src/version.js +1 -1
  341. package/dist/src/video.js +1 -1
  342. package/dist/src/viewport.js +1 -1
  343. package/dist/src/web.js +1 -1
  344. package/dist/src/web2.js +1 -1
  345. package/dist/src/webdriver-source.js +1 -1
  346. package/package.json +5 -1
  347. package/server.json +2 -2
  348. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.20.apk.sha256 +0 -1
  349. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk +0 -0
  350. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk.sha256 +0 -1
  351. package/dist/src/api.js +0 -3
  352. package/dist/src/daemon-process.js +0 -1
  353. package/dist/src/multitouch-support.js +0 -1
  354. package/dist/src/parameterized-recorded-fill.js +0 -1
  355. package/dist/src/runner-startup-transport.js +0 -1
  356. package/dist/src/runner-xctestrun.js +0 -1
  357. package/dist/src/session-store.js +0 -4
@@ -0,0 +1,27 @@
1
+ import{a as e,i as t,t as n}from"./rolldown-runtime.js";import{t as r}from"./undici.js";import{once as i}from"events";import a from"fs";import*as o from"zlib";import{Readable as s}from"stream";import*as c from"net";import l from"net";import u from"tls";import d from"os";import{domainToASCII as f}from"url";import p from"path";import*as m from"crypto";import h from"crypto";import{pipeline as g}from"stream/promises";import _ from"dns";var v=r();function y(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const b=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 x=class extends Error{},S=class e extends x{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 w({message:r,cause:b(n)});let a=n;return t===400?new E(t,a,r,i):t===401?new D(t,a,r,i):t===403?new O(t,a,r,i):t===404?new k(t,a,r,i):t===409?new A(t,a,r,i):t===422?new j(t,a,r,i):t===429?new M(t,a,r,i):t>=500?new N(t,a,r,i):new e(t,a,r,i)}},C=class extends S{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},w=class extends S{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},T=class extends w{constructor({message:e}={}){super({message:e??`Request timed out.`})}},E=class extends S{},D=class extends S{},O=class extends S{},k=class extends S{},A=class extends S{},j=class extends S{},M=class extends S{},N=class extends S{},P=n(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),F=n(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=P(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),I=n(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=F()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),ee=n(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),te=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=ee(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION);if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),L=n(((e,n)=>{let r=t(`tty`),i=t(`util`);e.init=d,e.log=c,e.formatArgs=o,e.save=l,e.load=u,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=te();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
2
+ `).join(`
3
+ `+a),e.push(i+`m+`+n.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+t+` `+e[0]}function s(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...t){return process.stderr.write(i.formatWithOptions(e.inspectOpts,...t)+`
4
+ `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}n.exports=F()(e);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
5
+ `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),R=n(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?I():L()})),z=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(e,"__esModule",{value:!0}),e.req=e.json=e.toBuffer=void 0;let a=i(t(`http`)),o=i(t(`https`));async function s(e){let t=0,n=[];for await(let r of e)t+=r.length,n.push(r);return Buffer.concat(n,t)}e.toBuffer=s;async function c(e){let t=(await s(e)).toString(`utf8`);try{return JSON.parse(t)}catch(e){let n=e;throw n.message+=` (input: ${t})`,n}}e.json=c;function l(e,t={}){let n=((typeof e==`string`?e:e.href).startsWith(`https:`)?o:a).request(e,t),r=new Promise((e,t)=>{n.once(`response`,e).once(`error`,t).end()});return n.then=r.then.bind(r),n}e.req=l})),ne=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=e&&e.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Agent=void 0;let o=i(t(`net`)),s=i(t(`http`)),c=t(`https`);a(z(),e);let l=Symbol(`AgentBaseInternalState`);e.Agent=class extends s.Agent{constructor(e){super(e),this[l]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==`boolean`)return e.secureEndpoint;if(typeof e.protocol==`string`)return e.protocol===`https:`}let{stack:t}=Error();return typeof t==`string`&&t.split(`
6
+ `).some(e=>e.indexOf(`(https.js:`)!==-1||e.indexOf(`node:https:`)!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],r=n.indexOf(t);r!==-1&&(n.splice(r,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?c.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let r={...t,secureEndpoint:this.isSecureEndpoint(t)},i=this.getName(r),a=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,r)).then(o=>{if(this.decrementSockets(i,a),o instanceof s.Agent)try{return o.addRequest(e,r)}catch(e){return n(e)}this[l].currentSocket=o,super.createSocket(e,t,n)},e=>{this.decrementSockets(i,a),n(e)})}createConnection(){let e=this[l].currentSocket;if(this[l].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[l].defaultPort??(this.protocol===`https:`?443:80)}set defaultPort(e){this[l]&&(this[l].defaultPort=e)}get protocol(){return this[l].protocol??(this.isSecureEndpoint()?`https:`:`http:`)}set protocol(e){this[l]&&(this[l].protocol=e)}}})),re=n((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.parseProxyResponse=void 0;let n=(0,t(R()).default)(`https-proxy-agent:parse-proxy-response`);function r(e){return new Promise((t,r)=>{let i=0,a=[];function o(){let t=e.read();t?u(t):e.once(`readable`,o)}function s(){e.removeListener(`end`,c),e.removeListener(`error`,l),e.removeListener(`readable`,o)}function c(){s(),n(`onend`),r(Error(`Proxy connection ended before receiving CONNECT response`))}function l(e){s(),n(`onerror %o`,e),r(e)}function u(c){a.push(c),i+=c.length;let l=Buffer.concat(a,i),u=l.indexOf(`\r
7
+ \r
8
+ `);if(u===-1){n(`have not received end of HTTP headers yet...`),o();return}let d=l.slice(0,u).toString(`ascii`).split(`\r
9
+ `),f=d.shift();if(!f)return e.destroy(),r(Error(`No header received from proxy CONNECT response`));let p=f.split(` `),m=+p[1],h=p.slice(2).join(` `),g={};for(let t of d){if(!t)continue;let n=t.indexOf(`:`);if(n===-1)return e.destroy(),r(Error(`Invalid header from proxy CONNECT response: "${t}"`));let i=t.slice(0,n).toLowerCase(),a=t.slice(n+1).trimStart(),o=g[i];typeof o==`string`?g[i]=[o,a]:Array.isArray(o)?o.push(a):g[i]=a}n(`got proxy server response: %o %o`,f,g),s(),t({connect:{statusCode:m,statusText:h,headers:g},buffered:l})}e.on(`error`,l),e.on(`end`,c),o()})}e.parseProxyResponse=r})),B=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.HttpsProxyAgent=void 0;let o=i(t(`net`)),s=i(t(`tls`)),c=a(t(`assert`)),l=a(R()),u=ne(),d=t(`url`),f=re(),p=(0,l.default)(`https-proxy-agent`),m=e=>e.servername===void 0&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e;var h=class extends u.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e==`string`?new d.URL(e):e,this.proxyHeaders=t?.headers??{},p(`Creating new HttpsProxyAgent instance: %o`,this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,``),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol===`https:`?443:80;this.connectOpts={ALPNProtocols:[`http/1.1`],...t?_(t,`headers`):null,host:n,port:r}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw TypeError(`No "host" provided`);let r;n.protocol===`https:`?(p("Creating `tls.Socket`: %o",this.connectOpts),r=s.connect(m(this.connectOpts))):(p("Creating `net.Socket`: %o",this.connectOpts),r=o.connect(this.connectOpts));let i=typeof this.proxyHeaders==`function`?this.proxyHeaders():{...this.proxyHeaders},a=o.isIPv6(t.host)?`[${t.host}]`:t.host,l=`CONNECT ${a}:${t.port} HTTP/1.1\r\n`;if(n.username||n.password){let e=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i[`Proxy-Authorization`]=`Basic ${Buffer.from(e).toString(`base64`)}`}i.Host=`${a}:${t.port}`,i[`Proxy-Connection`]||=this.keepAlive?`Keep-Alive`:`close`;for(let e of Object.keys(i))l+=`${e}: ${i[e]}\r\n`;let u=(0,f.parseProxyResponse)(r);r.write(`${l}\r\n`);let{connect:d,buffered:h}=await u;if(e.emit(`proxyConnect`,d),this.emit(`proxyConnect`,d,e),d.statusCode===200)return e.once(`socket`,g),t.secureEndpoint?(p(`Upgrading socket connection to TLS`),s.connect({..._(m(t),`host`,`path`,`port`),socket:r})):r;r.destroy();let v=new o.Socket({writable:!1});return v.readable=!0,e.once(`socket`,e=>{p(`Replaying proxy buffer for failed request`),(0,c.default)(e.listenerCount(`data`)>0),e.push(h),e.push(null)}),v}};h.protocols=[`http`,`https`],e.HttpsProxyAgent=h;function g(e){e.resume()}function _(e,...t){let n={},r;for(r in e)t.includes(r)||(n[r]=e[r]);return n}}))(),ie={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function ae(e){try{return new URL(e)}catch{return null}}function oe(e){var t=(typeof e==`string`?ae(e):e)||{},n=t.protocol,r=t.host,i=t.port;if(typeof r!=`string`||!r||typeof n!=`string`||(n=n.split(`:`,1)[0],r=r.replace(/:\d*$/,``),i=parseInt(i)||ie[n]||0,!se(r,i)))return``;var a=ce(n+`_proxy`)||ce(`all_proxy`);return a&&a.indexOf(`://`)===-1&&(a=n+`://`+a),a}function se(e,t){var n=ce(`no_proxy`).toLowerCase();return!n||n!==`*`&&n.split(/[,\s]/).every(function(n){if(!n)return!0;var r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?parseInt(r[2]):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.charAt(0)===`*`&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function ce(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||``}const V={headersTimeout:36e5,bodyTimeout:36e5},le=65536,H=new class{constructor(){this.websocketAgents=new Map,this.fetch=async(e,t)=>this.hasProxyEnv()?fetch(e,{...t??{},dispatcher:this.getEnvHttpProxyAgent()}):fetch(e,t),this.fetchLongRequest=async(e,t)=>(this.longRequestDispatcher??=new v.EnvHttpProxyAgent(V),fetch(e,{...t??{},dispatcher:this.longRequestDispatcher}))}getWebSocketAgent(e){if(!this.hasProxyEnv())return;let t=oe(this.getWebSocketProxyLookupUrl(e));if(!t)return;let n=this.websocketAgents.get(t);if(!n){let e=new B.HttpsProxyAgent(t);this.websocketAgents.set(t,e),n=e}return n}connectTcp(e){let t=e.proxyLookupHost??e.host,n=oe(`${e.proxyLookupProtocol}//${ue(t,e.port)}`);return n?W(n,e):U(e)}getEnvHttpProxyAgent(){return this.envHttpProxyAgent??=new v.EnvHttpProxyAgent,this.envHttpProxyAgent}hasProxyEnv(){if(typeof process>`u`||!process.versions?.node)return!1;let e=process.env;return!!(e.http_proxy||e.HTTP_PROXY||e.https_proxy||e.HTTPS_PROXY)}getWebSocketProxyLookupUrl(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.toString()}};function U(e){let t=Date.now();return new Promise((n,r)=>{let i=!1,a=l.createConnection({host:e.host,port:e.port,allowHalfOpen:!0}),o=setTimeout(()=>{c(G(`connection to ${ue(e.host,e.port)} timed out`,`ETIMEDOUT`))},e.timeoutMs);o.unref();let s=()=>{clearTimeout(o),a.removeListener(`connect`,d),a.removeListener(`error`,c),e.signal?.removeEventListener(`abort`,u)},c=e=>{i||(i=!0,s(),a.destroy(),r(e))},u=()=>c(G(`TCP connection cancelled`,`ECANCELED`)),d=()=>{i||(i=!0,a.pause(),s(),n({socket:a,connectMs:Date.now()-t,...a.remoteAddress===void 0?{}:{remoteAddress:a.remoteAddress}}))};a.once(`connect`,d),a.once(`error`,c),e.signal?.aborted?u():e.signal?.addEventListener(`abort`,u,{once:!0})})}function W(e,t){let n=Date.now();return new Promise((r,i)=>{let a=!1,o=Buffer.alloc(0),s;try{s=new URL(e)}catch{i(G(`invalid proxy URL: ${e}`,`EPROXY`));return}if(s.protocol!==`http:`&&s.protocol!==`https:`){i(G(`unsupported proxy protocol ${s.protocol}`,`EPROXY`));return}let c=s.port?Number(s.port):s.protocol===`https:`?443:80,d=de(s.hostname),f=s.protocol===`https:`?u.connect({host:d,port:c,rejectUnauthorized:!0,...l.isIP(d)?{}:{servername:d},ALPNProtocols:[`http/1.1`]}):l.createConnection({host:d,port:c,allowHalfOpen:!0});f.allowHalfOpen=!0;let p=s.protocol===`https:`?`secureConnect`:`connect`,m=setTimeout(()=>{g(G(`proxy connection to ${ue(t.host,t.port)} timed out`,`ETIMEDOUT`))},t.timeoutMs);m.unref();let h=()=>{clearTimeout(m),f.removeListener(p,y),f.removeListener(`data`,b),f.removeListener(`end`,v),f.removeListener(`close`,v),f.removeListener(`error`,g),t.signal?.removeEventListener(`abort`,_)},g=e=>{a||(a=!0,h(),f.destroy(),i(e))},_=()=>g(G(`proxy connection cancelled`,`ECANCELED`)),v=()=>g(G(`proxy closed before completing CONNECT`,`ECONNRESET`)),y=()=>{let e=ue(t.host,t.port),n=[`CONNECT ${e} HTTP/1.1`,`Host: ${e}`,`Proxy-Connection: Keep-Alive`];if(s.username||s.password){let e=fe(s.username),t=fe(s.password);n.push(`Proxy-Authorization: Basic ${Buffer.from(`${e}:${t}`,`utf8`).toString(`base64`)}`)}f.write(`${n.join(`\r
10
+ `)}\r\n\r\n`)},b=e=>{o=Buffer.concat([o,e]);let i=o.indexOf(`\r
11
+ \r
12
+ `);if(i<0){o.length>le&&g(G(`proxy CONNECT response headers exceeded 65536 bytes`,`EPROXY`));return}if(i+4>le){g(G(`proxy CONNECT response headers exceeded 65536 bytes`,`EPROXY`));return}let s=o.indexOf(`\r
13
+ `),c=o.subarray(0,s<0?i:s).toString(`latin1`),l=/^HTTP\/1\.[01] ([0-9]{3})(?: |$)/.exec(c);if(!l){g(G(`invalid proxy CONNECT response: ${c}`,`EPROXY`));return}let u=Number(l[1]);if(u<200||u>=300){g(G(`proxy CONNECT failed with status ${u}`,u===407?`EPROXYAUTH`:`EPROXYCONNECT`));return}a=!0,f.pause(),h();let d=o.subarray(i+4);d.length>0&&f.unshift(d),r({socket:f,connectMs:Date.now()-n,remoteAddress:t.host})};f.once(p,y),f.on(`data`,b),f.once(`end`,v),f.once(`close`,v),f.once(`error`,g),t.signal?.aborted?_():t.signal?.addEventListener(`abort`,_,{once:!0})})}function ue(e,t){return`${l.isIP(e)===6?`[${e}]`:e}:${t}`}function de(e){return e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function fe(e){try{return decodeURIComponent(e)}catch{return e}}function G(e,t){return Object.assign(Error(e),{code:t})}var pe=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(`
14
+ `)===-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(`
15
+ `,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(`
16
+ `,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(`
17
+ `,t);continue}m=h===0?a:`${m}
18
+ ${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(`
19
+ `,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
20
+ `,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}
21
+ ${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);r.includes(`\0`)||(p=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}
22
+ ${n}`,h++;break;case`id`:n.includes(`\0`)||(p=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 me=e(n((e=>{Object.defineProperty(e,"__esModule",{value:!0});var n=t(`node:stream`),r=pe();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:P,onRetry:F,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]:j,get lastEventId(){return T},get url(){return C},get readyState(){return O}};function k(){S||=(O=i,w=new AbortController,m(h,I()).then(N).catch(e=>{S=null,!(e.name===`AbortError`||e.type===`aborted`||w.signal.aborted)&&M()}))}function A(){O=o,w.abort(),x.reset(),clearTimeout(D),v.forEach(e=>e())}function j(){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 M(){p({delay:E}),!w.signal.aborted&&(O=i,D=setTimeout(k,E))}async function N(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(),M(),f())}while(l)}function P(e){typeof e.id==`string`&&(T=e.id),b(e)}function F(e){E=e}function I(){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;function he(e,t){return async(n,r)=>{try{return await e(n,r)}catch(e){throw t(e),e}}}const ge={healthyConnectionMs:15e3,giveUpAfterMs:3e5};var _e=class extends Error{},ve=class extends Error{},ye=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()}}},be=class{constructor(e,t){this.command=new ye,this.stdout=new ye,this.stderr=new ye,this.exitListeners=[],this.abortController=new AbortController,this.sseConnection=null,this.killed=!1,this.streamDeadSince=0,this.detached=!1,this.appStoreEvent=null,this.playstoreEvent=null,this.xctestCases=[],this.xctestSummary=null,this.lastSeenEventId=-1,this.options=t,this.log=t.log??(()=>{}),this.startedPromise=new Promise((e,t)=>{this.resolveStarted=e,this.rejectStarted=t}),this.startedPromise.catch(()=>{}),this.resultPromise=e instanceof Promise?e.then(e=>this.run(e)):this.run(e),this.resultPromise.catch(e=>this.rejectStarted(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}detach(){return this.detached=!0,this.resultPromise.catch(()=>{}),this.startedPromise}async kill(){if(this.killed=!0,this.abortController.abort(),this.sseConnection&&=(this.sseConnection.close(),null),!this.execId){this.log(`warn`,`Failed to cancel execution: execId is not set`);return}try{await H.fetch(`${this.options.apiUrl}/exec/${this.execId}/cancel`,{method:`POST`,headers:{Authorization:`Bearer ${this.options.token}`}}),this.log(`info`,`Execution cancelled`)}catch(e){this.log(`warn`,`Failed to cancel execution: ${e}`)}}async run(e){let{log:t}=this,{apiUrl:n,token:r}=this.options,i={...e};`additionalMetadata`in i&&delete i.additionalMetadata;let a;try{a=await H.fetch(`${n}/exec`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify(i),signal:this.abortController.signal})}catch(e){if(this.killed){this.rejectStarted(Error(`Execution cancelled before it started`)),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(),t=e;try{t=JSON.parse(e).message||e}catch{}throw Error(`exec failed: ${a.status} ${t}`)}let o=await a.json();if(this.execId=o.execId,t(`debug`,`Execution started: ${this.execId}`),this.resolveStarted(this.execId),this.detached)return this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`),new Promise(()=>{});let s=`${n}/exec/${this.execId}/events`,c=36e5;e.command===`xcodebuild`&&e.testflight&&(c+=(Math.max(0,e.testflight.waitTimeoutSeconds??0)+900)*1e3),e.command===`xcodebuild`&&e.xcodebuild?.action===`build-for-testing`&&(c+=72e5),e.command===`run`&&(c=(Math.max(1,e.timeoutSeconds??3600)+60)*1e3);let l,u=!1,d,f;try{l=await Promise.race([this.connectSSE(s),new Promise((e,t)=>{f=setTimeout(()=>t(Error(`SSE completion timeout`)),c)})])}catch(e){if(this.killed)t(`debug`,`Execution killed`),l=-1;else{let n=e instanceof Error?e.message:String(e),r=this.streamDeadSince>0?Date.now()-this.streamDeadSince:0,i=e instanceof ve?`stream-closed`:e instanceof _e?`stream-lost`:`timeout`;i===`timeout`&&r>0&&(i=`stream-lost`,n=`the completion budget expired while the event stream had already been failing for ${Math.round(r/1e3)}s; the execution may no longer exist (instance deleted or record expired)`),d={reason:i,message:n},t(`warn`,n),l=1,u=!0}}finally{clearTimeout(f),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(l);let p=l===0?`SUCCEEDED`:l===-1?`CANCELLED`:`FAILED`,m={exitCode:l,execId:this.execId,status:p,...`additionalMetadata`in e?e.additionalMetadata??{}:{},...this.appStoreEvent?{appstore:this.appStoreEvent}:{},...this.playstoreEvent?{playstore:this.playstoreEvent}:{},...this.xctestCases.length>0||this.xctestSummary?{xctest:{cases:this.xctestCases,...this.xctestSummary?{summary:this.xctestSummary}:{}}}:{},...u?{timedOut:u}:{},...d?{incomplete:d}:{}};return this.log(`debug`,`Execution finished: ${m.status} (exit ${m.exitCode})`),m}connectSSE(e){return new Promise((t,n)=>{let r=this.abortController.signal;if(r.aborted){n(Error(`killed`));return}let i=!1,a=0,o=0,s=0,c=!1,l=!1,u,d=()=>{h.close(),r.removeEventListener(`abort`,m)},f=e=>{i||(i=!0,d(),t(e))},p=e=>{i||(i=!0,d(),n(e))},m=()=>p(Error(`killed`)),h=me({url:e,fetch:he(async(t,n)=>{let r=await H.fetch(t,n);return r.status===204?p(new ve(`event stream to ${e} was closed by the server (HTTP 204)`)):r.ok||(u=Error(`server answered HTTP ${r.status}`)),l=r.ok,r},e=>{u=e instanceof Error?e:Error(String(e))}),headers:{Authorization:`Bearer ${this.options.token}`},onConnect:()=>{a=Date.now()},onComment:()=>{c=!0},onScheduleReconnect:()=>{if(i||this.killed)return;let t=Date.now(),n=performance.now(),r=a>0?t-a:0;a=0,this.streamDeadSince>0&&o>0&&t-o-(n-s)>3e4&&(this.streamDeadSince=t),o=t,s=n;let d=c||l&&r>=ge.healthyConnectionMs;if(c=!1,l=!1,d){this.streamDeadSince=0,u=void 0;return}if(this.streamDeadSince===0){this.streamDeadSince=t,this.log(`warn`,`SSE disconnected; reconnecting`);return}if(t-this.streamDeadSince>=ge.giveUpAfterMs){let n=Math.round((t-this.streamDeadSince)/1e3),r=u?`; last error: ${u.message}`:``;p(new _e(`event stream to ${e} kept failing for ${n}s without delivering events${r}; the execution may no longer exist (instance deleted or record expired)`))}},onMessage:e=>{this.streamDeadSince=0,c=!0,u=void 0;let t=e.id===void 0?NaN:parseInt(e.id,10);if(!Number.isNaN(t)){if(t<=this.lastSeenEventId)return;this.lastSeenEventId=t}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===`testflight`)try{this.appStoreEvent=JSON.parse(n)}catch{this.appStoreEvent={state:`unknown`},this.log(`warn`,`SSE testflight event has invalid data: ${n}`)}else if(r===`playstore`)try{this.playstoreEvent=JSON.parse(n)}catch{this.playstoreEvent={state:`unknown`},this.log(`warn`,`SSE playstore event has invalid data: ${n}`)}else if(r===`xctest`){let e;try{let t=JSON.parse(n);t?.type===`case`?(this.xctestCases.push(t),e=t):t?.type===`summary`?(this.xctestSummary=t,e=t):this.log(`debug`,`SSE xctest event of unknown type ignored: ${n}`)}catch{this.log(`warn`,`SSE xctest event has invalid data: ${n}`)}if(e)try{this.options.onXctestEvent?.(e)}catch(e){this.log(`warn`,`onXctestEvent callback threw: ${String(e)}`)}}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`,`Execution completed via SSE: exitCode=${e}`),f(e)}}});this.sseConnection=h,r.addEventListener(`abort`,m,{once:!0})})}};function xe(e,t){return new be(e,t)}const Se=(e,t)=>{};async function Ce(e){let t=e.log??Se,n=e.rootPath;if(!a.existsSync(n))throw Error(`watchFolderTree root does not exist: ${n}`);let r=a.watch(n,{recursive:!0},(t,n)=>{if(!n)return;let r=n.split(p.sep).join(`/`);e.ignoreFn(r)||e.onChange(r?`change:${r}`:`change`)});return t(`debug`,`watchFolderTree(recursive): ${n}`),{close:()=>r.close()}}function we(e,t,n,r){let i=`${e} failed: ${t}${n?` ${n}`:``}`;return t===404?new k(404,{message:i},void 0,r):Object.assign(Error(i),{status:t,body:n})}function Te(e,t){return e instanceof Error&&e.status===t}const Ee=67108864,De=(e,t)=>{};function K(){return Date.now()}function Oe(e){return e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(2)}s`}function ke(e){if(e<1024)return`${e}B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)}KiB`;let n=t/1024;return n<1024?`${n.toFixed(1)}MiB`:`${(n/1024).toFixed(2)}GiB`}function Ae(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function je(e){let t=e;return t?.code===`ENOENT`||t?.cause?.code===`ENOENT`}function Me(){let e=d.cpus()?.length??1;return Math.min(4,Math.max(1,e-1))}async function Ne(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)return;let a=e[t];r[t]=await n(a)}});return await Promise.all(a),r}function Pe(e){return`${e}/sync`}function Fe(e){let t=Buffer.allocUnsafe(4);return t.writeUInt32BE(e>>>0,0),t}async function Ie(e,t,n,r){let i=Pe(e.apiUrl),c={"Content-Type":`application/octet-stream`,Authorization:`Bearer ${e.token}`},l=Buffer.from(JSON.stringify(t),`utf-8`),u=Buffer.concat([Fe(l.length),l]);async function*d(){yield u;for(let e of n){let t=await a.promises.open(e.filePath,`r`);try{let e=await t.stat(),n=0;for(;n<e.size;){let r=Math.min(262144,e.size-n),i=Buffer.allocUnsafe(r),{bytesRead:a}=await t.read(i,0,r,n);if(a<=0)break;n+=a,yield i.subarray(0,a)}}finally{await t.close()}}}let f=s.from(d()),p;if(r===`zstd`){let e=o.createZstdCompress;if(!e)throw Error(`zstd compression not available in this Node.js version`);p=f.pipe(e({level:3})),c[`Content-Encoding`]=`zstd`}else if(r===`gzip`){let e=o.createGzip;if(!e)throw Error(`gzip compression not available in this Node.js version`);p=f.pipe(e({level:6})),c[`Content-Encoding`]=`gzip`}else p=f;let m=new AbortController,h,g=e=>{h=e,m.abort()};f.on(`error`,g),p.on(`error`,g);let _=await H.fetch(i,{method:`POST`,headers:c,body:p,duplex:`half`,signal:m.signal}).catch(e=>{throw h||e}),v=await _.text();if(!_.ok)throw we(`folder-sync http`,_.status,v,_.headers);return JSON.parse(v)}async function Le(e){return await new Promise((t,n)=>{let r=h.createHash(`sha256`),i=a.createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`error`,n),i.on(`end`,()=>t(r.digest(`hex`)))})}function Re(e,t){if(t.includes(`\\`))throw Error(`symlink ${e} -> ${t} target contains a backslash, which the daemon rejects; remove the link or pass --ignore to skip it`);let n=p.posix.normalize(p.posix.join(p.posix.dirname(e),t));if(n===`.`||n===`..`||n.startsWith(`../`))throw Error(`symlink ${e} -> ${t} points outside the sync root; run the sync from the repo root that contains the target, remove the link, or pass --ignore to skip it`)}async function ze(e,t,n,r){let i=p.resolve(e),o=await a.promises.stat(i);if(o.isFile()){let e=p.basename(i);return t(e)?[]:[{path:e,size:o.size,sha256:await Le(i),absPath:i,mode:o.mode&4095}]}let s=[],c=[i];for(;c.length;){let e=c.pop(),o=await a.promises.readdir(e,{withFileTypes:!0});for(let l of o){let o=p.join(e,l.name),u=p.relative(i,o).split(p.sep).join(`/`);if(l.isDirectory()){if(t(u+`/`))continue;c.push(o);continue}if(l.isSymbolicLink()){if(!n||t(u)||t(u+`/`))continue;let e=(await a.promises.readlink(o)).split(p.sep).join(`/`);if(p.posix.isAbsolute(e)||p.win32.isAbsolute(e)){r?.(`warn`,`skipping symlink ${u} -> ${e}: absolute targets cannot resolve remotely`);continue}Re(u,e);let i=h.createHash(`sha256`).update(e).digest(`hex`);s.push({path:u,size:Buffer.byteLength(e),sha256:i,absPath:o,mode:0,linkTarget:e});continue}if(!l.isFile()||t(u))continue;let d=await a.promises.stat(o),f=await Le(o),m=d.mode&4095;s.push({path:u,size:d.size,sha256:f,absPath:o,mode:m})}}return s.sort((e,t)=>e.path.localeCompare(t.path)),s}async function Be(e){if(!e||e.length===0)return[];let t=[];for(let n of e){let e=p.posix.normalize(n.remotePath),r=p.resolve(n.localPath),i=await a.promises.stat(r);if(!i.isFile())throw Error(`additional file localPath must be a file: ${n.localPath}`);let o=await Le(r);t.push({path:e,size:i.size,sha256:o,absPath:r,mode:i.mode&4095})}return t.sort((e,t)=>e.path.localeCompare(t.path)),t}let Ve=null;async function He(){return Ve||=(async()=>await import(`./limrun-delta-sync-omitted.js`))().catch(e=>{throw Ve=null,e}),await Ve}async function*Ue(e){for await(let t of a.createReadStream(e,{highWaterMark:1048576}))t instanceof Uint8Array?yield t:yield Buffer.from(t)}function We(e){return Math.max(0,Math.ceil(e*.9)-1)}async function Ge(e,t,n,r){let o=await He(),s=await a.promises.open(e,`r`),c=(await s.stat()).size,l=a.createWriteStream(n),u=0,d=!1,f={size:c,read:async(e,t)=>{let{bytesRead:n}=await s.read(t,0,t.byteLength,e);return n}};try{for await(let e of o.encode(Ue(t),f)){if(u+=e.byteLength,u>r){d=!0;break}l.write(e)||await i(l,`drain`)}l.end(),await i(l,`finish`)}catch(e){throw l.destroy(),await a.promises.rm(n,{force:!0}),e}finally{await s.close()}return d?(await a.promises.rm(n,{force:!0}),-1):u}async function Ke(e,t,n,r,i){let o=t.split(`/`),s=p.join(e,o.join(p.sep));if(i){let t=e;for(let e=0;e<o.length-1;e++){if(t=p.join(t,o[e]),i.has(t))continue;let n=await a.promises.lstat(t).catch(()=>null);n&&!n.isDirectory()?await a.promises.rm(t,{recursive:!0,force:!0}):n&&i.add(t)}}await a.promises.mkdir(p.dirname(s),{recursive:!0});let c=await a.promises.lstat(s).catch(()=>null);if(c&&(c.isSymbolicLink()||c.isDirectory()||r!==void 0)&&await a.promises.rm(s,{recursive:!0,force:!0}),r!==void 0){await a.promises.symlink(r,s);return}await a.promises.copyFile(n,s)}function qe(e,t){return p.join(e,t.split(`/`).join(p.sep))}async function Je(e,t){let n=(e,n)=>{(t.log??De)(e,`syncFolder: ${n}`)};n(`debug`,`setup ${e} watch=${t.watch} basisCacheDir=${t.basisCacheDir}`);let r=async n=>{let r=K(),i=await Ye(e,t,n);return t.onSyncComplete?.({bytesSent:i.bytesSent??0,durationMs:K()-r,...i.installedAppPath===void 0?{}:{installedAppPath:i.installedAppPath},...i.installedBundleId===void 0?{}:{installedBundleId:i.installedBundleId}}),i};if(!t.watch)return await r();let i=await r(`startup`),o=!1,s=!1,c=!1,l,u,d=async e=>{o=!0;try{await r(e)}finally{o=!1,s&&!c&&(s=!1,f(`queued-changes`))}},f=e=>{if(c)return;if(o){s=!0;return}let t=d(e).catch(e=>{n(`error`,`syncFolder: watch sync failed: ${e instanceof Error?e.message:String(e)}`)});u=t,t.finally(()=>{u===t&&(u=void 0)})},m=e=>{c||(l&&clearTimeout(l),l=setTimeout(()=>{l=void 0,f(e)},500))},h=await a.promises.stat(e),g;if(h.isFile()){let t=p.basename(e),n=p.dirname(e),r=a.watch(n,(e,n)=>{!n||n.toString()!==t||m(`change:${t}`)});g={close:()=>r.close()}}else g=await Ce({rootPath:e,log:n,ignoreFn:t.ignoreFn,onChange:e=>{m(e)}});return{...i,stopWatching:async()=>{c=!0,s=!1,l&&=(clearTimeout(l),void 0),g.close(),await u}}}async function Ye(e,t,n,r=0){let i=K(),s=t.log??De,c=(e,t)=>s(e,`syncFolder: ${t}`),l=await ze(e,t.ignoreFn,t.syncSymlinks??!1,c),u=await Be(t.additionalFiles),f=[...l,...u].sort((e,t)=>e.path.localeCompare(t.path)),m=new Map(f.map(e=>[e.path,e])),h=Ae(`sync`),g=p.basename(p.resolve(e)),_=t.compression??(o.createZstdCompress?`zstd`:`gzip`);await a.promises.mkdir(t.basisCacheDir,{recursive:!0});let v=0,y=0,b=0,x=0,S=Me(),C=[];for(let e of f){let n=qe(t.basisCacheDir,e.path),r=await a.promises.lstat(n).catch(()=>null);if(!r){C.push(e);continue}if(e.linkTarget!==void 0){if(!r.isSymbolicLink()){C.push(e);continue}(await a.promises.readlink(n)).split(p.sep).join(`/`)!==e.linkTarget&&C.push(e);continue}if(!r.isFile()){C.push(e);continue}await Le(n)!==e.sha256.toLowerCase()&&C.push(e)}let w=C.filter(e=>e.linkTarget===void 0),T=new Set(C.map(e=>e.path)),E=await Ne(w,S,async e=>{let n=qe(t.basisCacheDir,e.path);if((e.size>=65536?await a.promises.lstat(n).catch(()=>null):null)?.isFile()){let t=await Le(n),r=await a.promises.mkdtemp(p.join(d.tmpdir(),`limulator-xdelta3-`)),i=p.join(r,`patch.xdelta3`),o=K(),s=await Ge(n,e.absPath,i,We(e.size)),l=K()-o;if(x+=l,s>=0)return c(`debug`,`delta(file): ${p.posix.basename(e.path)} patchSize=${s} encode=${Oe(l)}`),y+=s,{payload:{kind:`delta`,path:e.path,basisSha256:t.toLowerCase(),targetSha256:e.sha256.toLowerCase(),length:s},filePath:i,cleanupDir:r};try{await a.promises.rm(r,{recursive:!0,force:!0})}catch{}}return c(`debug`,`full(file): ${e.path} size=${e.size}`),e.size>=Ee&&c(`debug`,`uploading large file ${e.path} (${ke(e.size)})`),v+=e.size,{payload:{kind:`full`,path:e.path,targetSha256:e.sha256.toLowerCase(),length:e.size},filePath:e.absPath}}),D={id:h,rootName:g,install:t.install,...t.launchMode?{launchMode:t.launchMode}:{},files:f.map(e=>({path:e.path,size:e.size,sha256:e.sha256.toLowerCase(),...e.linkTarget===void 0?{mode:e.mode}:{link:e.linkTarget}})),payloads:E.map(e=>e.payload)},O=E.some(e=>e.payload.kind===`delta`),k=t.compression??(O?`identity`:_);c(`debug`,`sync started files=${f.length}${n?` reason=${n}`:``} compression=${k}`);let A=K(),j;try{j=await Ie(t,D,E.map(e=>({filePath:e.filePath})),k)}catch(i){if(r<1&&je(i))return c(`warn`,`sync retrying after missing file during upload (ENOENT)`),await Ye(e,t,n,r+1);throw i}if(b+=K()-A,!j.ok&&j.needFull&&j.needFull.length>0){let e=new Set(j.needFull),n=[...e].filter(e=>m.get(e)?.linkTarget!==void 0);if(n.length>0)throw Error(`this instance's build daemon does not support symlinks yet (needs an updated limbuild); recreate the instance or retry later. Paths: ${n.join(`, `)}`);let r=[];for(let t of e){let e=m.get(t);e&&(e.size>=Ee&&c(`debug`,`uploading large file ${e.path} (${ke(e.size)})`),v+=e.size,T.add(e.path),r.push({payload:{kind:`full`,path:e.path,targetSha256:e.sha256.toLowerCase(),length:e.size},filePath:e.absPath}))}if(r.length>0){c(`debug`,`daemon requested a full upload for ${r.length} files (no matching basis); retrying once`);let e={...D,id:Ae(`sync`),payloads:r.map(e=>e.payload)},n=K();j=await Ie(t,e,r.map(e=>({filePath:e.filePath})),t.compression??_),b+=K()-n}}await Promise.all(E.map(async e=>{if(e.cleanupDir)try{await a.promises.rm(e.cleanupDir,{recursive:!0,force:!0})}catch{}}));let M=K()-i;if(!j.ok)throw Error(j.error??`sync failed`);let N=K()-i,P=v+y;c(`debug`,`sync complete: files=${f.length} changed=${T.size} sent=${ke(P)} in ${Oe(N)}`),c(`debug`,`sync timing syncWork=${Oe(M)} total=${Oe(N)}`);let F={bytesSent:P};j.installedAppPath&&(F.installedAppPath=j.installedAppPath),j.bundleId&&(F.installedBundleId=j.bundleId);let I=t.syncSymlinks?new Set:void 0;for(let e of f)await Ke(t.basisCacheDir,e.path,e.absPath,e.linkTarget,I);return F}var Xe=n(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),Ze=n(((e,n)=>{let{EMPTY_BUFFER:r}=Xe(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(n.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=t(`bufferutil`);n.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},n.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),Qe=n(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),$e=n(((e,n)=>{let r=t(`zlib`),i=Ze(),a=Qe(),{kStatusCode:o}=Xe(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.exports=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&(typeof e.client_max_window_bits==`number`?t.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),et=n(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=Xe(),a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=t(`utf-8-validate`);n.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),tt=n(((e,n)=>{let{Writable:r}=t(`stream`),i=$e(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Xe(),{concat:l,toArrayBuffer:u,unmask:d}=Ze(),{isValidStatusCode:f,isValidUTF8:p}=et(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new m(t.buffer,t.byteOffset+e,t.length-e),new m(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new m(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[i.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._state=this._masked?3:4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=o;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&d(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?l(n,t):this._binaryType===`arraybuffer`?u(l(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=l(n,t);if(!this._skipUTF8Validation&&!p(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[s]=r,a}}})),nt=n(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=$e(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=Xe(),{isBlob:u,isValidStatusCode:d}=et(),{mask:f,toBuffer:p}=Ze(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8192,_,v=g;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);y(this,e,i);return}this._bufferedBytes-=r[m],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function y(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function b(e,t,n){y(e,t,n),e.onerror(t)}})),rt=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Xe(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean!==void 0&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),it=n(((e,t)=>{let{tokenChars:n}=et();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`)}else if(l===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s){if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),at=n(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=$e(),m=tt(),h=nt(),{isBlob:g}=et(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=Xe(),{EventTarget:{addEventListener:E,removeEventListener:D}}=rt(),{format:O,parse:k}=it(),{toBuffer:A}=Ze(),j=Symbol(`kAborted`),M=[8,13],N=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],P=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var F=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),I(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,ne),i.on(`drain`,re),i.on(`error`,B),i.on(`message`,ae),i.on(`ping`,oe),i.on(`pong`,se),a.onerror=V,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,H),t.on(`data`,U),t.on(`end`,W),t.on(`error`,ue),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){R(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),le(this)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){z(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){z(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){z(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){R(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(F,"CONNECTING",{enumerable:!0,value:N.indexOf(`CONNECTING`)}),Object.defineProperty(F.prototype,"CONNECTING",{enumerable:!0,value:N.indexOf(`CONNECTING`)}),Object.defineProperty(F,"OPEN",{enumerable:!0,value:N.indexOf(`OPEN`)}),Object.defineProperty(F.prototype,"OPEN",{enumerable:!0,value:N.indexOf(`OPEN`)}),Object.defineProperty(F,"CLOSING",{enumerable:!0,value:N.indexOf(`CLOSING`)}),Object.defineProperty(F.prototype,"CLOSING",{enumerable:!0,value:N.indexOf(`CLOSING`)}),Object.defineProperty(F,"CLOSED",{enumerable:!0,value:N.indexOf(`CLOSED`)}),Object.defineProperty(F.prototype,"CLOSED",{enumerable:!0,value:N.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(F.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(F.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),F.prototype.addEventListener=E,F.prototype.removeEventListener=D,n.exports=F;function I(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:M[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!M.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${M.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ee(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,x;if(o.createConnection=o.createConnection||(u?L:te),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=O({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!P.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=_(o);o.timeout&&S.on(`timeout`,()=>{R(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[j]||(S=e._req=null,ee(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){R(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{ee(e,SyntaxError(`Invalid URL: ${a}`));return}I(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||R(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==F.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){R(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){R(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){R(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){R(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=k(u)}catch{R(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){R(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{R(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ee(e,t){e._readyState=F.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function te(e){return e.path=e.socketPath,o.connect(e)}function L(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function R(e,t,n){e._readyState=F.CLOSING;let r=Error(n);Error.captureStackTrace(r,R),t.setHeader?(t[j]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ee,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function z(e,t,n){if(t){let n=g(t)?t.size:A(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${N[e.readyState]})`);process.nextTick(n,t)}}function ne(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[w]!==void 0&&(n._socket.removeListener(`data`,U),process.nextTick(ce,n._socket),e===1005?n.close():n.close(e,t))}function re(){let e=this[w];e.isPaused||e._socket.resume()}function B(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,U),process.nextTick(ce,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ie(){this[w].emitClose()}function ae(e,t){this[w].emit(`message`,e,t)}function oe(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function se(e){this[w].emit(`pong`,e)}function ce(e){e.resume()}function V(e){let t=this[w];t.readyState!==F.CLOSED&&(t.readyState===F.OPEN&&(t._readyState=F.CLOSING,le(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function le(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function H(){let e=this[w];if(this.removeListener(`close`,H),this.removeListener(`data`,U),this.removeListener(`end`,W),e._readyState=F.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ie),e._receiver.on(`finish`,ie))}function U(e){this[w]._receiver.write(e)||this.pause()}function W(){let e=this[w];e._readyState=F.CLOSING,e._receiver.end(),this.end()}function ue(){let e=this[w];this.removeListener(`error`,ue),this.on(`error`,T),e&&(e._readyState=F.CLOSING,this.destroy())}})),ot=n(((e,n)=>{at();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),st=n(((e,t)=>{let{tokenChars:n}=et();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),ct=n(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=it(),c=$e(),l=st(),u=at(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=Xe(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=i.createServer((e,t)=>{let n=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=h(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(g,this);return}if(e&&this.once(`close`,e),this._state!==1){if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(this)})}}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
23
+ `).join(`\r
24
+ `)),i.removeListener(`error`,_),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(g,this)})),l(d,r)}};function h(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function g(e){e._state=2,e.emit(`close`)}function _(){this.destroy()}function v(e,t,n,r){n||=i.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
25
+ `)+`\r
26
+ \r
27
+ `+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));ot(),it(),$e(),tt(),nt(),st();var q=e(at(),1);ct();async function lt(e,t,n,r,i){return(i?.mode??`singleton`)===`multiplexed`?ft(e,t,n,r,i):dt(e,t,n,r,i)}async function ut(e,t,n){mt(n.localPort,`localPort`,1,65535);let r=n.localHost??`127.0.0.1`,i=n.localPort,a=n.logLevel??`info`,o=n.maxConnections??64,s=n.maxPendingBytesPerConnection??16777216,l=n.maxBufferedBytes??4194304,u=l/4,d=n.connectTimeoutMs??1e4,f={debug:(...e)=>{a===`debug`&&console.log(`[ReverseTunnel]`,...e)},info:(...e)=>{(a===`info`||a===`debug`)&&console.log(`[ReverseTunnel]`,...e)},warn:(...e)=>{(a===`warn`||a===`info`||a===`debug`)&&console.warn(`[ReverseTunnel]`,...e)},error:(...e)=>{a!==`none`&&console.error(`[ReverseTunnel]`,...e)}};return new Promise((n,a)=>{let p=new Map,m=new Set,h=new Map,g=new Map,_=new Map,v=new Map,y=new Set,b,x,S=!1,C=`connecting`,w=!1,T,E=!1,D=e=>{C!==e&&(C=e,f.debug(`Connection state changed to: ${e}`),y.forEach(t=>{try{t(e)}catch(e){f.error(`Error in connection state callback:`,e)}}))},O=e=>{b&&b.readyState===q.default.OPEN&&b.send(ht(e),()=>A())},k=()=>{if(!E){E=!0,f.debug(`WebSocket send buffer full, pausing local reads`);for(let e of p.values())e.destroyed||e.pause()}},A=()=>{if(E&&!(!b||b.bufferedAmount>=u)){E=!1,f.debug(`WebSocket send buffer drained, resuming local reads`);for(let e of p.values())e.destroyed||e.resume()}},j=e=>{let t=v.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{v.delete(e)},3e4);n.unref(),v.set(e,n)},M=(e,t,n=!1)=>{let r=p.get(e),i=_.get(e);p.delete(e),m.delete(e),h.delete(e),g.delete(e),_.delete(e),j(e),i&&clearTimeout(i),t&&O(e),r&&!r.destroyed&&(n?(r.end(),setTimeout(()=>{r.destroyed||r.destroy()},1e3).unref()):r.destroy())},N=()=>{for(let e of Array.from(p.keys()))M(e,!1);E=!1,p.clear(),m.clear(),h.clear(),g.clear();for(let e of v.values())clearTimeout(e);v.clear()},P=()=>{x&&=(clearInterval(x),void 0),b&&=(b.removeAllListeners(),(b.readyState===q.default.OPEN||b.readyState===q.default.CONNECTING)&&b.close(1e3,`close`),void 0)},F=()=>{S=!0,P(),N(),D(`disconnected`)},I=()=>C,ee=e=>(y.add(e),()=>{y.delete(e)}),te=e=>{T=e,w=!0,n({remoteAddress:T,close:F,getConnectionState:I,onConnectionStateChange:ee})},L=e=>{w?f.error(e.message):(P(),N(),D(`disconnected`),a(e))},R=(e,t)=>{let n=_.get(e);n&&(clearTimeout(n),_.delete(e));let r=h.get(e)??[];h.delete(e),g.delete(e),m.delete(e);for(let e of r)t.write(e)},z=(e,t)=>{if(v.has(e)){f.debug(`Ignoring payload for closed conn=${e}`);return}if(p.size>=o){f.warn(`Rejecting reverse tunnel conn=${e}: max connections reached`),O(e),j(e);return}if(t.length>s){f.warn(`Rejecting reverse tunnel conn=${e}: initial payload exceeds pending byte limit`),O(e),j(e);return}h.set(e,[t]),g.set(e,t.length),m.add(e);let n=c.createConnection({host:r,port:i});A(),E&&n.pause(),p.set(e,n);let a=setTimeout(()=>{f.error(`Local TCP connect timed out conn=${e} after ${d}ms`),p.has(e)&&M(e,!0)},d);a.unref(),_.set(e,a),n.on(`connect`,()=>{f.debug(`Connected conn=${e} to ${r}:${i}`),R(e,n)});let u=ht(e),y=t=>{t&&f.error(`Failed to send conn=${e} data: ${t.message}`),A()};n.on(`data`,e=>{if(b&&b.readyState===q.default.OPEN){let t=Buffer.allocUnsafe(4+e.length);u.copy(t,0),e.copy(t,4),b.send(t,y),!E&&b.bufferedAmount>l&&k()}}),n.on(`close`,()=>{f.debug(`Local TCP connection closed conn=${e}`),p.has(e)&&M(e,!0)}),n.on(`error`,t=>{f.error(`Local TCP connection error conn=${e}: ${t.message}`),p.has(e)&&M(e,!0)})},ne=e=>{if(e.length<4){f.error(`Received binary frame shorter than 4 bytes; dropping`);return}let t=gt(e),n=e.subarray(4);if(n.length===0){f.debug(`Received remote close for conn=${t}`),M(t,!1,!0);return}if(v.has(t)){f.debug(`Ignoring payload for closed conn=${t}`);return}let r=p.get(t);if(!r){z(t,n);return}if(m.has(t)){let e=h.get(t)??[],r=(g.get(t)??0)+n.length;if(r>s){f.warn(`Closing reverse tunnel conn=${t}: pending byte limit exceeded`),M(t,!0);return}e.push(n),h.set(t,e),g.set(t,r);return}r.write(n)},re=e=>{let t;try{t=JSON.parse(e.toString())}catch{L(Error(`Malformed reverse tunnel control message: ${e.toString()}`));return}if(t.type===`ready`){if(typeof t.remoteHost!=`string`||typeof t.remotePort!=`number`){L(Error(`Malformed reverse tunnel ready message: ${e.toString()}`));return}f.info(`Reverse tunnel ready: ${t.remoteHost}:${t.remotePort}`),D(`connected`),te({address:t.remoteHost,port:t.remotePort});return}if(t.type===`error`){L(Error(t.message||`Reverse tunnel failed to start`));return}L(Error(`Unexpected reverse tunnel control message type: ${t.type}`))},B=new URL(e),ie=H.getWebSocketAgent(B.toString());b=new q.default(B.toString(),{headers:{Authorization:`Bearer ${t}`},...ie?{agent:ie}:{},perMessageDeflate:!1}),b.on(`error`,e=>{f.error(`WebSocket error:`,e.message),L(e)}),b.on(`close`,(e,t)=>{x&&=(clearInterval(x),void 0),f.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),N(),D(`disconnected`),!S&&!w&&L(Error(`Reverse tunnel WebSocket closed before ready: ${e} ${t.toString()}`))}),b.on(`open`,()=>{let e=b;f.debug(`Connected WebSocket to ${B.toString()}`),x=setInterval(()=>{e.readyState===q.default.OPEN&&e.ping()},3e4)}),b.on(`message`,(e,t)=>{if(!w){if(t){L(Error(`Received reverse tunnel binary frame before ready control message`));return}re(e);return}if(!t){f.warn(`Ignoring unexpected reverse tunnel text message: ${e.toString()}`);return}ne(Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e))})})}async function dt(e,t,n,r,i){let a=i?.maxReconnectAttempts??6,o=i?.reconnectDelay??1e3,s=i?.maxReconnectDelay??3e4,l=i?.logLevel??`info`,u={debug:(...e)=>{l===`debug`&&console.log(`[Tunnel]`,...e)},info:(...e)=>{(l===`info`||l===`debug`)&&console.log(`[Tunnel]`,...e)},warn:(...e)=>{(l===`warn`||l===`info`||l===`debug`)&&console.warn(`[Tunnel]`,...e)},error:(...e)=>{l!==`none`&&console.error(`[Tunnel]`,...e)}};return new Promise((i,l)=>{let d=c.createServer(),f,p,h,g=0,_=!1,v,y=`connecting`,b,x,S=new Set,C=e=>{y!==e&&(y=e,u.debug(`Connection state changed to: ${e}`),S.forEach(t=>{try{t(e)}catch(e){u.error(`Error in connection state callback:`,e)}}))},w=()=>{h&&=(clearTimeout(h),void 0),p&&=(clearInterval(p),void 0),f&&=(f.removeAllListeners(),(f.readyState===q.default.OPEN||f.readyState===q.default.CONNECTING)&&f.close(1e3,`close`),void 0)},T=()=>{_=!0,w(),C(`disconnected`),v&&!v.destroyed&&v.destroy(),d.listening&&d.close()},E=()=>{if(_){u.debug(`Skipping reconnection (intentional disconnect)`);return}if(pt(x??``)){u.error(`Skipping reconnection (non-retryable error): ${x}`);return}if(!v||v.destroyed){u.debug(`Skipping reconnection (TCP socket closed)`);return}if(g>=a){u.error(`Max reconnection attempts (${a}) reached. Closing tunnel.`,x?`Last error: ${x}`:``),T();return}let e=Math.min(o*2**g,s);g++,u.debug(`Scheduling reconnection attempt ${g} in ${e}ms...`),C(`reconnecting`),h=setTimeout(()=>{u.debug(`Attempting to reconnect (attempt ${g})...`),D()},e)},D=()=>{if(!v||v.destroyed){u.error(`Cannot setup WebSocket: TCP socket is closed`);return}w(),C(`connecting`);let n=new URL(e);b&&n.searchParams.set(`sessionId`,b);let r=H.getWebSocketAgent(n.toString());f=new q.default(n.toString(),{headers:{Authorization:`Bearer ${t}`},...r?{agent:r}:{},perMessageDeflate:!1}),f.on(`error`,e=>{let t=e.message||String(e);x=t,u.debug(`WebSocket error:`,t)}),f.on(`close`,(e,t)=>{p&&=(clearInterval(p),void 0);let n=!_&&!pt(x??``)&&y!==`disconnected`;C(`disconnected`),u.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),v&&!v.destroyed&&!v.isPaused()&&(u.debug(`Pausing TCP socket (applying backpressure)`),v.pause()),n&&v&&!v.destroyed?E():pt(x??``)&&(u.error(`Closing tunnel due to non-retryable error: ${x}`),T())}),f.on(`open`,()=>{let e=f;u.debug(`WebSocket connected`),g=0,x=void 0,C(`connected`),p=setInterval(()=>{e.readyState===q.default.OPEN&&e.ping()},3e4),v&&v.isPaused()&&(u.debug(`Resuming TCP socket (releasing backpressure)`),v.resume());let t=t=>{e.readyState===q.default.OPEN&&e.send(t)};v.removeListener(`data`,t),v.on(`data`,t),e.on(`message`,e=>{v&&!v.destroyed&&v.write(e)})})};d.once(`error`,e=>{T(),l(Error(`TCP server error: ${e.message}`))});let O=()=>y,k=e=>(S.add(e),()=>{S.delete(e)});d.once(`listening`,()=>{let e=d.address();if(!e||typeof e==`string`)return T(),l(Error(`Failed to obtain listening address`));i({address:e,close:T,getConnectionState:O,onConnectionStateChange:k})});let A=()=>{w(),C(`disconnected`),v&&!v.destroyed&&(v.destroy(),v=void 0),g=0,_=!1,b=void 0,x=void 0,u.debug(`Connection cleaned up, ready for new TCP connection`)};d.on(`connection`,e=>{if(v&&!v.destroyed){u.debug(`Rejecting new TCP connection - already have an active connection`),e.destroy();return}b=m.randomUUID(),u.debug(`TCP client connected`,`sessionId`,b),v=e,v.on(`close`,()=>{u.debug(`TCP socket closed by client`),A()}),v.on(`error`,e=>{u.error(`TCP socket error:`,e),A()}),D()}),d.listen(r,n)})}async function ft(e,t,n,r,i){let a=i?.logLevel??`info`,o={debug:(...e)=>{a===`debug`&&console.log(`[Tunnel:Mux]`,...e)},info:(...e)=>{(a===`info`||a===`debug`)&&console.log(`[Tunnel:Mux]`,...e)},warn:(...e)=>{(a===`warn`||a===`info`||a===`debug`)&&console.warn(`[Tunnel:Mux]`,...e)},error:(...e)=>{a!==`none`&&console.error(`[Tunnel:Mux]`,...e)}};return new Promise((a,s)=>{let l=c.createServer(),u=new Map,d=1,f,p,m=!1,h=!1,g=`connecting`,_=i?.maxReconnectAttempts??6,v=i?.reconnectDelay??1e3,y=i?.maxReconnectDelay??3e4,b=0,x,S,C=new Set,w=e=>{g!==e&&(g=e,o.debug(`Connection state changed to: ${e}`),C.forEach(t=>{try{t(e)}catch(e){o.error(`Error in connection state callback:`,e)}}))},T=()=>{p&&=(clearInterval(p),void 0),f&&=(f.removeAllListeners(),(f.readyState===q.default.OPEN||f.readyState===q.default.CONNECTING)&&f.close(1e3,`close`),void 0)},E=()=>{for(let[e,t]of u)o.debug(`Closing TCP connection ${e}`),t.destroyed||t.destroy();u.clear()},D=()=>{m=!0,x&&=(clearTimeout(x),void 0),T(),E(),w(`disconnected`),l.listening&&l.close()},O=()=>{if(m||x)return;if(pt(S??``)){o.error(`Closing multiplexed tunnel (non-retryable error): ${S}`),D();return}if(b>=_){o.error(`Max reconnection attempts (${_}) reached. Closing tunnel.`),D();return}let e=Math.min(v*2**b,y);b++,w(`reconnecting`),o.debug(`Scheduling reconnection attempt ${b} in ${e}ms...`),x=setTimeout(()=>{x=void 0,j().catch(()=>{})},e)},k=e=>{if(f&&f.readyState===q.default.OPEN){let t=ht(e);f.send(t),o.debug(`Sent close signal for connection ${e}`)}},A=e=>{let t=u.get(e);t&&(t.destroyed||t.destroy(),u.delete(e),o.debug(`Removed connection ${e}`))},j=()=>new Promise((n,r)=>{T(),w(`connecting`);let i=new URL(e);i.searchParams.set(`mode`,`multiplexed`),o.debug(`Connecting WebSocket to: ${i.toString()}`);let a=H.getWebSocketAgent(i.toString());f=new q.default(i.toString(),{headers:{Authorization:`Bearer ${t}`},...a?{agent:a}:{},perMessageDeflate:!1}),f.on(`error`,e=>{let t=e.message||String(e);S=t,o.error(`WebSocket error:`,t,e.code||``),r(e)}),f.on(`close`,(e,t)=>{if(p&&=(clearInterval(p),void 0),o.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),E(),!h||m){w(`disconnected`);return}O()}),f.on(`open`,()=>{let e=f;o.debug(`WebSocket connected`),b=0,S=void 0,w(`connected`),p=setInterval(()=>{e.readyState===q.default.OPEN&&e.ping()},3e4),e.on(`message`,e=>{let t=e;if(o.debug(`WS→TCP raw message: ${t.length} bytes`),t.length<4){o.error(`Received binary frame shorter than 4 bytes; dropping`);return}let n=gt(t),r=t.subarray(4);if(r.length===0){o.debug(`Received close signal for connection ${n}`),A(n);return}o.debug(`WS→TCP [conn=${n}] ${r.length} bytes: ${r.subarray(0,Math.min(200,r.length)).toString(`utf8`).replace(/[\x00-\x1f]/g,`.`)}`);let i=u.get(n);i&&!i.destroyed?i.write(r):o.debug(`Received data for unknown/closed connection ${n}`)}),n()})});l.once(`error`,e=>{D(),s(Error(`TCP server error: ${e.message}`))});let M=()=>g,N=e=>(C.add(e),()=>{C.delete(e)});l.once(`listening`,async()=>{let e=l.address();if(!e||typeof e==`string`)return D(),s(Error(`Failed to obtain listening address`));o.debug(`Multiplexed tunnel listening on ${e.address}:${e.port}`);try{await j(),h=!0,o.debug(`WebSocket ready, tunnel fully initialized`),a({address:e,close:D,getConnectionState:M,onConnectionStateChange:N})}catch(e){D(),s(Error(`Failed to establish WebSocket connection: ${e}`))}}),l.on(`connection`,e=>{if(!f||f.readyState!==q.default.OPEN){e.destroy();return}let t=d++;d>4294967295&&(d=1),u.set(t,e),o.debug(`New TCP connection ${t} from ${e.remoteAddress}:${e.remotePort}, WS state=${f?.readyState}, total connections=${u.size}`),e.on(`data`,n=>{if(f&&f.readyState===q.default.OPEN){let e=ht(t),r=Buffer.concat([e,n]);o.debug(`TCP→WS [conn=${t}] ${n.length} bytes: ${n.subarray(0,Math.min(200,n.length)).toString(`utf8`).replace(/[\x00-\x1f]/g,`.`)}`),f.send(r,e=>{e&&o.error(`TCP→WS [conn=${t}] send error: ${e.message}`)})}else o.debug(`TCP→WS [conn=${t}] WS not open (state=${f?.readyState}), closing connection`),e.destroy()}),e.on(`close`,()=>{o.debug(`TCP connection ${t} closed by client`),k(t),u.delete(t)}),e.on(`error`,e=>{o.error(`TCP connection ${t} error:`,e),k(t),u.delete(t)})}),l.listen(r,n)})}const pt=e=>{let t=e.match(/Unexpected server response: (\d+)/);if(t&&t[1]){let e=parseInt(t[1],10);return e>=400&&e<500}return!1};function mt(e,t,n,r){if(!Number.isInteger(e)||e<n||e>r)throw Error(`${t} must be an integer between ${n} and ${r}`)}function ht(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}function gt(e){if(e.length<4)throw Error(`Header must be at least 4 bytes`);return e.readUInt32BE(0)}async function _t(e,t,n,r){for(let i=0;i<=3;i++){let o=await H.fetch(e,{method:`GET`,headers:{Authorization:`Bearer ${t}`}});if(!o.ok){let e=await o.text();if(o.status>=500&&o.status<600&&i<3)continue;throw Error(`Download failed: ${o.status} ${e}`)}if(!o.body)throw Error(`Download failed: response body is missing`);await a.promises.mkdir(p.dirname(n),{recursive:!0});let c=s.fromWeb(o.body);if(r){let e=Number(o.headers.get(`content-length`)??0),t=0;c.on(`data`,n=>{t+=n.length,r(t,e)})}await g(c,a.createWriteStream(n));return}}var J=class extends Error{constructor(e){super(e),this.name=`DestinationTunnelProtocolError`}};function Y(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new J(`${t} must be an object`);return e}function vt(e,t){let n=e[t];if(!Array.isArray(n))throw new J(`${t} must be an array`);return n}function X(e,t){let n=e[t];if(typeof n!=`string`)throw new J(`${t} must be a string`);return n}function Z(e,t){let n=X(e,t);if(n.length===0)throw new J(`${t} must not be empty`);return n}function yt(e,t){let n=e[t];if(typeof n!=`boolean`)throw new J(`${t} must be a boolean`);return n}function bt(e,t){let n=e[t];if(!Number.isInteger(n))throw new J(`${t} must be an integer`);return n}function xt(e,t){let n=e[t];if(typeof n!=`number`||!Number.isFinite(n))throw new J(`${t} must be a finite number`);return n}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new J(`${t} must be a safe non-negative integer`);return e}function Ct(e,t){return e[t]===void 0?{}:{[t]:X(e,t)}}function wt(e,t){return e[t]===void 0?{}:{[t]:yt(e,t)}}function Tt(e,t){let n=e[t];if(n===void 0)return{};if(!Number.isInteger(n)||n<0)throw new J(`${t} must be a non-negative integer`);return{[t]:n}}function Et(e){if(Buffer.isBuffer(e))return e;if(Array.isArray(e))return Buffer.concat(e);if(e instanceof ArrayBuffer)return Buffer.from(e);throw new J(`unsupported WebSocket payload type`)}function Dt(e,t){let n=new URL(e);if(n.protocol!==`https:`&&n.protocol!==`http:`&&n.protocol!==`wss:`&&n.protocol!==`ws:`)throw Error(`Unsupported apiUrl protocol for tunnel: ${n.protocol}`);let r=`${Mt(n.pathname)}/tunnel`;return n.pathname=t===void 0?r:`${r}/${t}`,n.search=``,n.hash=``,n}function Ot(e){let t=Dt(e);return t.protocol=t.protocol===`https:`||t.protocol===`wss:`?`wss:`:`ws:`,t.toString()}function kt(e){let t=Dt(e,`status`);return t.protocol=t.protocol===`wss:`?`https:`:t.protocol===`ws:`?`http:`:t.protocol,t}function At(e,t){let n=Dt(e,encodeURIComponent(t));return n.protocol=n.protocol===`wss:`?`https:`:n.protocol===`ws:`?`http:`:n.protocol,n}function jt(e,t,n=0,r){let i=typeof n==`number`?n:0,a=typeof n==`string`?n:r;if(!Number.isSafeInteger(i)||i<0)throw Error(`afterSequence must be a safe non-negative integer`);let o=new URL(e);return o.protocol=o.protocol===`wss:`?`https:`:o.protocol===`ws:`?`http:`:o.protocol,o.pathname=`${Mt(o.pathname)}/${encodeURIComponent(t)}/inspection/events`,o.search=``,i>0&&o.searchParams.set(`after-sequence`,String(i)),a!==void 0&&o.searchParams.set(`token`,a),o.hash=``,o.toString()}function Mt(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Nt(e,t,n,r={}){let i=!0,a=0,o=e=>{Ut(r.onError,e)},s=(e,t)=>{Ut(r.onEvent,{type:`gap`,sequence:t,data:{fromSequence:e,toSequence:t,message:`Inspection stream gap: missing sequences ${e}-${t}`}},o)},c=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new J(`inspection sequence must be a safe non-negative integer`);if(e<=a)throw new J(`inspection sequence ${e} is not newer than ${a}`);if(t){if(t.fromSequence!==a+1||t.toSequence!==e||t.fromSequence>t.toSequence)throw new J(`invalid inspection gap range`);s(t.fromSequence,t.toSequence)}else e>a+1&&s(a+1,e-1);a=e},l=jt(e,t,a,n),u=me({url:l,fetch:H.fetch.bind(H),onMessage:e=>{if(i)try{let t=Pt(e.id,e.data);t.type===`gap`?c(t.sequence,t.data):(c(t.sequence),Ut(r.onEvent,t,o))}catch(e){o(e instanceof Error?e:Error(String(e)))}},onDisconnect:()=>{i&&o(Error(`Inspection SSE disconnected; reconnecting`))}});return{close:()=>{i&&(i=!1,u.close())}}}function Pt(e,t){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e))throw new J(`inspection SSE event ID must be an unsigned integer`);let n=Number(e);if(!Number.isSafeInteger(n))throw new J(`inspection sequence must be a safe non-negative integer`);let r;try{r=JSON.parse(t)}catch{throw new J(`inspection SSE data must be valid JSON`)}let i=Y(r,`inspection event`);if(i.sequence!==void 0&&St(i.sequence,`inspection sequence`)!==n)throw new J(`inspection SSE event ID does not match envelope sequence`);if(X(i,`type`)!==`body`)return Ft(i,n);let a=Vt(i),o=Y(i.data,`inspection body data`),s=X(o,`direction`);if(s!==`request`&&s!==`response`)throw new J(`invalid inspection body direction`);if(X(o,`encoding`)!==`base64`)throw new J(`inspection body encoding must be base64`);return{type:`body`,sequence:n,requestId:a,direction:s,body:Wt(X(o,`chunk`))}}function Ft(e,t){let n=X(e,`type`),r=Y(e.data,`inspection metadata data`);switch(n){case`complete`:return{type:n,sequence:t,requestId:Vt(e),data:It(r)};case`gap`:{let e=St(r.fromSequence,`inspection sequence`),i=St(r.toSequence,`inspection sequence`);return{type:n,sequence:t,data:{fromSequence:e,toSequence:i,message:`Inspection stream gap: missing sequences ${e}-${i}`}}}case`inspection_error`:return{type:n,sequence:t,...e.requestId===void 0?{}:{requestId:Vt(e)},data:{...r,message:X(r,`message`)}};default:throw new J(`unknown inspection metadata type ${n}`)}}function It(e){return Ht(e,`startedDateTime`),xt(e,`time`),Rt(Y(e.request,`inspection request`)),zt(Y(e.response,`inspection response`)),Lt(Y(e._limrun,`inspection extension`)),e}function Lt(e){if(X(e,`tunnelId`),X(e,`selectorId`),Ct(e,`error`),wt(e,`requestBodyTruncated`),wt(e,`responseBodyTruncated`),e.responseTrailers!==void 0&&Bt(e.responseTrailers,`response trailers`),e.responseCookieSameSite!==void 0)for(let t of vt(e,`responseCookieSameSite`)){let e=Y(t,`response cookie same-site metadata`);St(e.index,`response cookie same-site index`),X(e,`value`)}}function Rt(e){X(e,`method`),X(e,`url`),X(e,`httpVersion`),Bt(e.headers,`request headers`),Bt(e.queryString,`request query string`),Bt(e.cookies,`request cookies`),xt(e,`headersSize`),xt(e,`bodySize`),e.postData!==void 0&&Y(e.postData,`request post data`)}function zt(e){xt(e,`status`),X(e,`statusText`),X(e,`httpVersion`),Bt(e.headers,`response headers`),Bt(e.cookies,`response cookies`);let t=Y(e.content,`response content`);xt(t,`size`),X(t,`mimeType`),X(e,`redirectURL`),xt(e,`headersSize`),xt(e,`bodySize`)}function Bt(e,t){if(!Array.isArray(e))throw new J(`${t} must be an array`);for(let n of e){let e=Y(n,t);X(e,`name`),X(e,`value`)}}function Vt(e){let t=X(e,`requestId`);if(!t)throw new J(`inspection request ID must not be empty`);return t}function Ht(e,t){let n=X(e,t);if(!Number.isFinite(Date.parse(n)))throw new J(`${t} must be an ISO date-time`);return n}function Ut(e,t,n){if(e)try{e(t)}catch(e){n?.(e instanceof Error?e:Error(String(e)))}}function Wt(e){try{if(e.length%4!=0)throw Error(`invalid base64 length`);let t=atob(e);if(btoa(t)!==e)throw Error(`non-canonical base64`);return Uint8Array.from(t,e=>e.charCodeAt(0))}catch{throw new J(`inspection body chunk must be valid base64`)}}var Q=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`DestinationTunnelSelectorError`}};function Gt(e,t){if(_n(e),t.length===0)throw new J(`tunnel data frame must include a payload`);let n=Buffer.allocUnsafe(4+t.length);return n.writeUInt32BE(e,0),t.copy(n,4),n}function Kt(e){if(e.length<=4)throw new J(`tunnel data frame must include a payload`);return{connId:e.readUInt32BE(0),payload:e.subarray(4)}}function qt(e,t={}){if(!Array.isArray(e))throw new Q(`invalid_host`,`tunnel selectors must be an array`);if(e.length===0)throw new Q(`empty`,`at least one tunnel selector is required`);let n=[],r=new Set,i=0,a=0;for(let o of e){let e=rn(o,t.minRoutePort);if(e.route?i++:a++,i>10)throw new Q(`too_many`,`at most 10 exact tunnel selectors are allowed`);if(a>64)throw new Q(`too_many`,`at most 64 domain tunnel selectors are allowed`);if(r.has(e.value))throw new Q(`duplicate`,`duplicate tunnel selector ${e.value}`);r.add(e.value),n.push(e.value)}return n}function Jt(e,t={}){let n=qt(e,t),r=[],i=[];for(let e of n){let n=rn(e,t.minRoutePort);n.route?r.push(n.route):i.push(n.domain)}return{...r.length>0?{routes:r}:{},...i.length>0?{domains:i}:{}}}function Yt(e,t=Zt()){let n=qt(e),r=Xt(t),i=[`"version":1`,`"selectors":[${n.map(e=>JSON.stringify(e)).join(`,`)}]`];return i.push(`"inspection":{"enabled":${r.enabled},"captureBodies":${r.captureBodies},"maxBodyBytes":${r.maxBodyBytes},"persist":${r.persist},"ttlSeconds":${r.ttlSeconds}}`),h.createHash(`sha256`).update(`{${i.join(`,`)}}`,`utf8`).digest(`hex`)}function Xt(e){let t=e.enabled??!1,n=e.captureBodies??!1,r=e.maxBodyBytes??10485760,i=e.persist??!1,a=e.ttlSeconds??259200;if(n&&!t)throw new J(`captureBodies requires inspection to be enabled`);if(i&&!t)throw new J(`persist requires inspection to be enabled`);if(!Number.isInteger(r)||r<1||r>67108864)throw new J(`maxBodyBytes must be an integer between 1 and 67108864`);if(!Number.isInteger(a)||a<1||a>2592e3)throw new J(`ttlSeconds must be an integer between 1 and 2592000`);return{enabled:t,captureBodies:n,maxBodyBytes:r,persist:i,ttlSeconds:a}}function Zt(){return Xt({enabled:!1,captureBodies:!1})}function Qt(e,t){let n=t.toLowerCase();if(e.startsWith(`*.`)){let t=e.slice(2);return n.length>t.length+1&&n.endsWith(`.${t}`)}return n===e}function $t(e,t){let n=qt(t),r=/^selector-([1-9]\d*)$/.exec(e.selectorId),i=r?.[1]?Number(r[1])-1:-1,a=()=>{throw new J(`server requested undeclared selector ${e.selectorId} ${e.host}:${e.port}`)};i<0&&a(),e.port===53&&a();let o=n[i];if(o===void 0)return a();let s=rn(o);return s.route?((e.host!==s.route.host||e.port!==s.route.port)&&a(),`route`):(Qt(s.domain,e.host)||a(),`domain`)}function en(e){if(e.version!==1)throw new J(`unsupported tunnel version ${e.version}`)}function tn(e){let t=Y(e,`tunnel control message`),n=X(t,`type`);switch(n){case`start`:{let e=bt(t,`version`);if(e!==1)throw new J(`unsupported tunnel version ${e}`);let r=qt(vt(t,`selectors`).map(e=>{if(typeof e!=`string`)throw new J(`tunnel selector must be a string`);return e})),i=un(t);return JSON.stringify({type:n,version:e,selectors:r,inspection:i,window:mn(t)})}case`openOk`:return JSON.stringify({type:n,connId:gn(t),transport:fn(t),window:mn(t)});case`fin`:return JSON.stringify({type:n,connId:gn(t)});case`openFail`:case`reset`:return JSON.stringify({type:n,connId:gn(t),reason:X(t,`reason`),...Ct(t,`osCode`)});case`windowUpdate`:return JSON.stringify({type:n,connId:gn(t),increment:hn(t)});default:throw new J(`unknown tunnel control message type ${n}`)}}function nn(e){let t=Y(e,`tunnel control message`),n=X(t,`type`);switch(n){case`ready`:return{type:n,version:bt(t,`version`),tunnelId:X(t,`tunnelId`),selectors:vt(t,`selectors`).map((e,t)=>cn(e,`selector-${t+1}`)),configHash:X(t,`configHash`)};case`open`:return{type:n,connId:gn(t),selectorId:X(t,`selectorId`),host:X(t,`host`),port:pn(t,`port`),transport:dn(t),window:mn(t)};case`fin`:return{type:n,connId:gn(t)};case`reset`:return{type:n,connId:gn(t),reason:X(t,`reason`),...Ct(t,`osCode`)};case`windowUpdate`:return{type:n,connId:gn(t),increment:hn(t)};case`error`:return{type:n,code:X(t,`code`)};default:throw new J(`unknown tunnel control message type ${n}`)}}function rn(e,t=1){if(typeof e!=`string`||e.length===0)throw new Q(`empty`,`tunnel selector must not be empty`);if(!e.startsWith(`[`)&&!e.includes(`:`)){let t=on(e);return{value:t,domain:t}}let n,r;if(e.startsWith(`[`)){let t=/^\[([^\]]+)\]:(\d+)$/.exec(e);if(!t?.[1]||!t[2])throw new Q(`invalid_host`,`invalid tunnel selector ${e}`);n=t[1],r=t[2]}else{let t=e.lastIndexOf(`:`);if(t<=0||e.indexOf(`:`)!==t)throw new Q(`invalid_host`,`invalid tunnel selector ${e}`);n=e.slice(0,t),r=e.slice(t+1)}if(!/^\d+$/.test(r))throw new Q(`invalid_port`,`invalid tunnel selector port ${r}`);let i=an({host:n,port:Number(r)},t);return{value:`${i.host.includes(`:`)?`[${i.host}]`:i.host}:${i.port}`,route:i}}function an(e,t=1){if(!Number.isInteger(e.port)||e.port<t||e.port>65535||e.port===53)throw new Q(`invalid_port`,`invalid tunnel route port ${e.port}`);if(Buffer.byteLength(e.host,`utf8`)===e.host.length&&e.host.toLowerCase()===`localhost`)return{host:`localhost`,port:e.port};let n=l.isIP(e.host);if(n===4)return{host:e.host,port:e.port};if(n===6){let t=new URL(`http://[${e.host}]/`).hostname.slice(1,-1);if(t!==`::1`&&/^::(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4}$/.test(t))throw new Q(`invalid_host`,`invalid tunnel route host ${e.host}`);return{host:sn(t),port:e.port}}throw new Q(`invalid_host`,`invalid tunnel route host ${e.host}`)}function on(e){let t=()=>{throw new Q(`invalid_domain`,`invalid tunnel domain ${e}`)};(typeof e!=`string`||e.length===0||e.length>260)&&t(),Buffer.byteLength(e,`utf8`)!==e.length&&t();let n=e.toLowerCase(),r=n.startsWith(`*.`),i=r?n.slice(2):n;(i.length===0||i.length>253)&&t(),i.includes(`*`)&&t(),(i.endsWith(`.`)||i.startsWith(`.`))&&t(),l.isIP(i)!==0&&t(),i===`localhost`&&t(),f(i)!==i&&t();let a=i.split(`.`);for(let e of a)(e.length===0||e.length>63)&&t(),/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)||t();let o=a[a.length-1];return o!==void 0&&/^\d+$/.test(o)&&t(),r?`*.${i}`:i}function sn(e){let t=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(!t?.[1]||!t[2])return e;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);return`${n>>8}.${n&255}.${r>>8}.${r&255}`}function cn(e,t){let n=Y(e,`tunnel selector`),r=X(n,`id`);if(r!==t)throw new J(`invalid tunnel selector id ${r}`);let i=X(n,`kind`);if(i!==`route`&&i!==`domain`)throw new J(`invalid tunnel selector kind ${i}`);let a={id:r,kind:i,value:X(n,`value`)};return n.binds!==void 0&&(a.binds=vt(n,`binds`).map(ln)),a}function ln(e){let t=Y(e,`tunnel bind report`),n=X(t,`status`);if(n!==`ok`&&n!==`conflict`&&n!==`error`)throw new J(`invalid tunnel bind status ${n}`);return{address:X(t,`address`),status:n,...Ct(t,`osCode`)}}function un(e){let t=Y(e.inspection,`inspection`);return Xt({enabled:yt(t,`enabled`),captureBodies:yt(t,`captureBodies`),maxBodyBytes:bt(t,`maxBodyBytes`),persist:yt(t,`persist`),ttlSeconds:bt(t,`ttlSeconds`)})}function dn(e){let t=Y(e.transport,`transport`),n=X(t,`type`);if(n===`tcp`)return{type:n};if(n===`tls`){let e=X(t,`serverName`);if(e.length===0)throw new J(`TLS transport requires serverName`);return{type:n,serverName:e,alpnProtocols:vt(t,`alpnProtocols`).map(e=>{if(typeof e!=`string`||e.length===0)throw new J(`alpnProtocols must contain non-empty strings`);return e})}}throw new J(`unsupported tunnel transport ${n}`)}function fn(e){let t=Y(e.transport,`transport`),n=X(t,`type`);if(n!==`tcp`&&n!==`tls`)throw new J(`unsupported tunnel transport ${n}`);return{type:n,...Ct(t,`alpnProtocol`),...Ct(t,`remoteAddress`),...Tt(t,`dnsMs`),...Tt(t,`connectMs`),...Tt(t,`tlsMs`)}}function pn(e,t){let n=bt(e,t);if(n<1||n>65535)throw new J(`${t} must be between 1 and 65535`);return n}function mn(e){let t=bt(e,`window`);if(t<1||t>67108864)throw new J(`window must be an integer between 1 and 67108864`);return t}function hn(e){let t=bt(e,`increment`);if(t<1||t>2147483647)throw new J(`increment must be an integer between 1 and 2147483647`);return t}function gn(e){let t=bt(e,`connId`);return _n(t),t}function _n(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new J(`connId must be an unsigned 32-bit integer`)}const $=new l.BlockList;$.addSubnet(`0.0.0.0`,8,`ipv4`),$.addSubnet(`127.0.0.0`,8,`ipv4`),$.addSubnet(`169.254.0.0`,16,`ipv4`),$.addSubnet(`224.0.0.0`,3,`ipv4`),$.addSubnet(`::`,96,`ipv6`),$.addSubnet(`fe80::`,10,`ipv6`),$.addSubnet(`ff00::`,8,`ipv6`),$.addSubnet(`::ffff:0.0.0.0`,104,`ipv6`),$.addSubnet(`::ffff:127.0.0.0`,104,`ipv6`),$.addSubnet(`::ffff:169.254.0.0`,112,`ipv6`),$.addSubnet(`::ffff:224.0.0.0`,99,`ipv6`);async function vn(e,t,n){let r=qt(n.selectors),i=Jt(r).routes??[],a=Xt(n.inspection??Zt()),o=n.logLevel??`info`,s=xn(n.window??1048576,`window`),c=xn(n.maxConnections??64,`maxConnections`),l=xn(n.maxPendingBytesPerConnection??16777216,`maxPendingBytesPerConnection`),d=xn(n.maxTotalPendingBytes??16777216,`maxTotalPendingBytes`),f=xn(n.maxBufferedBytes??4194304,`maxBufferedBytes`),p=xn(n.connectTimeoutMs??1e4,`connectTimeoutMs`),m=xn(n.handshakeTimeoutMs??15e3,`handshakeTimeoutMs`),h=xn(n.livenessTimeoutMs??9e4,`livenessTimeoutMs`),g=Math.min(3e4,Math.max(1,Math.floor(h/3))),v=f/4,y=f+Math.max(65536,Math.floor(f/4)),b={debug:(...e)=>{o===`debug`&&console.log(`[DestinationTunnel]`,...e)},info:(...e)=>{(o===`info`||o===`debug`)&&console.log(`[DestinationTunnel]`,...e)},warn:(...e)=>{(o===`warn`||o===`info`||o===`debug`)&&console.warn(`[DestinationTunnel]`,...e)},error:(...e)=>{o!==`none`&&console.error(`[DestinationTunnel]`,...e)}};return new Promise((o,x)=>{let S=new Map,C=new Map,w=new Set,T=new URL(e),E=H.getWebSocketAgent(T.toString()),D=new q.default(T.toString(),{headers:{Authorization:`Bearer ${t}`},...E?{agent:E}:{},perMessageDeflate:!1}),O=`connecting`,k,A,j,M=!1,N=!1,P,F=!1,I=0,ee=e=>{if(O!==e){O=e;for(let t of w)try{t(e)}catch(e){b.error(`Connection state callback failed:`,e)}}},te=()=>O,L=e=>(w.add(e),()=>w.delete(e)),R=e=>{let t=C.get(e);t&&clearTimeout(t);let n=setTimeout(()=>C.delete(e),3e4);n.unref(),C.set(e,n)},z=(e,t)=>{let n=S.get(e);n&&(S.delete(e),n.abortController.abort(),clearTimeout(n.connectTimer),R(e),t&&n.socket&&!n.socket.destroyed&&n.socket.destroy())},ne=()=>{for(let e of Array.from(S.keys()))z(e,!0);for(let e of C.values())clearTimeout(e);C.clear(),F=!1},re=()=>{N||(N=!0,k&&=(clearInterval(k),void 0),A&&=(clearTimeout(A),void 0),j&&=(clearTimeout(j),void 0),ne(),P?.close(),P=void 0,D.removeAllListeners(`open`),D.removeAllListeners(`message`),D.removeAllListeners(`ping`),D.removeAllListeners(`pong`),(D.readyState===q.default.OPEN||D.readyState===q.default.CONNECTING)&&D.close(1e3,`close`),ee(`disconnected`))},B=e=>{N||(b.error(e.message),re(),M||x(e))},ie=e=>!F&&e.creditQueueBytes===0,ae=()=>{if(!F){F=!0;for(let e of S.values())e.socket&&!e.socket.destroyed&&e.socket.pause()}},oe=()=>{if(!(!F||D.bufferedAmount>=v)){F=!1;for(let e of S.values())e.socket&&!e.socket.destroyed&&ie(e)&&e.socket.resume()}},se=()=>{D.bufferedAmount>y?B(Error(`destination tunnel WebSocket send buffer exceeded its hard limit`)):!F&&D.bufferedAmount>f&&ae()},ce=e=>{e?B(e):oe()},V=e=>{if(N||D.readyState!==q.default.OPEN){B(Error(`destination tunnel WebSocket is not open`));return}D.send(tn(e),ce),se()},le=(e,t)=>{if(N||D.readyState!==q.default.OPEN){B(Error(`destination tunnel WebSocket closed while sending data`));return}D.send(Gt(e,t),{binary:!0},ce),se()},U=(e,t,n)=>{V({type:`openFail`,connId:e,reason:t,...n?{osCode:n}:{}}),R(e)},W=(e,t,n)=>{V({type:`reset`,connId:e,reason:t,...n?{osCode:n}:{}})},ue=(e,t,n)=>{for(n&&n.length>0&&(t.creditQueue.push(n),t.creditQueueBytes+=n.length);t.creditQueue.length>0&&t.sendCredit>0;){let n=t.creditQueue[0];if(n.length<=t.sendCredit)t.creditQueue.shift(),t.creditQueueBytes-=n.length,t.sendCredit-=n.length,le(e,n);else{let r=n.subarray(0,t.sendCredit);t.creditQueue[0]=n.subarray(t.sendCredit),t.creditQueueBytes-=r.length,t.sendCredit=0,le(e,r)}if(N)return}t.creditQueue.length===0&&t.finPending&&(t.finPending=!1,t.localInputEnded=!0,V({type:`fin`,connId:e})),!(!t.socket||t.socket.destroyed)&&(t.creditQueueBytes>0?t.socket.pause():F||t.socket.resume())},de=async e=>{let t=Date.now(),n=await _.promises.lookup(e.host,{all:!0,verbatim:!0}),r=Date.now()-t;for(let t of n)if(yn(t.address,e.port,i))return{host:t.address,dnsMs:r};let a=Error(`all resolved addresses for ${e.host} are blocked`);throw a.code=`EBLOCKED`,a},fe=(e,t,n)=>new Promise((r,i)=>{let a=u.connect({socket:e,rejectUnauthorized:!0,servername:t.serverName,ALPNProtocols:t.alpnProtocols});a.allowHalfOpen=!0;let o=()=>{a.removeListener(`secureConnect`,s),a.removeListener(`error`,c),n.signal.removeEventListener(`abort`,l)},s=()=>{o(),a.pause(),r(a)},c=e=>{o(),i(e)},l=()=>{o(),a.destroy(),i(Object.assign(Error(`TLS connection cancelled`),{code:`ECANCELED`}))};a.once(`secureConnect`,s),a.once(`error`,c),n.signal.aborted?l():n.signal.addEventListener(`abort`,l,{once:!0})}),G=e=>{let t;try{t=$t(e,r)}catch{U(e.connId,`selector_not_allowed`);return}if(S.has(e.connId)||C.has(e.connId))throw new J(`server reused connection ID ${e.connId}`);if(S.size>=c){U(e.connId,`resource_exhausted`);return}let n=new AbortController,i=setTimeout(()=>{S.get(e.connId)?.phase===`connecting`&&(b.warn(`Failed to connect to ${e.host}:${e.port}: timed out`),U(e.connId,`connection_timed_out`,`ETIMEDOUT`),z(e.connId,!0))},p);i.unref();let a={phase:`connecting`,abortController:n,connectTimer:i,localInputEnded:!1,remoteInputEnded:!1,pendingWriteBytes:0,sendCredit:e.window,creditQueue:[],creditQueueBytes:0,finPending:!1,deliveredSinceUpdate:0};S.set(e.connId,a),(async()=>{let r=e.host;if(t===`domain`){let t=await de(e);r=t.host,a.dnsMs=t.dnsMs}if(S.get(e.connId)!==a||N)return;let o=await H.connectTcp({host:r,port:e.port,proxyLookupHost:e.host,proxyLookupProtocol:e.transport.type===`tls`?`https:`:`http:`,timeoutMs:p,signal:n.signal});if(S.get(e.connId)!==a||N){o.socket.destroy();return}a.socket=o.socket;let c=o.socket,l;if(e.transport.type===`tls`){let t=Date.now();if(c=await fe(o.socket,e.transport,n),l=Date.now()-t,S.get(e.connId)!==a||N){c.destroy();return}a.socket=c}clearTimeout(i),c.on(`data`,t=>{S.get(e.connId)===a&&a.phase===`open`&&ue(e.connId,a,t)}),c.once(`end`,()=>{if(S.get(e.connId)===a&&a.phase===`open`){if(a.creditQueueBytes>0){a.finPending=!0;return}a.localInputEnded=!0,V({type:`fin`,connId:e.connId})}}),c.once(`error`,t=>{S.get(e.connId)===a&&(W(e.connId,`connection_error`,t.code),z(e.connId,!0))}),c.once(`close`,()=>{S.get(e.connId)===a&&((!a.localInputEnded||!a.remoteInputEnded)&&W(e.connId,`connection_error`),z(e.connId,!1))}),a.phase=`open`,V({type:`openOk`,connId:e.connId,transport:{type:e.transport.type,...o.remoteAddress===void 0?{}:{remoteAddress:o.remoteAddress},...a.dnsMs===void 0?{}:{dnsMs:a.dnsMs},connectMs:o.connectMs,...l===void 0?{}:{tlsMs:l},...c instanceof u.TLSSocket&&c.alpnProtocol?{alpnProtocol:c.alpnProtocol}:{}},window:s}),b.debug(`Forwarding connection ${e.connId} to ${e.host}:${e.port}`),!F&&a.creditQueueBytes===0&&c.resume()})().catch(t=>{if(S.get(e.connId)!==a)return;b.warn(`Failed to connect to ${e.host}:${e.port}: ${t.code??t.message}`);let n=t.code===`EBLOCKED`?`selector_not_allowed`:bn(t);U(e.connId,n,t.code===`EBLOCKED`?void 0:t.code),z(e.connId,!0)})},pe=e=>{let t=S.get(e);if(t?.phase===`open`&&t.socket)return t;t?(W(e,`protocol_error`),z(e,!0)):C.has(e)||(W(e,`protocol_error`),R(e))},me=e=>{let t=pe(e);if(t){if(t.remoteInputEnded){W(e,`protocol_error`),z(e,!0);return}t.remoteInputEnded=!0,t.socket.end()}},he=e=>{S.has(e)&&z(e,!0)},ge=(e,t)=>{let n=S.get(e);!n||n.phase!==`open`||(n.sendCredit+=t,ue(e,n))},_e=e=>{if(!M)throw new J(`received tunnel data before READY`);let{connId:t,payload:n}=Kt(e),r=pe(t);if(!r)return;if(r.remoteInputEnded){W(t,`protocol_error`),z(t,!0);return}let i=r.pendingWriteBytes+n.length,a=I+n.length;if(i>l||a>d){W(t,`resource_exhausted`),z(t,!0);return}r.pendingWriteBytes=i,I=a,r.socket.write(n,e=>{if(r.pendingWriteBytes-=n.length,I-=n.length,e&&S.get(t)===r){let n=e.code;W(t,`connection_error`,n),z(t,!0);return}if(S.get(t)===r&&(r.deliveredSinceUpdate+=n.length,r.deliveredSinceUpdate>=Math.ceil(s/2))){let e=r.deliveredSinceUpdate;r.deliveredSinceUpdate=0,!N&&D.readyState===q.default.OPEN&&V({type:`windowUpdate`,connId:t,increment:e})}})},ve=i=>{switch(i.type){case`ready`:{if(M)throw new J(`received duplicate READY`);en(i);let s=Yt(r,a);if(i.configHash!==s)throw new J(`server acknowledged config ${i.configHash} but ${s} was negotiated`);if(M=!0,A&&=(clearTimeout(A),void 0),ye(),ee(`connected`),b.info(`Destination tunnel ready with ${r.length} selector(s)`),a.enabled)try{P=Nt(e,i.tunnelId,t,{...n.onInspectionEvent?{onEvent:n.onInspectionEvent}:{},...n.onInspectionError?{onError:n.onInspectionError}:{}})}catch(e){try{n.onInspectionError?.(e instanceof Error?e:Error(String(e)))}catch{}}o({tunnelId:i.tunnelId,selectors:i.selectors,configHash:i.configHash,inspection:a,...P?{inspectionStream:P}:{},close:re,getConnectionState:te,onConnectionStateChange:L});return}case`error`:throw Error(`destination tunnel failed: ${i.code}`);case`open`:if(!M)throw new J(`received OPEN before READY`);G(i);return;case`fin`:if(!M)throw new J(`received FIN before READY`);me(i.connId);return;case`windowUpdate`:if(!M)throw new J(`received windowUpdate before READY`);ge(i.connId,i.increment);return;case`reset`:if(!M)throw new J(`received RESET before READY`);he(i.connId)}},ye=()=>{!M||N||(j&&clearTimeout(j),j=setTimeout(()=>{B(Error(`destination tunnel received no frames for ${h}ms`))},h),j.unref())};A=setTimeout(()=>{B(Error(`destination tunnel was not ready within ${m}ms`))},m),A.unref(),D.on(`open`,()=>{V({type:`start`,version:1,selectors:r,inspection:a,window:s}),k=setInterval(()=>{D.readyState===q.default.OPEN&&(D.ping(void 0,!0,ce),se())},g),k.unref()}),D.on(`message`,(e,t)=>{try{ye(),t?_e(Et(e)):ve(nn(JSON.parse(Et(e).toString(`utf8`))))}catch(e){B(e instanceof Error?e:Error(String(e)))}}),D.on(`ping`,ye),D.on(`pong`,ye),D.once(`error`,e=>{B(e)}),D.once(`close`,(e,t)=>{if(N){D.removeAllListeners();return}B(Error(`destination tunnel WebSocket closed: ${e}${t.length?` ${t.toString()}`:``}`)),D.removeAllListeners()})})}function yn(e,t,n){for(let r of n)if(r.port===t&&(r.host===e||r.host===`localhost`&&(e===`127.0.0.1`||e===`::1`)))return!0;let r=l.isIP(e);return r===4?!$.check(e,`ipv4`):r===6&&!$.check(e,`ipv6`)}function bn(e){switch(e.code){case`ENOTFOUND`:return`dns_not_found`;case`EAI_AGAIN`:return`dns_temporary_failure`;case`ECONNREFUSED`:return`connection_refused`;case`ECONNRESET`:return`connection_reset`;case`ETIMEDOUT`:return`connection_timed_out`;case`ENETUNREACH`:case`EHOSTUNREACH`:return`unreachable`;case`EACCES`:case`EPERM`:case`EPROXYAUTH`:return`permission_denied`;case`EMFILE`:case`ENFILE`:case`ENOBUFS`:case`ENOMEM`:return`resource_exhausted`;case`ECANCELED`:return`cancelled`;case`CERT_HAS_EXPIRED`:case`CERT_NOT_YET_VALID`:case`CERT_REJECTED`:case`CERT_REVOKED`:case`CERT_SIGNATURE_FAILURE`:case`CERT_UNTRUSTED`:case`DEPTH_ZERO_SELF_SIGNED_CERT`:case`ERR_TLS_CERT_ALTNAME_FORMAT`:case`SELF_SIGNED_CERT_IN_CHAIN`:case`HOSTNAME_MISMATCH`:case`INVALID_CA`:case`INVALID_PURPOSE`:case`PATH_LENGTH_EXCEEDED`:case`UNABLE_TO_GET_ISSUER_CERT`:case`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`:case`UNABLE_TO_VERIFY_LEAF_SIGNATURE`:case`ERR_TLS_CERT_ALTNAME_INVALID`:return`tls_validation_failed`;case`EPROTO`:return`tls_protocol_error`;default:return e.code?.startsWith(`ERR_SSL_`)||e.code?.startsWith(`ERR_TLS_`)?`tls_handshake_failed`:`internal`}}function xn(e,t){if(!Number.isInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}async function Sn(e,t){let n=await H.fetch(kt(e).toString(),{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw Error(`getTunnelStatus failed: ${n.status} ${await n.text()}`);return wn(await n.json())}async function Cn(e,t,n){if(!n.trim())throw Error(`tunnelId must not be empty`);let r=await H.fetch(At(e,n).toString(),{method:`DELETE`,headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw Error(`stopTunnel failed: ${r.status} ${await r.text()}`)}function wn(e){let t=Y(e,`tunnel status`),n={};return t.active!==void 0&&(n.active=Tn(t.active)),t.lastFailure!==void 0&&(n.lastFailure=kn(t.lastFailure)),t.lastDialFailure!==void 0&&(n.lastDialFailure=An(t.lastDialFailure)),n}function Tn(e){let t=Y(e,`active tunnel`),n=X(t,`state`);if(n!==`starting`&&n!==`ready`&&n!==`stopping`)throw Error(`invalid tunnel state ${n}`);return{tunnelId:Z(t,`tunnelId`),state:n,selectors:vt(t,`selectors`).map((e,t)=>Dn(e,`selector-${t+1}`)),inspection:En(t)}}function En(e){let t=Y(e.inspection,`inspection`),n=t.enabled,r=t.captureBodies,i=t.persist;if(typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`)throw Error(`inspection enabled, captureBodies, and persist must be booleans`);let a=t.maxBodyBytes,o=t.ttlSeconds;if(typeof a!=`number`||typeof o!=`number`)throw Error(`inspection maxBodyBytes and ttlSeconds must be numbers`);return Xt({enabled:n,captureBodies:r,maxBodyBytes:a,persist:i,ttlSeconds:o})}function Dn(e,t){let n=Y(e,`tunnel selector`),r=Z(n,`id`);if(r!==t)throw Error(`invalid tunnel selector id ${r}`);let i=X(n,`kind`);if(i!==`route`&&i!==`domain`)throw Error(`invalid tunnel selector kind ${i}`);return{id:r,kind:i,value:Z(n,`value`),...n.binds===void 0?{}:{binds:vt(n,`binds`).map(On)}}}function On(e){let t=Y(e,`tunnel bind report`),n=X(t,`status`);if(n!==`ok`&&n!==`conflict`&&n!==`error`)throw Error(`invalid tunnel bind status ${n}`);let r=t.osCode;if(r!==void 0&&typeof r!=`string`)throw Error(`tunnel bind osCode must be a string`);return{address:Z(t,`address`),status:n,...r===void 0?{}:{osCode:r}}}function kn(e){let t=Y(e,`tunnel failure`);return{tunnelId:Z(t,`tunnelId`),code:Z(t,`code`)}}function An(e){let t=Y(e,`tunnel dial failure`),n=t.connectionId;if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>4294967295)throw Error(`tunnel dial failure connectionId must be an unsigned 32-bit integer`);let r=t.osCode;if(r!==void 0&&typeof r!=`string`)throw Error(`tunnel dial failure osCode must be a string`);return{tunnelId:Z(t,`tunnelId`),connectionId:n,selectorId:Z(t,`selectorId`),reason:Z(t,`reason`),...r===void 0?{}:{osCode:r}}}function jn(e){if(!e)return{};if(e===!0)return{persist:!0};if(e.ttlSeconds!==void 0&&(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0))throw Error(`ttlSeconds must be a positive integer`);return{persist:!0,...e.ttlSeconds!==void 0&&{ttlSeconds:e.ttlSeconds}}}var Mn=class extends Error{};function Nn(e){let t=!1,n=0,r=0,i=0,a=0,o=!1,s=!1,c,l=n=>{t||(t=!0,u.close(),e.onError?.(n))},u=me({url:e.url,fetch:he(async(e,t)=>{let n=await H.fetch(e,t);return n.ok||(c=Error(`server answered HTTP ${n.status}`)),s=n.ok,n},e=>{c=e instanceof Error?e:Error(String(e))}),headers:{Authorization:`Bearer ${e.token}`},onConnect:()=>{n=Date.now()},onComment:()=>{o=!0},onScheduleReconnect:()=>{if(t)return;let u=Date.now(),d=performance.now(),f=n>0?u-n:0;n=0,r>0&&i>0&&u-i-(d-a)>3e4&&(r=u),i=u,a=d;let p=o||s&&f>=ge.healthyConnectionMs;if(o=!1,s=!1,p){r=0,c=void 0;return}if(r===0){r=u;return}if(u-r>=ge.giveUpAfterMs){let t=Math.round((u-r)/1e3),n=c?`; last error: ${c.message}`:``;l(new Mn(`session stream to ${e.url} kept failing for ${t}s without delivering entries${n}; the instance may no longer exist`))}},onMessage:t=>{r=0,o=!0,c=void 0;let n=typeof t.data==`string`?t.data:String(t.data??``),i;try{i=JSON.parse(n)}catch{return}typeof i?.ts==`number`&&e.onEntry(i)}});return()=>{t||(t=!0,u.close())}}export{k as A,S as C,A as D,E,y as F,M,j as N,N as O,b as P,T as S,D as T,xe as _,vn as a,H as b,_t as c,ut as d,lt as f,Te as g,we as h,Cn as i,O as j,x as k,mt as l,Je as m,jn as n,Zt as o,q as p,Sn as r,Ot as s,Nn as t,pt as u,he as v,C as w,w as x,me as y};
@@ -1 +1 @@
1
- import{t as e}from"./string-enum.js";const t=[`app`,`frontmost-app`,`desktop`,`menubar`],n=e(t,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${t.join(`|`)}.`});function r(e){return n.parse(e)}const i={app:`xctest`,"frontmost-app":`macos-helper`,desktop:`macos-helper`,menubar:`macos-helper`};function a(e){return i[e??`app`]}function o(e){return e!==void 0&&a(e)===`macos-helper`?e:void 0}export{r as i,o as n,a as r,t};
1
+ import{t as e}from"./string-enum.js";const t=[`app`,`frontmost-app`,`desktop`,`menubar`],n=e(t,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${t.join(`|`)}.`});function r(e){return n.parse(e)}const i=[`xctest`,`native`],a=`AGENT_DEVICE_MACOS_APP_BACKEND`,o=e(i,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid ${a}: ${e}. Use ${i.join(`|`)}.`});function s(e){let t=e(a);return t===void 0||t.trim()===``?`xctest`:o.parse(t)}const c={"frontmost-app":`macos-helper`,desktop:`macos-helper`,menubar:`macos-helper`};function l(e,t){let n=e??`app`;return n===`app`?t===`native`?`macos-helper`:`xctest`:c[n]}function u(e,t){let n=e??`app`;return l(n,t)===`macos-helper`?n:void 0}export{s as a,r as i,u as n,l as r,t};