agent-device 0.20.2 → 0.20.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.2.apk → agent-device-android-ime-helper-0.20.4.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.4.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.2.manifest.json → agent-device-android-ime-helper-0.20.4.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.4.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.4.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.2.manifest.json → agent-device-android-snapshot-helper-0.20.4.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +57 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +45 -185
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +257 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +1 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +3 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +8 -2
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android-adb.d.ts +4 -27
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-helpers.js +1 -0
- package/dist/src/app-inventory.d.ts +4 -0
- package/dist/src/app-lifecycle.js +7 -7
- package/dist/src/app-resolution.js +1 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +27 -19
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +15 -14
- package/dist/src/client-metro.js +1 -1
- package/dist/src/{tv-remote.d.ts → cloud-artifacts.d.ts} +109 -126
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-surface.js +1 -1
- package/dist/src/context.js +1 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/debug-symbols.js +4 -4
- package/dist/src/device-input-state.d.ts +26 -0
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device.js +1 -9
- package/dist/src/devices2.js +1 -1
- package/dist/src/entities.js +1 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/ime-lifecycle.js +9 -0
- package/dist/src/index.d.ts +593 -556
- package/dist/src/input-actions.js +4 -4
- package/dist/src/install-artifact.js +4 -4
- package/dist/src/install-artifact2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.d.ts +7 -4
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +14 -14
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun.d.ts +171 -190
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/logcat.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/metro.d.ts +1 -1
- package/dist/src/parser.js +2 -0
- package/dist/src/path-resolution.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/plist-xml.js +1 -0
- package/dist/src/plist.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/process-lock.js +1 -1
- package/dist/src/provider-limrun-runtime.js +1 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +22 -22
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/reporting.js +7 -7
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runner-provider.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/screenshot-geometry.js +1 -0
- package/dist/src/screenshot-result.js +6 -0
- package/dist/src/sdk-android-adb.d.ts +5 -6
- package/dist/src/sdk-android-adb.js +3 -3
- package/dist/src/sdk-batch-runner.d.ts +2 -2
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +21 -25
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.d.ts +19 -4
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selector-vocabulary.js +1 -1
- package/dist/src/selectors.d.ts +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +8 -8
- package/dist/src/setting-state.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/src.js +1 -0
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/viewport-dimension.js +14 -0
- package/package.json +28 -19
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.2.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.2.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.2.apk.sha256 +0 -1
- package/dist/src/android-input-method-overlays.js +0 -1
- package/dist/src/android-input-ownership.js +0 -1
- package/dist/src/apple-multitouch-support.js +0 -1
- package/dist/src/click-button.d.ts +0 -5
- package/dist/src/compatibility-policy.js +0 -1
- package/dist/src/gesture-plan-types.js +0 -1
- package/dist/src/gesture-plan.js +0 -1
- package/dist/src/launch-console.js +0 -1
- package/dist/src/recording-export-quality.js +0 -15
- package/dist/src/rolldown-runtime.js +0 -1
- package/dist/src/runtime2.js +0 -1
- package/dist/src/sdk-app-inventory.d.ts +0 -4
- package/dist/src/sdk-app-inventory.js +0 -1
- package/dist/src/snapshot-diagnostics.js +0 -6
- package/dist/src/xml.js +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
003859ea5dc5d1ed8ddc5daf786eacb790ff471bbb0c3b0e1239712f73f37684 agent-device-android-snapshot-helper-0.20.2.apk
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{u as e}from"./sdk-contracts.js";import{Z as t,gt as n,ht as r,rt as i,s as a}from"./sdk-selectors.js";import{n as o}from"./android-input-ownership.js";const s=[`x`,`y`,`width`,`height`];function c(t){let n=l(t);if(!n)return null;let r=e(n);return!Number.isFinite(r.x)||!Number.isFinite(r.y)?null:r}function l(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function u(e,t){return!e||!t?!1:s.every(n=>Math.abs(e[n]-t[n])<=.5)}function d(e){return{x:f(e.x,e.width),y:f(e.y,e.height)}}function f(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}function p(e){let t=new Map;for(let n of e)t.set(n.index,n);return t}function m(e,t,n){let r=[],i=new Set([e.index]),o=e;for(;r.length<n;){if(typeof o.parentIndex!=`number`)return{chain:r,broken:!1};let e=t.get(o.parentIndex);if(!e||i.has(e.index))return{chain:r,broken:!0};i.add(e.index);let n=a(e);r.push({role:n.role,...n.label===void 0?{}:{label:n.label}}),o=e}return{chain:r,broken:!1}}function h(e,t,i,o){return e.filter(e=>{if(!n(a(e),i))return!1;let s=m(e,t,Math.max(o.length,1));return!s.broken&&r(s.chain,o)})}const g=[`tabbar`,`toolbar`,`navigationbar`,`bottomnavigation`,`bottomnavigationview`,`sheet`,`dialog`,`alert`,`popover`,`menu`],_=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`edittext`,`checkbox`,`radio`,`switch`,`cell`];function v(e,t={}){if(e.length<2)return e;let n=[...e],r=new Map(n.map(e=>[e.index,e])),i={nodes:n,byIndex:r,overlayPositions:n.flatMap((e,n)=>w(e,r,t)?[n]:[])},a=!1;for(let[e,r]of n.entries()){if(!C(r)||!b(i,e,r,t))continue;a=!0;let o={...r,hittable:!1,interactionBlocked:`covered`,presentationHints:F(r.presentationHints)};n[e]=o,i.byIndex.set(o.index,o)}return a?n:e}function y(e){return e.interactionBlocked!==void 0}function b(t,n,r,i){let a=P(r.rect);if(!a)return null;let o=e(a);for(let e of t.overlayPositions){if(e<=n)continue;let s=t.nodes[e];if(s&&x(t,e,r,a,o,i))return s}return null}function x(e,n,r,i,a,o){if(!e.nodes[n])return!1;let s=S(e,n,r,i,o);return!!(s&&t(s,a.x,a.y))}function S(e,t,n,r,i){let a=e.nodes[t];if(!a||!w(a,e.byIndex,i)||M(n,a,e.byIndex))return null;let o=P(a.rect);return!o||u(r,o)||b(e,t,a,i)?null:o}function C(e){return P(e.rect)?e.hittable===!0||O(e)?!0:!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()):!1}function w(e,t,n){return!P(e.rect)||j(e)?!1:k(e,g)||T(e,t,n)}function T(e,t,n){return n.isAdditionalOverlayNode?.(e)===!0?!E(e,t,n):!1}function E(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(D(r,n))return!0;i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function D(e,t){return t.isAdditionalOverlayNode?.(e)===!0&&P(e.rect)!==null&&!j(e)}function O(e){return k(e,_)}function k(e,t){let n=A(e);return t.some(e=>n.includes(e))}function A(e){return[e.type,e.role,e.subrole].map(e=>i(e??``)).join(` `)}function j(e){let t=A(e);return t.includes(`application`)||t.includes(`window`)}function M(e,t,n){return N(e,t,n)||N(t,e,n)}function N(e,t,n){let r=typeof t.parentIndex==`number`?n.get(t.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(r.index===e.index)return!0;i.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}return!1}function P(e){let t=l(e);return t&&t.width>0&&t.height>0?t:null}function F(e){return Array.from(new Set([...e??[],`covered`]))}function I(e){return e?o({packageName:e.bundleId,resourceId:e.identifier}).inputMethodOwned:!1}export{p as a,l as c,m as i,d as l,v as n,h as o,y as r,u as s,I as t,c as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function t(t){let n=l(t.packageName),r=(t.resourceId??``).toLowerCase(),i=l(t.activeInputMethodPackage);if(n&&i&&n===i)return{inputMethodOwned:!0,source:`active-input-method`};if(i&&r.startsWith(`${i}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(n&&e.has(n))return{inputMethodOwned:!0,source:`known-ime-package`};for(let t of e)if(r.startsWith(`${t}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function n(e,n,r){return t({packageName:e,resourceId:n,activeInputMethodPackage:r}).inputMethodOwned}function r(e){return t(e).inputMethodOwned}function i(t){let n=l(t);return!!(n&&e.has(n))}function a(t){let n=(t??``).toLowerCase();for(let t of e)if(n.startsWith(`${t}:id/`))return!0;return!1}function o(e,t,r){return!e&&!t?`unknown`:n(e,t,r)?`ime`:`app`}function s(e){for(let t of[/\bmCurMethodId=([^\s]+)/i,/\bmCurId=([^\s]+)/i,/\bmCurrentInputMethodId=([^\s]+)/i,/\bcurMethodId=([^\s]+)/i]){let n=c(e.match(t)?.[1]);if(n)return n}}function c(e){let t=(e??``).trim();if(t)return l((t.split(`/`)[0]??``).match(/[a-zA-Z0-9_.]+/)?.[0])}function l(e){return(e??``).trim().toLowerCase()||void 0}export{a,i,t as n,s as o,r,o as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{o as t,y as n}from"./sdk-device.js";const r={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`},i={visionos:`visionOS uses spatial input and does not support two-finger touch synthesis.`,tvos:`tvOS has no touch input — this gesture is supported on Android and the iOS simulator only.`,macos:`macOS automation has no multi-touch input — this gesture is supported on Android and the iOS simulator only.`};function a(a,s){if(!t(a.platform))throw o(s,a.platform);let c=n(a);if(!((c===`ios`||c===`ipados`)&&a.kind===`simulator`))throw c===`ios`||c===`ipados`?new e(`UNSUPPORTED_OPERATION`,`gesture ${s} is not supported on physical iOS devices`,{hint:`Two-finger gesture synthesis is iOS-simulator only — not available on physical iOS devices.`}):o(s,r[c],i[c])}function o(t,n,r){return new e(`UNSUPPORTED_OPERATION`,`gesture ${t} is not supported on ${n}`,r===void 0?void 0:{hint:r})}export{a as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e={control:{retryMaxRetries:3},command:{retryTapMaxAttempts:2,targetLookupTimeoutMs:17e3,optionalTargetLookupTimeoutMs:7e3,scrollUntilVisibleTimeoutMs:2e4,waitForAnimationToEndTimeoutMs:15e3,waitForAnimationToEndDifferencePercent:.005,longPressDurationMs:3e3,swipeDurationMs:400,repeatDelayMs:100,scrollUntilVisibleSpeed:40,scrollUntilVisiblePercentage:100,eraseTextMaxCharacters:50},observation:{pollIntervalMs:200,defaultSettleAttempts:10},targetSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9},screenSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9,centerFraction:.5,downStartFraction:.2,upStartFraction:{android:.5,ios:.9}},scrollUntilVisibleSwipe:{nearEdgeFraction:.1,farEdgeFraction:.9}};function t(e){return Math.trunc(1e3*(100-e)/100)+1}const n={assertVisibleTimeoutMs:e.command.targetLookupTimeoutMs,assertNotVisibleTimeoutMs:e.command.targetLookupTimeoutMs,extendedWaitUntilTimeoutMs:e.command.targetLookupTimeoutMs,runFlowConditionTimeoutMs:e.command.optionalTargetLookupTimeoutMs},r=e.observation.pollIntervalMs*e.observation.defaultSettleAttempts;export{t as i,e as n,r,n as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";function t(e,t){return e.includes(t)}function n(n,r,i={}){let a=r===void 0?void 0:i.normalize?.(r)??r;if(a!==void 0&&t(n,a))return a;throw new e(`INVALID_ARGS`,(typeof i.message==`function`?i.message(r):i.message)??`Invalid value: ${r}. Use ${n.join(`|`)}.`)}function r(e,r={}){return{values:e,is:n=>t(e,n),parse:t=>n(e,t,r)}}const i=[`up`,`down`,`left`,`right`,`top`,`bottom`],a=[`up`,`down`,`left`,`right`],o=[`left`,`right`,`left-edge`,`right-edge`],s=[`one-way`,`ping-pong`],c=1e4,l=6e4,u=r(a,{message:e=>`Unknown direction: ${e}`});function d(e){let t=e.direction,n=t===`up`||t===`down`?e.referenceHeight:e.referenceWidth,r=b(e.amount),i=e.pixels===void 0?Math.round(n*r):x(e.pixels),a=Math.max(1,Math.round(n*.05)),o=Math.max(1,n-a*2),s=Math.max(1,Math.min(i,o)),c=Math.round(s/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(n,r,i,a)=>({direction:t,x1:n,y1:r,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:s});switch(t){case`up`:return d(l,u-c,l,u+c);case`down`:return d(l,u+c,l,u-c);case`left`:return d(l-c,u,l+c,u);case`right`:return d(l+c,u,l-c,u)}}function f(e){b(e.amount),e.pixels!==void 0&&x(e.pixels)}function ee(e,t){if(e===`left`||e===`right`){let n=p(e,t);return{preset:e,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,referenceWidth:n.referenceWidth,referenceHeight:n.referenceHeight}}let[n,r]=e===`left-edge`?[99,15]:[1,85],i=g(h(t,n,50),t,8),a=g(h(t,r,50),t,8);return{preset:e,x1:i.x,y1:i.y,x2:a.x,y2:a.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function te(e,t){switch(e){case`up`:return{x:0,y:-t};case`down`:return{x:0,y:t};case`left`:return{x:-t,y:0};case`right`:return{x:t,y:0}}}function p(e,t){let n=e===`left`||e===`up`,r=n?85:15,i=n?15:85,a=e===`up`||e===`down`,o=g(h(t,a?50:r,a?r:50),t,8),s=g(h(t,a?50:i,a?i:50),t,8);return{direction:e,x1:o.x,y1:o.y,x2:s.x,y2:s.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function m(e){let t=_(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}function h(e,t,n){let r=Math.trunc(e.referenceWidth*t/100),i=Math.trunc(e.referenceHeight*n/100);return{x:Number.isFinite(r)?r:0,y:Number.isFinite(i)?i:0}}function g(e,t,n){return{x:S(e.x,n,t.referenceWidth),y:S(e.y,n,t.referenceHeight)}}function ne(e){return u.parse(e)}function _(e){let t=e.filter(e=>v(e.type)&&y(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let n=e.map(e=>e.rect).filter(y);if(n.length===0)return;let r=Math.max(...n.map(e=>e.x+e.width)),i=Math.max(...n.map(e=>e.y+e.height));if(!(r<=0||i<=0))return{x:0,y:0,width:r,height:i}}function v(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`application`)||t.includes(`window`)}function y(e){return!!e&&e.width>0&&e.height>0}function b(t){if(t===void 0)return .6;if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll amount must be a positive number`);return t}function x(t){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(t))}function S(e,t,n){let r=Math.round(t);if(!Number.isFinite(r))return 0;let i=Math.max(r,Math.round(n-t));return!Number.isFinite(i)||!Number.isFinite(e)?r:Math.min(i,Math.max(r,Math.round(e)))}const re={android:`longpress`,apple:`exact`,vega:`exact`},C={up:{aliases:[],androidKeyevent:`KEYCODE_DPAD_UP`,appleRemoteButton:`up`,vegaKey:`KEY_UP`},down:{aliases:[],androidKeyevent:`KEYCODE_DPAD_DOWN`,appleRemoteButton:`down`,vegaKey:`KEY_DOWN`},left:{aliases:[],androidKeyevent:`KEYCODE_DPAD_LEFT`,appleRemoteButton:`left`,vegaKey:`KEY_LEFT`},right:{aliases:[],androidKeyevent:`KEYCODE_DPAD_RIGHT`,appleRemoteButton:`right`,vegaKey:`KEY_RIGHT`},select:{aliases:[`ok`,`center`,`enter`],androidKeyevent:`KEYCODE_DPAD_CENTER`,appleRemoteButton:`select`,vegaKey:`KEY_ENTER`},menu:{aliases:[],androidKeyevent:`KEYCODE_MENU`,appleRemoteButton:`menu`,vegaKey:`KEY_MENU`},home:{aliases:[],androidKeyevent:`KEYCODE_HOME`,appleRemoteButton:`home`,vegaKey:`KEY_HOMEPAGE`},back:{aliases:[],androidKeyevent:`KEYCODE_BACK`,appleRemoteButton:`menu`,vegaKey:`KEY_BACK`}},w=Object.keys(C),T=`<${w.join(`|`)}>`;function E(t){let n=t?.toLowerCase();if(D(n))return n;let r=n?M.get(n):void 0;if(r)return r;throw new e(`INVALID_ARGS`,`tv-remote button must be one of: ${w.join(`, `)}.`)}function D(e){return typeof e==`string`&&w.includes(e)}function O(e){return C[e].appleRemoteButton}function k(e){return C[e].androidKeyevent}function A(e){return C[e].vegaKey}function j(e){return re[e]}const M=new Map(w.flatMap(e=>C[e].aliases.map(t=>[t,e])));function N(t,n){if(t===void 0||t.trim()===``)throw new e(`INVALID_ARGS`,`settings location set requires ${n}`);return F(Number(t),n)}function P(e){return{latitude:F(e?.latitude,`latitude`),longitude:F(e?.longitude,`longitude`)}}function F(t,n){let r=n===`latitude`?-90:-180,i=n===`latitude`?90:180;if(typeof t!=`number`||!Number.isFinite(t)||t<r||t>i)throw new e(`INVALID_ARGS`,`${n} must be a number from ${r} to ${i}`);return t}const I=new Set([`healthy`,`recovered`,`sparse`]),L=new Set([`tree`,`queries`,`private-ax`]),R=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`]);function z(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.state!=`string`||!I.has(t.state))&&!(typeof t.backend!=`string`||!L.has(t.backend)))return{state:t.state,backend:t.backend,reason:typeof t.reason==`string`?t.reason:void 0,reasonCode:typeof t.reasonCode==`string`&&R.has(t.reasonCode)?t.reasonCode:void 0,effectiveDepth:typeof t.effectiveDepth==`number`?t.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(t.collapsedLeafIndexes)?t.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0}}function B(e){return e?.state===`sparse`}function V(e,t){return[...H(e),...U(e),...ie(e,t)]}function H(e){return e.state===`recovered`?[`Detected an overly complex or slow accessibility tree. Fell back to the ${e.backend} snapshot backend. It is OK to continue; use --json to inspect snapshotQuality.reason if you need recovery details.`]:e.state===`sparse`?[`No snapshot backend could read this screen`+(e.reason?` (${e.reason})`:``)+`. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`]:[]}function U(e){return e.effectiveDepth===void 0?[]:[`Some deeper accessibility nodes were omitted; this tree is capped at depth ${e.effectiveDepth}. Re-run with --depth ${e.effectiveDepth} --scope <container> only if you need deeper content.`]}function ie(e,t){let n=[];for(let r of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===r);if(!e)continue;let i=e.identifier?` (${e.identifier})`:``;n.push(`@${e.ref} [${e.type??`element`}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return n}const W=new Set([`empty-helper-output`,`system-window-only`,`content-poor-app-window`]);function G(e){if(!e||typeof e!=`object`)return!1;let t=e.details?.androidSnapshotHelperFailureReason;return typeof t==`string`&&W.has(t)}function K(e){let t=z(e.quality);return{...e.analysis?{analysis:e.analysis}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.freshness?{freshness:e.freshness}:{},...t?{quality:t}:{},...e.warnings?{warnings:e.warnings}:{}}}function q(e){return{...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.quality?{snapshotQuality:e.quality}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function J(e){let t=Y(e.androidSnapshot),n=Array.isArray(e.warnings)?e.warnings.filter(e=>typeof e==`string`):void 0,r=z(e.snapshotQuality);return q({...t?{androidSnapshot:t}:{},...r?{quality:r}:{},...n?{warnings:n}:{}})}function Y(e){return typeof e==`object`&&e?e:void 0}function ae(e){return e}function oe(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)t=Math.min(t,a.x),n=Math.min(n,a.y),r=Math.max(r,a.x+a.width),i=Math.max(i,a.y+a.height);return{x:t,y:n,width:r-t,height:i-n}}function se(e,t){return{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}}function ce(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?0:(i-n)*(a-r)}function le(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function X(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}function ue(e,t,n){return Math.min(Math.max(e,t),n)}const Z=`com.android.systemui`;function de(e){let t=e??``;if(!t.startsWith(`com.android.systemui:id/`))return!1;let n=t.slice(`${Z}:id/`.length);return/(^|_)(status_bar|navigation_bar)(_|$)/.test(n)}function Q(e){return`systemChrome`in e&&e.systemChrome===!0}function $(e){if(!Q(e))return e;let{systemChrome:t,...n}=e;return n}function fe(e){return e.some(Q)?e.map($):e}const pe=1e4;export{a as A,te as B,w as C,O as D,k as E,l as F,ne as H,f as I,p as L,s as M,c as N,A as O,o as P,d as R,P as S,E as T,r as U,m as V,n as W,B as _,fe as a,V as b,se as c,le as d,X as f,K as g,J as h,de as i,i as j,j as k,ce as l,q as m,Z as n,$ as o,oe as p,Q as r,ue as s,pe as t,ae as u,G as v,T as w,N as x,z as y,ee as z};
|
package/dist/src/gesture-plan.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{B as t,t as n,z as r}from"./gesture-plan-types.js";const i={pinchAxisDegrees:-90,frameCount:Math.floor},a={ios:i,macos:i,android:{pinchAxisDegrees:0,frameCount:Math.round},vega:i,linux:i,web:i};function o(e,t,n){let r=v(t),i=k(n);switch(e.intent){case`fling`:return c(e,r,i);case`pan`:return l(e,r,i);case`pinch`:return d({intent:`pinch`,origin:e.origin??T(r),delta:{x:0,y:0},scale:C(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=S(e.degrees,`gesture rotate degrees`);return d({intent:`rotate`,origin:e.origin??T(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:b(t)},r,i)}case`transform`:{let t=S(e.degrees,`gesture transform degrees`);return d({intent:`transform`,origin:e.origin,delta:e.delta,scale:C(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:y(e.durationMs,b(t),`gesture transform durationMs`)},r,i)}}}function s(t){let n=t.pointers[0].samples[0]?.point,r=t.pointers[0].samples.at(-1)?.point;if(!n||!r)throw new e(`INVALID_ARGS`,`single-pointer gesture plan requires samples`);return{start:n,end:r}}function c(e,n,r){if(`preset`in e){let{from:t,to:i}=O(e.preset,n);return u(`fling`,t,i,100,n,`endpoint-hold`,r)}if(`from`in e)return u(`fling`,e.from,e.to,100,n,`endpoint-hold`,r);let i=x(e.origin,`gesture fling origin`),a=w(e.distance??180,`gesture fling distance`);return u(`fling`,i,E(i,t(e.direction,a)),100,n,`endpoint-hold`,r)}function l(t,n,r){let i=y(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=x(t.origin,`gesture pan origin`);return u(`pan`,e,E(e,x(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`,r)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return d({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function u(e,t,n,r,i,a,o){let s=x(t,`gesture ${e} start`),c=x(n,`gesture ${e} end`),l=h(r,o).map(e=>({offsetMs:e,point:D(s,c,e/r)}));return g(l,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:l}]}}function d(e,t,n){let r=x(e.origin,`gesture ${e.intent} origin`),i=E(r,x(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*m(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw _({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=h(e.durationMs,n),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:f({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return g(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function f(e){let t=e.offsetMs/e.durationMs,n=D(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=A(p(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function p(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function m(e){return e===`pinch`?.4:.25}function h(e,t){let n=e/16,r=Math.max(3,t.frameCount(n));return Array.from({length:r+1},(t,n)=>Math.round(e*n/r))}function g(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw _({...r,viewport:n,sample:o})}}function _(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function v(t){let n={x:S(t.x,`gesture viewport x`),y:S(t.y,`gesture viewport y`),width:S(t.width,`gesture viewport width`),height:S(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function y(t,r,i){let a=t??r;if(!Number.isInteger(a)||a<16||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 16 and ${n}`);return a}function b(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function x(e,t){return{x:S(e.x,`${t} x`),y:S(e.y,`${t} y`)}}function S(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function C(t,n){let r=S(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function w(t,n){let r=S(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function T(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function E(e,t){return{x:e.x+t.x,y:e.y+t.y}}function D(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function O(e,t){let n=r(e,{referenceWidth:t.width,referenceHeight:t.height});return{from:{x:t.x+n.x1,y:t.y+n.y1},to:{x:t.x+n.x2,y:t.y+n.y2}}}function k(e){return e===void 0?i:a[e]}function A(e){return e*Math.PI/180}export{s as n,o as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=`--launch-console is supported only for iOS simulator app launches`,t=`--launch-console requires a direct app launch and cannot be used with URL opens`;export{e as n,t};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{S as e,T as t,_ as n,d as r,f as i,g as a,p as o,u as s}from"./sdk-contracts.js";import{$ as c,A as l,J as u,Q as d,T as f,X as p,Y as m,Z as h}from"./sdk-batch-runner.js";import{d as g}from"./sdk-device.js";import{$ as ee,F as te,G as ne,J as re,K as ie,P as ae,Q as oe,U as se,W as ce,Y as le,Z as ue,a as de,at as fe,c as pe,d as me,et as he,g as ge,h as _e,lt as ve,n as ye,nt as be,o as xe,p as Se,q as Ce,r as we,rt as _,s as v,st as Te,t as Ee,tt as De,u as Oe,z as ke}from"./sdk-selectors.js";import{A as Ae,P as je,U as y,_ as Me,i as Ne,l as Pe,m as Fe,r as Ie,t as Le}from"./gesture-plan-types.js";import{a as Re,c as b,r as x,s as ze,t as Be,u as S}from"./android-input-method-overlays.js";import{createHash as Ve}from"node:crypto";import He from"node:path";import{styleText as Ue}from"node:util";const We=Xe(`public`),Ge=Xe(`internal`),Ke=Xe(`local-cli`),qe={help:`help`};function Je(){return[...Object.values(We),...Object.values(Ke)].sort()}function Ye(e){return Object.values(qe).includes(e)||Object.values(Ge).includes(e)?!0:Je().includes(e)}function Xe(e){let t={};for(let[n,r]of l(e))t[n]=r;return t}const Ze=[`out`,`overlayRefs`,`screenshotPixelDensity`,`screenshotFullscreen`,`screenshotMaxSize`,`screenshotNoStabilize`,`screenshotNormalizeStatusBar`],Qe=[`screenshotPixelDensity`,`screenshotFullscreen`,`screenshotMaxSize`,`screenshotNoStabilize`,`screenshotNormalizeStatusBar`],$e=[{key:`screenshotPixelDensity`,names:[`--pixel-density`],type:`int`,min:1,usageLabel:`--pixel-density <n>`,usageDescription:`Screenshot: output PNG pixel density in pixels per logical point (currently supported on iOS simulators)`},{key:`screenshotFullscreen`,names:[`--fullscreen`,`--full`,`-f`],type:`boolean`,usageLabel:`--fullscreen, --full, -f`,usageDescription:`Screenshot: on web capture the full page; on macOS app sessions capture the full desktop instead of the app window`},{key:`screenshotMaxSize`,names:[`--max-size`],type:`int`,min:1,usageLabel:`--max-size <px>`,usageDescription:`Screenshot/record: downscale so the longest edge is at most <px>`},{key:`screenshotNoStabilize`,names:[`--no-stabilize`],type:`boolean`,usageLabel:`--no-stabilize`,usageDescription:`Screenshot: skip Android demo-mode/status-bar stabilization and settle delay for low-latency capture loops`},{key:`screenshotNormalizeStatusBar`,names:[`--normalize-status-bar`],type:`boolean`,usageLabel:`--normalize-status-bar`,usageDescription:`Screenshot: on iOS simulators temporarily normalize status-bar chrome for deterministic screenshot diffs`}],et=[{tokens:[`--fullscreen`,`--full`,`-f`],key:`screenshotFullscreen`},{tokens:[`--no-stabilize`],key:`screenshotNoStabilize`},{tokens:[`--normalize-status-bar`],key:`screenshotNormalizeStatusBar`}],tt=[{token:`--pixel-density`,key:`screenshotPixelDensity`,label:`screenshot --pixel-density`},{token:`--max-size`,key:`screenshotMaxSize`,label:`screenshot --max-size`}];function nt(e){return ot({overlayRefs:e?.overlayRefs,pixelDensity:e?.screenshotPixelDensity,fullscreen:e?.screenshotFullscreen,maxSize:e?.screenshotMaxSize,stabilize:e?.screenshotNoStabilize?!1:void 0,normalizeStatusBar:e?.screenshotNormalizeStatusBar})}function rt(e={}){return ot({overlayRefs:e.overlayRefs,screenshotPixelDensity:e.screenshotPixelDensity??e.pixelDensity,screenshotFullscreen:e.screenshotFullscreen??e.fullscreen,screenshotMaxSize:e.screenshotMaxSize??e.maxSize,screenshotNoStabilize:e.screenshotNoStabilize??(e.stabilize===!1?!0:void 0),screenshotNormalizeStatusBar:e.screenshotNormalizeStatusBar??e.normalizeStatusBar})}function it(e,t){typeof t?.screenshotPixelDensity==`number`&&e.push(`--pixel-density`,String(t.screenshotPixelDensity)),t?.screenshotFullscreen&&e.push(`--fullscreen`),typeof t?.screenshotMaxSize==`number`&&e.push(`--max-size`,String(t.screenshotMaxSize)),t?.screenshotNoStabilize&&e.push(`--no-stabilize`),t?.screenshotNormalizeStatusBar&&e.push(`--normalize-status-bar`)}function at(e){let{args:t,flags:n,index:r}=e,i=t[r];return st(i,n,r)??ct({args:t,index:r,flags:n,token:i})??{handled:!1}}function ot(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function st(e,t,n){let r=et.find(t=>t.tokens.some(t=>t===e));if(r)return t[r.key]=!0,{handled:!0,nextIndex:n}}function ct(e){let t=tt.find(t=>t.token===e.token);if(!t)return;let r=e.args[e.index+1],i=r===void 0?NaN:Number(r);if(!Number.isInteger(i)||i<1)throw new n(`INVALID_ARGS`,`${t.label} requires a positive integer`);return e.flags[t.key]=i,{handled:!0,nextIndex:e.index+1}}function C(e){return e?{message:e}:{}}function lt(e,t){return t?{...e,message:t}:e}function ut(e){return typeof e?.message==`string`&&e.message.length>0?e.message:null}const dt=[`in-app`,`system`],ft=[`app`,`device`,`system`];function pt(e){return e===`device`||e===`system`}const mt=[`app`,`frontmost-app`,`desktop`,`menubar`],ht=y(mt,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${mt.join(`|`)}.`});function gt(e){return ht.parse(e)}const _t=[`primary`,`secondary`,`middle`];function vt(e){return e?.clickButton??`primary`}function yt(e){return e.button===`primary`?null:e.commandLabel===`click`?e.platform!==`macos`&&e.platform!==`linux`?new n(`UNSUPPORTED_OPERATION`,`click --button ${e.button} is supported only on macOS and Linux`):e.platform===`macos`&&e.button===`middle`?new n(`UNSUPPORTED_OPERATION`,`click --button middle is not supported by the macOS runner yet`):typeof e.count==`number`||typeof e.intervalMs==`number`||typeof e.holdMs==`number`||typeof e.jitterPx==`number`||e.doubleTap===!0?new n(`INVALID_ARGS`,`click --button ${e.button} does not support repeat or gesture modifier flags`):null:new n(`INVALID_ARGS`,`--button is supported only for click`)}function bt(e){return e===`primary`?{}:{button:e}}const xt=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`];function St(e){if(e===void 0)throw new n(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(e?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new n(`INVALID_ARGS`,`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}function w(e){return e.width>0&&e.height>0}function Ct(e,t){return!e||!t?!1:e.x>=t.x-2&&e.y>=t.y-2&&e.x+e.width<=t.x+t.width+2&&e.y+e.height<=t.y+t.height+2}function wt(e,t){if(!e||!t)return!0;let n=e.y+e.height/2,r=t.y+t.height/2;return Math.abs(n-r)<=Math.max(e.height,t.height,1)}function Tt(e){return typeof e.parentIndex!=`number`}function T(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function Et(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function E(e){let t=ve(e);if(!t||t!==e.identifier?.trim()||!Dt(t))return t;let n=(e.type??``).toLowerCase();return n.includes(`view`)||n.includes(`layout`)||n.includes(`image`)||n.includes(`list`)||n.includes(`recyclerview`)||n.includes(`collection`)?``:t}function D(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function Dt(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Ot(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){let e=t.get(r.parentIndex);if(!e)return null;if(n(e))return e;r=e}return null}function kt(e,t){let n=[],r=[t];for(;r.length>0;){let t=r.pop();for(let i of e)i.parentIndex===t&&(n.push(i),r.push(i.index))}return n}function O(e,t,n){let r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let i of e)i.parentIndex!==t||n.has(i.index)||r.push(i.index)}}}const At=[`button`,`switch`,`checkbox`,`radio`],jt=[`button`,`image`,`textview`,`view`];function Mt(e,t,n){for(let r of e){if(t.has(r.index)||!Ft(r))continue;let i=It(kt(e,r.index),r,t);if(i.label){n.set(r.index,{...r,...n.get(r.index),label:i.label});for(let n of i.removableIndexes)O(e,n,t)}}}function Nt(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Ut(i))continue;let a=D(E(i));if(!a)continue;let o=r.get(a);if(o&&Bt(o,i,t)){let s=Vt(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Pt(e,t){for(let n of e){if(t.has(n.index)||!Rt(n))continue;let r=D(E(n));if(!r)continue;let i=kt(e,n.index).filter(e=>!t.has(e.index)&&zt(n,e,r));for(let n of i.filter(Lt))O(e,n.index,t);let a=i.filter(e=>!Lt(e)),o=new Set(a.map(e=>D(E(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)O(e,n.index,t)}}function Ft(e){return e.hittable===!0&&!T(e)&&!!(e.rect&&w(e.rect))&&E(e).trim().length===0}function It(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!Lt(o)||!Ct(o.rect,t.rect))continue;let e=E(o).trim().replace(/\s+/g,` `),s=D(e);i.push(o.index),!(!e||!s||a.has(s))&&(a.add(s),r.push(e))}return{label:r.join(`, `),removableIndexes:i}}function Lt(e){if(e.hittable===!0||T(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Rt(e){return e.hittable===!0&&!T(e)&&!!(e.rect&&w(e.rect))&&!!D(E(e))}function zt(e,t,n){if(!Ut(t)||!Ct(t.rect,e.rect))return!1;let r=D(E(t));return!!(r&&n!==r&&n.includes(r))}function Bt(e,t,n){return!n.has(e.index)&&wt(e.rect,t.rect)&&(Jt(e,t)||qt(e,t))}function Vt(e,t,n,r,i){let a=Wt(t,n),o=a.index===t.index?n:t,s=(o.type??``).toLowerCase().includes(`image`)?`has image`:null,c=i.get(a.index)??a,l=i.get(o.index)?.presentationHints??o.presentationHints;return i.set(a.index,{...c,presentationHints:Ht(c.presentationHints,l,s)}),O(e,o.index,r),i.get(a.index)??a}function Ht(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Ut(e){if(!e.rect||!w(e.rect)||Tt(e)||T(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||Kt(t,jt)}function Wt(e,t){let n=Gt(e);return Gt(t)>n?t:e}function Gt(e){let t=(e.type??``).toLowerCase(),n=0;return Kt(t,At)?n+=100:t.includes(`image`)?n+=30:t.includes(`textview`)||t===`text`?n+=20:t.includes(`view`)&&(n+=10),e.hittable===!0&&(n+=20),e.enabled!==!1&&(n+=5),n}function Kt(e,t){return t.some(t=>e.includes(t))}function qt(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!n||!r?!1:Wt(n,r).index===n.index}function Jt(e,t){return e.parentIndex===t.parentIndex?Math.abs(e.index-t.index)<=3:e.parentIndex===t.index||t.parentIndex===e.index?!1:Math.abs((e.depth??0)-(t.depth??0))<=1&&Math.abs(e.index-t.index)<=2}function Yt(e,t,n){if(n.raw||!Xt(e))return{nodes:t,filteredCount:0};let r=Zt(t);return{nodes:r,filteredCount:t.length-r.length}}function Xt(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function Zt(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return Qt(e,t),$t(e,r,t,n),Mt(e,t,n),Pt(e,t),Nt(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function Qt(e,t){for(let n of e)!n.rect||w(n.rect)||Tt(n)||O(e,n.index,t)}function $t(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||Tt(i))continue;let a=Ot(i,t,Et);a&&tn(r,a,en(i,e)),O(e,i.index,n)}}function en(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&w(t.rect)).map(e=>e.index);return n.length===0?null:e.index<Math.min(...n)?`above`:e.index>Math.max(...n)?`below`:null}function tn(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:r.hiddenContentAbove===!0||n===`above`?!0:void 0,hiddenContentBelow:r.hiddenContentBelow===!0||n===`below`?!0:void 0})}function nn(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||rn(t)?null:t}function rn(e){return/\S+@\S+\.\S+/.test(e)}function an(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=nn(ve(n));if(!r)continue;let i=`${e}|${r}`,a=t.get(i)??[];a.push(n),t.set(i,a)}let n=0;for(let e of t.values())e.length<=1||!on(e)||(n+=e.length);return n>=8}function on(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(sn(e[t]?.rect,e[n]?.rect))return!0;return!1}function sn(e,t){if(!e||!t)return!0;let n=.5;return!(e.x+e.width<=t.x+n||t.x+t.width<=e.x+n||e.y+e.height<=t.y+n||t.y+t.height<=e.y+n)}const cn={digest:8*1024,default:24*1024,full:64*1024};function ln(e){return e===`digest`||e===`full`?e:`default`}function un(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function k(e,n=256){return un(t(e),n)}function dn(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function fn(e){return(t,n)=>k(dn(t,e),n)}function pn(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function mn(e,t){let n=ln(t),r=n===`digest`?8:20,i=pn(e.screen,r),a=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:i,suggestions:a}}function hn(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function gn(e){let{divergence:t,level:n,writeOverflowArtifact:r}=e,i=ln(n),a=cn[i],o=mn(t,n),s=hn(o);if(s<=a)return o;let c=s-a,l=r(mn(t,`full`)),u=_n(o);return`artifactPath`in l?{...u,overflow:{omittedBytes:c,artifactPath:l.artifactPath}}:{...u,artifactUnavailable:!0}}function _n(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:k(e.step.source.path),line:e.step.source.line}},action:k(e.action),cause:{code:e.cause.code,message:k(e.cause.message),...e.cause.hint?{hint:k(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function vn(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...An(n.step),...En(n.kind,n.targetBinding),...yn(n.repairHint,n.resume),...jn(n.screen),...Fn(n.suggestions,n.suggestionCount),...Ln(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
|
|
2
|
-
`):null}function yn(e,t){if(typeof e!=`string`)return[];let n=Sn(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function bn(e){let t=e;if(!t||typeof t.allowed!=`boolean`)return;if(!t.allowed)return{allowed:!1,reason:typeof t.reason==`string`?t.reason:void 0};let{from:n,planDigest:r,alternateFrom:i}=t;if(!(typeof n!=`number`||typeof r!=`string`||r.length===0))return{allowed:!0,from:n,planDigest:r,alternateFrom:typeof i==`number`?i:void 0}}function A(e,t){return`replay --from ${e} --plan-digest ${t}`}function xn(e){return e?.repairSessionHeld===!0}function Sn(e,t){let n=Cn(e,bn(t));if(n!==void 0)return xn(t)?`${n} Read-only inspection while armed (snapshot -i, get attrs, find, is) is excluded from the healed script by default — no --no-record needed. If the step you are repairing is itself a read, add --record to that command so it lands in the heal.`:n}function Cn(e,t){switch(e){case`record-and-heal`:return t?.allowed?`press the correct control via a blessed @ref from screen.refs (recorded), then ${A(t.from,t.planDigest)}.`:`press the correct control via a blessed @ref from screen.refs (recorded). ${Tn(t)}`;case`state-repair`:return t?.allowed?`fix app state with --no-record actions, then ${A(t.from,t.planDigest)} to re-run it.`:`fix app state with --no-record actions. ${Tn(t)}`;case`caution`:return wn({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return wn({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function wn(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${Tn(n)}`;let r=`if you fixed app state with --no-record actions: ${A(n.from,n.planDigest)}`;return n.alternateFrom===void 0?`${t} ${r}.`:`${t} ${r}; ${`if you performed the step's intent as a recorded action: ${A(n.alternateFrom,n.planDigest)}`}.`}function Tn(e){return e&&!e.allowed&&e.reason?`This step cannot currently be resumed automatically (${e.reason}) — run a fresh full replay instead.`:`This step cannot currently be resumed automatically — run a fresh full replay instead.`}function En(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[Dn(e,n.matchCount),...On(n.mismatches),...kn(n.candidates)]:[]}function Dn(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function On(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function kn(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${Pn(e)}`)]}function An(e){let t=e;if(typeof t?.index!=`number`)return[];let n=t.source,r=typeof n?.path==`string`&&typeof n.line==`number`?` (${n.path}:${n.line})`:``;return[`Divergence at step ${t.index}${r}`]}function jn(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?Mn(t.refs,t.refsGeneration):t?.state===`unavailable`?[Nn(t)]:[]}function Mn(e,t){let n=e.slice(0,8).map(Pn),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function Nn(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function Pn(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function Fn(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(In)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function In(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function Ln(e,t){return e&&typeof e==`object`?[`Full report written to ${String(e.artifactPath)}.`]:t===!0?[`Full report exceeded the response budget and the overflow artifact could not be written.`]:[]}const Rn={application:`application`,navigationbar:`navigation-bar`,tabbar:`tab-bar`,button:`button`,imagebutton:`button`,link:`link`,cell:`cell`,statictext:`text`,checkedtextview:`text`,textbox:`text-field`,textfield:`text-field`,edittext:`text-field`,textarea:`text-view`,switch:`switch`,slider:`slider`,image:`image`,imageview:`image`,webview:`webview`,framelayout:`group`,linearlayout:`group`,relativelayout:`group`,constraintlayout:`group`,viewgroup:`group`,view:`group`,listview:`list`,recyclerview:`list`,collectionview:`collection`,searchfield:`search`,heading:`heading`,activityindicator:`activity-indicator`,progressindicator:`progress-indicator`,segmentedcontrol:`segmented-control`,group:`group`,window:`window`,checkbox:`checkbox`,radio:`radio`,menuitem:`menu-item`,toolbar:`toolbar`,scrollarea:`scroll-area`,scrollview:`scroll-area`,nestedscrollview:`scroll-area`,table:`table`};function zn(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||``,o=M(i.type??`Element`),s=i.inheritsLabel===!0||i.inheritsIdentifier===!0;if(o===`group`&&!a&&!s)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let c=n.length;n.push(e),r.push({node:i,depth:c,type:o,text:Bn(i,c,!1,o,t)})}return r}function Bn(e,t,n,r,i={}){let a=r??M(e.type??`Element`),o=De(e,a),s=Gn(e,a,i,o),c=` `.repeat(t),l=e.ref?`@${e.ref}`:``,u=Kn(e,a,i,o);!s&&(e.inheritsLabel===!0||e.inheritsIdentifier===!0)&&u.push(`same label as parent`);let d=u.map(e=>` [${e}]`).join(``),f=s?` "${s}"`:``;return n?`${c}${l} [${a}]${d}`.trimEnd():`${c}${l} [${a}]${f}${d}`.trimEnd()}function j(e,t){let n=e.label?.trim();if(n&&Un(t,n))return``;let r=e.value?.trim();if(Hn(t)){if(r)return r;if(n)return n}else if(n)return n;if(r)return r;let i=e.identifier?.trim();return!i||Wn(i)&&(t===`group`||t===`image`||t===`list`||t===`collection`)?``:i}function M(e){let t=e,n=e.replace(/XCUIElementType/gi,``).toLowerCase(),r=t.includes(`.`)&&(t.startsWith(`android.`)||t.startsWith(`androidx.`)||t.startsWith(`com.`));return n.includes(`.`)&&(n=n.replace(/^android\.widget\./,``).replace(/^android\.view\./,``).replace(/^android\.webkit\./,``).replace(/^androidx\./,``).replace(/^com\.google\.android\./,``).replace(/^com\.android\./,``),r&&n.includes(`.`)&&(n=n.slice(n.lastIndexOf(`.`)+1))),n===`textview`?r?`text`:`text-view`:Vn(n)||n||`element`}function Vn(e){return Object.prototype.hasOwnProperty.call(Rn,e)?Rn[e]:void 0}function Hn(e){return e===`text-field`||e===`text-view`||e===`search`}function Un(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:Te(t)}function Wn(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Gn(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?j(e,t):qn(e,t,r.text)||j(e,t)}function Kn(e,t,n,r){let i=[];return e.enabled===!1&&i.push(`disabled`),i.push(...e.presentationHints??[]),!n.summarizeTextSurfaces||(e.selected===!0&&i.push(`selected`),e.focused===!0&&i.push(`focused`),Hn(t)&&i.push(`editable`),Jn(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?Xn(i):(i.push(`preview:"${Yn(he(r.text))}"`),i.push(`truncated`),Xn(i))}function qn(e,t,n){let r=fe(e.label);if(r&&r!==n)return r;let i=fe(e.identifier);if(i&&!Wn(i)&&i!==n)return i;switch(t){case`text`:case`text-view`:return`Text view`;case`text-field`:return`Text field`;case`search`:return`Search field`;default:return``}}function Jn(e,t){if(t===`scroll-area`)return!0;let n=(e.type??``).toLowerCase(),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`scroll`)||r.includes(`scroll`)}function Yn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Xn(e){return[...new Set(e)]}function Zn(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function Qn(t,r={}){let i=t instanceof n?e(t):t;process.stderr.write(`Error (${i.code}): ${i.message}\n`),i.hint&&process.stderr.write(`Hint: ${i.hint}\n`),i.diagnosticId&&process.stderr.write(`Diagnostic ID: ${i.diagnosticId}\n`),i.logPath&&process.stderr.write(`Diagnostics Log: ${i.logPath}\n`);let a=vn(i.details);a&&process.stderr.write(`${a}\n`),r.showDetails&&i.details&&process.stderr.write(`${JSON.stringify(i.details,null,2)}\n`)}function $n(e,t={}){let n=e.nodes,r=Array.isArray(n)?n:[],o=a(i(e.backend)?e.backend:void 0),s=Yt(e,r,t),c=rr(e),l=Ar(e,r,t,s),u=l.length>0?`${l.join(`
|
|
3
|
-
`)}\n`:``,d=t.raw?null:er(e);if(d)return`${c}${u}${tr(d)}\n`;let f=t.raw||!o?null:se(s.nodes),p=!!e.truncated,m=f?.nodes??r,h=t.raw||!o?null:lr(e,f,m.length,r.length,s.filteredCount),g=ir(r.length,h,p);return r.length===0?`${c}${g}\n${u}`:t.raw?`${c}${g}\n${u}${ar(r)}\n`:t.flatten?`${c}${g}\n${u}${or(m)}${cr(f)}\n`:`${c}${g}\n${u}${sr(m)}${cr(f)}\n`}function er(e){let t=e.unchanged;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.ageMs!=`number`||typeof n.nodeCount!=`number`?null:{ageMs:n.ageMs,nodeCount:n.nodeCount,interactiveOnly:n.interactiveOnly===!0?!0:void 0,scope:typeof n.scope==`string`?n.scope:void 0}}function tr(e){let t=nr(e.ageMs);return e.scope?[`Scoped snapshot unchanged for scope "${e.scope}" since previous read ${t} ago.`,`Previous refs in this scope remain valid. Use find/get/is for a targeted query, or --force-full to re-emit.`].join(`
|
|
4
|
-
`):e.interactiveOnly?[`Interactive snapshot unchanged since previous read ${t} ago.`,`${e.nodeCount} visible nodes are unchanged. Previous @e refs are still valid. Use find/get/is for a targeted query, or --force-full to re-emit.`].join(`
|
|
5
|
-
`):[`Snapshot unchanged since previous read ${t} ago.`,`Refs from the previous snapshot are still valid. Use --force-full to re-emit the tree, or use find/get/is for a targeted query.`].join(`
|
|
6
|
-
`)}function nr(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(Math.round(e/100)/10).toFixed(1)}s`;let t=e/6e4;if(t<60)return`${(Math.round(t*10)/10).toFixed(1)}m`;let n=t/60;return`${(Math.round(n*10)/10).toFixed(1)}h`}function rr(e){let t=typeof e.appName==`string`?e.appName:void 0,n=typeof e.appBundleId==`string`?e.appBundleId:void 0,r=[];return t&&r.push(`Page: ${t}`),n&&r.push(`App: ${n}`),r.length>0?`${r.join(`
|
|
7
|
-
`)}\n`:``}function ir(e,t,n){let r=n?` (truncated)`:``;return t?.partial?t.totalNodeCount>t.visibleNodeCount?`Snapshot: ${t.visibleNodeCount} visible nodes (${t.totalNodeCount} total)${r}`:`Snapshot: ${t.visibleNodeCount} visible nodes${r}`:`Snapshot: ${e} nodes${r}`}function ar(e){return e.map(e=>JSON.stringify(e)).join(`
|
|
8
|
-
`)}function or(e){return Rr(e).join(`
|
|
9
|
-
`)}function sr(e){return Fr(zn(e,{summarizeTextSurfaces:!0})).join(`
|
|
10
|
-
`)}function cr(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
|
|
11
|
-
`)}`:``}function lr(e,t,n,r,i=0){let a=ur(e);if(i===0&&a)return a;let o=(t?.hiddenCount??0)+i,s=t?t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow):!1;return o>0?{partial:!0,visibleNodeCount:n,totalNodeCount:Math.max(r,a?.totalNodeCount??r),reasons:dr([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function ur(e){let t=e.visibility;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.partial!=`boolean`||typeof n.visibleNodeCount!=`number`||typeof n.totalNodeCount!=`number`||!Array.isArray(n.reasons)?null:{partial:n.partial,visibleNodeCount:n.visibleNodeCount,totalNodeCount:n.totalNodeCount,reasons:n.reasons.filter(e=>typeof e==`string`)}}function dr(e){return[...new Set(e)]}function fr(e){let t=e.baselineInitialized===!0,n=e.summary??{},r=P(n.additions),i=P(n.removals),a=P(n.unchanged),o=F(),s=Pr(e),c=s.length>0?`${s.join(`
|
|
12
|
-
`)}\n`:``;if(t)return`${c}Baseline initialized (${a} lines).\n`;let l=kr(Array.isArray(e.lines)?e.lines:[],1).map(e=>{let t=typeof e.text==`string`?e.text:``;if(e.kind===`added`){let e=t.startsWith(` `)?`+${t}`:`+ ${t}`;return o?I(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return o?I(e,`red`):e}return o?I(t,`dim`):t}),u=l.length>0?`${l.join(`
|
|
13
|
-
`)}\n`:``;return o?`${c}${u}${[`${I(String(r),`green`)} additions`,`${I(String(i),`red`)} removals`,`${I(String(a),`dim`)} unchanged`].join(`, `)}\n`:`${c}${u}${r} additions, ${i} removals, ${a} unchanged\n`}function pr(e){let t=F(),n=e.match===!0,r=e.dimensionMismatch,i=[];return i.push(...mr(e,t)),i.push(...hr(e,n,t)),!n&&!r&&(i.push(...gr(e,t)),i.push(..._r(e,t)),i.push(...vr(e,t)),i.push(...br(e,t)),i.push(...xr(e,t))),`${i.join(`
|
|
14
|
-
`)}\n`}function mr(e,t){if(e.match===!0)return[`${t?I(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?I(`✗`,`red`):`✗`;if(n){let e=n.expected,t=n.actual;return[`${r} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let i=P(e.differentPixels),a=P(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?I(o,`red`):o}`]}function hr(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=Or(e.diffPath),i=n?I(`Diff image:`,`dim`):`Diff image:`,a=n?I(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=Or(e.currentOverlayPath),i=n?I(`Current overlay:`,`dim`):`Current overlay:`,a=n?I(t,`green`):t,o=P(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function gr(e,t){let n=P(e.differentPixels),r=P(e.totalPixels);return[` ${t?I(String(n),`red`):String(n)} different / ${r} total pixels`]}function _r(e,t){let n=Cr(e);return n.length===0?[]:[` ${L(`Hints:`,t)}`,...n.map(e=>` - ${e}`)]}function vr(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${L(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...yr(e));return r}function yr(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. ${e.location} x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff, change=${e.dominantChange}`],i=Dr(e);i&&r.push(` ${i}`);let a=e.currentOverlayMatches?.[0];if(a){let e=a.label?` "${a.label}"`:``;r.push(` overlaps @${a.ref}${e}, ${a.regionCoveragePercentage}% of region`)}return r}function br(e,t){let n=e.ocr?.matches??[];if(n.length===0)return[];let r=n.slice(0,8),i=[` ${L(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${n.length}; px):`,t)}`,` ${L(`item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint`,t)}`];for(let[e,t]of r.entries()){let n=t.delta;i.push(` ${e+1} | ${JSON.stringify(t.text)} | ${N(n.x)},${N(n.y)} | ${N(n.width)},${N(n.height)} | ${Sr(t.baselineRect)} | ${Sr(t.currentRect)} | ${t.confidence} | ${t.possibleTextMetricMismatch?`ocr-bbox-size-change`:`-`}`)}return i}function xr(e,t){let n=e.nonTextDeltas??[];if(n.length===0)return[];let r=n.slice(0,8),i=[` ${L(`Non-text visual deltas (showing ${r.length}/${n.length}; px):`,t)}`,` ${L(`item | region | slot | kind | bboxCurrent | nearestText`,t)}`];for(let e of r)i.push(` ${e.index} | ${e.regionIndex?`r${e.regionIndex}`:`-`} | ${e.slot} | ${e.likelyKind} | ${Sr(e.rect)} | ${e.nearestText?JSON.stringify(e.nearestText):`-`}`);return i}function Sr(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function N(e){return e>0?`+${e}`:String(e)}function Cr(e){let t=[],n=e.ocr?.movementClusters??[];for(let e of n.slice(0,2))t.push(`text movement cluster: ${Er(e.texts)} dx=${Tr(e.xRange)}px dy=${Tr(e.yRange)}px`);let r=(e.nonTextDeltas??[]).filter(e=>[`icon`,`toggle`,`chevron`].includes(e.likelyKind)).slice(0,3);r.length>0&&t.push(`non-text controls: ${r.map(wr).join(`; `)}`);let i=(e.nonTextDeltas??[]).filter(e=>e.likelyKind===`separator`).slice(0,2);return i.length>0&&t.push(`non-text boundaries: ${i.map(wr).join(`; `)}`),t.slice(0,6)}function wr(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:``,n=e.regionIndex?` r${e.regionIndex}`:``;return`${e.likelyKind}${t}${n}`}function Tr(e){return e.min===e.max?N(e.min):`${N(e.min)}..${N(e.max)}`}function Er(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),n=e.length>t.length?` +${e.length-t.length} more`:``;return`${t.join(`, `)}${n}`}function Dr(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,typeof e.densityPercentage==`number`?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,typeof e.baselineLuminance==`number`&&typeof e.currentLuminance==`number`?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>e!==null);return t.length>0?t.join(` `):null}function Or(e){let t=process.cwd(),n=He.relative(t,e);return n===``||!n.startsWith(`..`)&&!He.isAbsolute(n)?n===``?`.`:`.${He.sep}${n}`:e}function P(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function kr(e,t){if(e.length===0)return e;let n=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>e.kind===`added`||e.kind===`removed`).map(e=>e.index);if(n.length===0)return e;let r=Array(e.length).fill(!1);for(let i of n){let n=Math.max(0,i-t),a=Math.min(e.length-1,i+t);for(let e=n;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])}function F(e=process.stdout){let t=process.env.FORCE_COLOR;return typeof t==`string`?t!==`0`:typeof process.env.NO_COLOR==`string`?!1:!!e.isTTY}function I(e,t,n){return Ue(t,e,n)}function L(e,t){return t?I(e,`dim`):e}function Ar(e,t,n,r={nodes:t,filteredCount:0}){let i=Pr(e);if(jr(e)){let e=Nr(t,n);e&&i.push(e)}!n.raw&&r.filteredCount>0&&i.push(`Collapsed ${r.filteredCount} Android helper node${r.filteredCount===1?``:`s`} from the agent-facing text snapshot; use --raw or --json for the full hierarchy.`);let a=r.filteredCount>0?r.nodes:t;return!n.raw&&an(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function jr(e){return!e.snapshotQuality&&!Mr(e)}function Mr(e){let t=e.snapshotDiagnostics;if(!t||typeof t!=`object`)return!1;let n=t.stats;return!!(n&&typeof n==`object`&&n.platform===`web`)}function Nr(e,t){if(t.scoped===!0||t.depthLimited===!0||e.length>3)return null;let n=e.length===1?`node`:`nodes`;return`Hint: sparse accessibility snapshot returned ${e.length} ${n}; snapshot state is invalid or unavailable for this screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth. If screenshot shows the Home Screen or another app, run open for this app again first. Then navigate away with coordinates if needed and retry snapshot -i on the next screen.`}function Pr(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0):[]}function Fr(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||Ir(e,n[n.length-1],r));)t.push(...zr(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...zr(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function Ir(e,t,n){return Lr(e.node,t.node,n)?!1:e.depth<=t.depth}function Lr(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){if(r.parentIndex===t.index)return!0;let e=n.get(r.parentIndex);if(!e)return!1;r=e}return!1}function Rr(e){return zn(e,{summarizeTextSurfaces:!0}).flatMap(e=>[Bn(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...zr({...e,depth:0})])}function zr(e,t){let n=Br(e.type);if(!n)return[];let r=[];if(e.node.hiddenContentAbove&&t!==`below`&&r.push(`[content above ${n} hidden]`),e.node.hiddenContentBelow&&t!==`above`&&r.push(`[content below ${n} hidden]`),r.length===0)return[];let i=` `.repeat(e.depth+1);return r.map(e=>`${i}${e}`)}function Br(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}function Vr(e,t={}){let n=F(process.stderr);if(e===`pass`){let e=t.passFormat??`green`;return n?R(`✓`,e):`✓`}return e===`fail`?n?R(`⨯`,`red`):`⨯`:e===`warn`?n?R(`!`,`yellow`):`!`:n?R(`-`,`dim`):`-`}function R(e,t){return I(e,t,{validateStream:!1})}function Hr(e){return`${Vr(Wr(e.status))} ${Gr(e)}`}function Ur(e){return e.status!==`fail`&&e.status!==`warn`?[]:typeof e.command==`string`?[` run: ${e.command}`]:typeof e.hint==`string`?[` hint: ${e.hint}`]:[]}function Wr(e){return e===`pass`?`pass`:e===`fail`?`fail`:e===`warn`?`warn`:`skip`}function Gr(e){let t=typeof e.id==`string`&&e.id.length>0?e.id:`check`,n=typeof e.summary==`string`&&e.summary.length>0?e.summary:t;return n===t?t:`${t}: ${n}`}const Kr=3e5,qr=[`leaseId`,`tenantId`,`runId`,`clientId`,`deviceKey`];function Jr(e){return f({tenantId:e.meta?.tenantId??z(e.flags,`tenant`),runId:e.meta?.runId??z(e.flags,`runId`),leaseId:e.meta?.leaseId??z(e.flags,`leaseId`),leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend,leaseProvider:e.meta?.leaseProvider??z(e.flags,`leaseProvider`)??z(e.flags,`provider`),deviceKey:e.meta?.deviceKey??z(e.flags,`deviceKey`),clientId:e.meta?.clientId??z(e.flags,`clientId`)})}function Yr(e){return f({tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs??e.ttlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider??e.provider,deviceKey:e.deviceKey,clientId:e.clientId})}function Xr(e){return f({tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function Zr(e){return f({tenant:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function Qr(e){return f({tenantId:e.tenantId??``,runId:e.runId??``,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function $r(e){return ai(e)}function ei(e){let{ttlMs:t,...n}=ai(e);return n}function ti(e,t,n){let r=f({...n.includeTokenParam?{token:n.token}:{},session:n.session,tenantId:e.tenantId,runId:e.runId,leaseProvider:e.leaseProvider,clientId:e.clientId,deviceKey:e.deviceKey});switch(t){case`lease_allocate`:return{...r,...f({ttlMs:e.leaseTtlMs,backend:e.leaseBackend})};case`lease_heartbeat`:return{...r,...f({leaseId:e.leaseId,ttlMs:e.leaseTtlMs})};case`lease_release`:return{...r,...f({leaseId:e.leaseId})}}}function ni(e){let t=f({leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId});return Object.keys(t).length>0?t:void 0}function ri(e){return e.leaseProvider===`proxy`}function ii(e){return ri(e)?qr.filter(t=>!e[t]):[]}function ai(e){return f({leaseId:e.leaseId??``,tenantId:e.tenantId,runId:e.runId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function z(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function B(e,t,r={}){let i=e[t];if(i===void 0)return;if(!Number.isInteger(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be an integer.`);let a=i;if(r.min!==void 0&&a<r.min)throw new n(`INVALID_ARGS`,`Expected ${t} to be at least ${r.min}.`);if(r.max!==void 0&&a>r.max)throw new n(`INVALID_ARGS`,`Expected ${t} to be at most ${r.max}.`);return a}const oi=[`metrics`,`frames`,`memory`,`cpu`,`trace`],si=[`sample`,`snapshot`,`start`,`stop`,`report`],ci=[`profile`],li=[`xctrace`,`simpleperf`,`perfetto`,`android-hprof`,`memgraph`],ui=[`android-hprof`,`memgraph`],di=y(oi),fi=y(si),pi=y(ci),mi=y(li),hi=y(ui),gi=`perf area must be metrics, frames, memory, cpu, or trace`,_i=`perf action must be sample, snapshot, start, stop, or report`,vi=`perf cpu requires profile`,yi=`perf --kind must be xctrace, simpleperf, perfetto, android-hprof, or memgraph`,bi=`perf memory snapshot --kind must be android-hprof or memgraph`,xi=di.is,Si=fi.is,Ci=pi.is,wi=mi.is,Ti=hi.is,Ei=1e4,Di=2e3,Oi=[`get`,`accept`,`dismiss`,`wait`],ki=`<wifi|airplane|location> <on|off>`,Ai=`location set <lat> <lon>`,ji=`animations <on|off>`,Mi=`appearance <light|dark|toggle>`,Ni=`faceid <match|nonmatch|enroll|unenroll>`,Pi=`touchid <match|nonmatch|enroll|unenroll>`,Fi=`fingerprint <match|nonmatch>`,Ii=`clear-app-state [app-id]`,Li=`permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]`,Ri=`permission <grant|reset> <accessibility|screen-recording|input-monitoring>`,zi=`macOS supports only settings ${Mi} and settings ${Ri}. wifi|airplane|location|animations remain unsupported on macOS.`,Bi=[`settings ${ki}`,`settings ${Ai}`,`settings ${ji}`,`settings ${Mi}`,`settings ${Ni}`,`settings ${Pi}`,`settings ${Fi}`,`settings ${Ii}`,`settings ${Li}`,`settings ${Ri}`].join(` | `),Vi=`settings requires ${ki}, ${Ai}, ${ji}, ${Mi}, ${Ni}, ${Pi}, ${Fi}, ${Ii}, ${Li}, or ${Ri}`;function Hi(e){let t=e.trim().toLowerCase();return t===`appearance`||t===`permission`}function Ui(e){return`Unsupported macOS setting: ${e}. ${zi}`}function Wi(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function Gi(e,t,n){return{deviceId:t,deviceName:n,...g(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function Ki(e,t={}){let n=t.includeSerial??!0,r=qi(e);return{platform:e.platform,target:e.target,device:e.name,id:e.id,...e.platform===`ios`?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},...n&&r?{serial:r}:{}}}function qi(e){return g(e.platform)?e.identifiers.serial??e.id:void 0}function Ji(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...Ki(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function Yi(e){return{platform:e.platform,...e.appleOs?{appleOs:e.appleOs}:{},id:e.id,name:e.name,kind:e.kind,target:e.target,...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Xi(e){return e.bundleId??e.package??e.app}function Zi(e){return lt({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${Xi(e)}`)}function Qi(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function $i(e){return lt({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${Qi(e)}`)}function ea(e){let t=e.appName??e.appBundleId??e.session;return lt({session:e.session,...e.warnings?.length?{warnings:e.warnings}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.eventLogPath?{eventLogPath:e.eventLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?Ki(e.device):{}},t?`Opened: ${t}`:`Opened`)}function ta(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...C(e.session?`Closed: ${e.session}`:`Closed`)}}function na(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...Fe(ra(e)),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function ra(e){return{...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}}const ia=1e4;function aa(e,t=`scroll accepts either a relative amount or --pixels, not both`){if(e.amount!==void 0&&e.pixels!==void 0)throw new n(`INVALID_ARGS`,t)}function oa(e,t={}){if(e===void 0)return;let r=t.field??`scroll durationMs`,i=t.max??1e4,a=t.invalidMessage??`${r} must be a non-negative integer`;if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new n(`INVALID_ARGS`,a);if(e>i)throw new n(`INVALID_ARGS`,`${r} must be a non-negative integer at most ${i}`);return e}function sa(e){return typeof e?.durationMs==`number`?e.durationMs:void 0}function ca(e,t,r,i){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>i)throw new n(`INVALID_ARGS`,`${t} must be an integer between ${r} and ${i}`);return e}function la(e,t,n={}){let r=ma(e??[]);if(r.length===0)return{canScroll:!1,emptySnapshot:!0,signature:``};let i=ne(r),a=ha(r,i,t,n),o=Ca(a?_a(r,a.index):r);return a?{canScroll:ya(a,i.get(a.index),t),emptySnapshot:!1,signature:o,scope:ba(a,r)}:{canScroll:!1,emptySnapshot:!1,signature:o}}async function ua(e){let{edge:t,target:n={},scope:r,captureNodes:i}=e;try{let e=la(await i(r),t,n);return r&&e.emptySnapshot?await ua({edge:t,target:n,captureNodes:i}):e}catch(e){throw pa(t,r,e)}}async function da(e){let{edge:t,captureState:r,scroll:i}=e,a=await r();a.scope&&(a=await r(a.scope));let o=0,s;for(;a.canScroll;){if(o>=40)throw new n(`COMMAND_FAILED`,`scroll ${t} reached the safety limit before the snapshot showed the edge`,{hint:`The scoped scroll container still reports hidden content. Use a smaller manual scroll + snapshot loop to inspect the current state.`});s=await i(),o+=1,a=await r(a.scope)}return{passes:o,result:s}}function fa(e,t,n,r,i){return t&&n===0?`Already at ${t}; no hidden content ${t===`bottom`?`below`:`above`} detected`:t?`Scrolled to ${t} with ${n} ${e} passes`:i===void 0?r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`:`Scrolled ${e} by ${i}px`}function pa(e,t,r){return t?new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state for scoped container`,{scope:t,hint:`scroll ${e} could not verify the scoped scroll container. Run snapshot -i for the current screen and retry with a visible scroll target.`},r):new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state`,{hint:`scroll ${e} needs a snapshot showing hidden content ${e===`bottom`?`below`:`above`} before it will move.`},r)}function ma(e){return e.map((e,t)=>({...e,ref:`ref`in e&&e.ref?e.ref:`e${t+1}`}))}function ha(e,t,n,r){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>le(e)&&Da(e.rect));if(a.length===0)return null;let o=ga(r.nodeIndex,i);if(o)return o;let s=r.point;if(s){let e=a.filter(e=>e.rect&&Ea(e.rect,s)).sort(wa);if(e.length>0)return e.find(e=>ya(e,t.get(e.index),n))??e[0]??null}let c=a.filter(e=>ya(e,t.get(e.index),n)).sort(Ta);return c.length>0?c[0]??null:a.filter(t=>ie(t,e)).sort(Ta)[0]??a.sort(Ta)[0]??null}function ga(e,t){if(e===void 0)return null;let n=t.get(e);for(;n;){if(le(n)&&Da(n.rect))return n;n=n.parentIndex===void 0?void 0:t.get(n.parentIndex)}return null}function _a(e,t){let n=new Map(e.map(e=>[e.index,e]));return e.filter(e=>e.index===t||va(e,t,n))}function va(e,t,n){let r=e.parentIndex===void 0?void 0:n.get(e.parentIndex);for(;r;){if(r.index===t)return!0;r=r.parentIndex===void 0?void 0:n.get(r.parentIndex)}return!1}function ya(e,t,n){return n===`bottom`?e.hiddenContentBelow===!0||t?.hiddenContentBelow===!0:e.hiddenContentAbove===!0||t?.hiddenContentAbove===!0}function ba(e,t){return[e.identifier,e.label].map(e=>typeof e==`string`?e.trim():``).find(n=>Sa(n)&&xa(n,e,t))}function xa(e,t,n){let r=e.toLowerCase(),i=n.filter(e=>[e.identifier,e.label,e.value].some(e=>typeof e==`string`&&e.trim().toLowerCase().includes(r)));return i.length===1&&i[0]?.index===t.index}function Sa(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function Ca(e){return e.map(e=>{let t=e.rect?[`x`,`y`,`width`,`height`].map(t=>Oa(e.rect?.[t])).join(`,`):``;return[String(e.index??``),String(e.parentIndex??``),String(e.type??``),String(e.label??``),String(e.value??``),t].join(`|`)}).join(`
|
|
15
|
-
`)}function wa(e,t){return V(e.rect)-V(t.rect)}function Ta(e,t){return V(t.rect)-V(e.rect)}function V(e){return e?e.width*e.height:0}function Ea(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function Da(e){return!!(e&&e.width>0&&e.height>0)}function Oa(e){return typeof e==`number`&&Number.isFinite(e)?e.toFixed(1):``}function H(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function U(e){return e.clock?.now()??Date.now()}async function ka(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}function Aa(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e=>n(t,e)]))}function W(e){return e&&typeof e==`object`?e:void 0}const ja=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];function Ma(e,t){return Na(e,t).node}function Na(e,t){if(x(t))return{node:t,reason:`covered`};let n=Pa(e,t);if(n?.rect&&S(n.rect))return{node:n,reason:`same-rect-descendant`};if(Fa(t)&&t.rect&&S(t.rect))return{node:t,reason:`semantic-target`};let r=ae(e,t);return r?.rect&&!x(r)&&S(r.rect)?La(t,r,e)?{node:t,reason:`overly-broad-ancestor`}:{node:r,reason:`hittable-ancestor`}:{node:t,reason:`original`}}function Pa(e,t){let n=b(t.rect);if(!n)return null;let r=t,i=new Set;for(;!i.has(r.ref);){i.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable||x(e))return!1;let t=b(e.rect);return t?ze(t,n):!1});if(t.length!==1)break;r=t[0]}return r===t?null:r}function Fa(e){return[e.type,e.role,e.subrole].map(e=>_(e??``)).some(Ia)}function Ia(e){return e===`tab`||ja.some(t=>e.includes(t))}function La(e,t,n){let r=b(e.rect),i=b(t.rect);if(!r||!i)return!1;let a=Ra(n,r);return!a||!za(i,a)?!1:!ze(r,i)}function Ra(e,t){let n=s(t),r=e.filter(e=>{let t=(e.type??``).toLowerCase();return t.includes(`application`)||t.includes(`window`)}).map(e=>b(e.rect)).filter(e=>e!==null);if(r.length===0)return null;let i=r.filter(e=>ue(e,n.x,n.y));return oe(i.length>0?i:r)}function za(e,t){let n=Pe(e,t),r=e.width*e.height,i=t.width*t.height;if(n<=0||r<=0||i<=0)return!1;let a=n/i,o=n/r;return a>=.9&&o>=.8}function Ba(e){return e.hittable===!0||Fa(e)}function Va(e,t){let n=de(v(e),t);return n.id!==void 0||n.label!==void 0?!1:ye(e.value)===null}function Ha(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`;){if(r.has(i.index))return!1;if(r.add(i.index),i.parentIndex===t.index)return!0;let e=n.get(i.parentIndex);if(!e)return!1;i=e}return!1}function Ua(e,t){let n=Re(t);return t.filter(t=>t.index!==e.index&&Ha(t,e,n)).sort((e,t)=>e.index-t.index)}function Wa(e,t){let n=S(e.rect);return!n||!t.rect?!1:ue(t.rect,n.x,n.y)}function Ga(e,t){if(!Va(e,t))return e;let n=Ua(e,t);if(n.some(Ba))return e;let r=n.find(e=>v(e).label!==void 0);return!r||!Wa(r,e)?e:r}function Ka(e){return e===`text`||e===`label`||e===`any`}async function qa(e,t){let r=t??`default`,i=await e.sessions.get(r);if(!i)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let a=i.refFrameSnapshot??i.snapshot;if(!a)throw new n(`INVALID_ARGS`,`No snapshot in session. Run snapshot first.`);return{sessionName:r,session:i,snapshot:a}}async function Ja(e,t,r={updateSession:!0}){let i=e.backend.captureSnapshot;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let a=t.session??`default`,o=await e.sessions.get(a),s=await i(H(e,t),{interactiveOnly:r.interactiveOnly??!1,depth:t.depth,scope:r.scope??t.scope,raw:t.raw,includeRects:r.includeRects,...r.includeHiddenContentHints===void 0?{}:{includeHiddenContentHints:r.includeHiddenContentHints}}),c=s.snapshot??{nodes:s.nodes??[],truncated:s.truncated,backend:s.backend,...s.quality?{snapshotQuality:s.quality}:{},createdAt:U(e)};return r.updateSession&&o&&!Me(c.snapshotQuality)&&await e.sessions.set({...o,snapshot:c}),{sessionName:a,session:o,snapshot:c}}async function Ya(e,t,n){if(e.backend.readText){let r=await e.backend.readText(H(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return be(n)}function Xa(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,i.invalidRefMessage);let s=r(e,a)??(i.fallbackLabel.length>0?te(e,i.fallbackLabel):null);if(!s)throw new n(`COMMAND_FAILED`,i.notFoundMessage);return{ref:a,node:s}}function Za(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=Buffer.byteLength(`…`,`utf8`),r=Math.max(0,t-n),i=Buffer.from(e,`utf8`),a=Math.min(r,i.length);for(;a>0&&(i[a]&192)==128;)--a;return i.subarray(0,a).toString(`utf8`)+`…`}function Qa(e,t,r,i){if(!r)return;let a=v(e),o=pe(e,t);if(!(xe(a,r.identity)&&Oe(o,r.structural)))throw new n(`COMMAND_FAILED`,`${i} resolved to a different element than replay verification isolated; the action was not sent`,{reason:we,observed:a,observedStructural:o,expected:r.identity,expectedStructural:r.structural})}async function G(e,t,n){return await vo(e,t,n.action),t.target.kind===`point`?await eo(e,t,t.target,n):t.target.kind===`ref`?await no(e,t,t.target,n):await ro(e,t,t.target,n)}async function $a(e,t,n){let r=t.session??`default`,i=await e.sessions.get(r);if(!i?.snapshot)return;let a={x:n.x,y:n.y,width:0,height:0},o=ee(i.snapshot.nodes,a);if(!o)return;let s={x:n.x,y:n.y};if(!ue(o,s.x,s.y))return`Coordinates (${s.x}, ${s.y}) are outside the last-known viewport (${o.width}x${o.height}). The tap will be forwarded anyway; take a fresh snapshot if the screen changed.`}async function eo(e,t,n,r){let i=await $a(e,t,n);if(!r.captureEvidenceBaseline)return{kind:`point`,point:{x:n.x,y:n.y},...i?{warning:i}:{}};let a=await to(e,t);return{kind:`point`,point:{x:n.x,y:n.y},...a?{preActionNodes:a}:{},...i?{warning:i}:{}}}async function to(e,t){try{return(await K(e,t,!0)).snapshot.nodes}catch{return}}async function no(e,t,n,r){let i=await bo(e,t,n),a=i.resolved;Qa(a.node,i.snapshot.nodes,r.expectedResolvedTarget,r.action);let o=r.promoteToHittableAncestor?mo(i.snapshot.nodes,a.node,{action:r.action,label:`Ref ${n.ref}`}):a.node;return ho(o,`Ref ${n.ref}`,r.action),Eo(o,i.snapshot.nodes,n.ref,r.action),{kind:`ref`,point:Co(o,`Ref ${n.ref} not found or has invalid bounds`),target:{kind:`ref`,ref:`@${a.ref}`},...lo(e,o,i.snapshot.nodes,r.action,a.resolution)}}async function ro(e,t,r,i){let a=d(r.selector),o=await K(e,t,i.requireInteractive),s=_e(po(o.snapshot.nodes),a,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0});if((!s||!s.node.rect)&&i.requireInteractive&&(o=await K(e,t,!1),s=_e(po(o.snapshot.nodes),a,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0})),!s||!s.node.rect){let t=_e(o.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!0,requireUnique:!1});throw t?.node&&x(t.node)?go({label:`Selector ${t.selector.raw}`,node:t.node,action:i.action,selector:t.selector.raw}):new n(`COMMAND_FAILED`,Se(a,s?.diagnostics??[],{unique:!0}),{hint:ge(s?.diagnostics??[])})}Qa(s.node,o.snapshot.nodes,i.expectedResolvedTarget,i.action);let c=i.promoteToHittableAncestor?mo(o.snapshot.nodes,s.node,{action:i.action,label:`Selector ${s.selector.raw}`}):s.node;return ho(c,`Selector ${s.selector.raw}`,i.action),To(c,o.snapshot.nodes,s.selector.raw,i.action),{kind:`selector`,point:Co(c,`Selector ${s.selector.raw} resolved to invalid bounds`),target:{kind:`selector`,selector:s.selector.raw},...lo(e,c,o.snapshot.nodes,i.action,so(s,o.snapshot.nodes))}}const io={source:`ref`,phase:`pre-action`,kind:`exact`},ao={source:`ref`,phase:`pre-action`,kind:`label-fallback`},oo={source:`runtime`,phase:`pre-action`,kind:`unique`};function so(e,t){return e.disambiguation?{source:`runtime`,phase:`pre-action`,kind:`disambiguated`,matchCount:e.disambiguation.matchCount,winnerDiagnostic:co(e.node,t),tiebreak:e.disambiguation.tiebreak,alternatives:e.disambiguation.alternatives.slice(0,5).map(e=>co(e,t))}:oo}function co(e,t){let n=_(e.type??``),r=ke(e,t);return{diagnosticRef:`diag-${e.ref}`,...n?{role:Za(n,256)}:{},...r===void 0?{}:{label:Za(r,256)}}}function lo(e,t,n,r,i){return{node:t,selectorChain:Ee(t,e.backend.platform,{action:r===`fill`?`fill`:`click`,nodes:n}),refLabel:ke(t,n),...fo(t,r),preActionNodes:n,resolution:i,...uo(e,t,n,r)}}function uo(e,t,n,r){if(r!==`click`&&r!==`press`)return{};let i=Ga(t,n);return i===t?{}:{recordingTarget:{node:i,selectorChain:Ee(i,e.backend.platform,{action:`click`,nodes:n}),refLabel:ke(i,n)}}}function fo(e,t){return e.hittable===!1?{targetHittable:!1,hint:`The resolved element reports hittable: false, so this ${t} may have had no visible effect. Verify with a snapshot, or prefer a @ref or a longer/more specific selector to target the intended element.`}:{}}function po(e){return e.filter(e=>!x(e))}function mo(e,t,n){let r=Na(e,t);if(r.reason===`covered`)throw go({label:n.label,node:t,action:n.action});return r.node}function ho(e,t,n){if(x(e))throw go({label:t,node:e,action:n})}function go(e){return new n(`COMMAND_FAILED`,`${e.label} is covered by another visible element and cannot ${_o(e.action)} safely`,{hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`,...e.selector?{selector:e.selector}:{},ref:`@${e.node.ref}`,interactionBlocked:e.node.interactionBlocked})}function _o(e){switch(e){case`fill`:return`be filled`;case`focus`:return`be focused`;case`longPress`:return`be long-pressed`;default:return`be tapped`}}async function K(e,t,r){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let i=t.session??`default`,a=await e.sessions.get(i);if(!a)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let o=await e.backend.captureSnapshot(H(e,t),{interactiveOnly:r,includeRects:!0}),s=o.snapshot??{nodes:o.nodes??[],truncated:o.truncated,backend:o.backend,createdAt:U(e)};return await e.sessions.set({...a,snapshot:s}),{snapshot:s}}async function vo(e,t,r){if(e.backend.platform!==`macos`)return;let i=await yo(e,t);if(!(i!==`desktop`&&i!==`menubar`)&&!(i===`menubar`&&(r===`click`||r===`press`)))throw new n(`UNSUPPORTED_OPERATION`,`${r} is not supported on macOS ${i} sessions yet. Open an app session to act, or use the ${i} surface to inspect.`)}async function yo(e,t){return(await e.sessions.get(t.session??`default`))?.metadata?.surface}async function bo(e,t,r){let{session:i,snapshot:a}=await qa(e,t.session),o=r.fallbackLabel??``,s=So(a.nodes,r.ref,{fallbackLabel:o});if(!s)throw new n(`COMMAND_FAILED`,`Ref ${r.ref} not found or has no bounds`,{hint:me});return xo({session:i,frameTree:a,target:r,fallbackLabel:o,authorized:s})}function xo(e){let{session:t,frameTree:n,target:r,fallbackLabel:i,authorized:a}=e,o=t.snapshot;if(!o||o===n)return{snapshot:n,resolved:a};let s=So(o.nodes,r.ref,{fallbackLabel:i});return s&&xe(v(a.node),v(s.node))?{snapshot:o,resolved:s}:{snapshot:n,resolved:a}}function So(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,`Invalid ref: ${t}`);let s=r(e,a);if(wo(s))return{ref:a,node:s,resolution:io};let c=i.fallbackLabel.length>0?te(e,i.fallbackLabel):null;return wo(c)?{ref:a,node:c,resolution:ao}:null}function Co(e,t){let r=S(e.rect);if(!r)throw new n(`COMMAND_FAILED`,t);return r}function wo(e){return e?S(e.rect)!==null:!1}function To(e,t,n,r){ko(e,t,{message:`Selector ${n} resolved to an off-screen element and is not safe to ${r}`,details:{reason:`offscreen_selector`,selector:n},hint:e=>`${Do(e)} in small steps, retrying ${r} with the same selector after each (it re-resolves against a fresh snapshot). A single large scroll can overshoot the target; a short bounded gesture pan lands it more reliably. If it is inside a closed drawer or another tab, open that container first.`})}function Eo(e,t,n,r){ko(e,t,{message:`Ref ${n} is off-screen and not safe to ${r}`,details:{reason:`offscreen_ref`,ref:o(n)},hint:e=>`${Do(e)} in small steps (a single large scroll can overshoot; a short bounded gesture pan lands it more reliably), then retry ${r} with a selector (e.g. text=/id=) rather than this @ref — the scroll expires the ref frame, so re-run snapshot -i before reusing any @ref.`})}function Do(e){return e?`Scroll ${e} toward it`:`Scroll toward it`}async function Oo(e,t,n,r){let i=(await e.sessions.get(t.session??`default`))?.snapshot?.nodes;if(!i||o(n.ref)===null)return{};let a=So(i,n.ref,{fallbackLabel:n.fallbackLabel??``});return a?(ho(a.node,`Ref ${n.ref}`,r),Eo(a.node,i,n.ref,r),{...fo(a.node,r),node:a.node,preActionNodes:i}):{}}function ko(e,t,r){let i=e.rect?re(e,t):null;if(!e.rect||!i||Ce(e,t))return;let a=ce(e,t);throw new n(`COMMAND_FAILED`,r.message,{...r.details,rect:e.rect,viewport:i,...a?{scrollDirection:a}:{},hint:r.hint(a)})}function Ao(e){let t=Buffer.alloc(16);for(let n of e)Mo(t,jo(n));return{digest:`ax1:${Ve(`sha256`).update(t).update(`\0`).update(String(e.length)).digest(`hex`).slice(0,16)}`,nodeCount:e.length}}function jo(e){return Ve(`sha256`).update(e.type??``).update(`\0`).update(e.label??``).update(`\0`).update(e.identifier??``).digest().subarray(0,16)}function Mo(e,t){for(let n=0;n<e.length;n+=1)e[n]=(e[n]??0)^(t[n]??0)}function No(e){let{digest:t,nodeCount:n}=Ao(e),r=e.reduce((e,t)=>t.hittable===!1?e:e+1,0),i=Po(e);return{digest:t,nodeCount:n,interactiveNodeCount:r,...i?{foregroundApp:i}:{}}}function Po(e){for(let t of e)if(t.bundleId)return t.bundleId;for(let t of e)if(t.appName)return t.appName}function Fo(e,t){let n=M(e.type??`Element`),r=j(e,n),i=e.enabled===!1?`disabled`:`enabled`,a=e.selected===!0?`selected`:`unselected`,o=e.hittable===!0?`hittable`:`not-hittable`;return[String(t??e.depth??0),n,r,i,a,o].join(`|`)}function Io(e,t,n={}){let r=zo(Ro(e,n),Ro(t,n)),i={additions:0,removals:0,unchanged:0};for(let e of r)e.kind===`added`&&(i.additions+=1),e.kind===`removed`&&(i.removals+=1),e.kind===`unchanged`&&(i.unchanged+=1);return{summary:i,lines:r}}function Lo(e,t={}){return Ro(e,t).length}function Ro(e,t){return t.flatten?e.map(e=>({text:Bn(e,0,!1),comparable:Fo(e,0),...t.withRefs&&e.ref?{ref:e.ref}:{}})):zn(e).map(e=>({text:e.text,comparable:Fo(e.node,e.depth),...t.withRefs&&e.node.ref?{ref:e.node.ref}:{}}))}function zo(e,t){let n=e.length,r=t.length,i=n+r,a=new Map,o=[];a.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(a));for(let i=-s;i<=s;i+=2){let c=Vo(a,i,s)?q(a,i+1):q(a,i-1)+1,l=c-i;for(;c<n&&l<r&&e[c].comparable===t[l].comparable;)c+=1,l+=1;if(a.set(i,c),c>=n&&l>=r)return Bo(o,e,t,n,r)}}return[]}function Bo(e,t,n,r,i){let a=[],o=r,s=i;for(let r=e.length-1;r>=0;--r){let i=e[r],c=o-s,l=Vo(i,c,r)?c+1:c-1,u=q(i,l),d=u-l;for(;o>u&&s>d;)a.push({kind:`unchanged`,text:n[s-1].text}),--o,--s;if(r===0)break;if(o===u){let e=n[d];a.push({kind:`added`,text:e.text,...e.ref?{ref:e.ref}:{}}),s=d}else a.push({kind:`removed`,text:t[u].text}),o=u}return a.reverse(),a}function Vo(e,t,n){return t===-n||t!==n&&q(e,t-1)<q(e,t+1)}function q(e,t){return e.get(t)??0}const Ho=new Set([`textfield`,`securetextfield`,`textview`,`textarea`,`searchfield`,`edittext`]),Uo={strippedIndexes:new Set,refs:new Set};function Wo(e){let t=new Set(e.filter(e=>_(e.type??``)===`keyboard`).map(e=>e.index));if(t.size===0)return Uo;let n=new Map(e.map(e=>[e.index,e])),r=Yo(e,n,t),i=new Set(r),a=ns(e,n,r);for(let t of Yo(e,n,a))i.add(t);for(let o of Go(e,n,a,t,r))i.delete(o);let o=new Set(e.filter(e=>e.ref&&i.has(e.index)).map(e=>e.ref));return{strippedIndexes:new Set([...i].filter(e=>!t.has(e))),refs:o}}function Go(e,t,n,r,i){let a=new Set;if(n.size===0)return a;let o=qo(t,n,r);if(o.size===0)return a;let s=Jo(t,r);for(let n of e)!i.has(n.index)&&!s.has(n.index)&&n.rect&&Ko(n,t,o)&&a.add(n.index);return a}function Ko(e,t,n){if(!e.rect)return!1;let r=rs(e,t);if(r===void 0)return!1;let i=n.get(r);return i!==void 0&&e.rect.y+e.rect.height/2<i}function qo(e,t,n){let r=new Map;for(let i of n){let n=e.get(i);if(!n?.rect)continue;let a=rs(n,e);if(a===void 0||!t.has(a))continue;let o=r.get(a);(o===void 0||n.rect.y<o)&&r.set(a,n.rect.y)}return r}function Jo(e,t){let n=new Set;for(let r of t){let t=e.get(r),i=t&&typeof t.parentIndex==`number`?e.get(t.parentIndex):void 0;for(;i;)n.add(i.index),i=typeof i.parentIndex==`number`?e.get(i.parentIndex):void 0}return n}function Yo(e,t,n){let r=new Set(n);if(n.size===0)return r;for(let i of e)is(i,t,n)&&r.add(i.index);return r}function Xo(e,t){if(e.bundleId!==`com.android.systemui`)return!1;if(Ie(e))return!0;let n=new Set,r=e;for(;r?.bundleId===`com.android.systemui`&&!n.has(r.index);){if(Ne(r.identifier))return!0;n.add(r.index),r=r.parentIndex===void 0?void 0:t.get(r.parentIndex)}return!1}function Zo(e,t){let n=new Map(e.map(e=>[e.index,e])),r=new Set(e.filter(e=>Be(e)).map(e=>e.index)),i=new Set([...r].filter(e=>{let t=n.get(e)?.parentIndex,i=t===void 0?void 0:n.get(t);return!i||!r.has(i.index)})),a=t===`com.android.systemui`?new Set:Qo(e,n,r),o=new Set([...r].filter(e=>!i.has(e)));for(let e of a)o.add(e);let s=new Set(e.filter(e=>e.ref&&(r.has(e.index)||a.has(e.index))).map(e=>e.ref));return o.size===0&&s.size===0?Uo:{strippedIndexes:o,refs:s}}function Qo(e,t,n){return new Set(e.filter(e=>!n.has(e.index)&&Xo(e,t)).map(e=>e.index))}function $o(e,t){let n=Wo(e),r=Zo(e,t);return n.strippedIndexes.size===0&&n.refs.size===0?r:r.strippedIndexes.size===0&&r.refs.size===0?n:{strippedIndexes:new Set([...n.strippedIndexes,...r.strippedIndexes]),refs:new Set([...n.refs,...r.refs])}}function es(e,t){let{strippedIndexes:n}=$o(e,t);return n.size===0?e:e.filter(e=>!n.has(e.index))}function ts(e,t){return $o(e,t).refs}function ns(e,t,n){let r=new Set;for(let e of n){let n=t.get(e);if(!n||_(n.type??``)!==`keyboard`)continue;let i=rs(n,t);i!==void 0&&r.add(i)}for(let i of r){let a=new Set([i]);e.some(e=>Ho.has(_(e.type??``))&&!n.has(e.index)&&is(e,t,a))&&r.delete(i)}return r}function rs(e,t){let n=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;n;){if(_(n.type??``)===`window`)return n.index;n=typeof n.parentIndex==`number`?t.get(n.parentIndex):void 0}}function is(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;r;){if(n.has(r.index))return!0;r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}const as=`Settled on a nearly-empty tree — the app may still be loading. Wait for specific content (wait text ...) before interacting.`;async function os(e,t,n){let{quietMs:r,timeoutMs:i}=n,a=U(e),o=a+i,s=!1,c=Math.min(300,Math.max(25,r)),l=0,u,d=0,f,p=a;for(;U(e)<o;){let m=await ls(e,t,o-U(e));if(!m)return{settled:!1,stalled:!0,waitedMs:U(e)-a,captures:l,nodeCount:d,lastCapture:f};l+=1,f=m;let h=us(m.snapshot.nodes),g=U(e);if(n.resetBudgetOnPrivateAxRecovery===!0&&!s&&ss(m.snapshot.snapshotQuality)){s=!0,o=Math.max(o,g+i),p=g,u=h,d=m.snapshot.nodes.length;let t=cs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(t<=0)break;await ka(e,t);continue}if(h!==u)u=h,d=m.snapshot.nodes.length,p=g;else if(l>=2&&g-p>=r)return{settled:!0,stalled:!1,waitedMs:g-a,captures:l,nodeCount:d,lastCapture:f};let ee=cs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(ee<=0)break;await ka(e,ee)}return{settled:!1,stalled:!1,waitedMs:U(e)-a,captures:l,nodeCount:d,lastCapture:f}}function ss(e){return e?.state===`recovered`&&e.backend===`private-ax`}function cs(e){let t=e.quietSinceMs+e.quietMs-e.nowMs,n=t>e.pollMs?e.pollMs:Math.max(25,t+2),r=e.deadlineMs-e.nowMs,i=r-1;return i<2?r>=2?r:0:Math.min(n,i)}async function ls(e,t,n){let r=Ja(e,t,{updateSession:!1,interactiveOnly:!0}),i;try{let e=await Promise.race([r,new Promise(e=>{i=setTimeout(()=>e(void 0),n)})]);return e===void 0&&r.catch(()=>{}),e}finally{i!==void 0&&clearTimeout(i)}}function us(e){return e.map(ds).join(`|`)}function ds(e){let t=e.rect?`${Math.round(e.rect.x)},${Math.round(e.rect.y)},${Math.round(e.rect.width)},${Math.round(e.rect.height)}`:``;return`${e.type??``}#${e.label??``}#${e.identifier??``}#${t}`}const fs=`The UI kept changing for the whole settle budget (animation, carousel, or ticker?), so no settled diff is shown. Raise --timeout, wait for specific content, or take a fresh snapshot.`,ps=`A snapshot capture stalled past the settle budget, so no settled diff is shown. The action itself succeeded; observe with wait stable or snapshot.`;async function ms(e,t,n){let r=n.quietMs??500,i=n.timeoutMs??1e4,a={settled:!1,waitedMs:0,captures:0,quietMs:r,timeoutMs:i};try{let o=await os(e,t,{quietMs:r,timeoutMs:i,resetBudgetOnPrivateAxRecovery:!0}),s={...a,settled:o.settled,waitedMs:o.waitedMs,captures:o.captures};if(!o.lastCapture)return{observation:{...s,hint:o.stalled?ps:fs}};let{stored:c,session:l}=await Ts(e,t,o.lastCapture),u=o.lastCapture.snapshot.nodes;return{observation:{...s,...o.settled&&c?vs(gs(n.resolved),u,n.resolved.point,l?.appBundleId):{},...ws(o,c,u.length)},settledNodes:u}}catch(e){return{observation:{...a,hint:`Settle observation unavailable (${e instanceof Error?e.message:String(e)}). The action itself succeeded; take a snapshot to observe the result.`}}}}function hs(e,t){if(!e)return;let n=No(e),r=t!==void 0&&n.digest!==No(t).digest;return{...n,changedFromBefore:r}}function gs(e){return`preActionNodes`in e&&e.preActionNodes?e.preActionNodes:[]}function _s(e,t,n){let r=Io(es(e,n),es(t,n),{flatten:!0,withRefs:!0}),i=r.lines.filter(e=>e.kind!==`unchanged`),a=Cs(i).map(e=>({kind:e.kind,text:e.text,...e.ref?{ref:e.ref}:{}}));return{summary:r.summary,lines:a,...i.length>a.length?{truncated:!0}:{}}}function vs(e,t,n,r){let i=_s(e,t,r);return{diff:i,...ys(i,t,n,r)}}function ys(e,t,n,r){let i=new Set(e.lines.filter(e=>e.kind===`added`&&e.ref).map(e=>e.ref)),a=ts(t,r),o=new Map(t.filter(e=>e.ref).map(e=>[e.ref,e]));return[...i].some(e=>e!==void 0&&!a.has(e)&&!bs(o.get(e),n))?{}:Ss(t,i,r)}function bs(e,t){if(!e?.rect||!t)return!1;let{x:n,y:r,width:i,height:a}=e.rect;return t.x>=n&&t.x<=n+i&&t.y>=r&&t.y<=r+a}const xs=new Set([`application`,`window`]);function Ss(e,t,n){let r=ts(e,n),i=e.filter(e=>e.ref&&e.interactionBlocked!==`covered`&&!t.has(e.ref)&&!r.has(e.ref)&&!xs.has(M(e.type??`Element`)));if(i.length===0)return{};let a=i.slice(0,20).map(e=>{let t=M(e.type??`Element`),n=j(e,t);return{ref:e.ref,role:t,...n?{label:n}:{}}});return{tail:a,...i.length>a.length?{tailTruncated:!0}:{}}}function Cs(e){if(e.length<=80)return e;let t=e.filter(e=>e.kind===`added`),n=new Set(t.slice(0,80)),r=80-n.size,i=[];for(let t of e)n.has(t)?i.push(t):t.kind===`removed`&&r>0&&(i.push(t),--r);return i}function ws(e,t,n){return e.stalled?{hint:ps}:e.settled?t?n<5?{hint:as}:{}:{hint:`Settled on a sparse, unreadable tree — the diff is omitted. Use screenshot as visual truth before interacting further.`}:{hint:fs}}async function Ts(e,t,n){if(Me(n.snapshot.snapshotQuality))return{stored:!1};let r=await e.sessions.get(t.session??`default`);return r?(await e.sessions.set({...r,snapshot:n.snapshot}),{stored:!0,session:r}):{stored:!1}}function Es(e){let t=e.verify===!0;return{verify:t,needsPreActionBaseline:t||e.settle!==void 0,...e.settle===void 0?{}:{settle:e.settle}}}async function Ds(e,t,n,r,i){let a=await Os(e,t,n,i);return As({...r,...a})}async function Os(e,t,n,r){if(r.settle!==void 0){let i=await ms(e,t,{...r.settle,resolved:n}),a=r.verify?hs(i.settledNodes,`preActionNodes`in n?n.preActionNodes:void 0):void 0;return{settle:i.observation,...a?{evidence:a}:{}}}if(!r.verify)return{};let i=await ks(e,t,n);return i?{evidence:i}:{}}async function ks(e,t,n){let r=`preActionNodes`in n?n.preActionNodes:void 0;try{let n=No((await K(e,t,!0)).snapshot.nodes),i=r!==void 0&&n.digest!==No(r).digest;return{...n,changedFromBefore:i}}catch{return}}function As(e){let t=e;if(t.targetHittable!==!1||!js(t)||t.hint===void 0)return e;let{hint:n,...r}=t;return r}function js(e){if(e.evidence?.changedFromBefore===!0)return!0;let t=e.settle?.diff?.summary;return!!t&&(t.additions>0||t.removals>0)}const Ms=async(e,t)=>{let r=await G(e,t,{action:`focus`,requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new n(`UNSUPPORTED_OPERATION`,`focus is not supported by this backend`);let i=Rs(r),a=W(await e.backend.focus(H(e,t),i));return{...r,...a?{backendResult:a}:{},...C(`Focused (${i.x}, ${i.y})`)}},Ns=async(e,t)=>{let r=Es(t),i=await G(e,t,{action:`longPress`,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:t.expectedResolvedTarget});if(!e.backend.longPress)throw new n(`UNSUPPORTED_OPERATION`,`longPress is not supported by this backend`);let a=t.durationMs===void 0?void 0:ca(t.durationMs,`durationMs`,0,12e4),o=Rs(i),s=W(await e.backend.longPress(H(e,t),o,{durationMs:a}));return await Ds(e,t,i,{...i,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...C(`Long pressed (${o.x}, ${o.y})`)},r)},Ps=async(e,t)=>{if(!e.backend.scroll)throw new n(`UNSUPPORTED_OPERATION`,`scroll is not supported by this backend`);let r=Is(t.direction),i=Vs(t.amount,`scroll amount`),a=Us(t.pixels,`scroll pixels`),o=oa(t.durationMs);aa({amount:i,pixels:a},`scroll accepts either amount or pixels, not both`);let s=await Fs(e,t),c=s.kind===`viewport`?{kind:`viewport`}:{kind:`point`,point:Rs(s)},l=e.backend.scroll,u=async()=>await l(H(e,t),c,{direction:r.direction,...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},...o===void 0?{}:{durationMs:o}}),d,f=0;if(r.edge){let n=r.edge,i=Ls(s),a=await da({edge:n,captureState:async r=>await zs(e,t,n,i,r),scroll:u});d=a.result,f=a.passes}else d=await u(),f=1;let p=W(d),m=sa(p);return{...s,direction:r.direction,...r.edge?{edge:r.edge,passes:f}:{},...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},...m===void 0?{}:{durationMs:m},...p?{backendResult:p}:{},...C(fa(r.direction,r.edge,f,i,a))}};async function Fs(e,t){let n=t.target??{kind:`viewport`};return n.kind===`viewport`?(await vo(e,t,`scroll`),{kind:`viewport`}):await G(e,{...t,target:n},{action:`scroll`,requireInteractive:!1,promoteToHittableAncestor:!1})}function Is(e){return e===`bottom`?{direction:`down`,edge:`bottom`}:e===`top`?{direction:`up`,edge:`top`}:{direction:Bs(e,`scroll direction`)}}function Ls(e){return e.kind===`viewport`?{}:{point:e.point,nodeIndex:`node`in e?e.node?.index:void 0}}function Rs(e){if(!e.point)throw new n(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function zs(e,t,r,i,a){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:o}=e.backend;return await ua({edge:r,target:i,scope:a,captureNodes:async n=>{let r=await o(H(e,t),{scope:n});return r.snapshot?.nodes??r.nodes??[]}})}function Bs(e,t){switch(e){case`up`:case`down`:case`left`:case`right`:return e;default:throw new n(`INVALID_ARGS`,`${t} must be up, down, left, or right`)}}function Vs(e,t){return e===void 0?void 0:Hs(e,t)}function Hs(e,t){if(!Number.isFinite(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive number`);return e}function Us(e,t){if(e!==void 0){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive integer`);return e}}const Ws=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`];function J(e){let t=Ks(e),r=Js(t,`kind`,Ws);if(r===`pan`)return{kind:r,origin:Y(t,`origin`),delta:Y(t,`delta`),pointerCount:B(t,`pointerCount`,{min:1,max:2}),durationMs:Gs(t)};if(t.pointerCount!==void 0)throw new n(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(t.durationMs!==void 0)throw new n(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:Js(t,`direction`,Ae),origin:Y(t,`origin`),distance:B(t,`distance`,{min:0})}}if(r===`swipe`){if(t.durationMs!==void 0)throw new n(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:Js(t,`preset`,je)}}if(r===`pinch`)return{kind:r,scale:X(t,`scale`),origin:qs(t,`origin`)};if(r===`rotate`){if(t.velocity!==void 0)throw new n(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:X(t,`degrees`),origin:qs(t,`origin`)}}return{kind:r,origin:Y(t,`origin`),delta:Y(t,`delta`),scale:X(t,`scale`),degrees:X(t,`degrees`),durationMs:Gs(t)}}function Gs(e){let t=B(e,`durationMs`);if(t!==void 0){if(t<16||t>1e4)throw new n(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${Le}.`);return t}}function Ks(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`gesture requires structured object input`);return e}function Y(e,t){let n=Ks(e[t]);return{x:X(n,`x`),y:X(n,`y`)}}function qs(e,t){return e[t]===void 0?void 0:Y(e,t)}function X(e,t){let r=e[t];if(typeof r!=`number`||!Number.isFinite(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return r}function Js(e,t,r){let i=e[t];if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}const Ys={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:Xs}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`}};function Xs(e,t){let[n,r,i,a,o]=e,s=Zs(n,i),c=Zs(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function Zs(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function Qs(e,t){let n=Ys[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!$s(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function $s(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ec(e){if(!(!e||typeof e!=`object`||Array.isArray(e))&&e.durationMs!==void 0)throw new n(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function tc(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function Z(e,t){let r=Qs(e,t);if(r)throw new n(`INVALID_ARGS`,tc(r))}function nc(e,t,n){let r=rc(e,t);return r?tc(r,n):void 0}function rc(e,t){if(e===`swipe`)return Qs(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(Ys,n))return Qs(n,t.slice(1))}function ic(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function ac(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{Z(`gesture pan`,r);let{origin:e,delta:i}=ic(r);return J({kind:n,origin:e,delta:i,pointerCount:t,durationMs:uc(r[4])})}case`fling`:return Z(`gesture fling`,r),J({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:uc(r[3])});case`swipe`:return Z(`gesture swipe`,r),J({kind:n,preset:r[0]});case`pinch`:return Z(`gesture pinch`,r),J({kind:n,scale:Number(r[0]),origin:dc(r[1],r[2])});case`rotate`:return Z(`gesture rotate`,r),J({kind:n,degrees:Number(r[0]),origin:dc(r[1],r[2])});case`transform`:{Z(`gesture transform`,r);let{origin:e,delta:t}=ic(r);return J({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:uc(r[6])})}default:return J({kind:n})}}function oc(e){switch(e.kind){case`pan`:return Q([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return Q([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return Q([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?Q([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return Q([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs])}}function sc(e,t={}){return Z(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function cc(e){switch(e.kind){case`pan`:return{gesture:{intent:`pan`,origin:e.origin,delta:e.delta,pointerCount:e.pointerCount,durationMs:e.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:e.direction,origin:e.origin,distance:e.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:e.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:e.origin,scale:e.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:e.origin,degrees:e.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:e.origin,delta:e.delta,scale:e.scale,degrees:e.degrees,durationMs:e.durationMs}}}}function lc(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function uc(e){return e===void 0?void 0:Number(e)}function dc(e,t){if(e===void 0!=(t===void 0))throw new n(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return e===void 0?void 0:{x:Number(e),y:Number(t)}}function Q(e){return e.filter(e=>e!==void 0).map(String)}const fc=/^e\d+$/;function pc(e){if(e[0]?.startsWith(`@`)){let t=xc(e.slice(1));return{ref:e[0],...t===void 0?{}:{label:t}}}if(fc.test(e[0]??``))throw new n(`INVALID_ARGS`,`Did you mean "@${e[0]}"? Snapshot refs need the @ prefix.`);let t=c(e);if(t){if(t.rest.length>0)throw new n(`INVALID_ARGS`,yc(e,t));return{selector:t.selectorExpression}}return hc(e)}function mc(e){let t=e[0];if(t?.startsWith(`@`)){let n=e.length>=3?e.slice(2).join(` `):e.slice(1).join(` `);return{kind:`ref`,target:{ref:t,label:e.length>=3?xc(e.slice(1,2)):void 0},text:n}}if(fc.test(t??``))throw new n(`INVALID_ARGS`,`Did you mean "@${t}"? Snapshot refs need the @ prefix.`);let r=c(e,{preferTrailingValue:!0});return r?{kind:`selector`,target:{selector:r.selectorExpression},text:r.rest.join(` `)}:{kind:`point`,target:hc(e.slice(0,2)),text:e.slice(2).join(` `)}}function hc(e){let t=e[0]??``,r=m(t);if(r){let i=gc(t)?r.value:[r.value,...e.slice(1)].join(` `).trim();throw new n(`INVALID_ARGS`,_c({key:r.key,value:i}))}let i=Number(e[0]),a=Number(e[1]);if(Number.isFinite(i)&&Number.isFinite(a))return{x:i,y:a};throw new n(`INVALID_ARGS`,vc(e))}function gc(e){let t=e.slice(e.indexOf(`=`)+1).trim();if(t.length<2)return!1;let n=t[0];return(n===`"`||n===`'`)&&t.endsWith(n)}function _c(e){let{key:t,value:n}=e;return`Unknown selector key "${t}". Supported: ${u.join(`, `)}. ${p(t)?`Did you mean role=${t} label=${$(n)}?`:`Did you mean label=${$(n)}?`}`}function vc(e){let t=e.filter(e=>e!==void 0).join(` `);if(!t.trim())return`Missing target. Pass an @ref from snapshot, a selector like text="Sign in", or "x y" coordinates.`;let n=`Target "${t}" is not a @ref, selector, or "x y" point.`;return e.some(e=>h(e??``))?`${n} Selector values with spaces need quotes, e.g. text="Sign in".`:`${n} To match by visible text, use text=${$(t)} (or label=/id=/role=), or pass an @ref from snapshot.`}function yc(e,t){return`${`Selector ${t.selectorExpression} is followed by unexpected extra arguments: "${t.rest.join(` `)}".`} Selector values with spaces need quotes, e.g. ${bc(e,t)??`text="Sign in"`}.`}function bc(e,t){let n=e.length-t.rest.length,r=e[n-1];if(r===void 0)return;let i=r.indexOf(`=`);if(i<=0)return;let a=[r.slice(i+1),...t.rest].join(` `),o=`${r.slice(0,i+1)}${$(a)}`;return[...e.slice(0,n-1),o].join(` `)}function $(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function xc(e){return e.join(` `).trim()||void 0}function Sc(e,t){let r=e===void 0?NaN:Number(e);if(!Number.isInteger(r)||r<1)throw new n(`INVALID_ARGS`,`viewport ${t} must be a positive integer`);return r}const Cc=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],wc=[`medium`,`high`],Tc=`medium`;function Ec(e){return wc.includes(e)}function Dc(e){let t=typeof e==`number`?e:Oc(e);return t!==void 0&&Number.isInteger(t)&&t>=5&&t<=10?t:void 0}function Oc(e){return typeof e==`string`&&/^\d+$/.test(e)?Number(e):void 0}function kc(e){if(Ec(e))return e;let t=Dc(e);if(t!==void 0)return t<=7?`medium`:`high`}export{Wi as $,F as $t,K as A,Je as An,Ci as At,Aa as B,$r as Bt,os as C,it as Cn,bi as Ct,io as D,Ge as Dn,xi as Dt,Lo as E,nt as En,Si as Et,qa as F,Yr as Ft,ua as G,Hr as Gt,U as H,ei as Ht,Xa as I,Jr as It,ca as J,pr as Jt,fa as K,Vr as Kt,Ka as L,Qr as Lt,G as M,Kr as Mt,Ja as N,ii as Nt,Qa as O,We as On,wi as Ot,Ya as P,ri as Pt,oa as Q,Zn as Qt,Ma as R,Zr as Rt,as as S,$e as Sn,li as St,Io as T,rt as Tn,ci as Tt,ka as U,Xr as Ut,W as V,ti as Vt,H as W,Ur as Wt,aa as X,$n as Xt,ia as Y,fr as Yt,sa as Z,Qn as Zt,Ms as _,ut as _n,_i as _t,Sc as a,dn as an,Yi as at,Ds as b,Qe as bn,oi as bt,ec as c,_t as cn,Ji as ct,oc as d,vt as dn,Bi as dt,j as en,Gi as et,cc as f,mt as fn,Ui as ft,J as g,dt as gn,Ei as gt,Ws as h,pt as hn,Di as ht,Cc as i,vn as in,Zi as it,Oo as j,B as jt,vo as k,Ye as kn,Ti as kt,nc as l,bt as ln,na as lt,sc as m,ft as mn,Oi as mt,wc as n,gn as nn,Qi as nt,mc as o,xt as on,$i as ot,lc as p,gt as pn,Hi as pt,da as q,I as qt,kc as r,fn as rn,ta as rt,pc as s,St as sn,ea as st,Tc as t,M as tn,Xi as tt,ac as u,yt as un,Vi as ut,Ns as v,C as vn,si as vt,ts as w,at as wn,vi as wt,Es as x,Ze as xn,yi as xt,Ps as y,lt as yn,gi as yt,Na as z,ni as zt};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
package/dist/src/runtime2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import{p as n,v as r}from"./sdk-android-adb.js";import{n as i}from"./version.js";import{t as a}from"./timeouts.js";import{l as o}from"./install-artifact.js";import{i as s,n as c,r as l,t as u}from"./device.js";import{n as d}from"./android.js";import f from"node:fs";import p from"node:os";import m from"node:path";import h from"@limrun/api";import{createInstanceClient as g}from"@limrun/api/instance-client";import{createInstanceClient as _}from"@limrun/api/ios-client";function v(e){return e?.trim()||void 0}async function y(e){let t=await g({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),n={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:t},r={exec:async(e,t)=>await T(n,e,t),text:async e=>{await t.setText(e.target,e.text)}},{createAndroidPortReverseManager:i}=await import(`./sdk-android-adb.js`).then(e=>e.t);return r.reverse=i(r),Object.assign(n,{adbProvider:r})}function b(e){return d(e.device,e.adbProvider)}async function x(e,t,n,r){let i=v(r?.packageNameHint);r?.relaunch&&i&&await T(t,[`shell`,`am`,`force-stop`,i],{allowFailure:!0});let a=await e.assets.getOrUpload({path:n,name:j(i,n)});await t.client.sendAsset(a.signedDownloadUrl);let o=i?(await import(`./app-lifecycle.js`).then(e=>e.t)).inferAndroidAppName(i):void 0;return{...i?{packageName:i,launchTarget:i}:{},...o?{appName:o}:{}}}async function S(e,t){await e.adbProvider.reverse?.ensure({local:A(t.devicePort),remote:A(t.hostPort),ownerId:t.name})}async function C(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await w(e),await r(`adb`,[`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function w(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function T(e,t,n){let{adbArgs:r,result:i}=await E(e,t,n);return await D(r,i,n?.allowFailure)}async function E(e,t,n){let i=[`-s`,await O(e),...t];return{adbArgs:i,result:await r(`adb`,i,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function D(e,t,n){if(t.exitCode!==0&&n!==!0){let{androidAdbResultError:n}=await import(`./sdk-android-adb.js`).then(e=>e.t);throw n(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)})}return t}async function O(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??k(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function k(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function A(e){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${e}`);return`tcp:${e}`}function j(e,t){let n=m.extname(t)||`.apk`;return`${e?.replace(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}function M(e){let t=Array.isArray(e)?e:[e],n=[],r=(e,t,i)=>{let a=n.length;n.push(N(e,{index:a,depth:t,parentIndex:i}));for(let n of ee(e))r(n,t+1,a)};for(let e of t)r(e,0);return n}function N(e,t){return{index:t.index,type:P(e),role:F(e),label:I(e),value:L(e),identifier:R(e),rect:z(e),enabled:e.enabled,selected:e.selected,hittable:e.hittable,depth:t.depth,parentIndex:t.parentIndex}}function P(e){return e.elementType??e.type}function F(e){return e.role??P(e)}function I(e){return e.label??e.AXLabel??void 0}function L(e){return e.value??e.AXValue??void 0}function R(e){return e.identifier??e.AXUniqueId??void 0}function z(e){let t=e.rect??e.frame;if(!(!t||typeof t.x!=`number`||typeof t.y!=`number`||typeof t.width!=`number`||typeof t.height!=`number`))return{x:t.x,y:t.y,width:t.width,height:t.height}}function ee(e){return e.children??e.nodes??e.elements??[]}function B(e){return e.key===`id`?{accessibilityId:e.value}:e.key===`value`?{value:e.value}:{label:e.value}}async function V(e,t){f.mkdirSync(m.dirname(e),{recursive:!0}),await f.promises.writeFile(e,Buffer.from(t,`base64`))}async function H(e){let t=await _({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:t}}async function U(e,t,n,r){let i=await K(n);try{let n=await e.assets.getOrUpload({path:i.uploadPath,name:i.assetName}),a=v((await t.client.installApp(n.signedDownloadUrl,{md5:n.md5,launchMode:r?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`})).bundleId)??r?.appIdentifierHint;return{...a?{bundleId:a,launchTarget:a}:{},...i.appName?{appName:i.appName}:{}}}finally{await i.cleanup()}}function W(e){return new G(e)}var G=class{session;constructor(e){this.session=e}async open(e,t){if(t?.url){await this.session.client.launchApp(await q(e)),await this.session.client.openUrl(t.url);return}if(o(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await q(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await q(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(B(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw X(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await a(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async fillElementSelector(e,t){await this.session.client.setElementValue(t,B(e))}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){await V(e,(await this.session.client.screenshot()).base64)}async snapshot(e){let t=await this.session.client.elementTree();return{nodes:M(JSON.parse(t)),backend:`xctest`}}async back(){await this.session.client.pressKey(`escape`)}async home(){throw X(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw X(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw X(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw X(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw X(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readClipboard(){throw X(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw X(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw X(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function K(e){if(!(await f.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:m.basename(e),appName:J(e),cleanup:async()=>{}};let i=await f.promises.mkdtemp(m.join(p.tmpdir(),`agent-device-limrun-ios-app-`)),a=m.join(i,`${m.basename(e)}.zip`),o=await r(`zip`,[`-qr`,a,m.basename(e)],{cwd:m.dirname(e),timeoutMs:12e4});if(o.exitCode!==0)throw await f.promises.rm(i,{recursive:!0,force:!0}),new t(`COMMAND_FAILED`,`Failed to package iOS .app for Limrun install`,{command:[`zip`,`-qr`,a,m.basename(e)].join(` `),...n(o)});return{uploadPath:a,assetName:m.basename(a),appName:await Y(e),cleanup:async()=>{await f.promises.rm(i,{recursive:!0,force:!0})}}}async function q(e){let{resolveIosAppAlias:t}=await import(`./app-resolution.js`).then(e=>e.t);return t(e)}function J(e){return m.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}async function Y(e){let{readIosBundleInfo:t}=await import(`./install-artifact2.js`).then(e=>e.t);return(await t(e)).appName??J(e)}function X(e,n){throw new t(`UNSUPPORTED_OPERATION`,n,{command:e})}var Z=e({LimrunRuntime:()=>$});const Q=`agent-device-cli`;var $=class{limrun;sessions=new Map;options;provider=u;leaseLifecycle={allocate:async e=>await this.allocate(e),release:async e=>await this.release(e)};recoverExpiredLease=async e=>{if(e.leaseProvider!==this.provider||!s(e.backend))throw new t(`UNSUPPORTED_OPERATION`,`Limrun cannot recover this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});await this.release(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.sessions.get(e.leaseId);return t?e.platform&&e.platform!==t.platform?[]:[t.device]:null};constructor(e){this.options=e,this.limrun=new h({apiKey:e.apiKey,defaultHeaders:{"x-agent-device-client":Q,"x-agent-device-version":i()}})}ownsDevice(e){return l(e.id)!==void 0}getInteractor(e){let t=this.getSessionForDevice(e);if(t)return t.platform===`ios`?W(t):b(t)}async installApp(e,t,n,r){return await this.installInstallablePath(e,n,{...r,appIdentifierHint:r?.appIdentifierHint??t,packageNameHint:r?.packageNameHint??t})}async installInstallablePath(e,t,n){let r=this.getSessionForDevice(e);if(r)return r.platform===`ios`?await U(this.limrun,r,t,n):await x(this.limrun,r,t,n)}async configurePortReverse(e){let t=this.requireAndroidPortReverseSession(e.leaseId);if(t)return await S(t,e),te(e)}async shutdown(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(async e=>await this.terminateSession(e))),this.sessions.clear()}async allocate(e){if(e.leaseProvider!==this.provider)return;let t=s(e.backend);if(!t)return;let n=this.sessions.get(e.leaseId);if(n)return{limrunInstanceId:n.instanceId,device:n.device};let r=t===`ios`?await this.createIosSession(e):await this.createAndroidSession(e);return this.sessions.set(e.leaseId,r),{limrunInstanceId:r.instanceId,device:r.device}}async createIosSession(e){let n=await this.limrun.iosInstances.create({wait:!0,metadata:this.buildInstanceMetadata(e),spec:this.options.region?{region:this.options.region}:{}});try{if(!n.status.apiUrl)throw new t(`COMMAND_FAILED`,`Limrun iOS instance did not expose apiUrl`);return await H({lease:e,instanceId:n.metadata.id,device:c(`ios`,e,n.metadata.id),apiUrl:n.status.apiUrl,token:n.status.token})}catch(e){throw await this.limrun.iosInstances.delete(n.metadata.id).catch(()=>{}),e}}async createAndroidSession(e){let n=await this.limrun.androidInstances.create({wait:!0,metadata:this.buildInstanceMetadata(e),spec:this.options.region?{region:this.options.region}:{}});try{if(!n.status.apiUrl||!n.status.adbWebSocketUrl)throw new t(`COMMAND_FAILED`,`Limrun Android instance did not expose API and ADB websocket endpoints`);return await y({lease:e,instanceId:n.metadata.id,device:c(`android`,e,n.metadata.id),apiUrl:n.status.apiUrl,adbUrl:n.status.adbWebSocketUrl,token:n.status.token})}catch(e){throw await this.limrun.androidInstances.delete(n.metadata.id).catch(()=>{}),e}}buildInstanceMetadata(e){return{displayName:`agent-device-${e.tenantId}-${e.runId}`,labels:{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,provider:e.leaseProvider??`limrun`,source:Q}}}async release(e){let t=this.sessions.get(e.leaseId);return t?(await this.terminateSession(t),this.sessions.delete(e.leaseId),{limrunInstanceId:t.instanceId}):await this.releaseRecoveredSession(e)}async releaseRecoveredSession(e){let t=s(e.backend);if(!t)return;let n=`provider=${u},leaseId=${e.leaseId}`,r=(t===`ios`?await this.limrun.iosInstances.list({labelSelector:n}):await this.limrun.androidInstances.list({labelSelector:n})).getPaginatedItems().map(e=>e.metadata.id);for(let e of r)t===`ios`?await this.limrun.iosInstances.delete(e):await this.limrun.androidInstances.delete(e);if(r.length!==0)return{limrunInstanceId:r[0],limrunInstanceCount:r.length}}async terminateSession(e){if(e.client.disconnect(),e.platform===`ios`){await this.limrun.iosInstances.delete(e.instanceId);return}await C(e),await this.limrun.androidInstances.delete(e.instanceId)}getSessionForDevice(e){let t=l(e.id);if(!t)return;let n=this.sessions.get(t.leaseId);return n?.platform===t.platform?n:void 0}requireAndroidPortReverseSession(e){let t=this.sessions.get(e);if(!t||t.platform===`android`)return t;throw ne(`port reverse`,`Direct Limrun iOS sessions cannot reach local host ports; use a bridge public URL.`)}};function te(e){return{leaseId:e.leaseId,devicePort:e.devicePort,hostPort:e.hostPort,name:e.name}}function ne(e,n){throw new t(`UNSUPPORTED_OPERATION`,n,{command:e})}export{Z as n,$ as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";const t=`user-installed`;function n(e){return e??`user-installed`}function r(t){if(t===void 0)throw new e(`INVALID_ARGS`,`appsFilter must be resolved before executing the apps command`);return t}export{r as n,n as r,t};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{T as e,_ as t,h as n}from"./sdk-contracts.js";import{N as r,j as i}from"./sdk-android-adb.js";import{M as a,R as o,et as s,g as c,h as l,m as u}from"./sdk-batch-runner.js";import{Cn as ee,Dn as te,On as d,bn as ne,cn as re,fn as ie,gn as f,mn as ae,on as oe,vn as se}from"./recording-export-quality.js";import{n as ce,t as le}from"./version.js";import{n as ue,t as de}from"./path-resolution.js";import{h as fe,n as pe,r as me,t as he}from"./sdk-device.js";import{mt as ge}from"./sdk-selectors.js";import{C as _e,M as ve}from"./gesture-plan-types.js";import{a as ye,n as be,o as xe,u as p}from"./host-process.js";import Se from"node:crypto";import m from"node:fs";import h from"node:path";import{StringDecoder as Ce}from"node:string_decoder";const we=`/agent-device`,Te=`x-agent-device-tenant`;function Ee(e){return De(e,we)}function De(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Oe(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function ke(e){let t=e?.trim();return t?{[Te]:t}:{}}const Ae=`.webm`;function je(e){return e===`web`?Ae:`.mp4`}function Me(e,t){return h.extname(e)?e:`${e}${t}`}function Ne(e){return`./recording-${Date.now()}${je(e)}`}function Pe(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function Fe(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}function g(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function _(e,t){return ue(e,{cwd:t})}function v(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const y=/^[A-Z_][A-Z0-9_]*$/,Ie=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g;function b(e){return e.startsWith(`AD_`)}function Le(e){return new t(`INVALID_ARGS`,`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function Re(e){let t={};if(e.builtins)for(let[n,r]of Object.entries(e.builtins))t[n]=r;let n=[e.fileEnv,e.shellEnv,e.cliEnv];for(let e of n)if(e)for(let[n,r]of Object.entries(e)){if(b(n))throw Le(n);t[n]=r}return{values:t,expandedBuiltinNames:new Set}}function ze(e){let t={};for(let[n,r]of Object.entries(e)){if(typeof r!=`string`||!n.startsWith(`AD_VAR_`))continue;let e=n.slice(7);e.length!==0&&y.test(e)&&(b(e)||(t[e]=r))}return t}function Be(e){let n={};for(let r of e){let e=r.indexOf(`=`);if(e<=0)throw new t(`INVALID_ARGS`,`Invalid -e entry "${r}": expected KEY=VALUE.`);let i=r.slice(0,e);if(!y.test(i))throw new t(`INVALID_ARGS`,`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(b(i))throw Le(i);n[i]=r.slice(e+1)}return n}function Ve(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function He(e){if(e&&typeof e==`object`&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}return process.env}function Ue(e,n,r){return e.replace(Ie,(e,i,a,o)=>{if(i)return"${";if(!a)return e;if(Object.prototype.hasOwnProperty.call(n.values,a))return b(a)&&(n.expandedBuiltinNames??=new Set).add(a),String(n.values[a]);if(o!==void 0)return o.replace(/\\(.)/g,`$1`);throw new t(`INVALID_ARGS`,`Unresolved variable \${${a}} at ${r.file}:${r.line}.`)})}function We(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>Ue(e,t,n)),flags:Ge(e.flags,t,n)??{},runtime:Ge(e.runtime,t,n)}}function Ge(e,t,n){return e&&x(e,t,n)}function x(e,t,n){return typeof e==`string`?Ue(e,t,n):Array.isArray(e)?e.map(e=>x(e,t,n)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,x(r,t,n)])):e}function Ke(e){return Object.entries(e.values).filter(([t,n])=>n.length>0&&(!b(t)||e.expandedBuiltinNames?.has(t))).map(([e,t])=>({name:e,value:t})).sort((e,t)=>t.value.length-e.value.length)}const qe=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function Je(e){if(e!==e.trim()||!y.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function Ye(e){return`\${${e}}`}function Xe(e){let t=qe.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const Ze=new Set([`text`,`label`,`value`]),Qe=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),$e=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),et=new Set([`cost`,`evidence`,`resolution`,`settle`]),tt=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),nt=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function rt(e,t,n){if(!e)return e;let r=ut(e.selectorChain);return{...ot(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!at(e,t))}:{}}}function it(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function at(e,t){return s(e)?.selectors.some(e=>e.terms.some(e=>Ze.has(e.key)&&typeof e.value==`string`&&C(e.value,t,``)!==e.value))??!1}function ot(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[Qe.has(e)?e:C(e,t,n),st(r,e,t,n)]))}function st(e,t,n,r){return typeof e==`string`&&$e.has(t)?e:t===`selectorChain`&<(e)?ct(e,n):S(e,n,r,et.has(t)?t:void 0)}function S(e,t,n,r){if(typeof e==`string`)return r&&nt.has(r)?e:C(e,t,n);if(Array.isArray(e))return e.map(e=>S(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?tt.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:C(e,t,n),S(a,t,n,o?`${r}.${e}`:void 0)]}))}function ct(e,t){return e.filter(e=>!at(e,t))}function C(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function lt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function ut(e){return lt(e)?e:void 0}function dt(e,t,n){e.saveScriptPath!==void 0&&e.saveScriptPath!==t&&!n&&(e.saveScriptForce=void 0),e.saveScriptPath=t}function ft(e,t){if(t.flags?.noRecord||_t(e,t))return;t.flags?.saveScript&&(e.recordSession=!0,typeof t.flags.saveScript==`string`&&(dt(e,_(t.flags.saveScript),t.flags.force),e.saveScriptDefaultedHealedPath=!1),t.flags.force&&(e.saveScriptForce=!0));let n=pt(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:yt(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{}};return e.actions.push(r),i({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function pt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=Ye(Je(e.flags.recordAs)),n=v({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:mt(e.positionals,t),result:rt(e.result,n,t),targetEvidence:it(e.targetEvidence,n,t)}}function mt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const ht=new Set([`snapshot`,`get`,`is`,`find`]);function gt(e){return e.internal?.replayPlanStep===!0?!1:ht.has(e.command)}function _t(e,t){return!t.interactiveObservation||e.saveScriptBoundary===void 0?!1:t.flags?.record!==!0}const vt=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,...ne,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function yt(e){if(!e)return{};let t={};for(let n of vt)e[n]!==void 0&&(t[n]=e[n]);return t}function w(e){return e.startsWith(`@`)?n(e)?.base??e:e}const T=/^-?\d+(\.\d+)?$/,bt=/^[^\s"\\]+$/,xt=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),St=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Ct=new Map([[`--pointer-count`,`pointerCount`]]),wt=new Map([[`--delay-ms`,`delayMs`]]);function E(e){return e===`click`||e===`press`}function D(e){return E(e)||e===`longpress`}function Tt(e){return e===`type`||e===`fill`}function O(e){return Dt(e,Ot)}function Et(e){return JSON.stringify(e)}function k(e){return Dt(e,kt)}function Dt(e,t){return t(e)?e:Et(e)}function Ot(e){return kt(e)&&e.startsWith(`@`)||T.test(e)}function kt(e){return bt.test(e)}const At=new Set([`fill`,`type`]);function jt(e){if(!At.has(e.command)){let t=(e.positionals??[]).map(e=>O(e));return[e.command,...t].join(` `)}let t=Mt(e).map(e=>O(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function Mt(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&T.test(n)&&T.test(t[1]??``)?[n,t[1]]:[n]}function A(e,t){let n=t.flags??{};if(E(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}Tt(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Nt(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,k(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,k(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,k(t.launchUrl)))}function Pt(e,t){let[n,...r]=t.positionals??[];n&&e.push(k(n));for(let t of r)e.push(O(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),typeof t.flags?.screenshotMaxSize==`number`&&e.push(`--max-size`,String(t.flags.screenshotMaxSize)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function Ft(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,O(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function It(e,t){for(let n of t.positionals??[])e.push(O(n));ee(e,t.flags)}function Lt(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(k(t));Nt(e,t.flags)}function Rt(e,t){for(let n of t.positionals??[])e.push(O(t.command===`wait`?w(n):n));A(e,t)}function zt(e,t){let n=[],r={},i=E(e)?xt:e===`swipe`?St:e===`gesture`?Ct:Tt(e)?wt:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(E(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(E(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=Vt(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function Bt(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=Vt(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function Vt(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function Ht(e,t){for(let n of t.positionals??[])e.push(O(n));t.flags?.relaunch&&e.push(`--relaunch`),Nt(e,t.runtime)}function Ut(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}t.push(r)}let r=Bt(t);return{positionals:r.positionals,flags:n,runtime:Wt(r.flags)?r.flags:void 0}}function Wt(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}function Gt(e,t={}){let n=[e.command];return e.command===`snapshot`?Ft(n,e):e.command===`open`?Ht(n,e):e.command===`runtime`?Lt(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?Pt(n,e):e.command===`screenshot`?It(n,e):Rt(n,e),n.join(` `)}function Kt(e){return e.targetEvidence?[ge(e.targetEvidence)]:[]}function qt(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())a({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Xt))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Jt(e){for(let n of e){let e=Zt(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&a(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!s(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Yt(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Xt(e){if(e.command!==`wait`)return!1;let t=o(e.positionals);return t?.kind!==`selector`||s(t.selectorExpression)===null?!1:e.targetEvidence?.verification===`verified`}function Zt(e){if(e.command===`get`)return e.positionals[1];if(D(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Qt(t)&&Qt(n)?void 0:t}}function Qt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function $t(e){return e.saveScriptBoundary===void 0?!1:e.saveScriptCommitted?!0:!e.saveScriptComplete}var en=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=e.saveScriptBoundary!==void 0,r=t?.publication===`active`,i;try{if(!e.recordSession||$t(e))return{written:!1};let a=tn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=h.dirname(i);return m.existsSync(o)||m.mkdirSync(o,{recursive:!0}),an({scriptPath:i,script:a.script,force:t?.force}),n&&(e.saveScriptCommitted=!0),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return nn({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){if(e.saveScriptPath)return _(e.saveScriptPath);let t=g(e.name),n=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return h.join(this.sessionsDir,`${t}-${n}.ad`)}};function tn(e,t){let n=on(e,{strictPortableRefs:t.activePublication});return t.activePublication&&qt(n),{script:hn(e,n,t.appendCompleteSentinel),actionCount:n.length}}function nn(e){let{session:n,error:r,scriptPath:a,repairArmed:o,activePublication:s}=e;if(i({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:a,error:r instanceof Error?r.message:String(r)}}),o)return{written:!1,error:rn(r,a)};if(s)return{written:!1,error:Yt(r,a)};if(r instanceof t)throw r;return{written:!1}}function rn(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function an(e){let{scriptPath:n,script:r,force:i}=e,a=h.dirname(n),o=h.join(a,`.${h.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);m.writeFileSync(o,r);try{if(i){m.renameSync(o,n);return}m.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{m.rmSync(o,{force:!0})}}function on(e,t={}){let n=e.saveScriptBoundary!==void 0,r=e.actions.slice(e.saveScriptBoundary??0),i=[];for(let a of r){if(a.command===`snapshot`)continue;let r=cn(a);if(r){i.push(r);continue}(n||t.strictPortableRefs)&&sn(a);let o=mn(e,a);o&&i.push(o),i.push(a)}return t.strictPortableRefs&&Jt(i),i}function sn(e){if(!j(e.command))return;let n=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function cn(e){let t=ln(e);if(!(!t||!j(e.command)))return E(e.command)?{...e,positionals:[t]}:e.command===`longpress`?dn(e,t):e.command===`fill`?un(e,t):fn(e,t)}function ln(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function j(e){return D(e)||e===`fill`||e===`get`}function un(e,t){let n=v(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function dn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):pn(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function fn(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function pn(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function mn(e,t){if(!j(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function hn(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${fe(e.device)} device=${Et(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Kt(e)),r.push(gn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function gn(e){return _n([e.command],e)||Gt(e)}function _n(e,t){if(E(t.command))return vn(e,t);if(t.command===`fill`)return yn(e,t);if(t.command===`get`)return bn(e,t)}function vn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(O(w(n))),M(e,t),A(e,t),e.join(` `);if(t.positionals.length===1)return e.push(O(n)),A(e,t),e.join(` `)}}function yn(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(O(w(n))),M(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(O(r)),A(e,t),e.join(` `)}function bn(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(O(n)),e.push(O(w(r))),r.startsWith(`@`)&&M(e,t),e.join(` `)}function M(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(O(n))}const xn=[`status`,`get`,`dismiss`,`enter`,`return`];function N(e){return xn.includes(e)}const Sn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Cn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function wn(e,t){let n=t??{};switch(e.command){case d.devices:return Tn(n.devices);case d.apps:return En(n.apps,e.flags?.appsFilter);case d.boot:return Dn(`Booted`,n,!0);case d.shutdown:return Dn(`Shut down`,n,!1);case d.install:return On(`Installed`,n);case d.reinstall:return On(`Reinstalled`,n);case d.screenshot:return kn(e,n);default:return{}}}function Tn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=jn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Bn(`Found ${t.length} ${Vn(`device`,t.length)}`,i.map(e=>Rn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function En(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=I(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Bn(`Found ${n.length} ${Vn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Dn(e,t,n){let r=Mn(t);if(!r)return{};let i={device:r,...Ln(t),booted:n};return{summary:`${e} ${Rn(i,!1)}`,details:i}}function On(e,t){let n=I(t.appName),r=I(t.bundleId),i=P(t,[`packageName`,`package`]),a=I(t.platform),o=I(t.launchTarget),s=P(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=zn(n,s);if(!c)return{};let l={};return F(l,`appName`,n),F(l,`bundleId`,r),F(l,`packageName`,i),F(l,`platform`,a),o!==s&&F(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function kn(e,t){let n=An(e,t);return n?{details:{requestedFileName:n}}:{}}function An(e,t){let n=H(e.meta?.clientArtifactPaths?.path)??H(t.path);if(n)return V(n)}function jn(e){if(!u(e))return;let t=Mn(e);if(t)return{name:t,...Ln(e)}}function Mn(e){let t=P(e,[`name`,`deviceName`,`device`]);return!t||!Nn(e,t)?t:Fn(e)}function Nn(e,t){let n=Pn(t);return Sn.some(t=>{let r=I(e[t]);return r!==void 0&&Pn(r)===n})}function Pn(e){return e.toLowerCase()}function Fn(e){let t=I(e.appleOs),n=I(e.platform),r=I(e.kind),i=In(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function In(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Cn,n)))return Cn[n]}function Ln(e){let t=I(e.platform),n=I(e.appleOs),r=I(e.kind),i=I(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Rn(e,t){let n=I(e.name)??I(e.device)??`device`,r=I(e.platform),i=I(e.appleOs),a=[r,i===r?void 0:i,I(e.kind),I(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function zn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function P(e,t){for(let n of t){let t=I(e[n]);if(t)return t}}function F(e,t,n){n&&(e[t]=n)}function Bn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Vn(e,t){return t===1?e:`${e}s`}function I(e){let t=H(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function L(e){return I(e)}function R(e){return typeof e==`boolean`?e:void 0}function z(e,t){let n=L(e);return n&&t.includes(n)?n:void 0}function B(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function V(e){let t=H(e);return t?I(t.split(/[\\/]/).at(-1)):void 0}function H(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function U(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Hn=[`up`,`down`,`left`,`right`],Un=[`top`,`bottom`];function Wn(e){return`${e.command===d.reinstall?`Reinstalled`:`Installed`} ${Jn(e.result??{})??`app`}`}function Gn(e){let t=e.result??{};switch(e.command){case d.scroll:return Xn(t);case d.screenshot:return $n(t);case d.home:return`Went home`;case d.back:return tr(t);case d.appSwitcher:return`Opened app switcher`;case d.orientation:return nr(t);case d.viewport:return rr(t);case d.clipboard:return ir(t);case d.keyboard:return ar(t);case d.tvRemote:return sr(t);case d.gesture:return cr(t);case d.swipe:return lr(t);case d.trace:return dr(`trace`,e);case d.record:return dr(`recording`,e);default:return}}function Kn(e){let t=e.result??{};switch(e.command){case d.scroll:return B({direction:z(t.direction,Hn),edge:z(t.edge,Un),passes:U(t.passes),amount:U(t.amount),pixels:U(t.pixels),durationMs:U(t.durationMs),x1:U(t.x1),y1:U(t.y1),x2:U(t.x2),y2:U(t.y2)});case d.screenshot:return B({requestedFileName:er(t)});case d.back:return B({mode:z(t.mode,f)});case d.orientation:return B({orientation:z(t.orientation,oe)});case d.viewport:return B({width:U(t.width),height:U(t.height)});case d.clipboard:return B({action:z(t.action,[`read`,`write`])});case d.keyboard:return or(t);case d.tvRemote:return B({button:z(t.button,_e),durationMs:U(t.durationMs)});case d.gesture:case d.swipe:return ur(t);case d.trace:case d.record:return B({action:z(t.action,[`start`,`stop`]),fileName:pr(e),showTouches:R(t.showTouches)});default:return{}}}function qn(e,t){if(e.command!==d.screenshot)return t;let n=An(e,t);return n?{...t,requestedFileName:n}:t}function Jn(e){let t=L(e.appName),n=mr(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Yn(e)}function Yn(e){let t=L(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Xn(e){let t=z(e.direction,Hn),n=z(e.edge,Un),r=U(e.passes);return n?Zn(n,r):t?Qn(t,e):`Scrolled`}function Zn(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Qn(e,t){let n=U(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=U(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function $n(e){let t=er(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function er(e){return V(e.requestedFileName)??V(e.path)}function tr(e){return z(e.mode,f)===`system`?`Went back using system navigation`:`Went back`}function nr(e){let t=z(e.orientation,oe);return t?`Rotated to ${t}`:`Changed orientation`}function rr(e){let t=U(e.width),n=U(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ir(e){let t=z(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ar(e){let t=H(e.action);if(!t||!N(t))return`Used keyboard`;if(t===`dismiss`)return R(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`;if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=R(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function or(e){let t=H(e.action);return B({action:t&&N(t)?t:void 0,platform:z(e.platform,[`ios`,`android`]),visible:R(e.visible),wasVisible:R(e.wasVisible),dismissed:R(e.dismissed),attempts:U(e.attempts)})}function sr(e){let t=z(e.button,_e);return t?`Pressed TV remote ${t}`:`Used TV remote`}function cr(e){let t=z(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function lr(e){let t=U(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function ur(e){return B({kind:z(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:U(e.durationMs),pointerCount:U(e.pointerCount),x1:U(e.x1),y1:U(e.y1),x2:U(e.x2),y2:U(e.y2),count:U(e.count),pauseMs:U(e.pauseMs),pattern:z(e.pattern,[`one-way`,`ping-pong`]),scale:U(e.scale)})}function dr(e,t){let n=fr(e,z(t.result?.action,[`start`,`stop`])),r=pr(t);return r?`${n} ${r}`:n}function fr(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function pr(e){let t=e.result??{};return V(t.requestedFileName)??V(t.outPath)??V(t.path)??V(e.positionals[1])}function mr(e,t){for(let n of t){let t=L(e[n]);if(t)return t}}function hr(e){switch(e.command){case d.open:return`Opened ${W(e)??`session`}`;case d.close:return`Closed ${L(e.result?.session)??`session`}`;case d.click:case d.press:return`Tapped ${W(e)??`target`}`;case d.longPress:return`Long pressed ${W(e)??`target`}`;case d.fill:return`Filled ${W(e)??`target`}`;case d.type:return`Typed text`;case d.install:case d.reinstall:case te.installSource:return Wn(e);default:return Gn(e)??`Ran ${e.command}`}}function gr(e){return B({command:e.command,positionals:Tr(e),flags:Ir(e),..._r(e),...vr(e),...yr(e),...Kn(e)})}function _r(e){if(!br(e.command))return{};let t=e.result??{};return B({ref:J(t),targetLabel:W(e),selectorChainLength:Nr(t.selectorChain)?.length,x:U(t.x),y:U(t.y),x2:U(t.x2),y2:U(t.y2),durationMs:U(t.durationMs)})}function vr(e){if(!xr(e.command))return{};let t=e.result??{};return B({platform:z(t.platform,me),target:z(t.target,he),appName:L(t.appName),appBundleId:L(t.appBundleId),bundleId:L(t.bundleId),packageName:L(t.packageName),launchTarget:L(t.launchTarget)})}function yr(e){let t=e.result??{};return e.command===d.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==d.wait&&e.command!==d.find&&e.command!==d.get&&e.command!==d.is?{}:B({waitedMs:U(t.waitedMs),found:R(t.found)})}function br(e){return e===d.click||e===d.press||e===d.longPress||e===d.focus||e===d.fill}function xr(e){return e===d.open||e===d.install||e===d.reinstall||e===te.installSource}function W(e){let t=e.result??{};return Sr(t)??Cr(t)??wr(t)??jr(e.positionals[0])}function Sr(e){let t=J(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Cr(e){let t=U(e.x),n=U(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function wr(e){return L(e.appName)??L(e.appBundleId)??L(e.bundleId)??L(e.packageName)}function Tr(e){if(e.positionals.length!==0)return e.command===d.type?[K(`text`)]:e.command===d.fill?Er(e):e.command===d.find?Dr(e):e.command===d.clipboard?Or(e):e.command===d.push?kr(e,`app`,`payload`):e.command===d.triggerAppEvent?kr(e,`event`,`payload`):e.positionals.map(G)}function Er(e){let t=K(`text`),n=e.result??{},r=J(n);if(r)return[`@${r}`,t];if(L(n.selector))return[K(`target`),t];let i=U(n.x),a=U(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Dr(e){let t=+!!Mr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],K(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,K(`text`)]:[...r,...e.positionals.slice(n).map(Ar)]:r}function Or(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,K(`text`)]:e.positionals.map(G)}function kr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[K(t)]:[],...i?[K(n)]:[],...a.map(G)]}function Ar(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:G(e)}function G(e){return jr(e)??K(`arg`)}function jr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function K(e){return`<${e}>`}function Mr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Nr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Pr={enums:[{source:`platform`,values:pe},{source:`target`,values:he}]},Fr={[d.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:ie}]},[d.click]:q(),[d.press]:q(),[d.longPress]:q(),[d.fill]:Lr(),[d.type]:Lr(),[d.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[d.gesture]:Rr(),[d.swipe]:Rr(),[d.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotMaxSize`,output:`maxSize`}]},[d.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[d.back]:{enums:[{source:`backMode`,output:`mode`,values:f}]},[d.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`},{source:`screenshotMaxSize`,output:`maxSize`}],enums:[{source:`recordingScope`,output:`scope`,values:ae}]},[d.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[d.boot]:{booleans:[{source:`headless`}]},[d.close]:{booleans:[{source:`shutdown`}]}};function Ir(e){let t=e.flags??{},n={},r=Object.hasOwn(Fr,e.command)?Fr[e.command]:void 0;return zr(n,t,Pr),zr(n,t,r),Object.keys(n).length>0?n:void 0}function q(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:re}]}}function Lr(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Rr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ve}]}}function zr(e,t,n){n&&(Br(e,t,n.booleans??[]),Vr(e,t,n.numbers??[]),Hr(e,t,n.enums??[]))}function Br(e,t,n){for(let r of n)Ur(e,r.output??r.source,t[r.source])}function Vr(e,t,n){for(let r of n)Wr(e,r.output??r.source,t[r.source])}function Hr(e,t,n){for(let r of n)Gr(e,r.output??r.source,t[r.source],r.values)}function J(e){let t=L(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Ur(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Wr(e,t,n){let r=U(n);r!==void 0&&(e[t]=r)}function Gr(e,t,n,r){let i=z(n,r);i!==void 0&&(e[t]=i)}const Y=new Map,Kr=new Set;function qr(e){return h.join(e,`events.ndjson`)}function Jr(e){return e.command!==d.events}function Yr(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Zr(t,`${JSON.stringify(i)}\n`)}async function Xr(e){await(e?Y.get(e):Promise.all(Y.values()))}function Zr(e,t){let n=(Y.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Qr(e),await m.promises.appendFile(e,t,`utf8`)}).catch(t=>{i({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Y.get(e)===n&&Y.delete(e)});Y.set(e,n)}async function Qr(e){let t=h.dirname(e);if(!Kr.has(t))try{await m.promises.mkdir(t,{recursive:!0}),Kr.add(t)}catch(t){throw i({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function $r(e,t,n){Yr(e,t,{kind:`action.recorded`,requestId:r().requestId,command:n.command,summary:hr(n),details:gr(n)})}function ei(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??r().requestId,command:t.command,summary:`Started ${t.command}`}}function ti(e){let{req:t,response:n,durationMs:i}=e;if(n.ok){let e=wn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:i,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:i,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ni(e,t={}){let n=si(t.cursor),r=ci(t.limit);if(!m.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=ri(e,n,r),a=i.lines.flatMap(e=>{let t=li(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function ri(e,t,n){let r=m.openSync(e,`r`);try{let e=new Ce(`utf8`),i=Buffer.allocUnsafe(65536),a=ii(t,n),o=``,s=0;do{s=m.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=ai(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&oi(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{m.closeSync(r)}}function ii(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function ai(e,t){let n=0;for(let r=e.indexOf(`
|
|
3
|
-
`);r!==-1;r=e.indexOf(`
|
|
4
|
-
`,n))if(oi(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function oi(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0){if(t.lineIndex>=t.cursor+t.limit){t.nextCursor=t.cursor+t.limit;return}t.lineIndex>=t.cursor&&t.lines.push(n),t.lineIndex+=1}}function si(e){if(e===void 0||e.trim()===``)return 0;let n=Number(e);if(Number.isInteger(n)&&n>=0)return n;throw new t(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function ci(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let n=typeof e==`string`?Number(e):e;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new t(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function li(e){try{let t=ui(JSON.parse(e));return t?di(t):void 0}catch{return}}function ui(e){if(u(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&fi(e.kind))return e}function di(e){let t=u(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...pi(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function fi(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function pi(e){return e===`ok`||e===`error`}const mi=60*6e4;var hi=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new en(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=ft(e,t);if(n){let t=this.resolveStoredSessionName(e);$r(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Yr(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ni(this.resolveEventLogPath(e),t)}async flushEvents(e){await Xr(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&i({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:e.saveScriptForce});e.saveScriptBoundary!==void 0&&e.saveScriptCommitted!==!0&&(!t.written&&t.error?this.writeRepairTombstone(e,mi,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){e.saveScriptBoundary!==void 0&&e.saveScriptComplete===!0&&e.saveScriptCommitted!==!0&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...se(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=mi,n){try{let r=this.resolveSessionDir(e.name);m.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...e.repairSourcePath?{sourcePath:e.repairSourcePath}:{},...n?{commitFailure:n}:{}};m.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){i({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return gi(this.repairTombstonePath(e))}clearRepairTombstone(e){try{m.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return h.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=g(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return h.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return h.join(this.sessionsDir,g(e))}resolveDaemonStateDir(){return h.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return m.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return h.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return h.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return qr(this.resolveSessionDir(e))}static expandHome(e,t){return _(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function gi(e){let t;try{t=m.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||n.expiresAt<=Date.now()))return n}function _i(e){let t;try{t=m.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=gi(h.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function vi(e){return h.join(e,`runner.log`)}function yi(e,t){let n=g(t&&t.length>0?t:`unknown`);return h.join(e,`requests`,`${n}.ndjson`)}function bi(e,t={}){let n=xi(e,t);return{baseDir:n,infoPath:h.join(n,`daemon.json`),lockPath:h.join(n,`daemon.lock`),logPath:h.join(n,`daemon.log`),sessionsDir:h.join(n,`sessions`)}}function xi(e,t){let n=(e??``).trim();return n?ue(n,{env:t.env}):Si(t)}function Si(e={}){let t=h.join(de(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??le();return Ci(n)?h.join(t,`dev`,wi(n)):t}function Ci(e){return m.existsSync(h.join(e,`package.json`))&&m.existsSync(h.join(e,`src`,`daemon.ts`))}function wi(e){let t=Ti(e),n=h.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=Se.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function Ti(e){try{return m.realpathSync.native(e)}catch{return h.resolve(e)}}function Ei(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function Di(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Oi(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function ki(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Ai=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,ji=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,Mi=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function Ni(){let e=process.argv[1];return e?Pi(e):`unknown`}function Pi(e,t=le()){try{let n=h.resolve(t),r=[h.resolve(e)],i=new Set,a=[];for(;r.length>0;){let e=r.pop();if(!e||i.has(e))continue;i.add(e);let t=m.statSync(e);if(!t.isFile())continue;let o=h.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=m.readFileSync(e,`utf8`);for(let t of Fi(s)){let n=Li(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=Se.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function Fi(e){let t=new Set;return Ii(e,Ai,t),Ii(e,ji,t),[...t]}function Ii(e,t,n){t.lastIndex=0;let r=null;for(;(r=t.exec(e))!==null;){let e=r[1]?.trim();e?.startsWith(`.`)&&n.add(e)}}function Li(e,t){let n=h.resolve(h.dirname(e),t),r=X(n);if(r)return r;for(let e of Mi){let t=X(`${n}${e}`);if(t)return t}for(let e of Mi){let t=X(h.join(n,`index${e}`));if(t)return t}return null}function X(e){try{return m.statSync(e).isFile()?e:null}catch{return null}}const Ri=/^[A-Za-z0-9_@%+=:,./-]+$/;function zi(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Bi(e){return Ri.test(e)?e:zi(e)}const Vi=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Hi(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Vi.some(e=>e.test(t)):!1}function Ui(e,t){if(!be(e))return!1;if(t){let n=xe(e);if(!n||n!==t)return!1}let n=ye(e);return n?Hi(n):!1}function Z(e,t){try{return process.kill(e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}async function Wi(e,t){Ui(e,t.expectedStartTime)&&Z(e,`SIGTERM`)&&(await p(e,t.termTimeoutMs)||Z(e,`SIGKILL`)&&await p(e,t.killTimeoutMs))}function Gi(e,t){let n=[],r=e+t.toString(),i=r.indexOf(`
|
|
5
|
-
`);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e&&n.push(e),i=r.indexOf(`
|
|
6
|
-
`)}return{lines:n,buffer:r}}function Ki(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function qi(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function Ji(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function Yi(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function Xi(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function Zi(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function Qi(e,t={}){return{ok:!0,service:e,version:ce(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function $i(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{}}}function ea(e){if(u(e))return $i({path:typeof e.path==`string`?e.path:void 0,width:typeof e.width==`number`?e.width:void 0,height:typeof e.height==`number`?e.height:void 0,logicalWidth:typeof e.logicalWidth==`number`?e.logicalWidth:void 0,logicalHeight:typeof e.logicalHeight==`number`?e.logicalHeight:void 0,pixelDensity:typeof e.pixelDensity==`number`?e.pixelDensity:void 0,overlayRefs:Array.isArray(e.overlayRefs)?e.overlayRefs.filter(ia).flatMap(e=>{let t=ta(e);return t?[t]:[]}):void 0})}function ta(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=na(e);if(t)return{ref:e.ref,...ra(e),...t}}function na(e){let t=c(e.rect);if(!t)return;let n=c(e.overlayRect);if(!n)return;let r=l(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function ra(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function ia(e){return u(e)}const Q=1500;function aa(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function oa(e){let t=e?.snapshotDiagnostics?.samples;if(!(!t||t.length===0))return sa(t)}function sa(e){if(e.length===0)return;let t=ua(e);return{stats:t,...t.p95Ms>=Q?{warning:$(t)}:{}}}function ca(e){let t=e.flatMap(e=>va(e?.stats));if(t.length===0)return;let n=ua(t);return{stats:n,...n.p95Ms>=Q?{warning:$(n)}:{}}}function la(e){if(!u(e))return;let t=ma(e.stats);if(!t)return;let n=typeof e.warning==`string`?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function ua(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:t.length,p50Ms:da(t,50),p95Ms:da(t,95),maxMs:t[t.length-1]??0,slowThresholdMs:Q,...fa(e),...pa(e)}}function da(e,t){if(e.length===0)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function fa(e){let t=e.map(e=>e.platform).filter(e=>!!e);return new Set(t).size===1?{platform:t[0]}:{}}function pa(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}function $(e){return`Warning: ${e.platform?`${e.platform} `:``}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function ma(e){if(!u(e))return;let t=ha(e);if(t)return{...t,..._a(e)}}function ha(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>typeof e!=`number`))return t}function ga(e){let t=Object.entries(e).filter(e=>typeof e[1]==`number`);return t.length>0?Object.fromEntries(t):void 0}function _a(e){let t=typeof e.platform==`string`?e.platform:void 0,n=u(e.backends)?ga(e.backends):void 0;return{...t?{platform:t}:{},...n?{backends:n}:{}}}function va(e){if(!e||e.count<=0)return[];let t=e.platform;return e.count===1?[{durationMs:e.maxMs,platform:t}]:e.count===2?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]}export{Re as $,yi as A,O as B,ki as C,Oi as D,Di as E,Tr as F,w as G,D as H,qn as I,rt as J,dt as K,N as L,ti as M,ei as N,hi as O,Jr as P,y as Q,Ut as R,Ni as S,Ei as T,Bt as U,E as V,zt as W,Ye as X,Xe as Y,Je as Z,Wi as _,Oe as _t,sa as a,We as at,Bi as b,De as bt,Qi as c,g as ct,Yi as d,Ae as dt,Ke as et,Xi as f,Me as ft,Ui as g,Te as gt,Gi as h,we as ht,oa as i,He as it,vi as j,_i as k,qi as l,Fe as lt,Ki as m,je as mt,la as n,Be as nt,$i as o,v as ot,Zi as p,Ne as pt,gt as q,aa as r,Ve as rt,ea as s,_ as st,ca as t,ze as tt,Ji as u,Pe as ut,Z as v,Ee as vt,bi as w,Pi as x,zi as y,ke as yt,jt as z};
|
package/dist/src/xml.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-`),t=new Set([` `,` `,`
|
|
2
|
-
`,`\r`]),n=new Set([`__defineGetter__`,`__defineSetter__`,`__proto__`,`constructor`,`prototype`]);function r(e,t={}){let n=t.maxDocumentChars??134217728;if(e.length>n)throw Error(`XML document exceeds maximum supported size of ${n} characters.`);return new a(e).parse()}function i(e,t){for(let n of e){if(n.name===`dict`)for(let e=0;e<n.children.length-1;e+=1){let r=n.children[e],i=n.children[e+1];r?.name===`key`&&r.text&&i&&t(r.text,i)}i(n.children,t)}}var a=class{roots=[];stack=[];index=0;xml;constructor(e){this.xml=e}parse(){for(this.skipByteOrderMark();this.index<this.xml.length;)this.readNextToken();return this.assertFullyClosed(),this.roots}readNextToken(){if(this.xml[this.index]!==`<`){this.readText();return}this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith(`<!--`)?()=>this.skipUntil(`-->`,`Comment is not closed.`):this.startsWith(`<?`)?()=>this.skipUntil(`?>`,`Processing instruction is not closed.`):this.startsWith(`<![CDATA[`)?()=>this.readCdata():this.startsWith(`<!`)?()=>this.skipDeclaration():this.startsWith(`</`)?()=>this.readClosingTag():()=>this.readOpeningTag()}assertFullyClosed(){if(this.stack.length>0){let e=this.stack[this.stack.length-1];throw Error(`Unclosed XML tag <${e?.name??`unknown`}>.`)}}skipByteOrderMark(){this.xml.charCodeAt(0)===65279&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:n}=this.readOpeningTagBody(),r={name:e,attributes:t,text:null,children:[]};this.addNode(r),n||this.pushOpenNode(r)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:t===`self-closing`};let n=this.readAttribute();e[n.name]=n.value}}readOpeningTagEnd(){if(this.index>=this.xml.length)throw Error(`Opening XML tag is not closed.`);return this.xml[this.index]===`>`?(this.index+=1,`open`):this.xml[this.index]===`/`&&this.xml[this.index+1]===`>`?(this.index+=2,`self-closing`):null}readAttribute(){let e=this.readRequiredName(`Invalid XML attribute at offset ${this.index}.`);if(f(e),this.skipWhitespace(),this.xml[this.index]!==`=`)throw Error(`Missing value for XML attribute "${e}".`);return this.index+=1,this.skipWhitespace(),{name:e,value:this.readAttributeValue(e)}}pushOpenNode(e){if(this.stack.length>=256)throw Error(`Maximum XML nesting depth of 256 exceeded.`);this.stack.push(e)}readClosingTag(){this.index+=2,this.skipWhitespace();let e=this.readName();if(this.skipWhitespace(),this.xml[this.index]!==`>`)throw Error(`Closing XML tag </${e}> is not closed.`);this.index+=1;let t=this.stack.pop();if(!t)throw Error(`Unexpected closing XML tag </${e}>.`);if(t.name!==e)throw Error(`Expected </${t.name}> before </${e}>.`)}readText(){let e=this.xml.indexOf(`<`,this.index),t=e===-1?this.xml.length:e;this.appendText(this.xml.slice(this.index,t),!0),this.index=t}readCdata(){let e=this.index+9,t=this.xml.indexOf(`]]>`,e);if(t===-1)throw Error(`CDATA section is not closed.`);this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let n=e.trim();if(!n)return;let r=this.stack[this.stack.length-1];r&&(r.text=`${r.text??``}${t?p(n):n}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){let e=this.index;for(;this.index<this.xml.length&&o(this.xml[this.index]);)this.index+=1;return this.xml.slice(e,this.index)}readRequiredName(e){let t=this.readName();if(!t)throw Error(e);return t}readAttributeValue(e){let t=this.xml[this.index];if(t!==`"`&&t!==`'`)throw Error(`XML attribute "${e}" must use a quoted value.`);this.index+=1;let n=this.index,r=this.xml.indexOf(t,n);if(r===-1)throw Error(`XML attribute "${e}" is not closed.`);return this.index=r+1,p(this.xml.slice(n,r).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(c(e,this.xml[t])){this.index=t+1;return}throw Error(`XML declaration is not closed.`)}skipUntil(e,t){let n=this.xml.indexOf(e,this.index+e.length);if(n===-1)throw Error(t);this.index=n+e.length}skipWhitespace(){for(;this.index<this.xml.length&&s(this.xml[this.index]);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}};function o(t){return t!==void 0&&e.has(t)}function s(e){return e!==void 0&&t.has(e)}function c(e,t){return t===void 0||l(e,t)?!1:(u(e,t),d(e,t))}function l(e,t){return e.quote?(t===e.quote&&(e.quote=null),!0):t===`"`||t===`'`?(e.quote=t,!0):!1}function u(e,t){if(t===`[`){e.bracketDepth+=1;return}t===`]`&&e.bracketDepth>0&&--e.bracketDepth}function d(e,t){return t===`>`&&e.bracketDepth===0}function f(e){if(n.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}function p(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(e,t)=>{switch(t){case`amp`:return`&`;case`lt`:return`<`;case`gt`:return`>`;case`quot`:return`"`;case`apos`:return`'`;default:return m(e,t)}})}function m(e,t){let n=t.startsWith(`#x`)?Number.parseInt(t.slice(2),16):Number(t.slice(1));if(!Number.isInteger(n)||n<0||n>1114111)return e;try{return String.fromCodePoint(n)}catch{return e}}export{i as n,r as t};
|