@agent-device/revyl 0.21.38 → 0.21.39

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/README.md CHANGED
@@ -9,7 +9,8 @@ npm install -g agent-device
9
9
  agent-device plugins add @agent-device/revyl
10
10
  export REVYL_API_KEY=your-api-key
11
11
  export AGENT_DEVICE_SESSION=checkout-ios
12
- agent-device connect revyl --platform ios --provider-app https://apps.example.com/MyApp-simulator.zip
12
+ agent-device connect revyl --platform ios
13
+ agent-device install com.example.app ./build/MyApp.app
13
14
  agent-device open com.example.app
14
15
  agent-device snapshot -i
15
16
  agent-device close
@@ -1 +1 @@
1
- import{n as e,t}from"./device.mjs";import{t as n}from"./errors.mjs";import{i as r}from"./credentials.mjs";import{r as i}from"./revyl-client.mjs";import{n as a,r as o,revylTextFlag as s,t as c}from"./session-allocation.mjs";function l(n){return{resolve:({flags:e})=>{a(e,c),r(n.env,`connect ${t}`);let i=f(e),o=p(e.providerApp,n),l=s(e.device),u=s(e.providerOsVersion);return{profile:{leaseProvider:t,platform:i,...l===void 0?{}:{device:l},providerApp:o,...u===void 0?{}:{providerOsVersion:u}},extraFlags:{providerApp:o}}},verify:async({flags:i})=>{a(i,c);let l=s(i.device),d=s(i.providerOsVersion);return await u(r(n.env,`connect ${t}`),n.clientVersion,o(i.platform,e),{appUrl:m(i.providerApp),...l===void 0?{}:{deviceModel:l},...d===void 0?{}:{osVersion:d}})}}}async function u(r,a,o,s){if(await i({apiKey:r.apiKey,...r.apiUrl===void 0?{}:{backendUrl:r.apiUrl},clientVersion:a}).verifyCredentials(),!d(s.appUrl))throw new n(`INVALID_ARGS`,`${e} installs the app from a URL, so --provider-app must be an https URL.`,{reason:`invalid_provider_app`,hint:`Pass the URL ${e} can read the build from; a local path cannot.`});return{provider:t,service:e,verificationMessage:`Credentials verified; ${e} picks the device when the session starts.`,device:{status:`configured`,...s.deviceModel===void 0?{}:{name:s.deviceModel},platform:o,...s.osVersion===void 0?{}:{osVersion:s.osVersion},message:`${e} assigns a device of this platform when the session starts; a model or OS version it has no device for is reported then.`},app:{status:`configured`,reference:s.appUrl,message:`App URL configured; ${e} fetches and installs it when the session starts.`}}}function d(e){if(e===void 0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`&&!t.username&&!t.password}function f(e){if(e.platform===`ios`||e.platform===`android`)return e.platform;throw new n(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`,{reason:`unsupported_platform`})}function p(e,n){let r=e?.trim();if(!r)throw n.createError(`INVALID_ARGS`,`connect ${t} requires --provider-app <https-url> with the build to install.`);if(!d(r))throw n.createError(`INVALID_ARGS`,`connect ${t} installs the app from an https URL; "${r}" is not one.`);return r}function m(t){let r=t?.trim();if(!r)throw new n(`COMMAND_FAILED`,`${e} profile missed its app URL.`,{hint:`Reconnect with --provider-app <https-url>.`});return r}export{l as createRevylConnection};
1
+ import{n as e,t}from"./device.mjs";import{t as n}from"./errors.mjs";import{i as r}from"./credentials.mjs";import{r as i}from"./revyl-client.mjs";import{n as a,r as o,revylTextFlag as s,t as c}from"./session-allocation.mjs";function l(n){return{resolve:({flags:e})=>{a(e,c),r(n.env,`connect ${t}`);let i=f(e),o=p(e.providerApp,n),l=s(e.device),u=s(e.providerOsVersion);return{profile:{leaseProvider:t,platform:i,...l===void 0?{}:{device:l},...o===void 0?{}:{providerApp:o},...u===void 0?{}:{providerOsVersion:u}},...o===void 0?{}:{extraFlags:{providerApp:o}}}},verify:async({flags:i})=>{a(i,c);let l=s(i.device),d=s(i.providerOsVersion),f=s(i.providerApp);return await u(r(n.env,`connect ${t}`),n.clientVersion,o(i.platform,e),{...f===void 0?{}:{appUrl:f},...l===void 0?{}:{deviceModel:l},...d===void 0?{}:{osVersion:d}})}}}async function u(r,a,o,s){if(await i({apiKey:r.apiKey,...r.apiUrl===void 0?{}:{backendUrl:r.apiUrl},clientVersion:a}).verifyCredentials(),s.appUrl!==void 0&&!d(s.appUrl))throw new n(`INVALID_ARGS`,`${e} installs the app from a URL, so --provider-app must be an https URL.`,{reason:`invalid_provider_app`,hint:`Pass the URL ${e} can read the build from; a local path cannot.`});return{provider:t,service:e,verificationMessage:`Credentials verified; ${e} picks the device when the session starts.`,device:{status:`deferred`,...s.deviceModel===void 0?{}:{name:s.deviceModel},platform:o,...s.osVersion===void 0?{}:{osVersion:s.osVersion},message:`${e} assigns a device of this platform when the session starts; a model or OS version it has no device for is reported then.`},app:s.appUrl===void 0?{status:`missing`,message:`No app URL; the device starts without one. Install a build, then open it.`}:{status:`configured`,reference:s.appUrl,message:`App URL configured; ${e} fetches and installs it when the session starts.`}}}function d(e){if(e===void 0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`&&!t.username&&!t.password}function f(e){if(e.platform===`ios`||e.platform===`android`)return e.platform;throw new n(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`,{reason:`unsupported_platform`})}function p(e,n){let r=e?.trim();if(r){if(!d(r))throw n.createError(`INVALID_ARGS`,`connect ${t} installs the app from an https URL; "${r}" is not one.`);return r}}export{l as createRevylConnection};
package/dist/errors.mjs CHANGED
@@ -1 +1 @@
1
- const e=Symbol.for(`agent-device.AppError`);var t=class t extends Error{static[Symbol.hasInstance](n){return this===t?typeof n==`object`&&!!n&&n[e]===!0:Function.prototype[Symbol.hasInstance].call(this,n)}code;details;cause;constructor(t,n,r,i){super(n),Object.defineProperty(this,e,{value:!0}),this.code=t,this.details=r,this.cause=i}};function n(e,t=`COMMAND_FAILED`){return typeof e==`string`&&e.length>0?e:t}function r(e){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,hint:`This is an agent-device runtime contract bug; report the selected device and command.`})}function i(e){return e instanceof Error?e.message:String(e)}function a(e,t,n={}){return e.details={...e.details,...n,dispatched:t},e}function o(e,t){if(t===0)return e;let n=e?.dispatchedSteps;return{...e,dispatchedSteps:t+(typeof n==`number`?n:0),dispatched:`unknown`}}function s(e,n){return e instanceof t&&(e.details=o(e.details,n)),e}export{i as a,s as i,r as n,n as o,a as r,t};
1
+ const e=Symbol.for(`agent-device.AppError`);var t=class t extends Error{static[Symbol.hasInstance](n){return this===t?typeof n==`object`&&!!n&&n[e]===!0:Function.prototype[Symbol.hasInstance].call(this,n)}code;details;cause;constructor(t,n,r,i){super(n),Object.defineProperty(this,e,{value:!0}),this.code=t,this.details=r,this.cause=i}};function n(e,t=`COMMAND_FAILED`){return typeof e==`string`&&e.length>0?e:t}function r(e){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,hint:`This is an agent-device runtime contract bug; report the selected device and command.`})}function i(e,n){return new t(`COMMAND_FAILED`,`request canceled`,{hint:`The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.`,...e,reason:`request_canceled`},n)}function a(e){return e instanceof Error?e.message:String(e)}function o(e,t,n={}){return e.details={...e.details,...n,dispatched:t},e}function s(e,t){if(t===0)return e;let n=e?.dispatchedSteps;return{...e,dispatchedSteps:t+(typeof n==`number`?n:0),dispatched:`unknown`}}function c(e,n){return e instanceof t&&(e.details=s(e.details,n)),e}export{c as a,o as i,i as n,a as o,r,n as s,t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime.mjs";import{n as t,t as n}from"./errors.mjs";var r=e({providerInteractorSource:()=>a,requireInteractorMethod:()=>i});function i(e,n){if(e)return e;throw t(`${n} was admitted but its bound interactor has no implementation.`)}function a(e){return async t=>{let r=e.resolveInteractor(t);if(r)return r;throw new n(`UNSUPPORTED_OPERATION`,`Provider-owned ${e.operation} operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id})}}export{a as n,i as r,r as t};
1
+ import{n as e}from"./rolldown-runtime.mjs";import{r as t,t as n}from"./errors.mjs";var r=e({providerInteractorSource:()=>a,requireInteractorMethod:()=>i});function i(e,n){if(e)return e;throw t(`${n} was admitted but its bound interactor has no implementation.`)}function a(e){return async t=>{let r=e.resolveInteractor(t);if(r)return r;throw new n(`UNSUPPORTED_OPERATION`,`Provider-owned ${e.operation} operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id})}}export{a as n,i as r,r as t};
@@ -1 +1,3 @@
1
- import{i as e,t}from"./device.mjs";import{i as n,t as r}from"./errors.mjs";import{n as i}from"./device2.mjs";import{n as a,r as o}from"./interactor-operation-binding.mjs";import{a as s,i as c,r as l,t as u}from"./open-target.mjs";import{setTimeout as ee}from"node:timers/promises";function d(e){return Object.freeze({family:e.platform,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}const te=[`resolveOpenTarget`,`prepareApplicationOpen`,`openApplication`,`applyRuntimeHints`,`clearRuntimeHints`,`closeApplication`,`finalizeApplicationClose`,`prepareAppleRunner`,`configureProviderPortReverse`];function f(e){return Object.freeze({resolveOpenTarget:e.resolveOpenTarget,prepareApplicationOpen:e.prepareApplicationOpen,openApplication:e.openApplication,applyRuntimeHints:e.applyRuntimeHints,clearRuntimeHints:e.clearRuntimeHints,closeApplication:e.closeApplication,finalizeApplicationClose:e.finalizeApplicationClose,prepareAppleRunner:e.prepareAppleRunner,configureProviderPortReverse:e.configureProviderPortReverse})}function ne(e,t){return Object.freeze(Object.fromEntries(te.flatMap(n=>t[n].available?[[n,e[n]]]:[])))}function re(e){return()=>({captureBackendRefusal:e})}async function ie(e,t={}){let n=e?.captureBackend;if(n!==void 0&&!t.captureBackends?.includes(n))throw new r(`UNSUPPORTED_OPERATION`,`--capture-backend ${n} is not supported: ${t.captureBackendRefusal??`this capture owner declares no such backend`}`,{reason:`screenshot-capture-backend-unsupported`});if(e?.screenMask===void 0)return;let{readScreenshotScreenMask:i}=await import(`./screenshot.mjs`).then(e=>e.n);if(i(e?.screenMask)!==void 0&&t.screenMask!==!0)throw new r(`UNSUPPORTED_OPERATION`,`--screen-mask requires a handheld iOS simulator simctl capture`,{reason:`screenshot-screen-mask-unsupported`})}function p(e){return Object.freeze({captureScreenshot:e.capture})}function ae(e,t){let{captureBackend:n,preferredCaptureBackend:r,...i}=e??{};return n?{...i,captureBackend:n}:r&&t.captureCapabilities(i).captureBackends?.includes(r)?{...i,captureBackend:r}:i}function oe(e,t){return Object.freeze({captureScreenshot:async n=>{let r=ae(n.options,e);return await ie(r,e.captureCapabilities(r)),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e.signal})).screenshot(n.outPath,r)??{}}})}function se(e){return oe(e,a({...e,operation:`screenshot`}))}function ce(e,t){return t.signal===void 0?e:AbortSignal.any([e,t.signal])}function le(e){return Object.freeze({captureSnapshot:e.capture,captureSnapshotWithCustomActions:e.customActions,captureSnapshotWithoutActiveApp:e.withoutActiveApp})}function ue(e){let t=async t=>{await de(e,t);let n=ce(e.signal,t),i={...t.execution,appBundleId:t.options?.appBundleId,signal:n},a=e.ownership===`local`?await e.resolveInteractor(e.device,i):e.resolveInteractor(i);if(!a)throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned snapshot operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id});let o=await a.snapshot({...t.options,signal:n});if(!pe(o))return o;if(!e.presentIosAcquisition)throw new r(`COMMAND_FAILED`,`Acquired iOS snapshot has no host presentation owner.`,{reason:`ios-snapshot-presenter-missing`,deviceId:e.device.id});return await e.presentIosAcquisition(o,t.options)};return Object.freeze({captureSnapshot:t,captureSnapshotWithCustomActions:t,captureSnapshotWithoutActiveApp:t})}async function de(e,t){if(t.options?.observeOnly!==!0)return;let{isHandheldAppleDevice:n}=await import(`./device2.mjs`).then(e=>e.t);if(!(e.ownership===`local`&&n(e.device)))throw new r(`UNSUPPORTED_OPERATION`,`observe-only snapshot requires a local iOS or iPadOS runner.`)}function fe(e){return ue({...e,ownership:`provider`})}function pe(e){return`stage`in e&&e.stage===`acquired`}function me(e){return Object.freeze({findText:e.findText,querySelector:e.querySelector})}function he(e){return Object.freeze({setViewport:e.setViewport})}function ge(e){return Object.freeze({focusPoint:e.focus})}function _e(e,t){return Object.freeze({focusPoint:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).focus(n.point.x,n.point.y)}})}function ve(e){return _e(e.signal,a({...e,operation:`focus`}))}function m(e){let t=t=>t??e.unsupported;return Object.freeze({performGesturePlan:t(e.plan),performDirectionalFlingPlan:t(e.directionalFling),performMultiTouchGesturePlan:t(e.multiTouch),performTargetAuthoredDrag:t(e.targetAuthoredDrag),gestureViewport:t(e.viewport)})}function ye(e){let t=e??{},n=h(t.pixels),r=h(t.x1),i=h(t.y1),a=h(t.x2),o=h(t.y2),s=r===void 0||i===void 0||a===void 0||o===void 0?void 0:{x:r/2+a/2,y:i/2+o/2};return{report:t,...n===void 0?{}:{pixels:n},...s===void 0?{}:{midpoint:s}}}function h(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function g(e){return Object.freeze({scrollDirection:e.scroll})}function be(e,t){return Object.freeze({scrollDirection:async n=>(e.throwIfAborted(),ye(await(await t({...n.execution,appBundleId:n.target?.appBundleId,signal:e})).scroll(n.direction,n.options)))})}function xe(e){return be(e.signal,a({...e,operation:`scroll`}))}function _(e){return Object.freeze({typeText:e.type})}function Se(e,t){return Object.freeze({typeText:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).type(n.text,n.delayMs))})}function Ce(e){return Se(e.signal,a({...e,operation:`type`}))}function v(e){return Object.freeze({readTextAtPoint:e.readTextAtPoint})}function y(e){return Object.freeze({back:e.back})}function we(e,t){return Object.freeze({back:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).back(n.mode)}})}const Te=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`orientation auto is only supported on ADB-backed Android.`});function b(e){return Object.freeze({setOrientation:e.orientation,unlockOrientation:e.unlock??Te})}function Ee(e,t){return Object.freeze({setOrientation:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).setOrientation(n.rotation))})}function De(e,t){return Object.freeze({unlockOrientation:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.unlockOrientation,`orientation auto`).call(r)}})}function x(e){let{tvRemote:t,buttonSupport:n}=e;return Object.freeze({tvRemote:t.available&&n?Object.freeze({available:!0,subjects:Object.freeze(Object.fromEntries(n.supported.map(e=>[e,{available:!0}]))),unlisted:n.unsupported}):t})}const S=`tv-remote`;function Oe(e,t){return Object.freeze({tvRemote:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.tvRemote,S).call(r,n.button,n.durationMs)}})}function C(e){let t=t=>t??e.unsupported;return Object.freeze({keyboardStatus:t(e.status),keyboardDismiss:t(e.dismiss),keyboardEnter:t(e.enter)})}async function ke(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}const w={keyboardStatus:`keyboard status`,keyboardDismiss:`keyboard dismiss`,keyboardEnter:`keyboard enter`};function T(e,t,n){let r=async r=>{let i=await ke(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],w[e]).call(i)};return Object.freeze({[e]:r})}function E(e){let t=t=>t??e.unsupported;return Object.freeze({readClipboard:t(e.read),writeClipboard:t(e.write)})}const D={readClipboard:`clipboard read`,writeClipboard:`clipboard write`};async function O(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}async function k(e,t){let{requireInteractorMethod:n}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return n(e[t],D[t])}function Ae(e,t){return Object.freeze({readClipboard:async n=>{let r=await O(e,t,n);return await(await k(r,`readClipboard`)).call(r)}})}function je(e,t){return Object.freeze({writeClipboard:async n=>{let r=await O(e,t,n);await(await k(r,`writeClipboard`)).call(r,n.text)}})}const A=[`home`,`appSwitcher`,`actionButton`,`volumeUp`,`volumeDown`,`power`,`mute`,`sleep`,`wake`,`mediaPlayPause`,`mediaNext`,`mediaPrevious`,`mediaRewind`,`mediaFastForward`],j={home:`home`,appSwitcher:`app-switcher`,actionButton:`action-button`,volumeUp:`volume-up`,volumeDown:`volume-down`,power:`power`,mute:`mute`,sleep:`sleep`,wake:`wake`,mediaPlayPause:`media-play-pause`,mediaNext:`media-next`,mediaPrevious:`media-previous`,mediaRewind:`media-rewind`,mediaFastForward:`media-fast-forward`};function M(e){let t={};for(let n of A)t[n]=e[n]??e.unsupported;return Object.freeze(t)}Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is not supported on Android TV targets; use tv-remote.`}),Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is supported on Android emulators and physical devices.`}),Object.freeze({available:!0}),A.filter(e=>e!==`home`&&e!==`appSwitcher`&&e!==`actionButton`);function N(e,t,n){let r=async r=>{t.throwIfAborted();let i=await n({...r.execution,appBundleId:r.options?.appBundleId,signal:t});await o(i[e],j[e]).call(i)};return Object.freeze({[e]:r})}function P(e){return Object.freeze({triggerAppEvent:e.triggerAppEvent})}function Me(e,t){return Object.freeze({triggerAppEvent:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).open(n.eventUrl,{appBundleId:n.options?.appBundleId})}})}function F(e){return Object.freeze({readAlert:e.read,awaitAlert:e.wait,acceptAlert:e.accept,dismissAlert:e.dismiss})}async function Ne(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Pe(e,t){return{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e.surface===void 0?{}:{surface:e.surface},...t?{signal:t}:{}}}const I={readAlert:`alert get`,awaitAlert:`alert wait`,acceptAlert:`alert accept`,dismissAlert:`alert dismiss`};function L(e,t,n){return Object.freeze({[e]:async r=>{let i=await Ne(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],I[e]).call(i,Pe(r,t))}})}function Fe(e){return Object.freeze({audioProbeStart:e.capture,audioProbeReattach:e.capture,audioProbeCleanup:e.capture,audioProbeQuery:e.query})}function R(e){return Object.freeze({perfFrames:e.frames,perfMemorySample:e.memorySample,perfMemorySnapshot:e.memorySnapshot,perfNativeCaptureStart:e.nativeCapture,perfNativeCaptureReattach:e.nativeCapture,perfNativeCaptureCleanup:e.nativeCapture,perfProfileReport:e.profileReport})}function z(e){let t=t=>t??e.unsupported;return Object.freeze({tapPoint:e.tap,tapRef:t(e.tapRef),longPressPoint:e.longPress,hoverPoint:B(t(e.hover)),hoverRef:B(t(e.hoverRef)),fillPoint:e.fill,fillRef:t(e.fillRef),tapElementSelector:t(e.tapElementSelector)})}function B(e){return e.available?e:Object.freeze({...e,hint:e.hint??`hover raises pointer hover state and is available on web targets only. On touch platforms use longpress for hold gestures.`})}function Ie(e,t){return{...e.execution,appBundleId:e.appBundleId,signal:t}}function Le(e,t,n,r){let i=async n=>(e.throwIfAborted(),await t(Ie(n,e))),a=async t=>{e.throwIfAborted(),Re(t.options,n.longPressPoint);let a=await i(t);return t.options.button!==`primary`&&a.alternateClick?await a.alternateClick(t.point,t.options.button):a.pressPoint?await a.pressPoint(t.point,t.options):await Be(a,t.point,t.options,r)},s=async e=>{let t=await i(e);return await o(t.hover,`hoverPoint`).call(t,e.point.x,e.point.y)},c=async e=>await(await i(e)).fill(e.point.x,e.point.y,e.text,e.delayMs,{allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback});return Object.freeze({...n.tapPoint.available?{tapPoint:a}:{},...n.tapRef.available?{tapRef:async e=>{let t=await i(e);return await o(t.tapRef,`tapRef`).call(t,e.ref)}}:{},...n.longPressPoint.available?{longPressPoint:async e=>await(await i(e)).longPress(e.point.x,e.point.y,e.durationMs)}:{},...n.hoverPoint.available?{hoverPoint:s}:{},...n.hoverRef.available?{hoverRef:async e=>{let t=await i(e);return await o(t.hoverRef,`hoverRef`).call(t,e.ref)}}:{},...n.fillPoint.available?{fillPoint:c}:{},...n.fillRef.available?{fillRef:async e=>{let t=await i(e);return await o(t.fillRef,`fillRef`).call(t,e.ref,e.text,e.delayMs)}}:{},...n.tapElementSelector.available?{tapElementSelector:async e=>{let t=await i(e);return await o(t.tapElementSelector,`tapElementSelector`).call(t,e.selector)}}:{}})}function Re(e,t){if(!(e.holdMs<=0||t.available))throw new r(`UNSUPPORTED_OPERATION`,`press-and-hold is not supported by this runtime.`,{reason:t.reason,...t.hint===void 0?{}:{hint:t.hint}})}function ze(e){if(e.doubleTap)return e.doubleTap;throw new r(`UNSUPPORTED_OPERATION`,`double-tap is not supported by this runtime.`,{reason:`owner-capability-missing`,hint:`This runtime drives single presses; use --count to repeat them.`})}async function Be(e,t,i,a){if(i.button!==`primary`)throw new r(`UNSUPPORTED_OPERATION`,`Bound runtime does not implement ${i.button} click.`);let o=i.doubleTap?ze(e):void 0,s,c=0;try{for(let n=0;n<i.count;n+=1){let[r,l]=He(n,i.jitterPx),u=await Ve(e,o,t.x+r,t.y+l,i);c+=1,s??=u,n<i.count-1&&i.intervalMs>0&&await a(i.intervalMs)}}catch(e){throw n(e,c)}return s}async function Ve(e,t,n,r,i){return t?await t.call(e,n,r):i.holdMs>0?await e.longPress(n,r,i.holdMs):await e.tap(n,r)}const V=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function He(e,t){if(t<=0)return[0,0];let[n,r]=V[e%V.length];return[n*t,r*t]}function Ue(e){return Le(e.signal,a({...e,operation:`touch`}),e.facts,e.pause)}const We={appLog:!0,apps:!0,appDeployment:!0,appState:!0,network:!0,screenRecording:!0,screenshot:!0,snapshot:!0,viewport:!0,focus:!0,gesture:!0,scroll:!0,typeText:!0,touch:!0,elementText:!0,back:!0,orientation:!0,fold:!0,telephony:!0,tvRemote:!0,keyboard:!0,clipboard:!0,systemButton:!0,triggerAppEvent:!0,settings:!0,readAlert:!0,awaitAlert:!0,acceptAlert:!0,dismissAlert:!0,audioProbeCapture:!0,audioProbeQuery:!0,perf:!0,readiness:!0,shutdown:!0};function Ge(e){let t={};for(let n of Object.keys(We))t[n]=e(n);return t}function H(e,t,n){let r=qe(n);return Object.freeze({device:{...d(e),providerMode:Ke(t)},operations:{appLogInspect:r.appLog,appLogDoctor:r.appLog,appLogStart:r.appLog,appLogReattach:r.appLog,appLogCleanup:r.appLog,listApps:r.apps,deployApp:r.appDeployment,materializeAppSource:r.appDeployment,deployMaterializedApp:r.appDeployment,sendPushNotification:r.appDeployment,uninstallApp:r.appDeployment,appState:r.appState,networkDump:r.network,screenRecordingStart:r.screenRecording,screenRecordingReattach:r.screenRecording,screenRecordingCleanup:r.screenRecording,...p({capture:r.screenshot}),...le({capture:r.snapshot,customActions:r.snapshot,withoutActiveApp:r.snapshot}),...me({findText:r.snapshot,querySelector:r.snapshot}),...he({setViewport:r.viewport}),...ge({focus:r.focus}),...m({unsupported:r.gesture}),...g({scroll:r.scroll}),..._({type:r.typeText}),...z({unsupported:r.touch,tap:r.touch,longPress:r.touch,fill:r.touch}),...v({readTextAtPoint:r.elementText}),...y({back:r.back}),...b({orientation:r.orientation,unlock:r.orientation}),setFoldPose:r.fold,sendTelephonyEvent:r.telephony,...x({tvRemote:r.tvRemote}),...C({unsupported:r.keyboard}),...E({unsupported:r.clipboard}),...M({unsupported:r.systemButton}),...P({triggerAppEvent:r.triggerAppEvent}),setSetting:r.settings,readSetting:r.settings,...F({read:r.readAlert,wait:r.awaitAlert,accept:r.acceptAlert,dismiss:r.dismissAlert}),...Fe({capture:r.audioProbeCapture,query:r.audioProbeQuery}),...R({frames:r.perf,memorySample:r.perf,memorySnapshot:r.perf,nativeCapture:r.perf,profileReport:r.perf}),ensureReady:r.readiness,bootTarget:r.readiness,bootTargetHeadless:r.readiness,shutdownTarget:r.shutdown,...r.lifecycle}})}function Ke(e){switch(e.kind){case`local-family`:return`local`;case`provider-runtime`:return`provider-runtime`}}function qe(e){return Object.freeze({...Ge(t=>Object.freeze({...e[t]??e.network})),lifecycle:f(e.lifecycle)})}function Je(e){return Object.freeze({setSetting:U(e,e.write),readSetting:U(e,e.read??{})})}function U(e,t){if(!e.target.available)return e.target;let n=Object.values(t).filter(e=>e!==void 0);if(!n.some(e=>e.available))return n[0]??e.unsupported;let r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.available?Ye:t]));return Object.freeze({available:!0,subjects:Object.freeze(r),unlisted:e.unsupported})}const Ye=Object.freeze({available:!0});async function Xe(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Ze(e,t){return Object.freeze({setSetting:async n=>await(await Xe(e,t,n)).setSetting(n.setting,n.state,n.appBundleId,n.options)})}function Qe(e,t){return Object.freeze({readSetting:async n=>{let r=await Xe(e,t,n),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await i(r.readSetting,`settings read`).call(r,n.setting)}})}const $e=[{operation:`back`,label:`back`,bind:we},{operation:`home`,label:j.home,bind:(e,t)=>N(`home`,e,t)},{operation:`setOrientation`,label:`orientation`,bind:Ee},{operation:`unlockOrientation`,label:`orientation auto`,bind:De},{operation:`tvRemote`,label:S,bind:Oe},{operation:`keyboardStatus`,label:w.keyboardStatus,bind:(e,t)=>T(`keyboardStatus`,e,t)},{operation:`keyboardDismiss`,label:w.keyboardDismiss,bind:(e,t)=>T(`keyboardDismiss`,e,t)},{operation:`keyboardEnter`,label:w.keyboardEnter,bind:(e,t)=>T(`keyboardEnter`,e,t)},{operation:`readClipboard`,label:D.readClipboard,bind:Ae},{operation:`writeClipboard`,label:D.writeClipboard,bind:je},{operation:`appSwitcher`,label:j.appSwitcher,bind:(e,t)=>N(`appSwitcher`,e,t)},{operation:`actionButton`,label:j.actionButton,bind:(e,t)=>N(`actionButton`,e,t)},{operation:`volumeUp`,label:j.volumeUp,bind:(e,t)=>N(`volumeUp`,e,t)},{operation:`volumeDown`,label:j.volumeDown,bind:(e,t)=>N(`volumeDown`,e,t)},{operation:`power`,label:j.power,bind:(e,t)=>N(`power`,e,t)},{operation:`mute`,label:j.mute,bind:(e,t)=>N(`mute`,e,t)},{operation:`sleep`,label:j.sleep,bind:(e,t)=>N(`sleep`,e,t)},{operation:`wake`,label:j.wake,bind:(e,t)=>N(`wake`,e,t)},{operation:`mediaPlayPause`,label:j.mediaPlayPause,bind:(e,t)=>N(`mediaPlayPause`,e,t)},{operation:`mediaNext`,label:j.mediaNext,bind:(e,t)=>N(`mediaNext`,e,t)},{operation:`mediaPrevious`,label:j.mediaPrevious,bind:(e,t)=>N(`mediaPrevious`,e,t)},{operation:`mediaRewind`,label:j.mediaRewind,bind:(e,t)=>N(`mediaRewind`,e,t)},{operation:`mediaFastForward`,label:j.mediaFastForward,bind:(e,t)=>N(`mediaFastForward`,e,t)},{operation:`triggerAppEvent`,label:`trigger-app-event`,bind:Me},{operation:`setSetting`,label:`settings`,bind:Ze},{operation:`readSetting`,label:`settings read`,bind:Qe},{operation:`readAlert`,label:I.readAlert,bind:(e,t)=>L(`readAlert`,e,t)},{operation:`awaitAlert`,label:I.awaitAlert,bind:(e,t)=>L(`awaitAlert`,e,t)},{operation:`acceptAlert`,label:I.acceptAlert,bind:(e,t)=>L(`acceptAlert`,e,t)},{operation:`dismissAlert`,label:I.dismissAlert,bind:(e,t)=>L(`dismissAlert`,e,t)}];function et(e,t){let n={};for(let r of $e)e.facts[r.operation]?.available&&Object.assign(n,r.bind(e.signal,t(r)));return n}function tt(e){return et(e,t=>a({...e,operation:t.label}))}const W=Object.freeze({available:!0}),nt=s(`unsupported-provider-mode`,`Revyl enters text at a point; run fill <field> "text" instead of type.`),rt=s(`unsupported-provider-mode`,`Revyl does not expose portable gesture execution.`),it=s(`unsupported-provider-mode`,`Revyl does not expose keyboard status, dismissal, or a return-key press.`),at=s(`unsupported-provider-mode`,`Revyl does not expose the pasteboard.`),ot=s(`unsupported-provider-mode`,`Revyl does not expose orientation control.`),st=s(`unsupported-provider-mode`,`Revyl has a back button only on Android; on iOS, click the app's own back control.`),ct=s(`unsupported-provider-mode`,`Revyl exposes the home button only.`),lt=s(`unsupported-provider-mode`,`Revyl does not expose settings control.`),ut=s(`unsupported-provider-mode`,`Revyl does not deliver a push notification to a session.`),G=s(`unsupported-provider-mode`,`Revyl has no alert surface of its own; a system alert appears in the snapshot tree.`),dt=s(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets; Revyl rents phones and tablets.`),K=s(`owner-capability-missing`,`Revyl requires a matching live provider session for this device.`),ft=s(`unsupported-provider-mode`,`fold runs a HID helper inside a foldable iPhone simulator on the daemon host; a Revyl session has no such simulator.`),pt=s(`unsupported-provider-mode`,`telephony sends calls and SMS to an Android emulator's console through local adb; agent-device does not route it through a Revyl session.`);function mt(e){let t=e??W;return Object.freeze({...ge({focus:t}),..._({type:e??nt}),...z({unsupported:e??s(`unsupported-provider-mode`,`Revyl taps and fills at a point; it has no action for a hover or for a selector target.`),tap:t,longPress:t,fill:t}),...m({unsupported:e??rt}),...g({scroll:t})})}function ht(e,t){return Object.freeze(t?{...y({back:t}),...b({orientation:t,unlock:t}),...M({unsupported:t}),...x({tvRemote:t})}:{...y({back:e.platform===`android`?W:st}),...b({orientation:ot,unlock:ot}),...M({unsupported:ct,home:W}),...x({tvRemote:dt})})}function gt(e){return Object.freeze({...C({unsupported:e??it}),...E({unsupported:e??at}),...Je({target:e??W,unsupported:e??lt,write:{}}),...P({triggerAppEvent:e??ut}),...F({read:e??G,wait:e??G,accept:e??G,dismiss:e??G}),setFoldPose:e??ft,sendTelephonyEvent:e??pt})}function _t(e){let{device:t,signal:n}=e,r=n=>e.getInteractor(t,n);return Object.freeze({...fe({device:t,signal:n,resolveInteractor:r,presentIosAcquisition:e.presentIosAcquisition}),...se({device:t,signal:n,resolveInteractor:r,captureCapabilities:re(`Revyl captures through its provider endpoint`)}),...ve({device:t,signal:n,resolveInteractor:r}),...Ce({device:t,signal:n,resolveInteractor:r}),...Ue({device:t,signal:n,resolveInteractor:r,facts:mt(),pause:async e=>await ee(e,void 0,{signal:n})}),...xe({device:t,signal:n,resolveInteractor:r})})}const vt=`--launch-console requires a direct app launch and cannot be used with URL opens`;function yt(e,t,n){return{requestId:e.requestId,signal:n,appBundleId:t,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function bt(e){let{device:t,signal:n,ownership:i}=e;return Object.freeze({device:t,signal:n,resolveInteractor:async(a,o)=>{let s=yt(a,o,n);if(i===`local`)return await e.resolveLocalInteractor(t,s);if(a.launchConsole)throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for a local or Limrun iOS simulator app launch`,{reason:`launch-console-owner-unadmitted`,deviceId:t.id,hint:`Remove --launch-console, or use a local or Limrun iOS simulator for launch output.`});let c=i.resolveInteractor(s);if(c)return c;throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned application lifecycle operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:t.id})}})}function xt(e){return bt({device:e.device,signal:e.signal,ownership:{kind:`provider`,resolveInteractor:e.resolveInteractor}})}async function St(e){let{device:t,positionals:n,execution:r}=e;Ct(n);let i=n[0],a=n[1];if(!i){await wt(e);return}return Tt(t,r),a===void 0?await Dt(e,i):await Et(e,i,a)}function Ct(e){if(e.length>2)throw new r(`INVALID_ARGS`,`open accepts at most two arguments: <app|url> [url]`)}async function wt(e){if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,`--launch-console requires an app target`);if(e.execution.launchArgs&&e.execution.launchArgs.length>0)throw new r(`INVALID_ARGS`,`--launch-args requires an app target`);await e.interactor.openDevice()}function Tt(e,t){if(t.launchConsole&&(!i(e)||e.kind!==`simulator`))throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for iOS simulator app launches`);if(e.platform===`linux`&&t.launchArgs&&t.launchArgs.length>0)throw new r(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on Linux.`)}async function Et(e,t,n){if(u(t))throw new r(`INVALID_ARGS`,`open <app> <url> requires an app target as the first argument`);if(!u(n))throw new r(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,vt);return await e.interactor.open(t,{activity:e.execution.activity,appBundleId:e.appBundleId,launchArgs:e.execution.launchArgs?[...e.execution.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp,url:n})}async function Dt(e,t){let{execution:n,interactor:i}=e;if(n.launchConsole&&u(t))throw new r(`INVALID_ARGS`,vt);if(n.clearAppState){if(u(t))throw new r(`INVALID_ARGS`,`Clearing app state requires an app target, not a deep link.`);await i.setSetting(`clear-app-state`,`clear`,t)}return await i.open(t,{activity:n.activity,appBundleId:e.appBundleId,launchConsole:n.launchConsole,launchArgs:n.launchArgs?[...n.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp})}function Ot(e){let{binding:t}=e,n=async()=>{throw new r(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for ${e.owner}.`)};return Object.freeze({resolveOpenTarget:async t=>jt(e.openTargetIdentity,t),prepareApplicationOpen:async()=>void 0,openApplication:async t=>await kt(e,t),applyRuntimeHints:n,clearRuntimeHints:n,closeApplication:async e=>{await Mt({device:t.device,interactor:await t.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async()=>({}),prepareAppleRunner:n,configureProviderPortReverse:e.configureProviderPortReverse??n})}async function kt(e,t){let{binding:n}=e,r=await n.resolveInteractor(t.execution,t.appBundleId);e.closeBeforeRelaunch&&t.relaunch&&t.target!==void 0&&await Mt({device:n.device,interactor:r,positionals:[t.appBundleId??t.target]}),await St({device:n.device,interactor:r,positionals:t.positionals,appBundleId:t.appBundleId,execution:t.execution,...e.closeBeforeRelaunch?{}:{terminateRunningApp:t.relaunch}});let i=At(t);return i&&await St({device:n.device,interactor:r,positionals:[i],appBundleId:t.appBundleId,execution:{...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),{appBundleId:t.appBundleId,timing:{}}}function At(e){let t=e.runtimeLaunchUrl?.trim(),n=e.positionals.length===1?e.positionals[0]?.trim():void 0;if(!(!t||!n||u(n)))return t}function jt(e,t){let n=t.target;if(e===`app-name`)return Object.freeze(n===void 0?{}:{appName:n});let r=n?.trim(),i=r&&r.includes(`.`)&&!u(r)?r:t.currentAppBundleId;return Object.freeze({...i===void 0?{}:{appBundleId:i},...n===void 0?{}:{appName:n}})}async function Mt(e){let{device:t,interactor:n,positionals:r}=e,i=r[0];if(!i){t.platform===`web`&&await n.close(``);return}await n.close(i)}function Nt(e){let t=xt({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)}),n=Ot({owner:`Revyl`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!1,binding:t});return Object.freeze({...n,openApplication:async e=>(e.relaunch&&e.target!==void 0&&await(await t.resolveInteractor(e.execution,e.appBundleId)).close(``),await n.openApplication(e))})}const q=s(`unsupported-provider-mode`,`Revyl installs an app when the session starts. Pass --provider-app <URL> to connect, and run open afterwards.`),Pt=s(`unsupported-provider-mode`,`Revyl does not uninstall an app from a session.`),Ft=s(`unsupported-provider-mode`,`Revyl does not report which app the device has in the foreground.`),J=s(`unsupported-provider-mode`,`Revyl does not expose an app log stream.`),It=s(`unsupported-provider-mode`,`Revyl does not report the apps installed on a session.`),Lt=s(`unsupported-provider-mode`,`Revyl does not expose a network capture for a session.`),Y=s(`unsupported-provider-mode`,`Revyl streams the screen for its own viewer and does not expose a recording.`),Rt=s(`unsupported-provider-mode`,`Custom snapshot actions are available only on a local iOS runner.`),zt=s(`unsupported-provider-mode`,`Revyl rents a device at the size its model has.`),X=s(`unsupported-provider-mode`,`Revyl-owned devices read element text from the captured tree only.`),Bt=s(`unsupported-provider-mode`,`Headless boot is unavailable for provider-owned devices.`),Vt=s(`unsupported-provider-mode`,`Apple runner preparation is unavailable for Revyl-owned devices.`),Ht=s(`unsupported-provider-mode`,`Revyl owns the target lifecycle for provider-owned devices.`),Z=s(`unsupported-provider-mode`,`Runtime hints are not applied to provider-owned devices.`),Ut=s(`unsupported-provider-mode`,`Revyl does not expose port reverse; publish the app server at a public URL instead.`),Wt=s(`unsupported-provider-mode`,`Revyl does not expose the audio probe.`),Q=s(`unsupported-provider-mode`,`Revyl does not expose frame, memory, or profiler counters for a session.`),Gt=s(`unsupported-provider-mode`,`Revyl open requires the app the session was started with.`),Kt=s(`unsupported-provider-mode`,`Revyl close requires the app the session was started with.`);function $(t,n){let r=e(t),i=r?n?W:K:Gt,a=r?n?W:K:Kt;return f({resolveOpenTarget:i,prepareApplicationOpen:i,openApplication:i,applyRuntimeHints:Z,clearRuntimeHints:Z,closeApplication:a,finalizeApplicationClose:a,prepareAppleRunner:Vt,configureProviderPortReverse:Ut})}function qt(e){return Object.freeze({device:{...d(e),providerMode:`provider-runtime`},operations:{appLogInspect:J,appLogDoctor:J,appLogStart:J,appLogReattach:J,appLogCleanup:J,listApps:It,deployApp:q,materializeAppSource:q,deployMaterializedApp:q,sendPushNotification:ut,uninstallApp:Pt,appState:Ft,networkDump:Lt,screenRecordingStart:Y,screenRecordingReattach:Y,screenRecordingCleanup:Y,...le({capture:W,customActions:Rt,withoutActiveApp:W}),...p({capture:W}),...me({findText:X,querySelector:X}),...he({setViewport:zt}),...mt(),...v({readTextAtPoint:X}),...ht(e),...gt(),...Fe({capture:Wt,query:Wt}),...R({frames:Q,memorySample:Q,memorySnapshot:Q,nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:W,bootTargetHeadless:Bt,shutdownTarget:Ht,...$(e,!0)}})}const Jt=Object.freeze({appLog:K,appState:K,appDeployment:K,apps:K,network:K,screenRecording:K,screenshot:K,snapshot:K,viewport:K,focus:K,gesture:K,scroll:K,typeText:K,touch:K,elementText:K,back:K,orientation:K,fold:ft,telephony:pt,tvRemote:K,keyboard:K,clipboard:K,systemButton:K,triggerAppEvent:K,settings:K,readAlert:K,awaitAlert:K,acceptAlert:K,dismissAlert:K,audioProbeCapture:K,audioProbeQuery:K,perf:K,readiness:K,shutdown:K});function Yt(n){let i=l(t,n.runtimeInstance),a=t=>e(t)&&n.ownsDevice(t),o=e=>a(e)&&n.hasLiveSession(e);return Object.freeze({owner:i,ownsDevice:a,inspectFacts:async e=>o(e)?qt(e):H(e,i,{...Jt,lifecycle:$(e,!1)}),bind:async t=>{if(t.intent.kind===`exact-owner`&&!c(t.intent.owner,i))throw new r(`UNSUPPORTED_OPERATION`,`Revyl runtime owner identity does not match`);if(!e(t.device))throw new r(`UNSUPPORTED_PLATFORM`,`Revyl requires an iOS simulator or Android emulator device identity`);let a=o(t.device);if(t.intent.kind!==`exact-owner`&&!a)throw new r(`UNSUPPORTED_OPERATION`,`Revyl provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return Xt(n,i,t.device,t.scope.signal,a)},shutdown:async()=>void 0})}function Xt(e,t,n,r,i){let a=i?qt(n):H(n,t,{...Jt,lifecycle:$(n,!1)}),o={ensureReady:async()=>({...n,booted:!0}),bootTarget:async()=>({...n,booted:!0}),...ne(Nt({device:n,signal:r,getInteractor:e.getInteractor}),$(n,i)),..._t({device:n,signal:r,getInteractor:e.getInteractor,presentIosAcquisition:e.host.snapshot.presentIosAcquisition}),...tt({device:n,signal:r,resolveInteractor:t=>e.getInteractor(n,t),facts:a.operations})};return Object.freeze({device:n,owner:t,facts:a,operations:Object.freeze(Zt(a,o)),[Symbol.asyncDispose]:async()=>void 0})}function Zt(e,t){let n={};for(let[r,i]of Object.entries(t))e.operations[r]?.available&&(n[r]=i);return n}export{Yt as createRevylPlatformRuntimeOwner};
1
+ import{i as e,t}from"./device.mjs";import{a as n,n as r,t as i}from"./errors.mjs";import{n as a}from"./device2.mjs";import{n as o,r as s}from"./interactor-operation-binding.mjs";import{a as c,i as l,r as u,t as d}from"./open-target.mjs";import f from"node:fs";import p from"node:path";import{randomUUID as m}from"node:crypto";import{Readable as h}from"node:stream";import{setTimeout as g}from"node:timers/promises";import _ from"node:fs/promises";import v from"node:os";import{AsyncLocalStorage as y}from"node:async_hooks";import{spawn as ee}from"node:child_process";import{pipeline as te}from"node:stream/promises";const ne=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key|user[_-]?code|device[_-]?code|refresh[_-]?credential)/i,re=/\b(?:bearer\s+[a-z0-9._-]+|adc_(?:agent|live|refresh|cli)_[a-z0-9._-]+)\b/gi,ie=/\b([a-z0-9_-]*(?:api[_-]?key|token|secret|password|user[_-]?code|device[_-]?code|refresh[_-]?credential)[a-z0-9_-]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi,ae=/https?:\/\/[^\s"'<>]+/gi,b=8192,x=`...<truncated>`;function oe(e){return S(e,{ancestors:new WeakSet,clones:new WeakMap,circularMarks:0})}function S(e,t,n){if(e==null)return e;if(typeof e==`string`)return ce(e,n);if(typeof e!=`object`)return e;if(t.clones.has(e))return t.clones.get(e);if(t.ancestors.has(e))return t.circularMarks+=1,`[Circular]`;let r=t.circularMarks;t.ancestors.add(e);try{let n=se(e,t);return t.circularMarks===r&&t.clones.set(e,n),n}finally{t.ancestors.delete(e)}}function se(e,t){if(Array.isArray(e))return e.map(e=>S(e,t));let n={};for(let[r,i]of Object.entries(e))n[r]=ne.test(r)?`[REDACTED]`:S(i,t,r);return n}function ce(e,t){let n=e.trim();if(!n)return le(e,t);if(t&&ne.test(t))return`[REDACTED]`;let r=ue(n);return r=r.replace(re,`[REDACTED]`),r=r.replace(ie,(e,t,n,r,i,a)=>fe({key:t,separator:n,rawValue:r,offset:i,input:a})||de(r)?e:`${t}${n}[REDACTED]`),le(r,t)}function le(e,t){if(t===`stderr`){if(e.length<=b)return e;let t=`\n${x}\n`,n=b-t.length,r=Math.ceil(n/2);return`${e.slice(0,r)}${t}${e.slice(-(n-r))}`}return e.length<=400?e:`${e.slice(0,386)}${x}`}function ue(e){return e.replace(ae,e=>pe(e)??e)}function de(e){return/^adc_(?:agent|live|refresh|cli)_\.\.\.$/i.test(e)}function fe(e){if(e.key.toLowerCase()!==`token`||!e.separator.includes(`:`))return!1;try{return new URL(e.rawValue).pathname.replace(/\/+$/,``)===`/api-keys`&&/(?:^|\b)(?:service\/)?api\s+$/i.test(e.input.slice(0,e.offset))}catch{return!1}}function pe(e){try{let t=new URL(e);return t.search&&=`?REDACTED`,(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`),t.toString()}catch{return null}}function me(e){return Object.freeze({family:e.platform,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}const he=[`resolveOpenTarget`,`prepareApplicationOpen`,`openApplication`,`applyRuntimeHints`,`clearRuntimeHints`,`closeApplication`,`finalizeApplicationClose`,`prepareAppleRunner`,`configureProviderPortReverse`];function ge(e){return Object.freeze({resolveOpenTarget:e.resolveOpenTarget,prepareApplicationOpen:e.prepareApplicationOpen,openApplication:e.openApplication,applyRuntimeHints:e.applyRuntimeHints,clearRuntimeHints:e.clearRuntimeHints,closeApplication:e.closeApplication,finalizeApplicationClose:e.finalizeApplicationClose,prepareAppleRunner:e.prepareAppleRunner,configureProviderPortReverse:e.configureProviderPortReverse})}function _e(e,t){return Object.freeze(Object.fromEntries(he.flatMap(n=>t[n].available?[[n,e[n]]]:[])))}function ve(e){return()=>({captureBackendRefusal:e})}async function ye(e,t={}){let n=e?.captureBackend;if(n!==void 0&&!t.captureBackends?.includes(n))throw new i(`UNSUPPORTED_OPERATION`,`--capture-backend ${n} is not supported: ${t.captureBackendRefusal??`this capture owner declares no such backend`}`,{reason:`screenshot-capture-backend-unsupported`});if(e?.screenMask===void 0)return;let{readScreenshotScreenMask:r}=await import(`./screenshot.mjs`).then(e=>e.n);if(r(e?.screenMask)!==void 0&&t.screenMask!==!0)throw new i(`UNSUPPORTED_OPERATION`,`--screen-mask requires a handheld iOS simulator simctl capture`,{reason:`screenshot-screen-mask-unsupported`})}function be(e){return Object.freeze({captureScreenshot:e.capture})}function xe(e,t){let{captureBackend:n,preferredCaptureBackend:r,...i}=e??{};return n?{...i,captureBackend:n}:r&&t.captureCapabilities(i).captureBackends?.includes(r)?{...i,captureBackend:r}:i}function Se(e,t){return Object.freeze({captureScreenshot:async n=>{let r=xe(n.options,e);return await ye(r,e.captureCapabilities(r)),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e.signal})).screenshot(n.outPath,r)??{}}})}function Ce(e){return Se(e,o({...e,operation:`screenshot`}))}function we(e,t){return t.signal===void 0?e:AbortSignal.any([e,t.signal])}function Te(e){return Object.freeze({captureSnapshot:e.capture,captureSnapshotWithCustomActions:e.customActions,captureSnapshotWithoutActiveApp:e.withoutActiveApp})}function Ee(e){let t=async t=>{await De(e,t);let n=we(e.signal,t),r={...t.execution,appBundleId:t.options?.appBundleId,signal:n},a=e.ownership===`local`?await e.resolveInteractor(e.device,r):e.resolveInteractor(r);if(!a)throw new i(`UNSUPPORTED_OPERATION`,`Provider-owned snapshot operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id});let o=await a.snapshot({...t.options,signal:n});if(!ke(o))return o;if(!e.presentIosAcquisition)throw new i(`COMMAND_FAILED`,`Acquired iOS snapshot has no host presentation owner.`,{reason:`ios-snapshot-presenter-missing`,deviceId:e.device.id});return await e.presentIosAcquisition(o,t.options)};return Object.freeze({captureSnapshot:t,captureSnapshotWithCustomActions:t,captureSnapshotWithoutActiveApp:t})}async function De(e,t){if(t.options?.observeOnly!==!0)return;let{isHandheldAppleDevice:n}=await import(`./device2.mjs`).then(e=>e.t);if(!(e.ownership===`local`&&n(e.device)))throw new i(`UNSUPPORTED_OPERATION`,`observe-only snapshot requires a local iOS or iPadOS runner.`)}function Oe(e){return Ee({...e,ownership:`provider`})}function ke(e){return`stage`in e&&e.stage===`acquired`}function Ae(e){return Object.freeze({findText:e.findText,querySelector:e.querySelector})}function je(e){return Object.freeze({setViewport:e.setViewport})}function Me(e){return Object.freeze({focusPoint:e.focus})}function Ne(e,t){return Object.freeze({focusPoint:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).focus(n.point.x,n.point.y)}})}function Pe(e){return Ne(e.signal,o({...e,operation:`focus`}))}function Fe(e){let t=t=>t??e.unsupported;return Object.freeze({performGesturePlan:t(e.plan),performDirectionalFlingPlan:t(e.directionalFling),performMultiTouchGesturePlan:t(e.multiTouch),performTargetAuthoredDrag:t(e.targetAuthoredDrag),gestureViewport:t(e.viewport)})}function Ie(e){let t=e??{},n=C(t.pixels),r=C(t.x1),i=C(t.y1),a=C(t.x2),o=C(t.y2),s=r===void 0||i===void 0||a===void 0||o===void 0?void 0:{x:r/2+a/2,y:i/2+o/2};return{report:t,...n===void 0?{}:{pixels:n},...s===void 0?{}:{midpoint:s}}}function C(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Le(e){return Object.freeze({scrollDirection:e.scroll})}function Re(e,t){return Object.freeze({scrollDirection:async n=>(e.throwIfAborted(),Ie(await(await t({...n.execution,appBundleId:n.target?.appBundleId,signal:e})).scroll(n.direction,n.options)))})}function ze(e){return Re(e.signal,o({...e,operation:`scroll`}))}function Be(e){return Object.freeze({typeText:e.type})}function Ve(e,t){return Object.freeze({typeText:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).type(n.text,n.delayMs))})}function He(e){return Ve(e.signal,o({...e,operation:`type`}))}function Ue(e){return Object.freeze({readTextAtPoint:e.readTextAtPoint})}function w(e){return Object.freeze({back:e.back})}function We(e,t){return Object.freeze({back:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).back(n.mode)}})}const Ge=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`orientation auto is only supported on ADB-backed Android.`});function T(e){return Object.freeze({setOrientation:e.orientation,unlockOrientation:e.unlock??Ge})}function Ke(e,t){return Object.freeze({setOrientation:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).setOrientation(n.rotation))})}function qe(e,t){return Object.freeze({unlockOrientation:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.unlockOrientation,`orientation auto`).call(r)}})}function E(e){let{tvRemote:t,buttonSupport:n}=e;return Object.freeze({tvRemote:t.available&&n?Object.freeze({available:!0,subjects:Object.freeze(Object.fromEntries(n.supported.map(e=>[e,{available:!0}]))),unlisted:n.unsupported}):t})}const D=`tv-remote`;function Je(e,t){return Object.freeze({tvRemote:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.tvRemote,D).call(r,n.button,n.durationMs)}})}function Ye(e){let t=t=>t??e.unsupported;return Object.freeze({keyboardStatus:t(e.status),keyboardDismiss:t(e.dismiss),keyboardEnter:t(e.enter)})}async function Xe(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}const O={keyboardStatus:`keyboard status`,keyboardDismiss:`keyboard dismiss`,keyboardEnter:`keyboard enter`};function k(e,t,n){let r=async r=>{let i=await Xe(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],O[e]).call(i)};return Object.freeze({[e]:r})}function Ze(e){let t=t=>t??e.unsupported;return Object.freeze({readClipboard:t(e.read),writeClipboard:t(e.write)})}const A={readClipboard:`clipboard read`,writeClipboard:`clipboard write`};async function Qe(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}async function $e(e,t){let{requireInteractorMethod:n}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return n(e[t],A[t])}function et(e,t){return Object.freeze({readClipboard:async n=>{let r=await Qe(e,t,n);return await(await $e(r,`readClipboard`)).call(r)}})}function tt(e,t){return Object.freeze({writeClipboard:async n=>{let r=await Qe(e,t,n);await(await $e(r,`writeClipboard`)).call(r,n.text)}})}const nt=[`home`,`appSwitcher`,`actionButton`,`volumeUp`,`volumeDown`,`power`,`mute`,`sleep`,`wake`,`mediaPlayPause`,`mediaNext`,`mediaPrevious`,`mediaRewind`,`mediaFastForward`],j={home:`home`,appSwitcher:`app-switcher`,actionButton:`action-button`,volumeUp:`volume-up`,volumeDown:`volume-down`,power:`power`,mute:`mute`,sleep:`sleep`,wake:`wake`,mediaPlayPause:`media-play-pause`,mediaNext:`media-next`,mediaPrevious:`media-previous`,mediaRewind:`media-rewind`,mediaFastForward:`media-fast-forward`};function M(e){let t={};for(let n of nt)t[n]=e[n]??e.unsupported;return Object.freeze(t)}Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is not supported on Android TV targets; use tv-remote.`}),Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is supported on Android emulators and physical devices.`}),Object.freeze({available:!0}),nt.filter(e=>e!==`home`&&e!==`appSwitcher`&&e!==`actionButton`);function N(e,t,n){let r=async r=>{t.throwIfAborted();let i=await n({...r.execution,appBundleId:r.options?.appBundleId,signal:t});await s(i[e],j[e]).call(i)};return Object.freeze({[e]:r})}function P(e){return Object.freeze({triggerAppEvent:e.triggerAppEvent})}function rt(e,t){return Object.freeze({triggerAppEvent:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).open(n.eventUrl,{appBundleId:n.options?.appBundleId})}})}function F(e){return Object.freeze({readAlert:e.read,awaitAlert:e.wait,acceptAlert:e.accept,dismissAlert:e.dismiss})}async function it(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function at(e,t){return{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e.surface===void 0?{}:{surface:e.surface},...t?{signal:t}:{}}}const I={readAlert:`alert get`,awaitAlert:`alert wait`,acceptAlert:`alert accept`,dismissAlert:`alert dismiss`};function L(e,t,n){return Object.freeze({[e]:async r=>{let i=await it(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],I[e]).call(i,at(r,t))}})}function ot(e){return Object.freeze({audioProbeStart:e.capture,audioProbeReattach:e.capture,audioProbeCleanup:e.capture,audioProbeQuery:e.query})}function st(e){return Object.freeze({perfFrames:e.frames,perfMemorySample:e.memorySample,perfMemorySnapshot:e.memorySnapshot,perfNativeCaptureStart:e.nativeCapture,perfNativeCaptureReattach:e.nativeCapture,perfNativeCaptureCleanup:e.nativeCapture,perfProfileReport:e.profileReport})}function ct(e){let t=t=>t??e.unsupported;return Object.freeze({tapPoint:e.tap,tapRef:t(e.tapRef),longPressPoint:e.longPress,hoverPoint:lt(t(e.hover)),hoverRef:lt(t(e.hoverRef)),fillPoint:e.fill,fillRef:t(e.fillRef),tapElementSelector:t(e.tapElementSelector)})}function lt(e){return e.available?e:Object.freeze({...e,hint:e.hint??`hover raises pointer hover state and is available on web targets only. On touch platforms use longpress for hold gestures.`})}function ut(e,t){return{...e.execution,appBundleId:e.appBundleId,signal:t}}function dt(e,t,n,r){let i=async n=>(e.throwIfAborted(),await t(ut(n,e))),a=async t=>{e.throwIfAborted(),ft(t.options,n.longPressPoint);let a=await i(t);return t.options.button!==`primary`&&a.alternateClick?await a.alternateClick(t.point,t.options.button):a.pressPoint?await a.pressPoint(t.point,t.options):await mt(a,t.point,t.options,r)},o=async e=>{let t=await i(e);return await s(t.hover,`hoverPoint`).call(t,e.point.x,e.point.y)},c=async e=>await(await i(e)).fill(e.point.x,e.point.y,e.text,e.delayMs,{allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback});return Object.freeze({...n.tapPoint.available?{tapPoint:a}:{},...n.tapRef.available?{tapRef:async e=>{let t=await i(e);return await s(t.tapRef,`tapRef`).call(t,e.ref)}}:{},...n.longPressPoint.available?{longPressPoint:async e=>await(await i(e)).longPress(e.point.x,e.point.y,e.durationMs)}:{},...n.hoverPoint.available?{hoverPoint:o}:{},...n.hoverRef.available?{hoverRef:async e=>{let t=await i(e);return await s(t.hoverRef,`hoverRef`).call(t,e.ref)}}:{},...n.fillPoint.available?{fillPoint:c}:{},...n.fillRef.available?{fillRef:async e=>{let t=await i(e);return await s(t.fillRef,`fillRef`).call(t,e.ref,e.text,e.delayMs)}}:{},...n.tapElementSelector.available?{tapElementSelector:async e=>{let t=await i(e);return await s(t.tapElementSelector,`tapElementSelector`).call(t,e.selector)}}:{}})}function ft(e,t){if(!(e.holdMs<=0||t.available))throw new i(`UNSUPPORTED_OPERATION`,`press-and-hold is not supported by this runtime.`,{reason:t.reason,...t.hint===void 0?{}:{hint:t.hint}})}function pt(e){if(e.doubleTap)return e.doubleTap;throw new i(`UNSUPPORTED_OPERATION`,`double-tap is not supported by this runtime.`,{reason:`owner-capability-missing`,hint:`This runtime drives single presses; use --count to repeat them.`})}async function mt(e,t,r,a){if(r.button!==`primary`)throw new i(`UNSUPPORTED_OPERATION`,`Bound runtime does not implement ${r.button} click.`);let o=r.doubleTap?pt(e):void 0,s,c=0;try{for(let n=0;n<r.count;n+=1){let[i,l]=_t(n,r.jitterPx),u=await ht(e,o,t.x+i,t.y+l,r);c+=1,s??=u,n<r.count-1&&r.intervalMs>0&&await a(r.intervalMs)}}catch(e){throw n(e,c)}return s}async function ht(e,t,n,r,i){return t?await t.call(e,n,r):i.holdMs>0?await e.longPress(n,r,i.holdMs):await e.tap(n,r)}const gt=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function _t(e,t){if(t<=0)return[0,0];let[n,r]=gt[e%gt.length];return[n*t,r*t]}function vt(e){return dt(e.signal,o({...e,operation:`touch`}),e.facts,e.pause)}const yt={appLog:!0,apps:!0,appDeployment:!0,appState:!0,network:!0,screenRecording:!0,screenshot:!0,snapshot:!0,viewport:!0,focus:!0,gesture:!0,scroll:!0,typeText:!0,touch:!0,elementText:!0,back:!0,orientation:!0,fold:!0,telephony:!0,tvRemote:!0,keyboard:!0,clipboard:!0,systemButton:!0,triggerAppEvent:!0,settings:!0,readAlert:!0,awaitAlert:!0,acceptAlert:!0,dismissAlert:!0,audioProbeCapture:!0,audioProbeQuery:!0,perf:!0,readiness:!0,shutdown:!0};function bt(e){let t={};for(let n of Object.keys(yt))t[n]=e(n);return t}function xt(e,t,n){let r=Ct(n);return Object.freeze({device:{...me(e),providerMode:St(t)},operations:{appLogInspect:r.appLog,appLogDoctor:r.appLog,appLogStart:r.appLog,appLogReattach:r.appLog,appLogCleanup:r.appLog,listApps:r.apps,deployApp:r.appDeployment,materializeAppSource:r.appDeployment,deployMaterializedApp:r.appDeployment,sendPushNotification:r.appDeployment,uninstallApp:r.appDeployment,appState:r.appState,networkDump:r.network,screenRecordingStart:r.screenRecording,screenRecordingReattach:r.screenRecording,screenRecordingCleanup:r.screenRecording,...be({capture:r.screenshot}),...Te({capture:r.snapshot,customActions:r.snapshot,withoutActiveApp:r.snapshot}),...Ae({findText:r.snapshot,querySelector:r.snapshot}),...je({setViewport:r.viewport}),...Me({focus:r.focus}),...Fe({unsupported:r.gesture}),...Le({scroll:r.scroll}),...Be({type:r.typeText}),...ct({unsupported:r.touch,tap:r.touch,longPress:r.touch,fill:r.touch}),...Ue({readTextAtPoint:r.elementText}),...w({back:r.back}),...T({orientation:r.orientation,unlock:r.orientation}),setFoldPose:r.fold,sendTelephonyEvent:r.telephony,...E({tvRemote:r.tvRemote}),...Ye({unsupported:r.keyboard}),...Ze({unsupported:r.clipboard}),...M({unsupported:r.systemButton}),...P({triggerAppEvent:r.triggerAppEvent}),setSetting:r.settings,readSetting:r.settings,...F({read:r.readAlert,wait:r.awaitAlert,accept:r.acceptAlert,dismiss:r.dismissAlert}),...ot({capture:r.audioProbeCapture,query:r.audioProbeQuery}),...st({frames:r.perf,memorySample:r.perf,memorySnapshot:r.perf,nativeCapture:r.perf,profileReport:r.perf}),ensureReady:r.readiness,bootTarget:r.readiness,bootTargetHeadless:r.readiness,shutdownTarget:r.shutdown,...r.lifecycle}})}function St(e){switch(e.kind){case`local-family`:return`local`;case`provider-runtime`:return`provider-runtime`}}function Ct(e){return Object.freeze({...bt(t=>Object.freeze({...e[t]??e.network})),lifecycle:ge(e.lifecycle)})}function wt(e){return Object.freeze({setSetting:R(e,e.write),readSetting:R(e,e.read??{})})}function R(e,t){if(!e.target.available)return e.target;let n=Object.values(t).filter(e=>e!==void 0);if(!n.some(e=>e.available))return n[0]??e.unsupported;let r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.available?Tt:t]));return Object.freeze({available:!0,subjects:Object.freeze(r),unlisted:e.unsupported})}const Tt=Object.freeze({available:!0});async function Et(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Dt(e,t){return Object.freeze({setSetting:async n=>await(await Et(e,t,n)).setSetting(n.setting,n.state,n.appBundleId,n.options)})}function Ot(e,t){return Object.freeze({readSetting:async n=>{let r=await Et(e,t,n),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await i(r.readSetting,`settings read`).call(r,n.setting)}})}const kt=[{operation:`back`,label:`back`,bind:We},{operation:`home`,label:j.home,bind:(e,t)=>N(`home`,e,t)},{operation:`setOrientation`,label:`orientation`,bind:Ke},{operation:`unlockOrientation`,label:`orientation auto`,bind:qe},{operation:`tvRemote`,label:D,bind:Je},{operation:`keyboardStatus`,label:O.keyboardStatus,bind:(e,t)=>k(`keyboardStatus`,e,t)},{operation:`keyboardDismiss`,label:O.keyboardDismiss,bind:(e,t)=>k(`keyboardDismiss`,e,t)},{operation:`keyboardEnter`,label:O.keyboardEnter,bind:(e,t)=>k(`keyboardEnter`,e,t)},{operation:`readClipboard`,label:A.readClipboard,bind:et},{operation:`writeClipboard`,label:A.writeClipboard,bind:tt},{operation:`appSwitcher`,label:j.appSwitcher,bind:(e,t)=>N(`appSwitcher`,e,t)},{operation:`actionButton`,label:j.actionButton,bind:(e,t)=>N(`actionButton`,e,t)},{operation:`volumeUp`,label:j.volumeUp,bind:(e,t)=>N(`volumeUp`,e,t)},{operation:`volumeDown`,label:j.volumeDown,bind:(e,t)=>N(`volumeDown`,e,t)},{operation:`power`,label:j.power,bind:(e,t)=>N(`power`,e,t)},{operation:`mute`,label:j.mute,bind:(e,t)=>N(`mute`,e,t)},{operation:`sleep`,label:j.sleep,bind:(e,t)=>N(`sleep`,e,t)},{operation:`wake`,label:j.wake,bind:(e,t)=>N(`wake`,e,t)},{operation:`mediaPlayPause`,label:j.mediaPlayPause,bind:(e,t)=>N(`mediaPlayPause`,e,t)},{operation:`mediaNext`,label:j.mediaNext,bind:(e,t)=>N(`mediaNext`,e,t)},{operation:`mediaPrevious`,label:j.mediaPrevious,bind:(e,t)=>N(`mediaPrevious`,e,t)},{operation:`mediaRewind`,label:j.mediaRewind,bind:(e,t)=>N(`mediaRewind`,e,t)},{operation:`mediaFastForward`,label:j.mediaFastForward,bind:(e,t)=>N(`mediaFastForward`,e,t)},{operation:`triggerAppEvent`,label:`trigger-app-event`,bind:rt},{operation:`setSetting`,label:`settings`,bind:Dt},{operation:`readSetting`,label:`settings read`,bind:Ot},{operation:`readAlert`,label:I.readAlert,bind:(e,t)=>L(`readAlert`,e,t)},{operation:`awaitAlert`,label:I.awaitAlert,bind:(e,t)=>L(`awaitAlert`,e,t)},{operation:`acceptAlert`,label:I.acceptAlert,bind:(e,t)=>L(`acceptAlert`,e,t)},{operation:`dismissAlert`,label:I.dismissAlert,bind:(e,t)=>L(`dismissAlert`,e,t)}];function At(e,t){let n={};for(let r of kt)e.facts[r.operation]?.available&&Object.assign(n,r.bind(e.signal,t(r)));return n}function jt(e){return At(e,t=>o({...e,operation:t.label}))}const z=Object.freeze({available:!0}),Mt=c(`unsupported-provider-mode`,`Revyl enters text at a point; run fill <field> "text" instead of type.`),Nt=c(`unsupported-provider-mode`,`Revyl does not expose portable gesture execution.`),Pt=c(`unsupported-provider-mode`,`Revyl does not expose keyboard status, dismissal, or a return-key press.`),Ft=c(`unsupported-provider-mode`,`Revyl does not expose the pasteboard.`),It=c(`unsupported-provider-mode`,`Revyl does not expose orientation control.`),Lt=c(`unsupported-provider-mode`,`Revyl has a back button only on Android; on iOS, click the app's own back control.`),Rt=c(`unsupported-provider-mode`,`Revyl exposes the home button only.`),zt=c(`unsupported-provider-mode`,`Revyl does not expose settings control.`),Bt=c(`unsupported-provider-mode`,`Revyl does not deliver a push notification to a session.`),B=c(`unsupported-provider-mode`,`Revyl has no alert surface of its own; a system alert appears in the snapshot tree.`),Vt=c(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets; Revyl rents phones and tablets.`),V=c(`owner-capability-missing`,`Revyl requires a matching live provider session for this device.`),Ht=c(`unsupported-provider-mode`,`fold runs a HID helper inside a foldable iPhone simulator on the daemon host; a Revyl session has no such simulator.`),Ut=c(`unsupported-provider-mode`,`telephony sends calls and SMS to an Android emulator's console through local adb; agent-device does not route it through a Revyl session.`);function Wt(e){let t=e??z;return Object.freeze({...Me({focus:t}),...Be({type:e??Mt}),...ct({unsupported:e??c(`unsupported-provider-mode`,`Revyl taps and fills at a point; it has no action for a hover or for a selector target.`),tap:t,longPress:t,fill:t}),...Fe({unsupported:e??Nt}),...Le({scroll:t})})}function Gt(e,t){return Object.freeze(t?{...w({back:t}),...T({orientation:t,unlock:t}),...M({unsupported:t}),...E({tvRemote:t})}:{...w({back:e.platform===`android`?z:Lt}),...T({orientation:It,unlock:It}),...M({unsupported:Rt,home:z}),...E({tvRemote:Vt})})}function Kt(e){return Object.freeze({...Ye({unsupported:e??Pt}),...Ze({unsupported:e??Ft}),...wt({target:e??z,unsupported:e??zt,write:{}}),...P({triggerAppEvent:e??Bt}),...F({read:e??B,wait:e??B,accept:e??B,dismiss:e??B}),setFoldPose:e??Ht,sendTelephonyEvent:e??Ut})}function qt(e){let{device:t,signal:n}=e,r=n=>e.getInteractor(t,n);return Object.freeze({...Oe({device:t,signal:n,resolveInteractor:r,presentIosAcquisition:e.presentIosAcquisition}),...Ce({device:t,signal:n,resolveInteractor:r,captureCapabilities:ve(`Revyl captures through its provider endpoint`)}),...Pe({device:t,signal:n,resolveInteractor:r}),...He({device:t,signal:n,resolveInteractor:r}),...vt({device:t,signal:n,resolveInteractor:r,facts:Wt(),pause:async e=>await g(e,void 0,{signal:n})}),...ze({device:t,signal:n,resolveInteractor:r})})}const Jt=`--launch-console requires a direct app launch and cannot be used with URL opens`;function Yt(e,t,n){return{requestId:e.requestId,signal:n,appBundleId:t,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function Xt(e){let{device:t,signal:n,ownership:r}=e;return Object.freeze({device:t,signal:n,resolveInteractor:async(a,o)=>{let s=Yt(a,o,n);if(r===`local`)return await e.resolveLocalInteractor(t,s);if(a.launchConsole)throw new i(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for a local or Limrun iOS simulator app launch`,{reason:`launch-console-owner-unadmitted`,deviceId:t.id,hint:`Remove --launch-console, or use a local or Limrun iOS simulator for launch output.`});let c=r.resolveInteractor(s);if(c)return c;throw new i(`UNSUPPORTED_OPERATION`,`Provider-owned application lifecycle operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:t.id})}})}function Zt(e){return Xt({device:e.device,signal:e.signal,ownership:{kind:`provider`,resolveInteractor:e.resolveInteractor}})}async function Qt(e){let{device:t,positionals:n,execution:r}=e;$t(n);let i=n[0],a=n[1];if(!i){await en(e);return}return tn(t,r),a===void 0?await rn(e,i):await nn(e,i,a)}function $t(e){if(e.length>2)throw new i(`INVALID_ARGS`,`open accepts at most two arguments: <app|url> [url]`)}async function en(e){if(e.execution.launchConsole)throw new i(`INVALID_ARGS`,`--launch-console requires an app target`);if(e.execution.launchArgs&&e.execution.launchArgs.length>0)throw new i(`INVALID_ARGS`,`--launch-args requires an app target`);await e.interactor.openDevice()}function tn(e,t){if(t.launchConsole&&(!a(e)||e.kind!==`simulator`))throw new i(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for iOS simulator app launches`);if(e.platform===`linux`&&t.launchArgs&&t.launchArgs.length>0)throw new i(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on Linux.`)}async function nn(e,t,n){if(d(t))throw new i(`INVALID_ARGS`,`open <app> <url> requires an app target as the first argument`);if(!d(n))throw new i(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(e.execution.launchConsole)throw new i(`INVALID_ARGS`,Jt);return await e.interactor.open(t,{activity:e.execution.activity,appBundleId:e.appBundleId,launchArgs:e.execution.launchArgs?[...e.execution.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp,url:n})}async function rn(e,t){let{execution:n,interactor:r}=e;if(n.launchConsole&&d(t))throw new i(`INVALID_ARGS`,Jt);if(n.clearAppState){if(d(t))throw new i(`INVALID_ARGS`,`Clearing app state requires an app target, not a deep link.`);await r.setSetting(`clear-app-state`,`clear`,t)}return await r.open(t,{activity:n.activity,appBundleId:e.appBundleId,launchConsole:n.launchConsole,launchArgs:n.launchArgs?[...n.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp})}function an(e){let{binding:t}=e,n=async()=>{throw new i(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for ${e.owner}.`)};return Object.freeze({resolveOpenTarget:async t=>cn(e.openTargetIdentity,t),prepareApplicationOpen:async()=>void 0,openApplication:async t=>await on(e,t),applyRuntimeHints:n,clearRuntimeHints:n,closeApplication:async e=>{await ln({device:t.device,interactor:await t.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async()=>({}),prepareAppleRunner:n,configureProviderPortReverse:e.configureProviderPortReverse??n})}async function on(e,t){let{binding:n}=e,r=await n.resolveInteractor(t.execution,t.appBundleId);e.closeBeforeRelaunch&&t.relaunch&&t.target!==void 0&&await ln({device:n.device,interactor:r,positionals:[t.appBundleId??t.target]}),await Qt({device:n.device,interactor:r,positionals:t.positionals,appBundleId:t.appBundleId,execution:t.execution,...e.closeBeforeRelaunch?{}:{terminateRunningApp:t.relaunch}});let i=sn(t);return i&&await Qt({device:n.device,interactor:r,positionals:[i],appBundleId:t.appBundleId,execution:{...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),{appBundleId:t.appBundleId,timing:{}}}function sn(e){let t=e.runtimeLaunchUrl?.trim(),n=e.positionals.length===1?e.positionals[0]?.trim():void 0;if(!(!t||!n||d(n)))return t}function cn(e,t){let n=t.target;if(e===`app-name`)return Object.freeze(n===void 0?{}:{appName:n});let r=n?.trim(),i=r&&r.includes(`.`)&&!d(r)?r:t.currentAppBundleId;return Object.freeze({...i===void 0?{}:{appBundleId:i},...n===void 0?{}:{appName:n}})}async function ln(e){let{device:t,interactor:n,positionals:r}=e,i=r[0];if(!i){t.platform===`web`&&await n.close(``);return}await n.close(i)}function un(e){let t=Zt({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)}),n=an({owner:`Revyl`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!1,binding:t});return Object.freeze({...n,openApplication:async e=>(e.relaunch&&e.target!==void 0&&await(await t.resolveInteractor(e.execution,e.appBundleId)).close(``),await n.openApplication(e))})}const dn=c(`unsupported-provider-mode`,`Revyl does not uninstall an app from a session.`),fn=c(`unsupported-provider-mode`,`Revyl does not report which app the device has in the foreground.`),H=c(`unsupported-provider-mode`,`Revyl does not expose an app log stream.`),pn=c(`unsupported-provider-mode`,`Revyl does not report the apps installed on a session.`),mn=c(`unsupported-provider-mode`,`Revyl does not expose a network capture for a session.`),U=c(`unsupported-provider-mode`,`Revyl streams the screen for its own viewer and does not expose a recording.`),hn=c(`unsupported-provider-mode`,`Custom snapshot actions are available only on a local iOS runner.`),gn=c(`unsupported-provider-mode`,`Revyl rents a device at the size its model has.`),W=c(`unsupported-provider-mode`,`Revyl-owned devices read element text from the captured tree only.`),_n=c(`unsupported-provider-mode`,`Headless boot is unavailable for provider-owned devices.`),vn=c(`unsupported-provider-mode`,`Apple runner preparation is unavailable for Revyl-owned devices.`),yn=c(`unsupported-provider-mode`,`Revyl owns the target lifecycle for provider-owned devices.`),bn=c(`unsupported-provider-mode`,`Runtime hints are not applied to provider-owned devices.`),xn=c(`unsupported-provider-mode`,`Revyl does not expose port reverse; publish the app server at a public URL instead.`),Sn=c(`unsupported-provider-mode`,`Revyl does not expose the audio probe.`),G=c(`unsupported-provider-mode`,`Revyl does not expose frame, memory, or profiler counters for a session.`),Cn=c(`unsupported-provider-mode`,`Revyl open requires the app the session was started with.`),wn=c(`unsupported-provider-mode`,`Revyl close requires the app the session was started with.`);function K(t,n){let r=e(t),i=r?n?z:V:Cn,a=r?n?z:V:wn;return ge({resolveOpenTarget:i,prepareApplicationOpen:i,openApplication:i,applyRuntimeHints:bn,clearRuntimeHints:bn,closeApplication:a,finalizeApplicationClose:a,prepareAppleRunner:vn,configureProviderPortReverse:xn})}function Tn(e){return Object.freeze({device:{...me(e),providerMode:`provider-runtime`},operations:{appLogInspect:H,appLogDoctor:H,appLogStart:H,appLogReattach:H,appLogCleanup:H,listApps:pn,deployApp:z,materializeAppSource:z,deployMaterializedApp:z,sendPushNotification:Bt,uninstallApp:dn,appState:fn,networkDump:mn,screenRecordingStart:U,screenRecordingReattach:U,screenRecordingCleanup:U,...Te({capture:z,customActions:hn,withoutActiveApp:z}),...be({capture:z}),...Ae({findText:W,querySelector:W}),...je({setViewport:gn}),...Wt(),...Ue({readTextAtPoint:W}),...Gt(e),...Kt(),...ot({capture:Sn,query:Sn}),...st({frames:G,memorySample:G,memorySnapshot:G,nativeCapture:G,profileReport:G}),ensureReady:z,bootTarget:z,bootTargetHeadless:_n,shutdownTarget:yn,...K(e,!0)}})}const En=Object.freeze({appLog:V,appState:V,appDeployment:V,apps:V,network:V,screenRecording:V,screenshot:V,snapshot:V,viewport:V,focus:V,gesture:V,scroll:V,typeText:V,touch:V,elementText:V,back:V,orientation:V,fold:Ht,telephony:Ut,tvRemote:V,keyboard:V,clipboard:V,systemButton:V,triggerAppEvent:V,settings:V,readAlert:V,awaitAlert:V,acceptAlert:V,dismissAlert:V,audioProbeCapture:V,audioProbeQuery:V,perf:V,readiness:V,shutdown:V}),Dn=new Set([`1`,`true`,`yes`,`on`]),On=new Set([`0`,`false`,`no`,`off`]);function kn(e){let t=e.trim().toLowerCase();if(Dn.has(t))return!0;if(On.has(t))return!1}const q=new y;function An(e){let t=q.getStore();t&&Object.assign(t,e)}function jn(){let e=q.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:o}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:o}}function Mn(e,t=[]){return JSON.stringify(e,(e,n)=>typeof n==`bigint`||typeof n==`string`?X(n,t):n)}function J(e,t=[]){try{return Mn(e,t)}catch{let{data:n,...r}=e;return Mn({...r,data:{reason:`diagnostic-data-unserializable`}},t)}}function Nn(e){let t=q.getStore();if(t)try{let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?Fn(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${J(n,Y(t))}\n`;t.debug&&t.logPath&&(Z(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&Z(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}function Pn(e={}){let t=q.getStore();if(!t||!e.force&&!t.debug&&!t.flushOnSuccess||t.events.length===0)return null;let n=Y(t);try{let e=t.logPath??t.flushedLogPath;if(e){let r=t.events.slice(t.liveWrittenEventCount);r.length>0&&Z(t,e,`${r.map(e=>J(e,n)).join(`
2
+ `)}\n`);let i=t.logRecord;return t.events=[],t.liveWrittenEventCount=0,{path:e,...i?{ref:i}:{}}}let r=In(t.session??`default`),i=new Date().toISOString().slice(0,10),a=p.join(v.homedir(),`.agent-device`,`logs`,r,i);f.mkdirSync(a,{recursive:!0});let o=new Date().toISOString().replaceAll(/[:.]/g,`-`),s=p.join(a,`${o}-${t.diagnosticId}.ndjson`),c=t.events.map(e=>J(e,n));return f.writeFileSync(s,`${c.join(`
3
+ `)}\n`),t.flushedLogPath=s,t.events=[],{path:s}}catch{return null}}function Y(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function Fn(e,t){let n=Y(e);try{return X(oe(t),n)}catch{return X({reason:`diagnostic-data-unserializable`},n)}}function X(e,t){return typeof e==`bigint`&&(e=e.toString()),typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>X(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,X(n,t)]))}function In(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function Z(e,t,n){let r=p.dirname(t);e.ensuredDirectories.has(r)||(f.mkdirSync(r,{recursive:!0}),e.ensuredDirectories.add(r)),f.appendFileSync(t,n,`utf8`)}function Ln(e,t,n){let r=kn(n?.AGENT_DEVICE_EXEC_TRACE??``)===!0,i=jn();if(!i.debug&&!r)return{emit:()=>{}};r&&!i.flushOnSuccess&&An({flushOnSuccess:!0});let a=performance.now(),o=m(),s,c=!1,l=p.basename(e),u=y.bind((e,n={})=>{s=n.pid??s,Nn({level:`debug`,phase:`exec_command`,durationMs:performance.now()-a,data:{execId:o,command:l,event:e,pid:s,timeoutMs:t,...n}}),e===`settled`&&(c=!0),r&&(e===`settled`||e===`close`&&c)&&Pn()});return u(`spawn_start`),{emit:u}}const Rn=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,zn=new y,Q=new y;function Bn(){let e=Q.getStore();return e?.requestEnv&&Object.hasOwn(e.requestEnv,`DEVELOPER_DIR`)?e.requestEnv.DEVELOPER_DIR||void 0:e?.host.env.DEVELOPER_DIR||void 0}function Vn(e){let t=Q.getStore();return t?{...e??t.host.env,...t.requestEnv}:e}async function Hn(e,t,n={}){let r=zn.getStore()?.(e,t,n);return r?Un(await r):await Wn(e,t,n)}function Un(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function Wn(e,t,n={}){let r=Kn(e),i=Ln(e,ar(n.timeoutMs),Q.getStore()?.host.env);return new Promise((a,o)=>{let s=ee(r,t,{cwd:n.cwd,env:Vn(n.env),stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});s.once(`spawn`,()=>i.emit(`spawn`,{pid:s.pid})),n.onSpawn?.(s);let c=``,l=n.binaryStdout&&n.captureOutput!==!1?[]:void 0,u=``,d=!1,f=ar(n.timeoutMs),p=null,m=!1;function h(e){return!m&&(m=!0,p&&clearTimeout(p),y.dispose(),ur(s),i.emit(`settled`,{reason:e}),!0)}function g(e,t){h(t)&&o(e)}function _(i){if(!h(y.didAbort?`abort`:d?`timeout`:(i??1)!==0&&!n.allowFailure?`exit_failure`:`success`))return;let p=i??1;if(!y.didAbort&&d&&f){o(Zn(r,e,t,f,p,c,u));return}let m=rr(y,r,e,t,p,n.allowFailure,c,u);if(m){o(m);return}a(Gn(s,{stdout:c,stderr:u,exitCode:p,stdoutBuffer:l?Buffer.concat(l):void 0}))}let v=or({killProcessTree:()=>lr(s,n),settle:_}),y=sr(n,()=>{i.emit(`abort`),v.requestKill()});p=f?setTimeout(()=>{i.emit(`deadline`),d=!0,v.requestKill()},f):null,n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),dr(s,n.stdin).catch(i=>{y.didAbort||d||fr(i)||(g(Xn(r,e,t,i),`stdin_error`),lr(s,n))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);n.captureOutput!==!1&&(c+=t),n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);n.captureOutput!==!1&&(u+=t),n.onStderrChunk?.(t)}),s.on(`error`,n=>{i.emit(`error`),g(nr(y,r,e,t,n),`spawn_error`)}),s.once(`exit`,(e,t)=>{i.emit(`exit`,{exitCode:e,signal:t}),v.recordExit(e)}),s.once(`close`,(e,t)=>{i.emit(`close`,{exitCode:e,signal:t}),_(e)})})}function Gn(e,t){return e.signalCode?{...t,signal:e.signalCode}:t}function Kn(e){let t=ir(e);if(!t)throw new i(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return t}function qn(e,t,n,r){return r.code===`ENOENT`?Jn(e,t,r):Yn(e,t,n,r)}function Jn(e,t,n){return new i(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:t},n)}function Yn(e,t,n,r){return new i(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:t,args:n},r)}function Xn(e,t,n,r){return new i(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:t,args:n},r instanceof Error?r:void 0)}function Zn(e,t,n,r,a,o,s){return new i(`COMMAND_FAILED`,`${e} timed out after ${r}ms`,{cmd:t,args:n,stdout:o,stderr:s,exitCode:a,timeoutMs:r})}function Qn(e,t,n,r,a,o){return new i(`COMMAND_FAILED`,`${e} exited with code ${r}`,tr({stdout:a,stderr:o,exitCode:r},{cmd:t,args:n}))}const $n=/xcrun: error: unable to find utility "([^"]+)"/;function er(e){let t=$n.exec(e)?.[1];if(!t)return{};let n=Bn(),r=n?`DEVELOPER_DIR ${n}`:`the developer dir selected by xcode-select (see xcode-select -p)`;return{reason:`xcrun-tool-not-found`,developerDir:n??null,hint:`xcrun could not find ${t} in ${r}. Export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer (or your Xcode's path) before running agent-device, or run sudo xcode-select -s /Applications/Xcode.app.`}}function tr(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t,...er(e.stderr)}}function nr(e,t,n,i,a){return e.didAbort?r({cmd:n,args:i,executable:t}):qn(t,n,i,a)}function rr(e,t,n,i,a,o,s,c){return e.didAbort?r({cmd:n,args:i,executable:t}):a!==0&&!o?Qn(t,n,i,a,s,c):null}function ir(e){let t=e.trim();return!t||t.includes(`\0`)?null:p.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:Rn.test(t)?t:null}function ar(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function or(e){let t=!1,n=!1,r=null,i=()=>{t&&n&&e.settle(r)};return{requestKill:()=>{t=!0,e.killProcessTree(),i()},recordExit:e=>{n=!0,r=e??1,i()}}}function sr(e,t){let n=!1,r=()=>{n=!0,t()};return e.signal?.aborted?r():e.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{e.signal?.removeEventListener(`abort`,r)}}}function cr(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}function lr(e,t){if(!t.kill){$(e,t.detached,`SIGKILL`);return}$(e,t.detached,t.kill.signal);let n=setTimeout(()=>$(e,t.detached,`SIGKILL`),t.kill.graceMs);n.unref(),e.once(`exit`,()=>clearTimeout(n))}function $(e,t,n){if(t&&e.pid&&process.platform!==`win32`){cr(e.pid,n);return}e.exitCode===null&&e.signalCode===null&&e.kill(n)}function ur(e){e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()}async function dr(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await te(h.from([t]),e.stdin)}}function fr(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}async function pr(e,t){t.signal?.throwIfAborted();let n=p.basename(e),r=f.mkdtempSync(p.join(v.tmpdir(),`agent-device-pack-${m()}-`)),i=()=>{try{f.rmSync(r,{recursive:!0,force:!0})}catch{}},a=p.join(r,t.fileName??`${n}.tar.gz`);try{await Hn(`tar`,[`czf`,a,`-C`,p.dirname(e),`--`,n],{env:{...t.env,COPYFILE_DISABLE:`1`},...t.signal===void 0?{}:{signal:t.signal},...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}}),t.signal?.throwIfAborted()}catch(e){throw i(),e}return{archivePath:a,cleanup:i}}var mr=class e{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(t,n=Date.now()){return new e(n,t)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return this.remainingMs(e)<=0}};async function hr(e){let{probe:t,settled:n,deadline:i,intervalMs:a,signal:o}=e,s;for(;;){if(o?.aborted)throw r();let e=await t();if(n(e,s))return{settled:!0,value:e};let c=i.remainingMs();if(c<=0)return{settled:!1,value:e};s=e,await gr(Math.min(a,c),o)}}function gr(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=!1,i=()=>{r||(r=!0,t&&t.removeEventListener(`abort`,o),n())},a=setTimeout(i,e);function o(){clearTimeout(a),i()}t&&t.addEventListener(`abort`,o,{once:!0})})}async function _r(e,t,n,r,i=42e4){let a=mr.fromTimeoutMs(i),o=AbortSignal.timeout(i),s=AbortSignal.any([r,o]),c=e=>yr(`provider-unconfirmed`,`Revyl did not finish the install within ${i/1e3} s.`,e);try{let r=await vr(e,t,n,s,a);if(!r)throw c();return r}catch(e){throw r.aborted?yr(`request_canceled`,`The install was canceled.`,e):o.aborted?c(e):e}}async function vr(e,t,n,r,i){let a=await xr(e.platform,t,n,r);try{let{size:t}=await _.stat(a.filePath),n=await e.client.createSessionArtifactUpload(e.sessionId,t,a.contentType,r);await e.client.uploadSessionArtifact(n.upload_url,{filePath:a.filePath,size:t},a.contentType,r);let o=await wr(e,n.download_url,r,i);return o&&Er(e.platform,o)}finally{a.cleanup()}}function yr(e,t,n){return new i(`COMMAND_FAILED`,t,{reason:e,hint:`Check the session in Revyl; an install it already accepted may still complete.`},n)}const br={ios:[[`.zip`,`application/zip`],[`.tar.gz`,`application/gzip`],[`.tgz`,`application/gzip`]],android:[[`.apk`,`application/vnd.android.package-archive`]]};async function xr(e,t,n,r){let i=await _.stat(t),a=t.toLowerCase().replace(/[\\/]+$/,``);if(e===`ios`&&i.isDirectory()&&a.endsWith(`.app`)){let e=await pr(t,{env:n,signal:r});return{filePath:e.archivePath,contentType:`application/gzip`,cleanup:e.cleanup}}let o=i.isFile()?br[e].find(([e])=>a.endsWith(e)):void 0;if(o)return Cr(t,o[1]);throw Sr(e,t)}function Sr(e,t){return e===`ios`?new i(`INVALID_ARGS`,`Revyl installs an iOS simulator build: a .app directory, or a .zip, .tar.gz, or .tgz of one.`,{reason:`unsupported_app_artifact`,appPath:t,hint:`Build for the iOS simulator; a device .ipa does not run on a simulator.`}):new i(`INVALID_ARGS`,`Revyl installs an Android build from an .apk file.`,{reason:`unsupported_app_artifact`,appPath:t,hint:`Pass the .apk the build produced.`})}function Cr(e,t){return{filePath:e,contentType:t,cleanup:()=>void 0}}async function wr(e,t,n,r){let a=await e.client.startInstall(e.runId,{app_url:t,platform:e.platform},n),o=a.install_id?.trim();if(a.status!==`accepted`||!o)throw new i(`COMMAND_FAILED`,`Revyl did not accept the app install.`,{reason:`provider-refused`,...a.status===void 0?{}:{providerDetail:a.status}});let{settled:s,value:c}=await hr({probe:async()=>await e.client.getInstallStatus(e.runId,o,n),settled:e=>e.status!==`running`,deadline:r,intervalMs:1e3,signal:n});if(s){if(c.status===`completed`||c.status===`failed`||c.status===`cancelled`)return Tr(c.status,c.result??void 0);throw new i(`COMMAND_FAILED`,`Revyl reported install status "${c.status}".`,{reason:`provider-refused`,installId:o})}}function Tr(e,t){let n=typeof t?.error==`string`&&t.error!==``?t.error:void 0,r=t?.success??t?.Success;if(e===`completed`&&r!==!1&&!n)return t??{};throw new i(`COMMAND_FAILED`,`Revyl could not install the app${n===void 0?``:`: ${n}`}`,{reason:`provider-refused`,installStatus:e,...n===void 0?{}:{providerDetail:n}})}function Er(e,t){let n=(e===`ios`?t.bundle_id:t.package_name??t.bundle_id)??void 0;return n?e===`ios`?{bundleId:n,launchTarget:n}:{packageName:n,launchTarget:n}:{}}function Dr(e){let t=e.bundleId??e.packageName;return{...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{packageName:e.packageName}:{},...e.appName?{appName:e.appName}:{},...t?{launchTarget:t}:{}}}function Or(n){let r=u(t,n.runtimeInstance),a=t=>e(t)&&n.ownsDevice(t),o=e=>a(e)&&n.hasLiveSession(e);return Object.freeze({owner:r,ownsDevice:a,inspectFacts:async e=>o(e)?Tn(e):xt(e,r,{...En,lifecycle:K(e,!1)}),bind:async t=>{if(t.intent.kind===`exact-owner`&&!l(t.intent.owner,r))throw new i(`UNSUPPORTED_OPERATION`,`Revyl runtime owner identity does not match`);if(!e(t.device))throw new i(`UNSUPPORTED_PLATFORM`,`Revyl requires an iOS simulator or Android emulator device identity`);let a=o(t.device);if(t.intent.kind!==`exact-owner`&&!a)throw new i(`UNSUPPORTED_OPERATION`,`Revyl provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return kr(n,r,t.device,t.scope.signal,a)},shutdown:async()=>void 0})}function kr(e,t,n,r,i){let a=i?Tn(n):xt(n,t,{...En,lifecycle:K(n,!1)}),o={ensureReady:async()=>({...n,booted:!0}),bootTarget:async()=>({...n,booted:!0}),..._e(un({device:n,signal:r,getInteractor:e.getInteractor}),K(n,i)),...qt({device:n,signal:r,getInteractor:e.getInteractor,presentIosAcquisition:e.host.snapshot.presentIosAcquisition}),...jr(e,n,r),...jt({device:n,signal:r,resolveInteractor:t=>e.getInteractor(n,t),facts:a.operations})};return Object.freeze({device:n,owner:t,facts:a,operations:Object.freeze(Ar(a,o)),[Symbol.asyncDispose]:async()=>void 0})}function Ar(e,t){let n={};for(let[r,i]of Object.entries(t))e.operations[r]?.available&&(n[r]=i);return n}function jr(e,t,n){let r=()=>e.host.hostEnvironment.env,a=()=>{let n=e.getDeploymentSession(t);if(n)return n;throw new i(`UNSUPPORTED_OPERATION`,`Revyl provider session is no longer live.`,{reason:`provider-session-unavailable`})};return{deployApp:async e=>{if(e.replaceExisting)throw new i(`UNSUPPORTED_OPERATION`,`Revyl cannot reinstall an app: it has no uninstall, and installing over an app keeps its data.`,{reason:`unsupported-provider-mode`,hint:`Run install to update the build in place, or start a new session for a clean app.`});return await _r(a(),e.appPath,r(),n)},materializeAppSource:async r=>t.platform===`apple`?await e.host.appleDeployment.prepareArtifact(r,{signal:n}):await e.host.androidDeployment.prepareArtifact(r,{signal:n}),deployMaterializedApp:async({artifact:e})=>({...Dr(e),...await _r(a(),e.installablePath,r(),n)})}}export{Or as createRevylPlatformRuntimeOwner};
@@ -1 +1 @@
1
- import{r as e,t}from"./rolldown-runtime.mjs";import{o as n,t as r}from"./errors.mjs";import{t as i}from"./screenshot.mjs";import a,{promises as o}from"node:fs";import{Worker as s}from"node:worker_threads";import c from"node:path";import{fileURLToPath as l}from"node:url";var u=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)}}})),d=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}}})),f=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}})),p=t(((e,t)=>{let n=d(),r=f();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=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=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.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}},a.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}},a.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}},a.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}},a.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())}})),m=t(((t,n)=>{let r=e(`util`),i=u(),a=p(),o=n.exports=function(e){i.call(this);let t=[],n=this;this._filter=new a(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};r.inherits(o,i)})),h=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}})),g=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}})),_=t(((e,t)=>{let n=h(),r=g(),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()}})),v=t((e=>{let t=d(),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 i(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 a(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 o(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,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),y=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}})),b=t(((t,n)=>{let r=e(`util`),i=e(`zlib`),a=u(),o=m(),s=_(),c=v(),l=y(),d=n.exports=function(e){a.call(this),this._parser=new s(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()};r.inherits(d,a),d.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},d.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=i.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,i.Z_MIN_CHUNK);this._inflate=i.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 a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},d.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new o(this._bitmapInfo)},d.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},d.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},d.prototype._simpleTransparency=function(){this._metaData.alpha=!0},d.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},d.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},d.prototype._complete=function(e){if(this.errord)return;let t;try{let n=c.dataToBitMap(e,this._bitmapInfo);t=l(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),x=t(((e,t)=>{let n=h();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}})),S=t(((e,t)=>{let n=f();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 a(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 o(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 s(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 c(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 l(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 u(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 d(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:a,2:s,3:l,4:d},h={0:i,1:o,2:c,3:u,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}})),C=t(((t,n)=>{let r=h(),i=g(),a=x(),o=S(),s=e(`zlib`),c=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`)};c.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},c.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},c.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)},c.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},c.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)},c.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)},c.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},c.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),w=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=h(),o=C(),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)}})),T=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})),E=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`)}})),D=t((e=>{let t=E(),n=p();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)}})),O=t(((t,n)=>{let r=!0,i=e(`zlib`),a=T();i.deflateSync||(r=!1);let o=E(),s=D(),c=_(),l=v(),u=y();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 d(e){n=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.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:d,metadata:p,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(f.interlace)C=i.inflateSync(S);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.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,f);S=null;let T=l.dataToBitMap(w,f);w=null;let E=u(T,f,t.skipRescale);return f.data=E,f.gamma=_||0,f}})),k=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=h(),o=C();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)}})),A=t((e=>{let t=O(),n=k();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),j=t((t=>{let n=e(`util`),r=e(`stream`),i=b(),a=w(),o=A(),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)}}))();Buffer.from([137,80,78,71,13,10,26,10]);function M(e,t){try{return j.PNG.sync.read(e)}catch(e){throw new r(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}function N(e,t){try{let n=l(e),r=c.extname(n)||`.js`;return[c.join(c.dirname(n),`${t}${r}`),c.join(c.dirname(n),`internal`,`${t}${r}`)].find(e=>a.existsSync(e))??null}catch{return null}}function P(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var F=class extends Error{};let I=null,L;const R=new Set;let z=0;const B=new Map;function V(e){if(!L){L=e;for(let t of R)t(e)}}function H(e){let t=B.get(e.id);t&&(B.delete(e.id),G(),e.ok?t.resolve(e.result):t.reject(new r(n(e.error.code),e.error.message,e.error.details)))}function U(e,t){I===e&&(V(t),I=null,e.terminate().catch(()=>{}),W(new F(`PNG worker failed: ${t.kind}`)))}function W(e){let t=[...B.values()];B.clear();for(let n of t)n.reject(e)}function G(){I&&(B.size>0?I.ref():I.unref())}function K(){if(L)return null;if(I)return I;let e=N(import.meta.url,`png-worker`);if(!e)return V({kind:`entry-not-found`}),null;try{let t=new s(e,{env:{},execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,H),t.on(`error`,e=>{U(t,{kind:`worker-error`,detail:e.message})}),t.on(`exit`,e=>{U(t,{kind:`worker-exited`,detail:`exit code ${e}`})}),t.unref(),I=t,t}catch(e){return V({kind:`spawn-failed`,detail:e instanceof Error?e.message:String(e)}),null}}function q(e){let t=K();if(!t)return Promise.reject(new F(`PNG worker is unavailable`));z+=1;let n=z;return new Promise((r,i)=>{B.set(n,{resolve:r,reject:i}),G();try{t.postMessage({...e,id:n})}catch(e){B.delete(n),G(),i(new F(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function J(e,t){try{return await q(e)}catch(e){if(e instanceof F)return await t();throw e}}async function Y(e,t){return X(await J({kind:`decode`,png:e,label:t},()=>{let n=M(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}))}function X(e){let t=new j.PNG({width:e.width,height:e.height});return t.data=P(e.data),t}async function Z(e){return P((await J({kind:`encode`,width:e.width,height:e.height,data:e.data},async()=>{let{encodePngPixels:t}=await import(`./png-encode.mjs`);return{kind:`encode`,png:t(e.data,e.width,e.height,4)}})).png)}async function Q(e,t){let{min:n,max:a}=i;if(!Number.isFinite(t)||t<n||t>a)throw new r(`INVALID_ARGS`,`Screenshot scale must be between ${n} and ${a}`);if(t===1)return;let s=await Y(await o.readFile(e),`screenshot`),c=Math.max(1,Math.round(s.width*t)),l=Math.max(1,Math.round(s.height*t));await o.writeFile(e,await Z($(s,c,l)))}async function ee(e,t,n){if(!Number.isInteger(t)||t<1||!Number.isInteger(n)||n<1)throw new r(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await Y(await o.readFile(e),`screenshot`);(i.width!==t||i.height!==n)&&await o.writeFile(e,await Z($(i,t,n)))}function $(e,t,n){let r=new j.PNG({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}export{$ as resizePngBox,ee as resizePngFile,Q as resizePngFileToScale};
1
+ import{r as e,t}from"./rolldown-runtime.mjs";import{s as n,t as r}from"./errors.mjs";import{t as i}from"./screenshot.mjs";import a,{promises as o}from"node:fs";import{Worker as s}from"node:worker_threads";import c from"node:path";import{fileURLToPath as l}from"node:url";var u=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)}}})),d=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}}})),f=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}})),p=t(((e,t)=>{let n=d(),r=f();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=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=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.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}},a.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}},a.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}},a.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}},a.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())}})),m=t(((t,n)=>{let r=e(`util`),i=u(),a=p(),o=n.exports=function(e){i.call(this);let t=[],n=this;this._filter=new a(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};r.inherits(o,i)})),h=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}})),g=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}})),_=t(((e,t)=>{let n=h(),r=g(),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()}})),v=t((e=>{let t=d(),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 i(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 a(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 o(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,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),y=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}})),b=t(((t,n)=>{let r=e(`util`),i=e(`zlib`),a=u(),o=m(),s=_(),c=v(),l=y(),d=n.exports=function(e){a.call(this),this._parser=new s(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()};r.inherits(d,a),d.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},d.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=i.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,i.Z_MIN_CHUNK);this._inflate=i.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 a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},d.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new o(this._bitmapInfo)},d.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},d.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},d.prototype._simpleTransparency=function(){this._metaData.alpha=!0},d.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},d.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},d.prototype._complete=function(e){if(this.errord)return;let t;try{let n=c.dataToBitMap(e,this._bitmapInfo);t=l(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),x=t(((e,t)=>{let n=h();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}})),S=t(((e,t)=>{let n=f();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 a(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 o(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 s(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 c(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 l(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 u(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 d(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:a,2:s,3:l,4:d},h={0:i,1:o,2:c,3:u,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}})),C=t(((t,n)=>{let r=h(),i=g(),a=x(),o=S(),s=e(`zlib`),c=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`)};c.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},c.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},c.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)},c.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},c.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)},c.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)},c.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},c.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),w=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=h(),o=C(),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)}})),T=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})),E=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`)}})),D=t((e=>{let t=E(),n=p();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)}})),O=t(((t,n)=>{let r=!0,i=e(`zlib`),a=T();i.deflateSync||(r=!1);let o=E(),s=D(),c=_(),l=v(),u=y();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 d(e){n=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.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:d,metadata:p,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(f.interlace)C=i.inflateSync(S);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.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,f);S=null;let T=l.dataToBitMap(w,f);w=null;let E=u(T,f,t.skipRescale);return f.data=E,f.gamma=_||0,f}})),k=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=h(),o=C();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)}})),A=t((e=>{let t=O(),n=k();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),j=t((t=>{let n=e(`util`),r=e(`stream`),i=b(),a=w(),o=A(),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)}}))();Buffer.from([137,80,78,71,13,10,26,10]);function M(e,t){try{return j.PNG.sync.read(e)}catch(e){throw new r(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}function N(e,t){try{let n=l(e),r=c.extname(n)||`.js`;return[c.join(c.dirname(n),`${t}${r}`),c.join(c.dirname(n),`internal`,`${t}${r}`)].find(e=>a.existsSync(e))??null}catch{return null}}function P(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var F=class extends Error{};let I=null,L;const R=new Set;let z=0;const B=new Map;function V(e){if(!L){L=e;for(let t of R)t(e)}}function H(e){let t=B.get(e.id);t&&(B.delete(e.id),G(),e.ok?t.resolve(e.result):t.reject(new r(n(e.error.code),e.error.message,e.error.details)))}function U(e,t){I===e&&(V(t),I=null,e.terminate().catch(()=>{}),W(new F(`PNG worker failed: ${t.kind}`)))}function W(e){let t=[...B.values()];B.clear();for(let n of t)n.reject(e)}function G(){I&&(B.size>0?I.ref():I.unref())}function K(){if(L)return null;if(I)return I;let e=N(import.meta.url,`png-worker`);if(!e)return V({kind:`entry-not-found`}),null;try{let t=new s(e,{env:{},execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,H),t.on(`error`,e=>{U(t,{kind:`worker-error`,detail:e.message})}),t.on(`exit`,e=>{U(t,{kind:`worker-exited`,detail:`exit code ${e}`})}),t.unref(),I=t,t}catch(e){return V({kind:`spawn-failed`,detail:e instanceof Error?e.message:String(e)}),null}}function q(e){let t=K();if(!t)return Promise.reject(new F(`PNG worker is unavailable`));z+=1;let n=z;return new Promise((r,i)=>{B.set(n,{resolve:r,reject:i}),G();try{t.postMessage({...e,id:n})}catch(e){B.delete(n),G(),i(new F(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function J(e,t){try{return await q(e)}catch(e){if(e instanceof F)return await t();throw e}}async function Y(e,t){return X(await J({kind:`decode`,png:e,label:t},()=>{let n=M(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}))}function X(e){let t=new j.PNG({width:e.width,height:e.height});return t.data=P(e.data),t}async function Z(e){return P((await J({kind:`encode`,width:e.width,height:e.height,data:e.data},async()=>{let{encodePngPixels:t}=await import(`./png-encode.mjs`);return{kind:`encode`,png:t(e.data,e.width,e.height,4)}})).png)}async function Q(e,t){let{min:n,max:a}=i;if(!Number.isFinite(t)||t<n||t>a)throw new r(`INVALID_ARGS`,`Screenshot scale must be between ${n} and ${a}`);if(t===1)return;let s=await Y(await o.readFile(e),`screenshot`),c=Math.max(1,Math.round(s.width*t)),l=Math.max(1,Math.round(s.height*t));await o.writeFile(e,await Z($(s,c,l)))}async function ee(e,t,n){if(!Number.isInteger(t)||t<1||!Number.isInteger(n)||n<1)throw new r(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await Y(await o.readFile(e),`screenshot`);(i.width!==t||i.height!==n)&&await o.writeFile(e,await Z($(i,t,n)))}function $(e,t,n){let r=new j.PNG({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}export{$ as resizePngBox,ee as resizePngFile,Q as resizePngFileToScale};
@@ -1 +1 @@
1
- import{t as e}from"./errors.mjs";import t from"node:net";import{setTimeout as n}from"node:timers/promises";function r(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const i=`https://backend.revyl.ai`,a=`agent-device`,o=3e4,s=12e4,c=[500,1500],l=new Set([`screenshot`,`health`,`device_info`,`hierarchy`]);function u(e){let t=A(e.backendUrl??`https://backend.revyl.ai`),r=e.fetch??fetch,i={Authorization:`Bearer ${e.apiKey}`,Accept:`application/json`,"User-Agent":`agent-device/${e.clientVersion}`,"X-Revyl-Client":a};async function o(e){let a=e.retry??e.method===`GET`?c.length+1:1;for(let o=1;;o+=1){let s=await d(t,r,i,e);if(!f(e,s)||o>=a||e.signal?.aborted){if(s instanceof Error)throw s;return s}await n(c[o-1]??1500,void 0,e.signal===void 0?{}:{signal:e.signal}).catch(()=>void 0)}}async function u(e){let t=await o(e);return h(e,t),x(e,t)}async function p(e){let t=await o(e);return h(e,t),t.body}function m(e,t,n){return{method:l.has(t)?`GET`:`POST`,path:`/api/v1/execution/device-proxy/${encodeURIComponent(e)}/${t}`,workerAction:!0,route:`session`,...n===void 0?{}:{signal:n}}}return Object.freeze({backendUrl:t,startDevice(e,t){return u({method:`POST`,path:`/api/v1/execution/start_device`,body:e,timeoutMs:s,...t===void 0?{}:{signal:t}})},getWorkerConnection(e,t){return u({method:`GET`,path:`/api/v1/execution/streaming/worker-connection/${encodeURIComponent(e)}`,route:`session`,retry:!1,...t===void 0?{}:{signal:t}})},getWorkerHealth(e,t){return u({...m(e,`health`,t),retry:!1})},async getWorkerHierarchy(e,t){return new TextDecoder().decode(await p({...m(e,`hierarchy`,t),retryServerError:!0}))},async captureWorkerScreenshot(e,t){return await p(m(e,`screenshot`,t))},async workerAction(e,t,n,r){let i=m(e,t,r),a=await u({...i,...n===void 0?{}:{body:n}});return _(i,a),a},async stopDeviceSession(e){let t=await u({method:`POST`,path:`/api/v1/execution/device/sessions/${encodeURIComponent(e)}/stop`,retry:!0,route:`session`});return g(`stop`,t),t},async verifyCredentials(e){await u({method:`GET`,path:`/api/v1/entity/users/get_user_uuid`,...e===void 0?{}:{signal:e}})}})}async function d(t,n,r,i){let s=AbortSignal.timeout(i.timeoutMs??o),c=i.signal?AbortSignal.any([i.signal,s]):s,l={...r};i.workerAction&&(l[`X-Revyl-Agent`]=a),i.body!==void 0&&(l[`Content-Type`]=`application/json`);try{let e=await n(new URL(i.path,t),{method:i.method,headers:l,body:i.body===void 0?void 0:JSON.stringify(i.body),redirect:`error`,signal:c});return Object.freeze({status:e.status,contentType:e.headers.get(`content-type`)??void 0,body:new Uint8Array(await e.arrayBuffer())})}catch(t){return i.signal?.aborted?p(i,t):s.aborted?m(i,t):new e(`COMMAND_FAILED`,`Revyl did not answer ${i.method} ${i.path}.`,{reason:`provider-unreachable`,path:i.path},t)}}function f(t,n){return n instanceof Error?n instanceof e&&n.details?.reason===`provider-unreachable`:t.retryServerError===!0&&n.status===500||T(t.route??`general`,n.status).retryable}function p(t,n){return new e(`COMMAND_FAILED`,`Revyl request ${t.method} ${t.path} was canceled.`,{reason:`request_canceled`,path:t.path},n)}function m(t,n){return new e(`COMMAND_FAILED`,`Revyl request ${t.method} ${t.path} got no response within ${t.timeoutMs??o} ms.`,{reason:`request_timeout`,path:t.path,hint:`Revyl may have carried out the request. Check the session before retrying it.`},n)}function h(t,n){if(n.status>=200&&n.status<300)return;let r=y(n),i=T(t.route??`general`,n.status),a={reason:i.reason,path:t.path,providerStatus:n.status};throw r!==void 0&&(a.providerDetail=r),i.uncertain&&(a.hint=`Revyl did not confirm ${t.method} ${t.path}; the action may have landed.`),new e(i.code,`Revyl request ${t.method} ${t.path} failed with HTTP ${n.status}${r===void 0?``:`: ${r}`}`,a)}function g(t,n){if(n.success===!0&&(n.request_accepted??!0)===!0)return;let r=typeof n.message==`string`?n.message:void 0;throw new e(`COMMAND_FAILED`,`Revyl did not stop the session${r===void 0?``:`: ${r}`}`,{reason:`provider-refused`,operation:t,...r===void 0?{}:{providerDetail:r},hint:`The Revyl session may still be rented. End it from Revyl if it stays listed.`})}function _(t,n){let r=typeof n.error==`string`&&n.error!==``?n.error:void 0;if((n.success??n.Success)===!1||r!==void 0)throw new e(`COMMAND_FAILED`,`Revyl rejected the ${v(t.path)} action${r===void 0?``:`: ${r}`}`,{reason:n.execution_uncertain===!0?`provider-unconfirmed`:`provider-refused`,path:t.path,...r===void 0?{}:{providerDetail:r}})}function v(e){return e.slice(e.lastIndexOf(`/`)+1)}function y(e){let t=b(e);if(t!==void 0)for(let e of[t.detail,t.message,t.error]){if(typeof e==`string`&&e.length>0)return e.slice(0,500);if(r(e)&&typeof e.error==`string`&&e.error.length>0)return e.error.slice(0,500)}}function b(e){try{let t=JSON.parse(new TextDecoder().decode(e.body));return r(t)?t:void 0}catch{return}}function x(t,n){try{return JSON.parse(new TextDecoder().decode(n.body))}catch(r){throw new e(`COMMAND_FAILED`,`Revyl returned a response to ${t.method} ${t.path} that is not JSON (HTTP ${n.status}).`,{reason:`provider-response-invalid`,path:t.path},r)}}const S={code:`COMMAND_FAILED`,reason:`provider-request-failed`,uncertain:!1,retryable:!1},C={code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},w={400:S,401:{code:`UNAUTHORIZED`,reason:`provider-auth-rejected`,uncertain:!1,retryable:!1},403:{code:`UNAUTHORIZED`,reason:`provider-auth-rejected`,uncertain:!1,retryable:!1},404:{code:`SESSION_NOT_FOUND`,reason:`provider-session-gone`,uncertain:!1,retryable:!1},408:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},409:{code:`COMMAND_FAILED`,reason:`provider-conflict`,uncertain:!1,retryable:!1},410:{code:`SESSION_NOT_FOUND`,reason:`provider-session-gone`,uncertain:!1,retryable:!1},500:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},502:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0},503:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0},504:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0}};function T(e,t){let n=w[t]??(t>=500?C:S);return n.reason===`provider-session-gone`&&e!==`session`?S:n}function E(t){let n=t instanceof e?t.details?.providerStatus:void 0;return typeof n==`number`&&!T(`general`,n).uncertain}function D(t){return t instanceof e&&t.details?.reason===`provider-session-gone`}const O=new t.BlockList;O.addSubnet(`127.0.0.0`,8,`ipv4`),O.addAddress(`::1`,`ipv6`),O.addSubnet(`::ffff:127.0.0.0`,104,`ipv6`);function k(e){if(e===`localhost`)return!0;let n=e.startsWith(`[`)?e.slice(1,-1):e,r=t.isIP(n);return r!==0&&O.check(n,r===6?`ipv6`:`ipv4`)}function A(t){let n;try{n=new URL(t)}catch{throw new e(`INVALID_ARGS`,`REVYL_API_URL is not a valid URL.`,{reason:`invalid_provider_url`})}let r=k(n.hostname);if(n.protocol!==`https:`&&!(r&&n.protocol===`http:`))throw new e(`INVALID_ARGS`,`REVYL_API_URL must use HTTPS; plain HTTP is allowed only on loopback.`,{reason:`invalid_provider_url`,hint:`Example: https://backend.revyl.ai`});if(n.username||n.password||n.search||n.hash)throw new e(`INVALID_ARGS`,`REVYL_API_URL must be an origin without credentials, query, or fragment.`,{reason:`invalid_provider_url`});return n.origin}export{A as a,D as i,s as n,E as o,u as r,i as t};
1
+ import{t as e}from"./errors.mjs";import t from"node:fs";import n from"node:net";import{Readable as r}from"node:stream";import{setTimeout as i}from"node:timers/promises";function a(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const o=`https://backend.revyl.ai`,s=`agent-device`,c=3e4,l=12e4,u=[500,1500],d=new Set([`screenshot`,`health`,`device_info`,`hierarchy`]);function f(n){let a=M(n.backendUrl??`https://backend.revyl.ai`),o=n.fetch??fetch,c={Authorization:`Bearer ${n.apiKey}`,Accept:`application/json`,"User-Agent":`agent-device/${n.clientVersion}`,"X-Revyl-Client":s};async function f(e){let t=e.retry??e.method===`GET`?u.length+1:1;for(let n=1;;n+=1){let r=await p(a,o,c,e);if(!m(e,r)||n>=t||e.signal?.aborted){if(r instanceof Error)throw r;return r}await i(u[n-1]??1500,void 0,e.signal===void 0?{}:{signal:e.signal}).catch(()=>void 0)}}async function h(e){let t=await f(e);return _(e,t),C(e,t)}async function g(e){let t=await f(e);return _(e,t),t.body}function b(e,t,n){return{method:d.has(t)?`GET`:`POST`,path:`/api/v1/execution/device-proxy/${encodeURIComponent(e)}/${t}`,workerAction:!0,route:`session`,...n===void 0?{}:{signal:n}}}return Object.freeze({backendUrl:a,startDevice(e,t){return h({method:`POST`,path:`/api/v1/execution/start_device`,body:e,timeoutMs:l,...t===void 0?{}:{signal:t}})},getWorkerConnection(e,t){return h({method:`GET`,path:`/api/v1/execution/streaming/worker-connection/${encodeURIComponent(e)}`,route:`session`,retry:!1,...t===void 0?{}:{signal:t}})},getWorkerHealth(e,t){return h({...b(e,`health`,t),retry:!1})},async getWorkerHierarchy(e,t){return new TextDecoder().decode(await g({...b(e,`hierarchy`,t),retryServerError:!0}))},async captureWorkerScreenshot(e,t){return await g(b(e,`screenshot`,t))},async workerAction(e,t,n,r){let i=b(e,t,r),a=await h({...i,...n===void 0?{}:{body:n}});return y(i,a),a},async stopDeviceSession(e){let t=await h({method:`POST`,path:`/api/v1/execution/device/sessions/${encodeURIComponent(e)}/stop`,retry:!0,route:`session`});return v(`stop`,t),t},createSessionArtifactUpload(e,t,n,r){return h({method:`POST`,path:`/api/v1/execution/device-sessions/${encodeURIComponent(e)}/artifacts/upload-url`,body:{file_size:t,content_type:n},route:`session`,...r===void 0?{}:{signal:r}})},async uploadSessionArtifact(n,i,a,s){let c={method:`PUT`,headers:{"Content-Type":a,"Content-Length":String(i.size)},body:r.toWeb(t.createReadStream(i.filePath)),duplex:`half`,redirect:`error`,...s===void 0?{}:{signal:s}},l;try{l=await o(n,c)}catch(t){throw new e(`COMMAND_FAILED`,`Revyl storage did not accept the app upload.`,{reason:`provider-unreachable`},t)}if(!l.ok)throw new e(`COMMAND_FAILED`,`Revyl storage refused the app upload with HTTP ${l.status}.`,{reason:`provider-refused`,status:l.status})},startInstall(e,t,n){return h({...b(e,`install_async`,n),body:t})},getInstallStatus(e,t,n){return h({...b(e,`install_status/${encodeURIComponent(t)}`,n),method:`GET`})},async verifyCredentials(e){await h({method:`GET`,path:`/api/v1/entity/users/get_user_uuid`,...e===void 0?{}:{signal:e}})}})}async function p(t,n,r,i){let a=AbortSignal.timeout(i.timeoutMs??c),o=i.signal?AbortSignal.any([i.signal,a]):a,l={...r};i.workerAction&&(l[`X-Revyl-Agent`]=s),i.body!==void 0&&(l[`Content-Type`]=`application/json`);try{let e=await n(new URL(i.path,t),{method:i.method,headers:l,body:i.body===void 0?void 0:JSON.stringify(i.body),redirect:`error`,signal:o});return Object.freeze({status:e.status,contentType:e.headers.get(`content-type`)??void 0,body:new Uint8Array(await e.arrayBuffer())})}catch(t){return i.signal?.aborted?h(i,t):a.aborted?g(i,t):new e(`COMMAND_FAILED`,`Revyl did not answer ${i.method} ${i.path}.`,{reason:`provider-unreachable`,path:i.path},t)}}function m(t,n){return n instanceof Error?n instanceof e&&n.details?.reason===`provider-unreachable`:t.retryServerError===!0&&n.status===500||D(t.route??`general`,n.status).retryable}function h(t,n){return new e(`COMMAND_FAILED`,`Revyl request ${t.method} ${t.path} was canceled.`,{reason:`request_canceled`,path:t.path},n)}function g(t,n){return new e(`COMMAND_FAILED`,`Revyl request ${t.method} ${t.path} got no response within ${t.timeoutMs??c} ms.`,{reason:`request_timeout`,path:t.path,hint:`Revyl may have carried out the request. Check the session before retrying it.`},n)}function _(t,n){if(n.status>=200&&n.status<300)return;let r=x(n),i=D(t.route??`general`,n.status),a={reason:i.reason,path:t.path,providerStatus:n.status};throw r!==void 0&&(a.providerDetail=r),i.uncertain&&(a.hint=`Revyl did not confirm ${t.method} ${t.path}; the action may have landed.`),new e(i.code,`Revyl request ${t.method} ${t.path} failed with HTTP ${n.status}${r===void 0?``:`: ${r}`}`,a)}function v(t,n){if(n.success===!0&&(n.request_accepted??!0)===!0)return;let r=typeof n.message==`string`?n.message:void 0;throw new e(`COMMAND_FAILED`,`Revyl did not stop the session${r===void 0?``:`: ${r}`}`,{reason:`provider-refused`,operation:t,...r===void 0?{}:{providerDetail:r},hint:`The Revyl session may still be rented. End it from Revyl if it stays listed.`})}function y(t,n){let r=typeof n.error==`string`&&n.error!==``?n.error:void 0;if((n.success??n.Success)===!1||r!==void 0)throw new e(`COMMAND_FAILED`,`Revyl rejected the ${b(t.path)} action${r===void 0?``:`: ${r}`}`,{reason:n.execution_uncertain===!0?`provider-unconfirmed`:`provider-refused`,path:t.path,...r===void 0?{}:{providerDetail:r}})}function b(e){return e.slice(e.lastIndexOf(`/`)+1)}function x(e){let t=S(e);if(t!==void 0)for(let e of[t.detail,t.message,t.error]){if(typeof e==`string`&&e.length>0)return e.slice(0,500);if(a(e)&&typeof e.error==`string`&&e.error.length>0)return e.error.slice(0,500)}}function S(e){try{let t=JSON.parse(new TextDecoder().decode(e.body));return a(t)?t:void 0}catch{return}}function C(t,n){try{return JSON.parse(new TextDecoder().decode(n.body))}catch(r){throw new e(`COMMAND_FAILED`,`Revyl returned a response to ${t.method} ${t.path} that is not JSON (HTTP ${n.status}).`,{reason:`provider-response-invalid`,path:t.path},r)}}const w={code:`COMMAND_FAILED`,reason:`provider-request-failed`,uncertain:!1,retryable:!1},T={code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},E={400:w,401:{code:`UNAUTHORIZED`,reason:`provider-auth-rejected`,uncertain:!1,retryable:!1},403:{code:`UNAUTHORIZED`,reason:`provider-auth-rejected`,uncertain:!1,retryable:!1},404:{code:`SESSION_NOT_FOUND`,reason:`provider-session-gone`,uncertain:!1,retryable:!1},408:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},409:{code:`COMMAND_FAILED`,reason:`provider-conflict`,uncertain:!1,retryable:!1},410:{code:`SESSION_NOT_FOUND`,reason:`provider-session-gone`,uncertain:!1,retryable:!1},500:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!1},502:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0},503:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0},504:{code:`COMMAND_FAILED`,reason:`provider-unconfirmed`,uncertain:!0,retryable:!0}};function D(e,t){let n=E[t]??(t>=500?T:w);return n.reason===`provider-session-gone`&&e!==`session`?w:n}function O(t){let n=t instanceof e?t.details?.providerStatus:void 0;return typeof n==`number`&&!D(`general`,n).uncertain}function k(t){return t instanceof e&&t.details?.reason===`provider-session-gone`}const A=new n.BlockList;A.addSubnet(`127.0.0.0`,8,`ipv4`),A.addAddress(`::1`,`ipv6`),A.addSubnet(`::ffff:127.0.0.0`,104,`ipv6`);function j(e){if(e===`localhost`)return!0;let t=e.startsWith(`[`)?e.slice(1,-1):e,r=n.isIP(t);return r!==0&&A.check(t,r===6?`ipv6`:`ipv4`)}function M(t){let n;try{n=new URL(t)}catch{throw new e(`INVALID_ARGS`,`REVYL_API_URL is not a valid URL.`,{reason:`invalid_provider_url`})}let r=j(n.hostname);if(n.protocol!==`https:`&&!(r&&n.protocol===`http:`))throw new e(`INVALID_ARGS`,`REVYL_API_URL must use HTTPS; plain HTTP is allowed only on loopback.`,{reason:`invalid_provider_url`,hint:`Example: https://backend.revyl.ai`});if(n.username||n.password||n.search||n.hash)throw new e(`INVALID_ARGS`,`REVYL_API_URL must be an origin without credentials, query, or fragment.`,{reason:`invalid_provider_url`});return n.origin}export{M as a,k as i,l as n,O as o,f as r,o as t};
package/dist/runtime.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,o as t,r as n,t as r}from"./device.mjs";import{a as i,i as a,r as o,t as s}from"./errors.mjs";import{i as c,n as l,r as u}from"./snapshot-visibility.mjs";import{r as d}from"./device2.mjs";import{a as f,i as p,n as m,o as h,r as g}from"./revyl-client.mjs";import{n as ee,r as te,t as ne}from"./open-target.mjs";import _ from"node:fs";import v from"node:path";import{createHash as re,randomUUID as y}from"node:crypto";import{setTimeout as b}from"node:timers/promises";function x(e){let t=`${re(`sha256`).update(`agent-device:revyl:session:v1:${e}`).digest(`hex`).slice(0,32)}`;return[t.slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,`${(Number.parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}`,t.slice(20,32)].join(`-`)}const S=24e4,ie=m+S+1e4,ae=new Set([503,409]);async function oe(e,t,r){let i=x(t.leaseId);if(r.signal?.aborted)return{status:`failed`,error:C(r)};let a;try{a=await se(e,r,i)}catch(e){return{status:`failed`,error:e,...T(e)?{rented:{sessionId:i}}:{}}}let o=typeof a.workflow_run_id==`string`?a.workflow_run_id:void 0,c=typeof a.session_id==`string`?a.session_id:void 0;if(o&&c&&c!==i)return{status:`failed`,rented:{runId:o,sessionId:c},error:new s(`COMMAND_FAILED`,`Revyl started the device as session ${c} instead of ${i}.`,{reason:`provider-session-identity-mismatch`,runId:o,providerSessionId:c,hint:`Retry the command; agent-device ends a Revyl session by the identity it issued.`})};if(!o)return{status:`failed`,rented:{sessionId:c??i},error:new s(`COMMAND_FAILED`,`Revyl did not start a ${r.platform} device: ${a.error??a.message??`no workflow run was returned`}`,{reason:`provider-start-refused`,platform:r.platform,...a.trace_id===void 0?{}:{traceId:a.trace_id}})};if(r.onRented?.({runId:o,sessionId:i}),r.signal?.aborted)return{status:`failed`,rented:{runId:o,sessionId:i},error:C(r)};let l=le(r);try{let a=await ue(e,o,l,{...r,sessionId:i});return{status:`ready`,session:{platform:r.platform,runId:o,sessionId:i,screen:me(a),dragDuration:a.supports_explicit_drag_duration===!0,device:n(r.platform,t,o),client:e,lease:t,launchedApp:{}}}}catch(e){return{status:`failed`,error:e,rented:{runId:o,sessionId:i}}}}async function se(e,t,n){if(t.signal?.aborted)throw C(t);let r={platform:t.platform,is_simulation:!0,session_id:n,idle_timeout_seconds:1800,...t.appUrl===void 0?{}:{app_url:t.appUrl},...t.deviceModel===void 0?{}:{device_model:t.deviceModel},...t.osVersion===void 0?{}:{os_version:t.osVersion}};return await e.startDevice(r)}function C(e){return new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e.platform},e.signal?.reason)}function w(e,t,n,r){let i=`agent-device stops Revyl session ${r} once its start answers; end it from Revyl if it stays listed.`;return t.signal?.aborted?new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e,providerSessionId:r,hint:i},t.signal.reason):new s(`COMMAND_FAILED`,`Revyl did not report a ready device within ${n} ms.`,{reason:`provider-not-ready`,timeoutMs:n,providerSessionId:r,...t.deadline===void 0?{}:{deadline:t.deadline},hint:`Retry the command; Revyl may have had no device of that model available. ${i}`})}function T(e){return!h(e)}function ce(e,t={},n){let r=e.map(e=>e.sessionId).join(`, `),i=e.length===1?e[0]:void 0;return new s(`COMMAND_FAILED`,`Revyl did not release session${i?``:`s`} ${r}.`,{reason:`provider-cleanup-pending`,...t,providerSessionIds:e.map(e=>e.sessionId),causes:e.map(e=>e.failure),...i?{providerSessionId:i.sessionId,...i.runId===void 0?{}:{runId:i.runId},cause:i.failure}:{},hint:`End the Revyl session${i?``:`s`} ${r}; each device stays rented and billed until it is.`},n)}function le(e){let t=e.deadline===void 0?S:Math.min(S,e.deadline-Date.now());return{at:Date.now()+t,budgetMs:Math.max(0,t)}}async function ue(e,t,n,r){for(await fe(e,t,n,r);;){O(n,r);let i=await E(e,t,n,r);if(O(n,r),i.device_connected===!0)return i;await A(n,r.signal)}}async function E(e,t,n,r){try{return await D(()=>e.getWorkerHealth(t,k(n,r)),n,r)}catch(e){if(!de(e))throw e;return{}}}async function D(e,t,n){try{return await e()}catch(e){throw O(t,n),e}}function de(e){return e instanceof s&&typeof e.details?.providerStatus==`number`&&ae.has(e.details.providerStatus)}async function fe(e,t,n,r){for(;;){O(n,r);let i=await D(()=>e.getWorkerConnection(t,k(n,r)),n,r);if(O(n,r),i.status===`ready`&&i.worker_ws_url)return;if(i.status===`cancelled`||i.status===`stopped`||i.status===`failed`)throw new s(`COMMAND_FAILED`,`Revyl did not start the ${r.platform} device: ${i.status}${i.message===null||i.message===void 0?``:` (${i.message})`}`,{reason:`provider-start-failed`,runId:t,status:i.status});await A(n,r.signal)}}function O(e,t){if(!(Date.now()<e.at))throw w(t.platform,t,e.budgetMs,t.sessionId)}function k(e,t){let n=AbortSignal.timeout(Math.max(0,e.at-Date.now()));return t.signal===void 0?n:AbortSignal.any([t.signal,n])}async function A(e,t){await b(Math.min(2e3,Math.max(0,e.at-Date.now())),void 0,t===void 0?{}:{signal:t}).catch(()=>void 0)}async function pe(e,t){await e.stopDeviceSession(t)}function me(e){let{screen_width:t,screen_height:n}=e;if(!(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0))return{width:t,height:n}}var j=class{lease;generation;phase=`starting`;request;answerBy;abandon=new AbortController;start=Promise.resolve({status:`failed`,error:void 0});answered=!1;answer;markAnswered=()=>void 0;session=void 0;rentals=new Map;latest=void 0;unnamed=!1;waiters=new Set;followUpQueued=!1;ending=void 0;constructor(e,t,n,r){this.lease=e,this.generation=t,this.request=n,this.answerBy=r,this.answer=new Promise(e=>{this.markAnswered=e})}};function he(e){let t=new ge(e);return Object.freeze({live:e=>t.live(e),allocate:async(e,n,r)=>await t.allocate(e,n,r),release:async e=>await t.release(e),recover:async e=>await t.recover(e),shutdown:async()=>await t.shutdown()})}var ge=class{entries=new Map;shuttingDown=!1;generations=0;driver;constructor(e){this.driver=e}live(e){let t=this.entries.get(e);return t?.phase===`ready`?t.session:void 0}isCurrent(e){return this.entries.get(e.lease.leaseId)?.generation===e.generation}refusal(e,t,n){return this.shuttingDown?this.driver.shuttingDown(e):t&&(t.phase===`ending`||!this.isCurrent(t))?this.driver.releasing(e):n()}async allocate(e,t,n={}){let r=this.entries.get(e.leaseId);if(this.shuttingDown||r?.phase===`ending`)throw this.refusal(e,r,()=>0);r?.request!==void 0&&n.requireJoinable?.(r.request);let i=N(n),a=Date.now()+this.driver.startTimeoutMs,o=Math.min(i.deadline??a,a);if(!r&&P(i,o))throw this.driver.gaveUp(e,i,0,void 0);let s=r??this.rent(e,t,i,a),c=Math.max(0,o-Date.now()),l=await this.join(s,i,o);return this.deliver(s,l,i,o,c)}deliver(e,t,n,r,i){if(t.status===`failed`)throw this.refusal(e.lease,void 0,()=>t.error);let a=this.refusal(e.lease,e,()=>P(n,r)?this.driver.gaveUp(e.lease,n,i,e.latest):void 0);if(a!==void 0)throw a;return t.session}async release(e){let t=this.entries.get(e);if(!t)return;let n=await this.teardown(t);if(n.status===`pending`)throw this.pending(t,n,{route:`release`,leaseId:e});return n.status===`stopped`?{handle:n.handle,session:n.session}:void 0}async recover(e){let t=e.leaseId,n=this.entries.get(t);if(n===void 0){if(this.shuttingDown)throw this.driver.shuttingDown(e);n=this.recovering(e)}let r=await this.teardown(n);if(r.status===`pending`)throw this.pending(n,r,{route:`recover`,leaseId:t})}async shutdown(){this.shuttingDown=!0;let e=[],t=[...this.entries.values()];if((await Promise.all(t.map(async e=>await this.teardown(e)))).forEach((n,r)=>{if(n.status!==`pending`)return;let i=t[r].lease.leaseId;for(let t of n.owed)e.push({leaseId:i,...t})}),e.length>0)throw this.driver.cleanupPending(e,{route:`shutdown`})}rent(e,t,n,r){let i=new j(e,this.generations+=1,t,r);return i.start=this.runStart(i,t,n),this.entries.set(e.leaseId,i),i}recovering(e){let t=new j(e,this.generations+=1,void 0,Date.now());return t.answered=!0,t.markAnswered(),t.unnamed=!0,t.phase=`ending`,this.entries.set(e.leaseId,t),t}async runStart(e,t,n){let r=Date.now(),i=await this.callStart(e,t);if(_e(e,i,this.driver.handleKey),i.status===`ready`&&(e.session=i.session,e.phase===`starting`&&this.isCurrent(e)&&F(e)))return e.phase=`ready`,{status:`ready`,session:i.session};let a;try{a=this.startFailure(e,i,n,r)}catch(e){a=e}return await this.endFailedStart(e,a)}async callStart(e,t){try{return await this.driver.start(e.lease,t,{signal:e.abandon.signal,deadline:e.answerBy,rented:t=>{e.answered||(M(e,t,this.driver.handleKey(t)),e.phase===`ending`&&this.followUp(e))}})}catch(e){return{status:`rejected`,error:e}}}startFailure(e,t,n,r){let i=Math.max(0,e.answerBy-r);return this.refusal(e.lease,e,()=>t.status===`ready`?this.driver.gaveUp(e.lease,n,i,t.handle):t.error)}async endFailedStart(e,t){if(e.phase===`ending`)return this.followUp(e),{status:`failed`,error:t};let n=await this.teardown(e);if(n.status!==`pending`)return{status:`failed`,error:t};let r=e.lease.leaseId;return{status:`failed`,error:this.driver.cleanupPending(n.owed.map(e=>({leaseId:r,...e})),{route:`start`,leaseId:r},t)}}async join(e,t,n){if(e.phase===`ready`)return{status:`ready`,session:e.session};let r=Math.max(0,n-Date.now()),i=()=>{try{return this.refusal(e.lease,e,()=>this.driver.gaveUp(e.lease,t,r,e.latest))}catch(e){return e}},a=new AbortController,o=setTimeout(()=>a.abort(),r),s=t.signal?[t.signal,a.signal]:[a.signal],c={deadline:n,signal:t.signal},l=()=>void 0;try{if(e.waiters.add(c),s.some(e=>e.aborted))throw i();let t=new Promise((t,n)=>{l=()=>{let t=i();e.waiters.delete(c),this.abandonIfUnwanted(e),n(t)};for(let e of s)e.addEventListener(`abort`,l,{once:!0})});return await Promise.race([e.start,t])}finally{e.waiters.delete(c),this.abandonIfUnwanted(e),clearTimeout(o);for(let e of s)e.removeEventListener(`abort`,l)}}abandonIfUnwanted(e){e.answered||e.phase===`ending`||F(e)||this.teardown(e).catch(()=>void 0)}teardown(e){if(e.phase=`ending`,e.answered||e.abandon.abort(),e.ending)return e.ending;let t=this.runTeardown(e).finally(()=>{e.ending===t&&(e.ending=void 0)});return e.ending=t,t}async runTeardown(e){let t=new Map;for(;;){await this.untilAnswered(e);let n=await this.nameRental(e);if(n!==void 0)return n;let r=await this.stopRentals(e,t);if(r!==`progress`){if(r.length>0)return{status:`pending`,owed:r};if(!(e.unnamed||[...e.rentals.values()].some(e=>!e.stopped)))return this.finishTeardown(e)}}}async stopRentals(e,t){for(let n of e.rentals.values()){if(n.stopped)continue;if(t.get(n)!==void 0){if(n.stopping!==void 0)break;continue}let e=await this.stop(n);if(e===void 0)return`progress`;if(t.set(n,{handle:n.handle,cause:e.cause}),n.stopping!==void 0)break}return[...e.rentals.values()].filter(e=>!e.stopped).map(e=>t.get(e)??{handle:e.handle,cause:Error(`The stop waits for an earlier stop of this lease that is still in flight.`)})}async nameRental(e){if(e.unnamed)try{let t=await this.driver.findByLease(e.lease);M(e,t,this.driver.handleKey(t)),e.unnamed=!1;return}catch(e){return{status:`pending`,owed:[{handle:void 0,cause:e}]}}}finishTeardown(e){let t=e.latest;return e.answered?(this.isCurrent(e)&&this.entries.delete(e.lease.leaseId),t===void 0?{status:`nothing-rented`}:{status:`stopped`,handle:t,session:e.session}):{status:`pending`,owed:[{handle:t,cause:Error(`The provider start did not answer within its start timeout.`)}]}}followUp(e){let t=e.ending;if(t===void 0){this.teardown(e).catch(()=>void 0);return}e.followUpQueued||(e.followUpQueued=!0,t.then(async()=>(e.followUpQueued=!1,await this.teardown(e))).catch(()=>void 0))}async untilAnswered(e){if(e.answered)return;let t,n=new Promise(n=>{t=setTimeout(n,Math.max(0,e.answerBy-Date.now()))});try{await Promise.race([e.answer,n])}finally{clearTimeout(t)}}async stop(e){e.stopping??=this.stopHandle(e.handle).then(t=>(t===void 0&&(e.stopped=!0),e.stopping=void 0,t));let t=e.stopping,n=this.driver.stopTimeoutMs;if(n===void 0)return await t;let r,i=new Promise(e=>{r=setTimeout(()=>e({cause:Error(`The provider stop did not answer within ${n} ms.`)}),n)});try{return await Promise.race([t,i])}finally{clearTimeout(r)}}async stopHandle(e){try{await this.driver.stop(e);return}catch(e){return{cause:e}}}pending(e,t,n){return this.driver.cleanupPending(t.owed.map(t=>({leaseId:e.lease.leaseId,...t})),n)}};function _e(e,t,n){switch(t.status){case`ready`:M(e,t.handle,n(t.handle));break;case`failed`:t.rented!==void 0&&M(e,t.rented,n(t.rented));break;case`rejected`:e.rentals.size===0&&(e.unnamed=!0)}e.answered=!0,e.markAnswered()}function M(e,t,n){e.rentals.has(n)||e.rentals.set(n,{handle:t,stopped:!1,stopping:void 0}),e.latest=t}function N(e){return{...e.signal===void 0?{}:{signal:e.signal},...e.deadline===void 0?{}:{deadline:e.deadline}}}function P(e,t){return e.signal?.aborted===!0||Date.now()>=t}function F(e){if(e.phase===`ending`)return!1;let t=Date.now();for(let n of e.waiters)if(!n.signal?.aborted&&t<n.deadline)return!0;return!1}new Map([...Object.entries({ios:`ios-instance`,android:`android-instance`,harmonyos:`harmonyos-instance`}).flatMap(([e,t])=>t===void 0?[]:[[t,e]]),[`macos-app`,`macos`]]);function I(e,t={message:e=>`Invalid value: ${e}`}){let n=new Set(e),r=t.normalize??(e=>e);return{is:e=>typeof e==`string`&&n.has(e),parse:e=>{let i=r(e??``);if(n.has(i))return i;throw new s(`INVALID_ARGS`,t.message(e??``))}}}I([`up`,`down`,`left`,`right`],{message:e=>`Unknown direction: ${e}`});function ve(e){let t=e.direction,n=t===`up`||t===`down`,r=n?e.referenceHeight:e.referenceWidth,i=n?e.referenceWidth:e.referenceHeight,a=xe(e.amount),o=e.pixels===void 0?Math.round(r*a):Se(e.pixels),s=L(r),c=Math.max(1,r-s*2),l=Math.max(1,Math.min(o,c)),u=Math.round(l/2),d=Math.round(r/2),f={axisStart:d-u,axisEnd:d+u,cross:Math.round(i/2)},p=L(i),m=e.container?be(f,e.container,n,{axis:{min:s,max:r-s},cross:{min:p,max:i-p},crossFrame:{min:0,max:i}}):f,h=m.axisEnd-m.axisStart,g=h<l;return{direction:t,...ye(t,m),referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:g?h:l,...g?{requestedPixels:l}:{}}}function ye(e,t){let n=e===`up`||e===`down`,r=n?{x:t.cross,y:t.axisStart}:{x:t.axisStart,y:t.cross},i=n?{x:t.cross,y:t.axisEnd}:{x:t.axisEnd,y:t.cross},[a,o]=e===`up`||e===`left`?[r,i]:[i,r];return{x1:a.x,y1:a.y,x2:o.x,y2:o.y}}function L(e){return Math.max(1,Math.round(e*.1))}function be(e,t,n,r){let i=R(n?t.y:t.x,n?t.height:t.width,r.axis),a=n?t.x:t.y,o=n?t.width:t.height,s=R(a,o,r.cross)??R(a,o,r.crossFrame);if(!i||!s)return e;let c=e.cross>=s.min&&e.cross<=s.max?e.cross:Math.round((s.min+s.max)/2);if(e.axisEnd-e.axisStart>=i.max-i.min)return{axisStart:i.min,axisEnd:i.max,cross:c};let l=e.axisStart<i.min?i.min-e.axisStart:Math.min(0,i.max-e.axisEnd);return{axisStart:e.axisStart+l,axisEnd:e.axisEnd+l,cross:c}}function R(e,t,n){let r=Math.max(n.min,Math.ceil(e)+8),i=Math.min(n.max,Math.floor(e+t)-1-8);return i>r?{min:r,max:i}:void 0}function xe(e){if(e===void 0)return .6;if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll amount must be a positive number`);return e}function Se(e){if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(e))}Object.freeze({reason:`scroll_keyboard_occludes_surface`,hint:"The on-screen keyboard covers the surface this scroll would swipe, so it cannot reach it. Run `keyboard dismiss` and retry, accepting that it drops focus (re-tap the field to keep typing), or scroll before focusing the field."});const z=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function Ce(e){let t=B(e.packageName),n=(e.resourceId??``).toLowerCase(),r=B(e.activeInputMethodPackage);if(t&&r&&t===r)return{inputMethodOwned:!0,source:`active-input-method`};if(r&&n.startsWith(`${r}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(t&&z.has(t))return{inputMethodOwned:!0,source:`known-ime-package`};for(let e of z)if(n.startsWith(`${e}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function we(e){return Ce(e).inputMethodOwned}function Te(e){return we({packageName:e.bundleId,resourceId:e.identifier})}function B(e){return(e??``).trim().toLowerCase()||void 0}const Ee=new Set([`UIKeyboardDockItemButton`,`UIAccessibilityElementKBKey`]),De=new Set([`TUIPredictionViewCell`]),Oe=new Set([`UIKeyboardLayoutStar`,`TUIPredictionView`]),V=new Set([`_UIRemoteKeyboardPlaceholderView`,`TUISystemInputAssistantView`,`TUISystemInputAssistantPageView`]);function H(e,t){return e.role!==void 0&&t.has(e.role)}Object.freeze({reason:`tap_keyboard_occludes_target`,hint:"The visible keyboard covers this target, so the tap would land on a key instead of on it. End editing first: tap the app's own Done/Cancel/close control, or run `keyboard enter` when submitting is what you want (`keyboard dismiss` works only when the keyboard exposes its own dismiss key). This reads the snapshot the command measured against, so if the keyboard closed since it was taken, run `snapshot -i` and retry."});const ke=new Set([`keyboard`,`key`]);function U(e){return ke.has(l(e.type??``))||Te(e)}function W(e){return U(e)||Ee.has(e.role??``)}function G(e){return U(e)||H(e,Oe)}function Ae(e,t){if(W(e)||H(e,De)||H(e,V)||G(e))return!0;let n=new Set,r=e.parentIndex;for(;typeof r==`number`&&!n.has(r);){n.add(r);let e=t.get(r);if(!e)return!1;if(H(e,V)||G(e))return!0;r=e.parentIndex}return!1}function K(e){return e!==null&&u(e)}function q(e){return e.flatMap(e=>u(e.rect)?[e.rect]:[])}function je(e,t){let n=new Map(e.map(e=>[e.index,e.parentIndex])),r=new Set(t.map(e=>e.index)),i=new Set;for(let e of t)for(let t of Me(n,r,e.index))i.add(t);return i}function Me(e,t,n){let r=[],i=new Set,a=e.get(n);for(;typeof a==`number`&&!i.has(a);)i.add(a),t.has(a)&&r.push(a),a=e.get(a);return r}function Ne(e){let t=e.map(e=>[e.x,e.x+e.width]).sort((e,t)=>e[0]-t[0]),n=t[0]?.[1]??0;for(let[e,r]of t){if(e-n>2)return!1;n=Math.max(n,r)}return!0}function Pe(e){let t=Math.min(...e.anchorRects.map(e=>e.y)),n=Math.min(...e.anchorRects.map(e=>e.x)),r=Math.max(...e.anchorRects.map(e=>e.x+e.width)),i=e.viewport.y+e.viewport.height;return e.reportedBottom<i-80||r-n<=e.reportedBottom-t?null:{x:n,y:t,width:r-n,height:i-t}}function Fe(e){let t=q(e.anchorNodes.filter(t=>!e.planeIndices.has(t.index)));return Ne(t.length>0?t:e.anchorRects)}function Ie(e,t){let n=e.filter(U),r=q(n);if(r.length===0||!K(t))return null;let i=e.filter(W),a=q(i);if(a.length===0)return null;let o=Pe({anchorRects:r,reportedBottom:Math.max(...a.map(e=>e.y+e.height)),viewport:t});return!o||!u(o)||!Fe({anchorNodes:n,anchorRects:r,planeIndices:je(e,i)})?null:o}function J(e){let t=new Map(e.nodes.map(e=>[e.index,e]));return{nodes:e.nodes.map(e=>({...e,keyboardOwned:Ae(e,t)})),keyboard:Le(e)}}function Le(e){let t=Ie(e.nodes,e.viewport);return t?{kind:`derived`,derivation:`docked-tree`,frame:t,treeBound:!0}:K(e.viewport)&&e.nodes.some(U)?{kind:`tree-rejected`,derivation:`docked-tree`,...typeof e.visibility==`boolean`?{visible:e.visibility}:{}}:typeof e.visibility==`boolean`?{kind:`visibility-only`,visible:e.visibility}:{kind:`unmeasurable`,reason:e.nodes.some(U)?`keyboard-viewport-unavailable`:e.visibility===`failed`?`keyboard-visibility-probe-failed`:e.visibility===`unsupported`?`keyboard-visibility-probe-unsupported`:`keyboard-not-observed`}}function Re(e){return{readHierarchy:t=>e.client.getWorkerHierarchy(e.runId,t),viewport:()=>e.screen===void 0?void 0:c({x:0,y:0,...e.screen})}}async function ze(e,t,n){let r=await t.readHierarchy(n);return n?.throwIfAborted(),e.platform===`ios`?await Be(r,e.runId,t.viewport()):await He(r,t.viewport())}async function Be(e,t,n){let[{flattenIosTree:r,resolveIosAxTreeViewport:i},{interpretIosNode:a},o]=await Promise.all([import(`./ios-ax-tree.mjs`),import(`./ios-node-interpretation.mjs`),import(`./ios-snapshot-acquisition.mjs`)]),s=Ve(e),c=i(s,n);return o.createIosSnapshotAcquisition({producer:`revyl-ios-tree`,...J({nodes:r(s).map(e=>a(e)),viewport:c.kind===`missing`?null:c.rect}),viewport:c,lineage:{targetId:t}})}function Ve(e){let t;try{t=JSON.parse(e)}catch(e){throw X(e)}let n=Array.isArray(t)?t:[t];if(!n.every(Y))throw X();return n}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return[t.children,t.nodes,t.elements].every(e=>e===void 0||Array.isArray(e)&&e.every(Y))}function X(e){return new s(`COMMAND_FAILED`,`Revyl returned an iOS hierarchy that is not an accessibility node tree.`,{reason:`provider-response-invalid`},e)}async function He(e,t){let[{parseWebDriverAndroidSnapshotNodes:n},{stampSnapshotIdentity:r}]=await Promise.all([import(`./webdriver-android-source.mjs`),import(`./snapshot-producers.mjs`).then(e=>e.n)]),{nodes:i,keyboard:a}=J({nodes:n(e),viewport:t===void 0?null:{x:0,y:0,...t}});return r({nodes:i,keyboard:a,...t===void 0?{}:{viewport:t}},{backend:`android`,producer:`revyl-android-tree`})}var Ue=class{session;signal;constructor(e,t){this.session=e,this.signal=t}async open(e,t){let n=e.trim();if(t?.url)return await this.launch(n,t.launchArgs),await this.workerAction(`open_url`,{url:t.url}),n?{launchedAppBundleId:n}:void 0;if(ne(n)){await this.workerAction(`open_url`,{url:n});return}return await this.launch(n,t?.launchArgs),n?{launchedAppBundleId:n}:void 0}async launch(e,t){if(t?.length)throw new s(`UNSUPPORTED_OPERATION`,`Revyl launches an app without arguments.`,{reason:`unsupported-provider-mode`,hint:`Open a deep link instead: open <url>.`});await this.workerAction(`launch`,e?{bundle_id:e}:{}),e&&(this.session.launchedApp.bundleId=e)}async openDevice(){}async close(e){let t=e.trim();t&&this.requireCloseableApp(t,this.session.launchedApp.bundleId),await this.workerAction(`kill_app`)}requireCloseableApp(e,t){if(t===void 0)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl session has not launched ${e}, so it has no app to end.`,{reason:`provider-app-not-launched`,command:`close`,requestedApp:e,hint:`Close without an app name to end the app this session runs, or open the app first.`});if(e!==t)throw new s(`UNSUPPORTED_OPERATION`,`Revyl ends the app this session launched (${t}), not ${e}.`,{reason:`unsupported-provider-mode`,command:`close`,sessionApp:t,requestedApp:e,hint:"Revyl has no way to name an app to `/kill_app`; end the session to stop what it runs."})}async tap(e,t){await this.workerAction(`tap`,{x:e,y:t})}async doubleTap(e,t){await this.workerAction(`double_tap`,{x:e,y:t})}async longPress(e,t,n=1500){await this.workerAction(`longpress`,{x:e,y:t,duration_ms:n})}async focus(e,t){await this.tap(e,t)}type(){throw Z(`type`,`Revyl enters text at a point; run fill <field> "text" instead of type.`)}async fill(e,t,n,r,i){if(n===``){await this.workerAction(`clear_text`,{x:e,y:t});return}if(!r||r<=0){await this.workerAction(`input`,{x:e,y:t,text:n,clear_first:!0});return}let s=0,c=Array.from(n);try{for(let[n,i]of c.entries()){if(this.signal?.aborted)throw s===0?o(this.cancellation(),`no`):this.cancellation();if(await this.workerAction(`input`,{x:e,y:t,text:i,clear_first:s===0}),s+=1,n===c.length-1)return;await b(r,void 0,this.signal===void 0?{}:{signal:this.signal})}}catch(e){throw a(this.canceledAs(e),s)}}async scroll(e,t){let n=t?.durationMs;n!==void 0&&this.requireDragDuration(n);let r=this.session.screen;if(!r)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the scroll distance cannot be planned.`,{reason:`provider-viewport-unavailable`,runId:this.session.runId});let i=ve({direction:e,...t?.amount===void 0?{}:{amount:t.amount},...t?.pixels===void 0?{}:{pixels:t.pixels},referenceWidth:r.width,referenceHeight:r.height,...t?.containerRect===void 0?{}:{container:Ke(t.containerRect,r)}});return await this.workerAction(`drag`,{start_x:i.x1,start_y:i.y1,end_x:i.x2,end_y:i.y2,...n===void 0?{}:{duration_ms:n}}),{...i,...n===void 0?{}:{durationMs:n},backend:`revyl-device-proxy`}}requireDragDuration(e){if(!this.session.dragDuration)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl worker scrolls with one drag and cannot be told how fast the finger travels.`,{reason:`unsupported-provider-mode`,command:`scroll`,flag:`--duration-ms`,runId:this.session.runId,hint:`Scroll without --duration-ms; the drag runs at the speed Revyl gives it.`});if(e<1)throw new s(`INVALID_ARGS`,`Revyl drag --duration-ms must be at least 1.`,{flag:`--duration-ms`})}async screenshot(e,t){let n=await this.session.client.captureWorkerScreenshot(this.session.runId,this.signal),r=v.dirname(e);_.mkdirSync(r,{recursive:!0});let i=v.join(r,`.${v.basename(e)}.${process.pid}.${y()}.tmp`);try{if(await _.promises.writeFile(i,n,this.signal===void 0?{}:{signal:this.signal}),this.session.platform===`ios`&&await Ge(i,this.session.screen,t?.pixelDensity),this.signal?.aborted===!0)throw this.cancellation();await _.promises.rename(i,e)}catch(e){throw await _.promises.rm(i,{force:!0}).catch(()=>void 0),this.canceledAs(e)}}async snapshot(e){return await ze(this.session,Re(this.session),e?.signal??this.signal)}async back(){await this.workerAction(`back`)}async home(){await this.workerAction(`go_home`)}setOrientation(e){throw Z(`orientation`,`Revyl does not expose orientation control.`)}setSetting(){throw Z(`settings`,`Revyl does not expose settings control.`)}cancellation(e){return new s(`COMMAND_FAILED`,`The Revyl action was canceled before it finished.`,{reason:`request_canceled`,runId:this.session.runId},e??this.signal?.reason)}canceledAs(e){return!this.signal?.aborted||e instanceof s?e:this.cancellation(e)}workerAction(e,t){return this.session.client.workerAction(this.session.runId,e,t,this.signal)}};function We(e,t){return new Ue(e,t)}async function Ge(e,t,n){if(t===void 0)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the screenshot density cannot be known.`,{reason:`provider-viewport-unavailable`});let[{readPngSize:r},{resizePngFile:i},{computeDensityScaledScreenshotSize:a}]=await Promise.all([import(`./png-size.mjs`),import(`./png-resize.mjs`),import(`./screenshot-density.mjs`)]),o=await r(e),c=a(o,Math.max(o.width,o.height)/Math.max(t.width,t.height),n);c&&await i(e,c.width,c.height)}function Ke(e,t){let n=Math.min(e.width,t.width),r=Math.min(e.height,t.height);return{x:Math.max(0,Math.min(e.x,t.width-n)),y:Math.max(0,Math.min(e.y,t.height-r)),width:n,height:r}}function Z(e,t){return new s(`UNSUPPORTED_OPERATION`,t,{reason:`unsupported-provider-mode`,command:e})}function qe(e){return ee(r,[[`backendUrl`,f(e.backendUrl??`https://backend.revyl.ai`)],[`apiKey`,e.apiKey]])}function Je(e){let t=new Ye(e),n=te(r,qe({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl}}));if(n.kind!==`provider-runtime`)throw TypeError(`Invalid Revyl runtime owner`);return Object.freeze({runtime:t,platformModule:Object.freeze({owner:n,loadRuntime:async e=>await tt(t,n.instance,e)})})}var Ye=class{options;leases;provider=r;leaseLifecycle={allocate:(e,t)=>this.allocate(e,t),release:async e=>await this.release(e)};recoverExpiredLease=async e=>{$e(e,`recover`),await this.leases.recover(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.leases.live(e.leaseId);return t?d(t.device,e.platform)?[t.device]:[]:null};constructor(e){if(!e.apiKey.trim())throw TypeError(`Revyl runtime requires an apiKey`);this.options=e;let t=g({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl},clientVersion:e.clientVersion});this.leases=he(Xe(t))}ownsDevice(t){return e(t.id)!==void 0}hasLiveSession(e){return this.sessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.sessionForDevice(e);return n?We(n,t?.signal):void 0}async shutdown(){await this.leases.shutdown()}async allocate(e,n){let r=e.leaseProvider===this.provider?t(e.backend):void 0;if(r===void 0)return;let{rejectRefusedRevylProfileFields:i,requireSameRevylStartRequest:a,resolveRevylStartRequest:o}=await import(`./session-allocation.mjs`);i(n);let s={...o(n,{...this.options.deviceModel===void 0?{}:{deviceModel:this.options.deviceModel},...this.options.osVersion===void 0?{}:{osVersion:this.options.osVersion}}),platform:r};return $(await this.leases.allocate(e,s,{...Qe(n),requireJoinable:t=>a(e.leaseId,t,s)}))}async release(e){if(e.leaseProvider!==this.provider||!t(e.backend))return;let n=await this.leases.release(e.leaseId);if(n!==void 0)return n.session?$(n.session):{revylRunId:n.handle.runId,providerSessionId:n.handle.sessionId}}sessionForDevice(t){let n=e(t.id);if(!n)return;let r=this.leases.live(n.leaseId);return r?.platform===n.platform?r:void 0}};function Xe(e){return{startTimeoutMs:ie,start:async(t,n,r)=>{let i=await oe(e,t,{platform:n.platform,appUrl:n.appUrl,deviceModel:n.deviceModel,osVersion:n.osVersion,signal:r.signal,onRented:r.rented});if(i.status===`failed`)return i;let{runId:a,sessionId:o}=i.session;return{status:`ready`,session:i.session,handle:{runId:a,sessionId:o}}},stop:async t=>{try{await pe(e,t.sessionId)}catch(e){if(!p(e))throw e}},handleKey:e=>e.sessionId,findByLease:async e=>({sessionId:x(e.leaseId)}),shuttingDown:e=>et(e.leaseId,`allocate`),releasing:e=>new s(`COMMAND_FAILED`,`Revyl lease ${e.leaseId} is being released.`,{reason:`provider-lease-releasing`,leaseId:e.leaseId,hint:`Run open again; it allocates a new lease and rents a fresh device.`}),gaveUp:(e,t,n,r)=>w(Q(e),t,n,r?.sessionId??x(e.leaseId)),cleanupPending:(e,t,n)=>ce(e.map(e=>({...e.handle??{sessionId:x(e.leaseId)},failure:i(e.cause)})),Ze(t),n)}}function Ze(e){switch(e.route){case`shutdown`:return{operation:`shutdown`};case`start`:return{};case`release`:case`recover`:return{leaseId:e.leaseId}}}function Q(e){let n=t(e.backend);if(n===void 0)throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot serve this lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});return n}function Qe(e){return{...e?.signal===void 0?{}:{signal:e.signal},...e?.deadline===void 0?{}:{deadline:e.deadline}}}function $e(e,n){if(!(e.leaseProvider===`revyl`&&t(e.backend)))throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot ${n} this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend})}function et(e,t){return new s(`COMMAND_FAILED`,`The Revyl runtime is shutting down.`,{reason:`runtime-shutting-down`,operation:t,leaseId:e,hint:`Retry the command; the daemon is ending the sessions it holds.`})}async function tt(e,t,n){let{createRevylPlatformRuntimeOwner:r}=await import(`./platform-runtime.mjs`);return r({host:n,runtimeInstance:t,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n)})}function $(e){return{revylRunId:e.runId,providerSessionId:e.sessionId,device:e.device}}export{Je as createRevylRuntime};
1
+ import{a as e,o as t,r as n,t as r}from"./device.mjs";import{a as i,i as a,o,t as s}from"./errors.mjs";import{i as c,n as l,r as u}from"./snapshot-visibility.mjs";import{r as d}from"./device2.mjs";import{a as f,i as p,n as m,o as h,r as g}from"./revyl-client.mjs";import{n as ee,r as te,t as ne}from"./open-target.mjs";import _ from"node:fs";import v from"node:path";import{createHash as re,randomUUID as y}from"node:crypto";import{setTimeout as b}from"node:timers/promises";function x(e){let t=`${re(`sha256`).update(`agent-device:revyl:session:v1:${e}`).digest(`hex`).slice(0,32)}`;return[t.slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,`${(Number.parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}`,t.slice(20,32)].join(`-`)}const S=24e4,ie=m+S+1e4,ae=new Set([503,409]);async function oe(e,t,r){let i=x(t.leaseId);if(r.signal?.aborted)return{status:`failed`,error:C(r)};let a;try{a=await se(e,r,i)}catch(e){return{status:`failed`,error:e,...T(e)?{rented:{sessionId:i}}:{}}}let o=typeof a.workflow_run_id==`string`?a.workflow_run_id:void 0,c=typeof a.session_id==`string`?a.session_id:void 0;if(o&&c&&c!==i)return{status:`failed`,rented:{runId:o,sessionId:c},error:new s(`COMMAND_FAILED`,`Revyl started the device as session ${c} instead of ${i}.`,{reason:`provider-session-identity-mismatch`,runId:o,providerSessionId:c,hint:`Retry the command; agent-device ends a Revyl session by the identity it issued.`})};if(!o)return{status:`failed`,rented:{sessionId:c??i},error:new s(`COMMAND_FAILED`,`Revyl did not start a ${r.platform} device: ${a.error??a.message??`no workflow run was returned`}`,{reason:`provider-start-refused`,platform:r.platform,...a.trace_id===void 0?{}:{traceId:a.trace_id}})};if(r.onRented?.({runId:o,sessionId:i}),r.signal?.aborted)return{status:`failed`,rented:{runId:o,sessionId:i},error:C(r)};let l=le(r);try{let a=await ue(e,o,l,{...r,sessionId:i});return{status:`ready`,session:{platform:r.platform,runId:o,sessionId:i,screen:me(a),dragDuration:a.supports_explicit_drag_duration===!0,device:n(r.platform,t,o),client:e,lease:t,launchedApp:{}}}}catch(e){return{status:`failed`,error:e,rented:{runId:o,sessionId:i}}}}async function se(e,t,n){if(t.signal?.aborted)throw C(t);let r={platform:t.platform,is_simulation:!0,session_id:n,idle_timeout_seconds:1800,...t.appUrl===void 0?{}:{app_url:t.appUrl},...t.deviceModel===void 0?{}:{device_model:t.deviceModel},...t.osVersion===void 0?{}:{os_version:t.osVersion}};return await e.startDevice(r)}function C(e){return new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e.platform},e.signal?.reason)}function w(e,t,n,r){let i=`agent-device stops Revyl session ${r} once its start answers; end it from Revyl if it stays listed.`;return t.signal?.aborted?new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e,providerSessionId:r,hint:i},t.signal.reason):new s(`COMMAND_FAILED`,`Revyl did not report a ready device within ${n} ms.`,{reason:`provider-not-ready`,timeoutMs:n,providerSessionId:r,...t.deadline===void 0?{}:{deadline:t.deadline},hint:`Retry the command; Revyl may have had no device of that model available. ${i}`})}function T(e){return!h(e)}function ce(e,t={},n){let r=e.map(e=>e.sessionId).join(`, `),i=e.length===1?e[0]:void 0;return new s(`COMMAND_FAILED`,`Revyl did not release session${i?``:`s`} ${r}.`,{reason:`provider-cleanup-pending`,...t,providerSessionIds:e.map(e=>e.sessionId),causes:e.map(e=>e.failure),...i?{providerSessionId:i.sessionId,...i.runId===void 0?{}:{runId:i.runId},cause:i.failure}:{},hint:`End the Revyl session${i?``:`s`} ${r}; each device stays rented and billed until it is.`},n)}function le(e){let t=e.deadline===void 0?S:Math.min(S,e.deadline-Date.now());return{at:Date.now()+t,budgetMs:Math.max(0,t)}}async function ue(e,t,n,r){for(await fe(e,t,n,r);;){O(n,r);let i=await E(e,t,n,r);if(O(n,r),i.device_connected===!0)return i;await A(n,r.signal)}}async function E(e,t,n,r){try{return await D(()=>e.getWorkerHealth(t,k(n,r)),n,r)}catch(e){if(!de(e))throw e;return{}}}async function D(e,t,n){try{return await e()}catch(e){throw O(t,n),e}}function de(e){return e instanceof s&&typeof e.details?.providerStatus==`number`&&ae.has(e.details.providerStatus)}async function fe(e,t,n,r){for(;;){O(n,r);let i=await D(()=>e.getWorkerConnection(t,k(n,r)),n,r);if(O(n,r),i.status===`ready`&&i.worker_ws_url)return;if(i.status===`cancelled`||i.status===`stopped`||i.status===`failed`)throw new s(`COMMAND_FAILED`,`Revyl did not start the ${r.platform} device: ${i.status}${i.message===null||i.message===void 0?``:` (${i.message})`}`,{reason:`provider-start-failed`,runId:t,status:i.status});await A(n,r.signal)}}function O(e,t){if(!(Date.now()<e.at))throw w(t.platform,t,e.budgetMs,t.sessionId)}function k(e,t){let n=AbortSignal.timeout(Math.max(0,e.at-Date.now()));return t.signal===void 0?n:AbortSignal.any([t.signal,n])}async function A(e,t){await b(Math.min(2e3,Math.max(0,e.at-Date.now())),void 0,t===void 0?{}:{signal:t}).catch(()=>void 0)}async function pe(e,t){await e.stopDeviceSession(t)}function me(e){let{screen_width:t,screen_height:n}=e;if(!(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0))return{width:t,height:n}}var j=class{lease;generation;phase=`starting`;request;answerBy;abandon=new AbortController;start=Promise.resolve({status:`failed`,error:void 0});answered=!1;answer;markAnswered=()=>void 0;session=void 0;rentals=new Map;latest=void 0;unnamed=!1;waiters=new Set;followUpQueued=!1;ending=void 0;constructor(e,t,n,r){this.lease=e,this.generation=t,this.request=n,this.answerBy=r,this.answer=new Promise(e=>{this.markAnswered=e})}};function he(e){let t=new ge(e);return Object.freeze({live:e=>t.live(e),allocate:async(e,n,r)=>await t.allocate(e,n,r),release:async e=>await t.release(e),recover:async e=>await t.recover(e),shutdown:async()=>await t.shutdown()})}var ge=class{entries=new Map;shuttingDown=!1;generations=0;driver;constructor(e){this.driver=e}live(e){let t=this.entries.get(e);return t?.phase===`ready`?t.session:void 0}isCurrent(e){return this.entries.get(e.lease.leaseId)?.generation===e.generation}refusal(e,t,n){return this.shuttingDown?this.driver.shuttingDown(e):t&&(t.phase===`ending`||!this.isCurrent(t))?this.driver.releasing(e):n()}async allocate(e,t,n={}){let r=this.entries.get(e.leaseId);if(this.shuttingDown||r?.phase===`ending`)throw this.refusal(e,r,()=>0);r?.request!==void 0&&n.requireJoinable?.(r.request);let i=N(n),a=Date.now()+this.driver.startTimeoutMs,o=Math.min(i.deadline??a,a);if(!r&&P(i,o))throw this.driver.gaveUp(e,i,0,void 0);let s=r??this.rent(e,t,i,a),c=Math.max(0,o-Date.now()),l=await this.join(s,i,o);return this.deliver(s,l,i,o,c)}deliver(e,t,n,r,i){if(t.status===`failed`)throw this.refusal(e.lease,void 0,()=>t.error);let a=this.refusal(e.lease,e,()=>P(n,r)?this.driver.gaveUp(e.lease,n,i,e.latest):void 0);if(a!==void 0)throw a;return t.session}async release(e){let t=this.entries.get(e);if(!t)return;let n=await this.teardown(t);if(n.status===`pending`)throw this.pending(t,n,{route:`release`,leaseId:e});return n.status===`stopped`?{handle:n.handle,session:n.session}:void 0}async recover(e){let t=e.leaseId,n=this.entries.get(t);if(n===void 0){if(this.shuttingDown)throw this.driver.shuttingDown(e);n=this.recovering(e)}let r=await this.teardown(n);if(r.status===`pending`)throw this.pending(n,r,{route:`recover`,leaseId:t})}async shutdown(){this.shuttingDown=!0;let e=[],t=[...this.entries.values()];if((await Promise.all(t.map(async e=>await this.teardown(e)))).forEach((n,r)=>{if(n.status!==`pending`)return;let i=t[r].lease.leaseId;for(let t of n.owed)e.push({leaseId:i,...t})}),e.length>0)throw this.driver.cleanupPending(e,{route:`shutdown`})}rent(e,t,n,r){let i=new j(e,this.generations+=1,t,r);return i.start=this.runStart(i,t,n),this.entries.set(e.leaseId,i),i}recovering(e){let t=new j(e,this.generations+=1,void 0,Date.now());return t.answered=!0,t.markAnswered(),t.unnamed=!0,t.phase=`ending`,this.entries.set(e.leaseId,t),t}async runStart(e,t,n){let r=Date.now(),i=await this.callStart(e,t);if(_e(e,i,this.driver.handleKey),i.status===`ready`&&(e.session=i.session,e.phase===`starting`&&this.isCurrent(e)&&F(e)))return e.phase=`ready`,{status:`ready`,session:i.session};let a;try{a=this.startFailure(e,i,n,r)}catch(e){a=e}return await this.endFailedStart(e,a)}async callStart(e,t){try{return await this.driver.start(e.lease,t,{signal:e.abandon.signal,deadline:e.answerBy,rented:t=>{e.answered||(M(e,t,this.driver.handleKey(t)),e.phase===`ending`&&this.followUp(e))}})}catch(e){return{status:`rejected`,error:e}}}startFailure(e,t,n,r){let i=Math.max(0,e.answerBy-r);return this.refusal(e.lease,e,()=>t.status===`ready`?this.driver.gaveUp(e.lease,n,i,t.handle):t.error)}async endFailedStart(e,t){if(e.phase===`ending`)return this.followUp(e),{status:`failed`,error:t};let n=await this.teardown(e);if(n.status!==`pending`)return{status:`failed`,error:t};let r=e.lease.leaseId;return{status:`failed`,error:this.driver.cleanupPending(n.owed.map(e=>({leaseId:r,...e})),{route:`start`,leaseId:r},t)}}async join(e,t,n){if(e.phase===`ready`)return{status:`ready`,session:e.session};let r=Math.max(0,n-Date.now()),i=()=>{try{return this.refusal(e.lease,e,()=>this.driver.gaveUp(e.lease,t,r,e.latest))}catch(e){return e}},a=new AbortController,o=setTimeout(()=>a.abort(),r),s=t.signal?[t.signal,a.signal]:[a.signal],c={deadline:n,signal:t.signal},l=()=>void 0;try{if(e.waiters.add(c),s.some(e=>e.aborted))throw i();let t=new Promise((t,n)=>{l=()=>{let t=i();e.waiters.delete(c),this.abandonIfUnwanted(e),n(t)};for(let e of s)e.addEventListener(`abort`,l,{once:!0})});return await Promise.race([e.start,t])}finally{e.waiters.delete(c),this.abandonIfUnwanted(e),clearTimeout(o);for(let e of s)e.removeEventListener(`abort`,l)}}abandonIfUnwanted(e){e.answered||e.phase===`ending`||F(e)||this.teardown(e).catch(()=>void 0)}teardown(e){if(e.phase=`ending`,e.answered||e.abandon.abort(),e.ending)return e.ending;let t=this.runTeardown(e).finally(()=>{e.ending===t&&(e.ending=void 0)});return e.ending=t,t}async runTeardown(e){let t=new Map;for(;;){await this.untilAnswered(e);let n=await this.nameRental(e);if(n!==void 0)return n;let r=await this.stopRentals(e,t);if(r!==`progress`){if(r.length>0)return{status:`pending`,owed:r};if(!(e.unnamed||[...e.rentals.values()].some(e=>!e.stopped)))return this.finishTeardown(e)}}}async stopRentals(e,t){for(let n of e.rentals.values()){if(n.stopped)continue;if(t.get(n)!==void 0){if(n.stopping!==void 0)break;continue}let e=await this.stop(n);if(e===void 0)return`progress`;if(t.set(n,{handle:n.handle,cause:e.cause}),n.stopping!==void 0)break}return[...e.rentals.values()].filter(e=>!e.stopped).map(e=>t.get(e)??{handle:e.handle,cause:Error(`The stop waits for an earlier stop of this lease that is still in flight.`)})}async nameRental(e){if(e.unnamed)try{let t=await this.driver.findByLease(e.lease);M(e,t,this.driver.handleKey(t)),e.unnamed=!1;return}catch(e){return{status:`pending`,owed:[{handle:void 0,cause:e}]}}}finishTeardown(e){let t=e.latest;return e.answered?(this.isCurrent(e)&&this.entries.delete(e.lease.leaseId),t===void 0?{status:`nothing-rented`}:{status:`stopped`,handle:t,session:e.session}):{status:`pending`,owed:[{handle:t,cause:Error(`The provider start did not answer within its start timeout.`)}]}}followUp(e){let t=e.ending;if(t===void 0){this.teardown(e).catch(()=>void 0);return}e.followUpQueued||(e.followUpQueued=!0,t.then(async()=>(e.followUpQueued=!1,await this.teardown(e))).catch(()=>void 0))}async untilAnswered(e){if(e.answered)return;let t,n=new Promise(n=>{t=setTimeout(n,Math.max(0,e.answerBy-Date.now()))});try{await Promise.race([e.answer,n])}finally{clearTimeout(t)}}async stop(e){e.stopping??=this.stopHandle(e.handle).then(t=>(t===void 0&&(e.stopped=!0),e.stopping=void 0,t));let t=e.stopping,n=this.driver.stopTimeoutMs;if(n===void 0)return await t;let r,i=new Promise(e=>{r=setTimeout(()=>e({cause:Error(`The provider stop did not answer within ${n} ms.`)}),n)});try{return await Promise.race([t,i])}finally{clearTimeout(r)}}async stopHandle(e){try{await this.driver.stop(e);return}catch(e){return{cause:e}}}pending(e,t,n){return this.driver.cleanupPending(t.owed.map(t=>({leaseId:e.lease.leaseId,...t})),n)}};function _e(e,t,n){switch(t.status){case`ready`:M(e,t.handle,n(t.handle));break;case`failed`:t.rented!==void 0&&M(e,t.rented,n(t.rented));break;case`rejected`:e.rentals.size===0&&(e.unnamed=!0)}e.answered=!0,e.markAnswered()}function M(e,t,n){e.rentals.has(n)||e.rentals.set(n,{handle:t,stopped:!1,stopping:void 0}),e.latest=t}function N(e){return{...e.signal===void 0?{}:{signal:e.signal},...e.deadline===void 0?{}:{deadline:e.deadline}}}function P(e,t){return e.signal?.aborted===!0||Date.now()>=t}function F(e){if(e.phase===`ending`)return!1;let t=Date.now();for(let n of e.waiters)if(!n.signal?.aborted&&t<n.deadline)return!0;return!1}new Map([...Object.entries({ios:`ios-instance`,android:`android-instance`,harmonyos:`harmonyos-instance`}).flatMap(([e,t])=>t===void 0?[]:[[t,e]]),[`macos-app`,`macos`]]);function I(e,t={message:e=>`Invalid value: ${e}`}){let n=new Set(e),r=t.normalize??(e=>e);return{is:e=>typeof e==`string`&&n.has(e),parse:e=>{let i=r(e??``);if(n.has(i))return i;throw new s(`INVALID_ARGS`,t.message(e??``))}}}I([`up`,`down`,`left`,`right`],{message:e=>`Unknown direction: ${e}`});function ve(e){let t=e.direction,n=t===`up`||t===`down`,r=n?e.referenceHeight:e.referenceWidth,i=n?e.referenceWidth:e.referenceHeight,a=xe(e.amount),o=e.pixels===void 0?Math.round(r*a):Se(e.pixels),s=L(r),c=Math.max(1,r-s*2),l=Math.max(1,Math.min(o,c)),u=Math.round(l/2),d=Math.round(r/2),f={axisStart:d-u,axisEnd:d+u,cross:Math.round(i/2)},p=L(i),m=e.container?be(f,e.container,n,{axis:{min:s,max:r-s},cross:{min:p,max:i-p},crossFrame:{min:0,max:i}}):f,h=m.axisEnd-m.axisStart,g=h<l;return{direction:t,...ye(t,m),referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:g?h:l,...g?{requestedPixels:l}:{}}}function ye(e,t){let n=e===`up`||e===`down`,r=n?{x:t.cross,y:t.axisStart}:{x:t.axisStart,y:t.cross},i=n?{x:t.cross,y:t.axisEnd}:{x:t.axisEnd,y:t.cross},[a,o]=e===`up`||e===`left`?[r,i]:[i,r];return{x1:a.x,y1:a.y,x2:o.x,y2:o.y}}function L(e){return Math.max(1,Math.round(e*.1))}function be(e,t,n,r){let i=R(n?t.y:t.x,n?t.height:t.width,r.axis),a=n?t.x:t.y,o=n?t.width:t.height,s=R(a,o,r.cross)??R(a,o,r.crossFrame);if(!i||!s)return e;let c=e.cross>=s.min&&e.cross<=s.max?e.cross:Math.round((s.min+s.max)/2);if(e.axisEnd-e.axisStart>=i.max-i.min)return{axisStart:i.min,axisEnd:i.max,cross:c};let l=e.axisStart<i.min?i.min-e.axisStart:Math.min(0,i.max-e.axisEnd);return{axisStart:e.axisStart+l,axisEnd:e.axisEnd+l,cross:c}}function R(e,t,n){let r=Math.max(n.min,Math.ceil(e)+8),i=Math.min(n.max,Math.floor(e+t)-1-8);return i>r?{min:r,max:i}:void 0}function xe(e){if(e===void 0)return .6;if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll amount must be a positive number`);return e}function Se(e){if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(e))}Object.freeze({reason:`scroll_keyboard_occludes_surface`,hint:"The on-screen keyboard covers the surface this scroll would swipe, so it cannot reach it. Run `keyboard dismiss` and retry, accepting that it drops focus (re-tap the field to keep typing), or scroll before focusing the field."});const z=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function Ce(e){let t=B(e.packageName),n=(e.resourceId??``).toLowerCase(),r=B(e.activeInputMethodPackage);if(t&&r&&t===r)return{inputMethodOwned:!0,source:`active-input-method`};if(r&&n.startsWith(`${r}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(t&&z.has(t))return{inputMethodOwned:!0,source:`known-ime-package`};for(let e of z)if(n.startsWith(`${e}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function we(e){return Ce(e).inputMethodOwned}function Te(e){return we({packageName:e.bundleId,resourceId:e.identifier})}function B(e){return(e??``).trim().toLowerCase()||void 0}const Ee=new Set([`UIKeyboardDockItemButton`,`UIAccessibilityElementKBKey`]),De=new Set([`TUIPredictionViewCell`]),Oe=new Set([`UIKeyboardLayoutStar`,`TUIPredictionView`]),V=new Set([`_UIRemoteKeyboardPlaceholderView`,`TUISystemInputAssistantView`,`TUISystemInputAssistantPageView`]);function H(e,t){return e.role!==void 0&&t.has(e.role)}Object.freeze({reason:`tap_keyboard_occludes_target`,hint:"The visible keyboard covers this target, so the tap would land on a key instead of on it. End editing first: tap the app's own Done/Cancel/close control, or run `keyboard enter` when submitting is what you want (`keyboard dismiss` works only when the keyboard exposes its own dismiss key). This reads the snapshot the command measured against, so if the keyboard closed since it was taken, run `snapshot -i` and retry."});const ke=new Set([`keyboard`,`key`]);function U(e){return ke.has(l(e.type??``))||Te(e)}function W(e){return U(e)||Ee.has(e.role??``)}function G(e){return U(e)||H(e,Oe)}function Ae(e,t){if(W(e)||H(e,De)||H(e,V)||G(e))return!0;let n=new Set,r=e.parentIndex;for(;typeof r==`number`&&!n.has(r);){n.add(r);let e=t.get(r);if(!e)return!1;if(H(e,V)||G(e))return!0;r=e.parentIndex}return!1}function K(e){return e!==null&&u(e)}function q(e){return e.flatMap(e=>u(e.rect)?[e.rect]:[])}function je(e,t){let n=new Map(e.map(e=>[e.index,e.parentIndex])),r=new Set(t.map(e=>e.index)),i=new Set;for(let e of t)for(let t of Me(n,r,e.index))i.add(t);return i}function Me(e,t,n){let r=[],i=new Set,a=e.get(n);for(;typeof a==`number`&&!i.has(a);)i.add(a),t.has(a)&&r.push(a),a=e.get(a);return r}function Ne(e){let t=e.map(e=>[e.x,e.x+e.width]).sort((e,t)=>e[0]-t[0]),n=t[0]?.[1]??0;for(let[e,r]of t){if(e-n>2)return!1;n=Math.max(n,r)}return!0}function Pe(e){let t=Math.min(...e.anchorRects.map(e=>e.y)),n=Math.min(...e.anchorRects.map(e=>e.x)),r=Math.max(...e.anchorRects.map(e=>e.x+e.width)),i=e.viewport.y+e.viewport.height;return e.reportedBottom<i-80||r-n<=e.reportedBottom-t?null:{x:n,y:t,width:r-n,height:i-t}}function Fe(e){let t=q(e.anchorNodes.filter(t=>!e.planeIndices.has(t.index)));return Ne(t.length>0?t:e.anchorRects)}function Ie(e,t){let n=e.filter(U),r=q(n);if(r.length===0||!K(t))return null;let i=e.filter(W),a=q(i);if(a.length===0)return null;let o=Pe({anchorRects:r,reportedBottom:Math.max(...a.map(e=>e.y+e.height)),viewport:t});return!o||!u(o)||!Fe({anchorNodes:n,anchorRects:r,planeIndices:je(e,i)})?null:o}function J(e){let t=new Map(e.nodes.map(e=>[e.index,e]));return{nodes:e.nodes.map(e=>({...e,keyboardOwned:Ae(e,t)})),keyboard:Le(e)}}function Le(e){let t=Ie(e.nodes,e.viewport);return t?{kind:`derived`,derivation:`docked-tree`,frame:t,treeBound:!0}:K(e.viewport)&&e.nodes.some(U)?{kind:`tree-rejected`,derivation:`docked-tree`,...typeof e.visibility==`boolean`?{visible:e.visibility}:{}}:typeof e.visibility==`boolean`?{kind:`visibility-only`,visible:e.visibility}:{kind:`unmeasurable`,reason:e.nodes.some(U)?`keyboard-viewport-unavailable`:e.visibility===`failed`?`keyboard-visibility-probe-failed`:e.visibility===`unsupported`?`keyboard-visibility-probe-unsupported`:`keyboard-not-observed`}}function Re(e){return{readHierarchy:t=>e.client.getWorkerHierarchy(e.runId,t),viewport:()=>e.screen===void 0?void 0:c({x:0,y:0,...e.screen})}}async function ze(e,t,n){let r=await t.readHierarchy(n);return n?.throwIfAborted(),e.platform===`ios`?await Be(r,e.runId,t.viewport()):await He(r,t.viewport())}async function Be(e,t,n){let[{flattenIosTree:r,resolveIosAxTreeViewport:i},{interpretIosNode:a},o]=await Promise.all([import(`./ios-ax-tree.mjs`),import(`./ios-node-interpretation.mjs`),import(`./ios-snapshot-acquisition.mjs`)]),s=Ve(e),c=i(s,n);return o.createIosSnapshotAcquisition({producer:`revyl-ios-tree`,...J({nodes:r(s).map(e=>a(e)),viewport:c.kind===`missing`?null:c.rect}),viewport:c,lineage:{targetId:t}})}function Ve(e){let t;try{t=JSON.parse(e)}catch(e){throw X(e)}let n=Array.isArray(t)?t:[t];if(!n.every(Y))throw X();return n}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return[t.children,t.nodes,t.elements].every(e=>e===void 0||Array.isArray(e)&&e.every(Y))}function X(e){return new s(`COMMAND_FAILED`,`Revyl returned an iOS hierarchy that is not an accessibility node tree.`,{reason:`provider-response-invalid`},e)}async function He(e,t){let[{parseWebDriverAndroidSnapshotNodes:n},{stampSnapshotIdentity:r}]=await Promise.all([import(`./webdriver-android-source.mjs`),import(`./snapshot-producers.mjs`).then(e=>e.n)]),{nodes:i,keyboard:a}=J({nodes:n(e),viewport:t===void 0?null:{x:0,y:0,...t}});return r({nodes:i,keyboard:a,...t===void 0?{}:{viewport:t}},{backend:`android`,producer:`revyl-android-tree`})}var Ue=class{session;signal;constructor(e,t){this.session=e,this.signal=t}async open(e,t){let n=e.trim();if(t?.url)return await this.launch(n,t.launchArgs),await this.workerAction(`open_url`,{url:t.url}),n?{launchedAppBundleId:n}:void 0;if(ne(n)){await this.workerAction(`open_url`,{url:n});return}return await this.launch(n,t?.launchArgs),n?{launchedAppBundleId:n}:void 0}async launch(e,t){if(t?.length)throw new s(`UNSUPPORTED_OPERATION`,`Revyl launches an app without arguments.`,{reason:`unsupported-provider-mode`,hint:`Open a deep link instead: open <url>.`});await this.workerAction(`launch`,e?{bundle_id:e}:{}),e&&(this.session.launchedApp.bundleId=e)}async openDevice(){}async close(e){let t=e.trim();t&&this.requireCloseableApp(t,this.session.launchedApp.bundleId),await this.workerAction(`kill_app`)}requireCloseableApp(e,t){if(t===void 0)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl session has not launched ${e}, so it has no app to end.`,{reason:`provider-app-not-launched`,command:`close`,requestedApp:e,hint:`Close without an app name to end the app this session runs, or open the app first.`});if(e!==t)throw new s(`UNSUPPORTED_OPERATION`,`Revyl ends the app this session launched (${t}), not ${e}.`,{reason:`unsupported-provider-mode`,command:`close`,sessionApp:t,requestedApp:e,hint:"Revyl has no way to name an app to `/kill_app`; end the session to stop what it runs."})}async tap(e,t){await this.workerAction(`tap`,{x:e,y:t})}async doubleTap(e,t){await this.workerAction(`double_tap`,{x:e,y:t})}async longPress(e,t,n=1500){await this.workerAction(`longpress`,{x:e,y:t,duration_ms:n})}async focus(e,t){await this.tap(e,t)}type(){throw Z(`type`,`Revyl enters text at a point; run fill <field> "text" instead of type.`)}async fill(e,t,n,r,o){if(n===``){await this.workerAction(`clear_text`,{x:e,y:t});return}if(!r||r<=0){await this.workerAction(`input`,{x:e,y:t,text:n,clear_first:!0});return}let s=0,c=Array.from(n);try{for(let[n,i]of c.entries()){if(this.signal?.aborted)throw s===0?a(this.cancellation(),`no`):this.cancellation();if(await this.workerAction(`input`,{x:e,y:t,text:i,clear_first:s===0}),s+=1,n===c.length-1)return;await b(r,void 0,this.signal===void 0?{}:{signal:this.signal})}}catch(e){throw i(this.canceledAs(e),s)}}async scroll(e,t){let n=t?.durationMs;n!==void 0&&this.requireDragDuration(n);let r=this.session.screen;if(!r)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the scroll distance cannot be planned.`,{reason:`provider-viewport-unavailable`,runId:this.session.runId});let i=ve({direction:e,...t?.amount===void 0?{}:{amount:t.amount},...t?.pixels===void 0?{}:{pixels:t.pixels},referenceWidth:r.width,referenceHeight:r.height,...t?.containerRect===void 0?{}:{container:Ke(t.containerRect,r)}});return await this.workerAction(`drag`,{start_x:i.x1,start_y:i.y1,end_x:i.x2,end_y:i.y2,...n===void 0?{}:{duration_ms:n}}),{...i,...n===void 0?{}:{durationMs:n},backend:`revyl-device-proxy`}}requireDragDuration(e){if(!this.session.dragDuration)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl worker scrolls with one drag and cannot be told how fast the finger travels.`,{reason:`unsupported-provider-mode`,command:`scroll`,flag:`--duration-ms`,runId:this.session.runId,hint:`Scroll without --duration-ms; the drag runs at the speed Revyl gives it.`});if(e<1)throw new s(`INVALID_ARGS`,`Revyl drag --duration-ms must be at least 1.`,{flag:`--duration-ms`})}async screenshot(e,t){let n=await this.session.client.captureWorkerScreenshot(this.session.runId,this.signal),r=v.dirname(e);_.mkdirSync(r,{recursive:!0});let i=v.join(r,`.${v.basename(e)}.${process.pid}.${y()}.tmp`);try{if(await _.promises.writeFile(i,n,this.signal===void 0?{}:{signal:this.signal}),this.session.platform===`ios`&&await Ge(i,this.session.screen,t?.pixelDensity),this.signal?.aborted===!0)throw this.cancellation();await _.promises.rename(i,e)}catch(e){throw await _.promises.rm(i,{force:!0}).catch(()=>void 0),this.canceledAs(e)}}async snapshot(e){return await ze(this.session,Re(this.session),e?.signal??this.signal)}async back(){await this.workerAction(`back`)}async home(){await this.workerAction(`go_home`)}setOrientation(e){throw Z(`orientation`,`Revyl does not expose orientation control.`)}setSetting(){throw Z(`settings`,`Revyl does not expose settings control.`)}cancellation(e){return new s(`COMMAND_FAILED`,`The Revyl action was canceled before it finished.`,{reason:`request_canceled`,runId:this.session.runId},e??this.signal?.reason)}canceledAs(e){return!this.signal?.aborted||e instanceof s?e:this.cancellation(e)}workerAction(e,t){return this.session.client.workerAction(this.session.runId,e,t,this.signal)}};function We(e,t){return new Ue(e,t)}async function Ge(e,t,n){if(t===void 0)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the screenshot density cannot be known.`,{reason:`provider-viewport-unavailable`});let[{readPngSize:r},{resizePngFile:i},{computeDensityScaledScreenshotSize:a}]=await Promise.all([import(`./png-size.mjs`),import(`./png-resize.mjs`),import(`./screenshot-density.mjs`)]),o=await r(e),c=a(o,Math.max(o.width,o.height)/Math.max(t.width,t.height),n);c&&await i(e,c.width,c.height)}function Ke(e,t){let n=Math.min(e.width,t.width),r=Math.min(e.height,t.height);return{x:Math.max(0,Math.min(e.x,t.width-n)),y:Math.max(0,Math.min(e.y,t.height-r)),width:n,height:r}}function Z(e,t){return new s(`UNSUPPORTED_OPERATION`,t,{reason:`unsupported-provider-mode`,command:e})}function qe(e){return ee(r,[[`backendUrl`,f(e.backendUrl??`https://backend.revyl.ai`)],[`apiKey`,e.apiKey]])}function Je(e){let t=new Ye(e),n=te(r,qe({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl}}));if(n.kind!==`provider-runtime`)throw TypeError(`Invalid Revyl runtime owner`);return Object.freeze({runtime:t,platformModule:Object.freeze({owner:n,loadRuntime:async e=>await tt(t,n.instance,e)})})}var Ye=class{options;leases;provider=r;leaseLifecycle={allocate:(e,t)=>this.allocate(e,t),release:async e=>await this.release(e)};recoverExpiredLease=async e=>{$e(e,`recover`),await this.leases.recover(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.leases.live(e.leaseId);return t?d(t.device,e.platform)?[t.device]:[]:null};constructor(e){if(!e.apiKey.trim())throw TypeError(`Revyl runtime requires an apiKey`);this.options=e;let t=g({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl},clientVersion:e.clientVersion});this.leases=he(Xe(t))}ownsDevice(t){return e(t.id)!==void 0}hasLiveSession(e){return this.sessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.sessionForDevice(e);return n?We(n,t?.signal):void 0}getDeploymentSession(e){let t=this.sessionForDevice(e);return t?{runId:t.runId,sessionId:t.sessionId,platform:t.platform,client:t.client}:void 0}async shutdown(){await this.leases.shutdown()}async allocate(e,n){let r=e.leaseProvider===this.provider?t(e.backend):void 0;if(r===void 0)return;let{rejectRefusedRevylProfileFields:i,requireSameRevylStartRequest:a,resolveRevylStartRequest:o}=await import(`./session-allocation.mjs`);i(n);let s={...o(n,{...this.options.deviceModel===void 0?{}:{deviceModel:this.options.deviceModel},...this.options.osVersion===void 0?{}:{osVersion:this.options.osVersion}}),platform:r};return $(await this.leases.allocate(e,s,{...Qe(n),requireJoinable:t=>a(e.leaseId,t,s)}))}async release(e){if(e.leaseProvider!==this.provider||!t(e.backend))return;let n=await this.leases.release(e.leaseId);if(n!==void 0)return n.session?$(n.session):{revylRunId:n.handle.runId,providerSessionId:n.handle.sessionId}}sessionForDevice(t){let n=e(t.id);if(!n)return;let r=this.leases.live(n.leaseId);return r?.platform===n.platform?r:void 0}};function Xe(e){return{startTimeoutMs:ie,start:async(t,n,r)=>{let i=await oe(e,t,{platform:n.platform,appUrl:n.appUrl,deviceModel:n.deviceModel,osVersion:n.osVersion,signal:r.signal,onRented:r.rented});if(i.status===`failed`)return i;let{runId:a,sessionId:o}=i.session;return{status:`ready`,session:i.session,handle:{runId:a,sessionId:o}}},stop:async t=>{try{await pe(e,t.sessionId)}catch(e){if(!p(e))throw e}},handleKey:e=>e.sessionId,findByLease:async e=>({sessionId:x(e.leaseId)}),shuttingDown:e=>et(e.leaseId,`allocate`),releasing:e=>new s(`COMMAND_FAILED`,`Revyl lease ${e.leaseId} is being released.`,{reason:`provider-lease-releasing`,leaseId:e.leaseId,hint:`Run open again; it allocates a new lease and rents a fresh device.`}),gaveUp:(e,t,n,r)=>w(Q(e),t,n,r?.sessionId??x(e.leaseId)),cleanupPending:(e,t,n)=>ce(e.map(e=>({...e.handle??{sessionId:x(e.leaseId)},failure:o(e.cause)})),Ze(t),n)}}function Ze(e){switch(e.route){case`shutdown`:return{operation:`shutdown`};case`start`:return{};case`release`:case`recover`:return{leaseId:e.leaseId}}}function Q(e){let n=t(e.backend);if(n===void 0)throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot serve this lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});return n}function Qe(e){return{...e?.signal===void 0?{}:{signal:e.signal},...e?.deadline===void 0?{}:{deadline:e.deadline}}}function $e(e,n){if(!(e.leaseProvider===`revyl`&&t(e.backend)))throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot ${n} this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend})}function et(e,t){return new s(`COMMAND_FAILED`,`The Revyl runtime is shutting down.`,{reason:`runtime-shutting-down`,operation:t,leaseId:e,hint:`Retry the command; the daemon is ending the sessions it holds.`})}async function tt(e,t,n){let{createRevylPlatformRuntimeOwner:r}=await import(`./platform-runtime.mjs`);return r({host:n,runtimeInstance:t,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n),getDeploymentSession:t=>e.getDeploymentSession(t)})}function $(e){return{revylRunId:e.runId,providerSessionId:e.sessionId,device:e.device}}export{Je as createRevylRuntime};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-device/revyl",
3
- "version": "0.21.38",
3
+ "version": "0.21.39",
4
4
  "type": "module",
5
5
  "description": "Revyl cloud iOS simulator and Android emulator plugin for agent-device.",
6
6
  "files": [
@@ -17,11 +17,12 @@
17
17
  "devDependencies": {
18
18
  "@agent-device/capture-kit": "0.0.0",
19
19
  "@agent-device/contracts": "0.0.0",
20
+ "@agent-device/host-kit": "0.0.0",
20
21
  "@agent-device/kernel": "0.0.0",
21
- "@agent-device/provision-kit": "0.0.0",
22
22
  "@agent-device/provider-webdriver": "0.0.0",
23
+ "@agent-device/provision-kit": "0.0.0",
23
24
  "@agent-device/test-kit": "0.0.0",
24
- "agent-device": "0.21.38"
25
+ "agent-device": "0.21.39"
25
26
  },
26
27
  "agentDevicePlugin": {
27
28
  "apiVersion": 1,