agent-device 0.21.19 → 0.21.21
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.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.19.apk → agent-device-android-ime-helper-0.21.21.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.21.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.19.manifest.json → agent-device-android-ime-helper-0.21.21.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.21.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.21.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.19.manifest.json → agent-device-android-snapshot-helper-0.21.21.manifest.json} +6 -6
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift +73 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +557 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift +141 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +107 -3
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +136 -22
- package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift +88 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +133 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +10 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +36 -9
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +28 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -14
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -16
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +67 -14
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +6 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +7 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +21 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +121 -17
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +179 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +119 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +8 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +23 -11
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +59 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +112 -23
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +25 -12
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +6 -1
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +43 -13
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -5
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +2 -15
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +10 -25
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFoldProjection.swift +1 -18
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +2 -2
- package/dist/src/adb-failure.js +1 -1
- package/dist/src/adb-transport.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.js +1 -1
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/alert.js +1 -0
- package/dist/src/android-adb.d.ts +12 -0
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/app-backend.js +1 -0
- package/dist/src/app-catalog.js +1 -1
- package/dist/src/app-deployment-resolution.js +1 -1
- package/dist/src/app-inventory.js +1 -1
- package/dist/src/app-launch.js +2 -2
- package/dist/src/app-lifecycle.js +2 -2
- package/dist/src/app-lifecycle2.js +1 -1
- package/dist/src/app-log-files.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-log-session-resource.js +1 -0
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/archive.js +2 -2
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/auth-session.js +1 -1
- package/dist/src/auth.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/backend-snapshot-options.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/browser-launch.js +1 -1
- package/dist/src/cache.js +1 -1
- package/dist/src/capabilities.js +1 -1
- package/dist/src/capture.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +317 -323
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +4 -4
- package/dist/src/click-button.js +1 -1
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-options.js +3 -0
- package/dist/src/client-types.d.ts +101 -6
- package/dist/src/clipboard-shell-response.js +1 -1
- package/dist/src/{scroll-command.d.ts → cloud-artifacts.d.ts} +249 -240
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/code-signature.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/command-tools.js +2 -2
- package/dist/src/command.js +1 -1
- package/dist/src/config.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +5 -5
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-artifacts.js +1 -0
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client-liveness-probe.js +1 -0
- package/dist/src/daemon-client-transport.js +1 -1
- package/dist/src/daemon-http.js +1 -0
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/daemon-registration-owner.js +1 -0
- package/dist/src/daemon-registration.js +1 -1
- package/dist/src/daemon-resolution.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/daemon.js +2 -2
- package/dist/src/debug-symbols-facade.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-claim-rule.js +1 -1
- package/dist/src/device-inventory-context.js +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-release.js +1 -1
- package/dist/src/device-rotation.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device-session.js +1 -1
- package/dist/src/device-shell.js +1 -1
- package/dist/src/device.js +1 -1
- package/dist/src/device2.js +1 -3
- package/dist/src/device3.js +3 -0
- package/dist/src/devicectl.js +1 -1
- package/dist/src/diagnostics.js +3 -3
- package/dist/src/dispatch-resolve.js +4 -1
- package/dist/src/display-inventory.js +1 -1
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/doctor2.js +1 -1
- package/dist/src/durable-capture-resource.js +1 -0
- package/dist/src/engine-eval-script.js +1 -1
- package/dist/src/error.js +1 -1
- package/dist/src/exec.js +1 -1
- package/dist/src/file.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/host-file.js +1 -1
- package/dist/src/host.js +1 -1
- package/dist/src/human-control-contract.js +1 -1
- package/dist/src/human-control.js +1 -1
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +2 -2
- package/dist/src/install-artifact-facade.js +1 -1
- package/dist/src/install-source-network-transport.js +1 -1
- package/dist/src/install-source.d.ts +5 -0
- package/dist/src/install-source2.js +1 -1
- package/dist/src/instance-client.js +1 -0
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction-ref-policy.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor-operation-binding.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor2.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +1 -2
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/internal/run-script-http-child.js +1 -1
- package/dist/src/inventory.js +4 -4
- package/dist/src/inventory2.js +1 -1
- package/dist/src/inventory3.js +1 -1
- package/dist/src/inventory5.js +1 -1
- package/dist/src/ios-client.js +4 -30
- package/dist/src/ios-settings.js +1 -0
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/launch-confirmation.js +1 -0
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-registry-scope.js +1 -0
- package/dist/src/lease-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/legacy-xctest-device-set.js +1 -1
- package/dist/src/limrun-download-file.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +78 -44
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/load.js +1 -0
- package/dist/src/location-coordinates.js +1 -1
- package/dist/src/macos-facade.js +1 -1
- package/dist/src/managed-device-scope.js +1 -1
- package/dist/src/mechanics.js +16 -16
- package/dist/src/observation.js +1 -1
- package/dist/src/observe-until.js +1 -1
- package/dist/src/overlay.js +2 -2
- package/dist/src/owner-identity.js +3 -3
- package/dist/src/path-resolution.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-operation-builder.js +1 -1
- package/dist/src/perf-runtime-plan.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/perf.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-android-adb-host.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-managed-owner.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +2 -2
- package/dist/src/platform-runtime-runtime-hints.js +2 -2
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugins.d.ts +9 -0
- package/dist/src/plugins.js +1 -0
- package/dist/src/plugins2.js +2 -0
- package/dist/src/png-crop-bytes.js +1 -1
- package/dist/src/png-size.js +1 -1
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/png.js +1 -1
- package/dist/src/prepare-kind.js +1 -1
- package/dist/src/process.js +1 -1
- package/dist/src/project-runtime.js +1 -1
- package/dist/src/provider-credential-fingerprint.js +1 -0
- package/dist/src/provider-device-admission.js +1 -1
- package/dist/src/provider-device-runtimes.js +1 -0
- package/dist/src/provider-limrun-credentials.js +1 -0
- package/dist/src/provider-profile-fields.js +1 -0
- package/dist/src/provider-session-ownership.js +2 -2
- package/dist/src/provider-webdriver.js +2 -1
- package/dist/src/providers.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/quality-warnings.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording.js +1 -1
- package/dist/src/rect-center.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +52 -36
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/reporting.js +5 -5
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-cancel.js +1 -1
- package/dist/src/request-cancellation.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/retry.js +1 -1
- package/dist/src/runner-artifact-manifest.js +1 -1
- package/dist/src/runner-cache-metadata.js +3 -3
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-error-classification.js +2 -2
- package/dist/src/runner-exchange.js +1 -1
- package/dist/src/runner-operations-facade.js +1 -1
- package/dist/src/runner-session-types.js +1 -1
- package/dist/src/runner-start-budget.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-transport-hints.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/src/runtime10.js +2 -2
- package/dist/src/runtime2.js +3 -3
- package/dist/src/runtime3.js +1 -1
- package/dist/src/runtime4.js +5 -5
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-admission-ledger.js +1 -1
- package/dist/src/screen-recording-completion.js +1 -1
- package/dist/src/screen-recording-options.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-image.js +1 -1
- package/dist/src/screenshot-result.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot.js +1 -1
- package/dist/src/screenshot3.js +1 -1
- package/dist/src/script.js +1 -1
- package/dist/src/scroll-command.js +1 -1
- package/dist/src/scroll-gesture.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +47 -2
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +37 -8
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +2 -2
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-allocation.js +1 -1
- package/dist/src/session-artifact-paths.js +1 -1
- package/dist/src/session-repair-tombstone.js +1 -1
- package/dist/src/session-routing.js +1 -1
- package/dist/src/session-runtime-admission.js +1 -1
- package/dist/src/session-snapshot.js +1 -1
- package/dist/src/session-stream.js +27 -0
- package/dist/src/session.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settings.js +1 -1
- package/dist/src/settings2.js +1 -1
- package/dist/src/simctl-settings-facade.js +1 -0
- package/dist/src/simctl-settings.js +1 -0
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -1
- package/dist/src/snapshot4.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src7.js +1 -1
- package/dist/src/src8.js +2 -2
- package/dist/src/store.js +1 -0
- package/dist/src/string-enum.js +1 -1
- package/dist/src/surface-snapshot.js +1 -1
- package/dist/src/takeover.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/telemetry.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/toolchain-probe.js +2 -2
- package/dist/src/touch-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/transport.js +2 -2
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/vars.js +1 -1
- package/dist/src/verified-file.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/viewport.js +1 -1
- package/dist/src/web.js +1 -1
- package/dist/src/web2.js +1 -1
- package/dist/src/webdriver-source.js +1 -1
- package/package.json +5 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.19.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.19.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.19.apk.sha256 +0 -1
- package/dist/src/api.js +0 -3
- package/dist/src/daemon-process.js +0 -1
- package/dist/src/multitouch-support.js +0 -1
- package/dist/src/parameterized-recorded-fill.js +0 -1
- package/dist/src/runner-startup-transport.js +0 -1
- package/dist/src/runner-xctestrun.js +0 -1
- package/dist/src/session-store.js +0 -4
package/dist/src/png.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,t}from"./rolldown-runtime.js";import{N as n}from"./sdk-contracts.js";var r=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=n.exports=function(){i.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};r.inherits(a,i),a.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},a.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},a.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},a.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},a.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),i=t((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),a=t(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),o=t(((e,t)=>{let n=i(),r=a();function o(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let s=t.exports=function(e,t){let r=e.width,i=e.height,a=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],a){let e=n.getImagePasses(r,i);for(let t=0;t<e.length;t++)this._images.push({byteWidth:o(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:o(r,s,c),height:i,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},s.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},s.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},s.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},s.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},s.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),s=t(((t,n)=>{let i=e(`util`),a=r(),s=o(),c=n.exports=function(e){a.call(this);let t=[],n=this;this._filter=new s(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};i.inherits(c,a)})),c=t(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),l=t(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),u=t(((e,t)=>{let n=c(),r=l(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),d=t((e=>{let t=i(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function a(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function o(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function s(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,i=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=a(e,c));let f;f=c<=8?Buffer.alloc(r*i*4):new Uint16Array(r*i*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,i),g=t.getInterlaceIterator(r,i);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:i}]}for(let t=0;t<h.length;t++)c===8?m=o(h[t],f,g,l,e,m):s(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),f=t(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),p=t(((t,n)=>{let i=e(`util`),a=e(`zlib`),o=r(),c=s(),l=u(),p=d(),m=f(),h=n.exports=function(e){o.call(this),this._parser=new l(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};i.inherits(h,o),h.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},h.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=a.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,a.Z_MIN_CHUNK);this._inflate=a.createInflate({chunkSize:t});let n=e,r=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&r(e)}),this._filter.on(`complete`,this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,i(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},h.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new c(this._bitmapInfo)},h.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},h.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},h.prototype._simpleTransparency=function(){this._metaData.alpha=!0},h.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},h.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},h.prototype._complete=function(e){if(this.errord)return;let t;try{let n=p.dataToBitMap(e,this._bitmapInfo);t=m(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),m=t(((e,t)=>{let n=c();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),h=t(((e,t)=>{let n=a();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function o(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function s(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function c(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:o,2:c,3:u,4:f},h={0:i,1:s,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),g=t(((t,n)=>{let r=c(),i=l(),a=m(),o=h(),s=e(`zlib`),u=n.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:r.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:r.COLORTYPE_COLOR_ALPHA,[r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};u.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},u.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},u.prototype.filterData=function(e,t,n){let i=a(e,t,n,this._options),s=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(i,t,n,this._options,s)},u.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(i.crc32(r.slice(4,r.length-4)),r.length-4),r},u.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*r.GAMMA_DIVISION),0),this._packChunk(r.TYPE_gAMA,t)},u.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(r.TYPE_IHDR,n)},u.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},u.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),_=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=c(),o=g(),s=n.exports=function(e){i.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};r.inherits(s,i),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(a.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(i)}})),v=t(((t,n)=>{let r=e(`assert`).ok,i=e(`zlib`),a=e(`util`),o=e(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<i.Z_MIN_CHUNK&&(e.chunkSize=i.Z_MIN_CHUNK),i.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,n){if(typeof n==`function`)return i.Inflate._processChunk.call(this,e,t,n);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let n=c-t;if(r(n>=0,`have should not go down`),n>0){let e=a._buffer.slice(a._offset,a._offset+n);if(a._offset+=n,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0&&(d+=s-e,s=e,!0)}r(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},a.inherits(s,i.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=i.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}n.exports=t=d,t.Inflate=s,t.createInflate=c,t.inflateSync=d})),y=t(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),b=t((e=>{let t=y(),n=o();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),x=t(((t,n)=>{let r=!0,i=e(`zlib`),a=v();i.deflateSync||(r=!1);let o=y(),s=b(),c=u(),l=d(),p=f();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n;function u(e){n=e}let d;function f(e){d=e}function m(e){d.transColor=e}function h(e){d.palette=e}function g(){d.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:u,metadata:f,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),n)throw n;let S=Buffer.concat(y);y.length=0;let C;if(d.interlace)C=i.inflateSync(S);else{let e=((d.width*d.bpp*d.depth+7>>3)+1)*d.height;C=a(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,d);S=null;let T=l.dataToBitMap(w,d);w=null;let E=p(T,d,t.skipRescale);return d.data=E,d.gamma=_||0,d}})),S=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=c(),o=g();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n=new o(t||{}),s=[];s.push(Buffer.from(a.PNG_SIGNATURE)),s.push(n.packIHDR(e.width,e.height)),e.gamma&&s.push(n.packGAMA(e.gamma));let c=n.filterData(e.data,e.width,e.height),l=i.deflateSync(c,n.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(n.packIDAT(l)),s.push(n.packIEND()),Buffer.concat(s)}})),C=t((e=>{let t=x(),n=S();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),w=t((t=>{let n=e(`util`),r=e(`stream`),i=p(),a=_(),o=C(),s=t.PNG=function(e){r.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new i(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new a(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};n.inherits(s,r),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();const T=Buffer.from([137,80,78,71,13,10,26,10]);function E(e){return e.subarray(0,T.length).equals(T)}function D(e,t){try{return w.PNG.sync.read(e)}catch(e){throw new n(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{E as n,w as r,D as t};
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime.js";import{P as n}from"./sdk-contracts.js";var r=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=n.exports=function(){i.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};r.inherits(a,i),a.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},a.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},a.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},a.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},a.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),i=t((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),a=t(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),o=t(((e,t)=>{let n=i(),r=a();function o(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let s=t.exports=function(e,t){let r=e.width,i=e.height,a=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],a){let e=n.getImagePasses(r,i);for(let t=0;t<e.length;t++)this._images.push({byteWidth:o(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:o(r,s,c),height:i,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},s.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},s.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},s.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},s.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},s.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),s=t(((t,n)=>{let i=e(`util`),a=r(),s=o(),c=n.exports=function(e){a.call(this);let t=[],n=this;this._filter=new s(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};i.inherits(c,a)})),c=t(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),l=t(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),u=t(((e,t)=>{let n=c(),r=l(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),d=t((e=>{let t=i(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function a(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function o(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function s(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,i=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=a(e,c));let f;f=c<=8?Buffer.alloc(r*i*4):new Uint16Array(r*i*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,i),g=t.getInterlaceIterator(r,i);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:i}]}for(let t=0;t<h.length;t++)c===8?m=o(h[t],f,g,l,e,m):s(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),f=t(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),p=t(((t,n)=>{let i=e(`util`),a=e(`zlib`),o=r(),c=s(),l=u(),p=d(),m=f(),h=n.exports=function(e){o.call(this),this._parser=new l(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};i.inherits(h,o),h.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},h.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=a.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,a.Z_MIN_CHUNK);this._inflate=a.createInflate({chunkSize:t});let n=e,r=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&r(e)}),this._filter.on(`complete`,this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,i(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},h.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new c(this._bitmapInfo)},h.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},h.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},h.prototype._simpleTransparency=function(){this._metaData.alpha=!0},h.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},h.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},h.prototype._complete=function(e){if(this.errord)return;let t;try{let n=p.dataToBitMap(e,this._bitmapInfo);t=m(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),m=t(((e,t)=>{let n=c();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),h=t(((e,t)=>{let n=a();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function o(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function s(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function c(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:o,2:c,3:u,4:f},h={0:i,1:s,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),g=t(((t,n)=>{let r=c(),i=l(),a=m(),o=h(),s=e(`zlib`),u=n.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:r.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:r.COLORTYPE_COLOR_ALPHA,[r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};u.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},u.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},u.prototype.filterData=function(e,t,n){let i=a(e,t,n,this._options),s=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(i,t,n,this._options,s)},u.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(i.crc32(r.slice(4,r.length-4)),r.length-4),r},u.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*r.GAMMA_DIVISION),0),this._packChunk(r.TYPE_gAMA,t)},u.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(r.TYPE_IHDR,n)},u.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},u.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),_=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=c(),o=g(),s=n.exports=function(e){i.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};r.inherits(s,i),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(a.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(i)}})),v=t(((t,n)=>{let r=e(`assert`).ok,i=e(`zlib`),a=e(`util`),o=e(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<i.Z_MIN_CHUNK&&(e.chunkSize=i.Z_MIN_CHUNK),i.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,n){if(typeof n==`function`)return i.Inflate._processChunk.call(this,e,t,n);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let n=c-t;if(r(n>=0,`have should not go down`),n>0){let e=a._buffer.slice(a._offset,a._offset+n);if(a._offset+=n,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0&&(d+=s-e,s=e,!0)}r(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},a.inherits(s,i.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=i.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}n.exports=t=d,t.Inflate=s,t.createInflate=c,t.inflateSync=d})),y=t(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),b=t((e=>{let t=y(),n=o();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),x=t(((t,n)=>{let r=!0,i=e(`zlib`),a=v();i.deflateSync||(r=!1);let o=y(),s=b(),c=u(),l=d(),p=f();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n;function u(e){n=e}let d;function f(e){d=e}function m(e){d.transColor=e}function h(e){d.palette=e}function g(){d.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:u,metadata:f,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),n)throw n;let S=Buffer.concat(y);y.length=0;let C;if(d.interlace)C=i.inflateSync(S);else{let e=((d.width*d.bpp*d.depth+7>>3)+1)*d.height;C=a(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,d);S=null;let T=l.dataToBitMap(w,d);w=null;let E=p(T,d,t.skipRescale);return d.data=E,d.gamma=_||0,d}})),S=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=c(),o=g();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n=new o(t||{}),s=[];s.push(Buffer.from(a.PNG_SIGNATURE)),s.push(n.packIHDR(e.width,e.height)),e.gamma&&s.push(n.packGAMA(e.gamma));let c=n.filterData(e.data,e.width,e.height),l=i.deflateSync(c,n.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(n.packIDAT(l)),s.push(n.packIEND()),Buffer.concat(s)}})),C=t((e=>{let t=x(),n=S();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),w=t((t=>{let n=e(`util`),r=e(`stream`),i=p(),a=_(),o=C(),s=t.PNG=function(e){r.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new i(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new a(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};n.inherits(s,r),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();const T=Buffer.from([137,80,78,71,13,10,26,10]);function E(e){return e.subarray(0,T.length).equals(T)}function D(e,t){try{return w.PNG.sync.read(e)}catch(e){throw new n(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{E as n,w as r,D as t};
|
package/dist/src/prepare-kind.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";const t=[`auto`,`react-native`,`expo`,`repack`];function n(n){if(n!==void 0){if(t.includes(n))return n;throw new e(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}export{n as t};
|
package/dist/src/process.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{D as t,S as n,f as r,g as i,j as a,m as o,w as s}from"./owner-identity.js";import"./exec.js";import c from"node:fs";import l from"node:path";async function u(e,t={}){let n=f(),r=p(t);for(let t of e.read()){if(!d(t))continue;let i=await m(t,r,n);i.length===0?e.clear(t.scope):i.length!==t.records.length&&e.replace(t.scope,i)}return Object.freeze(n)}function d(e){return e.status===`decoded`}function f(){return{inspected:0,inspectedPids:[],terminated:0,terminatedPids:[],missing:0,missingPids:[],ownershipLost:0,ownershipLostPids:[],skippedForOpenWebSession:!1}}function p(e){return{openWebSession:(e.openWebSessionNames??[]).length>0,purposes:e.purposes?new Set(e.purposes):void 0,termTimeoutMs:e.termTimeoutMs??1500,killTimeoutMs:e.killTimeoutMs??1e3}}async function m(e,t,n){let r=[];for(let i of e.records){if(h(e.scope.kind,i,t)){r.push(i),_(e.scope.kind,i,t)&&(n.skippedForOpenWebSession=!0);continue}n.inspected+=1,n.inspectedPids.push(i.pid),v(n,i,await y(i,t),r)}return r}function h(e,t,n){return!g(t,n)||_(e,t,n)}function g(e,t){return t.purposes===void 0||t.purposes.has(e.purpose)}function _(e,t,n){return e===`daemon`&&t.purpose===`managed-web-browser`&&n.openWebSession}function v(e,t,n,r){if(n===`terminated`){e.terminated+=1,e.terminatedPids.push(t.pid);return}if(n===`missing`){e.missing+=1,e.missingPids.push(t.pid);return}e.ownershipLost+=1,e.ownershipLostPids.push(t.pid),r.push(t)}async function y(e,t){let n=b(e);return n===void 0?(T(e.pid,x(e)),await S(e,t)):n}function b(e){return e.pid===process.pid||!o(e.pid)||i(e.pid)?`missing`:w(e)?void 0:`ownership-lost`}function x(e){return e.purpose===`simctl-screen-recording`?`SIGINT`:`SIGTERM`}async function S(e,t){let n=await C(e,t.termTimeoutMs);return n===`exited`?`terminated`:n===`ownership-lost`?`ownership-lost`:(T(e.pid,`SIGKILL`),await C(e,t.killTimeoutMs)===`exited`?`terminated`:`ownership-lost`)}async function C(e,n){return await t(e.pid,n),!o(e.pid)||i(e.pid)?`exited`:w(e)?`owned-alive`:`ownership-lost`}function w(e){return s(e.pid)===e.startTime&&n(e.pid)===e.command}function T(e,t){try{process.kill(e,t)}catch{}}const E=`owned-processes.json`;function D(e){let t=l.resolve(e.stateDir),n=l.resolve(e.sessionsDir),r=l.join(t,E),i=t=>{if(t.kind===`daemon`)return r;let i=l.resolve(e.resolveSessionDir(t.sessionId));if(l.dirname(i)!==n)throw TypeError(`owned process session scope must resolve directly under the sessions dir`);return l.join(i,E)};return Object.freeze({replace(e,t){let n=A(t),r=i(e);if(n.length===0){N(r);return}let o=l.dirname(r);c.mkdirSync(o,{recursive:!0}),a(r,e=>{let t=c.openSync(e,`wx`,384);try{c.writeFileSync(t,`${JSON.stringify({version:1,processes:n})}\n`,`utf8`),c.fsyncSync(t)}finally{c.closeSync(t)}P(r),c.renameSync(e,r)})},clear(e){N(i(e))},read(){return k(n,r)}})}function O(e,t){let n;try{P(e),n=JSON.parse(c.readFileSync(e,`utf8`))}catch(n){return{scope:t,path:e,status:`invalid`,records:[],message:L(n)}}if(!M(n))return{scope:t,path:e,status:`invalid`,records:[],message:`owned process record must contain version 1 and a processes array`};try{return{scope:t,path:e,status:`decoded`,records:A(n.processes)}}catch(n){return{scope:t,path:e,status:`invalid`,records:[],message:L(n)}}}function k(e,t){let n=[];if(F(t)&&n.push(O(t,{kind:`daemon`})),!c.existsSync(e))return n;for(let t of c.readdirSync(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){if(!t.isDirectory())continue;let r=l.join(e,t.name,E);F(r)&&n.push(O(r,{kind:`session`,sessionId:t.name}))}return n}function A(e){let t=new Set,n=[];for(let r of e){if(!j(r))throw TypeError(`owned process record has an invalid identity or purpose`);if(t.has(r.pid))throw TypeError(`duplicate owned process pid ${r.pid}`);t.add(r.pid),n.push(Object.freeze({pid:r.pid,startTime:r.startTime,command:r.command,purpose:r.purpose}))}return n.sort((e,t)=>e.pid-t.pid)}function j(e){return Number.isInteger(e.pid)&&e.pid>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0&&typeof e.purpose==`string`&&e.purpose.length>0}function M(e){return typeof e==`object`&&!!e&&`version`in e&&e.version===1&&`processes`in e&&Array.isArray(e.processes)}function N(e){try{P(e),c.unlinkSync(e)}catch(e){if(!I(e))throw e}}function P(e){try{let t=c.lstatSync(e);if(t.isSymbolicLink())throw Error(`Refusing to follow an owned process record symlink`);if(!t.isFile())throw Error(`Owned process record is not a regular file`)}catch(e){if(!I(e))throw e}}function F(e){try{return c.lstatSync(e).isFile()}catch{return!1}}function I(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`)}function L(e){return e instanceof Error?e.message:`owned process record is invalid`}var R=e({hostPlatform:()=>r});export{D as n,u as r,R as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:
|
|
1
|
+
import e from"node:fs";import t from"node:path";function n(e){let t=i(e);return t?r(t):`auto`}function r(e){let t={...e.dependencies??{},...e.devDependencies??{}};return typeof t[`@callstack/repack`]==`string`?`repack`:typeof t.expo==`string`?`expo`:typeof t[`react-native`]==`string`?`react-native`:`auto`}function i(n){if(!n)return;let r=t.join(n,`package.json`);try{return JSON.parse(e.readFileSync(r,`utf8`))}catch{return}}export{r as n,i as r,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{n as t,o as n,t as r}from"./providers.js";import{r as i}from"./provider-limrun-credentials.js";import a from"node:crypto";var o=e({providerCredentialFingerprint:()=>c,readDaemonProviderCredentials:()=>l});const s=new Map([[`limrun`,i],[t.browserStack,e=>{let{username:t,accessKey:i}=n(e);return{[r.username]:t,[r.accessKey]:i}}]]);function c(e,t,n){let r=s.get(e);return r?u(r(t,n)):void 0}function l(e,t){let n={...e};return{fingerprint:(e,t)=>c(e,n,t),stateDir:t}}function u(e){let t=Object.entries(e).filter(e=>e[1]!==void 0).sort(([e],[t])=>e.localeCompare(t));if(t.length!==0)return`v1:${a.createHash(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}`}export{l as n,o as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
let e={
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{mn as t}from"./sdk-batch.js";import{t as n}from"./script.js";import{t as r}from"./session-paths.js";const i=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function a(t){if(t!==t.trim()||!n.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function o(e){return`\${${e}}`}function ee(e){let t=i.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}function s(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const c={kind:`none`};function l(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function te(e){return e.kind===`repair`?{...e,status:`armed`}:e}function u(e){return e.kind===`none`?void 0:e.target}function d(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function f(e){return e.kind===`authoring`&&e.status===`aborted`}function p(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function m(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function h(e){return{kind:`authoring`,status:`armed`,target:l(void 0,e)}}function g(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function _(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function v(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:l(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function y(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function b(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ne(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function re(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ie(e){return e.kind===`repair`?e.boundary:void 0}function ae(e){return e.kind===`repair`?e.sourcePath:void 0}function x(e){return e.kind===`repair`&&e.status!==`committed`}function S(e){let t=u(e);return t?.kind===`explicit`?t.path:void 0}function C(e){return u(e)?.force===!0}function w(e){return e?.scriptPublication??c}function T(e){let t=w(e);return t.kind===`authoring`&&t.status===`armed`}function E(e,t){e.scriptPublication=h({path:t.path===void 0?void 0:r(t.path),force:t.force===!0})}function D(e){e.scriptPublication=g(w(e))}function O(e){return p(w(e))}function k(e,t){if(!t.saveScript||f(w(e)))return;let n={path:typeof t.saveScript==`string`?r(t.saveScript):void 0,force:t.force===!0},i=w(e);if(i.kind===`repair`){e.scriptPublication=v(i,{requested:n,boundary:i.boundary,sourcePath:i.sourcePath});return}if(i.kind===`authoring`){e.scriptPublication={...i,target:l(i.target,n)};return}e.scriptPublication=h(n)}function A(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:l(n.target,{path:t.explicitPath===void 0?void 0:r(t.explicitPath),force:t.liveForce===!0})})}function j(e,t){e.scriptPublication=_(w(e),t)}function M(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication=_(n,t))}function N(e,t){return t===!0||C(w(e))}function P(e){return m(w(e))}const F=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),I=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),L=new Set([`cost`,`evidence`,`resolution`,`settle`]),R=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),z=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function oe(e,t,n){if(!e)return e;let r=ue(e.selectorChain),i=e=>K(e,t);return{...q(e,e=>le(e,t,n),i),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!i(e))}:{}}}function B(e,t){if(!e)return e;let n=X(t);return q(e,e=>Z(e,n),e=>W(e,t))}function V(e,t){if(!e)return e;let n=X(t);return{...e,...e.label===void 0?{}:{label:Z(e.label,n)},ancestry:e.ancestry.map(e=>({...e,...e.label===void 0?{}:{label:Z(e.label,n)}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===void 0?{}:{label:Z(e.scrollRegion.label,n)}}}:{}}}function H(e,t){return!!(e.label!==void 0&&U(e.label,t)||e.ancestry.some(e=>e.label&&U(e.label,t))||e.scrollRegion?.label&&U(e.scrollRegion.label,t))}function U(e,t){for(let n of t.keys())if(e.includes(n))return!0;return!1}function W(e,t){for(let n of t.keys())if(K(e,n))return!0;return!1}function G(e,t,n){return!e||!t?e:{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function K(e,n){return t(e,n)}function q(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[F.has(e)?e:t(e),se(r,e,t,n)]))}function se(e,t,n,r){return typeof e==`string`&&I.has(t)?e:t===`selectorChain`&&Q(e)?ce(e,r):J(e,n,r,L.has(t)?t:void 0)}function J(e,t,n,r){if(typeof e==`string`)return r&&z.has(r)?e:t(e);if(Array.isArray(e))return e.map(e=>J(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?R.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:t(e),J(a,t,n,o?`${r}.${e}`:void 0)]}))}function ce(e,t){return e.filter(e=>!t(e))}function le(e,t,n){if(!t)return e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}const Y=/\$\{[A-Z_][A-Z0-9_]*\}/y;function X(e){return[...e].sort(([e],[t])=>t.length-e.length)}function Z(e,t){if(!e||t.length===0)return e;let n=``,r=0;scan:for(;r<e.length;){for(let[i,a]of t)if(e.startsWith(i,r)){n+=a,r+=i.length;continue scan}if(e[r]===`$`){Y.lastIndex=r;let t=Y.exec(e);if(t){n+=t[0],r+=t[0].length;continue}}n+=e[r],r+=1}return n}function Q(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function ue(e){return Q(e)?e:void 0}let $={isActive:()=>!1};function de(e){$=e}function fe(e){return $.isActive(e)}export{C as A,p as C,b as D,y as E,a as F,s as M,ee as N,ie as O,o as P,te as S,x as T,A as _,B as a,v as b,D as c,N as d,T as f,M as g,j as h,G as i,S as j,ae as k,k as l,P as m,fe as n,V as o,O as p,oe as r,H as s,de as t,E as u,c as v,d as w,ne as x,re as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{F as t}from"./sdk-contracts.js";import{t as n}from"./provider-webdriver.js";import{i as r}from"./provider-limrun-credentials.js";var i=e({DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS:()=>a,createDaemonProviderRuntimeComposition:()=>s,createDefaultProviderRuntimeComposition:()=>c,createProviderPlatformRuntimeRegistrations:()=>o});const a=[...n.providerIds,`limrun`];function o(e){return Object.freeze(e.flatMap(e=>l(e)?[{runtime:e,module:d(e)}]:[]))}async function s(e=process.env){let t=await c(e);try{let{loadProviderPlugins:n}=await import(`./load.js`),r=await n(e,a);return Object.freeze({...t,runtimes:Object.freeze([...t.runtimes,...r.map(({runtime:e})=>e)]),platformModules:Object.freeze([...t.platformModules,...r.map(({runtime:e,platformModule:t})=>({runtime:e,module:t}))])})}catch(e){throw await Promise.allSettled(t.runtimes.map(async e=>await e.shutdown())),e}}async function c(e=process.env){let i=n.createDefaultRuntimes(e),a=[...o(i)],s;try{s=r(e)}catch(e){return Object.freeze({runtimes:i,platformModules:Object.freeze(a),skipped:[{provider:`limrun`,error:t(e)}]})}if(!s)return Object.freeze({runtimes:i,platformModules:Object.freeze(a)});let[c,l]=await Promise.all([import(`./src.js`).then(e=>e.t),import(`./limrun-runtime-dependencies.js`).then(e=>e.n)]),u=c.createLimrunRuntime(s,l.createLimrunRuntimeDependencies(),{includePlatformModule:!0});return Object.freeze({runtimes:Object.freeze([...i,u.runtime]),platformModules:Object.freeze([...a,{runtime:u.runtime,module:u.platformModule}])})}function l(e){if(!(`owner`in e)||!(`loadRuntime`in e))return!1;let t=e.owner;return typeof e.loadRuntime==`function`&&u(t)&&t.provider===e.provider}function u(e){return typeof e==`object`&&!!e&&`kind`in e&&e.kind===`provider-runtime`&&`provider`in e&&typeof e.provider==`string`&&`instance`in e&&typeof e.instance==`string`}function d(e){return Object.freeze({owner:e.owner,loadRuntime:async t=>await e.loadRuntime(t)})}export{s as n,i as r,a as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";const t={apiKey:`LIMRUN_API_KEY`,region:`LIMRUN_REGION`},n={ios:[`LIM_IOS_INSTANCE_URL`,`LIM_IOS_INSTANCE_TOKEN`],android:[`LIM_ANDROID_INSTANCE_URL`,`LIM_ANDROID_INSTANCE_TOKEN`,`LIM_ANDROID_INSTANCE_ADB_URL`]},r=[...Object.values(t),...n.ios,...n.android],i=new Map([[`ios-instance`,`ios`],[`android-instance`,`android`]]);function a(e){return e===void 0?void 0:i.get(e)}function o(e,i){let o=a(i),s=o?[...Object.values(t),...n[o]]:r;return Object.fromEntries(s.map(t=>[t,u(e,t)]))}function s(e){return n[e]}function c(e){let r=u(e,t.apiKey),i=u(e,t.region),a=[`1`,`true`].includes(e.LIMRUN_KEEP_ALIVE?.trim().toLowerCase()??``),o=l(e,n.ios),s=l(e,n.android);if(!r&&!o&&!s)return;let c={ios:o&&{apiUrl:o.LIM_IOS_INSTANCE_URL,token:o.LIM_IOS_INSTANCE_TOKEN},android:s&&{apiUrl:s.LIM_ANDROID_INSTANCE_URL,token:s.LIM_ANDROID_INSTANCE_TOKEN,adbUrl:s.LIM_ANDROID_INSTANCE_ADB_URL}};return{apiKey:r,region:i,keepAlive:a,instances:o||s?c:void 0}}function l(t,n){let r=n.map(e=>[e,u(t,e)]);if(r.every(([,e])=>e===void 0))return;let i=r.filter(([,e])=>e===void 0).map(([e])=>e);if(i.length>0)throw new e(`INVALID_ARGS`,`Limrun instance access is missing ${i.join(`, `)}.`,{hint:`Set ${n.join(`, `)} together from the instance status, or unset them all.`});return Object.fromEntries(r)}function u(e,t){return e[t]?.trim()||void 0}export{c as i,a as n,o as r,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{P as t}from"./sdk-contracts.js";import{l as n,u as r}from"./sdk-remote-config.js";var i=e({rejectRefusedProviderProfileFields:()=>a});function a(e,r){let i=Object.keys(r.fields).filter(t=>r.fields[t]===`refused`&&s(e?.[t]));if(i.length===0)return;let a=i.length!==1;throw new t(`INVALID_ARGS`,`${i.map(o).join(`, `)} ${a?`are`:`is`} not supported by ${r.label}.`,{hint:`Drop ${a?`those flags`:`the flag`} or use a provider that supports ${a?`them`:`it`}.`,provider:r.provider,flags:i.map(e=>n[e])})}function o(e){let t=r[e],i=n[e];return t?.length?`${i} (${t.join(`, `)})`:i}function s(e){return e!=null&&e!==!1&&e!==``}export{a as n,i as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}function C(e){let t=u.get(e);if(t&&(clearTimeout(t.timer),u.delete(e),w(t),t.deleteAfterDownload))try{r.rmSync(t.artifactPath,{recursive:!0,force:!0})}catch{}}function w(e){if(e.directoryArchive)try{r.rmSync(e.directoryArchive.tempDir,{recursive:!0,force:!0})}catch{}finally{e.directoryArchive=void 0}}const T=3e5,E={label:`Uploaded artifact`,expiredHint:`Uploaded artifacts expire ${T/6e4} minutes after upload. Upload the file again and retry with the new upload id.`},D=new Map;function O(e){let t=
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{l as t}from"./exec.js";import"./command.js";import n from"node:crypto";import r from"node:fs";import i from"node:os";import a from"node:path";function o(t,n){return new e(`COMMAND_FAILED`,`${t.label} not found or expired: ${n}`,{reason:`RESOURCE_EXPIRED`,hint:t.expiredHint})}function s(t,n,r,i){let a=t.get(n);if(!a)throw o(i,n);if(a.tenantId&&a.tenantId!==r)throw new e(`UNAUTHORIZED`,`${i.label} ${i.plural?`belong`:`belongs`} to a different tenant`);return a}const c=9e5,l={label:`Artifact`,expiredHint:`Downloadable artifacts are removed after download or after ${c/6e4} minutes. Re-run the command that produced the artifact and download it again.`},u=new Map;function d(e){let t=n.randomUUID(),r=Date.now(),i=setTimeout(()=>{C(t)},c);return i.unref(),u.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,artifactType:e.artifactType,fileName:e.fileName,...e.displayRotation===void 0?{}:{displayRotation:e.displayRotation},deleteAfterDownload:e.deleteAfterDownload!==!1,createdAt:r,timer:i}),t}async function f(t,n){let{entry:r,stat:i}=h(t,n),a=await g(t,r,i);if(!a)throw new e(`COMMAND_FAILED`,`Artifact path is not a regular file or directory: ${r.artifactPath}`);return a}async function p(e){let t=[];for(let[n,i]of u){if(!b(i,e))continue;let a;try{a=r.statSync(i.artifactPath)}catch{C(n);continue}let o=await m(n,i,a);o&&t.push({id:n,...i.artifactType===void 0?{}:{artifactType:i.artifactType},filename:o.fileName??n,mimeType:o.mimeType,sizeBytes:o.sizeBytes,createdAt:new Date(i.createdAt).toISOString(),expiresAt:new Date(i.createdAt+c).toISOString(),...i.displayRotation===void 0?{}:{displayRotation:i.displayRotation}})}return t}async function m(e,t,n){try{return await g(e,t,n)}catch{return null}}function h(t,n){let i=s(u,t,n,l),a;try{a=r.statSync(i.artifactPath)}catch{throw C(t),new e(`COMMAND_FAILED`,`Artifact file is missing: ${i.artifactPath}`)}return{entry:i,stat:a}}async function g(e,t,n){if(n.isFile())return{artifactPath:t.artifactPath,fileName:x(t.fileName,e),mimeType:`application/octet-stream`,sizeBytes:n.size};if(!n.isDirectory())return null;let r=await _(e,t);return{artifactPath:r.archivePath,fileName:r.fileName,mimeType:`application/gzip`,sizeBytes:r.sizeBytes}}async function _(e,t){if(t.directoryArchive&&r.existsSync(t.directoryArchive.archivePath))return t.directoryArchive;if(t.directoryArchivePromise)return await t.directoryArchivePromise;let n=v(e,t);t.directoryArchivePromise=n;try{return await n}finally{t.directoryArchivePromise===n&&(t.directoryArchivePromise=void 0)}}async function v(s,c){w(c);let d=y(x(c.fileName,a.basename(c.artifactPath)||s)),f=r.mkdtempSync(a.join(i.tmpdir(),`agent-device-download-${n.randomUUID()}-`)),p=a.join(f,d);try{await t(`tar`,[`czf`,p,`-C`,a.dirname(c.artifactPath),`--`,a.basename(c.artifactPath)],{env:{...process.env,COPYFILE_DISABLE:`1`}});let e={archivePath:p,tempDir:f,fileName:d,sizeBytes:r.statSync(p).size};if(u.get(s)!==c)throw r.rmSync(f,{recursive:!0,force:!0}),o(l,s);return c.directoryArchive=e,e}catch(t){throw r.rmSync(f,{recursive:!0,force:!0}),t instanceof e?t:new e(`COMMAND_FAILED`,`Failed to archive downloadable artifact: ${c.artifactPath}`,{artifactPath:c.artifactPath},t instanceof Error?t:void 0)}}function y(e){let t=e.toLowerCase();return t.endsWith(`.tar.gz`)||t.endsWith(`.tgz`)?e:`${e}.tar.gz`}function b(e,t){return!e.tenantId||e.tenantId===t}function x(e,t){let n=e?.trim();return n&&!S(n)?n:t}function S(e){return e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.includes(`\r`)||e.includes(`
|
|
2
|
+
`)}function C(e){let t=u.get(e);if(t&&(clearTimeout(t.timer),u.delete(e),w(t),t.deleteAfterDownload))try{r.rmSync(t.artifactPath,{recursive:!0,force:!0})}catch{}}function w(e){if(e.directoryArchive)try{r.rmSync(e.directoryArchive.tempDir,{recursive:!0,force:!0})}catch{}finally{e.directoryArchive=void 0}}const T=3e5,E={label:`Uploaded artifact`,expiredHint:`Uploaded artifacts expire ${T/6e4} minutes after upload. Upload the file again and retry with the new upload id.`},D=new Map;function O(e){let t=n.randomUUID(),r=setTimeout(()=>{A(t)},T);return r.unref(),D.set(t,{artifactPath:e.artifactPath,tempDir:e.tempDir,tenantId:e.tenantId,timer:r}),t}function k(e,t){let n=s(D,e,t,E);return clearTimeout(n.timer),n.artifactPath}function A(e){let t=D.get(e);t&&(clearTimeout(t.timer),D.delete(e),r.rmSync(t.tempDir,{recursive:!0,force:!0}))}function j(e){let t=e?.providerSessionId;return typeof t==`string`&&t.trim().length>0?t.trim():void 0}var M=class{records=new Map;now;retentionMs;constructor(e={}){this.now=e.now??(()=>Date.now()),this.retentionMs=Number.isInteger(e.retentionMs)?Math.max(0,Number(e.retentionMs)):3e5}record(e,t){let n=e.leaseProvider?.trim(),r=t.trim();if(!n||!r)return;this.prune();let i={provider:n,providerSessionId:r,leaseId:e.leaseId,tenantId:e.tenantId};this.records.set(this.key(n,r),i)}markLeaseReleased(e,t=this.now()){let n=e.leaseProvider?.trim();if(!n)return;this.prune();let r=t+this.retentionMs;for(let[t,i]of this.records)i.provider===n&&i.leaseId===e.leaseId&&this.records.set(t,{...i,retainedUntil:r})}resolve(e){let t=e.provider?.trim(),n=e.providerSessionId?.trim(),r=e.tenantId?.trim();if(!t||!n||!r)return;this.prune();let i=this.records.get(this.key(t,n));if(!(!i||i.tenantId!==r))return{...i}}prune(){let e=this.now();for(let[t,n]of this.records)n.retainedUntil!==void 0&&n.retainedUntil<=e&&this.records.delete(t)}key(e,t){return JSON.stringify([e,t])}};export{p as a,d as c,A as i,O as l,j as n,f as o,C as r,k as s,M as t,s as u};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{N as e,V as t}from"./sdk-contracts.js";import{C as n,o as r}from"./sdk-device.js";import{$t as i}from"./sdk-batch.js";import{d as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{c as s,s as c}from"./device-rotation.js";import{c as l}from"./exec.js";import"./command.js";import{a as u}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as ee}from"./webdriver-source.js";import{t as m}from"./providers.js";import h from"node:path";import te from"node:fs";import ne from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function re(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:ae(e?.launchTarget,n,r)}}function ie(e){return e===`ios`?`xctest`:`android`}function ae(...e){return e.find(e=>e!==void 0)}function oe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await ce(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),re(s,i)};return Object.freeze({fact:t=>se(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function se(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function ce(t,r,i,a,o,s,c){if(!p(r.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,f(r.capabilities,`install`),{provider:t.provider,deviceId:i.id,platform:n(i)});let l=r.prepared.uploadApp??t.uploadApp;if(l)return await l({provider:t.provider,lease:r.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}function le(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function ue(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function v(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function de(n,r){try{await r()}catch(r){n instanceof e&&(n.details={...n.details,cleanupError:t(r)})}}function fe(e,t){return typeof e==`function`?e(t):e}function y(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function pe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function me(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function he(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}const b=`webdriver_request_timeout`;function x(t){return t instanceof e&&t.details?.reason===b}function S(e){return{dispatched:e}}const C=`webdriver_connect_refused`,w=`webdriver_request_interrupted`,ge=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function _e(t){return t instanceof e&&t.details?.reason===C}const ve=new Set([`GET`,`HEAD`]);var ye=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=he(new URL(e.endpoint)),this.headers={...v(e.clientVersion),...e.auth?{Authorization:y(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??ve.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!xe(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?Ce(s):{};if(a)return{status:o,value:Se(c)};let l=we(o,c);throw A(l)&&k(D,{method:e,path:t,status:o,code:O(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(pe(t),this.endpoint),o=AbortSignal.timeout(r),s=i?AbortSignal.any([i,o]):o,c={method:e,path:t,timeoutMs:r,timeoutSignal:o,requestSignal:i},l;try{l=await fetch(a,{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:s})}catch(e){throw T(e,c,`request`)}try{return{ok:l.ok,status:l.status,text:await l.text()}}catch(e){throw T(e,c,`response`)}}};function T(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Oe(r,i,a,e):n===`request`&&be(e)?ke(r,i,e):n===`response`||e instanceof TypeError?Ae(r,i,e):e}function be(e){let t=E(e,0);return t.length>0&&t.every(e=>ge.has(e))}function E(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...E(r,t+1),...i.flatMap(e=>E(e,t+1))]}function xe(e,t,n,r){return!r?.aborted&&je(e)&&t<n}function Se(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function Ce(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function we(t,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${t}.`;return De(t,n)?new e(`COMMAND_FAILED`,i,{reason:D,status:t,response:n,...S(`no`)}):new e(`COMMAND_FAILED`,i,{status:t,response:n,...t>=500?S(`unknown`):{}})}const D=`webdriver_route_unsupported`,Te=new Set([`unknown command`,`unknown method`]),Ee=new Set([404,405,501]);function De(e,t){let n=O(t);return n===void 0?Ee.has(e):Te.has(n.toLowerCase())}function O(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function k(e,t){import(`./diagnostics2.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function A(t){return t instanceof e&&t.details?.reason===D}function Oe(t,n,r,i){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} timed out after ${r}ms.`,{reason:b,method:t,path:n,timeoutMs:r,...S(`unknown`)},i instanceof Error?i:void 0)}function ke(t,n,r){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} could not reach the driver.`,{reason:C,method:t,path:n,...S(`no`)},r instanceof Error?r:void 0)}function Ae(t,n,r){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} lost its connection to the driver.`,{reason:w,method:t,path:n,...S(`unknown`)},r instanceof Error?r:void 0)}function je(t){if(x(t)||_e(t)||t instanceof e&&t.details?.reason===w)return!0;if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return!1}var Me=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new ye(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Fe(await this.requestValue(`POST`,`/session`,{capabilities:Pe(e)},{timeoutMs:Re(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!A(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});k(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(A(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=Ie(await this.sessionRequest(`GET`,`/element/active`,void 0,Le(t)))}catch(e){if(A(e))return`unsupported`;if(Be(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,Le(t));return{id:n,rect:Ne(e)}}catch(e){if(A(e))return`unsupported`;if(Be(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(t){let n=await this.sessionRequest(`GET`,`/source`,void 0,t);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ne.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return Ne(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new e(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function Ne(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:j(n,`x`),y:j(n,`y`),width:j(n,`width`),height:j(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function j(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Pe(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Fe(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}function Ie(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function Le(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:ze(e)}}function Re(e,t){return t===void 0?e:Math.min(e,ze(t))}function ze(e){return Math.max(0,e-Date.now())}function Be(t){return t instanceof e&&Ve(t).toLowerCase()===`no such element`}function Ve(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function He(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function Ue(e){return M(ee(e,`android`).nodes)}function We(e){return M(ee(e).nodes)}function M(e){let t=e.flatMap(e=>Ge(e)&&Ke(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function Ge(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ke(e){return!!e&&e.width>=50&&e.height>=50}async function qe(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Je(t,e,r);return}catch(t){if(!A(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}async function Je(e,t,n){if(t===`rotation`){await e.setRotation(s(n));return}await e.setOrientation(c(n))}const N=1500;function Ye(e){return new Promise(t=>setTimeout(t,e))}function P(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function Xe(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ze(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Qe(e){return new $e(e.client,e.backend,e.capabilities,e.targetId)}var $e=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(t,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new e(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(t,n);let o=await this.awaitTextEntryReadiness(a,t,n);return await this.type(r),{backend:`webdriver`,x:t,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(tt(e)),await this.client.performActions(e.pointers.map(e=>He(`gesture-pointer-${e.pointerId}`,et(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=await this.readSource(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(t,this.targetId)}let{parseWebDriverSourceFacts:n}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:n(t,`android`).nodes}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw x(e)?nt(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await qe(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ze(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw P(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Xe(t,n);if(r)throw P(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw P(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(N),this.client.activeElement(N)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(N,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Ye(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([He(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?We(e):Ue(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,f(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function et(t){let n=t[0];if(!n)throw new e(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function tt(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}function nt(t){return new e(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...t.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},t)}var rt=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new Me({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:Qe({client:r,backend:ie(n.platform),capabilities:s,targetId:a.id})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=x(e)?it(e,this.options.provider,n,t):e;throw await de(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:F(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...r(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return ue({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function F(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function it(t,n,r,i){let a=t.details?.timeoutMs;return new e(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},t)}function I(e){return new at(e)}var at=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new rt(e),this.deployment=oe({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};async function L(e,t,n){return t?le({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>st(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function ot(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function st(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:ct(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function ct(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}const lt={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function R(e){let t=z(e);return{createRemoteAccessSession:async e=>B(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>B(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>B(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>ot(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function ut(t){return async({lease:n,req:r,base:i})=>{let a=await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:fe(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration}),o,s;try{if(o=await pt(a.arn,t,r),s=dt(o),!s)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(e){throw await de(e,()=>t.client.stopRemoteAccessSession(a.arn)),e}let c=o.device?.name??t.deviceName,l=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{},u=t.platform===`android`?{"appium:autoLaunch":!1}:{};return{...i,endpoint:s,platform:t.platform,deviceName:c,webdriverCapabilities:F(t.platform,c,{...u,...l}),cleanup:async()=>(await t.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function dt(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?ft(n):void 0}function ft(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function pt(t,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(t);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;ht(c),await g(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:c.status,result:c.result,timeoutMs:o-a})}const mt=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function ht(t){if(!(!t.status||!mt.has(t.status)))throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t.arn,status:t.status,result:t.result})}async function gt(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function z(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await gt(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function B(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const _t={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function V(e,t,n){return t?le({provider:e,providerSessionId:t,artifacts:St(e,t,await xt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function H(t,n,r){r?.throwIfAborted();let i=await ne.readFile(t),a=new FormData;a.set(`file`,new Blob([i]),h.basename(t));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...v(n.clientVersion),Authorization:y(n)},body:a,signal:r}),s=await o.json(),c=Ct(s);if(!o.ok||!c)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function vt(e){return async({appPath:t,options:n,signal:r})=>({appReference:await H(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function yt(e){let{"bstack:options":t,...n}=e.configured??{};return{"appium:deviceName":e.deviceName,"appium:platformVersion":e.osVersion,...e.app?{"appium:app":e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...bt(t)}}}function bt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function xt(t,n){let r=new URL(`${me(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...v(n.clientVersion),Authorization:y(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function St(e,t,n){return[U(e,t,n,`video_url`,`video`,`Session video`),U(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),U(e,t,n,`device_logs_url`,`device-log`,`Device logs`),U(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),U(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function U(e,t,n,r,i,a){let o=n[r];if(typeof o==`string`&&o.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function Ct(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}const W=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerAppiumVersion`,capability:`appiumVersion`,flag:`--provider-appium-version`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function wt(e,t){At(e);let n={};for(let r of W){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(kt(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function Tt(e){return W.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function G(t,n){let r=Tt(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function Et(e){let t={};for(let n of W){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&Dt(t,n,r)}return t}function Dt(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=Ot(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function Ot(t,n){let r=o.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:t.flag,capability:t.capability})}function kt(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function At(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}function K(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function jt(t,n){let r=z({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=q(i,`project`),c=q(a,`device`),l=Nt(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${J(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?Mt(q(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:J(s.name),reference:t.projectArn},device:{status:`verified`,name:J(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:J(c.os),availability:J(c.availability)},app:u}}function Mt(t,n){let r=J(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=J(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:J(t.name),reference:n.appArn}}function q(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function Nt(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function J(e){return typeof e==`string`&&e.length>0?e:void 0}async function Pt(t,n){let r={username:t.username,accessKey:t.accessKey},i=Lt(await Y(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&It(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await Ft(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function Ft(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Rt(await Y(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:h.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function Y(t,n,r){try{let i=await fetch(t,{headers:{...v(r),Authorization:y(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function It(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Lt(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=X(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Rt(t){let n=X(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=X(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function X(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function zt(e,t){return e.provider===`browserstack`?await Pt(e,t.clientVersion):await jt(e,t.runHostCommand)}function Bt(e){return[{provider:m.browserStack,createRuntime:t=>I({clientVersion:e.clientVersion,provider:m.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:_t,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await V(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=Ut(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Wt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await Vt({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:vt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:yt({deviceName:l,osVersion:u,app:d,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:wt(Et(a.flags),c),configured:F(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await V(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,createRuntime:t=>I({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:lt,listArtifacts:async({provider:n,providerSessionId:r})=>await L(n,r,R({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??K(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=Ut(n,`AWS Device Farm`);G(a.flags,m.awsDeviceFarm);let o=Wt(a,`AWS Device Farm`);return await ut({client:R({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Gt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Gt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:Kt(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=R({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??K(t)});return await L(m.awsDeviceFarm,t,r)}}]}async function Vt(t){if(Ht(t.app))return t.app;let n=h.resolve(t.cwd??process.cwd(),t.app);if(!te.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await H(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint},t.signal)}function Ht(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function Ut(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Wt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(t,n,r){let i=Q(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Gt(t,n,r,i,a){let o=Q(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${qt(String(r))} or ${a}.`)}function Kt(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function qt(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Jt(e){let t=Bt(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await zt(t,e)}}const Yt=Jt({clientVersion:u(),runHostCommand:async(e,t)=>({stdout:(await l(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{K as n,G as r,Yt as t};
|
|
1
|
+
import{H as e,P as t}from"./sdk-contracts.js";import{o as n,w as r}from"./sdk-device.js";import{$t as i}from"./sdk-batch.js";import{d as a}from"./scroll-gesture.js";import{c as o,l as s}from"./sdk-remote-config.js";import"./device.js";import{c,l}from"./device-rotation.js";import{l as u}from"./exec.js";import"./command.js";import{a as ee}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as te}from"./webdriver-source.js";import{i as ne,n as m,o as re,r as ie,t as h}from"./providers.js";import ae from"node:fs";import g from"node:path";import oe,{readFile as se,stat as ce}from"node:fs/promises";import{setTimeout as le}from"node:timers/promises";function ue(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:fe(e?.launchTarget,n,r)}}function de(e){return e===`ios`?`xctest`:`android`}function fe(...e){return e.find(e=>e!==void 0)}function pe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await he(e,o,t,n,r.uploadPath,i,a);return await o.client.installApp(s?.appReference??r.appPath,a),ue(s,i)},n=async(e,n,r,i,a)=>await t(e,n,{appPath:r,uploadPath:r},i,a);return Object.freeze({fact:t=>me(e.findSessionForDevice(t)),installApp:n,installInstallablePath:async(e,t,r,i)=>await n(e,``,t,r,i),deployApp:async(e,t,r)=>ge(await n(e,t.app,t.appPath,{relaunch:t.replaceExisting,appIdentifierHint:t.app,packageNameHint:t.app},r),t.app),deployMaterializedApp:async(e,n,r)=>ge(await t(e,``,{appPath:n.artifact.installablePath,uploadPath:n.artifact.uploadPath??n.artifact.installablePath},{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function me(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function he(e,n,i,a,o,s,c){if(!p(n.capabilities,`install`))throw new t(`UNSUPPORTED_OPERATION`,f(n.capabilities,`install`),{provider:e.provider,deviceId:i.id,platform:r(i)});let l=n.prepared.uploadApp??e.uploadApp;if(l)return await l({provider:e.provider,lease:n.lease,device:i,app:a,appPath:o,options:s,signal:c})}function ge(e,n){if(!e)throw new t(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{packageName:e.packageName}:{},...e.appName?{appName:e.appName}:{},...e.launchTarget??n?{launchTarget:e.launchTarget??n}:{}}}function _e(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function ve(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function _(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function v(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function ye(n,r){try{await r()}catch(r){n instanceof t&&(n.details={...n.details,cleanupError:e(r)})}}function be(e,t){return typeof e==`function`?e(t):e}function y(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function xe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function Se(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function Ce(e,t){let n=new URL(e);return n.pathname=`${Se(n.pathname)}/${t}`,n}function we(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function Te(e,n,r){if(!(await ce(e).catch(()=>void 0))?.isFile())throw new t(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(n,new Blob([await se(e)]),g.basename(e)),i}async function Ee(e,n,r){let i=await fetch(n.endpoint,{method:`POST`,headers:{...v(n.clientVersion),Authorization:y(n.auth)},body:e,signal:r}),a=await x(i),o=n.readAppReference(a)?.trim();if(!i.ok||!o)throw new t(`COMMAND_FAILED`,`${n.service} app upload failed.`,{status:i.status,response:a});return o}function De(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function Oe(e){let{app:n}=e,r=e.parseReference(n);if(r!==void 0)return r;if(/^https?:\/\//i.test(n))return n;let i=g.resolve(e.cwd??process.cwd(),n);if(!ae.existsSync(i))throw new t(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:n});return await e.uploadFile(i,e.signal)}const b=15e3;async function ke(e,n){let{service:r,unauthorizedHint:i,networkHint:a}=n.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...v(n.clientVersion),Authorization:y(n.auth)},signal:AbortSignal.timeout(b)});if(!a.ok){let e=a.status===401||a.status===403;throw new t(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await x(a);if(s===void 0)throw new t(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof t?e:new t(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function Ae(e,n){let r,i;try{r=await fetch(e,{headers:{...v(n.clientVersion),Authorization:y(n.auth)},signal:AbortSignal.timeout(b)}),i=await x(r)}catch(e){throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{hint:`Check network access to the ${n.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{status:r.status,response:i});return a}async function x(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function je(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Me(e,n){let r=o.find(e=>e===n);if(r)return r;throw new t(`INVALID_ARGS`,`Invalid ${e.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:e.flag,capability:e.capability})}const S=`webdriver_request_timeout`;function C(e){return e instanceof t&&e.details?.reason===S}function w(e){return{dispatched:e}}const T=`webdriver_connect_refused`,E=`webdriver_request_interrupted`,Ne=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function Pe(e){return e instanceof t&&e.details?.reason===T}const Fe=new Set([`GET`,`HEAD`]),Ie=Object.freeze({});var Le=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=we(new URL(e.endpoint)),this.headers={...v(e.clientVersion),...e.auth?{Authorization:y(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??Fe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!ze(e,a,r.retryAttempts,r.signal))throw e;await le(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?Ve(s):{};if(a)return{status:o,value:Be(c)};let l=He(o,c);throw N(l)&&M(k,{method:e,path:t,status:o,code:j(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(xe(t),this.endpoint),o=n===void 0&&e===`POST`?Ie:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw D(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw D(e,l,`response`)}}};function D(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Ke(r,i,a,e):n===`request`&&Re(e)?qe(r,i,e):n===`response`||e instanceof TypeError?Je(r,i,e):e}function Re(e){let t=O(e,0);return t.length>0&&t.every(e=>Ne.has(e))}function O(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...O(r,t+1),...i.flatMap(e=>O(e,t+1))]}function ze(e,t,n,r){return!r?.aborted&&Ye(e)&&t<n}function Be(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function Ve(e){try{return JSON.parse(e)}catch(n){throw new t(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},n)}}function He(e,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return Ge(e,n)?new t(`COMMAND_FAILED`,i,{...A(),status:e,response:n}):new t(`COMMAND_FAILED`,i,{status:e,response:n,...e>=500?w(`unknown`):{}})}const k=`webdriver_route_unsupported`;function A(){return{reason:k,...w(`no`)}}const Ue=new Set([`unknown command`,`unknown method`]),We=new Set([404,405,501]);function Ge(e,t){let n=j(t);return n===void 0?We.has(e):Ue.has(n.toLowerCase())}function j(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function M(e,t){import(`./diagnostics2.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function N(e){return e instanceof t&&e.details?.reason===k}function Ke(e,n,r,i){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} timed out after ${r}ms.`,{reason:S,method:e,path:n,timeoutMs:r,...w(`unknown`)},i instanceof Error?i:void 0)}function qe(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} could not reach the driver.`,{reason:T,method:e,path:n,...w(`no`)},r instanceof Error?r:void 0)}function Je(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} lost its connection to the driver.`,{reason:E,method:e,path:n,...w(`unknown`)},r instanceof Error?r:void 0)}function Ye(e){if(C(e)||Pe(e)||e instanceof t&&e.details?.reason===E)return!0;if(e instanceof t){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Xe=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Le(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Qe(await this.requestValue(`POST`,`/session`,{capabilities:Ze(e)},{timeoutMs:et(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!N(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});M(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(N(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=$e(await this.sessionRequest(`GET`,`/element/active`,void 0,I(t)))}catch(e){if(N(e))return`unsupported`;if(R(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,I(t));return{id:n,rect:P(e)}}catch(e){if(N(e))return`unsupported`;if(R(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(e){let n=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(e){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await oe.writeFile(e,Buffer.from(n,`base64`))}async windowRect(){return P(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new t(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function P(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=e,r={x:F(n,`x`),y:F(n,`y`),width:F(n,`width`),height:F(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function F(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ze(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Qe(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=e,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new t(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}function $e(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function I(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:L(e)}}function et(e,t){return t===void 0?e:Math.min(e,L(t))}function L(e){return Math.max(0,e-Date.now())}function R(e){return e instanceof t&&tt(e).toLowerCase()===`no such element`}function tt(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function z(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function nt(e){return it(te(e,`android`).nodes)}function rt(e){return it(te(e).nodes)}function it(e){let t=e.flatMap(e=>at(e)&&ot(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function at(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function ot(e){return!!e&&e.width>=50&&e.height>=50}async function st(e,n,r){let i=[];for(let t of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await ct(e,t,r);return}catch(e){if(!N(e))throw e;i.push({transport:t,error:e instanceof Error?e.message:String(e)})}throw new t(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...A(),hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}async function ct(e,t,n){if(t===`rotation`){await e.setRotation(l(n));return}await e.setOrientation(c(n))}const B=1500;function lt(e){return new Promise(t=>setTimeout(t,e))}function V(e,n,r){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function ut(e,n){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:e,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function dt(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function ft(e){return new pt(e.client,e.backend,e.capabilities,e.targetId)}var pt=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new t(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(e,n);let o=await this.awaitTextEntryReadiness(a,e,n);return await this.type(r),{backend:`webdriver`,x:e,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport(ht(e)),await this.client.performActions(e.pointers.map(e=>z(`gesture-pointer-${e.pointerId}`,mt(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=await this.readSource(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(t,this.targetId)}let{parseWebDriverSourceFacts:n}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:n(t,`android`).nodes}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw C(e)?gt(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await st(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
|
|
2
|
+
`);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(B);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new t(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||dt(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw V(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw ut(t,n);if(r)throw V(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw V(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(B),this.client.activeElement(B)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(B,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await lt(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([z(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?rt(e):nt(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new t(`UNSUPPORTED_OPERATION`,f(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function mt(e){let n=e[0];if(!n)throw new t(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function ht(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}function gt(e){return new t(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}var _t=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;let{rejectRefusedProviderProfileFields:n}=await import(`./provider-profile-fields.js`).then(e=>e.t);if(n(t?.flags,this.options.profileFields),this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let r=await this.prepareSession(e,t),i=new Xe({clientVersion:this.options.clientVersion,endpoint:r.endpoint,auth:r.auth,headers:r.headers,requestPolicy:this.options.requestPolicy}),a=await this.createSessionWithPreparedCleanup(i,r,e,t),o=this.deviceForLease(e,r),s=r.providerSessionId??a.sessionId,c=d({provider:this.options.provider,platform:r.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:o,client:i,prepared:r,capabilities:c,webDriverSessionId:a.sessionId,providerSessionId:s,interactor:ft({client:i,backend:de(r.platform),capabilities:c,targetId:o.id})})),this.ownedDeviceIds.add(o.id),{provider:this.options.provider,deviceId:o.id,sessionId:a.sessionId,providerSessionId:s,capabilities:c,...r.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=C(e)?vt(e,this.options.provider,n,t):e;throw await ye(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:H(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...n(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(t){let n=[],r;try{await t.client.deleteSession()}catch(t){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:e(t)})}try{r=await t.prepared.cleanup?.()}catch(t){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:e(t)})}return{cleanup:r,warnings:n}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return ve({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function H(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function vt(e,n,r,i){let a=e.details?.timeoutMs;return new t(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}function yt(e){return new bt(e)}var bt=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new _t(e),this.deployment=pe({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};async function xt(e,t,n){return t?_e({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Ct(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function St(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Ct(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:wt(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function wt(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}const Tt={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function U(e){let t=Nt(e);return{createRemoteAccessSession:async e=>W(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>W(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>W(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>St(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function Et(e){return async({lease:n,req:r,base:i})=>{let a=await e.client.createRemoteAccessSession({projectArn:e.projectArn,deviceArn:e.deviceArn,appArn:e.appArn,name:be(e.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:e.interactionMode,configuration:e.configuration}),o,s;try{if(o=await kt(a.arn,e,r),s=Dt(o),!s)throw new t(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(t){throw await ye(t,()=>e.client.stopRemoteAccessSession(a.arn)),t}let c=o.device?.name??e.deviceName,l=typeof e.webdriverCapabilities==`function`?e.webdriverCapabilities(n):e.webdriverCapabilities??{},u=e.platform===`android`?{"appium:autoLaunch":!1}:{};return{...i,endpoint:s,platform:e.platform,deviceName:c,webdriverCapabilities:H(e.platform,c,{...u,...l}),cleanup:async()=>(await e.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function Dt(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?Ot(n):void 0}function Ot(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function kt(e,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(e);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;jt(c),await le(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(e)}throw new t(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:e,status:c.status,result:c.result,timeoutMs:o-a})}const At=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function jt(e){if(!(!e.status||!At.has(e.status)))throw new t(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:e.arn,status:e.status,result:e.result})}async function Mt(e,n,r){let i=await e(n,r);try{return JSON.parse(i.stdout)}catch(e){throw new t(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,e)}}function Nt(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await Mt(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function W(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:e});let n=e.remoteAccessSession;if(!n||typeof n!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:e});return n}const Pt={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function Ft(e,t,n){return t?_e({provider:e,providerSessionId:t,artifacts:Ht(e,t,await Vt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function It(e,t,n){return n?.throwIfAborted(),await Ee(await Te(e,`file`,{provider:m.browserStack,service:`BrowserStack`}),{service:`BrowserStack`,endpoint:t.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,clientVersion:t.clientVersion,auth:t,readAppReference:Ut},n)}function Lt(e){return De(async(t,n)=>await It(t,e,n))}function G(e){let n=ie(e);if(n===void 0||ne(n))return n;throw new t(`INVALID_ARGS`,`BrowserStack --provider-app ${e} is not a bs:// app id.`,{providerApp:e,hint:`Pass <bs://app-id-or-local-path>.`})}async function Rt(e,t){return await Oe({service:`BrowserStack`,app:e,cwd:t.cwd,referenceLabel:`a bs:// app id`,parseReference:G,uploadFile:async(e,n)=>await It(e,t,n),signal:t.signal})}function zt(e){let{"bstack:options":t,...n}=e.configured??{};return{"appium:deviceName":e.deviceName,"appium:platformVersion":e.osVersion,...e.app?{"appium:app":e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},...Bt(t)}}}function Bt(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function Vt(e,t){let n=await Ae(Ce(t.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`,`${e}.json`),{clientVersion:t.clientVersion,auth:t,service:`BrowserStack`});return Bt(n.automation_session??n)}function Ht(e,t,n){return[_(e,t,n,`video_url`,`video`,`Session video`),_(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),_(e,t,n,`device_logs_url`,`device-log`,`Device logs`),_(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),_(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function Ut(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}const Wt=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,type:`string`},{field:`providerTimezone`,capability:`timezone`,type:`string`},{field:`providerAppiumVersion`,capability:`appiumVersion`,type:`string`},{field:`providerLanguage`,capability:`language`,type:`string`},{field:`providerLocale`,capability:`locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,type:`negated-boolean`,platform:`ios`}].map(e=>({...e,flag:s[e.field]}));function Gt(e,t){Yt(e);let n={};for(let r of Wt){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(Jt(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function Kt(e){let t={};for(let n of Wt){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&qt(t,n,r)}return t}function qt(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=Me(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function Jt(e,n){if(!(!e.platform||e.platform===n))throw new t(`INVALID_ARGS`,`${e.flag} applies to ${e.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${e.flag} or connect with --platform ${e.platform}.`,flag:e.flag,capability:e.capability,platform:n})}function Yt(e){if(!(!e.providerNetworkProfile||!e.providerCustomNetwork))throw new t(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:e.providerNetworkProfile,customNetwork:e.providerCustomNetwork})}function K(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function Xt(e,n){let r=Nt({runHostCommand:n,region:e.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,e.projectArn]),r(`get-device`,[`--arn`,e.deviceArn]),e.appArn?r(`get-upload`,[`--arn`,e.appArn]):void 0]),s=q(i,`project`),c=q(a,`device`),l=Qt(c.platform);if(l!==e.platform)throw new t(`INVALID_ARGS`,`AWS Device Farm device "${J(c.name)??e.deviceArn}" is ${l}, not ${e.platform}.`);let u=e.appArn?Zt(q(o,`upload`),e):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:e.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:J(s.name),reference:e.projectArn},device:{status:`verified`,name:J(c.name)??e.deviceArn,reference:e.deviceArn,platform:l,osVersion:J(c.os),availability:J(c.availability)},app:u}}function Zt(e,n){let r=J(e.status);if(r!==`SUCCEEDED`)throw new t(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=J(e.type);if(a!==i)throw new t(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:J(e.name),reference:n.appArn}}function q(e,n){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=e[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new t(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function Qt(e){if(e===`ANDROID`)return`android`;if(e===`IOS`)return`ios`;throw new t(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(e)}.`)}function J(e){return typeof e==`string`&&e.length>0?e:void 0}async function $t(e,n){let r=en(e.app),i={username:e.username,accessKey:e.accessKey},a=rn(await nn(e.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,i,n)).find(t=>t.device===e.deviceName&&t.os.toLowerCase()===e.platform&&je(t.osVersion,e.osVersion));if(!a)throw new t(`INVALID_ARGS`,`BrowserStack device "${e.deviceName}" with ${e.platform} ${e.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let o=await tn(r,e,i,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:o.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:a.device,platform:e.platform,osVersion:a.osVersion},app:o}}function en(e){return G(e)??e}async function tn(e,t,n,r){if(ne(e)){let i=an(await nn(t.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,n,r)).find(t=>t.reference===e);return i?{status:`verified`,...i}:{status:`configured`,reference:e,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(e)?{status:`configured`,reference:e,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:g.basename(e),reference:e,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function nn(e,t,n){return await ke(e,{clientVersion:n,auth:t,hints:{service:`BrowserStack`,unauthorizedHint:`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`,networkHint:`Check network access to api-cloud.browserstack.com and retry connect.`}})}function rn(e){if(!Array.isArray(e))throw new t(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return e.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function an(e){let n=Y(e);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(e))throw new t(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return e.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function on(e,t){return e.provider===`browserstack`?await $t(e,t.clientVersion):await Xt(e,t.runHostCommand)}const sn={provider:m.browserStack,label:`BrowserStack`,fields:{providerApp:`consumed`,providerOsVersion:`consumed`,providerProject:`consumed`,providerBuild:`consumed`,providerSessionName:`consumed`,providerDeviceOrientation:`consumed`,providerGeoLocation:`consumed`,providerTimezone:`consumed`,providerAppiumVersion:`consumed`,providerLanguage:`consumed`,providerLocale:`consumed`,providerNetworkProfile:`consumed`,providerCustomNetwork:`consumed`,providerNoResignApp:`consumed`,awsProjectArn:`refused`,awsDeviceArn:`refused`,awsAppArn:`refused`,awsRegion:`refused`,awsInteractionMode:`refused`}},cn={provider:m.awsDeviceFarm,label:`AWS Device Farm`,fields:{providerApp:`refused`,providerOsVersion:`refused`,providerProject:`refused`,providerBuild:`refused`,providerSessionName:`consumed`,providerDeviceOrientation:`refused`,providerGeoLocation:`refused`,providerTimezone:`refused`,providerAppiumVersion:`refused`,providerLanguage:`refused`,providerLocale:`refused`,providerNetworkProfile:`refused`,providerCustomNetwork:`refused`,providerNoResignApp:`refused`,awsProjectArn:`consumed`,awsDeviceArn:`consumed`,awsAppArn:`consumed`,awsRegion:`consumed`,awsInteractionMode:`consumed`}},ln={[m.browserStack]:sn,[m.awsDeviceFarm]:cn};function un(e){return[{provider:m.browserStack,profileFields:sn,createRuntime:(t,n)=>yt({clientVersion:e.clientVersion,provider:m.browserStack,profileFields:n,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:Pt,listArtifacts:async({provider:n,providerSessionId:r})=>{let{username:i,accessKey:a}=$(t,`BrowserStack artifact lookup`);return await Ft(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`BrowserStack`),{username:o,accessKey:s}=$(t,`BrowserStack`),c=dn(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),ee=await Rt(Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),{clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,cwd:a.cwd,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:Lt({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:zt({deviceName:l,osVersion:u,app:ee,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:Gt(Kt(a.flags),c),configured:H(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let{username:r,accessKey:i}=$(n,`BrowserStack artifact lookup`);return await Ft(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,profileFields:cn,createRuntime:(t,n)=>yt({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,profileFields:n,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:Tt,listArtifacts:async({provider:n,providerSessionId:r})=>await xt(n,r,U({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??K(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`AWS Device Farm`),o=dn(a,`AWS Device Farm`);return await Et({client:U({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:fn(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:fn(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:pn(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=U({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??K(t)});return await xt(m.awsDeviceFarm,t,r)}}]}function X(e,n){if(e)return e;throw new t(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function dn(e,n){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new t(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(e,n,r){let i=Q(e,n);if(i)return i;throw new t(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function fn(e,n,r,i,a){let o=Q(e,r)??n[i]??n[a];if(o)return o;throw new t(`INVALID_ARGS`,`AWS Device Farm requires --${mn(String(r))} or ${a}.`)}function pn(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function mn(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function $(e,n){let{username:r,accessKey:i}=re(e);if(r&&i)return{username:r,accessKey:i};let a=r?h.accessKey:h.username;throw new t(`INVALID_ARGS`,`${n} requires ${a} in the environment.`)}function hn(e){let t=un(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e,t.profileFields)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await on(t,e)}}const gn=hn({clientVersion:ee(),runHostCommand:async(e,t)=>({stdout:(await u(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{G as a,K as i,ln as n,$ as r,gn as t};
|
package/dist/src/providers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={browserStack:`browserstack`,awsDeviceFarm:`aws-device-farm`},t=new Set(Object.values(e));function n(e){return e!==void 0&&t.has(e)}export{n,e as t};
|
|
1
|
+
const e={browserStack:`browserstack`,awsDeviceFarm:`aws-device-farm`},t=new Set(Object.values(e));function n(e){return e!==void 0&&t.has(e)}const r={username:`BROWSERSTACK_USERNAME`,accessKey:`BROWSERSTACK_ACCESS_KEY`};function i(e){return{username:e[r.username]||void 0,accessKey:e[r.accessKey]||void 0}}const a=`bs://`;function o(e){if(e.slice(0,5).toLowerCase()===a)return`${a}${e.slice(5)}`}function s(e){return/^bs:\/\/[\w.-]+$/.test(e)}export{n as a,s as i,e as n,i as o,o as r,r as t};
|
package/dist/src/proxy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{J as e,P as t}from"./sdk-contracts.js";import{v as n}from"./owner-identity.js";import{a as r,c as i,f as a,i as o,l as s,n as c,o as l,p as u,r as d,s as f,t as p,u as m}from"./daemon-http.js";import{a as h,r as ee}from"./transport.js";import"./process.js";import{a as te}from"./version.js";import{t as ne}from"./shared.js";import{ensureDaemon as re,resolveClientSettings as ie}from"./daemon-client-lifecycle.js";import{n as g,t as _}from"./color.js";import{randomBytes as v,randomUUID as y}from"node:crypto";import{Readable as b}from"node:stream";import{pipeline as x}from"node:stream/promises";import S from"node:http";function C(e){let t=T(e);if(!t)return!1;let n=O(t.meta);return E(n)?!1:D(t.source)||D(n?.installSource)}function w(n,r){let i=new t(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});n.statusCode=400,n.setHeader(`content-type`,`application/json`),n.end(JSON.stringify({jsonrpc:`2.0`,id:r,error:{code:-32602,message:i.message,data:e(i)}}))}function T(e){if(e)try{return O(O(JSON.parse(e))?.params)}catch{return}}function E(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function D(e){return O(e)?.kind===`path`}function O(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const k=`${p}/`,A=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,l],j=[`content-type`,`content-disposition`,`x-request-id`,d];function M(e){let t=W(e),n=y();return S.createServer((e,r)=>{N(e,r,t,n).catch(e=>{ye(r,e)})})}async function N(e,t,n,r){let i=q(e.url??`/`);if(e.method===`GET`&&i===`/health`){await P(t,n,r);return}if(!J(i,e.method)){t.statusCode=404,t.end(`Not found`);return}let a;if(i===`/rpc`&&(a=(await ee(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!de(e,n.clientToken,a)){ve(t,i,Z(a));return}if(!ge(e,t,i,Z(a),r)){if(C(a)){w(t,Z(a));return}await I({req:e,res:t,route:i,options:n,rpcBody:a})}}async function P(e,t,r){let a=await F(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(i(`agent-device-proxy`,te(),{upstream:a,instanceId:r,hostArch:await n()})))}async function F(e){let t=new URL(a(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:X({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function I(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=ce(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=X(t,i.upstreamToken,r),l=ue(t,r,a,i.upstreamToken);await R({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:L(t,n,i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}function L(e,n,r){let i=new AbortController,a=()=>{n.writableFinished||i.signal.aborted||i.abort(new t(`COMMAND_FAILED`,`Proxy client disconnected before the upstream response ended`))};return e.on(`aborted`,a),n.on(`close`,a),AbortSignal.any([i.signal,AbortSignal.timeout(r)])}async function R(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,z(i,n),B(t,n),Y(r)){await V({req:t,res:n,response:i,clientToken:a});return}await ae(i,n)}function z(e,t){for(let n of j){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function B(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,he(e))}async function V(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(H(a,t,i))}function H(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let i=r;if(!i.upload||typeof i.upload.url!=`string`)return e;let a=U(i.upload.url,t);if(!a)return e;let o=i.upload.headers&&typeof i.upload.headers==`object`?{...i.upload.headers}:{};return Object.assign(o,s(n)),JSON.stringify({...r,upload:{...i.upload,url:a,headers:o}})}function U(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function ae(e,t){if(!e.body){t.end();return}await x(b.fromWeb(e.body),t)}function W(e){return{upstreamBaseUrl:G(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:K(e.upstreamToken,`upstreamToken`),clientToken:K(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function G(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function K(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function q(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(k)?`/${t.slice(k.length)}`:t}function J(e,t){return e===`/rpc`?t===`POST`:se(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)||oe(e)?t===`GET`:!1}function oe(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function se(e,t){return e===`/upload`||Y(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function Y(e){return e===`/upload/preflight`}function ce(e,t,n){let r=new URL(a(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function le(e){let t=e.headers[f];return typeof t==`string`?{[c]:t}:{}}function X(e,t,n){let i=new Headers;for(let t of A){let n=e.headers[t];typeof n==`string`&&n.trim()&&i.set(t,n)}if(n===`/rpc`&&!i.has(`content-type`)&&i.set(`content-type`,`application/json`),n===`/rpc`){i.set(o,r);for(let[t,n]of Object.entries(le(e)))i.set(t,n)}for(let[e,n]of Object.entries(s(t)))i.set(e,n);return i}function ue(e,t,n,r){if(e.method!==`GET`&&e.method!==`HEAD`)return t===`/rpc`?pe(n??``,r):e}function de(e,t,n){let r=fe(e,n);return r.length>0&&h(r,t)}function fe(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=me(t);if(e)return e}return``}function pe(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function me(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Z(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function he(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):y()}function ge(e,t,n,r,i){if(n!==`/rpc`)return!1;let a=e.headers[c];return typeof a!=`string`||a===i?!1:(_e(t,r),!0)}function _e(n,r){n.statusCode=409,n.setHeader(`content-type`,`application/json`),n.setHeader(d,`true`),n.end(JSON.stringify(u(r,`Proxy instance changed`,e(new t(`COMMAND_FAILED`,`Proxy instance changed`,{reason:`remote_instance_mismatch`})))))}function ve(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function ye(t,n){if(t.destroyed)return;if(t.headersSent){t.destroy(n instanceof Error?n:void 0);return}let r=e(n);t.statusCode=r.code===`INVALID_ARGS`?400:500,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const be=async({positionals:e,flags:n})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await xe(n);return await ne(n,r,()=>Te(r)),await Ee(),!0};async function xe(e){let n=ie({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:e.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await re(n),i=Q(r.info.httpPort),a=Se(e),o=M({upstreamBaseUrl:i,upstreamToken:r.info.token,clientToken:a});await Ce(o,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let s=o.address();if(!s||typeof s==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let c=`http://${we(s.address)}:${s.port}`;return{proxyBaseUrl:c,agentDeviceBaseUrl:m(c),token:a,upstreamBaseUrl:i,stateDir:n.paths.baseDir}}function Q(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function Se(e){return e.daemonAuthToken?.trim()||v(32).toString(`hex`)}function Ce(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function we(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function Te(e,t={}){let n=t.useColor??g(),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(`
|
|
2
2
|
`)}function $(e,t,n){return n?_(e,t,{validateStream:!1}):e}function Ee(){return new Promise(()=>{})}export{be as proxyCommand};
|