agent-device 0.20.9 → 0.20.10
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.9.apk → agent-device-android-ime-helper-0.20.10.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.10.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.9.manifest.json → agent-device-android-ime-helper-0.20.10.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.9.apk → agent-device-android-snapshot-helper-0.20.10.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.10.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.9.manifest.json → agent-device-android-snapshot-helper-0.20.10.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +6 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +4 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +94 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +22 -23
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +3 -23
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +10 -11
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +30 -12
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +8 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +133 -63
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +13 -12
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentation.swift +183 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentationTests.swift +0 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +20 -18
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +19 -0
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.d.ts +61 -0
- package/dist/src/ai-sdk.js +1 -0
- package/dist/src/android-adb.d.ts +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apps.js +5 -5
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/boot-diagnostics.js +2 -2
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +30 -23
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +7 -7
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +1582 -0
- package/dist/src/command-tools.js +2 -0
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/daemon.js +1 -1
- package/dist/src/debug-symbols.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/dispatch.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/helper-package-install.js +1 -1
- package/dist/src/helper.js +1 -1
- package/dist/src/ime-lifecycle.js +1 -1
- package/dist/src/ime-recovery-marker.js +1 -1
- package/dist/src/index.d.ts +2 -1578
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions3.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-common.js +1 -1
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +2 -2
- package/dist/src/internal/daemon.js +4 -4
- 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 +10 -2
- package/dist/src/linux.js +1 -1
- package/dist/src/location-coordinates.js +1 -1
- package/dist/src/{screenshot-geometry.js → mobile-snapshot-semantics.js} +1 -1
- package/dist/src/perf.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/png-resize.js +1 -1
- package/dist/src/provider.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/registry.js +27 -27
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/reporting.js +5 -5
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime2.js +4 -4
- package/dist/src/runtime3.js +1 -1
- package/dist/src/runtime4.js +3 -3
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/screenshot.js +1 -1
- package/dist/src/script-source-bundle.js +16 -0
- package/dist/src/sdk-android-adb.d.ts +40 -40
- package/dist/src/sdk-android-adb.js +4 -4
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +122 -85
- 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-selectors.d.ts +89 -77
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +10 -3
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session2.js +7 -8
- package/dist/src/shared.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-scope.js +1 -0
- package/dist/src/snapshot.js +6 -6
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +1 -1
- package/dist/src/src3.js +1 -1
- package/dist/src/src4.js +1 -0
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -0
- package/dist/src/verified-file.js +1 -1
- package/dist/src/web.js +1 -1
- package/package.json +21 -8
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.9.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.9.apk.sha256 +0 -1
- package/dist/src/cancel.js +0 -1
- package/dist/src/prepare-kind.js +0 -15
- package/dist/src/selector-vocabulary.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{D as e,_ as t,h as n}from"./sdk-contracts.js";import{C as r,S as i,_ as a,v as o}from"./location-coordinates.js";import{Ar as s,Fn as c,Gt as l,Mn as u,Nn as d,Pn as ee,Ut as te,Yt as ne,jr as re,kr as f,v as ie}from"./sdk-batch-runner.js";import{_ as ae,i as oe,r as se,t as ce}from"./sdk-device.js";import{Dt as le,Vt as ue}from"./prepare-kind.js";import{r as de}from"./recording-export-quality.js";import{C as fe,H as pe,K as me,N as he,S as ge,n as _e}from"./interaction.js";import{n as p,t as ve}from"./command-catalog.js";import{t as ye}from"./session.js";import{t as be}from"./device.js";import{A as m,M as h}from"./sdk-android-adb.js";import{n as xe,t as Se}from"./path-resolution.js";import{n as Ce,t as we}from"./version.js";import{c as Te,d as Ee,n as De,s as Oe}from"./host-process.js";import g from"node:path";import ke from"node:crypto";import _ from"node:fs";import{StringDecoder as Ae}from"node:string_decoder";function v(e){return e.startsWith(`@`)?n(e)?.base??e:e}const je=/^-?\d+(\.\d+)?$/,Me=/^[^\s"\\]+$/,Ne=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Pe=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Fe=new Map([[`--pointer-count`,`pointerCount`]]),Ie=new Map([[`--delay-ms`,`delayMs`]]);function y(e){return e===`click`||e===`press`}function Le(e){return y(e)||e===`longpress`}function Re(e){return e===`type`||e===`fill`}function b(e){return Be(e,Ve)}function ze(e){return JSON.stringify(e)}function x(e){return Be(e,He)}function Be(e,t){return t(e)?e:ze(e)}function Ve(e){return He(e)&&e.startsWith(`@`)||je.test(e)}function He(e){return Me.test(e)}const Ue=new Set([`fill`,`type`]);function We(e){if(!Ue.has(e.command)){let t=(e.positionals??[]).map(e=>b(e));return[e.command,...t].join(` `)}let t=Ge(e).map(e=>b(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function Ge(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&je.test(n)&&je.test(t[1]??``)?[n,t[1]]:[n]}function S(e,t){let n=t.flags??{};if(y(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}Re(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Ke(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`,x(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`,x(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,x(t.launchUrl)))}function qe(e,t){let[n,...r]=t.positionals??[];n&&e.push(x(n));for(let t of r)e.push(b(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(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 Je(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`,b(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Ye(e,t){for(let n of t.positionals??[])e.push(b(n));i(e,t.flags)}function Xe(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(x(t));Ke(e,t.flags)}function Ze(e,t){for(let n of t.positionals??[])e.push(b(t.command===`wait`?v(n):n));S(e,t)}function Qe(e,t){let n=[],r={},i=y(e)?Ne:e===`swipe`?Pe:e===`gesture`?Fe:Re(e)?Ie:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(y(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(y(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=et(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 $e(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=et(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 et(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function tt(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function nt(e,t){for(let n of t.positionals??[])e.push(b(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),Ke(e,t.runtime)}function rt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=$e(t);return{positionals:r.positionals,flags:n,runtime:it(r.flags)?r.flags:void 0}}function it(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const C=/^[A-Z_][A-Z0-9_]*$/,at=new Set(se.filter(e=>e!==`web`)),ot=new Set([`mobile`,`tv`,`desktop`]);function st(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,o,s=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,l]of i.entries()){let i=l.trim();if(i.length===0){o&&s(o,e,`is blank`);continue}if(i.startsWith(`#`)){let t=ee(i);if(t.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=c(i);if(n.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:e+1};continue}o&&s(o,e,`is a comment`);continue}if(lt(i)){if(o&&s(o,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let u=pt(l);if(!u){o&&s(o,e,`did not parse as an action`);continue}let d=ge(u.command,u.positionals??[],`line ${e+1}`);if(d)throw new t(`INVALID_ARGS`,d);o&&=(o.kind===`single`?u.targetEvidence=o.evidence:u.targetEvidences=o.evidence,void 0),n.push(u),r.push(e+1),a=!0}if(o)throw new t(`INVALID_ARGS`,`${o.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function ct(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(lt(t)){ft(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&at.has(e)&&w(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&ot.has(e)&&w(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&w(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&w(n,`retries`,Math.floor(e))}}return n}function lt(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function ut(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!C.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:dt(r.slice(i+1),n)}}function dt(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function ft(e,n,r){let{key:i,value:a}=ut(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function w(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function pt(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[i,...o]=ht(n);if(i===void 0||i===`context`)return null;let s={ts:Date.now(),command:i,positionals:[],flags:{}};if(i===`snapshot`){s.positionals=[];for(let e=0;e<o.length;e+=1){let t=o[e];if(t===`-i`){s.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){s.flags.snapshotRaw=!0;continue}if(t===`--force-full`){s.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<o.length){let t=Number(o[e+1]);Number.isFinite(t)&&t>=0&&(s.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<o.length){s.flags.snapshotScope=o[e+1],e+=1;continue}if(t===`--backend`&&e+1<o.length){e+=1;continue}}}return s}if(i===`open`){let e=rt(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s.runtime=e.runtime,s}if(i===`runtime`){let e=$e(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s}if(y(i)){let e=Qe(i,o);Object.assign(s.flags,e.flags);let t=e.positionals[0];if(t===void 0)return s;if(t.startsWith(`@`))return s.positionals=[v(t)],e.positionals[1]&&(s.result={refLabel:e.positionals[1]}),s;let n=e.positionals[0],r=e.positionals[1];return T(n)&&T(r)&&e.positionals.length>=2?(s.positionals=[n,r],s):(s.positionals=[e.positionals.join(` `)],s)}if(i===`fill`){let e=Qe(i,o);if(Object.assign(s.flags,e.flags),!mt(e.positionals))return s.positionals=e.positionals,s;let[t,n,...r]=e.positionals;if(T(t)&&T(n))return s.positionals=[t,n,r.join(` `)],s;let[a,c,...l]=e.positionals;if(a.startsWith(`@`)){let e=v(a);return l.length>0?(s.positionals=[e,l.join(` `)],s.result={refLabel:c},s):(s.positionals=[e,c],s)}return s.positionals=[a,[c,...l].join(` `)],s}if(i===`get`){let e=o[0],t=o[1];return e===void 0||t===void 0?(s.positionals=o,s):t.startsWith(`@`)?(s.positionals=[e,v(t)],o[2]&&(s.result={refLabel:o[2]}),s):(s.positionals=[e,o.slice(1).join(` `)],s)}if(i===`swipe`||i===`type`||i===`gesture`){let e=Qe(i,o);return Object.assign(s.flags,e.flags),s.positionals=e.positionals,s}if(i===`record`){let e=[];for(let n=0;n<o.length;n+=1){let r=o[n];if(r===a.cliToken)throw new t(`INVALID_ARGS`,a.migration.record);if(r===`--hide-touches`){s.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<o.length){let e=Number(o[n+1]);Number.isFinite(e)&&(s.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<o.length){let e=o[n+1],t=de(e);t!==void 0&&(s.flags.quality=t),n+=1;continue}e.push(r)}return s.positionals=e,s}if(i===`screenshot`){let e=[];for(let t=0;t<o.length;t+=1){let n=o[t],i=r({args:o,index:t,flags:s.flags});if(i.handled){t=i.nextIndex;continue}e.push(n)}return s.positionals=e,s}return s.positionals=i===`wait`||i===`longpress`?o.map(e=>v(e)):o,s}function mt(e){return e.length>=2}function T(e){return e?!Number.isNaN(Number(e)):!1}function ht(e){let t=[],n=0;for(;n<e.length&&(n=gt(e,n),!(n>=e.length));){let r=e[n]===`"`?_t(e,n):vt(e,n);t.push(r.value),n=r.nextCursor}return t}function gt(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function _t(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function vt(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function yt(e,t={}){let n=[e.command];return e.command===`snapshot`?Je(n,e):e.command===`open`?nt(n,e):e.command===`runtime`?Xe(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?qe(n,e):e.command===`screenshot`?Ye(n,e):Ze(n,e),n.join(` `)}function bt(e){return e.targetEvidences?[u(e.targetEvidences)]:e.targetEvidence?[d(e.targetEvidence)]:[]}async function xt(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function St(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 Ct(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)}const wt=`/agent-device`,Tt=`x-agent-device-tenant`;function Et(e){return Dt(e,wt)}function Dt(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ot(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function kt(e){let t=e?.trim();return t?{[Tt]:t}:{}}const E={kind:`none`};function D(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function At(e){return e.kind===`repair`?{...e,status:`armed`}:e}function jt(e){return e.kind===`none`?void 0:e.target}function Mt(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Nt(e){return e.kind===`authoring`&&e.status===`aborted`}function Pt(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function Ft(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function It(e){return{kind:`authoring`,status:`armed`,target:D(void 0,e)}}function Lt(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Rt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function zt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:D(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function Bt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Vt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Ht(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function Ut(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function Wt(e){return e.kind===`repair`?e.boundary:void 0}function Gt(e){return e.kind===`repair`?e.sourcePath:void 0}function Kt(e){return e.kind===`repair`&&e.status!==`committed`}function qt(e){let t=jt(e);return t?.kind===`explicit`?t.path:void 0}function Jt(e){return jt(e)?.force===!0}function O(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function k(e,t){return xe(e,{cwd:t})}function A(e){return e?.scriptPublication??E}function Yt(e){let t=A(e);return t.kind===`authoring`&&t.status===`armed`}function Xt(e,t){e.scriptPublication=It({path:t.path===void 0?void 0:k(t.path),force:t.force===!0})}function Zt(e){e.scriptPublication=Lt(A(e))}function Qt(e){return Pt(A(e))}function $t(e,t){if(!t.saveScript||Nt(A(e)))return;let n={path:typeof t.saveScript==`string`?k(t.saveScript):void 0,force:t.force===!0},r=A(e);if(r.kind===`repair`){e.scriptPublication=zt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:D(r.target,n)};return}e.scriptPublication=It(n)}function en(e,t){let n=A(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:D(n.target,{path:t.explicitPath===void 0?void 0:k(t.explicitPath),force:t.liveForce===!0})})}function tn(e,t){e.scriptPublication=Rt(A(e),t)}function nn(e,t){let n=A(e);n.kind===`authoring`&&(e.scriptPublication=Rt(n,t))}function rn(e,t){return t===!0||Jt(A(e))}function an(e){return Ft(A(e))}function j(e){return e?.scriptPublication??E}function on(e,t){let n=j(e);e.scriptPublication=zt(n,{requested:{path:typeof t.saveScript==`string`?k(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function sn(e){e.scriptPublication=At(j(e))}function cn(e){e.scriptPublication=Bt(j(e))}function ln(e,t){e.scriptPublication=Vt(j(e),t)}function un(e){e.scriptPublication=Ut(j(e))}function dn(e,t){let n=j(e);return n.kind===`repair`&&n.closeReceipt===t}function fn(e){return j(e).kind===`repair`}function pn(e){return Kt(j(e))}function M(e){return Wt(j(e))}function mn(e){return Gt(j(e))}function N(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 hn=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function gn(e){if(e!==e.trim()||!C.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 _n(e){return`\${${e}}`}function vn(e){let t=hn.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const yn=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(`.`)),bn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),xn=new Set([`cost`,`evidence`,`resolution`,`settle`]),Sn=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`])]]),Cn=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 wn(e,t,n){if(!e)return e;let r=jn(e.selectorChain);return{...Dn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!En(e,t))}:{}}}function Tn(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 En(e,t){return ne(e,t)}function Dn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[yn.has(e)?e:F(e,t,n),On(r,e,t,n)]))}function On(e,t,n,r){return typeof e==`string`&&bn.has(t)?e:t===`selectorChain`&&An(e)?kn(e,n):P(e,n,r,xn.has(t)?t:void 0)}function P(e,t,n,r){if(typeof e==`string`)return r&&Cn.has(r)?e:F(e,t,n);if(Array.isArray(e))return e.map(e=>P(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Sn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:F(e,t,n),P(a,t,n,o?`${r}.${e}`:void 0)]}))}function kn(e,t){return e.filter(e=>!En(e,t))}function F(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 An(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function jn(e){return An(e)?e:void 0}function Mn(e,t){if(t.flags?.noRecord||Ln(e,t))return;t.flags&&$t(e,t.flags);let n=Nn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:zn(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Nn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=_n(gn(e.flags.recordAs)),n=N({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:Pn(e.positionals,t),result:wn(e.result,n,t),targetEvidence:Tn(e.targetEvidence,n,t)}}function Pn(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 Fn=new Set([`snapshot`,`get`,`is`,`find`]);function In(e){return e.internal?.replayPlanStep===!0?!1:Fn.has(e.command)}function Ln(e,t){return!t.interactiveObservation||M(e)===void 0?!1:t.flags?.record!==!0}const Rn=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...o,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function zn(e){if(!e)return{};let t={};for(let n of Rn)e[n]!==void 0&&(t[n]=e[n]);return t}function Bn(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())ie({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Kn))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 Vn(e){for(let n of e){if(Hn(n)){Un(n);continue}let e=qn(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`&&ie(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||!l(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 Hn(e){return Wn(e)!==void 0}function Un(e){let n=Wn(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Wn(e){return e.command===`gesture`?fe(e.positionals):void 0}function Gn(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 Kn(e){if(e.command!==`wait`)return!1;let t=te(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function qn(e){if(e.command===`get`)return e.positionals[1];if(Le(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Jn(t)&&Jn(n)?void 0:t}}function Jn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Yn(e){let t=e.scriptPublication??E;return t.kind===`repair`?t.status===`committed`?!0:!Mt(t):!1}function Xn(e){return Pt(e.scriptPublication??E)?Yn(e):!0}var Zn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=fn(e),r=t?.publication===`active`,i;try{if(Xn(e))return{written:!1};let a=Qn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=g.dirname(i);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),tr({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Ht(e.scriptPublication??E)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return $n({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=qt(e.scriptPublication??E);if(t)return k(t);let n=O(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return g.join(this.sessionsDir,`${n}-${r}.ad`)}};function Qn(e,t){let n=nr(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Bn(n),{script:fr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function $n(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(m({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:er(r,i)};if(o)return{written:!1,error:Gn(r,i)};if(r instanceof t)throw r;return{written:!1}}function er(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 tr(e){let{scriptPath:n,script:r,force:i}=e,a=g.dirname(n),o=g.join(a,`.${g.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);_.writeFileSync(o,r);try{if(i){_.renameSync(o,n);return}_.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{_.rmSync(o,{force:!0})}}function nr(e,t={}){let n=M(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=ar(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&rr(n);let o=dr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Vn(a),a}function rr(e){let n=e.command===`gesture`?fe(e.positionals??[]):void 0;if(n){ir(n);return}if(!I(e.command))return;let r=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function ir(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function ar(e){let t=or(e);if(!(!t||!I(e.command)))return y(e.command)?{...e,positionals:[t]}:e.command===`longpress`?cr(e,t):e.command===`fill`?sr(e,t):lr(e,t)}function or(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 I(e){return Le(e)||e===`fill`||e===`get`}function sr(e,t){let n=N(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function cr(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):ur(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function lr(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function ur(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function dr(e,t){if(!I(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 fr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${ae(e.device)} device=${ze(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...bt(e)),r.push(pr(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function pr(e){return mr([e.command],e)||yt(e)}function mr(e,t){if(y(t.command))return hr(e,t);if(t.command===`fill`)return gr(e,t);if(t.command===`get`)return _r(e,t)}function hr(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(b(v(n))),L(e,t),S(e,t),e.join(` `);if(t.positionals.length===1)return e.push(b(n)),S(e,t),e.join(` `)}}function gr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(b(v(n))),L(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(b(r)),S(e,t),e.join(` `)}function _r(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(b(n)),e.push(b(v(r))),r.startsWith(`@`)&&L(e,t),e.join(` `)}function L(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(b(n))}const vr=[`status`,`get`,`dismiss`,`enter`,`return`];function R(e){return vr.includes(e)}const yr=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],br={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function xr(e,t){let n=t??{};switch(e.command){case p.devices:return Sr(n.devices);case p.apps:return Cr(n.apps,e.flags?.appsFilter);case p.boot:return wr(`Booted`,n,!0);case p.shutdown:return wr(`Shut down`,n,!1);case p.install:return Tr(`Installed`,n);case p.reinstall:return Tr(`Reinstalled`,n);case p.screenshot:return Er(e,n);default:return{}}}function Sr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Or(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Lr(`Found ${t.length} ${Rr(`device`,t.length)}`,i.map(e=>Fr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Cr(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=V(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Lr(`Found ${n.length} ${Rr(`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 wr(e,t,n){let r=kr(t);if(!r)return{};let i={device:r,...Pr(t),booted:n};return{summary:`${e} ${Fr(i,!1)}`,details:i}}function Tr(e,t){let n=V(t.appName),r=V(t.bundleId),i=z(t,[`packageName`,`package`]),a=V(t.platform),o=V(t.launchTarget),s=z(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Ir(n,s);if(!c)return{};let l={};return B(l,`appName`,n),B(l,`bundleId`,r),B(l,`packageName`,i),B(l,`platform`,a),o!==s&&B(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Er(e,t){let n=Dr(e,t);return n?{details:{requestedFileName:n}}:{}}function Dr(e,t){let n=q(e.meta?.clientArtifactPaths?.path)??q(t.path);if(n)return K(n)}function Or(e){if(!f(e))return;let t=kr(e);if(t)return{name:t,...Pr(e)}}function kr(e){let t=z(e,[`name`,`deviceName`,`device`]);return!t||!Ar(e,t)?t:Mr(e)}function Ar(e,t){let n=jr(t);return yr.some(t=>{let r=V(e[t]);return r!==void 0&&jr(r)===n})}function jr(e){return e.toLowerCase()}function Mr(e){let t=V(e.appleOs),n=V(e.platform),r=V(e.kind),i=Nr(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Nr(e,t){let n=e??t;if(!(!n||!Object.hasOwn(br,n)))return br[n]}function Pr(e){let t=V(e.platform),n=V(e.appleOs),r=V(e.kind),i=V(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Fr(e,t){let n=V(e.name)??V(e.device)??`device`,r=V(e.platform),i=V(e.appleOs),a=[r,i===r?void 0:i,V(e.kind),V(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 Ir(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function z(e,t){for(let n of t){let t=V(e[n]);if(t)return t}}function B(e,t,n){n&&(e[t]=n)}function Lr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Rr(e,t){return t===1?e:`${e}s`}function V(e){let t=q(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function H(e){return V(e)}function U(e){return typeof e==`boolean`?e:void 0}function W(e,t){let n=H(e);return n&&t.includes(n)?n:void 0}function G(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function K(e){let t=q(e);return t?V(t.split(/[\\/]/).at(-1)):void 0}function q(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function J(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const zr=[`up`,`down`,`left`,`right`],Br=[`top`,`bottom`];function Vr(e){return`${e.command===p.reinstall?`Reinstalled`:`Installed`} ${Gr(e.result??{})??`app`}`}function Hr(e){let t=e.result??{};switch(e.command){case p.scroll:return qr(t);case p.screenshot:return Xr(t);case p.home:return`Went home`;case p.back:return Qr(t);case p.appSwitcher:return`Opened app switcher`;case p.orientation:return $r(t);case p.viewport:return ei(t);case p.clipboard:return ti(t);case p.keyboard:return ni(t);case p.tvRemote:return ai(t);case p.gesture:return oi(t);case p.swipe:return si(t);case p.trace:return li(`trace`,e);case p.record:return li(`recording`,e);default:return}}function Ur(e){let t=e.result??{};switch(e.command){case p.scroll:return G({direction:W(t.direction,zr),edge:W(t.edge,Br),passes:J(t.passes),amount:J(t.amount),pixels:J(t.pixels),durationMs:J(t.durationMs),x1:J(t.x1),y1:J(t.y1),x2:J(t.x2),y2:J(t.y2)});case p.screenshot:return G({requestedFileName:Zr(t)});case p.back:return G({mode:W(t.mode,me)});case p.orientation:return G({orientation:W(t.orientation,be)});case p.viewport:return G({width:J(t.width),height:J(t.height)});case p.clipboard:return G({action:W(t.action,[`read`,`write`])});case p.keyboard:return ii(t);case p.tvRemote:return G({button:W(t.button,_e),durationMs:J(t.durationMs)});case p.gesture:case p.swipe:return ci(t);case p.trace:case p.record:return G({action:W(t.action,[`start`,`stop`]),fileName:di(e),showTouches:U(t.showTouches)});default:return{}}}function Wr(e,t){if(e.command!==p.screenshot)return t;let n=Dr(e,t);return n?{...t,requestedFileName:n}:t}function Gr(e){let t=H(e.appName),n=fi(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Kr(e)}function Kr(e){let t=H(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function qr(e){let t=W(e.direction,zr),n=W(e.edge,Br),r=J(e.passes);return n?Jr(n,r):t?Yr(t,e):`Scrolled`}function Jr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Yr(e,t){let n=J(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=J(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Xr(e){let t=Zr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Zr(e){return K(e.requestedFileName)??K(e.path)}function Qr(e){return W(e.mode,me)===`system`?`Went back using system navigation`:`Went back`}function $r(e){let t=W(e.orientation,be);return t?`Rotated to ${t}`:`Changed orientation`}function ei(e){let t=J(e.width),n=J(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ti(e){let t=W(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ni(e){let t=q(e.action);if(!t||!R(t))return`Used keyboard`;if(t===`dismiss`)return ri(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=U(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ri(e){return U(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function ii(e){let t=q(e.action);return G({action:t&&R(t)?t:void 0,platform:W(e.platform,[`ios`,`android`]),visible:U(e.visible),wasVisible:U(e.wasVisible),dismissed:U(e.dismissed),attempts:J(e.attempts),mechanism:W(e.mechanism,[`dismissKey`])})}function ai(e){let t=W(e.button,_e);return t?`Pressed TV remote ${t}`:`Used TV remote`}function oi(e){let t=W(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function si(e){let t=J(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function ci(e){return G({kind:W(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:J(e.durationMs),pointerCount:J(e.pointerCount),x1:J(e.x1),y1:J(e.y1),x2:J(e.x2),y2:J(e.y2),count:J(e.count),pauseMs:J(e.pauseMs),pattern:W(e.pattern,[`one-way`,`ping-pong`]),scale:J(e.scale)})}function li(e,t){let n=ui(e,W(t.result?.action,[`start`,`stop`])),r=di(t);return r?`${n} ${r}`:n}function ui(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 di(e){let t=e.result??{};return K(t.requestedFileName)??K(t.outPath)??K(t.path)??K(e.positionals[1])}function fi(e,t){for(let n of t){let t=H(e[n]);if(t)return t}}function pi(e){switch(e.command){case p.open:return`Opened ${Y(e)??`session`}`;case p.close:return`Closed ${H(e.result?.session)??`session`}`;case p.click:case p.press:return`Tapped ${Y(e)??`target`}`;case p.longPress:return`Long pressed ${Y(e)??`target`}`;case p.fill:return`Filled ${Y(e)??`target`}`;case p.type:return`Typed text`;case p.install:case p.reinstall:case ve.installSource:return Vr(e);default:return Hr(e)??`Ran ${e.command}`}}function mi(e){return G({command:e.command,positionals:Ci(e),flags:Pi(e),...hi(e),...gi(e),..._i(e),...Ur(e)})}function hi(e){if(!vi(e.command))return{};let t=e.result??{};return G({ref:Q(t),targetLabel:Y(e),selectorChainLength:ji(t.selectorChain)?.length,x:J(t.x),y:J(t.y),x2:J(t.x2),y2:J(t.y2),durationMs:J(t.durationMs)})}function gi(e){if(!yi(e.command))return{};let t=e.result??{};return G({platform:W(t.platform,oe),target:W(t.target,ce),appName:H(t.appName),appBundleId:H(t.appBundleId),bundleId:H(t.bundleId),packageName:H(t.packageName),launchTarget:H(t.launchTarget)})}function _i(e){let t=e.result??{};return e.command===p.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==p.wait&&e.command!==p.find&&e.command!==p.get&&e.command!==p.is?{}:G({waitedMs:J(t.waitedMs),found:U(t.found)})}function vi(e){return e===p.click||e===p.press||e===p.longPress||e===p.focus||e===p.fill}function yi(e){return e===p.open||e===p.install||e===p.reinstall||e===ve.installSource}function Y(e){let t=e.result??{};return bi(t)??xi(t)??Si(t)??ki(e.positionals[0])}function bi(e){let t=Q(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function xi(e){let t=J(e.x),n=J(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Si(e){return H(e.appName)??H(e.appBundleId)??H(e.bundleId)??H(e.packageName)}function Ci(e){if(e.positionals.length!==0)return e.command===p.type?[Z(`text`)]:e.command===p.fill?wi(e):e.command===p.find?Ti(e):e.command===p.clipboard?Ei(e):e.command===p.push?Di(e,`app`,`payload`):e.command===p.triggerAppEvent?Di(e,`event`,`payload`):e.positionals.map(X)}function wi(e){let t=Z(`text`),n=e.result??{},r=Q(n);if(r)return[`@${r}`,t];if(H(n.selector))return[Z(`target`),t];let i=J(n.x),a=J(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Ti(e){let t=+!!Ai(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],Z(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,Z(`text`)]:[...r,...e.positionals.slice(n).map(Oi)]:r}function Ei(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,Z(`text`)]:e.positionals.map(X)}function Di(e,t,n){let[r,i,...a]=e.positionals;return[...r?[Z(t)]:[],...i?[Z(n)]:[],...a.map(X)]}function Oi(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:X(e)}function X(e){return ki(e)??Z(`arg`)}function ki(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function Z(e){return`<${e}>`}function Ai(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function ji(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Mi={enums:[{source:`platform`,values:se},{source:`target`,values:ce}]},Ni={[p.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:ye}]},[p.click]:Fi(),[p.press]:Fi(),[p.longPress]:Fi(),[p.fill]:Ii(),[p.type]:Ii(),[p.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[p.gesture]:Li(),[p.swipe]:Li(),[p.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[p.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[p.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:me}]},[p.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:le}]},[p.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[p.boot]:{booleans:[{source:`headless`}]},[p.close]:{booleans:[{source:`shutdown`}]}};function Pi(e){let t=e.flags??{},n={},r=Object.hasOwn(Ni,e.command)?Ni[e.command]:void 0;return Ri(n,t,Mi),Ri(n,t,r),Object.keys(n).length>0?n:void 0}function Fi(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:pe}]}}function Ii(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Li(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:he}]}}function Ri(e,t,n){n&&(zi(e,t,n.booleans??[]),Bi(e,t,n.numbers??[]),Vi(e,t,n.enums??[]))}function zi(e,t,n){for(let r of n)Hi(e,r.output??r.source,t[r.source])}function Bi(e,t,n){for(let r of n)Ui(e,r.output??r.source,t[r.source])}function Vi(e,t,n){for(let r of n)Wi(e,r.output??r.source,t[r.source],r.values)}function Q(e){let t=H(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Hi(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Ui(e,t,n){let r=J(n);r!==void 0&&(e[t]=r)}function Wi(e,t,n,r){let i=W(n,r);i!==void 0&&(e[t]=i)}const $=new Map,Gi=new Set;function Ki(e){return g.join(e,`events.ndjson`)}function qi(e){return e.command!==p.events}function Ji(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Xi(t,`${JSON.stringify(i)}\n`)}async function Yi(e){await(e?$.get(e):Promise.all($.values()))}function Xi(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Zi(e),await _.promises.appendFile(e,t,`utf8`)}).catch(t=>{m({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function Zi(e){let t=g.dirname(e);if(!Gi.has(t))try{await _.promises.mkdir(t,{recursive:!0}),Gi.add(t)}catch(t){throw m({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function Qi(e,t,n){Ji(e,t,{kind:`action.recorded`,requestId:h().requestId,command:n.command,summary:pi(n),details:mi(n)})}function $i(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??h().requestId,command:t.command,summary:`Started ${t.command}`}}function ea(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=xr(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ta(e,t={}){let n=oa(t.cursor),r=sa(t.limit);if(!_.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=na(e,n,r),a=i.lines.flatMap(e=>{let t=ca(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function na(e,t,n){let r=_.openSync(e,`r`);try{let e=new Ae(`utf8`),i=Buffer.allocUnsafe(65536),a=ra(t,n),o=``,s=0;do{s=_.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=ia(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&aa(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{_.closeSync(r)}}function ra(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function ia(e,t){let n=0;for(let r=e.indexOf(`
|
|
1
|
+
import{_ as e,j as t}from"./sdk-contracts.js";import{v as n}from"./location-coordinates.js";import{$t as r,Bn as i,Lr as a,Rr as o,Vn as s,Zt as c,b as l,rn as ee,zr as te}from"./sdk-batch-runner.js";import{_ as ne,i as re,r as ie,t as ae}from"./sdk-device.js";import{Gt as oe,Ht as se,Jt as ce,Qt as le,Xt as ue,Yt as de,Zt as u,an as fe,en as d,in as f,nn as pe,qt as me,rn as he,tn as ge,yn as _e}from"./script-source-bundle.js";import{C as ve,H as ye,K as p,N as be,n as xe}from"./interaction.js";import{n as m,t as Se}from"./command-catalog.js";import{t as Ce}from"./session.js";import{t as we}from"./device.js";import{n as Te,t as Ee}from"./path-resolution.js";import{A as h,M as g}from"./sdk-android-adb.js";import{n as De,t as _}from"./version.js";import{c as Oe,d as ke,n as Ae,s as je}from"./host-process.js";import v from"node:path";import Me from"node:crypto";import y from"node:fs";import{StringDecoder as Ne}from"node:string_decoder";function Pe(e,t={}){let n=[e.command];return e.command===`snapshot`?le(n,e):e.command===`open`?oe(n,e):e.command===`runtime`?de(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ce(n,e):e.command===`screenshot`?ue(n,e):me(n,e),n.join(` `)}function Fe(e){return e.targetEvidences?[i(e.targetEvidences)]:e.targetEvidence?[s(e.targetEvidence)]:[]}async function Ie(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function Le(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 Re(t,n,r){let i=[],a=0;for await(let o of t){let t=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=t.length,a>n)throw new e(`INVALID_ARGS`,r);i.push(t)}return Buffer.concat(i)}const ze=`/agent-device`,Be=`x-agent-device-tenant`;function Ve(e){return He(e,ze)}function He(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ue(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function We(e){let t=e?.trim();return t?{[Be]:t}:{}}const b={kind:`none`};function x(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function Ge(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Ke(e){return e.kind===`none`?void 0:e.target}function qe(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Je(e){return e.kind===`authoring`&&e.status===`aborted`}function Ye(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function Xe(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Ze(e){return{kind:`authoring`,status:`armed`,target:x(void 0,e)}}function Qe(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function $e(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function et(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:x(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function tt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function nt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function rt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function it(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function at(e){return e.kind===`repair`?e.boundary:void 0}function ot(e){return e.kind===`repair`?e.sourcePath:void 0}function st(e){return e.kind===`repair`&&e.status!==`committed`}function S(e){let t=Ke(e);return t?.kind===`explicit`?t.path:void 0}function ct(e){return Ke(e)?.force===!0}function C(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function lt(e){let t=C(e);return t.length>0&&t!==`.`&&t!==`..`}function w(e,t){return Te(e,{cwd:t})}function T(e){return e?.scriptPublication??b}function ut(e){let t=T(e);return t.kind===`authoring`&&t.status===`armed`}function dt(e,t){e.scriptPublication=Ze({path:t.path===void 0?void 0:w(t.path),force:t.force===!0})}function ft(e){e.scriptPublication=Qe(T(e))}function pt(e){return Ye(T(e))}function mt(e,t){if(!t.saveScript||Je(T(e)))return;let n={path:typeof t.saveScript==`string`?w(t.saveScript):void 0,force:t.force===!0},r=T(e);if(r.kind===`repair`){e.scriptPublication=et(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:x(r.target,n)};return}e.scriptPublication=Ze(n)}function ht(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:x(n.target,{path:t.explicitPath===void 0?void 0:w(t.explicitPath),force:t.liveForce===!0})})}function gt(e,t){e.scriptPublication=$e(T(e),t)}function _t(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication=$e(n,t))}function vt(e,t){return t===!0||ct(T(e))}function yt(e){return Xe(T(e))}function E(e){return e?.scriptPublication??b}function bt(e,t){let n=E(e);e.scriptPublication=et(n,{requested:{path:typeof t.saveScript==`string`?w(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function xt(e){e.scriptPublication=Ge(E(e))}function St(e){e.scriptPublication=tt(E(e))}function Ct(e,t){e.scriptPublication=nt(E(e),t)}function wt(e){e.scriptPublication=it(E(e))}function Tt(e,t){let n=E(e);return n.kind===`repair`&&n.closeReceipt===t}function Et(e){return E(e).kind===`repair`}function Dt(e){return st(E(e))}function D(e){return at(E(e))}function Ot(e){return ot(E(e))}function O(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 kt=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function k(t){if(t!==t.trim()||!se.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function At(e){return`\${${e}}`}function jt(e){let t=kt.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const Mt=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(`.`)),Nt=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Pt=new Set([`cost`,`evidence`,`resolution`,`settle`]),Ft=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`])]]),It=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 Lt(e,t,n){if(!e)return e;let r=Wt(e.selectorChain);return{...Bt(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!zt(e,t))}:{}}}function Rt(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 zt(e,t){return ee(e,t)}function Bt(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[Mt.has(e)?e:j(e,t,n),Vt(r,e,t,n)]))}function Vt(e,t,n,r){return typeof e==`string`&&Nt.has(t)?e:t===`selectorChain`&&Ut(e)?Ht(e,n):A(e,n,r,Pt.has(t)?t:void 0)}function A(e,t,n,r){if(typeof e==`string`)return r&&It.has(r)?e:j(e,t,n);if(Array.isArray(e))return e.map(e=>A(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Ft.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:j(e,t,n),A(a,t,n,o?`${r}.${e}`:void 0)]}))}function Ht(e,t){return e.filter(e=>!zt(e,t))}function j(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 Ut(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Wt(e){return Ut(e)?e:void 0}function Gt(e,t){if(t.flags?.noRecord||Xt(e,t))return;t.flags&&mt(e,t.flags);let n=Kt(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Qt(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),h({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Kt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=At(k(e.flags.recordAs)),n=O({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:qt(e.positionals,t),result:Lt(e.result,n,t),targetEvidence:Rt(e.targetEvidence,n,t)}}function qt(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 Jt=new Set([`snapshot`,`get`,`is`,`find`]);function Yt(e){return e.internal?.replayPlanStep===!0?!1:Jt.has(e.command)}function Xt(e,t){return!t.interactiveObservation||D(e)===void 0?!1:t.flags?.record!==!0}const Zt=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...n,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Qt(e){if(!e)return{};let t={};for(let n of Zt)e[n]!==void 0&&(t[n]=e[n]);return t}function $t(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`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(t.some(e=>e.command===`close`))throw new e(`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[e,n]of t.entries())l({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(on))throw new e(`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 en(t){for(let n of t){if(tn(n)){nn(n);continue}let t=sn(n),i=t??(n.command===`wait`?n.positionals[0]:void 0);if(i?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": 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`&&l(n)===`mutates-app`)throw new e(`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 a=t;if(!(!a||!r(a)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${a}": 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 tn(e){return rn(e)!==void 0}function nn(t){let n=rn(t);if(!n)return;let i=[n.source,n.destination];for(let n of i){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!r(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function rn(e){return e.command===`gesture`?ve(e.positionals):void 0}function an(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.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=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.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=t instanceof Error?t.message:String(t);return new e(`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 on(e){if(e.command!==`wait`)return!1;let t=c(e.positionals);return t?.kind!==`selector`||!r(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function sn(e){if(e.command===`get`)return e.positionals[1];if(he(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&cn(t)&&cn(n)?void 0:t}}function cn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function ln(e){let t=e.scriptPublication??b;return t.kind===`repair`?t.status===`committed`?!0:!qe(t):!1}function un(e){return Ye(e.scriptPublication??b)?ln(e):!0}var dn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=Et(e),r=t?.publication===`active`,i;try{if(un(e))return{written:!1};let a=fn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=v.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),hn({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=rt(e.scriptPublication??b)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return pn({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=S(e.scriptPublication??b);if(t)return w(t);let n=C(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return v.join(this.sessionsDir,`${n}-${r}.ad`)}};function fn(e,t){let n=gn(e,{strictPortableRefs:t.activePublication});return t.activePublication&&$t(n),{script:En(e,n,t.appendCompleteSentinel),actionCount:n.length}}function pn(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(h({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:mn(r,i)};if(o)return{written:!1,error:an(r,i)};if(r instanceof e)throw r;return{written:!1}}function mn(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`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 hn(t){let{scriptPath:n,script:r,force:i}=t,a=v.dirname(n),o=v.join(a,`.${v.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);y.writeFileSync(o,r);try{if(i){y.renameSync(o,n);return}y.linkSync(o,n)}catch(t){throw t.code===`EEXIST`?new e(`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}):t}finally{y.rmSync(o,{force:!0})}}function gn(e,t={}){let n=D(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=yn(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&_n(n);let o=Tn(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&en(a),a}function _n(t){let n=t.command===`gesture`?ve(t.positionals??[]):void 0;if(n){vn(n);return}if(!M(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function vn(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function yn(e){let t=bn(e);if(!(!t||!M(e.command)))return pe(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Sn(e,t):e.command===`fill`?xn(e,t):Cn(e,t)}function bn(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 M(e){return he(e)||e===`fill`||e===`get`}function xn(e,t){let n=O(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Sn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):wn(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Cn(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function wn(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Tn(e,t){if(!M(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 En(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${ne(e.device)} device=${ge(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Fe(e)),r.push(Dn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
+
`)}\n`}function Dn(e){return On([e.command],e)||Pe(e)}function On(e,t){if(pe(t.command))return kn(e,t);if(t.command===`fill`)return An(e,t);if(t.command===`get`)return jn(e,t)}function kn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(d(f(n))),N(e,t),u(e,t),e.join(` `);if(t.positionals.length===1)return e.push(d(n)),u(e,t),e.join(` `)}}function An(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(d(f(n))),N(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(d(r)),u(e,t),e.join(` `)}function jn(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(d(n)),e.push(d(f(r))),r.startsWith(`@`)&&N(e,t),e.join(` `)}function N(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(d(n))}const Mn=[`status`,`get`,`dismiss`,`enter`,`return`];function P(e){return Mn.includes(e)}const Nn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Pn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Fn(e,t){let n=t??{};switch(e.command){case m.devices:return In(n.devices);case m.apps:return Ln(n.apps,e.flags?.appsFilter);case m.boot:return Rn(`Booted`,n,!0);case m.shutdown:return Rn(`Shut down`,n,!1);case m.install:return zn(`Installed`,n);case m.reinstall:return zn(`Reinstalled`,n);case m.screenshot:return Bn(e,n);default:return{}}}function In(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Hn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Zn(`Found ${t.length} ${Qn(`device`,t.length)}`,i.map(e=>Yn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Ln(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=L(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Zn(`Found ${n.length} ${Qn(`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 Rn(e,t,n){let r=Un(t);if(!r)return{};let i={device:r,...Jn(t),booted:n};return{summary:`${e} ${Yn(i,!1)}`,details:i}}function zn(e,t){let n=L(t.appName),r=L(t.bundleId),i=F(t,[`packageName`,`package`]),a=L(t.platform),o=L(t.launchTarget),s=F(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Xn(n,s);if(!c)return{};let l={};return I(l,`appName`,n),I(l,`bundleId`,r),I(l,`packageName`,i),I(l,`platform`,a),o!==s&&I(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Bn(e,t){let n=Vn(e,t);return n?{details:{requestedFileName:n}}:{}}function Vn(e,t){let n=U(e.meta?.clientArtifactPaths?.path)??U(t.path);if(n)return H(n)}function Hn(e){if(!a(e))return;let t=Un(e);if(t)return{name:t,...Jn(e)}}function Un(e){let t=F(e,[`name`,`deviceName`,`device`]);return!t||!Wn(e,t)?t:Kn(e)}function Wn(e,t){let n=Gn(t);return Nn.some(t=>{let r=L(e[t]);return r!==void 0&&Gn(r)===n})}function Gn(e){return e.toLowerCase()}function Kn(e){let t=L(e.appleOs),n=L(e.platform),r=L(e.kind),i=qn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function qn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Pn,n)))return Pn[n]}function Jn(e){let t=L(e.platform),n=L(e.appleOs),r=L(e.kind),i=L(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Yn(e,t){let n=L(e.name)??L(e.device)??`device`,r=L(e.platform),i=L(e.appleOs),a=[r,i===r?void 0:i,L(e.kind),L(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 Xn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function F(e,t){for(let n of t){let t=L(e[n]);if(t)return t}}function I(e,t,n){n&&(e[t]=n)}function Zn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Qn(e,t){return t===1?e:`${e}s`}function L(e){let t=U(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function R(e){return L(e)}function z(e){return typeof e==`boolean`?e:void 0}function B(e,t){let n=R(e);return n&&t.includes(n)?n:void 0}function V(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function H(e){let t=U(e);return t?L(t.split(/[\\/]/).at(-1)):void 0}function U(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function W(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const $n=[`up`,`down`,`left`,`right`],er=[`top`,`bottom`];function tr(e){return`${e.command===m.reinstall?`Reinstalled`:`Installed`} ${ar(e.result??{})??`app`}`}function nr(e){let t=e.result??{};switch(e.command){case m.scroll:return sr(t);case m.screenshot:return ur(t);case m.home:return`Went home`;case m.back:return fr(t);case m.appSwitcher:return`Opened app switcher`;case m.orientation:return pr(t);case m.viewport:return mr(t);case m.clipboard:return hr(t);case m.keyboard:return gr(t);case m.tvRemote:return yr(t);case m.gesture:return br(t);case m.swipe:return xr(t);case m.trace:return Cr(`trace`,e);case m.record:return Cr(`recording`,e);default:return}}function rr(e){let t=e.result??{};switch(e.command){case m.scroll:return V({direction:B(t.direction,$n),edge:B(t.edge,er),passes:W(t.passes),amount:W(t.amount),pixels:W(t.pixels),durationMs:W(t.durationMs),x1:W(t.x1),y1:W(t.y1),x2:W(t.x2),y2:W(t.y2)});case m.screenshot:return V({requestedFileName:dr(t)});case m.back:return V({mode:B(t.mode,p)});case m.orientation:return V({orientation:B(t.orientation,we)});case m.viewport:return V({width:W(t.width),height:W(t.height)});case m.clipboard:return V({action:B(t.action,[`read`,`write`])});case m.keyboard:return vr(t);case m.tvRemote:return V({button:B(t.button,xe),durationMs:W(t.durationMs)});case m.gesture:case m.swipe:return Sr(t);case m.trace:case m.record:return V({action:B(t.action,[`start`,`stop`]),fileName:Tr(e),showTouches:z(t.showTouches)});default:return{}}}function ir(e,t){if(e.command!==m.screenshot)return t;let n=Vn(e,t);return n?{...t,requestedFileName:n}:t}function ar(e){let t=R(e.appName),n=Er(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??or(e)}function or(e){let t=R(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function sr(e){let t=B(e.direction,$n),n=B(e.edge,er),r=W(e.passes);return n?cr(n,r):t?lr(t,e):`Scrolled`}function cr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function lr(e,t){let n=W(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=W(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function ur(e){let t=dr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function dr(e){return H(e.requestedFileName)??H(e.path)}function fr(e){return B(e.mode,p)===`system`?`Went back using system navigation`:`Went back`}function pr(e){let t=B(e.orientation,we);return t?`Rotated to ${t}`:`Changed orientation`}function mr(e){let t=W(e.width),n=W(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function hr(e){let t=B(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function gr(e){let t=U(e.action);if(!t||!P(t))return`Used keyboard`;if(t===`dismiss`)return _r(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=z(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function _r(e){return z(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function vr(e){let t=U(e.action);return V({action:t&&P(t)?t:void 0,platform:B(e.platform,[`ios`,`android`]),visible:z(e.visible),wasVisible:z(e.wasVisible),dismissed:z(e.dismissed),attempts:W(e.attempts),mechanism:B(e.mechanism,[`dismissKey`])})}function yr(e){let t=B(e.button,xe);return t?`Pressed TV remote ${t}`:`Used TV remote`}function br(e){let t=B(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function xr(e){let t=W(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Sr(e){return V({kind:B(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:W(e.durationMs),pointerCount:W(e.pointerCount),x1:W(e.x1),y1:W(e.y1),x2:W(e.x2),y2:W(e.y2),count:W(e.count),pauseMs:W(e.pauseMs),pattern:B(e.pattern,[`one-way`,`ping-pong`]),scale:W(e.scale)})}function Cr(e,t){let n=wr(e,B(t.result?.action,[`start`,`stop`])),r=Tr(t);return r?`${n} ${r}`:n}function wr(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 Tr(e){let t=e.result??{};return H(t.requestedFileName)??H(t.outPath)??H(t.path)??H(e.positionals[1])}function Er(e,t){for(let n of t){let t=R(e[n]);if(t)return t}}function Dr(e){switch(e.command){case m.open:return`Opened ${G(e)??`session`}`;case m.close:return`Closed ${R(e.result?.session)??`session`}`;case m.click:case m.press:return`Tapped ${G(e)??`target`}`;case m.longPress:return`Long pressed ${G(e)??`target`}`;case m.hover:return`Hovered ${G(e)??`target`}`;case m.fill:return`Filled ${G(e)??`target`}`;case m.type:return`Typed text`;case m.install:case m.reinstall:case Se.installSource:return tr(e);default:return nr(e)??`Ran ${e.command}`}}function Or(e){return V({command:e.command,positionals:Lr(e),flags:Jr(e),...kr(e),...Ar(e),...jr(e),...rr(e)})}function kr(e){if(!Mr(e.command))return{};let t=e.result??{};return V({ref:Y(t),targetLabel:G(e),selectorChainLength:Gr(t.selectorChain)?.length,x:W(t.x),y:W(t.y),x2:W(t.x2),y2:W(t.y2),durationMs:W(t.durationMs)})}function Ar(e){if(!Nr(e.command))return{};let t=e.result??{};return V({platform:B(t.platform,re),target:B(t.target,ae),appName:R(t.appName),appBundleId:R(t.appBundleId),bundleId:R(t.bundleId),packageName:R(t.packageName),launchTarget:R(t.launchTarget)})}function jr(e){let t=e.result??{};return e.command===m.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==m.wait&&e.command!==m.find&&e.command!==m.get&&e.command!==m.is?{}:V({waitedMs:W(t.waitedMs),found:z(t.found)})}function Mr(e){return e===m.click||e===m.press||e===m.longPress||e===m.hover||e===m.focus||e===m.fill}function Nr(e){return e===m.open||e===m.install||e===m.reinstall||e===Se.installSource}function G(e){let t=e.result??{};return Pr(t)??Fr(t)??Ir(t)??Ur(e.positionals[0])}function Pr(e){let t=Y(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Fr(e){let t=W(e.x),n=W(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Ir(e){return R(e.appName)??R(e.appBundleId)??R(e.bundleId)??R(e.packageName)}function Lr(e){if(e.positionals.length!==0)return e.command===m.type?[q(`text`)]:e.command===m.fill?Rr(e):e.command===m.find?zr(e):e.command===m.clipboard?Br(e):e.command===m.push?Vr(e,`app`,`payload`):e.command===m.triggerAppEvent?Vr(e,`event`,`payload`):e.positionals.map(K)}function Rr(e){let t=q(`text`),n=e.result??{},r=Y(n);if(r)return[`@${r}`,t];if(R(n.selector))return[q(`target`),t];let i=W(n.x),a=W(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function zr(e){let t=+!!Wr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,q(`text`)]:[...r,...e.positionals.slice(n).map(Hr)]:r}function Br(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,q(`text`)]:e.positionals.map(K)}function Vr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[q(t)]:[],...i?[q(n)]:[],...a.map(K)]}function Hr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:K(e)}function K(e){return Ur(e)??q(`arg`)}function Ur(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function q(e){return`<${e}>`}function Wr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Gr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Kr={enums:[{source:`platform`,values:ie},{source:`target`,values:ae}]},qr={[m.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Ce}]},[m.click]:J(),[m.press]:J(),[m.longPress]:J(),[m.hover]:J(),[m.fill]:Yr(),[m.type]:Yr(),[m.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[m.gesture]:Xr(),[m.swipe]:Xr(),[m.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[m.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[m.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:p}]},[m.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:fe}]},[m.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[m.boot]:{booleans:[{source:`headless`}]},[m.close]:{booleans:[{source:`shutdown`}]}};function Jr(e){let t=e.flags??{},n={},r=Object.hasOwn(qr,e.command)?qr[e.command]:void 0;return Zr(n,t,Kr),Zr(n,t,r),Object.keys(n).length>0?n:void 0}function J(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ye}]}}function Yr(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Xr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:be}]}}function Zr(e,t,n){n&&(Qr(e,t,n.booleans??[]),$r(e,t,n.numbers??[]),ei(e,t,n.enums??[]))}function Qr(e,t,n){for(let r of n)ti(e,r.output??r.source,t[r.source])}function $r(e,t,n){for(let r of n)ni(e,r.output??r.source,t[r.source])}function ei(e,t,n){for(let r of n)ri(e,r.output??r.source,t[r.source],r.values)}function Y(e){let t=R(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function ti(e,t,n){typeof n==`boolean`&&(e[t]=n)}function ni(e,t,n){let r=W(n);r!==void 0&&(e[t]=r)}function ri(e,t,n,r){let i=B(n,r);i!==void 0&&(e[t]=i)}const X=new Map,ii=new Set;function ai(e){return v.join(e,`events.ndjson`)}function oi(e){return e.command!==m.events}function si(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});li(e,`${JSON.stringify(i)}\n`)}async function ci(e){await(e?X.get(e):Promise.all(X.values()))}function li(e,t){let n=(X.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ui(e),await y.promises.appendFile(e,t,`utf8`)}).catch(t=>{h({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{X.get(e)===n&&X.delete(e)});X.set(e,n)}async function ui(e){let t=v.dirname(e);if(!ii.has(t))try{await y.promises.mkdir(t,{recursive:!0}),ii.add(t)}catch(t){throw h({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function di(e,t,n){si(e,t,{kind:`action.recorded`,requestId:g().requestId,command:n.command,summary:Dr(n),details:Or(n)})}function fi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??g().requestId,command:t.command,summary:`Started ${t.command}`}}function pi(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Fn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??g().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??g().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function mi(e,t={}){let n=yi(t.cursor),r=bi(t.limit);if(!y.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=hi(e,n,r),a=i.lines.flatMap(e=>{let t=xi(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function hi(e,t,n){let r=y.openSync(e,`r`);try{let e=new Ne(`utf8`),i=Buffer.allocUnsafe(65536),a=gi(t,n),o=``,s=0;do{s=y.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=_i(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&vi(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{y.closeSync(r)}}function gi(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function _i(e,t){let n=0;for(let r=e.indexOf(`
|
|
3
3
|
`);r!==-1;r=e.indexOf(`
|
|
4
|
-
`,n))if(
|
|
4
|
+
`,n))if(vi(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function vi(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 yi(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function bi(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function xi(e){try{let t=Si(JSON.parse(e));return t?Ci(t):void 0}catch{return}}function Si(e){if(a(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&wi(e.kind))return e}function Ci(e){let t=a(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}:{},...Ti(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function wi(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Ti(e){return e===`ok`||e===`error`}const Ei=60*6e4;var Di=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new dn(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=Gt(e,t);if(n){let t=this.resolveStoredSessionName(e);di(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){si(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return mi(this.resolveEventLogPath(e),t)}async flushEvents(e){await ci(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&h({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:vt(e,void 0)});Dt(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,Ei,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){qe(e.scriptPublication??b)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,..._e(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=Ei,n){try{let r=this.resolveSessionDir(e.name);y.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...Ot(e)?{sourcePath:Ot(e)}:{},...n?{commitFailure:n}:{}};y.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){h({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Oi(this.repairTombstonePath(e))}clearRepairTombstone(e){try{y.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return v.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=C(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return v.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!lt(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return v.join(this.sessionsDir,C(t))}resolveDaemonStateDir(){return v.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return y.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return v.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return v.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return ai(this.resolveSessionDir(e))}static expandHome(e,t){return w(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function Oi(e){let t;try{t=y.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 ki(e){let t;try{t=y.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=Oi(v.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function Ai(e){return v.join(e,`runner.log`)}function Z(e,t){let n=C(t&&t.length>0?t:`unknown`);return v.join(e,`requests`,`${n}.ndjson`)}function ji(e){return{path:Z(e.sessionDir,e.requestId),ref:{session:e.session,requestId:e.requestId&&e.requestId.length>0?e.requestId:`unknown`}}}function Mi(e,t){return Z(v.join(e,`remote-diagnostics`,C(t.session)),t.requestId)}function Ni(e,t={}){let n=Pi(e,t);return{baseDir:n,infoPath:v.join(n,`daemon.json`),lockPath:v.join(n,`daemon.lock`),logPath:v.join(n,`daemon.log`),sessionsDir:v.join(n,`sessions`)}}function Pi(e,t){let n=(e??``).trim();return n?Te(n,{env:t.env}):Fi(t)}function Fi(e={}){let t=v.join(Ee(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??_();return Ii(n)?v.join(t,`dev`,Li(n)):t}function Ii(e){return y.existsSync(v.join(e,`package.json`))&&y.existsSync(v.join(e,`src`,`daemon.ts`))}function Li(e){let t=Ri(e),n=v.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=Me.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function Ri(e){try{return y.realpathSync.native(e)}catch{return v.resolve(e)}}function zi(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function Bi(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Vi(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function Hi(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Ui=/(['"])(\.\.?\/[^'"]*)\1/g,Wi=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function Gi(){let e=process.argv[1];return e?Ki(e):`unknown`}function Ki(e,t=_()){try{let n=v.resolve(t),r=[v.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=y.statSync(e);if(!t.isFile())continue;let o=v.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=y.readFileSync(e,`utf8`);for(let t of qi(s)){let n=Ji(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=Me.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function qi(e){let t=new Set;Ui.lastIndex=0;let n=null;for(;(n=Ui.exec(e))!==null;)t.add(n[2]);return[...t]}function Ji(e,t){let n=v.resolve(v.dirname(e),t),r=Q(n);if(r)return r;for(let e of Wi){let t=Q(`${n}${e}`);if(t)return t}for(let e of Wi){let t=Q(v.join(n,`index${e}`));if(t)return t}return null}function Q(e){try{return y.statSync(e).isFile()?e:null}catch{return null}}const Yi=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Xi(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Yi.some(e=>e.test(t)):!1}function Zi(e,t){if(!Ae(e))return!1;if(t){let n=Oe(e);if(!n||n!==t)return!1}let n=je(e);return n?Xi(n):!1}function $(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 Qi(e,t){Zi(e,t.expectedStartTime)&&$(e,`SIGTERM`)&&(await ke(e,t.termTimeoutMs)||$(e,`SIGKILL`)&&await ke(e,t.killTimeoutMs))}function $i(e,t){let n=[],r=e+t.toString(),i=r.indexOf(`
|
|
5
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
|
|
6
|
+
`)}return{lines:n,buffer:r}}function ea(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function ta(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function na(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function ra(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function ia(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function aa(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function oa(e,t={}){return{ok:!0,service:e,version:De(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function sa(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 ca(e){if(a(e))return sa({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(fa).flatMap(e=>{let t=la(e);return t?[t]:[]}):void 0})}function la(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=ua(e);if(t)return{ref:e.ref,...da(e),...t}}function ua(e){let t=te(e.rect);if(!t)return;let n=te(e.overlayRect);if(!n)return;let r=o(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function da(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function fa(e){return a(e)}export{yt as $,Lr as A,bt as B,Mi as C,pi as D,Ai as E,jt as F,Ct as G,Et as H,At as I,ft as J,D as K,k as L,P as M,Yt as N,fi as O,Lt as P,pt as Q,O as R,ki as S,Z as T,Dt as U,Tt as V,St as W,vt as X,dt as Y,ut as Z,Ni as _,Le as _t,na as a,C as at,Vi as b,aa as c,S as ct,Zi as d,Ue as dt,gt as et,Qi as f,Ve as ft,Hi as g,Re as gt,Gi as h,Ie as ht,ta as i,lt as it,ir as j,oi as k,ea as l,ze as lt,Ki as m,He as mt,ca as n,ht as nt,ra as o,b as ot,$ as p,We as pt,xt as q,oa as r,w as rt,ia as s,ct as st,sa as t,_t as tt,$i as u,Be as ut,zi as v,ji as w,Di as x,Bi as y,wt as z};
|
package/dist/src/screenshot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,a as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e,a as t}from"./sdk-contracts.js";import{vt as n,yt as r}from"./script-source-bundle.js";import{t as i}from"./screenshot-result.js";import{n as a}from"./path-resolution.js";import{t as o}from"./shared.js";import{t as s}from"./cli-runner.js";const c=async({positionals:e,flags:n,client:r})=>{let a=await s({client:r,command:`screenshot`,positionals:e,flags:n});return t(n.responseLevel)?(o(n,a,()=>JSON.stringify(a,null,2)),!0):(o(n,i(a),()=>a.overlayRefs?`Annotated ${a.overlayRefs.length} refs onto ${a.path}`:d(a)),!0)},l=async({positionals:t,flags:i,client:c})=>{if(t[0]===`snapshot`){let e=await s({client:c,command:`diff`,positionals:t,flags:i});return o(i,e,()=>r(e)),!0}if(t[0]!==`screenshot`)return!1;let l=i.baseline;if(!l||typeof l!=`string`)throw new e(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let d=a(l),f=typeof i.out==`string`?a(i.out):void 0,m=t[1];if(t.length>2)throw new e(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:h,localCommandPolicy:g},{createLocalArtifactAdapter:_}]=await Promise.all([import(`./runtime.js`).then(e=>e.r),import(`./sdk-io.js`).then(e=>e.n)]),v=await h({backend:u(c,i),artifacts:_(),sessions:{get:e=>({name:e}),set:()=>{}},policy:g()}).capture.diffScreenshot({session:i.session,baseline:{kind:`path`,path:d},current:m?{kind:`path`,path:a(m)}:{kind:`live`},...f?{out:{kind:`path`,path:f}}:{},threshold:p(i.threshold),overlayRefs:i.overlayRefs,normalizeStatusBar:i.screenshotNormalizeStatusBar,surface:i.surface});return o(i,v,()=>n(v)),!0};function u(e,t){return{platform:f(t),captureScreenshot:async(t,n,r)=>i(await e.capture.screenshot({path:n,session:t.session,overlayRefs:r?.overlayRefs,pixelDensity:r?.pixelDensity,fullscreen:r?.fullscreen,normalizeStatusBar:r?.normalizeStatusBar,stabilize:r?.stabilize,surface:r?.surface}))}}function d(e){if(typeof e.width!=`number`||typeof e.height!=`number`)return e.path;let t=typeof e.pixelDensity==`number`?` @${e.pixelDensity}x`:``;return`${e.path} (${e.width}x${e.height}${t})`}function f(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function p(e){if(!(e==null||e===``))return Number(e)}export{l as diffCommand,c as screenshotCommand};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{E as e,_ as t,d as n,f as r,g as i,h as a,j as o,p as s,u as c}from"./sdk-contracts.js";import{C as l,S as u,_ as d,m as f}from"./location-coordinates.js";import{Ar as p,Cr as m,Dn as h,Dr as g,En as _,Fn as v,Hn as y,In as ee,Jr as b,Lt as te,Mn as ne,Mr as re,Nn as ie,Pn as ae,Rn as oe,Rt as se,Sr as ce,Tr as le,Un as ue,Ut as de,_r as x,ar as fe,br as pe,cr as me,dn as he,gn as ge,hn as _e,ir as ve,kn as ye,kr as be,ln as S,mn as xe,mr as Se,or as Ce,pn as we,pr as Te,rr as Ee,sr as De,un as Oe,vr as ke,wr as Ae,yr as je}from"./sdk-batch-runner.js";import{p as Me,r as Ne}from"./sdk-device.js";import{n as Pe}from"./snapshot-scope.js";import{r as Fe}from"./recording-export-quality.js";import{S as Ie,b as Le,d as Re,f as ze,g as Be,t as Ve,u as He}from"./interaction.js";import{n as Ue,o as We,r as Ge,t as Ke}from"./mobile-snapshot-semantics.js";import{n as qe,t as Je}from"./verdict.js";import"./device.js";import{n as Ye}from"./path-resolution.js";import Xe from"node:path";import{styleText as Ze}from"node:util";import{createHash as Qe}from"node:crypto";import $e from"node:fs";const et=3e5,tt=[`leaseId`,`tenantId`,`runId`,`clientId`,`deviceKey`];function nt(e){return b({tenantId:e.meta?.tenantId??C(e.flags,`tenant`),runId:e.meta?.runId??C(e.flags,`runId`),leaseId:e.meta?.leaseId??C(e.flags,`leaseId`),leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend,leaseProvider:e.meta?.leaseProvider??C(e.flags,`leaseProvider`)??C(e.flags,`provider`),deviceKey:e.meta?.deviceKey??C(e.flags,`deviceKey`),clientId:e.meta?.clientId??C(e.flags,`clientId`)})}function rt(e){return b({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 it(e){return b({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 at(e){return b({tenant:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function ot(e){return b({tenantId:e.tenantId??``,runId:e.runId??``,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function st(e){return pt(e)}function ct(e){let{ttlMs:t,...n}=pt(e);return n}function lt(e,t,n){let r=b({...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,...b({ttlMs:e.leaseTtlMs,backend:e.leaseBackend})};case`lease_heartbeat`:return{...r,...b({leaseId:e.leaseId,ttlMs:e.leaseTtlMs})};case`lease_release`:return{...r,...b({leaseId:e.leaseId})}}}function ut(e){let t=b({leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId});return Object.keys(t).length>0?t:void 0}function dt(e){return e.leaseProvider===`proxy`}function ft(e){return dt(e)?tt.filter(t=>!e[t]):[]}function pt(e){return b({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 C(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function w(e){return e?{message:e}:{}}function mt(e,t){return t?{...e,message:t}:e}function ht(e){return typeof e?.message==`string`&&e.message.length>0?e.message:null}function gt(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function _t(e,t,n){return{deviceId:t,deviceName:n,...Me(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function vt(e,t={}){let n=t.includeSerial??!0,r=yt(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 yt(e){return Me(e.platform)?e.identifiers.serial??e.id:void 0}function bt(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...vt(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function xt(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 St(e){return e.bundleId??e.package??e.app}function Ct(e){return mt({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: ${St(e)}`)}function wt(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function Tt(e){return mt({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: ${wt(e)}`)}function Et(e){let t=e.appName??e.appBundleId??e.session;return mt({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?vt(e.device):{},...e.snapshot?{snapshot:e.snapshot}:{},...e.initialSnapshotError?{initialSnapshotError:e.initialSnapshotError}:{}},t?`Opened: ${t}`:`Opened`)}function Dt(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...w(e.session?`Closed: ${e.session}`:`Closed`)}}function Ot(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...f(kt(e)),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.fallbackScreenshotPath?{fallbackScreenshotPath:e.fallbackScreenshotPath}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function kt(e){return{...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}}const At=[`app`,`device`,`system`];function jt(e){return e===`device`||e===`system`}function T(e){return e.startsWith(`@`)?a(e)?.base??e:e}const Mt=/^-?\d+(\.\d+)?$/,Nt=/^[^\s"\\]+$/,Pt=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Ft=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),It=new Map([[`--pointer-count`,`pointerCount`]]),Lt=new Map([[`--delay-ms`,`delayMs`]]);function E(e){return e===`click`||e===`press`}function Rt(e){return E(e)||e===`longpress`||e===`hover`}function zt(e){return e===`type`||e===`fill`}function D(e){return Vt(e,Ht)}function Bt(e){return JSON.stringify(e)}function O(e){return Vt(e,Ut)}function Vt(e,t){return t(e)?e:Bt(e)}function Ht(e){return Ut(e)&&e.startsWith(`@`)||Mt.test(e)}function Ut(e){return Nt.test(e)}const Wt=new Set([`fill`,`type`]);function Gt(e){if(!Wt.has(e.command)){let t=(e.positionals??[]).map(e=>D(e));return[e.command,...t].join(` `)}let t=Kt(e).map(e=>D(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function Kt(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&Mt.test(n)&&Mt.test(t[1]??``)?[n,t[1]]:[n]}function qt(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}zt(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Jt(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`,O(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`,O(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,O(t.launchUrl)))}function Yt(e,t){let[n,...r]=t.positionals??[];n&&e.push(O(n));for(let t of r)e.push(D(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(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 Xt(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`,D(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Zt(e,t){for(let n of t.positionals??[])e.push(D(n));u(e,t.flags)}function Qt(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(O(t));Jt(e,t.flags)}function $t(e,t){for(let n of t.positionals??[])e.push(D(t.command===`wait`?T(n):n));qt(e,t)}function en(e,t){let n=[],r={},i=E(e)?Pt:e===`swipe`?Ft:e===`gesture`?It:zt(e)?Lt: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=nn(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 tn(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=nn(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 nn(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function rn(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function an(e,t){for(let n of t.positionals??[])e.push(D(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),Jt(e,t.runtime)}function on(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=tn(t);return{positionals:r.positionals,flags:n,runtime:sn(r.flags)?r.flags:void 0}}function sn(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const cn=/^[A-Z_][A-Z0-9_]*$/,ln=new Set(Ne.filter(e=>e!==`web`)),un=new Set([`mobile`,`tv`,`desktop`]);function dn(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,o,s=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,c]of i.entries()){let i=c.trim();if(i.length===0){o&&s(o,e,`is blank`);continue}if(i.startsWith(`#`)){let t=y(i);if(t.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=ue(i);if(n.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:e+1};continue}o&&s(o,e,`is a comment`);continue}if(pn(i)){if(o&&s(o,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let l=vn(c);if(!l){o&&s(o,e,`did not parse as an action`);continue}let u=Ie(l.command,l.positionals??[],`line ${e+1}`);if(u)throw new t(`INVALID_ARGS`,u);o&&=(o.kind===`single`?l.targetEvidence=o.evidence:l.targetEvidences=o.evidence,void 0),n.push(l),r.push(e+1),a=!0}if(o)throw new t(`INVALID_ARGS`,`${o.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function fn(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(pn(t)){gn(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&ln.has(e)&&_n(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&un.has(e)&&_n(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&_n(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&_n(n,`retries`,Math.floor(e))}}return n}function pn(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function mn(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!cn.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:hn(r.slice(i+1),n)}}function hn(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function gn(e,n,r){let{key:i,value:a}=mn(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function _n(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function vn(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[r,...i]=xn(n);if(r===void 0||r===`context`)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if(r===`snapshot`){a.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if(t===`-i`){a.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){a.flags.snapshotRaw=!0;continue}if(t===`--force-full`){a.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<i.length){a.flags.snapshotScope=i[e+1],e+=1;continue}if(t===`--backend`&&e+1<i.length){e+=1;continue}}}return a}if(r===`open`){let e=on(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if(r===`runtime`){let e=tn(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(E(r)){let e=en(r,i);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(t===void 0)return a;if(t.startsWith(`@`))return a.positionals=[T(t)],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let n=e.positionals[0],o=e.positionals[1];return bn(n)&&bn(o)&&e.positionals.length>=2?(a.positionals=[n,o],a):(a.positionals=[e.positionals.join(` `)],a)}if(r===`fill`){let e=en(r,i);if(Object.assign(a.flags,e.flags),!yn(e.positionals))return a.positionals=e.positionals,a;let[t,n,...o]=e.positionals;if(bn(t)&&bn(n))return a.positionals=[t,n,o.join(` `)],a;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=T(s);return l.length>0?(a.positionals=[e,l.join(` `)],a.result={refLabel:c},a):(a.positionals=[e,c],a)}return a.positionals=[s,[c,...l].join(` `)],a}if(r===`get`){let e=i[0],t=i[1];return e===void 0||t===void 0?(a.positionals=i,a):t.startsWith(`@`)?(a.positionals=[e,T(t)],i[2]&&(a.result={refLabel:i[2]}),a):(a.positionals=[e,i.slice(1).join(` `)],a)}if(r===`swipe`||r===`type`||r===`gesture`){let e=en(r,i);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if(r===`record`){let e=[];for(let n=0;n<i.length;n+=1){let r=i[n];if(r===d.cliToken)throw new t(`INVALID_ARGS`,d.migration.record);if(r===`--hide-touches`){a.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<i.length){let e=Number(i[n+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<i.length){let e=i[n+1],t=Fe(e);t!==void 0&&(a.flags.quality=t),n+=1;continue}e.push(r)}return a.positionals=e,a}if(r===`screenshot`){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=l({args:i,index:t,flags:a.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return a.positionals=e,a}return a.positionals=r===`wait`||r===`longpress`||r===`hover`?i.map(e=>T(e)):i,a}function yn(e){return e.length>=2}function bn(e){return e?!Number.isNaN(Number(e)):!1}function xn(e){let t=[],n=0;for(;n<e.length&&(n=Sn(e,n),!(n>=e.length));){let r=e[n]===`"`?Cn(e,n):wn(e,n);t.push(r.value),n=r.nextCursor}return t}function Sn(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Cn(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function wn(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function k(e){return e.startsWith(`AD_`)}function Tn(e){return new t(`INVALID_ARGS`,`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function En(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(k(n))throw Tn(n);t[n]=r}return{values:t,expandedBuiltinNames:new Set}}function Dn(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&&cn.test(e)&&(k(e)||(t[e]=r))}return t}function On(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(!cn.test(i))throw new t(`INVALID_ARGS`,`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(k(i))throw Tn(i);n[i]=r.slice(e+1)}return n}function kn(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function An(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 jn(e){return e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`||e===`_`}function Mn(e){return jn(e)||e>=`0`&&e<=`9`||e===`.`}function Nn(e){return e===`
|
|
2
|
+
`||e===`\r`||e===`\u2028`||e===`\u2029`}function Pn(e,t){let n=t+2;if(n>=e.length||!jn(e[n]))return null;for(n+=1;n<e.length&&Mn(e[n]);)n+=1;let r=e.slice(t+2,n);if(e[n]===`}`)return{key:r,fallback:void 0,end:n+1};if(e[n]!==`:`||e[n+1]!==`-`)return null;n+=2;let i=``;for(;n<e.length;){let t=e[n];if(t===`}`)return{key:r,fallback:i,end:n+1};if(t===`\\`){let t=e[n+1];if(t===void 0)return{abortEnd:e.length};if(Nn(t))return{abortEnd:n+2};i+=t,n+=2;continue}i+=t,n+=1}return{abortEnd:e.length}}function Fn(e,n,r){let i=``,a=0;for(;a<e.length;){let o=e[a];if(o===`\\`&&e.startsWith("${",a+1)){i+="${",a+=3;continue}if(o===`$`&&e[a+1]===`{`){let o=Pn(e,a);if(o!==null&&`abortEnd`in o){i+=e.slice(a,o.abortEnd),a=o.abortEnd;continue}if(o!==null){let{key:e,fallback:s}=o;if(Object.prototype.hasOwnProperty.call(n.values,e))k(e)&&(n.expandedBuiltinNames??=new Set).add(e),i+=String(n.values[e]);else if(s!==void 0)i+=s;else throw new t(`INVALID_ARGS`,`Unresolved variable \${${e}} at ${r.file}:${r.line}.`);a=o.end;continue}}i+=o,a+=1}return i}function In(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>Fn(e,t,n)),flags:Ln(e.flags,t,n)??{},runtime:Ln(e.runtime,t,n)}}function Ln(e,t,n){return e&&Rn(e,t,n)}function Rn(e,t,n){return typeof e==`string`?Fn(e,t,n):Array.isArray(e)?e.map(e=>Rn(e,t,n)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Rn(r,t,n)])):e}function zn(e){return Object.entries(e.values).filter(([t,n])=>n.length>0&&(!k(t)||e.expandedBuiltinNames?.has(t))).map(([e,t])=>({name:e,value:t})).sort((e,t)=>t.value.length-e.value.length)}function A(e){return e.width>0&&e.height>0}function Bn(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 Vn(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 Hn(e){return typeof e.parentIndex!=`number`}function j(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function Un(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function M(e){let t=pe(e);if(!t||t!==e.identifier?.trim()||!Wn(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 N(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function Wn(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Gn(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 Kn(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 P(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 qn=[`button`,`switch`,`checkbox`,`radio`],Jn=[`button`,`image`,`textview`,`view`];function Yn(e,t,n){for(let r of e){if(t.has(r.index)||!Qn(r))continue;let i=$n(Kn(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)P(e,n,t)}}}function Xn(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!sr(i))continue;let a=N(M(i));if(!a)continue;let o=r.get(a);if(o&&ir(o,i,t)){let s=ar(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Zn(e,t){for(let n of e){if(t.has(n.index)||!nr(n))continue;let r=N(M(n));if(!r)continue;let i=Kn(e,n.index).filter(e=>!t.has(e.index)&&rr(n,e,r));for(let n of i.filter(tr))P(e,n.index,t);let a=i.filter(e=>!tr(e)),o=new Set(a.map(e=>N(M(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)P(e,n.index,t)}}function Qn(e){return e.hittable===!0&&!j(e)&&!!(e.rect&&A(e.rect))&&M(e).trim().length===0}function $n(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!er(o,e)||!Bn(o.rect,t.rect))continue;let s=M(o).trim().replace(/\s+/g,` `),c=N(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function er(e,t){if(tr(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!j(e)&&n.includes(`view`)&&M(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function tr(e){if(e.hittable===!0||j(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function nr(e){return e.hittable===!0&&!j(e)&&!!(e.rect&&A(e.rect))&&!!N(M(e))}function rr(e,t,n){if(!sr(t)||!Bn(t.rect,e.rect))return!1;let r=N(M(t));return!!(r&&n!==r&&n.includes(r))}function ir(e,t,n){return!n.has(e.index)&&Vn(e.rect,t.rect)&&(fr(e,t)||dr(e,t))}function ar(e,t,n,r,i){let a=cr(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:or(c.presentationHints,l,s)}),P(e,o.index,r),i.get(a.index)??a}function or(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function sr(e){if(!e.rect||!A(e.rect)||Hn(e)||j(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||ur(t,Jn)}function cr(e,t){let n=lr(e);return lr(t)>n?t:e}function lr(e){let t=(e.type??``).toLowerCase(),n=0;return ur(t,qn)?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 ur(e,t){return t.some(t=>e.includes(t))}function dr(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:cr(n,r).index===n.index}function fr(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 pr(e,t,n){if(n.raw||!mr(e))return{nodes:t,filteredCount:0};let r=hr(t);return{nodes:r,filteredCount:t.length-r.length}}function mr(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function hr(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return gr(e,t),_r(e,r,t,n),Yn(e,t,n),Zn(e,t),Xn(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function gr(e,t){for(let n of e)!n.rect||A(n.rect)||Hn(n)||P(e,n.index,t)}function _r(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||Hn(i))continue;let a=Gn(i,t,Un);a&&yr(r,a,vr(i,e)),P(e,i.index,n)}}function vr(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&A(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 yr(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 br(e){return[...xr(e),...wr(e)]}function xr(e){let t=Tr(e?.candidates);if(t.length===0)return[];let n=typeof e?.matches==`number`?e.matches:t.length,r=typeof e?.refsGeneration==`number`?e.refsGeneration:void 0,i=n-t.length;return[`Candidates:`,...t.map(e=>` ${Cr(e,r)}`),...i>0?[` +${i} more`]:[]]}function Sr(e){return Tr(e?.candidates).flatMap(e=>{let t=/^@(e\d+)(?:~s\d+)?(?:\s|$)/.exec(e);return t?.[1]?[t[1]]:[]})}function Cr(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}function wr(e){let t=Er(e?.devices);return t.length===0?[]:[`Devices:`,...t.map(e=>` ${e.id} ${e.name}`)]}function Tr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Er(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.name==`string`):[]}function Dr(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Or(pe(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||!Ar(e)||(n+=e.length);return n>=8}function Or(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||kr(t)?null:t}function kr(e){return/\S+@\S+\.\S+/.test(e)}function Ar(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(jr(e[t]?.rect,e[n]?.rect))return!0;return!1}function jr(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 Mr={digest:8*1024,default:24*1024,full:64*1024};function Nr(e){return e===`digest`||e===`full`?e:`default`}function Pr(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 F(e,t=256){return Pr(o(e),t)}function Fr(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function Ir(e){return(t,n)=>F(Fr(t,e),n)}function Lr(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function Rr(e,t){let n=Nr(t),r=n===`digest`?8:20,i=Lr(e.screen,r),a=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:i,suggestions:a}}function zr(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function Br(e){let{divergence:t,level:n,writeOverflowArtifact:r}=e,i=Nr(n),a=Mr[i],o=Rr(t,n),s=zr(o);if(s<=a)return o;let c=s-a,l=r(Rr(t,`full`)),u=Vr(o);return`artifactPath`in l?{...u,overflow:{omittedBytes:c,artifactPath:l.artifactPath}}:{...u,artifactUnavailable:!0}}function Vr(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:F(e.step.source.path),line:e.step.source.line}},action:F(e.action),cause:{code:e.cause.code,message:F(e.cause.message),...e.cause.hint?{hint:F(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 Hr(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...ti(n.step),...Zr(n.kind,n.targetBinding),...Ur(n.repairHint,n.resume),...ni(n.screen),...oi(n.suggestions,n.suggestionCount),...ci(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
|
|
3
|
+
`):null}function Ur(e,t){if(typeof e!=`string`)return[];let n=qr(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function Wr(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 Gr(e,t){return`replay --from ${e} --plan-digest ${t}`}function Kr(e){return e?.repairSessionHeld===!0}function qr(e,t){let n=Jr(e,Wr(t));if(n!==void 0)return Kr(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 Jr(e,t){switch(e){case`record-and-heal`:return t?.allowed?`press the correct control via a blessed @ref from screen.refs (recorded), then ${Gr(t.from,t.planDigest)}.`:`press the correct control via a blessed @ref from screen.refs (recorded). ${Xr(t)}`;case`state-repair`:return t?.allowed?`fix app state with --no-record actions, then ${Gr(t.from,t.planDigest)} to re-run it.`:`fix app state with --no-record actions. ${Xr(t)}`;case`caution`:return Yr({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return Yr({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function Yr(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${Xr(n)}`;let r=`if you fixed app state with --no-record actions: ${Gr(n.from,n.planDigest)}`;return n.alternateFrom===void 0?`${t} ${r}.`:`${t} ${r}; ${`if you performed the step's intent as a recorded action: ${Gr(n.alternateFrom,n.planDigest)}`}.`}function Xr(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 Zr(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[Qr(e,n.matchCount),...$r(n.mismatches),...ei(n.candidates)]:[]}function Qr(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function $r(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function ei(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${ai(e)}`)]}function ti(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 ni(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?ri(t.refs,t.refsGeneration):t?.state===`unavailable`?[ii(t)]:[]}function ri(e,t){let n=e.slice(0,8).map(ai),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function ii(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function ai(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function oi(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(si)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function si(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function ci(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.`]:[]}function li(e){let t=I(e.label),n=I(e.value),r=I(e.identifier),i=hi(r)?r:``;return mi(e.type??``)?n||t||i:t||n||i}function ui(e,t){if(t===`text-view`||t===`text-field`||t===`search`)return!0;let n=m(e.type??``),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`textview`)||n.includes(`textarea`)||n.includes(`textfield`)||n.includes(`securetextfield`)||n.includes(`searchfield`)||n.includes(`edittext`)||r.includes(`text area`)||r.includes(`text field`)}function di(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=48?t:`${t.slice(0,45)}...`}function fi(e,t){let n=li(e),r=ui(e,t);return{text:n,isLargeSurface:r,shouldSummarize:r&&pi(n)}}function pi(e){return e?e.length>80||/[\r\n]/.test(e):!1}function I(e){return typeof e==`string`?e.trim():``}function mi(e){let t=m(e);return t.includes(`textfield`)||t.includes(`securetextfield`)||t.includes(`searchfield`)||t.includes(`edittext`)||t.includes(`textview`)||t.includes(`textarea`)}function hi(e){return e?!/^[\w.]+:id\/[\w.-]+$/i.test(e)&&!/^_?NS:\d+$/i.test(e):!1}const gi={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 _i(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=z(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:L(i,c,!1,o,t)})}return r}function L(e,t,n,r,i={}){let a=r??z(e.type??`Element`),o=fi(e,a),s=wi(e,a,i,o),c=` `.repeat(t),l=e.ref?`@${e.ref}`:``,u=Ti(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}"`:``,p=vi(e);return n?`${c}${l} [${a}]${d}${p}`.trimEnd():`${c}${l} [${a}]${f}${d}${p}`.trimEnd()}function vi(e){let t=e.actions?.filter(e=>e.trim().length>0);return!t||t.length===0?``:` actions: [${t.map(e=>`"${Oi(yi(e))}"`).join(`, `)}]`}function yi(e){return e.replace(/\s+/g,` `).replace(/[\u0000-\u001f\u007f-\u009f]/g,``).trim()}function R(e,t){let n=e.label?.trim();if(n&&Si(t,n))return``;let r=e.value?.trim();if(xi(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||Ci(i)&&(t===`group`||t===`image`||t===`list`||t===`collection`)?``:i}function z(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`:bi(n)||n||`element`}function bi(e){return Object.prototype.hasOwnProperty.call(gi,e)?gi[e]:void 0}function xi(e){return e===`text-field`||e===`text-view`||e===`search`}function Si(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:We(t)}function Ci(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function wi(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?R(e,t):Ei(e,t,r.text)||R(e,t)}function Ti(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`),xi(t)&&i.push(`editable`),Di(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?ki(i):(i.push(`preview:"${Oi(di(r.text))}"`),i.push(`truncated`),ki(i))}function Ei(e,t,n){let r=I(e.label);if(r&&r!==n)return r;let i=I(e.identifier);if(i&&!Ci(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 Di(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 Oi(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function ki(e){return[...new Set(e)]}function Ai(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function ji(n,r={}){let i=n instanceof t?e(n):n;process.stderr.write(`Error (${i.code}): ${i.message}\n`),i.hint&&process.stderr.write(`Hint: ${i.hint}\n`);let a=br(i.details);a.length>0&&process.stderr.write(`${a.join(`
|
|
4
|
+
`)}\n`),i.diagnosticId&&process.stderr.write(`Diagnostic ID: ${i.diagnosticId}\n`),i.logPath&&process.stderr.write(`Diagnostics Log: ${i.logPath}\n`),i.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${i.logPathUnavailable})\n`);let o=Hr(i.details);o&&process.stderr.write(`${o}\n`),r.showDetails&&i.details&&process.stderr.write(`${JSON.stringify(i.details,null,2)}\n`)}function Mi(e,t={}){let n=e.nodes,a=Array.isArray(n)?n:[],o=i(r(e.backend)?e.backend:void 0),s=pr(e,a,t),c=Ii(e),l=na(e,a,t,s),u=l.length>0?`${l.join(`
|
|
5
|
+
`)}\n`:``,d=t.raw?null:Ni(e);if(d)return`${c}${u}${Pi(d)}\n`;let f=t.raw||!o?null:Ke(s.nodes),p=!!e.truncated,m=f?.nodes??a,h=t.raw||!o?null:Hi(e,f,m.length,a.length,s.filteredCount),g=Li(a.length,h,p);return a.length===0?`${c}${g}\n${u}`:t.raw?`${c}${g}\n${u}${Ri(a)}\n`:t.flatten?`${c}${g}\n${u}${zi(m)}${Vi(f)}\n`:`${c}${g}\n${u}${Bi(m)}${Vi(f)}\n`}function Ni(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 Pi(e){let t=Fi(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(`
|
|
6
|
+
`):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(`
|
|
7
|
+
`):[`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(`
|
|
8
|
+
`)}function Fi(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 Ii(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(`
|
|
9
|
+
`)}\n`:``}function Li(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 Ri(e){return e.map(e=>JSON.stringify(e)).join(`
|
|
10
|
+
`)}function zi(e){return da(e).join(`
|
|
11
|
+
`)}function Bi(e){return ca(_i(e,{summarizeTextSurfaces:!0})).join(`
|
|
12
|
+
`)}function Vi(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
|
|
13
|
+
`)}`:``}function Hi(e,t,n,r,i=0){let a=Ui(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:Wi([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function Ui(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 Wi(e){return[...new Set(e)]}function Gi(e){let t=e.baselineInitialized===!0,n=e.summary??{},r=B(n.additions),i=B(n.removals),a=B(n.unchanged),o=ea(),s=sa(e),c=s.length>0?`${s.join(`
|
|
14
|
+
`)}\n`:``;if(t)return`${c}Baseline initialized (${a} lines).\n`;let l=$i(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?V(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return o?V(e,`red`):e}return o?V(t,`dim`):t}),u=l.length>0?`${l.join(`
|
|
15
|
+
`)}\n`:``;return o?`${c}${u}${[`${V(String(r),`green`)} additions`,`${V(String(i),`red`)} removals`,`${V(String(a),`dim`)} unchanged`].join(`, `)}\n`:`${c}${u}${r} additions, ${i} removals, ${a} unchanged\n`}function Ki(e){let t=ea(),n=e.match===!0,r=e.dimensionMismatch,i=[];return i.push(...qi(e,t)),i.push(...Ji(e,n,t)),!n&&!r&&(i.push(...Yi(e,t)),i.push(...Xi(e,t))),`${i.join(`
|
|
16
|
+
`)}\n`}function qi(e,t){if(e.match===!0)return[`${t?V(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?V(`✗`,`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=B(e.differentPixels),a=B(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?V(o,`red`):o}`]}function Ji(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=Qi(e.diffPath),i=n?V(`Diff image:`,`dim`):`Diff image:`,a=n?V(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=Qi(e.currentOverlayPath),i=n?V(`Current overlay:`,`dim`):`Current overlay:`,a=n?V(t,`green`):t,o=B(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function Yi(e,t){let n=B(e.differentPixels),r=B(e.totalPixels);return[` ${t?V(String(n),`red`):String(n)} different / ${r} total pixels`]}function Xi(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${ta(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...Zi(e));return r}function Zi(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff`],i=e.currentOverlayMatches?.[0];if(i){let e=i.label?` "${i.label}"`:``;r.push(` overlaps @${i.ref}${e}, ${i.regionCoveragePercentage}% of region`)}return r}function Qi(e){let t=process.cwd(),n=Xe.relative(t,e);return n===``||!n.startsWith(`..`)&&!Xe.isAbsolute(n)?n===``?`.`:`.${Xe.sep}${n}`:e}function B(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function $i(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 ea(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 V(e,t,n){return Ze(t,e,n)}function ta(e,t){return t?V(e,`dim`):e}function na(e,t,n,r={nodes:t,filteredCount:0}){let i=[...sa(e),...ra(e)];if(ia(e)){let e=oa(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&&Dr(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function ra(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function ia(e){return!e.snapshotQuality&&!aa(e)}function aa(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 oa(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 sa(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0):[]}function ca(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||la(e,n[n.length-1],r));)t.push(...fa(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...fa(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function la(e,t,n){return ua(e.node,t.node,n)?!1:e.depth<=t.depth}function ua(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 da(e){return _i(e,{summarizeTextSurfaces:!0}).flatMap(e=>[L(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...fa({...e,depth:0})])}function fa(e,t){let n=pa(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 pa(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}const ma={defaultTimeoutMs:1e4,intervalMs:300},H={promotedTarget:{resolution:S.act,occlusion:`exclude-and-refuse`,offscreen:`refuse`,promotion:`hittable-ancestor`,poll:`none`},resolvedTarget:{resolution:S.act,occlusion:`exclude-and-refuse`,offscreen:`refuse`,promotion:`none`,poll:`none`},coveredDiagnosis:{resolution:S.actCoveredDiagnosis,occlusion:`refuse`,offscreen:`ignore`,promotion:`none`,poll:`none`},readText:{resolution:S.readText,occlusion:`ignore`,offscreen:`ignore`,promotion:`none`,poll:`none`},readUnique:{resolution:S.readUnique,occlusion:`ignore`,offscreen:`ignore`,promotion:`none`,poll:`none`},readAny:{resolution:S.readAny,occlusion:`ignore`,offscreen:`ignore`,promotion:`none`,poll:`none`},findWait:{resolution:S.readAny,occlusion:`ignore`,offscreen:`ignore`,promotion:`none`,poll:ma},wait:{resolution:S.wait,occlusion:`ignore`,offscreen:`ignore`,promotion:`none`,poll:ma},readList:{resolution:S.readList,occlusion:`ignore`},findAct:{resolution:S.findAct,occlusion:`refuse`,offscreen:`ignore`,promotion:`hittable-ancestor-below-root`,poll:`none`}};function ha(e,t,n={}){let r=ba(e);if(r.length===0)return{canScroll:!1,emptySnapshot:!0};let i=Ge(r),a=xa(r,i,t,n);return a?{canScroll:Ca(a,i.get(a.index),t),emptySnapshot:!1,scope:wa(a,r)}:{canScroll:!1,emptySnapshot:!1}}async function ga(e){let{edge:t,target:n={},scope:r,captureNodes:i}=e;try{let e=ha(await i(r),t,n);return r&&e.emptySnapshot?await ga({edge:t,target:n,captureNodes:i}):e}catch(e){throw ya(t,r,e)}}async function _a(e){let{edge:n,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 t(`COMMAND_FAILED`,`scroll ${n} 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 va(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 ya(e,n,r){return n?new t(`COMMAND_FAILED`,`Failed to verify scroll ${e} state for scoped container`,{scope:n,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 t(`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 ba(e){return e.map((e,t)=>({...e,ref:`ref`in e&&e.ref?e.ref:`e${t+1}`}))}function xa(e,t,n,r){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>g(e)&&ja(e.rect));if(a.length===0)return null;let o=Sa(r.nodeIndex,i);if(o)return o;let s=r.point;if(s){let e=a.filter(e=>e.rect&&Aa(e.rect,s)).sort(Da);if(e.length>0)return e.find(e=>Ca(e,t.get(e.index),n))??e[0]??null}let c=a.filter(e=>Ca(e,t.get(e.index),n)).sort(Oa);return c.length>0?c[0]??null:a.filter(t=>Te(t,e)).sort(Oa)[0]??a.sort(Oa)[0]??null}function Sa(e,t){if(e===void 0)return null;let n=t.get(e);for(;n;){if(g(n)&&ja(n.rect))return n;n=n.parentIndex===void 0?void 0:t.get(n.parentIndex)}return null}function Ca(e,t,n){return n===`bottom`?e.hiddenContentBelow===!0||t?.hiddenContentBelow===!0:e.hiddenContentAbove===!0||t?.hiddenContentAbove===!0}function wa(e,t){return[e.identifier,e.label].filter(e=>typeof e==`string`).map(e=>e.trim()).find(n=>Ea(n)&&Ta(n,e,t))}function Ta(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 Ea(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function Da(e,t){return ka(e.rect)-ka(t.rect)}function Oa(e,t){return ka(t.rect)-ka(e.rect)}function ka(e){return e?e.width*e.height:0}function Aa(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function ja(e){return!!(e&&e.width>0&&e.height>0)}function Ma(e,n,r,i){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>i)throw new t(`INVALID_ARGS`,`${n} must be an integer between ${r} and ${i}`);return e}function U(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function W(e){return e.clock?.now()??Date.now()}async function Na(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}function Pa(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e=>n(t,e)]))}function G(e){return e&&typeof e==`object`?e:void 0}function Fa(e){let t=Buffer.alloc(16);for(let n of e)La(t,Ia(n));return{digest:`ax1:${Qe(`sha256`).update(t).update(`\0`).update(String(e.length)).digest(`hex`).slice(0,16)}`,nodeCount:e.length}}function Ia(e){return Qe(`sha256`).update(e.type??``).update(`\0`).update(e.label??``).update(`\0`).update(e.identifier??``).digest().subarray(0,16)}function La(e,t){for(let n=0;n<e.length;n+=1)e[n]=(e[n]??0)^(t[n]??0)}function K(e){let{digest:t,nodeCount:n}=Fa(e),r=e.reduce((e,t)=>t.hittable===!1?e:e+1,0),i=Ra(e);return{digest:t,nodeCount:n,interactiveNodeCount:r,...i?{foregroundApp:i}:{}}}function Ra(e){for(let t of e)if(t.bundleId)return t.bundleId;for(let t of e)if(t.appName)return t.appName}const za=[`x`,`y`,`width`,`height`];function q(e){let t=J(e);if(!t)return null;let n=c(t);return!Number.isFinite(n.x)||!Number.isFinite(n.y)?null:n}function J(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 Y(e,t){return!e||!t?!1:za.every(n=>Math.abs(e[n]-t[n])<=.5)}function Ba(e){return{x:Va(e.x,e.width),y:Va(e.y,e.height)}}function Va(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 Ha(e,t,n,r){let i=n.ambiguity,a=xe(e,t,{...r,requireRect:n.requireRect});if(!a||a.matchedNodes.length===0)return{kind:`none`};if(i===`first-match`)return Wa(a);if(i===`reject-candidates`)return a.matchedNodes.length>1?Ua(a):Wa(a);let o=_e(e,t,{...r,...Oe({ambiguity:i,requireRect:n.requireRect})});return o?{kind:`resolved`,resolution:o,matchedNodes:a.matchedNodes}:Ua(a)}function Ua(e){return{kind:`ambiguous`,selector:e.selector.raw,selectorIndex:e.selectorIndex,matchedNodes:e.matchedNodes}}function Wa(e){let t=e.matchedNodes[0];return t?{kind:`resolved`,matchedNodes:e.matchedNodes,resolution:{node:t,selector:e.selector,selectorIndex:e.selectorIndex,matches:e.matchedNodes.length,diagnostics:[{selector:e.selector.raw,matches:e.matchedNodes.length}]}}:{kind:`none`}}function Ga(e,t,n){let r=xe(e,De(t),n);return r?{...r,selector:r.selector.raw}:null}function Ka(e,t,n,r){let i=Ha(e,De(t),n,r);return i.kind===`resolved`?{...i,resolution:{...i.resolution,selector:i.resolution.selector.raw}}:i}const qa=[`tabbar`,`toolbar`,`navigationbar`,`bottomnavigation`,`bottomnavigationview`,`sheet`,`dialog`,`alert`,`popover`,`menu`],Ja=[`tabbar`,`toolbar`,`navigationbar`],Ya=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`edittext`,`checkbox`,`radio`,`switch`,`cell`];function Xa(e,t={}){if(e.length<2)return e;let n=new Map(e.map(e=>[e.index,e])),r={nodes:e,byIndex:n,overlayPositions:e.flatMap((e,r)=>ro(e,n,t)?[r]:[]),coverCache:new Map},i=[];for(let[n,a]of e.entries())no(a)&&Za(r,n,a,t)&&i.push(n);if(i.length===0)return e;let a=[...e];for(let t of i){let n=e[t];a[t]={...n,hittable:!1,interactionBlocked:`covered`,presentationHints:mo(n.presentationHints)}}return a}function X(e){return e.interactionBlocked!==void 0}function Za(e,t,n,r){let i=e.coverCache.get(t);if(i!==void 0)return i;e.coverCache.set(t,null);let a=Z(n.rect);if(!a)return $a(e,t,null);let o=c(a),s=r.isAdditionalOverlayNode?.(n)===!0;for(let i of e.overlayPositions){if(!Qa(e,i,t,s,r))continue;let c=e.nodes[i];if(eo(e,i,n,a,o,r))return $a(e,t,c)}return $a(e,t,null)}function Qa(e,t,n,r,i){let a=e.nodes[t];return a?t>n?!0:t===n||r?!1:i.isAdditionalOverlayNode?.(a)===!0:!1}function $a(e,t,n){return e.coverCache.set(t,n),n}function eo(e,t,n,r,i,a){if(!e.nodes[t])return!1;let o=to(e,t,n,r,a);return!!(o&&be(o,i.x,i.y))}function to(e,t,n,r,i){let a=e.nodes[t];if(!a||!ro(a,e.byIndex,i)||fo(n,a,e.byIndex))return null;let o=Z(a.rect);return!o||Y(r,o)||Za(e,t,a,i)?null:o}function no(e){return Z(e.rect)?e.hittable===!0||co(e)?!0:!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()):!1}function ro(e,t,n){return!Z(e.rect)||x(e)||io(e,t)?!1:lo(e,qa)||ao(e,t,n)}function io(e,t){if(!lo(e,Ja))return!1;let n=Z(e.rect);if(!n)return!1;let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(x(r)){let e=Z(r.rect);return!!(e&&Y(n,e))}i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function ao(e,t,n){return n.isAdditionalOverlayNode?.(e)===!0?!oo(e,t,n):!1}function oo(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(so(r,n))return!0;i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function so(e,t){return t.isAdditionalOverlayNode?.(e)===!0&&Z(e.rect)!==null&&!x(e)}function co(e){return lo(e,Ya)}function lo(e,t){let n=uo(e);return t.some(e=>n.includes(e))}function uo(e){return[e.type,e.role,e.subrole].map(e=>m(e??``)).join(` `)}function fo(e,t,n){return po(e,t,n)||po(t,e,n)}function po(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 Z(e){let t=J(e);return t&&t.width>0&&t.height>0?t:null}function mo(e){return Array.from(new Set([...e??[],`covered`]))}function ho(e){return e}function go(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)}const _o=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];function vo(e,t){let n=t[0];if(!n||!yo(t,new Map(e.map(e=>[e.index,e]))))return{kind:`ambiguous`,candidates:t};let r=So(e,n).node;for(let n of t.slice(1))if(So(e,n).node.index!==r.index)return{kind:`ambiguous`,candidates:t};return{kind:`equivalent`,node:r}}function yo(e,t){for(let n=0;n<e.length;n+=1)for(let r=n+1;r<e.length;r+=1){let i=e[n],a=e[r];if(!bo(i,a,t)&&!bo(a,i,t))return!1}return!0}function bo(e,t,n){let r=t,i=new Set;for(;r.parentIndex!==void 0&&!i.has(r.index);){if(i.add(r.index),r.parentIndex===e.index)return!0;let t=n.get(r.parentIndex);if(!t)return!1;r=t}return!1}function xo(e,t){if(!t?.rect||!e.rect||!x(e))return!1;let n=e.rect,r=t.rect;return n.x===r.x&&n.y===r.y&&n.width===r.width&&n.height===r.height}function So(e,t){if(X(t))return{node:t,reason:`covered`};let n=wo(e,t);if(n?.rect&&q(n.rect))return{node:n,reason:`same-rect-descendant`};if(To(t)&&t.rect&&q(t.rect))return{node:t,reason:`semantic-target`};let r=Co(e,t);return r?.rect&&!X(r)&&q(r.rect)?Do(t,r,e)?{node:t,reason:`overly-broad-ancestor`}:{node:r,reason:`hittable-ancestor`}:{node:t,reason:`original`}}function Co(e,t){return t.hittable?t:le(e,t,e=>e.hittable===!0)}function wo(e,t){let n=J(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=J(e.rect);return t?Y(t,n):!1});if(t.length!==1)break;r=t[0]}return r===t?null:r}function To(e){return[e.type,e.role,e.subrole].map(e=>m(e??``)).some(Eo)}function Eo(e){return e===`tab`||_o.some(t=>e.includes(t))}function Do(e,t,n){let r=J(e.rect),i=J(t.rect);if(!r||!i)return!1;if(Oo(t)&&!Y(r,i))return!0;let a=ko(n,r);return!a||!Ao(i,a)?!1:!Y(r,i)}function Oo(e){let t=m(e.type??``);return t.includes(`scrollview`)||t.includes(`scrollarea`)||t.includes(`listview`)||t.includes(`recyclerview`)||t.includes(`collectionview`)||t===`list`||t===`table`||t===`collection`}function ko(e,t){let n=c(t),r=e.filter(x).map(e=>J(e.rect)).filter(e=>e!==null);if(r.length===0)return null;let i=r.filter(e=>be(e,n.x,n.y));return re(i.length>0?i:r)}function Ao(e,t){let n=go(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}async function jo(e,t,n,r,i={}){let a=Ka(Po(e,t),n,e.resolution,r);if(a.kind===`none`)return{kind:`none`};if(a.kind===`ambiguous`)return{kind:`ambiguous`,selector:a.selector,selectorIndex:a.selectorIndex,matchedNodes:a.matchedNodes};let o=a.resolution,s=await No(e,t,o.node,i);return s.kind===`occluded`?{kind:`occluded`,node:s.node,selector:o.selector}:{kind:`target`,node:s.node,selector:o.selector,selectorIndex:o.selectorIndex,matches:o.matches,matchedNodes:a.matchedNodes}}function Mo(e,t,n,r){let i=Po(e,t);return{candidates:i,list:Ga(i,n,{...r,requireRect:e.resolution.requireRect})}}async function No(e,t,n,r={}){r.onResolved?.(n,t);let i=Fo(e.promotion,t,n);return e.occlusion!==`ignore`&&(i.covered||X(i.node))?{kind:`occluded`,node:i.node}:{kind:`target`,node:await Io(e,t,i.node,r)}}function Po(e,t){return e.occlusion===`exclude-and-refuse`?t.filter(e=>!X(e)):t}function Fo(e,t,n){if(e===`none`)return{node:n,covered:!1};let r=So(t,n);return r.reason===`covered`?{node:r.node,covered:!0}:e===`hittable-ancestor-below-root`&&xo(r.node,t[0])&&n.rect?{node:n,covered:!1}:{node:r.node,covered:!1}}async function Io(e,t,n,r){if(e.offscreen!==`refuse`)return n;if(!r.offscreen)throw Error(`selector pipeline row declares an off-screen refusal but this route supplies no refusal shape`);return await r.offscreen(n,t)}function Lo(e){if(e.poll===`none`)throw Error(`selector pipeline row resolves against one capture and declares no poll budget`);return e.poll}function Ro(e){let t=new Map;for(let n of e)t.set(n.index,n);return t}function zo(e,t,n){let r=[],i=new Set([e.index]),a=e;for(;r.length<n;){if(typeof a.parentIndex!=`number`)return{chain:r,broken:!1};let e=t.get(a.parentIndex);if(!e||i.has(e.index))return{chain:r,broken:!0};i.add(e.index);let n=v(e);r.push({role:n.role,...n.label===void 0?{}:{label:n.label}}),a=e}return{chain:r,broken:!1}}function Bo(e,t,n,r){return e.filter(e=>{if(!ae(v(e),n))return!1;let i=zo(e,t,Math.max(r.length,1));return!i.broken&&ie(i.chain,r)})}function Vo(e){return e.hittable===!0||To(e)}function Ho(e,t){let n=ye(v(e),t);return n.id!==void 0||n.label!==void 0?!1:h(e.value)===null}function Uo(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 Wo(e,t){let n=Ro(t);return t.filter(t=>t.index!==e.index&&Uo(t,e,n)).sort((e,t)=>e.index-t.index)}function Go(e,t){let n=q(e.rect);return!n||!t.rect?!1:be(t.rect,n.x,n.y)}function Ko(e,t){if(!Ho(e,t))return e;let n=Wo(e,t);if(n.some(Vo))return e;let r=n.find(e=>v(e).label!==void 0);return!r||!Go(r,e)?e:r}function qo(e,t){return e.find(e=>Pe(e,t))??null}function Jo(e,t){let n=pe(e);return n&&ce(n)?n:Yo(e,t)}function Yo(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=pe(e);if(!t||!ce(t))continue;let i=e.rect.y+e.rect.height/2,a=Math.abs(i-n);(!r||a<r.distance)&&(r={label:t,distance:a})}return r?.label}function Xo(e){return e===`text`||e===`label`||e===`any`}function Zo(e,t,n,r){if(!(r||e===`web`))return Xo(t)?n:void 0}function Qo(e){return new t(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}async function $o(e,n){let r=n??`default`,i=await e.sessions.get(r);if(!i)throw new t(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let a=i.refFrameSnapshot??i.snapshot;if(!a)throw new t(`INVALID_ARGS`,`No snapshot in session. Run snapshot first.`);return{sessionName:r,session:i,snapshot:a}}async function es(e,n,r={updateSession:!0}){let i=e.backend.captureSnapshot;if(!i)throw new t(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let a=n.session??`default`,o=await e.sessions.get(a),s=await i(U(e,n),{interactiveOnly:r.interactiveOnly??!1,depth:n.depth,scope:r.scope??n.scope,raw:n.raw,includeRects:r.includeRects,...r.preferredBackend?{preferredBackend:r.preferredBackend}:{},...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:W(e)};return(n.signal??e.signal)?.throwIfAborted(),r.updateSession&&o&&!Je(c.snapshotQuality)&&await e.sessions.set({...o,snapshot:c}),{sessionName:a,session:o,snapshot:c}}async function ts(e,t,n){if(e.backend.readText){let r=await e.backend.readText(U(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return li(n)}function ns(e,r,i){let a=s(r);if(!a)throw new t(`INVALID_ARGS`,i.invalidRefMessage);let o=n(e,a)??(i.fallbackLabel.length>0?qo(e,i.fallbackLabel):null);if(!o)throw new t(`COMMAND_FAILED`,i.notFoundMessage);return{ref:a,node:o}}function rs(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 is(e,t,n={}){let r=J(t.rect),i=q(r??void 0);if(!r||!i)return{kind:`invalid`};let a=as(e,t,r);if(a.length===0)return{kind:`resolved`,point:i,strategy:`center`};let o=(n.bounds??[]).reduce((e,t)=>e?ss(e,t):null,r),s=o?cs(r,o,i,a):null;return s?{kind:`resolved`,point:s,strategy:`parent-owned`}:{kind:`blocked`,competitorRefs:a.map(e=>e.ref)}}function as(e,t,n){let r=new Map(e.map(e=>[e.index,e]));return e.filter(e=>e.index!==t.index).filter(e=>os(e,t,r)).filter(To).flatMap(e=>{let t=J(e.rect);if(!t||Y(t,n))return[];let r=ss(t,n);return r&&r.width>0&&r.height>0?[{ref:e.ref,index:e.index,rect:r}]:[]}).sort((e,t)=>e.index-t.index)}function os(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`&&!r.has(i.index);){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 ss(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?null:{x:n,y:r,width:i-n,height:a-r}}function cs(e,t,n,r){let i=ms(e),a=fs(t.x,t.width,n.x,r.flatMap(({rect:e})=>[e.x,e.x+e.width]),i),o=fs(t.y,t.height,n.y,r.flatMap(({rect:e})=>[e.y,e.y+e.height]),i);return a.flatMap(a=>o.flatMap(o=>{let s={x:Math.round(a),y:Math.round(o)};if(!ls(t,s))return[];let c=us(s,e,n,r,i);return c?[c]:[]})).sort(ds)[0]?.point??null}function ls(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function us(e,t,n,r,i){let a=ps(e,t,r);return a.parentEdge<i||a.competitor<12?null:{point:e,distanceSquared:(e.x-n.x)**2+(e.y-n.y)**2,clearance:Math.min(a.parentEdge,a.competitor)}}function ds(e,t){return e.distanceSquared-t.distanceSquared||t.clearance-e.clearance||e.point.y-t.point.y||e.point.x-t.point.x}function fs(e,t,n,r,i){let a=e+i,o=e+t-i;if(a>o)return[];let s=[...new Set([e,e+t,...r])].sort((e,t)=>e-t),c=new Set([n,a,o]);for(let e of r)c.add(e-12),c.add(e+12);for(let e=1;e<s.length;e+=1)c.add((s[e-1]+s[e])/2);return[...c].filter(e=>e>=a&&e<=o).sort((e,t)=>e-t)}function ps(e,t,n){let r=Math.min(e.x-t.x,t.x+t.width-e.x,e.y-t.y,t.y+t.height-e.y),i=1/0;for(let{rect:t}of n){let n=e.x<t.x?t.x-e.x:Math.max(0,e.x-(t.x+t.width)),r=e.y<t.y?t.y-e.y:Math.max(0,e.y-(t.y+t.height));i=Math.min(i,Math.max(n,r))}return{parentEdge:r,competitor:i}}function ms(e){let t=Math.min(e.width,e.height);return Math.max(0,Math.min(12,Math.floor(t/2)-1))}const hs=`replay_target_guard_mismatch`,gs=Ve.landmarkIdentityMismatch;function _s(e,n,r,i){let{candidates:a,list:o}=Mo(i,e,n,{platform:r}),s=o?.matchedNodes??[];if(!o||s.length===0)return null;let c=[{selector:o.selector,matches:s.length}];if(s.length===1)return{node:s[0],selector:o.selector,selectorIndex:o.selectorIndex,matches:1,diagnostics:c};let l=vo(a,s);if(l.kind===`ambiguous`)throw new t(`AMBIGUOUS_MATCH`,`Selector matched ${l.candidates.length} distinct actionable elements: ${o.selector}`,{selector:o.selector,matches:l.candidates.length,candidates:l.candidates.slice(0,5).map(e=>L(e,0,!1))});return{node:l.node,selector:o.selector,selectorIndex:o.selectorIndex,matches:s.length,diagnostics:c,disambiguation:{matchCount:s.length,tiebreak:`structural-equivalence`,alternatives:s.filter(e=>e.index!==l.node.index)}}}function vs(e,n,r,i,a){if(!r)return;let o=v(e),s=ee(e,n);if(!(ne(o,r.identity)&&oe(s,r.structural)))throw new t(`COMMAND_FAILED`,`${i} resolved to a different element than replay verification isolated; the action was not sent`,{reason:hs,observed:o,observedStructural:s,expected:r.identity,expectedStructural:r.structural,...a?{targetRole:a}:{}})}async function Q(e,t,n){return await Vs(e,t,n.action),t.target.kind===`point`?await bs(e,t,t.target,n):t.target.kind===`ref`?await ws(e,t,t.target,n):await Ts(e,t,t.target,n)}async function ys(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=je(i.snapshot.nodes,a);if(!o)return;let s={x:n.x,y:n.y};if(!be(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 bs(e,t,n,r){let i=await ys(e,t,n);if(!r.captureEvidenceBaseline)return{kind:`point`,point:{x:n.x,y:n.y},...i?{warning:i}:{}};let a=await xs(e,t);return{kind:`point`,point:{x:n.x,y:n.y},...a?{preActionNodes:a}:{},...i?{warning:i}:{}}}async function xs(e,t){try{return(await Bs(e,t,!0)).snapshot.nodes}catch{return}}function Ss(e,n){let r=s(e.ref);if(!r)throw new t(`INVALID_ARGS`,`Invalid ref: ${e.ref}`);let i=s(n.ref),a=n.node.ref?s(n.node.ref):null;if(i!==r||a!==r||!n.nodes.includes(n.node))throw new t(`COMMAND_FAILED`,`Internal find target provenance does not match the interaction ref`);return{nodes:n.nodes,resolved:As(r,n.node,`exact`)}}async function Cs(e,t,n){let r=await Us(e,t,n);return{nodes:r.snapshot.nodes,resolved:r.resolved}}async function ws(e,t,n,r){let{nodes:i,resolved:a}=r.preresolvedTarget?Ss(n,r.preresolvedTarget):await Cs(e,t,n),o=await Ls({policy:r.pipeline,nodes:i,node:a.node,action:r.action,label:`Ref ${n.ref}`,hooks:{onResolved:(e,t)=>Ds(e,t,r),offscreen:async(i,a)=>await Ys(e,t,i,a,n.ref,r)}});return{kind:`ref`,point:Ks(o,i,{invalidMessage:`Ref ${n.ref} not found or has invalid bounds`,blockedTargetLabel:`Ref ${n.ref}`,blockedTargetDetails:{ref:`@${s(n.ref)??o.ref}`}}),target:{kind:`ref`,ref:`@${a.ref}`},...Ps(e,o,i,r.action,a.resolution)}}async function Ts(e,t,n,r){let i=n.selector,a=await Bs(e,t,r.requireInteractive),o=_s(a.snapshot.nodes,i,e.backend.platform,r.pipeline);if((!o||!o.node.rect)&&r.requireInteractive&&(a=await Bs(e,t,!1),o=_s(a.snapshot.nodes,i,e.backend.platform,r.pipeline)),!o||!o.node.rect)throw await Es({runtime:e,nodes:a.snapshot.nodes,selectorExpression:i,action:r.action,resolved:o});let s=o,c=await Ls({policy:r.pipeline,nodes:a.snapshot.nodes,node:s.node,action:r.action,label:`Selector ${s.selector}`,hooks:{onResolved:(e,t)=>Ds(e,t,r),offscreen:async(n,i)=>await Js(e,t,n,i,s.selector,r)}});return{kind:`selector`,point:Ks(c,a.snapshot.nodes,{invalidMessage:`Selector ${o.selector} resolved to invalid bounds`,blockedTargetLabel:`Selector ${i}`,blockedTargetDetails:{selector:i}}),target:{kind:`selector`,selector:o.selector},...Ps(e,c,a.snapshot.nodes,r.action,Ms(o,a.snapshot.nodes))}}async function Es(e){let{runtime:n,nodes:r,selectorExpression:i,action:a,resolved:o}=e,s=await jo(H.coveredDiagnosis,r,i,{platform:n.backend.platform});if(s.kind===`occluded`)return Rs({label:`Selector ${s.selector}`,node:s.node,action:a,selector:s.selector});let c=o?.diagnostics??[];return new t(`COMMAND_FAILED`,we(i,c,{unique:!0}),{hint:ge(c)})}function Ds(e,t,n){vs(e,t,n.expectedResolvedTarget,n.action,n.replayTargetRole)}const Os={source:`ref`,phase:`pre-action`,kind:`exact`},ks={source:`ref`,phase:`pre-action`,kind:`label-fallback`};function As(e,t,n){return{ref:e,node:t,resolution:n===`exact`?Os:ks}}const js={source:`runtime`,phase:`pre-action`,kind:`unique`};function Ms(e,t){return e.disambiguation?{source:`runtime`,phase:`pre-action`,kind:`disambiguated`,matchCount:e.disambiguation.matchCount,winnerDiagnostic:Ns(e.node,t),tiebreak:e.disambiguation.tiebreak,alternatives:e.disambiguation.alternatives.slice(0,5).map(e=>Ns(e,t))}:js}function Ns(e,t){let n=m(e.type??``),r=Jo(e,t);return{diagnosticRef:`diag-${e.ref}`,...n?{role:rs(n,256)}:{},...r===void 0?{}:{label:rs(r,256)}}}function Ps(e,t,n,r,i){return{node:t,selectorChain:_(t,e.backend.platform,{action:r===`fill`?`fill`:`click`,nodes:n}),refLabel:Jo(t,n),...Is(t,r),preActionNodes:n,resolution:i,...Fs(e,t,n,r)}}function Fs(e,t,n,r){if(r!==`click`&&r!==`press`)return{};let i=Ko(t,n);return i===t?{}:{recordingTarget:{node:i,selectorChain:_(i,e.backend.platform,{action:`click`,nodes:n}),refLabel:Jo(i,n)}}}function Is(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.`}:{}}async function Ls(e){let t=await No(e.policy,e.nodes,e.node,e.hooks);if(t.kind===`occluded`)throw Rs({label:e.label,node:t.node,action:e.action});return t.node}function Rs(e){return new t(`COMMAND_FAILED`,`${e.label} is covered by another visible element and cannot ${zs(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 zs(e){switch(e){case`fill`:return`be filled`;case`focus`:return`be focused`;case`longPress`:return`be long-pressed`;case`hover`:return`be hovered`;default:return`be tapped`}}async function Bs(e,n,r){if(!e.backend.captureSnapshot)throw new t(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let i=n.session??`default`,a=await e.sessions.get(i);if(!a)throw new t(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let o=await e.backend.captureSnapshot(U(e,n),{interactiveOnly:r,includeRects:!0}),s=o.snapshot??{nodes:o.nodes??[],truncated:o.truncated,backend:o.backend,createdAt:W(e)};return await e.sessions.set({...a,snapshot:s}),{snapshot:s}}async function Vs(e,n,r){if(e.backend.platform!==`macos`)return;let i=await Hs(e,n);if(!(i!==`desktop`&&i!==`menubar`)&&!(i===`menubar`&&(r===`click`||r===`press`)))throw new t(`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 Hs(e,t){return(await e.sessions.get(t.session??`default`))?.metadata?.surface}async function Us(e,n,r){let{session:i,snapshot:a}=await $o(e,n.session),o=r.fallbackLabel??``,s=Gs(a.nodes,r.ref,{fallbackLabel:o});if(!s)throw new t(`COMMAND_FAILED`,`Ref ${r.ref} not found or has no bounds`,{hint:he});return Ws({session:i,frameTree:a,target:r,fallbackLabel:o,authorized:s})}function Ws(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=Gs(o.nodes,r.ref,{fallbackLabel:i});return s&&ne(v(a.node),v(s.node))?{snapshot:o,resolved:s}:{snapshot:n,resolved:a}}function Gs(e,r,i){let a=s(r);if(!a)throw new t(`INVALID_ARGS`,`Invalid ref: ${r}`);let o=n(e,a);if(qs(o))return As(a,o,`exact`);let c=i.fallbackLabel.length>0?qo(e,i.fallbackLabel):null;return qs(c)?As(a,c,`label-fallback`):null}function Ks(e,n,r){let i=is(n,e,{bounds:[ke(e,n),e.rect?je(n,e.rect):null].filter(e=>e!==null)});if(i.kind===`resolved`)return i.point;throw i.kind===`invalid`?new t(`COMMAND_FAILED`,r.invalidMessage):new t(`COMMAND_FAILED`,`${r.blockedTargetLabel} has no parent-owned touch point outside its interactive descendants`,{reason:`covered_by_interactive_descendants`,...r.blockedTargetDetails,competitorRefs:i.competitorRefs.slice(0,5).map(e=>`@${e}`),competitorCount:i.competitorRefs.length,hint:`Tap the specific interactive child you intend, or use a more specific selector. Every safely tappable region of the parent belongs to one of its child controls.`})}function qs(e){return e?q(e.rect)!==null:!1}async function Js(e,t,n,r,i,{action:a}){return await $s(e,t,n,r,{message:`Selector ${i} resolved to an off-screen element and is not safe to ${a}`,details:{reason:`offscreen_selector`,selector:i},hint:e=>`${Xs(e)} in small steps, retrying ${a} 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.`})}async function Ys(e,t,n,r,i,{action:a}){return await $s(e,t,n,r,{message:`Ref ${i} is off-screen and not safe to ${a}`,details:{reason:`offscreen_ref`,ref:s(i)},hint:e=>`${Xs(e)} in small steps (a single large scroll can overshoot; a short bounded gesture pan lands it more reliably), then retry ${a} 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 Xs(e){return e?`Scroll ${e} toward it`:`Scroll toward it`}async function Zs(e,t,n,r){let i=(await e.sessions.get(t.session??`default`))?.snapshot?.nodes;if(!i||s(n.ref)===null)return{};let a=Gs(i,n.ref,{fallbackLabel:n.fallbackLabel??``});if(!a)return{};let o=H.resolvedTarget,c=await Ls({policy:o,nodes:i,node:a.node,action:r,label:`Ref ${n.ref}`,hooks:{offscreen:async(i,a)=>await Ys(e,t,i,a,n.ref,{action:r,pipeline:o})}});return{...Is(c,r),node:c,preActionNodes:i}}async function Qs(e,t,n,r,i){let a=await Zs(e,t,n,r),o=G(await i(U(e,t),{kind:`ref`,ref:n.ref,...n.fallbackLabel?{fallbackLabel:n.fallbackLabel}:{}}));return{kind:`ref`,target:{kind:`ref`,ref:n.ref},resolution:Os,...a,...o?{backendResult:o}:{}}}async function $s(e,n,r,i,a){let o=r.rect?ke(r,i):null;if(!r.rect||!o||Se(r,i))return r;let s=je(i,r.rect),c=await e.backend.confirmOffscreenTargetVisible?.(U(e,n),r,s);if(c)return{...r,rect:c};let l=Ue(r,i);throw new t(`COMMAND_FAILED`,a.message,{...a.details,rect:r.rect,viewport:o,...l?{scrollDirection:l}:{},hint:a.hint(l)})}function ec(e,t){let n=z(e.type??`Element`),r=R(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,e.actions?JSON.stringify(e.actions):``].join(`|`)}function tc(e,t,n={}){let r=ic(rc(e,n),rc(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 nc(e,t={}){return rc(e,t).length}function rc(e,t){return t.flatten?e.map(e=>({text:L(e,0,!1),comparable:ec(e,0),...t.withRefs&&e.ref?{ref:e.ref}:{}})):_i(e).map(e=>({text:e.text,comparable:ec(e.node,e.depth),...t.withRefs&&e.node.ref?{ref:e.node.ref}:{}}))}function ic(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=oc(a,i,s)?sc(a,i+1):sc(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 ac(o,e,t,n,r)}}return[]}function ac(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=oc(i,c,r)?c+1:c-1,u=sc(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 oc(e,t,n){return t===-n||t!==n&&sc(e,t-1)<sc(e,t+1)}function sc(e,t){return e.get(t)??0}const cc=new Set([`textfield`,`securetextfield`,`textview`,`textarea`,`searchfield`,`edittext`]),lc={strippedIndexes:new Set,refs:new Set};function uc(e){let t=new Set(e.filter(e=>m(e.type??``)===`keyboard`).map(e=>e.index));if(t.size===0)return lc;let n=new Map(e.map(e=>[e.index,e])),r=hc(e,n,t),i=new Set(r),a=Cc(e,n,r);for(let t of hc(e,n,a))i.add(t);for(let o of dc(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 dc(e,t,n,r,i){let a=new Set;if(n.size===0)return a;let o=pc(t,n,r);if(o.size===0)return a;let s=mc(t,r);for(let n of e)!i.has(n.index)&&!s.has(n.index)&&n.rect&&fc(n,t,o)&&a.add(n.index);return a}function fc(e,t,n){if(!e.rect)return!1;let r=wc(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 pc(e,t,n){let r=new Map;for(let i of n){let n=e.get(i);if(!n?.rect)continue;let a=wc(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 mc(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 hc(e,t,n){let r=new Set(n);if(n.size===0)return r;for(let i of e)Tc(i,t,n)&&r.add(i.index);return r}function gc(e,t){if(e.bundleId!==`com.android.systemui`)return!1;if(te(e))return!0;let n=new Set,r=e;for(;r?.bundleId===`com.android.systemui`&&!n.has(r.index);){if(se(r.identifier))return!0;n.add(r.index),r=r.parentIndex===void 0?void 0:t.get(r.parentIndex)}return!1}function _c(e,t){let n=new Map(e.map(e=>[e.index,e])),r=new Set(e.filter(de).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:vc(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?lc:{strippedIndexes:o,refs:s}}function vc(e,t,n){return new Set(e.filter(e=>!n.has(e.index)&&gc(e,t)).map(e=>e.index))}function yc(e,t){let n=uc(e),r=_c(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 bc(e,t){let{strippedIndexes:n}=yc(e,t);return n.size===0?e:e.filter(e=>!n.has(e.index))}function xc(e,t){return yc(e,t).refs}function Sc(e){return uc(e).refs}function Cc(e,t,n){let r=new Set;for(let e of n){let n=t.get(e);if(!n||m(n.type??``)!==`keyboard`)continue;let i=wc(n,t);i!==void 0&&r.add(i)}for(let i of r){let a=new Set([i]);e.some(e=>cc.has(m(e.type??``))&&!n.has(e.index)&&Tc(e,t,a))&&r.delete(i)}return r}function wc(e,t){let n=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;n;){if(m(n.type??``)===`window`)return n.index;n=typeof n.parentIndex==`number`?t.get(n.parentIndex):void 0}}function Tc(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}async function Ec(e,t,n,r){let i=new AbortController,a=[t.signal,e.signal].filter(e=>e!==void 0),o=AbortSignal.any([...a,i.signal]),s=!1,c=setTimeout(()=>{s=!0,i.abort(new DOMException(`Wait deadline exceeded`,`TimeoutError`))},Math.max(0,n));c.unref();try{let e=await r(o);return s&&!a.some(e=>e.aborted)?{timedOut:!0}:(o.throwIfAborted(),{timedOut:!1,value:e})}catch(e){if(s&&!a.some(e=>e.aborted))return{timedOut:!0};throw e}finally{clearTimeout(c)}}function Dc(e){let t=e.snapshotQuality?.backend,n=(e.backend===`xctest`?Oc(e.nodes):e.nodes).map(jc);return n.sort((e,t)=>Nc(e).localeCompare(Nc(t))),{captureBackend:t,nodes:n}}function Oc(e){let t=Ae(e),n=e.flatMap(e=>x(e)&&p(e.rect)?[e.rect]:[]);return e.filter(r=>x(r)||Se(r,e,t,n))}function kc(e,t){return!e||e.captureBackend!==t.captureBackend||e.nodes.length!==t.nodes.length?!1:e.nodes.every((e,n)=>{let r=t.nodes[n];if(!r||e.identity!==r.identity)return!1;if(!e.rect||!r.rect)return e.rect===r.rect;let i=e.rect,a=r.rect;return[`x`,`y`,`width`,`height`].every(e=>Math.abs(Math.round(i[e])-Math.round(a[e]))<=1)})}function Ac(e,t){if(!e||e.nodes.length===0||t.nodes.length===0)return!1;let n=new Map;for(let t of e.nodes)n.set(t.identity,(n.get(t.identity)??0)+1);let r=0;for(let e of t.nodes){let t=n.get(e.identity)??0;t!==0&&(r+=1,n.set(e.identity,t-1))}return r/Math.max(e.nodes.length,t.nodes.length)<.5}function jc(e){return{identity:`${e.type??``}#${Mc(e)}`,...e.rect?{rect:{...e.rect}}:{}}}function Mc(e){return[e.label,e.identifier,e.value].map(e=>String(e??``).trim()).join(`#`)}function Nc(e){let t=e.rect;return`${e.identity}#${t?`${t.x},${t.y},${t.width},${t.height}`:``}`}const Pc=`Settled on a nearly-empty tree — the app may still be loading. Wait for specific content (wait text ...) before interacting.`;async function Fc(e,t,n){let{quietMs:r,timeoutMs:i}=n,a=W(e),o=a+i,s=!1,c=await e.sessions.get(t.session??`default`),l,u=qe(c?.snapshot?.snapshotQuality),d=Math.min(300,Math.max(25,r)),f=0,p,m=0,h,g=a,_=r;for(;W(e)<o;){let c=await Hc(e,t,o-W(e),u);if(!c)return{settled:!1,stalled:!0,waitedMs:W(e)-a,captures:f,nodeCount:m,lastCapture:h};f+=1,h=c,l??=Ic(n.broadTransitionBaselineNodes,c.snapshot,e.backend.platform);let v=Dc(c.snapshot);_=Rc({baseline:l,signal:v,requestedQuietMs:r,currentQuietMs:_}),u??=qe(c.snapshot.snapshotQuality);let y=W(e),ee=Bc({resetRequested:n.resetBudgetOnPrivateAxRecovery,alreadyReset:s,verdict:c.snapshot.snapshotQuality,nowMs:y,timeoutMs:i,deadlineMs:o});if(ee!==void 0){s=!0,o=ee,g=y,p=v,m=c.snapshot.nodes.length;let t=Vc({nowMs:y,quietSinceMs:g,quietMs:_,pollMs:d,deadlineMs:o});if(t<=0)break;await Na(e,t);continue}if(!kc(p,v))p=v,m=c.snapshot.nodes.length,g=y;else if(f>=2&&y-g>=_)return{settled:!0,stalled:!1,waitedMs:y-a,captures:f,nodeCount:m,lastCapture:h};let b=Vc({nowMs:y,quietSinceMs:g,quietMs:_,pollMs:d,deadlineMs:o});if(b<=0)break;await Na(e,b)}return{settled:!1,stalled:!1,waitedMs:W(e)-a,captures:f,nodeCount:m,lastCapture:h}}function Ic(e,t,n){if(!e||!t||!Lc(t.backend,n))return;let r=t.nodes.some(x),i=e.length<=5;if(!(!r&&!i))return Dc({...t,nodes:e})}function Lc(e,t){return e===`xctest`?!0:e===void 0&&t===`ios`}function Rc(e){return e.requestedQuietMs<500||!Ac(e.baseline,e.signal)?e.currentQuietMs:Math.max(e.requestedQuietMs,1500)}function zc(e){return e?.state===`recovered`&&e.backend===`private-ax`&&e.reasonCode!==`deferred`}function Bc(e){if(!(e.resetRequested!==!0||e.alreadyReset||!zc(e.verdict)))return Math.max(e.deadlineMs,e.nowMs+e.timeoutMs)}function Vc(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 Hc(e,t,n,r){let i=await Ec(e,t,n,async n=>await es(e,{...t,signal:n},{updateSession:!1,interactiveOnly:!0,preferredBackend:r}));return i.timedOut?void 0:i.value}const Uc=`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.`,Wc=`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 Gc(e,t,n){return await qc(e,t,{...n,baselineNodes:await Xc(e,t,n.resolved),actionPoint:n.resolved.point})}const Kc=async(e,t)=>(await qc(e,t,t)).observation;async function qc(e,t,n){let r=n.quietMs??500,i=n.timeoutMs??1e4,a={settled:!1,waitedMs:0,captures:0,quietMs:r,timeoutMs:i};try{return await Jc(e,t,n,a,await Fc(e,t,{quietMs:r,timeoutMs:i,resetBudgetOnPrivateAxRecovery:!0,broadTransitionBaselineNodes:n.baselineNodes}))}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.`}}}}async function Jc(e,t,n,r,i){let a={...r,settled:i.settled,waitedMs:i.waitedMs,captures:i.captures};if(!i.lastCapture)return{observation:{...a,hint:i.stalled?Wc:Uc}};let{stored:o,session:s}=await ll(e,t,i.lastCapture),c=i.lastCapture.snapshot.nodes;return{observation:{...a,...i.settled&&o?nl(n.baselineNodes,c,n.actionPoint,s?.appBundleId):{},...cl(i,o,c.length)},settledNodes:c}}function Yc(e,t){if(!e)return;let n=K(e),r=t!==void 0&&n.digest!==K(t).digest;return{...n,changedFromBefore:r}}async function Xc(e,t,n){let r=await e.sessions.get(t.session??`default`);return Zc(n,r)??Qc(n)??$c(r)}function Zc(e,t){if(e.kind===`ref`)return el(t?.refFrameSnapshot?.nodes)}function Qc(e){if(`preActionNodes`in e)return el(e.preActionNodes)}function $c(e){return e?.refFrameSnapshot?.nodes??e?.snapshot?.nodes??[]}function el(e){return e?.length?e:void 0}function tl(e,t,n){let r=tc(bc(e,n),bc(t,n),{flatten:!0,withRefs:!0}),i=r.lines.filter(e=>e.kind!==`unchanged`),a=sl(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 nl(e,t,n,r){let i=tl(e,t,r);return{diff:i,...rl(i,t,n,r)}}function rl(e,t,n,r){let i=new Set(e.lines.filter(e=>e.kind===`added`&&e.ref).map(e=>e.ref)),a=xc(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)&&!il(o.get(e),n))?{}:ol(t,i,r)}function il(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 al=new Set([`application`,`window`]);function ol(e,t,n){let r=xc(e,n),i=e.filter(e=>e.ref&&e.interactionBlocked!==`covered`&&!t.has(e.ref)&&!r.has(e.ref)&&!al.has(z(e.type??`Element`)));if(i.length===0)return{};let a=i.slice(0,20).map(e=>{let t=z(e.type??`Element`),n=R(e,t);return{ref:e.ref,role:t,...n?{label:n}:{}}});return{tail:a,...i.length>a.length?{tailTruncated:!0}:{}}}function sl(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 cl(e,t,n){return e.stalled?{hint:Wc}:e.settled?t?n<5?{hint:Pc}:{}:{hint:`Settled on a sparse, unreadable tree — the diff is omitted and its refs/selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`}:{hint:Uc}}async function ll(e,t,n){if(Je(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 ul(e){let t=e.verify===!0;return{verify:t,needsPreActionBaseline:t||e.settle!==void 0,...e.settle===void 0?{}:{settle:e.settle}}}async function dl(e,t,n,r,i){let a=await fl(e,t,n,i);return ml({...r,...a})}async function fl(e,t,n,r){if(r.settle!==void 0){let i=await Gc(e,t,{...r.settle,resolved:n}),a=r.verify?Yc(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 pl(e,t,n);return i?{evidence:i}:{}}async function pl(e,t,n){let r=`preActionNodes`in n?n.preActionNodes:void 0;try{let n=K((await Bs(e,t,!0)).snapshot.nodes),i=r!==void 0&&n.digest!==K(r).digest;return{...n,changedFromBefore:i}}catch{return}}function ml(e){let t=e;if(t.targetHittable!==!1||!hl(t)||t.hint===void 0)return e;let{hint:n,...r}=t;return r}function hl(e){if(e.evidence?.changedFromBefore===!0)return!0;let t=e.settle?.diff?.summary;return!!t&&(t.additions>0||t.removals>0)}function gl(e,n){let r=e.filter(t=>Te(t,e)).map(e=>e.rect).filter(_l),i=r.length>0?r:e.map(e=>e.rect).filter(_l);if(i.length===0)throw new t(`COMMAND_FAILED`,`Cannot infer viewport for ${n}`);let a=Math.min(...i.map(e=>e.x)),o=Math.min(...i.map(e=>e.y)),s=Math.max(...i.map(e=>e.x+e.width)),c=Math.max(...i.map(e=>e.y+e.height));return{x:a,y:o,width:s-a,height:c-o}}function _l(e){return!!(e&&e.width>0&&e.height>0)}async function vl(e,t){return await e.backend.resolveGestureViewport?.(U(e,t))||gl((await Bs(e,t,!1)).snapshot.nodes,`gesture`)}const yl=async(e,n)=>{let r=await Q(e,n,{action:`focus`,requireInteractive:!0,pipeline:H.resolvedTarget});if(!e.backend.focus)throw new t(`UNSUPPORTED_OPERATION`,`focus is not supported by this backend`);let i=$(r),a=G(await e.backend.focus(U(e,n),i));return{...r,...a?{backendResult:a}:{},...w(`Focused (${i.x}, ${i.y})`)}},bl=async(e,n)=>{let r=ul(n),i=await Q(e,n,{action:`longPress`,requireInteractive:!0,pipeline:H.promotedTarget,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:n.expectedResolvedTarget});if(!e.backend.longPress)throw new t(`UNSUPPORTED_OPERATION`,`longPress is not supported by this backend`);let a=n.durationMs===void 0?void 0:Ma(n.durationMs,`durationMs`,0,12e4),o=$(i),s=G(await e.backend.longPress(U(e,n),o,{durationMs:a}));return await dl(e,n,i,{...i,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...w(`Long pressed (${o.x}, ${o.y})`)},r)},xl=async(e,n)=>{let r=ul(n),i=r.needsPreActionBaseline?null:await Sl(e,n);if(i)return i;let a=await Q(e,n,{action:`hover`,requireInteractive:!1,pipeline:H.resolvedTarget,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:n.expectedResolvedTarget});if(!e.backend.hover)throw new t(`UNSUPPORTED_OPERATION`,`hover is not supported by this backend`);let o=$(a),s=G(await e.backend.hover(U(e,n),o));return await dl(e,n,a,{...a,...s?{backendResult:s}:{},...w(`Hovered (${o.x}, ${o.y})`)},r)};async function Sl(e,t){if(t.target.kind!==`ref`||!e.backend.hoverTarget||t.expectedResolvedTarget)return null;let{hoverTarget:n}=e.backend;return await Qs(e,t,t.target,`hover`,async(e,t)=>await n(e,t))}const Cl=async(e,n)=>{if(!e.backend.performGesture)throw new t(`UNSUPPORTED_OPERATION`,`gesture is not supported by this backend`);await Vs(e,n,`drag`);let r=await vl(e,n),i=await wl(e,n,`source`),a=await wl(e,n,`destination`),o=Be({from:$(i),to:$(a),sourceHoldMs:n.gesture.sourceHoldMs,moveMs:n.gesture.moveMs,destinationHoldMs:n.gesture.destinationHoldMs},r),s=G(await e.backend.performGesture(U(e,n),o)),{start:c,end:l}=Le(o);return{kind:`drag`,durationMs:o.durationMs,pointerCount:1,from:c,to:l,targets:{source:Tl(i),destination:Tl(a)},recording:El(i,a),...s?{backendResult:s}:{},...w(`Dragged ${n.gesture.source} to ${n.gesture.destination}`)}};async function wl(e,t,n){let r=t.gesture[n];return await Q(e,{...t,target:r.startsWith(`@`)?{kind:`ref`,ref:r}:{kind:`selector`,selector:r}},{action:`drag`,requireInteractive:!1,pipeline:H.resolvedTarget,expectedResolvedTarget:t.expectedResolvedTargets?.[n],replayTargetRole:n})}function Tl(e){if(e.kind===`point`||!e.resolution)throw new t(`COMMAND_FAILED`,`gesture drag target resolution was not disclosed`);let n=`selectorChain`in e?e.selectorChain:void 0;return{...n?.length?{selectorChain:n}:{},resolution:e.resolution}}function El(e,t){let n=Dl(e),r=Dl(t),i=Ol(e),a=Ol(t);return{...n?{sourceSelector:n}:{},...r?{destinationSelector:r}:{},...i?{sourceTarget:i}:{},...a?{destinationTarget:a}:{}}}function Dl(e){return`selectorChain`in e&&e.selectorChain?.length?e.selectorChain.join(` || `):void 0}function Ol(e){if(!(!(`selectorChain`in e)||!e.selectorChain?.length||!e.node||!e.preActionNodes))return{selectorChain:e.selectorChain,node:e.node,preActionNodes:e.preActionNodes}}const kl=async(e,n)=>{if(!e.backend.scroll)throw new t(`UNSUPPORTED_OPERATION`,`scroll is not supported by this backend`);let r=jl(n.direction),i=Fl(n.amount,`scroll amount`),a=Ll(n.pixels,`scroll pixels`),o=ze(n.durationMs);He({amount:i,pixels:a},`scroll accepts either amount or pixels, not both`);let s=await Al(e,n),c=s.kind===`viewport`?{kind:`viewport`}:{kind:`point`,point:$(s)},l=e.backend.scroll,u=async()=>await l(U(e,n),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 t=r.edge,i=Ml(s),a=await _a({edge:t,captureState:async r=>await Nl(e,n,t,i,r),scroll:u});d=a.result,f=a.passes}else d=await u(),f=1;let p=G(d),m=Re(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}:{},...w(va(r.direction,r.edge,f,i,a))}};async function Al(e,t){let n=t.target??{kind:`viewport`};return n.kind===`viewport`?(await Vs(e,t,`scroll`),{kind:`viewport`}):await Q(e,{...t,target:n},{action:`scroll`,requireInteractive:!1,pipeline:H.resolvedTarget})}function jl(e){return e===`bottom`?{direction:`down`,edge:`bottom`}:e===`top`?{direction:`up`,edge:`top`}:{direction:Pl(e,`scroll direction`)}}function Ml(e){return e.kind===`viewport`?{}:{point:e.point,nodeIndex:`node`in e?e.node?.index:void 0}}function $(e){if(!e.point)throw new t(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Nl(e,n,r,i,a){if(!e.backend.captureSnapshot)throw new t(`UNSUPPORTED_OPERATION`,`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:o}=e.backend;return await ga({edge:r,target:i,scope:a,captureNodes:async t=>{let r=await o(U(e,n),{scope:t});return r.snapshot?.nodes??r.nodes??[]}})}function Pl(e,n){switch(e){case`up`:case`down`:case`left`:case`right`:return e;default:throw new t(`INVALID_ARGS`,`${n} must be up, down, left, or right`)}}function Fl(e,t){return e===void 0?void 0:Il(e,t)}function Il(e,n){if(!Number.isFinite(e)||e<=0)throw new t(`INVALID_ARGS`,`${n} must be a positive number`);return e}function Ll(e,n){if(e!==void 0){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new t(`INVALID_ARGS`,`${n} must be a positive integer`);return e}}const Rl=/^e\d+$/;function zl(e){if(e[0]?.startsWith(`@`)){let t=Jl(e.slice(1));return{ref:e[0],...t===void 0?{}:{label:t}}}if(Rl.test(e[0]??``))throw new t(`INVALID_ARGS`,`Did you mean "@${e[0]}"? Snapshot refs need the @ prefix.`);let n=me(e);if(n){if(n.rest.length>0)throw new t(`INVALID_ARGS`,Gl(e,n));return{selector:n.selectorExpression}}return Vl(e)}function Bl(e){let n=e[0];if(n?.startsWith(`@`)){let t=e.length>=3?e.slice(2).join(` `):e.slice(1).join(` `);return{kind:`ref`,target:{ref:n,label:e.length>=3?Jl(e.slice(1,2)):void 0},text:t}}if(Rl.test(n??``))throw new t(`INVALID_ARGS`,`Did you mean "@${n}"? Snapshot refs need the @ prefix.`);let r=me(e,{preferTrailingValue:!0});return r?{kind:`selector`,target:{selector:r.selectorExpression},text:r.rest.join(` `)}:{kind:`point`,target:Vl(e.slice(0,2)),text:e.slice(2).join(` `)}}function Vl(e){let n=e[0]??``,r=ve(n);if(r){let i=Hl(n)?r.value:[r.value,...e.slice(1)].join(` `).trim();throw new t(`INVALID_ARGS`,Ul({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 t(`INVALID_ARGS`,Wl(e))}function Hl(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 Ul(e){let{key:t,value:n}=e;return`Unknown selector key "${t}". Supported: ${Ee.join(`, `)}. ${fe(t)?`Did you mean role=${t} label=${ql(n)}?`:`Did you mean label=${ql(n)}?`}`}function Wl(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=>Ce(e??``))?`${n} Selector values with spaces need quotes, e.g. text="Sign in".`:`${n} To match by visible text, use text=${ql(t)} (or label=/id=/role=), or pass an @ref from snapshot.`}function Gl(e,t){return`${`Selector ${t.selectorExpression} is followed by unexpected extra arguments: "${t.rest.join(` `)}".`} Selector values with spaces need quotes, e.g. ${Kl(e,t)??`text="Sign in"`}.`}function Kl(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)}${ql(a)}`;return[...e.slice(0,n-1),o].join(` `)}function ql(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function Jl(e){return e.join(` `).trim()||void 0}function Yl(e,t={}){let n=ea(process.stderr);if(e===`pass`){let e=t.passFormat??`green`;return n?Xl(`✓`,e):`✓`}return e===`fail`?n?Xl(`⨯`,`red`):`⨯`:e===`warn`?n?Xl(`!`,`yellow`):`!`:n?Xl(`-`,`dim`):`-`}function Xl(e,t){return V(e,t,{validateStream:!1})}function Zl(e){return`${Yl($l(e.status))} ${eu(e)}`}function Ql(e){return e.status!==`fail`&&e.status!==`warn`?[]:typeof e.command==`string`?[` run: ${e.command}`]:typeof e.hint==`string`?[` hint: ${e.hint}`]:[]}function $l(e){return e===`pass`?`pass`:e===`fail`?`fail`:e===`warn`?`warn`:`skip`}function eu(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}`}let tu=!1;function nu(){tu=!0}function ru(){let e=tu;return tu=!1,e}function iu(e,n){let r=e===void 0?NaN:Number(e);if(!Number.isInteger(r)||r<1)throw new t(`INVALID_ARGS`,`viewport ${n} must be a positive integer`);return r}const au=[`auto`,`react-native`,`expo`,`repack`];function ou(e){if(e!==void 0){if(au.includes(e))return e;throw new t(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}function su(e){let t=Xe.extname(e).toLowerCase();return t===`.yaml`||t===`.yml`}function cu(e,t){return`Maestro YAML requires explicit --maestro routing: ${e} ${t} --maestro`}function lu(e,t){return t===`maestro`&&su(e)?`maestro`:`ad`}const uu=2*1024*1024,du=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;async function fu(e){let t=Ye(e.inputPath,{cwd:e.cwd}),n=mu(t,e.inputPath);if(lu(t,e.replayBackend)!==`maestro`)return pu(t,{[t]:n},e.inputPath);let{collectMaestroFlowSources:r}=await import(`./src4.js`).then(e=>e.t);return pu(t,r({entryPath:t,entrySource:n,env:e.env,readSource:hu}),e.inputPath)}function pu(e,t,n){return gu(t,n),{entry:e,files:t}}function mu(e,n){try{return $e.readFileSync(e,`utf8`)}catch(r){throw new t(`INVALID_ARGS`,`replay script not found on this machine: ${n}`,{path:e,hint:`Replay scripts are read by the client and sent to the daemon, so the path must resolve where you ran the command.`},r instanceof Error?r:void 0)}}function hu(e){try{return $e.readFileSync(e,`utf8`)}catch{return}}function gu(e,n){let r=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(r<=2097152))throw new t(`INVALID_ARGS`,`replay script sources for ${n} total ${r} bytes, over the ${uu}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:uu,totalBytes:r})}function _u(e,n){let r=e.files[n];if(r===void 0)throw new t(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:e.entry});return r}export{xo as $,Gt as $t,tc as A,lt as An,Ir as At,$o as B,An as Bt,ul as C,dt as Cn,ea as Ct,Ec as D,at as Dn,li as Dt,Fc as E,ot as En,L as Et,Q as F,En as Ft,qo as G,an as Gt,Zo as H,cn as Ht,hs as I,zn as It,Bo as J,Yt as Jt,zo as K,rn as Kt,gs as L,Dn as Lt,vs as M,it as Mn,Fr as Mt,Vs as N,br as Nt,Sc as O,ut as On,mi as Ot,Qs as P,Sr as Pt,Lo as Q,Xt as Qt,es as R,On as Rt,dl as S,ft as Sn,Ai as St,Pc as T,nt as Tn,z as Tt,Qo as U,dn as Ut,ns as V,In as Vt,Jo as W,fn as Wt,jo as X,Zt as Xt,Mo as Y,Qt as Yt,No as Z,qt as Zt,yl as _,Ot as _n,V as _t,cu as a,At as an,Ba as at,vl as b,mt as bn,Mi as bt,iu as c,_t as cn,Pa as ct,Ql as d,Dt as dn,U as dt,D as en,So as et,Zl as f,Ct as fn,Ma as ft,Cl as g,bt as gn,H as gt,zl as h,Et as hn,_a as ht,su as i,T as in,Y as it,nc as j,ct as jn,Hr as jt,xc as k,st as kn,Br as kt,ru as l,St as ln,G as lt,Bl as m,Tt as mn,va as mt,fu as n,E as nn,ho as nt,lu as o,jt as on,q as ot,Yl as p,xt as pn,ga as pt,Ro as q,$t as qt,_u as r,Rt as rn,Xa as rt,ou as s,gt as sn,K as st,du as t,Bt as tn,go as tt,nu as u,wt as un,W as ut,xl as v,ht as vn,Ki as vt,Kc as w,rt as wn,R as wt,kl as x,et as xn,ji as xt,bl as y,w as yn,Gi as yt,ts as z,kn as zt};
|