agent-device 0.17.2 → 0.17.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +2 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.2.apk → agent-device-android-multitouch-helper-0.17.3.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.3.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.2.manifest.json → agent-device-android-multitouch-helper-0.17.3.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.2.apk → agent-device-android-snapshot-helper-0.17.3.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.3.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.2.manifest.json → agent-device-android-snapshot-helper-0.17.3.manifest.json} +6 -6
  8. package/dist/src/123.js +1 -1
  9. package/dist/src/1231.js +1 -1
  10. package/dist/src/1352.js +1 -1
  11. package/dist/src/221.js +2 -2
  12. package/dist/src/2403.js +3 -3
  13. package/dist/src/2415.js +36 -29
  14. package/dist/src/5611.js +1 -0
  15. package/dist/src/5827.js +1 -0
  16. package/dist/src/6088.js +1 -0
  17. package/dist/src/6133.js +1 -0
  18. package/dist/src/7847.js +1 -1
  19. package/dist/src/9471.js +1 -1
  20. package/dist/src/9542.js +6 -3
  21. package/dist/src/9616.js +2 -1
  22. package/dist/src/9818.js +1 -1
  23. package/dist/src/android-snapshot-helper.d.ts +0 -1
  24. package/dist/src/android.js +5 -5
  25. package/dist/src/apple.js +1 -1
  26. package/dist/src/apps.js +10 -10
  27. package/dist/src/args.js +53 -14
  28. package/dist/src/batch.js +1 -1
  29. package/dist/src/cli-output.js +29 -0
  30. package/dist/src/cli.js +15 -16
  31. package/dist/src/command-surface.js +1 -1
  32. package/dist/src/contracts.d.ts +52 -0
  33. package/dist/src/contracts.js +1 -1
  34. package/dist/src/find.js +1 -1
  35. package/dist/src/generic.js +5 -5
  36. package/dist/src/index.d.ts +111 -8
  37. package/dist/src/index.js +1 -1
  38. package/dist/src/input-actions.js +1 -1
  39. package/dist/src/interaction.js +1 -1
  40. package/dist/src/react-native.js +1 -1
  41. package/dist/src/record-trace-recording.js +3 -3
  42. package/dist/src/selector-runtime.js +1 -1
  43. package/dist/src/selectors.d.ts +14 -0
  44. package/dist/src/selectors.js +1 -1
  45. package/dist/src/server.js +2 -2
  46. package/dist/src/session.js +8 -10
  47. package/dist/src/snapshot.js +2 -2
  48. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +1 -0
  49. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +14 -0
  50. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +297 -0
  51. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +328 -0
  52. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +121 -172
  53. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +153 -5
  54. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +171 -0
  55. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +0 -10
  56. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +64 -18
  57. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +200 -0
  58. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +406 -0
  59. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +82 -169
  60. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +425 -0
  61. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +77 -6
  62. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +10 -1
  63. package/ios-runner/README.md +5 -5
  64. package/ios-runner/RUNNER_PROTOCOL.md +0 -1
  65. package/package.json +3 -3
  66. package/server.json +2 -2
  67. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.2.apk.sha256 +0 -1
  68. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.2.apk.sha256 +0 -1
  69. package/dist/src/1534.js +0 -1
  70. package/dist/src/1620.js +0 -1
  71. package/dist/src/1644.js +0 -2
  72. package/dist/src/2284.js +0 -1
  73. package/dist/src/2474.js +0 -1
  74. package/dist/src/2672.js +0 -1
  75. package/dist/src/3393.js +0 -1
  76. package/dist/src/5898.js +0 -1
  77. package/dist/src/695.js +0 -1
  78. package/dist/src/7455.js +0 -1
  79. package/dist/src/8173.js +0 -27
  80. package/dist/src/8407.js +0 -1
  81. package/dist/src/8699.js +0 -1
  82. package/dist/src/9673.js +0 -1
  83. package/dist/src/9974.js +0 -1
@@ -1,6 +1,4 @@
1
- import{__webpack_require__ as e}from"./rslib-runtime.js";import t,{promises as r}from"node:fs";import n from"node:os";import a from"node:path";import{fileURLToPath as i}from"node:url";import o from"node:vm";import{setTimeout as s}from"node:timers/promises";import{asAppError as l,normalizeError as u,AppError as d}from"./9152.js";import{runXcrun as c,dispatchCommand as p,sessionMatchesScope as f,selectorTargetsSessionDevice as m,appendAppLogMarker as h,resolveCommandDevice as w,hasRuntimeTransportHints as g,getSessionCommandKind as y,inferFillText as v,stopIosRunnerSession as A,resolvePublicSessionName as b,requireSessionOrExplicitSelector as S,cleanupUploadedArtifact as _,resolveSessionRequestLogPath as I,refreshSessionDeviceIfNeeded as N,createRequestCanceledError as M,resolveIosDevicectlHint as k,registerRequestAbort as D,errorResponse as x,IOS_SIMULATOR_POST_OPEN_SETTLE_MS as R,IOS_SIMULATOR_POST_CLOSE_SETTLE_MS as O,settleIosSimulator as P,uniqueStrings as L,applyRuntimeHintsToApp as C,withKeyedLock as F,buildSessionRecoveryHint as E,resolveTargetDevice as $,getAppLogPathMetadata as V,setSessionSnapshot as U,shutdownDeviceTarget as T,getSnapshotReferenceFrame as G,clearRuntimeHintsFromApp as q,handleCloseCommand as K,clearAppLogFiles as j,prepareIosRunner as H,session_device_utils_hasExplicitSessionFlag as B,readSessionNetworkCapture as W,cleanupRetainedMaterializedPaths as z,isImplicitSessionScopeConflict as J,resolveSessionRunnerLogPath as X,IOS_DEVICECTL_DEFAULT_HINT as Y,buildSnapshotState as Z,resolveLogBackend as Q,context_contextFromFlags as ee,listDeviceInventory as et,SessionStore as er,isRequestCanceled as en,resolveRequestTrackingId as ea,retainMaterializedPaths as ei,runAppLogDoctor as eo,resolvePayloadInput as es,prepareUploadedArtifact as el,markRequestCanceled as eu,stopAppLog as ed,resolveImplicitSessionScope as ec,ensureDeviceReady as ep,prewarmIosRunnerSession as ef,clearRequestCanceled as em,resolveAndroidEmulatorAvdName as eh,buildSimctlArgsForDevice as ew,parseXmlDocumentSync as eg,resolveFrontmostMacOsApp as ey,runAppleToolCommand as ev,listIosDeviceApps as eA,isCommandSupportedOnDevice as eb,listIosDeviceProcesses as eS,getRequestSignal as e_,markAndroidSnapshotFreshness as eI,startAppLog as eN,emitRequestProgress as eM}from"./2415.js";import{withSuccessText as ek,successText as eD}from"./1534.js";import{isPerfAction as ex,resolveInstallFromSourceResultTarget as eR,PERF_AREA_ERROR_MESSAGE as eO,LOG_ACTION_VALUES as eP,resolveDeployResultTarget as eL,PERF_ACTION_ERROR_MESSAGE as eC,isPerfArea as eF}from"./2672.js";import{isApplePlatform as eE,resolveAppleSimulatorSetPathForSelector as e$,normalizePlatformSelector as eV,matchesPlatformSelector as eU}from"./1644.js";import{parseSessionSurface as eT}from"./2474.js";import{resolveAndroidAdbExecutor as eG}from"./9639.js";import{splitNonEmptyTrimmedLines as eq}from"./7455.js";import{resolveIosSimulatorDeviceSetPath as eK,classifyAndroidAppTarget as ej,resolveIosDeviceDeepLinkBundleId as eH,isInfrastructureBootFailureReason as eB,isWebUrl as eW,resolveAndroidSerialAllowlist as ez,isDeepLinkTarget as eJ,formatAndroidInstalledPackageRequiredMessage as eX,listAndroidApps as eY}from"./8806.js";import{getDiagnosticsMeta as eZ,emitDiagnostic as eQ}from"./7599.js";import{runBatch as e0,mergeParentFlags as e1}from"./1231.js";import{assertResolvedAppsFilter as e2}from"./3675.js";import{listIosApps as e3,readInfoPlistString as e5}from"./apps.js";import{NETWORK_INCLUDE_MODES as e6}from"./9616.js";import{unsupportedCommand as e8,readEnvMap as e4,parseReplayScriptDetailed as e9,readReplayShellEnvSource as e7,normalizeCommandList as te,normalizePlatform as tt,readReplayCliEnvEntries as tr,parseMaestroYamlDocuments as tn,parseAbsolutePoint as ta,readReplayScriptMetadata as ti,parseReplayCliEnvEntries as to,collectReplayShellEnv as ts,support_action as tl,isPlainRecord as tu,requireAppId as td,assertOnlyKeys as tc,resolveMaestroString as tp,requireStringValue as tf,parseMaestroPoint as tm,unsupportedMaestroSyntax as th,readTimeoutMs as tw,writeReplayScript as tg,buildReplayVarScope as ty,resolveReplayAction as tv,mergeReplayVarScopeValues as tA}from"./2403.js";import{runCmdSync as tb}from"./9818.js";import{resolveSelectorChain as tS,extractNodeText as t_,findSnapshotAncestor as tI,isDescendantOfSnapshotNode as tN,splitIsSelectorArgs as tM,buildSelectorChainForNode as tk,buildSnapshotNodeByIndex as tD,matchesSelector as tx,normalizeType as tR}from"./7847.js";import{formatScriptActionSummary as tO,readReactNativeOverlayActionNodes as tP,isTouchTargetCommand as tL,detectReactNativeOverlay as tC,evaluateIsPredicate as tF}from"./123.js";import{normalizeText as tE}from"./7556.js";import{sleep as t$}from"./4829.js";import{pointInsideRect as tV,pointFromPercent as tU,clampGesturePoint as tT,clampToRange as tG,buildSwipeGesturePlan as tq,buildSnapshotDisplayLines as tK}from"./1620.js";import{handleRecordCommand as tj}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as tH,PUBLIC_COMMANDS as tB}from"./5898.js";import{trimRuntimeValue as tW}from"./8656.js";import{splitSelectorFromArgs as tz,parseSelectorChain as tJ,tryParseSelectorChain as tX}from"./8407.js";var tY={};async function tZ(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new d("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await ep(e.session.device),e.session.device}if(!r)throw new d("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let n=await $(e.flags??{});return await ep(n),n}async function tQ(e){let{prepared:t,retention:r,req:n,session:a,sessionName:i}=e;if(r.enabled)return await ei({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:n.meta?.tenantId,sessionName:a?i:void 0,ttlMs:r.ttlMs})}function t0(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function t1(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new d("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new d("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new d("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new d("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new d("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:el(i,t.meta?.tenantId)},cleanup:()=>{_(i)}}:{source:e,cleanup:()=>{}}),s=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new d("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),l=await tZ({session:a,flags:t.flags});if(!eb("install",l))return x("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let u=e_(t.meta?.requestId),c=async(e,i)=>{let l;try{var u;l=await tQ({prepared:e,retention:s,req:t,session:a,sessionName:r});let o=await i(l),d=ek(o,(u=o,`Installed: ${eR(u)}`));return!function(e){let{session:t,sessionStore:r,req:n,data:a}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:n.flags??{},result:a})}({session:a,sessionStore:n,req:t,data:d}),{ok:!0,data:d}}catch(e){throw l&&await z(l.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===l.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:u});return await c(r,async t=>{if(await e(l,r.installablePath),!r.bundleId)throw new d("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...t0(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:p}=await import("./8806.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./8806.js"),m=await p(o.source,{signal:u});return await c(m,async e=>{let t=await f(l,m.installablePath,m.packageName);if(!t)throw new d("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./8806.js"),n=r(t);return{...t0(e),packageName:t,...n?{appName:n}:{},launchTarget:t}})}catch(e){return{ok:!1,error:u(e)}}}async function t2(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new d("INVALID_ARGS","release_materialized_paths requires a materializationId");return await z(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:u(e)}}}e.r(tY),e.d(tY,{handleSessionCommands:()=>op});let t3=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function t5(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function t6(e,t){if(void 0!==e){if("string"!=typeof e)throw new d("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return tW(e)}}function t8(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new d("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function t4(e){if("ios"===e||"android"===e)return e}async function t9(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:n,session:a}=e;!t||!a?.appBundleId||!g(r)||g(n)||await q({device:a.device,appId:a.appBundleId})}async function t7(e){var t,r;let{req:n,sessionName:a,sessionStore:i}=e,o=(n.positionals?.[0]??"show").toLowerCase(),s=i.get(a),l=i.getRuntimeHints(a);if(!["set","show","clear"].includes(o))return x("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){g(l)&&s?.appBundleId&&await q({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(a);return{ok:!0,data:{session:a,cleared:e}}}if("show"===o)return{ok:!0,data:{session:a,configured:!!l,runtime:l}};let u=t4(eV(n.flags?.platform)??l?.platform??s?.device.platform);if(!u)return x("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return x("INVALID_ARGS",`runtime set targets ${u}, but session "${a}" is already bound to ${s.device.platform}.`);let d={platform:(t=n.flags,r={platform:u,metroHost:tW(t?.metroHost),metroPort:t8(t?.metroPort),bundleUrl:tW(t?.bundleUrl),launchUrl:tW(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===t5(d)?x("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(a,d),{ok:!0,data:{session:a,configured:!0,runtime:d}})}let re="open-command-roundtrip",rt="Not implemented for this platform in this release.";function rr(e){let{existingSession:t,sessionName:r,sessionScope:n,device:a,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:a,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:n,device:a,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let rn=new Set(["app","desktop","frontmost-app"]);async function ra(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await ey();return{appBundleId:t.bundleId,appName:t.appName}}function ri(e){let t=e.replaceAll(",","").match(/^-?\d+(?:\.\d+)?/);if(!t)return null;let r=Number(t[0]);return Number.isFinite(r)?r:null}function ro(e){return Math.round(10*e)/10}function rs(e){return Math.round(10*e)/10}let rl="adb-shell-dumpsys-gfxinfo-framestats",ru="Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.";function rd(e,t,r){let n=t.get(r);if(void 0===n)return null;let a=Number(e[n]);return Number.isFinite(a)?a:null}function rc(e){return 0===e.length?{}:{firstFrameNs:Math.min(...e.map(e=>e.intendedVsyncNs)),lastFrameNs:Math.max(...e.map(e=>e.frameCompletedNs))}}function rp(e,t){if(void 0!==e&&void 0!==t)return Math.max(0,Math.round((t-e)/1e6))}function rf(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`^\\s*${r}:\\s*([0-9][0-9,]*)`,"im"));if(!n)return;let a=n[1];return void 0===a?void 0:ri(a)??void 0}async function rm(e,t,r={}){var n,a,i,o,s,l,u,c;let p=eG(e,r.adb);try{let u,c,f,m,h,w,g,y,v,A,b,S=(n=(await p(["shell","dumpsys","gfxinfo",t,"framestats"],{timeoutMs:15e3})).stdout,a=new Date().toISOString(),function(e,t){if(/no process found for:/i.test(e))throw new d("COMMAND_FAILED",`Android gfxinfo did not find a running process for ${t}`,{metric:"fps",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf after the interaction you want to inspect."})}(n,t),f=function(e){let t=e.split(/\nProfile data in ms:\n/i)[0]??"",r=rf(t,"Total frames rendered"),n=t.match(/^\s*Janky frames:\s*([0-9][0-9,]*)\s*\(([0-9.]+)%\)/im);if(void 0===r||!n)return;let a=n[1],i=n[2];if(void 0===a||void 0===i)return;let o=ri(a)??void 0,s=Number(i);if(void 0===o||!Number.isFinite(s)||r<0)return;let l=rf(t,"Uptime"),u=rf(t,"Stats since");return{droppedFramePercent:ro(s),droppedFrameCount:o,totalFrameCount:r,sampleWindowMs:function(e){let{uptimeMs:t,statsSinceNs:r}=e;if(void 0===t||void 0===r)return;let n=t-Math.round(r/1e6);return n>=0?n:void 0}({uptimeMs:l,statsSinceNs:u}),uptimeMs:l,statsSinceNs:u}}(n),m=function(e){let t=[],r=null;for(let a of e.split("\n")){var n;let e=a.trim();if(0===e.length||"---PROFILEDATA---"===e)continue;let i=e.split(",").map(e=>e.trim());if((n=i).includes("IntendedVsync")&&n.includes("FrameCompleted")){r=new Map(i.map((e,t)=>[e,t]));continue}let o=function(e,t){if(!t||e.length<t.size)return;let r=rd(e,t,"Flags"),n=rd(e,t,"IntendedVsync"),a=rd(e,t,"FrameCompleted");if(0===r&&null!==n&&null!==a&&!(n<=0)&&!(a<=n))return{intendedVsyncNs:n,frameCompletedNs:a,durationNs:a-n}}(i,r);o&&t.push(o)}return t.sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs)}(n),h=function(e,t,r){let n=function(e){var t;let r=(t=e.map(e=>e.intendedVsyncNs),[...new Set(t.filter(e=>Number.isFinite(e)))].sort((e,t)=>e-t)),n=[];for(let e=1;e<r.length;e+=1){let t=r[e]-r[e-1];t>=4e6&&t<=5e7&&n.push(t)}if(0!==n.length){let e,t;return e=[...n].sort((e,t)=>e-t),t=Math.floor(e.length/2),e.length%2==1?e[t]:(e[t-1]+e[t])/2}}(e);if(t||0!==e.length||function(e){throw new d("COMMAND_FAILED",`Failed to parse Android framestats output for ${e}`,{metric:"fps",package:e,hint:"Retry perf after exercising the app screen. If the problem persists, capture adb shell dumpsys gfxinfo <package> framestats output for debugging."})}(r),t||void 0!==n)return n;throw new d("COMMAND_FAILED",`Failed to infer Android frame deadline from framestats output for ${r}`,{metric:"fps",package:r,hint:"Retry perf after a longer interaction window so consecutive Android frame timestamps are available."})}(m,f,t),w=Date.parse(a),g=function(e){let{frames:t,measuredAtMs:r,summary:n}=e,a=rc(t),i=n?.statsSinceNs,o=i??a.firstFrameNs,s=rp(o,a.lastFrameNs),l=n?.sampleWindowMs??s;if(!Number.isFinite(r)||n?.uptimeMs===void 0||void 0===o)return{sampleWindowMs:l,windowStartNs:o};let u=r-n.uptimeMs;return{sampleWindowMs:l,windowStartNs:o,windowStartedAt:new Date(u+o/1e6).toISOString(),windowEndedAt:function(e){let{deviceBootWallClockMs:t,measuredAtMs:r,summaryStartNs:n,lastFrameNs:a}=e;return void 0!==n?new Date(r).toISOString():void 0===a?void 0:new Date(t+a/1e6).toISOString()}({deviceBootWallClockMs:u,measuredAtMs:r,summaryStartNs:i,lastFrameNs:a.lastFrameNs}),timestampSource:"estimated-from-device-uptime"}}({frames:m,measuredAtMs:w,summary:f}),y=function(e){let{frames:t,frameDeadlineNs:r,summaryDroppedFrameCount:n}=e;return void 0!==n?n<=0?[]:[...t].sort((e,t)=>t.durationNs-e.durationNs).slice(0,n).sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs):void 0===r?[]:t.filter(e=>e.durationNs>r)}({frames:m,frameDeadlineNs:h,summaryDroppedFrameCount:f?.droppedFrameCount}),v=f?.sampleWindowMs??g.sampleWindowMs??function(e){if(0===e.length)return;let t=rc(e);return rp(t.firstFrameNs,t.lastFrameNs)}(m),i=f,o=m,s=y,u=i?.totalFrameCount??o.length,c=i?.droppedFrameCount??s.length,A={totalFrameCount:u,droppedFrameCount:c,droppedFramePercent:i?.droppedFramePercent??(u>0?ro(c/u*100):0)},b=function(e){let{droppedFrames:t,timing:r,measuredAtMs:n,summary:a}=e;if(0===t.length)return;let i=function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e;if(0===t.length||void 0===r)return[];let i=[],o=[];for(let e of t){let t=o.at(-1);if(!t||e.intendedVsyncNs-t.frameCompletedNs<=5e8){o.push(e);continue}i.push(o),o=[e]}return o.length>0&&i.push(o),i.map(e=>(function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e,i=Math.min(...t.map(e=>e.intendedVsyncNs)),o=Math.max(...t.map(e=>e.frameCompletedNs)),s=Math.max(0,Math.round((i-r)/1e6)),l=Math.max(s,Math.round((o-r)/1e6)),u=void 0!==a&&Number.isFinite(n)?n-a:void 0;return{startOffsetMs:s,endOffsetMs:l,startAt:void 0===u?void 0:new Date(u+i/1e6).toISOString(),endAt:void 0===u?void 0:new Date(u+o/1e6).toISOString(),missedDeadlineFrameCount:t.length,worstFrameMs:rs(Math.max(...t.map(e=>e.durationNs))/1e6)}})({frames:e,windowStartNs:r,measuredAtMs:n,uptimeMs:a})).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}({frames:t,windowStartNs:r.windowStartNs,measuredAtMs:n,uptimeMs:a?.uptimeMs});return i.length>0?i:void 0}({droppedFrames:y,timing:g,measuredAtMs:w,summary:f}),{...A,sampleWindowMs:v,...(l=h,{frameDeadlineMs:void 0===l?void 0:rs(l/1e6),refreshRateHz:void 0===l?void 0:rs(1e9/l)}),windowStartedAt:g.windowStartedAt,windowEndedAt:g.windowEndedAt,timestampSource:g.timestampSource,measuredAt:a,method:rl,source:f?"android-gfxinfo-summary":"framestats-rows",worstWindows:b&&b.length>0?b:void 0});return await rh(e,t,r),S}catch(e){throw u=t,(c=e)instanceof d?new d(c.code,c.message,{...c.details??{},metric:"fps",package:u},c):new d("COMMAND_FAILED",`Failed to sample Android fps for ${u}`,{metric:"fps",package:u},c)}}async function rh(e,t,r={}){let n=eG(e,r.adb);try{await n(["shell","dumpsys","gfxinfo",t,"reset"],{allowFailure:!0,timeoutMs:3e3})}catch{}}let rw="adb-shell-dumpsys-cpuinfo",rg="adb-shell-dumpsys-meminfo";async function ry(e,t,r={}){let n=eG(e,r.adb);try{let e=await n(["shell","dumpsys","cpuinfo"],{timeoutMs:15e3});return function(e,t,r){let n=new Set,a=0;for(let r of eq(e)){var i,o;let e=r.match(/^([0-9]+(?:\.[0-9]+)?)%\s+\d+\/([^\s]+):\s/);if(!e)continue;let s=e[1],l=e[2];if(void 0===s||void 0===l)continue;let u=Number(s);Number.isFinite(u)&&(i=l,o=t,i===o||i.startsWith(`${o}:`))&&(a+=u,n.add(l))}return{usagePercent:ro(a),measuredAt:r,method:rw,matchedProcesses:[...n]}}(e.stdout,t,new Date().toISOString())}catch(e){throw rA("cpu",t,e)}}async function rv(e,t,r={}){let n=eG(e,r.adb);try{let e=await n(["shell","dumpsys","meminfo",t],{timeoutMs:15e3});return function(e,t,r){if(/no process found for:/i.test(e))throw new d("COMMAND_FAILED",`Android meminfo did not find a running process for ${t}`,{metric:"memory",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf."});let n=rb(e,"TOTAL PSS")??function(e){for(let t of e.split("\n")){let e=t.trim();if(!/^TOTAL\b(?!\s+PSS:)/.test(e))continue;let r=e.split(/\s+/).slice(1).find(e=>null!==ri(e));if(!r)break;return ri(r)??void 0}}(e);if(void 0===n)throw new d("COMMAND_FAILED",`Failed to parse Android meminfo output for ${t}`,{metric:"memory",package:t,hint:"Retry perf after reopening the app session. If the problem persists, capture adb shell dumpsys meminfo output for debugging."});return{totalPssKb:n,totalRssKb:rb(e,"TOTAL RSS"),measuredAt:r,method:rg}}(e.stdout,t,new Date().toISOString())}catch(e){throw rA("memory",t,e)}}function rA(e,t,r){return r instanceof d?new d(r.code,r.message,{...r.details??{},metric:e,package:t},r):new d("COMMAND_FAILED",`Failed to sample Android ${e} for ${t}`,{metric:e,package:t},r)}function rb(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`${r}:\\s*([0-9][0-9,]*)`,"i"));if(!n)return;let a=n[1];return void 0===a?void 0:ri(a)??void 0}async function rS(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return eJ(t)?"macos"===e.platform?void 0:"device"===e.kind?eH(r,t):eW(t)?void 0:r??await r_(e,t):await rI(e,t)}async function r_(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rI(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rN(e,t){if(!("android"!==e.platform||!t||eJ(t)))try{let{resolveAndroidApp:r}=await import("./8806.js"),n=await r(e,t);return"package"===n.type?n.value:void 0}catch{return}}async function rM(e,t,r){if(r||"android"!==e.platform||!t||!eJ(t))return r;try{let{getAndroidAppState:t}=await import("./8806.js"),n=await t(e);return n.package?.trim()||r}catch{return r}}async function rk(e,t,r,n){return await rS(e,t,r)??await n(e,t)??("android"===e.platform&&t&&eJ(t)?r:void 0)}function rD(e){return x("INVALID_ARGS",e)}function rx(e,t,r,n){try{return function(e){let{device:t,surfaceFlag:r,openTarget:n,existingSurface:a}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return a??"app";if("linux"===t.platform){if(!r)return"app";let e=eT(r);if(!rn.has(e))throw new d("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&n)throw new d("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new d("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?eT(r):"app";if("app"!==i&&"menubar"!==i&&n)throw new d("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:n})}catch(e){return x(e instanceof d?e.code:"INVALID_ARGS",String(e.message))}}function rR(e){let{shouldRelaunch:t,openTarget:r,surface:n,device:a}=e;return t?r&&eJ(r)?rD("open --relaunch does not support URL targets."):"app"!==n?rD("open --relaunch is supported only for app surfaces."):"android"===a.platform&&r&&"binary"===ej(r)?rD(eX(r)):null:null}async function rO(e){let{req:t,sessionName:r,sessionStore:n,device:a,surface:i,openTarget:o,existingSession:s}=e;await ep(a,{focusExisting:!0,noDeviceHub:t.flags?.noDeviceHub===!0});let{appBundleId:u,appName:c}=await rP({device:a,surface:i,openTarget:o,existingAppBundleId:s?.appBundleId}),p=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:n,device:a}=e,i=r.getRuntimeHints(n),o=function(e){let{runtime:t,sessionName:r,platform:n}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new d("INVALID_ARGS","open runtime must be an object.");let a=Object.keys(t).find(e=>!t3.includes(e));if(a)throw new d("INVALID_ARGS",`Invalid open runtime field: ${a}. Supported fields are ${t3.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new d("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new d("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,n),metroHost:t6(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new d("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return t8(e)}}(t.metroPort),bundleUrl:t6(t.bundleUrl,"bundleUrl"),launchUrl:t6(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:n,platform:t4(a.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let n=e.getRuntimeHints(t);if(!n)return;let a=r?.platform,i=t4(a);if(n.platform&&r&&!i)throw new d("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${a}.`);if(n.platform&&i&&n.platform!==i)throw new d("INVALID_ARGS",`Session runtime hints target ${n.platform}, but session "${t}" is bound to ${a}. Clear the runtime hints or use a different session.`);return i&&n.platform!==i?{...n,platform:i}:n}(r,n,a),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&t5(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=l(t);return x(e.code,e.message,e.details)}}({req:t,sessionStore:n,sessionName:r,device:a});if(!p.ok)return{type:"response",response:p};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=p.data;await t9({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:s})}return{type:"details",details:{appBundleId:u,appName:c,runtime:p.data.runtime}}}async function rP(e){let{device:t,surface:r,openTarget:n,existingAppBundleId:a}=e,i=await ra(r);return{appBundleId:i.appBundleId??await rk(t,n,a,rN),appName:i.appName??n}}let rL=new Map;async function rC(e){let{device:t,closeTarget:r,outFlag:n,context:a}=e;"android"!==t.platform&&await A(t.id),await p(t,"close",[r],n,a),await P(t,O)}async function rF(e){var t,r;let n,{runtime:a,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=a?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||eJ(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,n=ee(t,r,l,u),delete n.launchConsole,delete n.launchArgs,n)})}async function rE(e){var t,r,n,a;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:w,runtime:g,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=w,_=Date.now(),N={};if(v&&c){let e=S??c,t=Date.now();await rC({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ee(u,o.flags,S??y?.appBundleId,A)}}),N.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await C({device:d,appId:S,runtime:g}),N.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let D="ios"===d.platform&&"app"===h&&f.length>0,O={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId},L=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(D&&S&&(N.runnerPrewarmKind="session",N.runnerPrewarmScheduled=!0,L)){i=ef(d,O);let e=Date.now();await i,N.runnerPrewarmWaited=!0,N.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let F=Date.now(),E=await r$({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===E.type)return E.response;let $=E.session??y;await p(d,"open",f,o.flags?.out,{...ee(u,o.flags,S)}),N.openDispatchDurationMs=Math.max(0,Date.now()-F);let V=Date.now();if(await rF({runtime:g,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),N.launchUrlDurationMs=Math.max(0,Date.now()-V),D&&S&&!i&&(i=ef(d,O)),v&&i&&!0!==N.runnerPrewarmWaited){let e=Date.now();await i,N.runnerPrewarmWaited=!0,N.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==N.runnerPrewarmWaited&&(N.runnerPrewarmWaited=!1);S=await rM(d,c,S),"android"===d.platform&&S&&await rh(d,S);let U=c?(t=S,{durationMs:Math.max(0,Date.now()-F),measuredAt:new Date().toISOString(),method:re,appTarget:c,appBundleId:t}):void 0,T=Date.now();if(await P(d,R),N.postOpenSettleDurationMs=Math.max(0,Date.now()-T),en(o.meta?.requestId)){let e=M();return x(e.code,e.message,e.details)}y&&eI(y,"open",y.snapshot);let G=rr({existingSession:$,sessionName:y?.name??b(o),sessionScope:y?.sessionScope??ec(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,n=s,(a=g)&&(0===t5(a)?r.clearRuntimeHints(n):r.setRuntimeHints(n,a)));let q=l.ensureSessionDir(s),K=I(q,o.meta?.requestId??eZ().requestId);N.totalDurationMs=Math.max(0,Date.now()-_);let j=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:n,requestLogPath:a,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:d,runtime:c,runtimeHintCount:p}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:n,requestLogPath:a};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),c&&p(c)>0&&(f.runtime=c),d&&(f.platform=d.platform,f.target=d.target??"mobile",f.device=d.name,f.id=d.id,f.kind=d.kind,"android"===d.platform&&(f.serial=d.id)),d?.platform==="ios"&&(f.device_udid=d.id,f.ios_simulator_device_set=d.simulatorSetPath??null),{...f,...eD(`Opened: ${i??o??t}`)}}({sessionName:G.name,sessionStateDir:q,runnerLogPath:X(q),requestLogPath:K,appName:m,appBundleId:S,surface:h,startup:U,timing:N,device:d,runtime:g,runtimeHintCount:t5});return l.recordAction(G,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?g:void 0,result:j}),l.set(s,G),{ok:!0,data:j}}async function r$(e){let{req:t,sessionName:r,sessionStore:n,device:a,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let d=rr({existingSession:l,sessionName:l?.name??b(t),sessionScope:l?.sessionScope??ec(t),device:a,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});n.set(r,d);let c=await u(d);return c&&!c.ok?{type:"response",response:c}:{type:"session",session:n.get(r)??d}}async function rV(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,i=a.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rx(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?rD("open --relaunch requires an app name or an active session app."):rD("Session already active. Close it first or pass a new --session name.");let u=rR({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let d=await N(i.device),c=await rO({req:t,sessionName:r,sessionStore:a,device:d,surface:l,openTarget:s,existingSession:i});return"response"===c.type?c.response:await rE({req:t,sessionName:r,sessionStore:a,logPath:n,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:c.details.appBundleId,appName:c.details.appName,runtime:c.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return rD("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:n}=e;return t?r&&eJ(r)?rD("open --relaunch does not support URL targets."):"android"===n&&r&&"binary"===ej(r)?rD(eX(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await $(t.flags??{}),d=rx(u,t.flags?.surface,s);if("string"!=typeof d)return d;let c=rR({shouldRelaunch:o,openTarget:s,surface:d,device:u});return c||await F(rL,u.id,async()=>{let e=a.toArray().find(e=>e.device.id===u.id);if(e)return J(t,e)?x("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):x("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:E(e,"device-in-use")});let i=await rO({req:t,sessionName:r,sessionStore:a,device:u,surface:d,openTarget:s});return"response"===i.type?i.response:await rE({req:t,sessionName:r,sessionStore:a,logPath:n,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:d})})}let rU={ios:async(e,t,r)=>{let{reinstallIosApp:n}=await import("./apps.js");return await n(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:n}=await import("./8806.js");return await n(e,t,r)}},rT={ios:async(e,t,r)=>{let{installIosApp:n}=await import("./apps.js"),a=await n(e,r,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:n}=await import("./8806.js"),a=await n(e,r);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function rG(e){let{req:r,command:n,sessionName:a,sessionStore:i,deployOps:o}=e,s=i.get(a),l=r.flags??{},u=S(n,s,l);if(u)return u;let d=r.positionals?.[0]?.trim(),c=r.positionals?.[1]?.trim();if(!d||!c)return x("INVALID_ARGS",`${n} requires: ${n} <app> <path-to-app-binary>`);let p=r.meta?.uploadedArtifactId;try{var f;let e,a=p?el(p,r.meta?.tenantId):er.expandHome(c);if(!t.existsSync(a))return x("INVALID_ARGS",`App binary not found: ${a}`);let u=await w({session:s,flags:l,ensureReady:!1});if(!eb(n,u))return x("UNSUPPORTED_OPERATION",`${n} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,d,a),r=t.bundleId;e=r?{app:d,appPath:a,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:a,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,d,a),r=t.package;e=r?{app:d,appPath:a,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:a,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=ek(e,(f=e,`Installed: ${f.appName??eL(f)}`));return s&&i.recordAction(s,{command:n,positionals:r.positionals??[],flags:r.flags??{},result:m??{}}),{ok:!0,data:m}}finally{p&&_(p)}}async function rq(e,t,r){return await e0(e,t,r)}async function rK(e){let{req:t,sessionName:r,sessionStore:n}=e;if("session_list"===t.command){let e=ec(t);return{ok:!0,data:{sessions:n.toArray().filter(t=>f(t,e)).map(e=>{let t=n.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:X(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=ez(t.flags?.androidDeviceAllowlist),r=eV(t.flags?.platform),n=e$({simulatorSetPath:eK(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),a=await et({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:n,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?a.filter(e=>{var t,n;return t=e,!(n=r)||("apple"===n?eE(t.platform):t.platform===n)}):a,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=l(t);return x(e.code,e.message,e.details)}if("apps"===t.command){let e=n.get(r),a=t.flags??{},i=S(t.command,e,a);if(i)return i;let o=await w({session:e,flags:a,ensureReady:!0});if(!eb("apps",o))return x("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=e2(t.flags?.appsFilter);return eE(o.platform)?{ok:!0,data:{apps:(await e3(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await eY(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rj(e){let{ensureAndroidEmulatorBooted:t}=await import("./8806.js");return await t(e)}let rH='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',rB='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function rW(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r),i=t.flags??{},o=eV(i.platform);if(!a&&B(i))return x("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=S("appstate",a,i);if(s)return s;let l=eE(a?.device.platform)&&m(i,a);if("ios"===o&&!l)return x("SESSION_NOT_FOUND",rH);if("macos"===o&&!l)return x("SESSION_NOT_FOUND",rB);if(l&&a){let e=a.appName??a.appBundleId;if(!a.appName&&!a.appBundleId){if("macos"===a.device.platform&&a.surface&&"app"!==a.surface&&"frontmost-app"!==a.surface)return{ok:!0,data:{platform:a.device.platform,appName:a.surface,appBundleId:a.appBundleId,source:"session",surface:a.surface}};let e="macos"===a.device.platform?"macOS":"iOS";return x("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:a.device.platform,appName:e??"unknown",appBundleId:a.appBundleId,source:"session",surface:a.surface??"app",..."ios"===a.device.platform?{device_udid:a.device.id,ios_simulator_device_set:a.device.simulatorSetPath??null}:{}}}}let u=await w({session:a,flags:i,ensureReady:!0});if("ios"===u.platform)return x("SESSION_NOT_FOUND",rH);if("macos"===u.platform)return x("SESSION_NOT_FOUND",rB);let{getAndroidAppState:d}=await import("./8806.js"),c=await d(u);return{ok:!0,data:{platform:"android",package:c.package,activity:c.activity}}}async function rz(e){let{req:t,sessionName:r,sessionStore:n}=e;if("boot"===t.command){let e,a=n.get(r),i=t.flags??{},o=S(t.command,a,i);if(o)return o;let s="android"===(eV(i.platform)??a?.device.platform),u=!0===i.headless;if(u&&!s)return x("INVALID_ARGS","boot --headless is supported only for Android emulators.");let d=eh({flags:i,sessionDevice:a?.device}),c=s&&!!d,p=!1;try{e=await w({session:a,flags:i,ensureReady:!1})}catch(r){let t=l(r);if(s&&u&&!d&&"DEVICE_NOT_FOUND"===t.code)return x("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!c||"DEVICE_NOT_FOUND"!==t.code||!d)throw r;e=await rj({avdName:d,serial:i.serial,headless:u}),p=!0}if(i.target&&(e.target??"mobile")!==i.target)return x("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${i.target}.`);if(s&&u){if("android"!==e.platform||"emulator"!==e.kind)return x("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!p){let t=eh({flags:i,sessionDevice:a?.device,resolvedDevice:e});if(!t)return x("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rj({avdName:t,serial:i.serial,headless:!0})}await ep(e)}else("android"!==e.platform||!0!==e.booted)&&await ep(e);return eb("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:x("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var a;let e,i=n.get(r),o=t.flags??{},s=S(t.command,i,o);if(s)return s;let l=await w({ensureReady:!1,flags:o,session:i});if(!eb("shutdown",l))return x("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return x("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await T(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:x(u.error?.code??"COMMAND_FAILED",(a=u,(e=a.error?.message??a.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await rW({req:t,sessionName:r,sessionStore:n}):null}function rJ(e,t){for(let r of e){if(t(r))return r;let e=rJ(r.children,t);if(e)return e}}function rX(e,t){let r=[];for(let n of e)t(n)&&r.push(n),r.push(...rX(n.children,t));return r}function rY(e,t){let r=rJ(e,e=>"schema"===e.name&&e.attributes.name===t);return r?r.children.filter(e=>"col"===e.name).map(e=>{let t;return t=e.children.find(e=>"mnemonic"===e.name),t?.text??null??""}):[]}function rZ(e){if(!e||e.children.some(e=>"sentinel"===e.name)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function rQ(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:rZ(e):null}let r0="xctrace-animation-hitches";function r1(e,t){let r=eg(e),n=rY(r,t);return{rows:0===n.length?[]:rX(r,e=>"row"===e.name),schema:n}}function r2(e,t){for(let r of e)r2(r.children,t),r.attributes.id&&t.set(r.attributes.id,{numberValue:rZ(r),process:r3(r)})}function r3(e){if(!e||e.children.some(e=>"sentinel"===e.name))return null;let t=rZ(rJ(e.children,e=>"pid"===e.name)),r=(e.attributes.fmt??"").replace(/\s+\(\d+\)$/,"").trim();return null===t&&0===r.length?null:{pid:t??void 0,name:r.length>0?r:void 0}}let r5="ps-process-snapshot",r6="ps-process-snapshot",r8="xctrace-activity-monitor",r4="xctrace-activity-monitor";async function r9(e,t){if("ios"===e.platform&&"device"===e.kind)return await nu(e,t);let r=await nl(e,t),n=await nh(e,r);if(0===n.length)throw new d("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,hint:"Run open <app> for this session again to ensure the Apple app is active, then retry perf."});let a=new Date().toISOString();return nw({usagePercent:n.reduce((e,t)=>e+t.cpuPercent,0),residentMemoryKb:n.reduce((e,t)=>e+t.rssKb,0),measuredAt:a,matchedProcesses:[r.executableName],cpuMethod:r5,memoryMethod:r6})}async function r7(e,t){var r;let n,o,s,l,u,c;if("ios"!==e.platform||"device"!==e.kind)throw new d("COMMAND_FAILED","Apple frame-health sampling is currently available only on connected iOS devices.",{metric:"fps",platform:e.platform,deviceKind:e.kind});let p=await nd(e,t),f=await nt(e,t,p);return n=r1((r={hitchesXml:f.hitchesXml,frameLifetimesXml:f.frameLifetimesXml,displayInfoXml:f.displayInfoXml,processIds:p.map(e=>e.pid),processNames:L(p.map(e=>a.basename(i(e.executable)))),windowStartedAt:f.windowStartedAt,windowEndedAt:f.windowEndedAt,measuredAt:f.windowEndedAt}).frameLifetimesXml,"hitches-frame-lifetimes").rows.length,o=function(e){if(!e)return;let{rows:t,schema:r}=r1(e,"device-display-info"),n=r.indexOf("max-refresh-rate");if(n<0)return;let a=new Map;for(let e of t){r2(e.children,a);let t=rQ(e.children[n],a);if(null!==t&&t>0)return t}}(r.displayInfoXml),l=(s=(function(e){let t,r,n=eg(e),a=Object.values(r={start:(t=rY(n,"hitches")).indexOf("start"),duration:t.indexOf("duration"),process:t.indexOf("process"),isSystem:t.indexOf("is-system")}).every(e=>e>=0)?r:null;if(!a)return[];let i=new Map;return rX(n,e=>"row"===e.name).map(e=>(function(e,t,r){var n,a,i;let o;if(r2(e.children,r),!0===(n=e.children[t.isSystem],null===(o=rQ(n,r))?null:0!==o))return null;let s=rQ(e.children[t.start],r),l=rQ(e.children[t.duration],r);if(null===s||null===l)return null;let u=(a=e.children[t.process],i=r,a?a.attributes.ref?i.get(a.attributes.ref)?.process??null:r3(a):null);return{startNs:s,durationNs:l,pid:u?.pid,processName:u?.name}})(e,a,i)).filter(e=>!!e)})(r.hitchesXml).filter(e=>{var t,n,a;return t=e,n=r.processIds,a=r.processNames,!!(void 0!==t.pid&&n.includes(t.pid))||!!t.processName&&a.includes(t.processName)})).length,u=Math.max(0,Math.round(Date.parse(r.windowEndedAt)-Date.parse(r.windowStartedAt))),c=function(e,t){if(0===e.length)return[];let r=[...e].sort((e,t)=>e.startNs-t.startNs),n=[],a=[];for(let e of r){let t=a.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){a.push(e);continue}n.push(a),a=[e]}return a.length>0&&n.push(a),n.map(e=>{var r,n;let a,i,o,s;return r=e,n=t,a=Math.min(...r.map(e=>e.startNs)),i=Math.max(...r.map(e=>e.startNs+e.durationNs)),s=Math.max(o=Math.max(0,Math.round(a/1e6)),Math.round(i/1e6)),{startOffsetMs:o,endOffsetMs:s,startAt:new Date(n+o).toISOString(),endAt:new Date(n+s).toISOString(),missedDeadlineFrameCount:r.length,worstFrameMs:ro(Math.max(...r.map(e=>e.durationNs))/1e6)}}).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}(s,Date.parse(r.windowStartedAt)),{droppedFramePercent:n>0?ro(l/n*100):0,droppedFrameCount:l,totalFrameCount:n,sampleWindowMs:u,windowStartedAt:r.windowStartedAt,windowEndedAt:r.windowEndedAt,measuredAt:r.measuredAt,method:r0,matchedProcesses:[...new Set(s.map(e=>e.processName).filter(e=>"string"==typeof e&&e.length>0))],frameDeadlineMs:void 0===o?void 0:ro(1e3/o),refreshRateHz:o,worstWindows:c.length>0?c:void 0}}function ne(e){return"ios"===e.platform&&"device"===e.kind?{method:r0,description:"Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.",unit:"percent",primaryField:"droppedFramePercent",window:"short 2s xctrace Animation Hitches record of the active app process",resetsAfterRead:!1}:{method:r0,description:"Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.",unit:"percent",primaryField:"droppedFramePercent"}}async function nt(e,t,i){let o=await r.mkdtemp(a.join(n.tmpdir(),"agent-device-ios-frame-perf-")),s=a.join(o,"animation-hitches.trace"),l=a.join(o,"hitches.xml"),u=a.join(o,"frame-lifetimes.xml"),d=a.join(o,"display-info.xml");try{let n=await nr({device:e,appBundleId:t,tracePath:s,template:"Animation Hitches",duration:"2s",targetPids:i.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await ni(e,t,s,"hitches",l),await ni(e,t,s,"hitches-frame-lifetimes",u);let a=await no(e,t,s,"device-display-info",d);return{windowStartedAt:n.startedAt,windowEndedAt:n.endedAt,hitchesXml:await r.readFile(l,"utf8"),frameLifetimesXml:await r.readFile(u,"utf8"),displayInfoXml:a?await r.readFile(d,"utf8"):void 0}}finally{await r.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async function nr(e){let{device:t,appBundleId:r,tracePath:n,template:a,duration:i}=e,o=e.allProcesses?["--all-processes"]:(e.targetPids??[]).flatMap(e=>["--attach",String(e)]),s=["xctrace","record","--template",a,"--device",t.id,...o,"--time-limit",i,"--output",n,"--quiet","--no-prompt"],l=await nn(s,e.tracePath);if(0===l.result.exitCode)return e.validateTraceOutput&&await na(e,l.result.stdout,l.result.stderr),{startedAt:l.startedAt,endedAt:l.endedAt,capturedAtMs:l.capturedAtMs};throw new d("COMMAND_FAILED",e.failureMessage,{cmd:"xcrun",args:s,exitCode:l.result.exitCode,stdout:l.result.stdout,stderr:l.result.stderr,appBundleId:r,deviceId:t.id,hint:ny(l.result.stdout,l.result.stderr)})}async function nn(e,t){let n;for(let a=1;a<=3;a+=1){a>1&&(await r.rm(t,{recursive:!0,force:!0}).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)));let i=new Date().toISOString(),o=await c(e,{allowFailure:!0,timeoutMs:6e4});if(n={result:o,startedAt:i,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},0===o.exitCode||!function(e){let t=`${e.stdout}
2
- ${e.stderr}`.toLowerCase();return t.includes("_lockkperf")||t.includes("could not lock kperf")||t.includes("likely another session just started")}(o))break}return n}async function na(e,t,n){let a=await r.stat(e.tracePath).catch(()=>null);if(!(a?.isDirectory()===!0?(await r.readdir(e.tracePath).catch(()=>[])).length>0:(a?.size??0)>0))throw new d("COMMAND_FAILED",`${e.failureMessage}: xctrace produced no trace data`,{tracePath:e.tracePath,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:t,stderr:n,hint:"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf."})}async function ni(e,t,r,n,a){let i=["xctrace","export","--input",r,"--xpath",`/trace-toc/run/data/table[@schema="${n}"]`,"--output",a],o=await c(i,{allowFailure:!0,timeoutMs:15e3});if(0!==o.exitCode)throw new d("COMMAND_FAILED",`Failed to export iOS device ${n} data`,{cmd:"xcrun",args:i,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,appBundleId:t,deviceId:e.id,hint:ny(o.stdout,o.stderr)})}async function no(e,t,r,n,a){try{return await ni(e,t,r,n,a),!0}catch{return!1}}async function ns(e){let t=eg(e),r=rY(t,"activity-monitor-process-live");if(0===r.length)throw new d("COMMAND_FAILED","Failed to parse xctrace activity-monitor-process-live schema");let n=r.indexOf("pid"),a=r.indexOf("process"),i=r.indexOf("cpu-total"),o=r.indexOf("memory-real");if(n<0||a<0||i<0||o<0)throw new d("COMMAND_FAILED","xctrace activity-monitor-process-live export is missing expected columns");let s=rX(t,e=>"row"===e.name),l=[],u=new Map;for(let e of s){var c,p;let t=e.children;if(0===t.length)continue;for(let e of t){let t=rJ(e.children,e=>"pid"===e.name&&"string"==typeof e.attributes.id);if(t?.attributes.id){let e=Number(t.text);u.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&u.set(e.attributes.id,{numberValue:rZ(e),processName:ng(e)})}let r=rQ(t[n],u),s=(c=t[a],p=u,c?c.attributes.ref?p.get(c.attributes.ref)?.processName??null:ng(c):null);null!==r&&Number.isFinite(r)&&s&&l.push({pid:r,processName:s,cpuTimeNs:rQ(t[i],u),residentMemoryBytes:rQ(t[o],u)})}return l}async function nl(e,t){let r="macos"===e.platform?await nf(t):await nm(e,t),n="macos"===e.platform?a.join(r,"Contents","Info.plist"):a.join(r,"Info.plist"),i=await e5(n,"CFBundleExecutable");if(!i)throw new d("COMMAND_FAILED",`Failed to resolve executable for ${t}`,{appBundleId:t,appPath:r});return{executableName:i,executablePath:"macos"===e.platform?a.join(r,"Contents","MacOS",i):a.join(r,i)}}async function nu(e,t){let r=await nd(e,t),n=await nc(e,t),a=await nc(e,t),i=np(await ns(n.xml),r,t,e),o=np(await ns(a.xml),r,t,e),s=a.capturedAtMs-n.capturedAtMs;if(s<=0)throw new d("COMMAND_FAILED",`Invalid Activity Monitor sample window for ${t}`,{appBundleId:t,deviceId:e.id});if(null===i.cpuTimeNs||null===o.cpuTimeNs||null===o.residentMemoryBytes)throw new d("COMMAND_FAILED",`Incomplete Activity Monitor sample for ${t}`,{appBundleId:t,deviceId:e.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});return nw({usagePercent:Math.max(0,o.cpuTimeNs-i.cpuTimeNs)/(1e6*s)*100,residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,cpuMethod:r8,memoryMethod:r4})}async function nd(e,t){let r=(await eA(e,"all")).find(e=>e.bundleId===t);if(!r)throw new d("APP_NOT_INSTALLED",`No iOS device app found for ${t}`,{appBundleId:t,deviceId:e.id});if(!r.url)throw new d("COMMAND_FAILED",`Missing app bundle URL for ${t}`,{appBundleId:t,deviceId:e.id});let n=r.url.replace(/\/$/,""),a=i(n),o=(await eS(e)).filter(e=>e.executable.startsWith(`${n}/`));if(0===o.length)throw new d("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,deviceId:e.id,appBundlePath:a,hint:"Run open <app> for this session again to ensure the iOS app is active, then retry perf."});return o}async function nc(e,t){let i=await r.mkdtemp(a.join(n.tmpdir(),"agent-device-ios-perf-")),o=a.join(i,"sample.trace"),s=a.join(i,"activity-monitor-process-live.xml");try{let n=await nr({device:e,appBundleId:t,tracePath:o,template:"Activity Monitor",duration:"1s",allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await ni(e,t,o,"activity-monitor-process-live",s),{capturedAtMs:n.capturedAtMs,xml:await r.readFile(s,"utf8")}}finally{await r.rm(i,{recursive:!0,force:!0}).catch(()=>{})}}function np(e,t,r,n){let o=new Set(t.map(e=>e.pid)),s=new Set(t.map(e=>a.basename(i(e.executable)))),l=e.filter(e=>o.has(e.pid)||s.has(e.processName));if(0===l.length)throw new d("COMMAND_FAILED",`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:n.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});let u=new Map;for(let e of l){let t=u.get(e.pid);if(!t){u.set(e.pid,e);continue}u.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,cpuTimeNs:nv(t.cpuTimeNs,e.cpuTimeNs),residentMemoryBytes:nv(t.residentMemoryBytes,e.residentMemoryBytes)})}let c=[...u.values()],p=c.map(e=>e.cpuTimeNs).filter(e=>null!==e),f=c.map(e=>e.residentMemoryBytes).filter(e=>null!==e);return{cpuTimeNs:p.length>0?p.reduce((e,t)=>e+t,0):null,residentMemoryBytes:f.length>0?f.reduce((e,t)=>e+t,0):null,matchedProcesses:L(c.map(e=>e.processName))}}async function nf(e){let t=`kMDItemCFBundleIdentifier == "${e.replaceAll('"','\\"')}"`,r=await ev("mdfind",[t],{allowFailure:!0,timeoutMs:15e3});if(0!==r.exitCode)throw new d("COMMAND_FAILED",`Failed to resolve macOS app bundle for ${e}`,{appBundleId:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let n=r.stdout.split("\n").map(e=>e.trim()).find(e=>e.endsWith(".app"));if(!n)throw new d("APP_NOT_INSTALLED",`No macOS app found for ${e}`,{appBundleId:e});return n}async function nm(e,t){let r=ew(e,["get_app_container",e.id,t,"app"]),n=await c(r,{allowFailure:!0,timeoutMs:15e3});if(0!==n.exitCode)throw new d("COMMAND_FAILED",`Failed to resolve iOS simulator app container for ${t}`,{appBundleId:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:"Ensure the iOS simulator app is installed and booted, then retry perf."});let a=n.stdout.trim();if(0===a.length)throw new d("APP_NOT_INSTALLED",`No iOS simulator app container found for ${t}`,{appBundleId:t});return a}async function nh(e,t){let r="macos"===e.platform?["-axo","pid=,%cpu=,rss=,command="]:ew(e,["spawn",e.id,"ps","-axo","pid=,%cpu=,rss=,command="]);return(function(e){let t=[];for(let r of eq(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[n,a,i,o]=e.slice(1);if(void 0===n||void 0===a||void 0===i||void 0===o)continue;let s=Number(n),l=Number(a),u=Number(i),d=o.trim();Number.isFinite(s)&&Number.isFinite(l)&&Number.isFinite(u)&&t.push({pid:s,cpuPercent:l,rssKb:u,command:d})}return t})(("macos"===e.platform?await ev("ps",r,{timeoutMs:15e3}):await c(r,{timeoutMs:15e3})).stdout).filter(e=>{var r,n;let i;return r=e.command,n=t,i=function(e){let[t=""]=e.trim().split(/\s+/,1);return t}(r),!!(n.executablePath&&(r===n.executablePath||i===n.executablePath||r.startsWith(`${n.executablePath} `)))||a.basename(i)===n.executableName})}function nw(e){return{cpu:{usagePercent:ro(e.usagePercent),measuredAt:e.measuredAt,method:e.cpuMethod,matchedProcesses:e.matchedProcesses},memory:{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}}function ng(e){let t=e?.attributes.fmt?.trim()??"";return t?t.replace(/\s+\(\d+\)$/,"").trim():null}function ny(e,t){let r=k(e,t);if(r)return r;let n=`${e}
3
- ${t}`.toLowerCase();return n.includes("no device matched")||n.includes("failed to find device")?Y:n.includes("timed out")?"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.":"Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it."}function nv(e,t){return null===e?t:null===t?e:Math.max(e,t)}async function nA(e,t={}){var r,n;let a,i,o,s,l=(o=(i=(a=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===re&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:re,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:i.durationMs,lastMeasuredAt:i.measuredAt,method:re,sampleCount:a.length,samples:a}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:re},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:o,...{fps:nS(),memory:{available:!1,reason:rt},cpu:{available:!1,reason:rt}}},sampling:{startup:{method:re,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},...function(e){if("android"===e.device.platform)return{memory:{method:rg,description:"Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.",unit:"kB"},cpu:{method:rw,description:"Aggregated CPU usage for app processes matched from adb shell dumpsys cpuinfo.",unit:"percent"},fps:{method:rl,description:ru,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}};var t=e.device;let r=ne(t);if("ios"===t.platform&&"device"===t.kind)return{fps:r,memory:{method:r4,description:"Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"kB"},cpu:{method:r8,description:"Recent CPU usage snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"percent"}};let n="macos"===t.platform?"host ps for the running macOS app executable resolved from the bundle ID.":"xcrun simctl spawn ps for the running iOS simulator app executable resolved from the bundle ID.";return{fps:r,memory:{method:r6,description:`Resident memory snapshot from ${n}`,unit:"kB"},cpu:{method:r5,description:`Recent CPU usage snapshot from ${n}`,unit:"percent"}}}(r)}});return nk(e)&&(e.appBundleId?"android"===e.device.platform?await n_(l,e,e.appBundleId,t):await nI(l,e,e.appBundleId):(n=l,s=nD(e),n.metrics.fps={available:!1,reason:s},n.metrics.memory={available:!1,reason:s},n.metrics.cpu={available:!1,reason:s})),l}async function nb(e,t={}){var r,n;let a={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:nS()},sampling:{fps:"android"===(n=r).device.platform?{method:rl,description:ru,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:ne(n.device)}};return nk(e)&&(e.appBundleId?await nM(a,e,e.appBundleId,t):a.metrics.fps={available:!1,reason:nD(e)}),a}function nS(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function n_(e,t,r,n){let a=await nx(t,r,n);nN(e,t,a)}async function nI(e,t,r){let n=await nR(t,r);nN(e,t,n)}function nN(e,t,r){e.metrics.memory=nP(r.memory),e.metrics.cpu=nP(r.cpu),e.metrics.fps=nL(nP(r.fps),t)}async function nM(e,t,r,n){let a="android"===t.device.platform?await nO(rm(t.device,r,{adb:n.androidAdb})):await nO(r7(t.device,r));e.metrics.fps=nL(nP(a),t)}function nk(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function nD(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function nx(e,t,r){let n={adb:r.androidAdb},[a,i,o]=await Promise.allSettled([rv(e.device,t,n),ry(e.device,t,n),rm(e.device,t,n)]);return{memory:a,cpu:i,fps:o}}async function nR(e,t){let r=await nO(r7(e.device,t)),n=await nO(r9(e.device,t));if("fulfilled"===n.status){let e=n.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:n.reason},cpu:{status:"rejected",reason:n.reason},fps:r}}async function nO(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function nP(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=u(e.reason);return{available:!1,reason:t.message,error:t}}function nL(e,t){var r,n;let a,i;if(!0!==e.available)return e;let o=(r=t.actions,a=nC((n=e).windowStartedAt),i=nC(n.windowEndedAt)??nC(n.measuredAt),void 0===a||void 0===i?[]:r.filter(e=>e.ts>=a&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-a)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function nC(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}let nF=`logs requires ${eP.slice(0,-1).join(", ")}, or ${eP.at(-1)}`,nE=["dump","log"],n$=`network requires ${nE.join(" or ")}`,nV=`network include mode must be one of: ${e6.join(", ")}`,nU={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let n=r.resolveAppLogPath(t),a=V(n);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??Q(e.device),sizeBytes:a.sizeBytes,modifiedAt:a.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>nK(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var n,a,i;let o,s;return n=e,a=t,i=r,o=n.positionals?.slice(1).join(" ")??"",h(s=i.resolveAppLogPath(a),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:n})=>nj(e,t,r,n),start:({session:e,sessionName:t,sessionStore:r})=>nH(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>nB(e,t,r)};async function nT(e){let{req:t}=e;return"perf"===t.command?nG(e):"logs"===t.command?nq(e):"network"===t.command?nW(e):null}async function nG(e){let{req:t,sessionName:r,sessionStore:n,androidAdbExecutor:a}=e,i=n.get(r);if(!i)return x("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let o=(t.positionals?.[0]??"metrics").toLowerCase(),s=(t.positionals?.[1]??"sample").toLowerCase();if(!eF(o))return x("INVALID_ARGS",eO);if(!ex(s))return x("INVALID_ARGS",eC);try{return{ok:!0,data:"frames"===o?await nb(i,{androidAdb:a}):await nA(i,{androidAdb:a})}}catch(e){return{ok:!1,error:u(e)}}}async function nq(e){var t;let r,n,{req:a,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return x("SESSION_NOT_FOUND","logs requires an active session");if(!eb("logs",s.device))return x("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=a,r=(t.positionals?.[0]??"path").toLowerCase(),n=!!t.flags?.restart,eP.includes(r)?n&&"clear"!==r?x("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:n}:x("INVALID_ARGS",nF));return l.ok?await nU[l.action]({...e,session:s,restart:l.restart}):l}async function nK(e,t,r){let n=r.resolveAppLogPath(t),a=await eo(e.device,e.appBundleId);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:a.checks,notes:a.notes}}}async function nj(e,t,r,n){if(e.appLog&&!n)return x("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let a=r.resolveAppLogPath(t);if(!n)return{ok:!0,data:j(a)};let i=e.appBundleId;if(!i)return x("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await ed(e.appLog);let o=j(a),s=r.resolveAppLogPidPath(t);try{let n=await eN(e.device,i,a,s);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:a,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}}),{ok:!0,data:{...o,restarted:!0}}}catch(n){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:u(n)}}}async function nH(e,t,r){if(e.appLog)return x("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return x("INVALID_ARGS","logs start requires an app session; run open <app> first");let n=r.resolveAppLogPath(t),a=r.resolveAppLogPidPath(t);try{let i=await eN(e.device,e.appBundleId,n,a);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:n,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:n,started:!0}}}catch(e){return{ok:!1,error:u(e)}}}async function nB(e,t,r){if(!e.appLog)return x("INVALID_ARGS","no app log stream active");let n=e.appLog.outPath;return await ed(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:n,stopped:!0}}}async function nW(e){let t=function(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(!a)return x("SESSION_NOT_FOUND","network requires an active session");if(!eb("network",a.device))return x("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!nE.includes(i))return x("INVALID_ARGS",n$);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return x("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return x("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let n=(r??t??"summary").toLowerCase();return e6.includes(n)?{ok:!0,include:n}:x("INVALID_ARGS",nV)}(t);return s.ok?{ok:!0,session:a,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:n,session:a}=t,i=await W({device:a.device,appBundleId:a.appBundleId,appLogState:a.appLog?.getState(),appLogStartedAt:a.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:n,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!a.appLog,state:a.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}function nz(e,t,r){var n,a;if(null==e)return tl("open",[tp(td(t,"launchApp"),r)]);if("string"==typeof e)return tl("open",[tp(e,r)]);if(!tu(e))throw new d("INVALID_ARGS","launchApp expects a string or map.");tc(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),nZ(e,"permissions"),nZ(e,"clearKeychain");let i=tp("string"==typeof e.appId?e.appId:td(t,"launchApp"),r),o=(n=e,a=r,[...nX(n.arguments,"launchApp.arguments",a),...nX(n.launchArguments,"launchApp.launchArguments",a)]),s=!0===e.clearState;return tl("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function nJ(e,t,r){if(null==e)return tl("close",[tp(td(t,"stopApp"),r)]);if("string"==typeof e)return tl("close",[tp(e,r)]);throw new d("INVALID_ARGS","stopApp expects a string appId or no value.")}function nX(e,t,r){if(null==e)return[];if("string"==typeof e)return[tp(e,r)];if(Array.isArray(e))return e.map((e,n)=>nY(e,`${t}[${n}]`,r));if(tu(e))return Object.entries(e).flatMap(([e,n])=>[tp(e,r),nY(n,`${t}.${e}`,r)]);throw new d("INVALID_ARGS",`${t} expects a string, list, or map.`)}function nY(e,t,r){if("string"==typeof e)return tp(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new d("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function nZ(e,t){if(void 0!==e[t])throw th(`Maestro launchApp field "${t}" is not supported yet.`)}let nQ="__maestroRunScript",n0="__maestroAssertVisible",n1="__maestroAssertNotVisible",n2="__maestroPressEnter",n3="__maestroWaitForAnimationToEnd",n5="__maestroScrollUntilVisible",n6="__maestroSwipeScreen",n8="__maestroSwipeOn",n4="__maestroTapOn",n9="__maestroTapPointPercent";function n7(e){if(null==e)return tl("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tl("type",["\b".repeat(e)]);if(!tu(e))throw new d("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tc(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tl("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new d("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tl("type",["\b".repeat(e.charactersToErase)])}function ae(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function at(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw th(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function ar(e){return at(e,"swipe direction")}function an(e,t,r=[],n){if("string"==typeof e)return aa(tp(e,n));if(!tu(e))throw new d("INVALID_ARGS",`${t} expects a string or selector map.`);tc(e,t,["id","text","enabled","selected",...r]);let a=[],i=[];if("boolean"==typeof e.enabled&&i.push(ao("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(ao("selected",String(e.selected))),"string"==typeof e.id&&a.push(ao("id",tp(e.id,n)),...i),"string"==typeof e.text&&0===a.length)return aa(tp(e.text,n),i);if("string"==typeof e.label&&0===a.length&&a.push(ao("label",tp(e.label,n)),...i),0===a.length&&i.length>0&&a.push(...i),0===a.length)throw new d("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return a.join(" ")}function aa(e,t=[]){return[[ao("label",e),...t].join(" "),[ao("text",e),...t].join(" "),[ao("id",e),...t].join(" ")].join(" || ")}function ai(e){let t=ae(e.duration);return t?[t]:[]}function ao(e,t){return`${e}=${JSON.stringify(t)}`}function as(e){var t,r;if(!tu(e))return;let n={},a="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return a&&a>1&&(n.count=a),void 0!==i&&(n.intervalMs=i),!0===e.optional&&(n.maestro={optional:!0}),Object.keys(n).length>0?n:void 0}function al(e){let t=as(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function au(e){let t={doubleTap:!0};return tu(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class ad{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new d("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new d("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new d("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new d("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new d("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new d("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function ac(e,t,r){return{...tl(e,t),replayControl:r}}function ap(e,t,r){let n="string"==typeof e?tp(e,t):e,a="number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):void 0;if(void 0===a||!Number.isInteger(a)||a<0)throw new d("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return a}let af=`
1
+ import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./9152.js";import{startAndroidSimpleperfProfile as l,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as u,dispatchCommand as p,sessionMatchesScope as d,selectorTargetsSessionDevice as c,appendAppLogMarker as f,resolveCommandDevice as m,hasRuntimeTransportHints as h,sampleAppleFramePerf as g,captureAppleMemorySnapshot as w,getSessionCommandKind as y,inferFillText as v,startAndroidPerfettoTrace as A,stopIosRunnerSession as I,captureAndroidHeapSnapshot as S,stopAppleXctracePerfCapture as b,resolvePublicSessionName as _,writeAppleXctracePerfReport as k,requireSessionOrExplicitSelector as N,cleanupUploadedArtifact as D,resolveSessionRequestLogPath as x,ANDROID_FRAME_SAMPLE_METHOD as R,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,IOS_SIMULATOR_POST_OPEN_SETTLE_MS as C,IOS_SIMULATOR_POST_CLOSE_SETTLE_MS as $,settleIosSimulator as V,buildSessionRecoveryHint as U,applyRuntimeHintsToApp as F,withKeyedLock as G,resolveTargetDevice as q,getAppLogPathMetadata as T,uniqueStrings as B,setSessionSnapshot as H,sampleAndroidMemoryPerf as K,shutdownDeviceTarget as j,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as z,sampleAndroidCpuPerf as W,clearRuntimeHintsFromApp as J,ANDROID_HPROF_SNAPSHOT_METHOD as Y,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Z,getSnapshotReferenceFrame as Q,clearAppLogFiles as ee,handleCloseCommand as et,prepareIosRunner as er,session_device_utils_hasExplicitSessionFlag as ea,readSessionNetworkCapture as en,cleanupRetainedMaterializedPaths as ei,isImplicitSessionScopeConflict as eo,resolveSessionRunnerLogPath as es,ANDROID_CPU_SAMPLE_DESCRIPTION as el,buildSnapshotState as eu,resolveLogBackend as ep,stopAndroidSimpleperfProfile as ed,context_contextFromFlags as ec,listDeviceInventory as ef,SessionStore as em,ANDROID_CPU_SAMPLE_METHOD as eh,buildAppleMemorySnapshotSupport as eg,stopAndroidPerfettoTrace as ew,isRequestCanceled as ey,resolveRequestTrackingId as ev,retainMaterializedPaths as eA,runAppLogDoctor as eI,resolvePayloadInput as eS,prepareUploadedArtifact as eb,resetAndroidFramePerfStats as e_,ANDROID_FRAME_SAMPLE_DESCRIPTION as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as ex,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eR,ensureDeviceReady as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,prewarmIosRunnerSession as eL,clearRequestCanceled as eO,resolveAndroidEmulatorAvdName as eE,writeAndroidSimpleperfReport as eC,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eG,getRequestSignal as eq,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./2415.js";import{isPerfAction as eK,isPerfSubject as ej,pointFromPercent as ez,PERF_AREA_ERROR_MESSAGE as eW,buildSwipeGesturePlan as eJ,PERF_ACTION_ERROR_MESSAGE as eY,isPerfKind as eX,isPerfMemoryKind as eZ,pointInsideRect as eQ,successText as e0,clampGesturePoint as e1,resolveDeployResultTarget as e2,PERF_MEMORY_KIND_ERROR_MESSAGE as e3,PERF_KIND_ERROR_MESSAGE as e5,isPerfArea as e6,LOG_ACTION_VALUES as e8,withSuccessText as e4,clampToRange as e7,parseSessionSurface as e9,resolveInstallFromSourceResultTarget as te,readReactNativeOverlayActionNodes as tt,detectReactNativeOverlay as tr,PERF_SUBJECT_ERROR_MESSAGE as ta}from"./6133.js";import{isApplePlatform as tn,resolveAppleSimulatorSetPathForSelector as ti,normalizePlatformSelector as to,NETWORK_INCLUDE_MODES as ts,matchesPlatformSelector as tl}from"./9616.js";import{resolveIosSimulatorDeviceSetPath as tu,classifyAndroidAppTarget as tp,resolveIosDeviceDeepLinkBundleId as td,isInfrastructureBootFailureReason as tc,isWebUrl as tf,resolveAndroidSerialAllowlist as tm,isDeepLinkTarget as th,formatAndroidInstalledPackageRequiredMessage as tg,listAndroidApps as tw}from"./8806.js";import{getDiagnosticsMeta as ty,emitDiagnostic as tv}from"./7599.js";import{runBatch as tA,mergeParentFlags as tI}from"./1231.js";import{assertResolvedAppsFilter as tS}from"./3675.js";import{listIosApps as tb}from"./apps.js";import{unsupportedCommand as t_,readEnvMap as tk,parseReplayScriptDetailed as tN,readReplayShellEnvSource as tD,normalizeCommandList as tx,normalizePlatform as tR,readReplayCliEnvEntries as tM,parseMaestroYamlDocuments as tP,parseAbsolutePoint as tL,readReplayScriptMetadata as tO,parseReplayCliEnvEntries as tE,collectReplayShellEnv as tC,support_action as t$,isPlainRecord as tV,requireAppId as tU,assertOnlyKeys as tF,resolveMaestroString as tG,requireStringValue as tq,parseMaestroPoint as tT,unsupportedMaestroSyntax as tB,readTimeoutMs as tH,writeReplayScript as tK,buildReplayVarScope as tj,resolveReplayAction as tz,mergeReplayVarScopeValues as tW}from"./2403.js";import{runCmdSync as tJ}from"./9818.js";import{splitSelectorFromArgs as tY,extractNodeText as tX,findSnapshotAncestor as tZ,isDescendantOfSnapshotNode as tQ,parseSelectorChain as t0,tryParseSelectorChain as t1,splitIsSelectorArgs as t2,resolveSelectorChain as t3,buildSelectorChainForNode as t5,buildSnapshotNodeByIndex as t6,matchesSelector as t8,normalizeType as t4}from"./7847.js";import{formatScriptActionSummary as t7,evaluateIsPredicate as t9,isTouchTargetCommand as re}from"./123.js";import{normalizeText as rt}from"./7556.js";import{sleep as rr}from"./4829.js";import{buildSnapshotDisplayLines as ra}from"./5827.js";import{handleRecordCommand as rn}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as ri,PUBLIC_COMMANDS as ro}from"./6088.js";import{trimRuntimeValue as rs}from"./8656.js";var rl={};async function ru(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eM(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await q(e.flags??{});return await eM(a),a}async function rp(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await eA({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rd(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rc(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eb(i,t.meta?.tenantId)},cleanup:()=>{D(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await ru({session:n,flags:t.flags});if(!eV("install",u))return E("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let p=eq(t.meta?.requestId),d=async(e,i)=>{let s;try{var u;s=await rp({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e4(o,(u=o,`Installed: ${te(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:p}),{ok:!0,data:p}}catch(e){throw s&&await ei(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:p});return await d(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...rd(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./8806.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./8806.js"),m=await c(o.source,{signal:p});return await d(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./8806.js"),a=r(t);return{...rd(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rf(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await ei(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rl),e.d(rl,{handleSessionCommands:()=>oc});let rm=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function rh(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rg(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rs(e)}}function rw(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function ry(e){if("ios"===e||"android"===e)return e}async function rv(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await J({device:n.device,appId:n.appBundleId})}async function rA(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return E("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h(l)&&s?.appBundleId&&await J({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=ry(to(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return E("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return E("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let p={platform:(t=a.flags,r={platform:u,metroHost:rs(t?.metroHost),metroPort:rw(t?.metroPort),bundleUrl:rs(t?.bundleUrl),launchUrl:rs(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===rh(p)?E("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,p),{ok:!0,data:{session:n,configured:!0,runtime:p}})}let rI="open-command-roundtrip",rS="Not implemented for this platform in this release.";function rb(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let r_=new Set(["app","desktop","frontmost-app"]);async function rk(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rN(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return th(t)?"macos"===e.platform?void 0:"device"===e.kind?td(r,t):tf(t)?void 0:r??await rD(e,t):await rx(e,t)}async function rD(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rx(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rR(e,t){if(!("android"!==e.platform||!t||th(t)))try{let{resolveAndroidApp:r}=await import("./8806.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rM(e,t,r){if(r||"android"!==e.platform||!t||!th(t))return r;try{let{getAndroidAppState:t}=await import("./8806.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rP(e,t,r,a){return await rN(e,t,r)??await a(e,t)??("android"===e.platform&&t&&th(t)?r:void 0)}function rL(e){return E("INVALID_ARGS",e)}function rO(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=e9(r);if(!r_.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?e9(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return E(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function rE(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&th(r)?rL("open --relaunch does not support URL targets."):"app"!==a?rL("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tp(r)?rL(tg(r)):null:null}async function rC(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eM(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:p,appName:d}=await r$({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!rm.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${rm.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:rg(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return rw(e)}}(t.metroPort),bundleUrl:rg(t.bundleUrl,"bundleUrl"),launchUrl:rg(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:ry(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=ry(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&rh(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await rv({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function r$(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rk(r);return{appBundleId:i.appBundleId??await rP(t,a,n,rR),appName:i.appName??a}}let rV=new Map;async function rU(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await I(t.id),await p(t,"close",[r],a,n),await V(t,$)}async function rF(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||th(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=ec(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rG(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,I=g,S=Date.now(),b={};if(v&&c){let e=I??c,t=Date.now();await rU({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ec(u,o.flags,I??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await F({device:d,appId:I,runtime:w}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let N="ios"===d.platform&&"app"===h&&f.length>0,D={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId},R=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&I&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,R)){i=eL(d,D);let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rq({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:I,appName:m,existingSession:y});if("response"===P.type)return P.response;let O=P.session??y;await p(d,"open",f,o.flags?.out,{...ec(u,o.flags,I)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rF({runtime:w,device:d,req:o,logPath:u,appBundleId:I,traceLogPath:A,openPositionals:f}),b.launchUrlDurationMs=Math.max(0,Date.now()-$),N&&I&&!i&&(i=eL(d,D)),v&&i&&!0!==b.runnerPrewarmWaited){let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==b.runnerPrewarmWaited&&(b.runnerPrewarmWaited=!1);I=await rM(d,c,I),"android"===d.platform&&I&&await e_(d,I);let U=c?(t=I,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:rI,appTarget:c,appBundleId:t}):void 0,G=Date.now();if(await V(d,C),b.postOpenSettleDurationMs=Math.max(0,Date.now()-G),ey(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let q=rb({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??ex(o),device:d,surface:h,appBundleId:I,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===rh(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let T=l.ensureSessionDir(s),B=x(T,o.meta?.requestId??ty().requestId);b.totalDurationMs=Math.max(0,Date.now()-S);let H=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:p,runtime:d,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),d&&c(d)>0&&(f.runtime=d),p&&(f.platform=p.platform,f.target=p.target??"mobile",f.device=p.name,f.id=p.id,f.kind=p.kind,"android"===p.platform&&(f.serial=p.id)),p?.platform==="ios"&&(f.device_udid=p.id,f.ios_simulator_device_set=p.simulatorSetPath??null),{...f,...e0(`Opened: ${i??o??t}`)}}({sessionName:q.name,sessionStateDir:T,runnerLogPath:es(T),requestLogPath:B,appName:m,appBundleId:I,surface:h,startup:U,timing:b,device:d,runtime:w,runtimeHintCount:rh});return l.recordAction(q,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:H}),l.set(s,q),{ok:!0,data:H}}async function rq(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let p=rb({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??ex(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});a.set(r,p);let d=await u(p);return d&&!d.ok?{type:"response",response:d}:{type:"session",session:a.get(r)??p}}async function rT(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rO(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?rL("open --relaunch requires an app name or an active session app."):rL("Session already active. Close it first or pass a new --session name.");let u=rE({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rC({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rG({req:t,sessionName:r,sessionStore:n,logPath:a,device:p,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return rL("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&th(r)?rL("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tp(r)?rL(tg(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await q(t.flags??{}),p=rO(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rE({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await G(rV,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return eo(t,e)?E("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):E("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:U(e,"device-in-use")});let i=await rC({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rG({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:p})})}let rB={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./8806.js");return await a(e,t,r)}},rH={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./8806.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rK(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=N(a,s,l);if(u)return u;let p=r.positionals?.[0]?.trim(),d=r.positionals?.[1]?.trim();if(!p||!d)return E("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eb(c,r.meta?.tenantId):em.expandHome(d);if(!t.existsSync(n))return E("INVALID_ARGS",`App binary not found: ${n}`);let u=await m({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return E("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,p,n),r=t.bundleId;e=r?{app:p,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,p,n),r=t.package;e=r?{app:p,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let h=e4(e,(f=e,`Installed: ${f.appName??e2(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:h??{}}),{ok:!0,data:h}}finally{c&&D(c)}}async function rj(e,t,r){return await tA(e,t,r)}async function rz(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ex(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>d(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:es(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tm(t.flags?.androidDeviceAllowlist),r=to(t.flags?.platform),a=ti({simulatorSetPath:tu(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ef({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?tn(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=N(t.command,e,n);if(i)return i;let o=await m({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return E("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tS(t.flags?.appsFilter);return tn(o.platform)?{ok:!0,data:{apps:(await tb(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tw(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rW(e){let{ensureAndroidEmulatorBooted:t}=await import("./8806.js");return await t(e)}let rJ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',rY='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function rX(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=to(i.platform);if(!n&&ea(i))return E("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=N("appstate",n,i);if(s)return s;let l=tn(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rJ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",rY);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return E("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await m({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return E("SESSION_NOT_FOUND",rJ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",rY);let{getAndroidAppState:p}=await import("./8806.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function rZ(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=N(t.command,n,o);if(s)return s;let l="android"===(to(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=eE({flags:o,sessionDevice:n?.device}),d=l&&!!p,c=!1;try{e=await m({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!p&&"DEVICE_NOT_FOUND"===t.code)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await rW({avdName:p,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return E("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=eE({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rW({avdName:t,serial:o.serial,headless:!0})}await eM(e)}else("android"!==e.platform||!0!==e.booted)&&await eM(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:E("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=N(t.command,i,o);if(s)return s;let l=await m({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return E("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return E("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await j(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:E(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await rX({req:t,sessionName:r,sessionStore:a}):null}async function rQ(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===rI&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:rI,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:rI,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:rI},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r2(),memory:{available:!1,reason:rS},cpu:{available:!1,reason:rS}}},sampling:{startup:{method:rI,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eG,description:eP,unit:"kB"},cpu:{method:eh,description:el,unit:"percent"},fps:{method:R,description:ek,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Z(a.device)}});return r4(e)&&(e.appBundleId?"android"===e.device.platform?await r3(u,e,e.appBundleId,t):await r5(u,e,e.appBundleId):(n=u,l=r7(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function r0(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:r2()},sampling:{fps:"android"===(a=r).device.platform?{method:R,description:ek,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return r4(e)&&(e.appBundleId?await r8(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:r7(e)}),n}async function r1(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eG,description:eP,unit:"kB",topConsumerLimit:5}:Z(a.device).memory,snapshot:"android"===r.device.platform?{method:Y,description:z,defaultKind:"android-hprof",artifactOnly:!0}:{method:eR,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!r4(e)){if("snapshot"===t.action){let r=an(e,t.kind);return n.artifact=ai(e,r),n.support=as(n.artifact.support)??ao(e),n}return n.metrics={memory:{available:!1,reason:rS}},n}return"sample"===t.action?n.metrics={memory:await at(e,t)}:(n.artifact=await aa(e,t),n.support=as(n.artifact.support)??ao(e)),n}function r2(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r3(e,t,r,a){let n=await r9(t,r,a);r6(e,t,n)}async function r5(e,t,r){let a=await ae(t,r);r6(e,t,a)}function r6(e,t,r){e.metrics.memory=au(r.memory),e.metrics.cpu=au(r.cpu),e.metrics.fps=ap(au(r.fps),t)}async function r8(e,t,r,a){let n="android"===t.device.platform?await al(eF(t.device,r,{adb:a.androidAdb})):await al(g(t.device,r));e.metrics.fps=ap(au(n),t)}function r4(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function r7(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function r9(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([K(e.device,t,a),W(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function ae(e,t){let r=await al(g(e.device,t)),a=await al(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function at(e,t){return e.appBundleId?au("android"===e.device.platform?await al(K(e.device,e.appBundleId,{adb:t.androidAdb})):await al(ar(e))):{available:!1,reason:r7(e)}}async function ar(e){if(!e.appBundleId)throw new s("INVALID_ARGS",r7(e));return(await eU(e.device,e.appBundleId)).memory}async function aa(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",r7(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=an(e,t.kind),n=function(e,t){if(e.out)return em.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?ai(e,a):await S(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?ai(e,a):await w(e.device,e.appBundleId,n)}function an(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function ai(e,t){var r,a;let n=ao(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function ao(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{...eg(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function as(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function al(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function au(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function ap(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=ad((a=e).windowStartedAt),i=ad(a.windowEndedAt)??ad(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function ad(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ac(e){var t,r,a,n,i,s,l,u,p,d;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=af(i,1),m=af(i,2),h=af(i,3),ej(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?E("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?E("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:E("INVALID_ARGS",ta)):(u=t,p=c,g=af(u,1),w=af(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eX(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e5)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return E("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return E("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===y.area?await ag(e,v,v.appBundleId,y):await aw(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function af(e,t){return(e.positionals?.[t]??"").toLowerCase()}function am(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function ah(e,t,a){var n,i,o;let s;return t?em.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function ag(e,t,r,a){if("start"===a.action){ay(t);let n=ah(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return am(e,i)}let n=aA(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=ah(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=av(e,a.outPath,n),o=await ed(t.device,n,i,{adb:e.androidAdbExecutor});return am(e,o)}async function aw(e,t,r,a){if("start"===a.action){ay(t);let n=ah(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return am(e,i)}let n=aA(t,"trace",a.kind),i=av(e,a.outPath,n),o=await ew(t.device,n,i,{adb:e.androidAdbExecutor});return am(e,o)}function ay(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function av(e,t,r){return t?ah(e,t,r.outPath):r.outPath}function aA(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function aI(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return E("INVALID_ARGS","perf cpu requires profile");let t=aS(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=ab(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=aS(e[1],"perf trace",!1);if(!t.ok)return t;let r=ab(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):E("INVALID_ARGS",eW));if(!n.ok)return n;if("android"===t.device.platform)return E("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return E("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return E("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await a_(e,t,n);if("stop"===n.action)return await ak(e,t,n);return await aN(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function aS(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:E("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function ab(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function a_(e,t,r){if(t.applePerf?.active)return E("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=ax(e,r),i=await X({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=aR("started",i);return aD(e,t,o),{ok:!0,data:o}}async function ak(e,t,r){var a,n,o,s,l,u,p;let d,c=t.applePerf?.active;if(!c)return E("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?em.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{d=await b(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=d,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(p=u).mode?{lastProfileTracePath:p.outPath,lastProfileTemplate:p.template}:{lastTracePath:p.outPath}},s.sessionStore.set(s.sessionName,l);let m=aR("stopped",d);return aD(e,t,m),{ok:!0,data:m}}async function aN(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return E("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=ax(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await k({tracePath:em.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aD(e,t,s),{ok:!0,data:s}}function aD(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function ax(e,t){if(t.outPath)return em.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function aR(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let aM=`logs requires ${e8.slice(0,-1).join(", ")}, or ${e8.at(-1)}`,aP=["dump","log"],aL=`network requires ${aP.join(" or ")}`,aO=`network include mode must be one of: ${ts.join(", ")}`,aE={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=T(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??ep(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>aG(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>aq(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aT(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>aB(e,t,r)};async function aC(e){let{req:t}=e;return"perf"===t.command?a$(e):"logs"===t.command?aF(e):"network"===t.command?aH(e):null}async function a$(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return E("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await ac({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await aI(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e6(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return E("INVALID_ARGS",eW);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=eK(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return E("INVALID_ARGS",eY);let w=function(e){if(void 0!==e)return"string"==typeof e&&eX(e)?e:new s("INVALID_ARGS",e5)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aU(r)?void 0:E("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?E("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return E("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,p=n,d=i,u?"memory"!==p||"snapshot"!==d?E("INVALID_ARGS","--kind is only supported with perf memory snapshot"):eZ(u)?void 0:E("INVALID_ARGS",e3):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!p.ok)return p;if(p.native)return await aI(e,l);try{return{ok:!0,data:await aV(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aV(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r1(t,{action:function(e){if(aU(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await r0(t,{androidAdb:i}):await rQ(t,{androidAdb:i})}function aU(e){return"sample"===e||"snapshot"===e}async function aF(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return E("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return E("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e8.includes(r)?a&&"clear"!==r?E("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:E("INVALID_ARGS",aM));return l.ok?await aE[l.action]({...e,session:s,restart:l.restart}):l}async function aG(e,t,r){let a=r.resolveAppLogPath(t),n=await eI(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function aq(e,t,r,a){if(e.appLog&&!a)return E("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:ee(n)};let i=e.appBundleId;if(!i)return E("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eD(e.appLog);let s=ee(n),l=r.resolveAppLogPidPath(t);try{let a=await eB(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function aT(e,t,r){if(e.appLog)return E("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return E("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eB(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function aB(e,t,r){if(!e.appLog)return E("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eD(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function aH(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return E("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return E("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!aP.includes(i))return E("INVALID_ARGS",aL);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return E("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return E("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return ts.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",aO)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t,i=await en({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}function aK(e,t,r){var a,n;if(null==e)return t$("open",[tG(tU(t,"launchApp"),r)]);if("string"==typeof e)return t$("open",[tG(e,r)]);if(!tV(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tF(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),aJ(e,"permissions"),aJ(e,"clearKeychain");let i=tG("string"==typeof e.appId?e.appId:tU(t,"launchApp"),r),o=(a=e,n=r,[...az(a.arguments,"launchApp.arguments",n),...az(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return t$("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aj(e,t,r){if(null==e)return t$("close",[tG(tU(t,"stopApp"),r)]);if("string"==typeof e)return t$("close",[tG(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function az(e,t,r){if(null==e)return[];if("string"==typeof e)return[tG(e,r)];if(Array.isArray(e))return e.map((e,a)=>aW(e,`${t}[${a}]`,r));if(tV(e))return Object.entries(e).flatMap(([e,a])=>[tG(e,r),aW(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aW(e,t,r){if("string"==typeof e)return tG(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function aJ(e,t){if(void 0!==e[t])throw tB(`Maestro launchApp field "${t}" is not supported yet.`)}let aY="__maestroRunScript",aX="__maestroAssertVisible",aZ="__maestroAssertNotVisible",aQ="__maestroPressEnter",a0="__maestroWaitForAnimationToEnd",a1="__maestroScrollUntilVisible",a2="__maestroSwipeScreen",a3="__maestroSwipeOn",a5="__maestroTapOn",a6="__maestroTapPointPercent";function a8(e){if(null==e)return t$("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return t$("type",["\b".repeat(e)]);if(!tV(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tF(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return t$("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return t$("type",["\b".repeat(e.charactersToErase)])}function a4(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function a7(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tB(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function a9(e){return a7(e,"swipe direction")}function ne(e,t,r=[],a){if("string"==typeof e)return nt(tG(e,a));if(!tV(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tF(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(na("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(na("selected",String(e.selected))),"string"==typeof e.id&&n.push(na("id",tG(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return nt(tG(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(na("label",tG(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function nt(e,t=[]){return[[na("label",e),...t].join(" "),[na("text",e),...t].join(" "),[na("id",e),...t].join(" ")].join(" || ")}function nr(e){let t=a4(e.duration);return t?[t]:[]}function na(e,t){return`${e}=${JSON.stringify(t)}`}function nn(e){var t,r;if(!tV(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function ni(e){let t=nn(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function no(e){let t={doubleTap:!0};return tV(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class ns{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function nl(e,t,r){return{...t$(e,t),replayControl:r}}function nu(e,t,r){let a="string"==typeof e?tG(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let np=`
4
2
  const fs = require('node:fs');
5
3
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
6
4
  if (typeof fetch !== 'function') {
@@ -21,10 +19,10 @@ fetch(input.url, {
21
19
  console.error(error && error.stack ? error.stack : String(error));
22
20
  process.exit(1);
23
21
  });
24
- `;function am(e){if("string"!=typeof e)throw new d("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new d("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,ah)}catch(t){throw new d("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function ah(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let aw={launchApp:({value:e,config:t,context:r})=>[nz(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return tl(n4,[aa(tp(e,t))],al(e));if(tu(e)&&"string"==typeof e.point){tc(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tm(e.point);return"percent"===t.kind?tl(n9,[String(t.x),String(t.y)],as(e)):tl("click",[String(t.x),String(t.y)],as(e))}tu(e)&&tc(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=al(e);return tl(n4,[an(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tu(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new d("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=an(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tu(e)&&"string"==typeof e.point){tc(e,"doubleTapOn",["point","delay"]);let t=ta(e.point);return tl("click",[String(t.x),String(t.y)],au(e))}return tu(e)&&tc(e,"doubleTapOn",["id","text","enabled","selected","delay"]),tl("click",[an(e,"doubleTapOn",["delay"],t)],au(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tu(e)&&"string"==typeof e.point){tc(e,"longPressOn",["point"]);let t=ta(e.point);return tl("longpress",[String(t.x),String(t.y),"3000"])}return tu(e)&&tc(e,"longPressOn",["id","text","enabled","selected"]),tl("click",[an(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[tl("type",[tp(function(e){if("string"==typeof e)return e;if(!tu(e))throw new d("INVALID_ARGS","inputText expects a string or map.");if(tc(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new d("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[n7(e)],pasteText:({value:e,context:t,name:r})=>[tl("type",[tp(tf(r,e),t)])],openLink:({value:e,config:t,context:r,name:n})=>{var a,i,o,s,l,u;let d;return[(a=e,i=t,o=r,s=n,d=tp((l=a,u=s,"string"==typeof l?l:tu(l)?(tc(l,u,["link"]),tf(`${u}.link`,l.link)):tf(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?tl("open",[tp(td(i,s),o),d],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):tl("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[tl(n0,[an(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[tl(n1,[an(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tu(e))throw new d("INVALID_ARGS","extendedWaitUntil expects a map.");tc(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw th("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let n=an(r,"extendedWaitUntil",[],t),a=String(tw(e,17e3));return void 0!==e.notVisible?[tl(n1,[n,a])]:[tl(n0,[n,a],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[tl("screenshot",[tp(tf(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw th("Maestro scroll options are not supported yet.");return tl("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[tl(n5,[aa(tp(e,t)),"5000","down"])];if(!tu(e))throw new d("INVALID_ARGS","scrollUntilVisible expects a string or map.");tc(e,"scrollUntilVisible",["element","direction","timeout"]);let r=an(e.element,"scrollUntilVisible.element",[],t),n="string"==typeof e.direction?at(e.direction,"scrollUntilVisible.direction"):"down";return[tl(n5,[r,String(tw(e,5e3)),n])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,n,a;let i;if(!tu(e))throw new d("INVALID_ARGS","swipe expects a map.");tc(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,n=o,a=t,i=ar("string"==typeof r.direction?r.direction:"up"),tl(n8,[an(n,"swipe.from",[],a),i,...ai(r)])):"string"==typeof e.direction?tl(n6,["direction",ar(e.direction),...ai(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tm(e.start),end:tm(e.end)};throw th("Only Maestro swipe start/end coordinates are supported.")}(e);var n=t,a=r,i=ae(e.duration);if("absolute"===n.kind&&"absolute"===a.kind)return tl("swipe",[String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);if("percent"===n.kind&&"percent"===a.kind)return tl(n6,["percent",String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);throw th("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[tl("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tf("pressKey",e).toLowerCase();if("back"===t)return tl("back");if("enter"===t||"return"===t)return tl(n2);if("home"===t)return tl("home");throw th(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[tl("back")],waitForAnimationToEnd:({value:e})=>[tl(n3,[String(tw(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[nJ(e,t,r)],runScript:({value:e,context:t})=>{let r;return[tl(nQ,[function(e,t){if(a.isAbsolute(e))return e;if(!t.baseDir)throw new d("INVALID_ARGS","runScript file paths require replay input to have a source path.");return a.resolve(t.baseDir,e)}((r=function(e,t){if("string"==typeof e)return{file:tp(e,t),env:{}};if(!tu(e))throw new d("INVALID_ARGS","runScript expects a file path string or map.");return tc(e,"runScript",["file","env"]),{file:tp(tf("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(e4(e.env,"runScript.env")).map(([e,r])=>[e,tp(r,t)]))}}(e,t)).file,t)],{...Object.keys(r.env).length>0?{maestro:{runScriptEnv:r.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){if("string"==typeof e)return n.parseRunFlowFile(tp(e,r),r).actions;if(!tu(e))throw new d("INVALID_ARGS","runFlow expects a file path string or map.");tc(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,n;if(null==e)return{shouldRun:!0};if(!tu(e))throw new d("INVALID_ARGS","runFlow.when expects a map.");return(tc(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new d("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new ad(function(e){let t=[],r=0;for(;r<e.length;){var n,a;let i=e.slice(r),o=(n=i,/^\s+/.exec(n)?.[0].length??0);if(o>0){r+=o;continue}let s=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(a=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(a)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(a)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(a)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(a);if(s){t.push(s.token),r+=s.length;continue}throw new d("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tp(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new d("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new d("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new d("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,n=t,{...void 0!==r.visible?{visibleSelector:an(r.visible,"runFlow.when.visible",[],n)}:{},...void 0!==r.notVisible?{notVisibleSelector:an(r.notVisible,"runFlow.when.notVisible",[],n)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...e4(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:n}=t;if(!r&&!n)return e;if(r&&n)throw th("Maestro runFlow.when cannot combine visible and notVisible yet.");let a=r?"visible":"notVisible",i=r??n??"";return[ac("runFlow.when",[a,i],{kind:"maestroRunFlowWhen",mode:a,selector:i,actions:e})]}(function(e,t,r,n,a){if("string"==typeof e.file)return n.parseRunFlowFile(tp(e.file,r),r).actions;if(Array.isArray(e.commands))return a(te(e.commands),t,r,n);throw new d("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,n,a),i)})(e,t,r,n,av),repeat:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i;if(!tu(e))throw new d("INVALID_ARGS","repeat expects a map.");if(tc(e,"repeat",["times","commands","while"]),void 0!==e.while)throw th("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,ap(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new d("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new d("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=te(e.commands);return Array.from({length:o}).flatMap(()=>a(s,t,r,n))})(e,t,r,n,av),retry:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i,o;if(!tu(e))throw new d("INVALID_ARGS","retry expects a map.");if(tc(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new d("INVALID_ARGS","retry requires a commands list.");let s=(i=e.maxRetries,o=r,void 0===i?1:ap(i,o,"retry.maxRetries")),l=a(te(e.commands),t,r,n);return[ac("retry",[String(s)],{kind:"retry",maxRetries:s,actions:l})]})(e,t,r,n,av)},ag={launchApp:(e,t)=>[nz(void 0,e,t)],scroll:()=>[tl("scroll",["down"])],hideKeyboard:()=>[tl("keyboard",["dismiss"])],eraseText:()=>[n7(void 0)],back:()=>[tl("back")],waitForAnimationToEnd:()=>[tl(n3,["15000"])],stopApp:(e,t)=>[nJ(void 0,e,t)]};function ay(e,t,r,n,a){try{return function(e,t,r,n){if("string"==typeof e){var a,i,o;let n;return a=e,i=t,o=r,(n=ag[a])?n(i,o):e8(a)}let s=Object.entries(e);if(1!==s.length)throw new d("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[l,u]=s[0],c=aw[l];return c?c({value:u,config:t,context:r,deps:n,name:l}):e8(l)}(e,t,n,a)}catch(e){if(e instanceof d&&!/\bline \d+\b/.test(e.message))throw new d(e.code,`${e.message} (line ${r})`,e.details);throw e}}function av(e,t,r,n){return e.flatMap((e,a)=>ay(e,t,a+1,r,n))}function aA(e,t){let{config:r,commands:n}=ab(tn(e)),a={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:n,context:a}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...n,...Array.from({length:t.onFlowComplete?.length??0},()=>n.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let n=o[e]??e+1,i=ay(r,t,n,a,{parseRunFlowFile:aS});s.push(...i),i.forEach(()=>l.push(n))}return function(e,t){let r=[],n=[];for(let a=0;a<e.length;a+=1){let i=e[a],o=function(e,t,r){var n;let a=function(e,t,r){let n=e[r],a=e[r+1],i=e[r+2];if(i?.command!==n2||n.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a),s=function(e){if(e?.command!==n4)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n);return a&&null!==o&&null!==s?{action:n,nextAction:a,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!a)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:d}=a;return(n=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(n.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[d,d,t[r+2]??d],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[d],consumed:1}}(e,t,a);if(o){r.push(...o.actions),n.push(...o.actionLines),a+=o.consumed-1;continue}r.push(i),n.push(t[a]??1)}return{actions:r,actionLines:n}}(s,l)}({config:r,commands:n,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),n=-1===r?0:r+1,a=[];for(let e=n;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&a.push(e+1);return a}(e),context:a});return{actions:i,actionLines:o,metadata:{env:r.env}}}function ab(e){if(0===e.length)throw new d("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:te(e[0])};let t=function(e){if(!tu(e))throw new d("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tu(e.env)?{env:e4(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:te(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:te(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new d("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:te(r)}}function aS(e,r){let n=function(e,t){if(a.isAbsolute(e))return e;if(!t.baseDir)throw new d("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return a.resolve(t.baseDir,e)}(e,r);if(r.visitedPaths.has(n))throw new d("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(r.visitedPaths);return o.add(n),aA(i,{...r,baseDir:a.dirname(n),visitedPaths:o})}let a_=/[*?[\]{}]/;function aI(e,t){return"number"==typeof e?e:t}function aN(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function aM(e){return"maestro"===e}let ak=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function aD(e){var t,r,n,a;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&eB(i)||(n=s.code,a=s.message,o=`${n}
25
- ${a}`.toLowerCase(),ak.some(e=>o.includes(e))))}async function ax(e){let r,n,{filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:d,target:c,artifactsDir:p,shard:f,runReplay:m,cleanupSession:h,finalizeAttempt:w}=e;D(s);let g=new Set,y=!1,v=Date.now(),A=function(e){let{artifactsDir:r,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:d}=e;if(!r)return;let c=a.join(r,"replay-timing.ndjson");return t.mkdirSync(a.dirname(c),{recursive:!0}),t.writeFileSync(c,""),n.add(c),aL(c,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:d}),c}({artifactsDir:p,artifactPaths:g,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:d,target:c}),b=m({filePath:i,sessionName:o,platform:d,target:c,requestId:s,artifactsDir:p,artifactPaths:g,tracePath:A,shard:f}).catch(e=>({ok:!1,error:u(e)})).finally(()=>{em(s)});try{n="number"==typeof l?await Promise.race([b,new Promise(e=>{r=setTimeout(()=>{y=!0,eu(s),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(l,[...g]))},l)})]):await b,aL(A,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:o,ok:n.ok,timedOut:y,durationMs:Date.now()-v,errorCode:n.ok?void 0:n.error.code})}finally{var S,_,I;let e,t;r&&clearTimeout(r),y&&(await aR(b)||((S=n)&&!S.ok&&(S.error.details={...S.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),eQ({level:"warn",phase:"test_timeout_cleanup_race",data:{session:o,requestId:s,graceMs:2e3}}),aO({replayPromise:b,cleanupSession:h,sessionName:o,requestId:s})));let a=await aP({finalizeAttempt:w,sessionName:o,artifactPaths:g,artifactsDir:p,tracePath:A});n?.ok&&a&&!a.ok&&(_=n,I=`Replay test finalization failed: ${a.error.message}`,t=Array.isArray((e=_.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,I]);let i=Date.now();try{aL(A,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:o}),await h(o),aL(A,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!0,durationMs:Date.now()-i})}catch(t){let e=u(t);aL(A,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:o,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),eQ({level:"warn",phase:"test_cleanup_failed",data:{session:o,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function aR(e){return await Promise.race([e.then(()=>!0),s(2e3).then(()=>!1)])}async function aO(e){let{replayPromise:t,cleanupSession:r,sessionName:n,requestId:a}=e;try{await t}finally{try{await r(n)}catch(e){eQ({level:"warn",phase:"test_late_cleanup_failed",data:{session:n,requestId:a,error:u(e).message}})}}}async function aP(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:n,artifactsDir:a,tracePath:i}=e;if(!t)return;let o=Date.now();aL(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:n,artifactsDir:a,tracePath:i});return aL(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-o,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let e=u(t);return aL(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-o,errorCode:e.code}),eQ({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function aL(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
26
- `)}async function aC(e){var t,r,n;let i,o=function(e){var t;let r,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:a.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(r=i?a.relative(i,t):a.basename(t)).length||r.startsWith("..")?a.basename(t):r).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await aF(e,o);return t=e,r=o,n=s,i=Date.now()-r.testStartedAt,n.finalResponse?.ok?function(e,t,r,n){let{entry:a,suiteIndex:i,suiteTotal:o,shard:s}=e,l=r.finalResponse;if(!l?.ok)throw Error("Expected passing replay test response.");return eM({type:"replay-test",file:a.path,title:a.title,status:"pass",index:i,total:o,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:n,artifactsDir:t.testArtifactsDir}),{file:a.path,title:a.title,session:r.finalSessionName,status:"passed",durationMs:n,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,replayed:"number"==typeof l.data?.replayed?l.data.replayed:0,healed:"number"==typeof l.data?.healed?l.data.healed:0,...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(l.data?.warnings),...a$(s),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,r,n,i):function(e,t,r,n){var a;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=(a=r.finalResponse)&&!a.ok?a.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return eM({type:"replay-test",file:i.path,title:i.title,status:"fail",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:n,artifactsDir:t.testArtifactsDir,message:u.message}),{file:i.path,title:i.title,session:r.finalSessionName,status:"failed",durationMs:n,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:u,...a$(l)}}(t,r,n,i)}async function aF(e,t){let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let c=0;c<=e.retries;c+=1){var n,a,i,o,s,l,u,d;let p=await aE(e,t,c);if((n=r).finalResponse=(a=p).response,n.finalSessionName=a.sessionName,n.attempts=a.attempt,n.finalAttemptDurationMs=a.durationMs,a.response.ok||n.attemptFailures.push({attempt:a.attempt,message:a.response.error.message,durationMs:a.durationMs}),i=p.response,o=c,s=e.retries,i.ok||aD(i)||o>=s)break;l=e,u=t,(d=p).response.ok||eM({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:d.attempt,maxAttempts:u.maxAttempts,durationMs:d.durationMs,retrying:!0,message:d.response.error.message})}return r}async function aE(e,r,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,requestId:d,timeoutMs:c,shard:p}=e,f=n+1,m=Date.now(),h=function(e,t,r,n,i=0){let o=a.basename(r,a.extname(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}(s,l,o.path,u,n),w=a.join(r.testArtifactsDir,`attempt-${f}`);i=o.path,t.mkdirSync(w,{recursive:!0}),function(e,r){var n;let i,o=a.join(r,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=a.extname(n).toLowerCase())&&".yaml"!==i)return;let s=a.join(r,a.basename(e));a.resolve(s)!==a.resolve(o)&&t.copyFileSync(e,s)}(i,w);let g=await ax({filePath:o.path,sessionName:h,requestId:function(e){let{requestId:t,suiteInvocationId:r,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return ea(`${t??r}${l}:test:${i+1}:${a.basename(n)}:attempt:${o+1}`,r)}({requestId:d,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:p?.shardIndex}),timeoutMs:c,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:w,shard:p,runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),y=Date.now()-m;return!function(e){var r;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:d}=e,c=[...Array.isArray(n=(r=i).ok?r.data?.artifactPaths:r.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||c.push(i.error.logPath);let p=function(e,r){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let r=a.extname(e),n=r?e.slice(0,-r.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${r}`}(a.basename(o),i),s=a.join(r,e);a.resolve(o)!==a.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(c,d),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");p.length>0&&f.push(`copiedArtifacts: ${p.map(e=>a.basename(e)).join(", ")}`);let m=a.join(d,"result.txt"),h=`${f.join("\n")}
27
- `;t.writeFileSync(m,h),i.ok||t.writeFileSync(a.join(d,"failure.txt"),h)}({response:g,filePath:o.path,sessionName:h,attempts:f,maxAttempts:r.maxAttempts,attemptArtifactsDir:w}),{response:g,sessionName:h,attempt:f,durationMs:y}}function a$(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function aV(e,t,r){let n=function(e){let t=aU(e?.shardAll,"--shard-all"),r=aU(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new d("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!n||0===t.length)return;let a=await aT(e,n.count);return{mode:n.kind,shardCount:n.count,total:r+("all"===n.kind?t.length*n.count:t.length),shards:a.map((e,r)=>({shardIndex:r,shardCount:n.count,device:e,entries:"all"===n.kind?t:t.filter((e,t)=>t%n.count===r)}))}}function aU(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new d("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function aT(e,t){var r,n,a,i,o,s,l,u,c;let p,f,m=(r=e,"string"!=typeof(p=r?.device)||0===p.trim().length?[]:p.split(",").map(e=>e.trim()).filter(Boolean)),h=(a=await et((n=e,f=ez(n?.androidDeviceAllowlist),{platform:n?.platform,target:n?.target,iosSimulatorSetPath:e$({simulatorSetPath:eK(n?.iosSimulatorDeviceSet),platform:n?.platform,target:n?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(s=a,l=i,u=o,l.map(e=>{let t=aq(e),r=s.find(r=>aG(r,u)&&(r.id===e||aq(r.name)===t));if(!r)throw new d("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):a.filter(e=>{var t;return!!aG(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(aK));if(h.length<t){throw new d("DEVICE_NOT_FOUND",`test sharding requires ${(c=t,`${c} device${1===c?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function aG(e,t){return!(!eU(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function aq(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function aK(e,t){return e.id.localeCompare(t.id)}async function aj(e){let{req:r,sessionName:n,runReplay:i,cleanupSession:o,finalizeAttempt:s}=e;if((r.positionals?.length??0)===0)return x("INVALID_ARGS","test requires at least one path or glob");try{var u,c,p,f;let e,l,m,h,w,g=function(e){var r,n,i,o,s,l;let{inputs:u,cwd:c,platformFilter:p,replayBackend:f}=e,m=(r=f,new Set(aM(r)?[".ad",".yaml",".yml"]:[".ad"])),h=c??process.cwd(),w=[...new Set(u.flatMap(e=>(function(e,r,n){var i,o;let s=er.expandHome(e,r);if(t.existsSync(s)){let r=t.statSync(s);if(r.isDirectory())return[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:s}).map(e=>a.join(s,e)));if(r.isFile()){if(!n.has(a.extname(s)))throw new d("INVALID_ARGS",`test does not support this file type: ${e}`);return[s]}return[]}if(i=e,!a_.test(i)&&(o=s,!a_.test(o)))throw new d("INVALID_ARGS",`test input not found: ${e}`);let l=a.isAbsolute(s)?s:e;return t.globSync(l,{cwd:a.isAbsolute(s)?void 0:r}).map(e=>a.isAbsolute(e)?e:a.resolve(r,e)).filter(e=>n.has(a.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e))})(e,h,m)))].map(e=>a.normalize(e)).sort((e,t)=>e.localeCompare(t)),g=[];for(let e of w){let r=t.readFileSync(e,"utf8"),u=ti(r),d=(n=r,i=e,o=f,aM(o)&&".ad"!==a.extname(i)?function(e){let{config:t}=ab(tn(e));return t.name}(n):void 0);if(!p){g.push({kind:"run",path:e,title:d,metadata:u});continue}if(!u.platform){aM(f)?g.push({kind:"run",path:e,title:d,metadata:u}):g.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${p}`});continue}s=p,l=u.platform,("apple"===s?"apple"===l||"ios"===l||"macos"===l:l===s)&&g.push({kind:"run",path:e,title:d,metadata:u})}if(0===g.filter(e=>"run"===e.kind).length){let e=p?` for --platform ${p}`:"";throw new d("INVALID_ARGS",`No replay tests matched${e}.`)}return g}({inputs:r.positionals,cwd:r.meta?.cwd,platformFilter:r.flags?.platform,replayBackend:r.flags?.replayBackend}),y=(u=r.meta?.requestId,(u?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),v=function(e){let{artifactsDir:t,cwd:r,suiteInvocationId:n}=e,i=er.expandHome(t??".agent-device/test-artifacts",r);return a.join(i,n)}({artifactsDir:"string"==typeof r.flags?.artifactsDir?r.flags.artifactsDir:void 0,cwd:r.meta?.cwd,suiteInvocationId:y}),A=Date.now(),b=g.filter(e=>"skip"===e.kind),S=g.filter(e=>"run"===e.kind),_=await aV(r.flags,S,b.length),I=_?function(e){let{entries:t,total:r}=e,n=[];for(let[e,a]of t.entries())"skip"===a.kind&&(eM({type:"replay-test",file:a.path,status:"skip",index:e+1,total:r,message:a.message}),n.push({file:a.path,status:"skipped",durationMs:0,reason:a.reason,message:a.message}));return n}({entries:g,total:_.total}):[];_?I.push(...await aH({shards:_.shards,sessionName:n,suiteInvocationId:y,cwd:r.meta?.cwd,requestId:r.meta?.requestId,flags:r.flags,suiteArtifactsDir:v,suiteTotal:_.total,runReplay:i,cleanupSession:o,finalizeAttempt:s})):I.push(...await az({discoveryEntries:g,sessionName:n,suiteInvocationId:y,cwd:r.meta?.cwd,requestId:r.meta?.requestId,flags:r.flags,suiteArtifactsDir:v,suiteTotal:g.length,runReplay:i,cleanupSession:o,finalizeAttempt:s}));let N=(c=_?.total??g.length,p=I,f=Date.now()-A,e=p.filter(e=>"passed"===e.status).length,m=(l=p.filter(e=>"failed"===e.status)).length,h=p.filter(e=>"skipped"===e.status).length,w=e+m,{total:c,executed:w,passed:e,failed:m,skipped:h,notRun:Math.max(0,c-w-h),durationMs:f,failures:l,tests:p});return{ok:!0,data:N}}catch(t){let e=l(t);return x(e.code,e.message)}}async function aH(e){return(await Promise.allSettled(e.shards.map(async t=>await aB({...e,shard:t})))).flatMap((t,r)=>{var n,a;let i;if("fulfilled"===t.status)return t.value;let o=e.shards[r];return o?[(n=o,a=e.sessionName,i=u(t.reason),{file:n.entries[0]?.path??`shard-${n.shardIndex+1}`,session:aW(a,n),status:"failed",durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:n.shardIndex,shardCount:n.shardCount,deviceId:n.device.id})]:[]})}async function aB(e){let{shard:t,sessionName:r}=e;return await aJ({...e,entries:t.entries,sessionName:aW(r,t),shard:t})}function aW(e,t){return`${e}:shard-${t.shardIndex+1}`}async function az(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:n,cwd:a,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:c}=e,p=[],f=0;for(let[e,m]of t.entries()){if("skip"===m.kind){eM({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),p.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await aC({entry:m,sessionName:r,suiteInvocationId:n,caseIndex:f-1,cwd:a,requestId:i,retries:aN(o?.retries,m.metadata.retries),timeoutMs:aI(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:d,finalizeAttempt:c});if(p.push(t),o?.failFast===!0||aD(t))break}return p}async function aJ(e){let{entries:t,sessionName:r,suiteInvocationId:n,cwd:a,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:d,cleanupSession:c,finalizeAttempt:p}=e,f=[];for(let[e,m]of t.entries()){let t=await aC({entry:m,sessionName:r,suiteInvocationId:n,caseIndex:e,cwd:a,requestId:i,retries:aN(o?.retries,m.metadata.retries),timeoutMs:aI(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,shard:u,runReplay:d,cleanupSession:c,finalizeAttempt:p});if(f.push(t),o?.failFast===!0||aD(t))break}return f}let aX={maestro:{parse:function(e,t={}){var r;let n;return aA(e,(n=(r=t).visitedPaths??new Set,r.sourcePath&&n.add(a.resolve(r.sourcePath)),{baseDir:r.sourcePath?a.dirname(r.sourcePath):void 0,platform:tt(r.platform),env:{},envOverrides:r.env??{},visitedPaths:n}))}}};function aY(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,n=tz(null!==r?e.slice(0,-1):e.slice());return!n||n.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:n.selectorExpression,selectorTimeout:r}}async function aZ(e){let{action:t,sessionName:r,logPath:n,sessionStore:a}=e;if(!(tL(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=a.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),tL(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&aQ(r)?t.slice(0,-1):t}(e),n=r[0]??"";n&&!n.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=tM(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=aY(e.positionals??[]);r&&t.push(r)}return L(t).filter(e=>e.trim().length>0)})(t).map(e=>tX(e)).filter(e=>null!==e);if(0===o.length)return null;let s=tL(t.command)||"fill"===t.command,l=tL(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await a0(i,t,n,s,a);for(let e of o){let r=tS(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let n=tk(r.node,i.device.platform,{action:"fill"===t.command?"fill":tL(t.command)?"click":"get"}).join(" || ");if(tL(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&aQ(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,n):[n]};if("fill"===t.command){let e=v(t);if(!e)continue;return{...t,positionals:[n,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,n]}}if("is"===t.command){let{predicate:e,split:r}=tM(t.positionals);if(!e)continue;let a=r?.rest.join(" ").trim()??"",i=[e,n];return"text"===e&&a.length>0&&i.push(a),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=aY(t.positionals??[]),r=[n];return e&&r.push(e),{...t,positionals:r}}}return null}function aQ(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function a0(e,t,r,n,a){let i=Z(await p(e.device,"snapshot",[],t.flags?.out,{...ee(r,{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n});return U(e,i),a.set(e.name,e),i}let a1=new WeakMap,a2=new WeakMap;function a3(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function a5(e){var t;let r,n=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,a=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...n?{snapshotRaw:!0}:{}}});return a.ok&&e.scope&&(t=e.scope,(r=G(a6(a.data)))&&a1.set(t,r)),a}function a6(e){return Array.isArray(e?.nodes)?e:void 0}let a8=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function a4(e,t,r,n){let a=it(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=a9({nodes:e.nodes,matches:a,platform:r}),o=ii(e.nodes,i.matches,void 0,ie(t),n,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:a.length>0?`Maestro selector matched ${a.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function a9(e){let t=e.matches.filter(t=>tF({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let n=tC(e);if(!n.detected||!n.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let a=tP(n),i=a.filter(t=>tF({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===a.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function a7(e){return e?.platform==="android"?"android":"ios"}function ie(e){let t=tJ(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),n=r[0];return n&&r.every(e=>e===n)?n:null}function it(e,t,r,n={}){for(let a of tJ(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,n){return!!tx(e,t,r)||t.terms.every(t=>(function(e,t,r,n){var a,i,o;return"string"!=typeof t.value||"id"!==(a=t.key)&&"label"!==a&&"text"!==a&&"value"!==a?tx(e,{raw:t.key,terms:[t]},r):ir((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:t_(i)),t.value,n)})(e,t,r,n))})(e,a,r,n));if(t.length>0)return t}return[]}function ir(e,t,r={}){var n;let a=e??"",i=tE(a),o=tE(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(n=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(n))return!1;try{return new RegExp(t).test(a)}catch{return!1}}function ia(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let n=function(e,t,r){let n=t;for(;"number"==typeof n.parentIndex&&(n=r.get(n.parentIndex)??e[n.parentIndex]);)if(n.rect)return n.rect.width>0&&n.rect.height>0?n.rect:null;return null}(e,t,r);return n?{rect:n,inherited:!0}:null}function ii(e,t,r,n,a,i=!1,o=!1,s){var l,u,d,c,p,f,m,h,w,g,y,v,A,b,S,_,I,N,M;let k,D,x,R,O=tD(e),P=(l=e,u=t,d=O,c=n,p=r,f=a,m=i,x=(D=(k=u.map(e=>{var t;let r;return(r=ia(l,t=e,d))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?D:k,c&&void 0===p?(h=x,w=f,g=m,R=h.filter(e=>{var t,r;let n,a;return t=e.rect,r=w,n=r?.referenceWidth??1/0,a=r?.referenceHeight??1/0,t.x<n&&t.y<a&&t.x+t.width>0&&t.y+t.height>0}),g||R.length>0?R:h):k),L=function(e,t,r,n,a,i){var o,s,l,u,d,c,p;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=n,u=a,d=i,u&&l?function(e,t,r,n){let a=t.filter(e=>0===iw(e.node,r));if(a.length>=2){let t=is(e,a,r,n);if(t)return t}let i=t.filter(e=>1===iw(e.node,r));return a.length>0||i.length<2?null:is(e,i,r,n)}(o,s,l,d)??io(o,s,l,d):io(o,s,l,d));return(c=f,p=n,a&&p&&c)?function(e,t,r){var n,a,i,o,s,l,u,d,c,p,f,m,h,w,g,y,v,A;let b,S,_,I,N,M,k,D;if(n=t,a=r,!(("cell"===(b=tR(n.node.type??""))||"other"===b||"scrollview"===b||"scroll-area"===b)&&!(n.rect.width<120)&&!(n.rect.height<32)&&!(n.rect.height>80)&&1>=iw(n.node,a)))return null;let x=(i=e,o=t,s=r,l=tD(e),i.filter(e=>{var t,r,n;let a;return e.index!==o.node.index&&!!e.rect&&tN(i,e,o.node,l)&&(t=e,r=o.rect,n=s,!("button"!==(a=tR(t.type??""))&&"cell"!==a&&"other"!==a||1>=iw(t,n))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!im(r,t.rect)&&ic(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===x.length)return null;let R=(_=Math.floor((S=[...x.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),S[_]??0),O=function(e,t){let r=[],n=e.x,a=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(a,i.x+i.width);t>n&&r.push({x:n,width:t-n}),n=Math.max(n,o)}return a>n&&r.push({x:n,width:a-n}),r}(t.rect,x.map(e=>e.rect)),P=(u=t,d=r,c=O,p=R,M=c.filter(e=>{var t,r;return t=e.width,r=p,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),k=(f=u,m=d,I=c.find(e=>1>Math.abs(e.x-f.rect.x)),N=Math.max(48,Math.min(220,8*m.length+24)),(h=f,w=m,g=I,y=N,g&&"scrollview"===tR(h.node.type??"")&&1>=iw(h.node,w)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&g.width<=.55*h.rect.width&&g.width>=.6*y)?{x:f.rect.x,width:Math.min(N,I.width)}:null),D=M.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),k&&!D?k:1===M.length?M[0]??null:k);return P?(v=t,A=P,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,n)??f:f}(e,P,r,n,o,s);return y=e,v=L,A=O,b=o,S=a,v?b?(_=y,I=v,N=A,M=S,(ip(I.node)?null:tI(_,I.node,N,e=>{if(!ip(e))return null;let t=ia(_,e,N);return t&&function(e,t,r){var n,a;if(!im(t,e)||(n=e,!((a=t).height<32||a.height>80||n.height<.75*a.height||.75>ic(n,a))&&!(a.width<240)&&a.width>=3*n.width))return!1;let i=iu(t),o=iu(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(I.rect,t.rect,M)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function io(e,t,r,n){return(function(e,t,r,n){var a;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===iw(e.node,r));if(l.length<2)return t;let u=tD(e),d=l.map(t=>({candidate:t,container:il(e,t.node,u)})).filter(e=>!!e.container);if(d.length<2||d.length!==l.length)return t;let c=d.filter(e=>{var t;return t=e,d.some(e=>e!==t&&t.container.index!==e.container.index&&ih(t.container.rect,e.container.rect)>=.6)});if(c.length<2)return t;let p=(o=Math.max(...i=(a=c).map(e=>iu(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:a.filter(e=>iu(e.container.rect)===o).map(e=>e.candidate));if(p.length>0)return p;let f=function(e,t,r,n){if(!r)return[];let a=il(e,r.node,n),i=a&&im(a.rect,r.rect)?a:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>ih(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(ih(e.rect,t.rect)>=.6)return 0;let n=e.index-t.node.index;return n>=0?n:1e5+Math.abs(n)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,c,n,u);if(f.length>0)return f;let m=Math.max(...c.map(e=>e.container.index)),h=c.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,n).sort((e,t)=>(function(e,t,r){var n,a;let i=function(e,t,r){if(r){let n=iw(e.node,r)-iw(t.node,r);if(0!==n)return n}let n=id(e.node)-id(t.node);if(0!==n)return n;let a=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==a)return a;let i=r&&id(e.node)===id(t.node)?iu(t.rect)-iu(e.rect):iu(e.rect)-iu(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(n=e.rect,a=t.rect,Math.round(n.x)!==Math.round(a.x)||Math.round(n.y)!==Math.round(a.y)||Math.round(n.width)!==Math.round(a.width)||Math.round(n.height)!==Math.round(a.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function is(e,t,r,n){let a=tD(e),i=t.filter(r=>{var n;return(n=r).rect.width>=16&&n.rect.width<=260&&n.rect.height>=24&&n.rect.height<=80&&t.some(t=>{var n,i,o,s;return n=e,i=t,o=r,s=a,!(i.node.index===o.node.index||!im(i.rect,o.rect)||iu(i.rect)<2*iu(o.rect))&&tN(n,o.node,i.node,s)})});return io(e,i,r,n)}function il(e,t,r){return tI(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=tR(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iu(e){return e.width*e.height}function id(e){return a8.get(tR(e.type??""))??3}function ic(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function ip(e){let t=tR(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function im(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function ih(e,t){let r=Math.max(e.x,t.x),n=Math.min(e.x+e.width,t.x+t.width),a=Math.max(e.y,t.y);return Math.max(0,n-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-a)/Math.max(1,Math.min(iu(e),iu(t)))}function iw(e,t){let r=[e.label,t_(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>tE(e)===tE(t))?1:r.some(e=>ir(e,t))?2:3}async function ig(e){var t,r;let n=i_(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!n.ok)return n.response;let a=(t=e.baseReq,r=n.selector,t.flags?.platform!=="ios"&&t.flags?.platform!=="android"?null:ie(r));return a?await iy(e,n,a):await iA(e,n)}async function iy(e,t,r){let n=Date.now(),a=await iv(e,t,r);return a.ok?ik({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:a.data}},t.selector,n):await ib(e,t,a,n)}async function iv(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iA(e,t){let r,n,a=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await iI(e,t.selector,"assertVisible");if(l.visible)return ik(l.response,t.selector,a);r=l.response,n=l.snapshot??n;let u=iS(e.baseReq,t,l,a);if("return"===u.kind)return u.response;let d=function(e){var t,r,n,a;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,n=e.startedAt,a=e.deadlineMs,!t&&r-n<a)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:a,deadlineMs:i});if("capture-again"===d){o=!0;continue}if("finish"===d)break;await t$(250)}return iD(r??a3("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),n,e.baseReq)}async function ib(e,t,r,n){let a=await iI(e,t.selector,"assertVisible");if(a.visible)return ik(a.response,t.selector,n);let i=iS(e.baseReq,t,a,n);return"return"===i.kind?i.response:iD(r,a.snapshot,e.baseReq)}function iS(e,t,r,n){var a,i,o,s,l,u,d;return!(a=r.response).ok&&"COMMAND_FAILED"===a.error.code&&a.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=iN(ie(e));if(!iM(r))return!1;let n=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>iN(e));return!n.some(e=>e.includes("something went wrong"))&&n.some(e=>e!==r&&!iM(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,d=n,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-d,timeoutMs:u}})}:{kind:"continue"}}function i_(e,t){let[r,n=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:a3("INVALID_ARGS",`${t.command} requires a selector.`)};let a=Number(n);return!Number.isFinite(a)||a<0?{ok:!1,response:a3("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:a}}async function iI(e,t,r){let n=await a5(e);return function(e,t,r,n){var a;if(!n.ok)return{visible:!1,response:n,infrastructureFailure:!0};let i=a6(n.data);if(!i)return{visible:!1,response:a3("COMMAND_FAILED",`Unable to read snapshot data for ${r}.`),infrastructureFailure:!0};let o=a4(i,t,a7(e.baseReq.flags),G(i));return o.ok?(a=e.scope,a&&a2.set(a,{selector:t}),{visible:!0,response:{ok:!0,data:{selector:t,matches:o.matches,nodeIndex:o.node.index,nodeType:o.node.type,nodeLabel:o.node.label,nodeIdentifier:o.node.identifier,rect:o.rect}}}):{visible:!1,response:a3("COMMAND_FAILED",o.message,{selector:t}),infrastructureFailure:!1,snapshot:i}}(e,t,r,n)}function iN(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iM(e){return"loading"===e||"loading..."===e}function ik(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function iD(e,r,n){var i;if(e.ok||!r)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,r){try{t.mkdirSync(r,{recursive:!0});let n=a.join(r,"failure-snapshot.json"),i=a.join(r,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
28
- `);let o=tK(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
29
- `),[n,i]}catch{return[]}}(r,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function ix(e){let t,r=i_(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let n=Date.now(),a=0;for(;Date.now()-n<=r.timeoutMs;){let i=await iI(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)a=0,t=i.response;else{a+=1;let e=Date.now()-n;if(a>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:a,waitedMs:e,timeoutMs:r.timeoutMs}}}await t$(250)}return a>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:a,waitedMs:Date.now()-n,timeoutMs:r.timeoutMs}}:a3("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function iR(e){let t,r,n=Number(e.positionals[0]??15e3);if(!Number.isFinite(n)||n<0)return a3("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let a=Date.now();for(;Date.now()-a<n;){let a=await a5(e),i=function(e,t,r){let n=function(e){if(!e.ok)return null;let t=a6(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?n?t===n?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:n}:{done:!0,response:e}:{done:!1}}(a,t,n);if(i.done)return i.response;t=i.signature??t,r=a,await t$(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:n}}}let iO=.35,iP=120,iL=360,iC=8;function iF(e,t){return Math.round(Math.min(iL,Math.max(iP,"number"==typeof e?e*iO:0,1.5*t)))}async function iE(e){var t,r,n;let[a,i="5000",o="down"]=e.positionals;if(!a)return a3("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return a3("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=ie(a),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await iH(e,a,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let n=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!n.ok)return n}return t=d,r=a,n=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${n}ms for selector: ${r}. Last wait: ${t.error.message}`}}:a3("COMMAND_FAILED",`scrollUntilVisible timed out after ${n}ms for selector: ${r}`)}async function i$(e){let[t,r]=e.positionals,n=Number(t),a=Number(r);if(!Number.isFinite(n)||!Number.isFinite(a))return a3("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await a5(e);if(!i.ok)return i;let o=a6(i.data);if(!o)return a3("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=G(o);if(!s)return a3("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=tU(s,n,a);return await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function iV(e){let t=await iU(e);if(t)return t;let r=await iK(e);return r.ok?await iq(e,r,r.durationMs):r.response}async function iU(e){let[t,r,n]=e.positionals;if("direction"===t&&("left"===r||"right"===r))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...n?[n]:[]]})}async function iT(e){var t,r,n,a;let i,[o,s]=e.positionals;if(!o)return a3("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:a3("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await iB(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await t$(250)}return r=e,n=o,a=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:n}}:a??a3("COMMAND_FAILED",`tapOn timed out for selector: ${n}`)}async function iG(e){let[t,r="up",n]=e.positionals;if(!t)return a3("INVALID_ARGS","swipe.label requires a label selector.");let a=await iX(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!a.ok)return a.response;let i=function(e,t){let r=tV(e.rect),n=e.frame,a=iF(n?.referenceWidth,e.rect.width),i=iF(n?.referenceHeight,e.rect.height),o=iC,s=n?n.referenceWidth-o:r.x+a,l=n?n.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:tG(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:tG(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:tG(r.x-a,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:tG(r.x+a,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(a.target,r);return i.ok?await iq(e,i,n):a3("INVALID_ARGS",i.message)}async function iq(e,t,r){return await e.invoke({...e.baseReq,command:"swipe",positionals:[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]]})}async function iK(e){var t;let r=((t=e.scope)?a1.get(t):void 0)??await ij(e);if(!r)return{ok:!1,response:a3("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[n,...a]=e.positionals;return"direction"===n?function(e,t){let[r,n]=e;if(!r)return{ok:!1,response:a3("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(r){case"up":case"down":var a,i,o;let s;return a=r,i=t,o=n,{ok:!0,start:tT({x:(s=tq({direction:a,amount:.6,referenceWidth:i.referenceWidth,referenceHeight:i.referenceHeight})).x1,y:s.y1},i,8),end:tT({x:s.x2,y:s.y2},i,8),durationMs:o};default:return{ok:!1,response:a3("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(a,r):"percent"===n?function(e,t,r){var n,a,i,o,s;let[l,u,d,c,p]=e,f=[l,u,d,c].map(Number);if(f.some(e=>!Number.isFinite(e)))return{ok:!1,response:a3("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[m,h,w,g]=f,y=(n=r,a=m,i=h,o=w,s=g,"android"!==n||i!==s||50!==i||30>Math.abs(o-a)?{startY:i,endY:s}:{startY:65,endY:65});return{ok:!0,start:tU(t,m,y.startY,{marginPx:1}),end:tU(t,w,y.endY,{marginPx:1}),durationMs:p}}(a,r,a7(e.baseReq.flags)):{ok:!1,response:a3("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function ij(e){let t=await a5(e);if(t.ok)return G(a6(t.data))}async function iH(e,t,r,n){let a=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(n)]});return a.ok||!r?a:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(n)]})}async function iB(e,t,r){let n=ie(t),a=await iW(e,t,r);return a.response.ok?{retry:!1,response:a.response}:a.targetResolved&&n?await iJ(e,n):{retry:!0,response:a.response}}async function iW(e,t,r){let n=await iX(e,t,r,"tapOn",{promoteTapTarget:!0});return n.ok?await iz(e,t,n.target):{response:n.response,targetResolved:!1}}async function iz(e,t,r){var n;let a=tV(r.rect);eQ({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:a}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(a.x),String(a.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return i.ok&&(n=e.scope)&&a2.delete(n),{response:i,targetResolved:!0}}async function iJ(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(eQ({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?{retry:!1,response:r}:{retry:!0,response:r}}async function iX(e,t,r,n,a){let i=await a5({...e,raw:!0});return function(e,t,r,n,a,i){if(!i.ok)return{ok:!1,response:i};let o=a6(i.data);if(!o)return{ok:!1,response:a3("COMMAND_FAILED",`Unable to read snapshot data for ${n}.`)};let s=G(o),l=a7(e.baseReq.flags),u=function(e,t,r,n){var a;let i=(a=e.scope)?a2.get(a):void 0;if(!i)return;let o=a4(t,i.selector,r,n);if(o.ok)return eQ({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),d=function(e,t,r,n,a,i={}){let o=it(e,t,n);if(r.childOf){let t=it(e,r.childOf,n);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let a=tD(e.nodes);o=o.filter(r=>t.some(t=>tN(e.nodes,r,t,a)))}let s=a9({nodes:e.nodes,matches:o,platform:n}),l=ii(e.nodes,s.matches,r.index,ie(t),a,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}(o,t,r,l,s,{...a,preferredContext:u,requireOnScreen:!0});if(!d.ok){let e=ie(t);if(e){let t=function(e,t,r,n,a={}){let i=function(e,t){let r=tE(t);if(!r)return[];let n=[],a=[];for(let t of e.nodes){let e=[t.label,t_(t),t.identifier,t.value].filter(e=>!!e).map(e=>tE(e));e.some(e=>e===r)?n.push(t):e.some(e=>e.includes(r))&&a.push(t)}return n.length>0?n:a}(e,t),o=a9({nodes:e.nodes,matches:i,platform:r}),s=ii(e.nodes,o.matches,void 0,t,n,!0===a.requireOnScreen,a.promoteTapTarget,a.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...a,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return d.ok?{ok:!0,target:{node:d.node,rect:d.rect,frame:s}}:{ok:!1,response:a3("ELEMENT_NOT_FOUND",d.message,{selector:t,options:r,command:n})}}(e,t,r,n,a,i)}async function iY(e){switch(e.command){case n0:return await ig(e);case n1:return await ix(e);case n2:return await iZ(e);case n3:return await iR(e);case n5:return await iE(e);case n6:return await iV(e);case n8:return await iG(e);case n4:return await iT(e);case n9:return await i$(e);case nQ:return function(e){let[r]=e.positionals;if(!r)return a3("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,a=t.readFileSync(r,"utf8"),i=Object.create(null);try{var s,l;o.runInNewContext(a,(s=n,l=i,{...s,output:l,json:am,http:{post:(e,t)=>(function(e,t,r){let n=tb(process.execPath,["-e",af],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==n.exitCode){let r;throw new d("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=n.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:n.exitCode,stderr:n.stderr})}try{return JSON.parse(n.stdout)}catch(r){throw new d("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:n.stdout.slice(0,1e3),stderr:n.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new d("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new d("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(i,r),Object.fromEntries(Object.entries(i).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=l(t);return a3(e.code,e.message,e.details)}}(e);default:return}}async function iZ(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function iQ(e){for(let[t,r]of e.actions.entries()){let n=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!n.ok)return n}return{ok:!0,data:{ran:e.actions.length}}}async function i0(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let n=await iQ({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(n.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=n}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function i1(e){let t=await i2(e,e.control);return t.ok?t.matched?await i6(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function i2(e,t){if("visible"===t.mode)return await i3(e,t);let r=await i5(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function i3(e,t){let r=Date.now();for(;;){let n=await i5(e,t.selector);if(!n.ok)return{ok:!1,response:n.response};if(n.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await t$(250)}}async function i5(e,t){var r,n;let a,i=await a5(e);return i.ok?(r=e,n=t,(a=a6(i.data))?{ok:!0,matched:a4(a,n,a7(r.baseReq.flags),G(a)).ok}:{ok:!1,response:a3("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function i6(e){let t=await iQ({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function i8(e){let{req:t,sessionName:r,action:n,scope:a,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,d=tv(n,a,{file:i,line:o}),c=Date.now();i7(l,{type:"replay_action_start",ts:new Date(c).toISOString(),replayPath:i,line:o,step:s,command:d.command,positionals:d.positionals??[]});let p=await i4({req:t,sessionName:r,resolved:d,scope:a,line:o,step:s,invoke:u,invokeReplayAction:e=>i8({req:t,sessionName:r,action:e.action,scope:a,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return i7(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:d.command,ok:p.ok,durationMs:f-c,resultTiming:p.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(p.data):void 0,errorCode:p.ok?void 0:p.error.code}),p}async function i4(e){var t;let{req:r,sessionName:n,resolved:a,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,e1(t,{...a.flags??{}})),c={token:r.token,session:n,flags:d,runtime:a.runtime,meta:r.meta,internal:r.internal},p=await i9({control:a.replayControl,baseReq:c,line:o,step:s,invoke:l,invokeReplayAction:u})??await iY({command:a.command,baseReq:c,positionals:a.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...c,command:a.command,positionals:a.positionals??[]});if(p.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(p.data);e&&tA(i,e)}return p}async function i9(e){let{control:t,baseReq:r,line:n,step:a,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await i0({actions:t.actions,maxRetries:t.maxRetries,line:n,step:a,invokeReplayAction:o});case"maestroRunFlowWhen":return await i1({baseReq:r,control:t,line:n,step:a,invoke:i,invokeReplayAction:o})}return t}}function i7(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
30
- `)}async function oe(e){let{req:r,sessionName:n,logPath:i,sessionStore:o,tracePath:s,invoke:u}=e,c=r.positionals?.[0];if(!c)return x("INVALID_ARGS","replay requires a path");let p="",f=new Set;try{var m,h;p=er.expandHome(c,r.meta?.cwd);let e=t.readFileSync(p,"utf8"),l=e.trimStart()[0];if("{"===l||"["===l)return x("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let w=function(e,t,r={}){var n;let a=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=aX[t];if(!r)throw new d("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return a?{...a.parse(e,{...r,platform:t?.platform,env:(n=t,{...ts(e7(n?.replayShellEnv)),...to(tr(n?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...e9(e),metadata:ti(e)}}(e,r.flags,{sourcePath:p}),g=w.metadata,y=g.platform||g.target?{...r,flags:(m=r.flags,h=g,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:r,v=w.actions,A=w.actionLines;if(r.flags?.replayUpdate===!0&&w.updateUnsupportedMessage)return x("INVALID_ARGS",w.updateUnsupportedMessage);if(r.flags?.replayUpdate===!0&&g.env&&Object.keys(g.env).length>0)return x("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(r.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(oa(t.flags)||oa(t.runtime))return!0}return!1}(v))return x("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let b=ty({builtins:function(e){let{req:t,sessionName:r,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:r,AD_FILENAME:a.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let d=o.target??n.target;d&&(l.AD_TARGET=d);let c=o.device;"string"==typeof c&&c.length>0&&(l.AD_DEVICE=c);let p="string"==typeof o.serial?o.serial:o.udid;"string"==typeof p&&p.length>0&&(l.AD_DEVICE_ID=p),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:y,sessionName:n,metadata:g,resolvedPath:p}),fileEnv:g.env,shellEnv:ts(e7(r.flags?.replayShellEnv)),cliEnv:to(tr(r.flags?.replayEnv))}),S=r.flags?.replayUpdate===!0,_=s??o.get(n)?.trace?.outPath,I=0;for(let e=0;e<v.length;e+=1){let t=v[e];if(!t||"replay"===t.command)continue;let r=await i8({req:y,sessionName:n,action:t,scope:b,filePath:p,line:A[e]??0,step:e+1,tracePath:_,invoke:u});if(r.ok){or(r).forEach(e=>f.add(e));continue}if(or(r).forEach(e=>f.add(e)),!S)return ot(r,t,e,p,[...f]);let a=await aZ({action:t,sessionName:n,logPath:i,sessionStore:o});if(!a)return ot(r,t,e,p,[...f]);if(v[e]=a,!(r=await i8({req:y,sessionName:n,action:a,scope:b,filePath:p,line:A[e]??0,step:e+1,tracePath:_,invoke:u})).ok)return or(r).forEach(e=>f.add(e)),ot(r,a,e,p,[...f]);or(r).forEach(e=>f.add(e)),I+=1}return S&&I>0&&tg(p,v,o.get(n)),{ok:!0,data:{replayed:v.length,healed:I,session:n,artifactPaths:[...f]}}}catch(t){let e=l(t);return x(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function ot(e,t,r,n,a=[]){if(e.ok)return e;let i=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${i} (${tO(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:n,step:i,action:t.command,positionals:t.positionals??[],artifactPaths:a}}}}function or(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&on(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,n="string"==typeof r.path?r.path:void 0;e?t.push(e):n&&t.push(n)}return[...new Set(t.filter(e=>on(e)))]}function on(e){try{return t.statSync(e).isFile()}catch{return!1}}function oa(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(oa):!!e&&"object"==typeof e&&Object.values(e).some(oa)}async function oi(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(r);if(!l||l.recording)return;let u=o?a.join(o,"recording.mp4"):`./recording-${Date.now()}.mp4`;os(s,{type:"video_recording_start",session:r,videoPath:u}),eQ({phase:"replay_test_video_recording_start",data:{session:r,videoPath:u}});let d=await tj({req:{token:t.token,session:r,command:"record",positionals:["start",u],flags:{},meta:t.meta},sessionName:r,sessionStore:i,logPath:n});if(!d.ok)return os(s,{type:"video_recording_start_failed",session:r,videoPath:u,errorCode:d.error.code}),d;let c=Date.now();return await t$(1e3),os(s,{type:"video_preroll_done",session:r,durationMs:Date.now()-c,requestedDurationMs:1e3}),eQ({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-c,data:{session:r,requestedDurationMs:1e3}}),d}async function oo(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!a.get(r)?.recording)return;os(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await t$(3e3);let l=Date.now(),u=await tj({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:a,logPath:n});return or(u).forEach(e=>o.add(e)),os(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),eQ({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function os(e,t){aL(e,{...t,ts:new Date().toISOString()})}async function ol(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}=e;return"replay"===t.command?await oe({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}):"test"===t.command?await aj({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:d,tracePath:c,shard:p})=>{let f=function(e){let{platform:t,target:r,artifactsDir:n,shard:a}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===n&&void 0===a)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==n?{artifactsDir:n}:{}};if(!a)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:a.device.platform,target:a.device.target,shardAll:void 0,shardSplit:void 0,shardCount:a.shardCount,shardIndex:a.shardIndex};return"android"===a.device.platform?{...s,serial:a.device.id}:{...s,udid:a.device.id}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u,shard:p}),m={req:t,sessionName:r,logPath:n,sessionStore:a,artifactsDir:u,tracePath:c},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await oi(e)}}(m);return await oe({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:n,sessionStore:a,tracePath:c,invoke:async e=>{var t;let r=await oi(m);return r&&!r.ok?r:(t=await i(e),d&&or(t).forEach(e=>d.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await oo({req:t,sessionName:e,logPath:n,sessionStore:a,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{a.get(e)&&await K({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:n,sessionStore:a})}}):null}async function ou(e){var t,r,n,a,i,o,s,l;let u,d,{req:c,sessionName:p,logPath:f,sessionStore:m}=e,h=c.positionals?.[0]??"";if("ios-runner"!==h)return x("INVALID_ARGS","prepare requires a subcommand: ios-runner");let g=m.get(p),y=c.flags??{},v=S(tB.prepare,g,y);if(v)return v;let A=await w({session:g,flags:y,ensureReady:!0});if(!eE(A.platform))return x("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let b=Date.now(),_=await H(A,(t=c,r=g,n=f,d=(a=t,"number"==typeof(u=a.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:n,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:d,healthTimeoutMs:Math.min(d,9e4)}));return{ok:!0,data:(i=h,o=A,s=Math.max(0,Date.now()-b),l=_,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function od(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=a.get(r),d=t.flags??{},c=S(i,u,d);if(c)return c;let f=await w({session:u,flags:d,ensureReady:!0});if(!eb(i,f))return x("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let m=await p(f,i,o,t.flags?.out,{...ee(n,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,m,f):u;a.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:m??{}}),e!==u&&a.set(r,e)}return{ok:!0,data:m??{}}}async function oc(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,i=a.get(r),o=t.flags??{},s=S(tB.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return x("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await w({session:i,flags:o,ensureReady:!0});if(!eb(tB.clipboard,u))return x("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,tB.clipboard,t.positionals??[],t.flags?.out,{...ee(n,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&a.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function op(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if("inventory"===y(t.command))return await rK({req:t,sessionName:r,sessionStore:a});if("runtime"===t.command)return await t7({req:t,sessionName:r,sessionStore:a});if("state"===y(t.command))return await rz({req:t,sessionName:r,sessionStore:a});if(t.command===tB.clipboard)return await oc({req:t,sessionName:r,logPath:n,sessionStore:a});if(t.command===tB.keyboard){let e=a.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==eV((t.flags??{}).platform)?await od({req:t,sessionName:r,logPath:n,sessionStore:a,command:tB.keyboard,positionals:t.positionals??[]}):x("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===y(t.command))return await nT({req:t,sessionName:r,sessionStore:a,androidAdbExecutor:s});if(t.command===tB.prepare)return await ou({req:t,sessionName:r,logPath:n,sessionStore:a});if(t.command===tB.install||t.command===tB.reinstall)return await rG({req:t,command:t.command,sessionName:r,sessionStore:a,deployOps:t.command===tB.install?rT:rU});if(t.command===tH.installSource)return await t1({req:t,sessionName:r,sessionStore:a});if(t.command===tH.releaseMaterializedPaths)return await t2({req:t});if(t.command===tB.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await od({req:t,sessionName:r,logPath:n,sessionStore:a,command:tB.push,positionals:[i,"file"===(e=es(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>er.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):x("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===tB.triggerAppEvent?await od({req:t,sessionName:r,logPath:n,sessionStore:a,command:tB.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,n=r?await rk(e.device,r,e.appBundleId,rN)??e.appBundleId:e.appBundleId;return{...e,appBundleId:n}}}):t.command===tB.open?await rV({req:t,sessionName:r,logPath:n,sessionStore:a}):"replay"===y(t.command)?await ol({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o??i}):t.command===tB.batch?await rq(t,r,i):t.command===tB.close?await K({req:t,sessionName:r,logPath:n,sessionStore:a}):null}export{tY as session_namespaceObject};
22
+ `;function nd(e){if("string"!=typeof e)throw new s("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new s("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,nc)}catch(t){throw new s("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function nc(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let nf={launchApp:({value:e,config:t,context:r})=>[aK(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return t$(a5,[nt(tG(e,t))],ni(e));if(tV(e)&&"string"==typeof e.point){tF(e,"tapOn",["point","repeat","delay","optional","label"]);let t=tT(e.point);return"percent"===t.kind?t$(a6,[String(t.x),String(t.y)],nn(e)):t$("click",[String(t.x),String(t.y)],nn(e))}tV(e)&&tF(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=ni(e);return t$(a5,[ne(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!tV(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new s("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=ne(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(tV(e)&&"string"==typeof e.point){tF(e,"doubleTapOn",["point","delay"]);let t=tL(e.point);return t$("click",[String(t.x),String(t.y)],no(e))}return tV(e)&&tF(e,"doubleTapOn",["id","text","enabled","selected","delay"]),t$("click",[ne(e,"doubleTapOn",["delay"],t)],no(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(tV(e)&&"string"==typeof e.point){tF(e,"longPressOn",["point"]);let t=tL(e.point);return t$("longpress",[String(t.x),String(t.y),"3000"])}return tV(e)&&tF(e,"longPressOn",["id","text","enabled","selected"]),t$("click",[ne(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[t$("type",[tG(function(e){if("string"==typeof e)return e;if(!tV(e))throw new s("INVALID_ARGS","inputText expects a string or map.");if(tF(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new s("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[a8(e)],pasteText:({value:e,context:t,name:r})=>[t$("type",[tG(tq(r,e),t)])],openLink:({value:e,config:t,context:r,name:a})=>{var n,i,o,s,l,u;let p;return[(n=e,i=t,o=r,s=a,p=tG((l=n,u=s,"string"==typeof l?l:tV(l)?(tF(l,u,["link"]),tq(`${u}.link`,l.link)):tq(u,l)),o),("ios"===o.platform||"android"===o.platform)&&i.appId?t$("open",[tG(tU(i,s),o),p],"ios"===o.platform?{maestro:{prewarmRunnerBeforeOpen:!0}}:void 0):t$("open",[p]))]},assertVisible:({value:e,context:t,name:r})=>[t$(aX,[ne(e,r,[],t),"17000"])],assertNotVisible:({value:e,context:t,name:r})=>[t$(aZ,[ne(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!tV(e))throw new s("INVALID_ARGS","extendedWaitUntil expects a map.");tF(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw tB("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let a=ne(r,"extendedWaitUntil",[],t),n=String(tH(e,17e3));return void 0!==e.notVisible?[t$(aZ,[a,n])]:[t$(aX,[a,n],{maestro:{allowAlreadyPastLoading:!0}})]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[t$("screenshot",[tG(tq(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw tB("Maestro scroll options are not supported yet.");return t$("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[t$(a1,[nt(tG(e,t)),"5000","down"])];if(!tV(e))throw new s("INVALID_ARGS","scrollUntilVisible expects a string or map.");tF(e,"scrollUntilVisible",["element","direction","timeout"]);let r=ne(e.element,"scrollUntilVisible.element",[],t),a="string"==typeof e.direction?a7(e.direction,"scrollUntilVisible.direction"):"down";return[t$(a1,[r,String(tH(e,5e3)),a])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,a,n;let i;if(!tV(e))throw new s("INVALID_ARGS","swipe expects a map.");tF(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,a=o,n=t,i=a9("string"==typeof r.direction?r.direction:"up"),t$(a3,[ne(a,"swipe.from",[],n),i,...nr(r)])):"string"==typeof e.direction?t$(a2,["direction",a9(e.direction),...nr(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:tT(e.start),end:tT(e.end)};throw tB("Only Maestro swipe start/end coordinates are supported.")}(e);var a=t,n=r,i=a4(e.duration);if("absolute"===a.kind&&"absolute"===n.kind)return t$("swipe",[String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);if("percent"===a.kind&&"percent"===n.kind)return t$(a2,["percent",String(a.x),String(a.y),String(n.x),String(n.y),...i?[i]:[]]);throw tB("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[t$("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=tq("pressKey",e).toLowerCase();if("back"===t)return t$("back");if("enter"===t||"return"===t)return t$(aQ);if("home"===t)return t$("home");throw tB(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[t$("back")],waitForAnimationToEnd:({value:e})=>[t$(a0,[String(tH(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[aj(e,t,r)],runScript:({value:e,context:t})=>{let a;return[t$(aY,[function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runScript file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}((a=function(e,t){if("string"==typeof e)return{file:tG(e,t),env:{}};if(!tV(e))throw new s("INVALID_ARGS","runScript expects a file path string or map.");return tF(e,"runScript",["file","env"]),{file:tG(tq("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(tk(e.env,"runScript.env")).map(([e,r])=>[e,tG(r,t)]))}}(e,t)).file,t)],{...Object.keys(a.env).length>0?{maestro:{runScriptEnv:a.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){if("string"==typeof e)return a.parseRunFlowFile(tG(e,r),r).actions;if(!tV(e))throw new s("INVALID_ARGS","runFlow expects a file path string or map.");tF(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,a;if(null==e)return{shouldRun:!0};if(!tV(e))throw new s("INVALID_ARGS","runFlow.when expects a map.");return(tF(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new s("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new ns(function(e){let t=[],r=0;for(;r<e.length;){var a,n;let i=e.slice(r),o=(a=i,/^\s+/.exec(a)?.[0].length??0);if(o>0){r+=o;continue}let l=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(n=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(n)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(n)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(n)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(n);if(l){t.push(l.token),r+=l.length;continue}throw new s("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=tG(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new s("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new s("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,a=t,{...void 0!==r.visible?{visibleSelector:ne(r.visible,"runFlow.when.visible",[],a)}:{},...void 0!==r.notVisible?{notVisibleSelector:ne(r.notVisible,"runFlow.when.notVisible",[],a)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...tk(e.env,"runFlow.env"),...r.envOverrides}};return function(e,t){let{visibleSelector:r,notVisibleSelector:a}=t;if(!r&&!a)return e;if(r&&a)throw tB("Maestro runFlow.when cannot combine visible and notVisible yet.");let n=r?"visible":"notVisible",i=r??a??"";return[nl("runFlow.when",[n,i],{kind:"maestroRunFlowWhen",mode:n,selector:i,actions:e})]}(function(e,t,r,a,n){if("string"==typeof e.file)return a.parseRunFlowFile(tG(e.file,r),r).actions;if(Array.isArray(e.commands))return n(tx(e.commands),t,r,a);throw new s("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,a,n),i)})(e,t,r,a,ng),repeat:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i;if(!tV(e))throw new s("INVALID_ARGS","repeat expects a map.");if(tF(e,"repeat",["times","commands","while"]),void 0!==e.while)throw tB("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,nu(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new s("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new s("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let l=tx(e.commands);return Array.from({length:o}).flatMap(()=>n(l,t,r,a))})(e,t,r,a,ng),retry:({value:e,config:t,context:r,deps:a})=>(function(e,t,r,a,n){var i,o;if(!tV(e))throw new s("INVALID_ARGS","retry expects a map.");if(tF(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new s("INVALID_ARGS","retry requires a commands list.");let l=(i=e.maxRetries,o=r,void 0===i?1:nu(i,o,"retry.maxRetries")),u=n(tx(e.commands),t,r,a);return[nl("retry",[String(l)],{kind:"retry",maxRetries:l,actions:u})]})(e,t,r,a,ng)},nm={launchApp:(e,t)=>[aK(void 0,e,t)],scroll:()=>[t$("scroll",["down"])],hideKeyboard:()=>[t$("keyboard",["dismiss"])],eraseText:()=>[a8(void 0)],back:()=>[t$("back")],waitForAnimationToEnd:()=>[t$(a0,["15000"])],stopApp:(e,t)=>[aj(void 0,e,t)]};function nh(e,t,r,a,n){try{return function(e,t,r,a){if("string"==typeof e){var n,i,o;let a;return n=e,i=t,o=r,(a=nm[n])?a(i,o):t_(n)}let l=Object.entries(e);if(1!==l.length)throw new s("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[u,p]=l[0],d=nf[u];return d?d({value:p,config:t,context:r,deps:a,name:u}):t_(u)}(e,t,a,n)}catch(e){if(e instanceof s&&!/\bline \d+\b/.test(e.message))throw new s(e.code,`${e.message} (line ${r})`,e.details);throw e}}function ng(e,t,r,a){return e.flatMap((e,n)=>nh(e,t,n+1,r,a))}function nw(e,t){let{config:r,commands:a}=ny(tP(e)),n={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:a,context:n}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...a,...Array.from({length:t.onFlowComplete?.length??0},()=>a.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let a=o[e]??e+1,i=nh(r,t,a,n,{parseRunFlowFile:nv});s.push(...i),i.forEach(()=>l.push(a))}return function(e,t){let r=[],a=[];for(let n=0;n<e.length;n+=1){let i=e[n],o=function(e,t,r){var a;let n=function(e,t,r){let a=e[r],n=e[r+1],i=e[r+2];if(i?.command!==aQ||a.flags?.maestro?.optional===!0)return null;let o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(n),s=function(e){if(e?.command!==a5)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);return n&&null!==o&&null!==s?{action:a,nextAction:n,pressEnterAction:i,tapSelector:s,typedAfterTap:o,line:t[r]??1}:null}(e,t,r);if(!n)return null;let{action:i,nextAction:o,pressEnterAction:s,tapSelector:l,typedAfterTap:u,line:p}=n;return(a=l,/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(a.replace(/([a-z])([A-Z])/g,"$1 $2")))?{actions:[{...i,command:"wait",positionals:[l,"30000"]},{...o,command:"fill",positionals:[l,u],flags:i.flags},s],actionLines:[p,p,t[r+2]??p],consumed:3}:{actions:[function(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}(i)],actionLines:[p],consumed:1}}(e,t,n);if(o){r.push(...o.actions),a.push(...o.actionLines),n+=o.consumed-1;continue}r.push(i),a.push(t[n]??1)}return{actions:r,actionLines:a}}(s,l)}({config:r,commands:a,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),a=-1===r?0:r+1,n=[];for(let e=a;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&n.push(e+1);return n}(e),context:n});return{actions:i,actionLines:o,metadata:{env:r.env}}}function ny(e){if(0===e.length)throw new s("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:tx(e[0])};let t=function(e){if(!tV(e))throw new s("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.name&&e.name.length>0?{name:e.name}:{},..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...tV(e.env)?{env:tk(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:tx(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:tx(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new s("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:tx(r)}}function nv(e,a){let n=function(e,t){if(r.isAbsolute(e))return e;if(!t.baseDir)throw new s("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return r.resolve(t.baseDir,e)}(e,a);if(a.visitedPaths.has(n))throw new s("INVALID_ARGS",`Maestro runFlow cycle detected at ${n}.`);let i=t.readFileSync(n,"utf8"),o=new Set(a.visitedPaths);return o.add(n),nw(i,{...a,baseDir:r.dirname(n),visitedPaths:o})}let nA=/[*?[\]{}]/;function nI(e,t,a,n,i=0){let o=r.basename(a,r.extname(a)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${o?`-${o}`:""}:attempt-${i+1}`}function nS(e,t){return"number"==typeof e?e:t}function nb(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}function n_(e){return"maestro"===e}let nk=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function nN(e){var t,r,a,n;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(i="string"==typeof r?.reason?r.reason:"")||!!i&&tc(i)||(a=s.code,n=s.message,o=`${a}
23
+ ${n}`.toLowerCase(),nk.some(e=>o.includes(e))))}async function nD(e){let a,n,{filePath:i,sessionName:s,requestId:l,parentRequestId:u,timeoutMs:p,platform:d,target:c,artifactsDir:f,shard:m,runReplay:h,cleanupSession:g,finalizeAttempt:w}=e;O(l);let y=function(e,t){if(!t||t===e)return()=>{};let r=eq(t);if(!r)return()=>{};let a=()=>{eN(e)};return r.aborted?(a(),()=>{}):(r.addEventListener("abort",a,{once:!0}),()=>{r.removeEventListener("abort",a)})}(l,u),v=new Set,A=!1,I=Date.now(),S=function(e){let{artifactsDir:a,artifactPaths:n,filePath:i,sessionName:o,requestId:s,timeoutMs:l,platform:u,target:p}=e;if(!a)return;let d=r.join(a,"replay-timing.ndjson");return t.mkdirSync(r.dirname(d),{recursive:!0}),t.writeFileSync(d,""),n.add(d),nP(d,{type:"replay_test_attempt_start",ts:new Date().toISOString(),replayPath:i,session:o,requestId:s,timeoutMs:l,platform:u,target:p}),d}({artifactsDir:f,artifactPaths:v,filePath:i,sessionName:s,requestId:l,timeoutMs:p,platform:d,target:c}),b=h({filePath:i,sessionName:s,platform:d,target:c,requestId:l,artifactsDir:f,artifactPaths:v,tracePath:S,shard:m}).catch(e=>({ok:!1,error:o(e)})).finally(()=>{y(),eO(l)});try{n="number"==typeof p?await Promise.race([b,new Promise(e=>{a=setTimeout(()=>{A=!0,eN(l),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(p,[...v]))},p)})]):await b,nP(S,{type:"replay_test_attempt_stop",ts:new Date().toISOString(),session:s,ok:n.ok,timedOut:A,durationMs:Date.now()-I,errorCode:n.ok?void 0:n.error.code})}finally{var _,k,N;let e,t;a&&clearTimeout(a),A&&(await nx(b)||((_=n)&&!_.ok&&(_.error.details={..._.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),tv({level:"warn",phase:"test_timeout_cleanup_race",data:{session:s,requestId:l,graceMs:2e3}}),nR({replayPromise:b,cleanupSession:g,sessionName:s,requestId:l})));let r=await nM({finalizeAttempt:w,sessionName:s,artifactPaths:v,artifactsDir:f,tracePath:S});n?.ok&&r&&!r.ok&&(k=n,N=`Replay test finalization failed: ${r.error.message}`,t=Array.isArray((e=k.data??={}).warnings)?e.warnings.filter(e=>"string"==typeof e):[],e.warnings=[...t,N]);let i=Date.now();try{nP(S,{type:"replay_test_cleanup_start",ts:new Date().toISOString(),session:s}),await g(s),nP(S,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!0,durationMs:Date.now()-i})}catch(t){let e=o(t);nP(S,{type:"replay_test_cleanup_stop",ts:new Date().toISOString(),session:s,ok:!1,durationMs:Date.now()-i,errorCode:e.code}),tv({level:"warn",phase:"test_cleanup_failed",data:{session:s,error:e.message}})}}return n??{ok:!1,error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"}}}async function nx(e){return await Promise.race([e.then(()=>!0),n(2e3).then(()=>!1)])}async function nR(e){let{replayPromise:t,cleanupSession:r,sessionName:a,requestId:n}=e;try{await t}finally{try{await r(a)}catch(e){tv({level:"warn",phase:"test_late_cleanup_failed",data:{session:a,requestId:n,error:o(e).message}})}}}async function nM(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i}=e;if(!t)return;let s=Date.now();nP(i,{type:"replay_test_finalize_start",ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:a,artifactsDir:n,tracePath:i});return nP(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let e=o(t);return nP(i,{type:"replay_test_finalize_stop",ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:e.code}),tv({level:"warn",phase:"test_finalize_failed",data:{session:r,error:e.message}}),{ok:!1,error:e}}}function nP(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
24
+ `)}async function nL(e){var t,a,n;let i,o=function(e){var t;let a,{entry:n,cwd:i,retries:o,suiteArtifactsDir:s,shard:l}=e;return{testStartedAt:Date.now(),testArtifactsDir:r.join(s,...l?[`shard-${l.shardIndex+1}`]:[],(t=n.path,(0===(a=i?r.relative(i,t):r.basename(t)).length||a.startsWith("..")?r.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),maxAttempts:o+1}}(e),s=await nO(e,o);return t=e,a=o,n=s,i=Date.now()-a.testStartedAt,n.finalResponse?.ok?function(e,t,r,a){let{entry:n,suiteIndex:i,suiteTotal:o,shard:s}=e,l=r.finalResponse;if(!l?.ok)throw Error("Expected passing replay test response.");return eH({type:"replay-test",file:n.path,title:n.title,status:"pass",index:i,total:o,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,...nC(s)}),{file:n.path,title:n.title,session:r.finalSessionName,status:"passed",durationMs:a,finalAttemptDurationMs:r.finalAttemptDurationMs,attempts:r.attempts,artifactsDir:t.testArtifactsDir,replayed:"number"==typeof l.data?.replayed?l.data.replayed:0,healed:"number"==typeof l.data?.healed?l.data.healed:0,...function(e){if(!Array.isArray(e))return{};let t=e.filter(e=>"string"==typeof e);return t.length>0?{warnings:t}:{}}(l.data?.warnings),...function(e){return nC(e)}(s),...r.attemptFailures.length>0?{attemptFailures:r.attemptFailures}:{}}}(t,a,n,i):function(e,t,r,a){var n;let{entry:i,suiteIndex:o,suiteTotal:s,shard:l}=e,u=(n=r.finalResponse)&&!n.ok?n.error:{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return eH({type:"replay-test",file:i.path,title:i.title,status:"fail",index:o,total:s,attempt:r.attempts,maxAttempts:t.maxAttempts,durationMs:a,session:r.finalSessionName,artifactsDir:t.testArtifactsDir,message:u.message,...nC(l)}),{file:i.path,title:i.title,session:r.finalSessionName,status:"failed",durationMs:a,attempts:r.attempts,artifactsDir:t.testArtifactsDir,error:u,...function(e){return nC(e)}(l)}}(t,a,n,i)}async function nO(e,t){!function(e,t){let{entry:r,sessionName:a,suiteInvocationId:n,caseIndex:i,suiteIndex:o,suiteTotal:s,shard:l}=e;eH({type:"replay-test",file:r.path,title:r.title,status:"start",index:o,total:s,maxAttempts:t.maxAttempts,session:nI(a,n,r.path,i),artifactsDir:t.testArtifactsDir,...nC(l)})}(e,t);let r={finalSessionName:"",attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let d=0;d<=e.retries&&!ey(e.requestId);d+=1){var a,n,i,o,s,l,u,p;let c=await nE(e,t,d);if((a=r).finalResponse=(n=c).response,a.finalSessionName=n.sessionName,a.attempts=n.attempt,a.finalAttemptDurationMs=n.durationMs,n.response.ok||a.attemptFailures.push({attempt:n.attempt,message:n.response.error.message,durationMs:n.durationMs}),i=e,o=c.response,s=d,o.ok||ey(i.requestId)||nN(o)||s>=i.retries)break;l=e,u=t,(p=c).response.ok||eH({type:"replay-test",file:l.entry.path,title:l.entry.title,status:"fail",index:l.suiteIndex,total:l.suiteTotal,attempt:p.attempt,maxAttempts:u.maxAttempts,durationMs:p.durationMs,retrying:!0,message:p.response.error.message,session:p.sessionName,artifactsDir:u.testArtifactsDir,...nC(l.shard)})}return r}async function nE(e,a,n){var i;let{entry:o,sessionName:s,suiteInvocationId:l,caseIndex:u,requestId:p,timeoutMs:d,shard:c}=e,f=n+1,m=Date.now(),h=nI(s,l,o.path,u,n),g=r.join(a.testArtifactsDir,`attempt-${f}`);i=o.path,t.mkdirSync(g,{recursive:!0}),function(e,a){var n;let i,o=r.join(a,"replay.ad");if(t.copyFileSync(e,o),n=e,".yml"!==(i=r.extname(n).toLowerCase())&&".yaml"!==i)return;let s=r.join(a,r.basename(e));r.resolve(s)!==r.resolve(o)&&t.copyFileSync(e,s)}(i,g);let w=function(e){let{requestId:t,suiteInvocationId:a,filePath:n,caseIndex:i,attemptIndex:o,shardIndex:s}=e,l=void 0===s?"":`:shard:${s+1}`;return ev(`${t??a}${l}:test:${i+1}:${r.basename(n)}:attempt:${o+1}`,a)}({requestId:p,suiteInvocationId:l,filePath:o.path,caseIndex:u,attemptIndex:n,shardIndex:c?.shardIndex}),y=await nD({filePath:o.path,sessionName:h,requestId:w,parentRequestId:p,timeoutMs:d,platform:o.metadata.platform,target:o.metadata.target,artifactsDir:g,shard:c,runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-m;return!function(e){var a;let n,{response:i,filePath:o,sessionName:s,attempts:l,maxAttempts:u,attemptArtifactsDir:p}=e,d=[...Array.isArray(n=(a=i).ok?a.data?.artifactPaths:a.error.details?.artifactPaths)?[...new Set(n.filter(e=>"string"==typeof e))]:[]];i.ok||"string"!=typeof i.error.logPath||d.push(i.error.logPath);let c=function(e,a){let n=[],i=new Map;for(let o of e){if(!function(e){try{return t.statSync(e).isFile()}catch{return!1}}(o))continue;let e=function(e,t){let a=r.extname(e),n=a?e.slice(0,-a.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${a}`}(r.basename(o),i),s=r.join(a,e);r.resolve(o)!==r.resolve(s)&&t.copyFileSync(o,s),n.push(s)}return n}(d,p),f=[`file: ${o}`,`session: ${s}`,`attempt: ${l}/${u}`,`status: ${i.ok?"passed":"failed"}`];if(i.ok){let e="number"==typeof i.data?.replayed?i.data.replayed:0,t="number"==typeof i.data?.healed?i.data.healed:0;f.push(`replayed: ${e}`,`healed: ${t}`)}else f.push(`code: ${i.error.code}`,`message: ${i.error.message}`),i.error.hint&&f.push(`hint: ${i.error.hint}`),i.error.diagnosticId&&f.push(`diagnosticId: ${i.error.diagnosticId}`),i.error.logPath&&f.push(`logPath: ${i.error.logPath}`),i.error.details?.reason==="timeout"&&f.push("timeoutMode: cooperative");c.length>0&&f.push(`copiedArtifacts: ${c.map(e=>r.basename(e)).join(", ")}`);let m=r.join(p,"result.txt"),h=`${f.join("\n")}
25
+ `;t.writeFileSync(m,h),i.ok||t.writeFileSync(r.join(p,"failure.txt"),h)}({response:y,filePath:o.path,sessionName:h,attempts:f,maxAttempts:a.maxAttempts,attemptArtifactsDir:g}),{response:y,sessionName:h,attempt:f,durationMs:v}}function nC(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id}:{}}async function n$(e,t,r){let a=function(e){let t=nV(e?.shardAll,"--shard-all"),r=nV(e?.shardSplit,"--shard-split");if(void 0!==t&&void 0!==r)throw new s("INVALID_ARGS","--shard-all and --shard-split are mutually exclusive");return void 0!==t?{kind:"all",count:t}:void 0!==r?{kind:"split",count:r}:void 0}(e);if(!a||0===t.length)return;let n=await nU(e,a.count);return{mode:a.kind,shardCount:a.count,total:r+("all"===a.kind?t.length*a.count:t.length),shards:n.map((e,r)=>({shardIndex:r,shardCount:a.count,device:e,entries:"all"===a.kind?t:t.filter((e,t)=>t%a.count===r)}))}}function nV(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<1)throw new s("INVALID_ARGS",`${t} requires a positive integer`);return e}}async function nU(e,t){var r,a,n,i,o,l,u,p,d;let c,f,m=(r=e,"string"!=typeof(c=r?.device)||0===c.trim().length?[]:c.split(",").map(e=>e.trim()).filter(Boolean)),h=(n=await ef((a=e,f=tm(a?.androidDeviceAllowlist),{platform:a?.platform,target:a?.target,iosSimulatorSetPath:ti({simulatorSetPath:tu(a?.iosSimulatorDeviceSet),platform:a?.platform,target:a?.target}),androidSerialAllowlist:f?Array.from(f).sort():void 0})),i=m,o=e,i.length>0?(l=n,u=i,p=o,u.map(e=>{let t=nG(e),r=l.find(r=>nF(r,p)&&(r.id===e||nG(r.name)===t));if(!r)throw new s("DEVICE_NOT_FOUND",`No shard device matched ${e}`);return r})):n.filter(e=>{var t;return!!nF(t=e,o)&&("ios"===t.platform||"android"===t.platform)&&!1!==t.booted}).sort(nq));if(h.length<t){throw new s("DEVICE_NOT_FOUND",`test sharding requires ${(d=t,`${d} device${1===d?"":"s"}`)}, but only ${h.length} matched`)}return h.slice(0,t)}function nF(e,t){return!(!tl(e.platform,t?.platform)||t?.target&&(e.target??"mobile")!==t.target)}function nG(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function nq(e,t){return e.id.localeCompare(t.id)}async function nT(e){let{req:t,sessionName:r,runReplay:a,cleanupSession:n,finalizeAttempt:o}=e;if((t.positionals?.length??0)===0)return E("INVALID_ARGS","test requires at least one path or glob");try{var s,l,u,p;let e,i,d,c,f,m=Date.now(),h=await nB(t);s=h,eH({type:"replay-test-suite",status:"start",total:s.total,runnable:s.runnable.length,skipped:s.entries.length-s.runnable.length,artifactsDir:s.suiteArtifactsDir,shardMode:s.shardPlan?.mode,shardCount:s.shardPlan?.shardCount});let g=h.shardPlan?function(e){let{entries:t,total:r}=e,a=[];for(let[e,n]of t.entries())"skip"===n.kind&&(eH({type:"replay-test",file:n.path,status:"skip",index:e+1,total:r,message:n.message}),a.push({file:n.path,status:"skipped",durationMs:0,reason:n.reason,message:n.message}));return a}({entries:h.entries,total:h.total}):[];h.shardPlan?g.push(...await nH({shards:h.shardPlan.shards,sessionName:r,suiteInvocationId:h.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:h.suiteArtifactsDir,suiteTotal:h.total,runReplay:a,cleanupSession:n,finalizeAttempt:o})):g.push(...await nz({discoveryEntries:h.entries,sessionName:r,suiteInvocationId:h.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:h.suiteArtifactsDir,suiteTotal:h.total,runReplay:a,cleanupSession:n,finalizeAttempt:o}));let w=(l=h.total,u=g,p=Date.now()-m,e=u.filter(e=>"passed"===e.status).length,d=(i=u.filter(e=>"failed"===e.status)).length,c=u.filter(e=>"skipped"===e.status).length,f=e+d,{total:l,executed:f,passed:e,failed:d,skipped:c,notRun:Math.max(0,l-f-c),durationMs:p,failures:i,tests:u});return{ok:!0,data:w}}catch(t){let e=i(t);return E(e.code,e.message)}}async function nB(e){var a,n,i,o;let l=function(e){let{inputs:a,cwd:n,platformFilter:i,replayBackend:o}=e,l=new Set(n_(o)?[".ad",".yaml",".yml"]:[".ad"]),u=n??process.cwd(),p=[...new Set(a.flatMap(e=>(function(e,a,n){var i,o;let l=em.expandHome(e,a);if(t.existsSync(l)){let a=t.statSync(l);if(a.isDirectory())return[...n].map(e=>`**/*${e}`).flatMap(e=>t.globSync(e,{cwd:l}).map(e=>r.join(l,e)));if(a.isFile()){if(!n.has(r.extname(l)))throw new s("INVALID_ARGS",`test does not support this file type: ${e}`);return[l]}return[]}if(i=e,!nA.test(i)&&(o=l,!nA.test(o)))throw new s("INVALID_ARGS",`test input not found: ${e}`);let u=r.isAbsolute(l)?l:e;return t.globSync(u,{cwd:r.isAbsolute(l)?void 0:a}).map(e=>r.isAbsolute(e)?e:r.resolve(a,e)).filter(e=>n.has(r.extname(e))&&function(e){try{return t.statSync(e).isFile()}catch{return!1}}(e))})(e,u,l)))].map(e=>r.normalize(e)).sort((e,t)=>e.localeCompare(t)),d=[];for(let e of p){var c,f,m,h;let a=t.readFileSync(e,"utf8"),n=tO(a),s=(c=a,f=e,n_(o)&&".ad"!==r.extname(f)?function(e){let{config:t}=ny(tP(e));return t.name}(c):void 0);if(!i){d.push({kind:"run",path:e,title:s,metadata:n});continue}if(!n.platform){n_(o)?d.push({kind:"run",path:e,title:s,metadata:n}):d.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${i}`});continue}m=i,h=n.platform,("apple"===m?"apple"===h||"ios"===h||"macos"===h:h===m)&&d.push({kind:"run",path:e,title:s,metadata:n})}if(0===d.filter(e=>"run"===e.kind).length){let e=i?` for --platform ${i}`:"";throw new s("INVALID_ARGS",`No replay tests matched${e}.`)}return d}({inputs:(n=e).positionals??[],cwd:n.meta?.cwd,platformFilter:n.flags?.platform,replayBackend:n.flags?.replayBackend}),u=l.flatMap((e,t)=>"run"===e.kind?[{entry:e,suiteIndex:t+1}]:[]),p=l.length-u.length,d=(a=e.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),c=await n$(e.flags,u,p);return{entries:l,runnable:u,shardPlan:c,suiteInvocationId:d,suiteArtifactsDir:(i=e,o=d,function(e){let{artifactsDir:t,cwd:a,suiteInvocationId:n}=e,i=em.expandHome(t??".agent-device/test-artifacts",a);return r.join(i,n)}({artifactsDir:"string"==typeof i.flags?.artifactsDir?i.flags.artifactsDir:void 0,cwd:i.meta?.cwd,suiteInvocationId:o})),total:c?.total??l.length}}async function nH(e){return(await Promise.allSettled(e.shards.map(async t=>await nK({...e,shard:t})))).flatMap((t,r)=>{var a,n;let i;if("fulfilled"===t.status)return t.value;let s=e.shards[r];return s?[(a=s,n=e.sessionName,i=o(t.reason),{file:a.entries[0]?.entry.path??`shard-${a.shardIndex+1}`,session:nj(n,a),status:"failed",durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:a.shardIndex,shardCount:a.shardCount,deviceId:a.device.id})]:[]})}async function nK(e){let{shard:t,sessionName:r}=e;return await nW({...e,entries:t.entries,sessionName:nj(r,t),shard:t})}function nj(e,t){return`${e}:shard-${t.shardIndex+1}`}async function nz(e){let{discoveryEntries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d}=e,c=[],f=0;for(let[e,m]of t.entries()){if(ey(i))break;if("skip"===m.kind){eH({type:"replay-test",file:m.path,status:"skip",index:e+1,total:l,message:m.message}),c.push({file:m.path,status:"skipped",durationMs:0,reason:m.reason,message:m.message});continue}f+=1;let t=await nL({entry:m,sessionName:r,suiteInvocationId:a,caseIndex:f-1,cwd:n,requestId:i,retries:nb(o?.retries,m.metadata.retries),timeoutMs:nS(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:l,runReplay:u,cleanupSession:p,finalizeAttempt:d});if(c.push(t),nJ(t,o,i))break}return c}async function nW(e){let{entries:t,sessionName:r,suiteInvocationId:a,cwd:n,requestId:i,flags:o,suiteArtifactsDir:s,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c}=e,f=[];for(let[e,m]of t.entries()){if(ey(i))break;let{entry:t,suiteIndex:h}=m,g=await nL({entry:t,sessionName:r,suiteInvocationId:a,caseIndex:e,cwd:n,requestId:i,retries:nb(o?.retries,t.metadata.retries),timeoutMs:nS(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:l,shard:u,runReplay:p,cleanupSession:d,finalizeAttempt:c});if(f.push(g),nJ(g,o,i))break}return f}function nJ(e,t,r){return ey(r)||t?.failFast===!0||nN(e)}let nY={maestro:{parse:function(e,t={}){var a;let n;return nw(e,(n=(a=t).visitedPaths??new Set,a.sourcePath&&n.add(r.resolve(a.sourcePath)),{baseDir:a.sourcePath?r.dirname(a.sourcePath):void 0,platform:tR(a.platform),env:{},envOverrides:a.env??{},visitedPaths:n}))}}};function nX(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,a=tY(null!==r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r}}async function nZ(e){let{action:t,sessionName:r,logPath:a,sessionStore:n}=e;if(!(re(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=n.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),re(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&nQ(r)?t.slice(0,-1):t}(e),a=r[0]??"";a&&!a.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=t2(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=nX(e.positionals??[]);r&&t.push(r)}return B(t).filter(e=>e.trim().length>0)})(t).map(e=>t1(e)).filter(e=>null!==e);if(0===o.length)return null;let s=re(t.command)||"fill"===t.command,l=re(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await n0(i,t,a,s,n);for(let e of o){let r=t3(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let a=t5(r.node,i.device.platform,{action:"fill"===t.command?"fill":re(t.command)?"click":"get"}).join(" || ");if(re(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&nQ(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,a):[a]};if("fill"===t.command){let e=v(t);if(!e)continue;return{...t,positionals:[a,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,a]}}if("is"===t.command){let{predicate:e,split:r}=t2(t.positionals);if(!e)continue;let n=r?.rest.join(" ").trim()??"",i=[e,a];return"text"===e&&n.length>0&&i.push(n),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=nX(t.positionals??[]),r=[a];return e&&r.push(e),{...t,positionals:r}}}return null}function nQ(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function n0(e,t,r,a,n){let i=eu(await p(e.device,"snapshot",[],t.flags?.out,{...ec(r,{...t.flags??{},snapshotInteractiveOnly:a},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:a});return H(e,i),n.set(e.name,e),i}let n1=new WeakMap,n2=new WeakMap;function n3(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function n5(e){var t;let r,a=!0===e.raw||"1"===process.env.AGENT_DEVICE_MAESTRO_RAW_SNAPSHOTS,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,...a?{snapshotRaw:!0}:{}}});return n.ok&&e.scope&&(t=e.scope,(r=Q(n6(n.data)))&&n1.set(t,r)),n}function n6(e){return Array.isArray(e?.nodes)?e:void 0}let n8=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function n4(e,t,r,a){let n=it(e,t,r,{allowLeadingCompositeLabelMatch:!1}),i=n7({nodes:e.nodes,matches:n,platform:r}),o=ii(e.nodes,i.matches,void 0,ie(t),a,!0);return o?{ok:!0,node:o.node,rect:o.rect,matches:i.matches.length}:{ok:!1,message:i.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:n.length>0?`Maestro selector matched ${n.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function n7(e){let t=e.matches.filter(t=>t9({predicate:"visible",node:t,nodes:e.nodes,platform:e.platform}).pass),r=function(e,t,r){let a=tr(e);if(!a.detected||!a.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=tt(a),i=n.filter(t=>t9({predicate:"visible",node:t,nodes:e,platform:r}).pass);if(0===i.length)return 0===n.length?{matches:[],blockedByReactNativeOverlay:!0}:{matches:t,blockedByReactNativeOverlay:!1};let o=new Set(i.map(e=>e.index)),s=t.filter(e=>o.has(e.index));return{matches:s,blockedByReactNativeOverlay:t.length>0&&0===s.length}}(e.nodes,t,e.platform);return{matches:r.matches,blockedByReactNativeOverlay:r.blockedByReactNativeOverlay}}function n9(e){return e?.platform==="android"?"android":"ios"}function ie(e){let t=t0(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),a=r[0];return a&&r.every(e=>e===a)?a:null}function it(e,t,r,a={}){for(let n of t0(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r,a){return!!t8(e,t,r)||t.terms.every(t=>(function(e,t,r,a){var n,i,o;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?t8(e,{raw:t.key,terms:[t]},r):ir((i=e,"id"===(o=t.key)?i.identifier:"label"===o?i.label:"value"===o?i.value:tX(i)),t.value,a)})(e,t,r,a))})(e,n,r,a));if(t.length>0)return t}return[]}function ir(e,t,r={}){var a;let n=e??"",i=rt(n),o=rt(t);if(i===o||!1!==r.allowLeadingCompositeLabelMatch&&function(e,t){if(!e||!t||!e.startsWith(t))return!1;let r=e.at(t.length);return","===r||":"===r||";"===r}(i,o))return!0;if(a=t,!/(?:\.\*|\.\+|\[[^\]]+\]|\([^)]*\)|\||\^|\$|\\[dDsSwWbB])/.test(a))return!1;try{return new RegExp(t).test(n)}catch{return!1}}function ia(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let a=function(e,t,r){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);)if(a.rect)return a.rect.width>0&&a.rect.height>0?a.rect:null;return null}(e,t,r);return a?{rect:a,inherited:!0}:null}function ii(e,t,r,a,n,i=!1,o=!1,s){var l,u,p,d,c,f,m,h,g,w,y,v,A,I,S,b,_,k,N;let D,x,R,M,P=t6(e),L=(l=e,u=t,p=P,d=a,c=r,f=n,m=i,R=(x=(D=u.map(e=>{var t;let r;return(r=ia(l,t=e,p))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?x:D,d&&void 0===c?(h=R,g=f,w=m,M=h.filter(e=>{var t,r;let a,n;return t=e.rect,r=g,a=r?.referenceWidth??1/0,n=r?.referenceHeight??1/0,t.x<a&&t.y<n&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:h):D),O=function(e,t,r,a,n,i){var o,s,l,u,p,d,c;if(void 0!==r)return t[r]??null;let f=(o=e,s=t,l=a,u=n,p=i,u&&l?function(e,t,r,a){let n=t.filter(e=>0===ig(e.node,r));if(n.length>=2){let t=is(e,n,r,a);if(t)return t}let i=t.filter(e=>1===ig(e.node,r));return n.length>0||i.length<2?null:is(e,i,r,a)}(o,s,l,p)??io(o,s,l,p):io(o,s,l,p));return(d=f,c=a,n&&c&&d)?function(e,t,r){var a,n,i,o,s,l,u,p,d,c,f,m,h,g,w,y,v,A;let I,S,b,_,k,N,D,x;if(a=t,n=r,!(("cell"===(I=t4(a.node.type??""))||"other"===I||"scrollview"===I||"scroll-area"===I)&&!(a.rect.width<120)&&!(a.rect.height<32)&&!(a.rect.height>80)&&1>=ig(a.node,n)))return null;let R=(i=e,o=t,s=r,l=t6(e),i.filter(e=>{var t,r,a;let n;return e.index!==o.node.index&&!!e.rect&&tQ(i,e,o.node,l)&&(t=e,r=o.rect,a=s,!("button"!==(n=t4(t.type??""))&&"cell"!==n&&"other"!==n||1>=ig(t,a))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!im(r,t.rect)&&id(r,t.rect)>=.5)}).sort((e,t)=>e.rect.x-t.rect.x));if(0===R.length)return null;let M=(b=Math.floor((S=[...R.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),S[b]??0),P=function(e,t){let r=[],a=e.x,n=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(n,i.x+i.width);t>a&&r.push({x:a,width:t-a}),a=Math.max(a,o)}return n>a&&r.push({x:a,width:n-a}),r}(t.rect,R.map(e=>e.rect)),L=(u=t,p=r,d=P,c=M,N=d.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),D=(f=u,m=p,_=d.find(e=>1>Math.abs(e.x-f.rect.x)),k=Math.max(48,Math.min(220,8*m.length+24)),(h=f,g=m,w=_,y=k,w&&"scrollview"===t4(h.node.type??"")&&1>=ig(h.node,g)&&h.rect.width>=240&&h.rect.height>=32&&h.rect.height<=80&&w.width<=.55*h.rect.width&&w.width>=.6*y)?{x:f.rect.x,width:Math.min(k,_.width)}:null),x=N.some(e=>{var t;return t=u.rect,1>Math.abs(e.x-t.x)}),D&&!x?D:1===N.length?N[0]??null:D);return L?(v=t,A=L,{...v,rect:{x:A.x,y:v.rect.y,width:A.width,height:v.rect.height}}):null}(e,f,a)??f:f}(e,L,r,a,o,s);return y=e,v=O,A=P,I=o,S=n,v?I?(b=y,_=v,k=A,N=S,(ic(_.node)?null:tZ(b,_.node,k,e=>{if(!ic(e))return null;let t=ia(b,e,k);return t&&function(e,t,r){var a,n;if(!im(t,e)||(a=e,!((n=t).height<32||n.height>80||a.height<.75*n.height||.75>id(a,n))&&!(n.width<240)&&n.width>=3*a.width))return!1;let i=iu(t),o=iu(e);if(o>0&&i>30*o)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&i>.5*e)return!1}return!0}(_.rect,t.rect,N)?{node:e,rect:t.rect}:null}))??{node:v.node,rect:v.rect}):{node:v.node,rect:v.rect}:null}function io(e,t,r,a){return(function(e,t,r,a){var n;let i,o,s;if(!r||t.length<2)return t;let l=t.filter(e=>0===ig(e.node,r));if(l.length<2)return t;let u=t6(e),p=l.map(t=>({candidate:t,container:il(e,t.node,u)})).filter(e=>!!e.container);if(p.length<2||p.length!==l.length)return t;let d=p.filter(e=>{var t;return t=e,p.some(e=>e!==t&&t.container.index!==e.container.index&&ih(t.container.rect,e.container.rect)>=.6)});if(d.length<2)return t;let c=(o=Math.max(...i=(n=d).map(e=>iu(e.container.rect))),(s=Math.min(...i))<=0||o<1.2*s?[]:n.filter(e=>iu(e.container.rect)===o).map(e=>e.candidate));if(c.length>0)return c;let f=function(e,t,r,a){if(!r)return[];let n=il(e,r.node,a),i=n&&im(n.rect,r.rect)?n:null,o=t.map(e=>({entry:e,score:function(e,t,r){if(r)return e.index===r.index?0:.6>ih(e.rect,r.rect)?1/0:Math.abs(e.index-r.index);if(ih(e.rect,t.rect)>=.6)return 0;let a=e.index-t.node.index;return a>=0?a:1e5+Math.abs(a)}(e.container,r,i)})),s=Math.min(...o.map(e=>e.score));return Number.isFinite(s)?o.filter(e=>e.score===s).map(e=>e.entry.candidate):[]}(e,d,a,u);if(f.length>0)return f;let m=Math.max(...d.map(e=>e.container.index)),h=d.filter(e=>e.container.index===m).map(e=>e.candidate);return h.length>0?h:t})(e,t,r,a).sort((e,t)=>(function(e,t,r){var a,n;let i=function(e,t,r){if(r){let a=ig(e.node,r)-ig(t.node,r);if(0!==a)return a}let a=ip(e.node)-ip(t.node);if(0!==a)return a;let n=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==n)return n;let i=r&&ip(e.node)===ip(t.node)?iu(t.rect)-iu(e.rect):iu(e.rect)-iu(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(a=e.rect,n=t.rect,Math.round(a.x)!==Math.round(n.x)||Math.round(a.y)!==Math.round(n.y)||Math.round(a.width)!==Math.round(n.width)||Math.round(a.height)!==Math.round(n.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function is(e,t,r,a){let n=t6(e),i=t.filter(r=>{var a;return(a=r).rect.width>=16&&a.rect.width<=260&&a.rect.height>=24&&a.rect.height<=80&&t.some(t=>{var a,i,o,s;return a=e,i=t,o=r,s=n,!(i.node.index===o.node.index||!im(i.rect,o.rect)||iu(i.rect)<2*iu(o.rect))&&tQ(a,o.node,i.node,s)})});return io(e,i,r,a)}function il(e,t,r){return tZ(e,t,r,e=>{let t;return!e.rect||"scrollview"!==(t=t4(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e})}function iu(e){return e.width*e.height}function ip(e){return n8.get(t4(e.type??""))??3}function id(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}function ic(e){let t=t4(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function im(e,t){return t.x>=e.x-1&&t.y>=e.y-1&&t.x+t.width<=e.x+e.width+1&&t.y+t.height<=e.y+e.height+1}function ih(e,t){let r=Math.max(e.x,t.x),a=Math.min(e.x+e.width,t.x+t.width),n=Math.max(e.y,t.y);return Math.max(0,a-r)*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-n)/Math.max(1,Math.min(iu(e),iu(t)))}function ig(e,t){let r=[e.label,tX(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>rt(e)===rt(t))?1:r.some(e=>ir(e,t))?2:3}async function iw(e){var t,r;let a=ib(e.positionals,{command:"assertVisible",defaultTimeoutMs:17e3});if(!a.ok)return a.response;let n=(t=e.baseReq,r=a.selector,t.flags?.platform!=="ios"&&t.flags?.platform!=="android"?null:ie(r));return n?await iy(e,a,n):await iA(e,a)}async function iy(e,t,r){let a=Date.now(),n=await iv(e,t,r);return n.ok?iD({ok:!0,data:{selector:t.selector,nativeWait:!0,query:r,response:n.data}},t.selector,a):await iI(e,t,n,a)}async function iv(e,t,r){return await e.invoke({...e.baseReq,command:"wait",positionals:[r,String(t.timeoutMs)]})}async function iA(e,t){let r,a,n=Date.now(),i=t.timeoutMs+1e3,o=!1;for(;;){let s=Date.now(),l=await i_(e,t.selector,"assertVisible");if(l.visible)return iD(l.response,t.selector,n);r=l.response,a=l.snapshot??a;let u=iS(e.baseReq,t,l,n);if("return"===u.kind)return u.response;let p=function(e){var t,r,a,n;return Date.now()-e.startedAt<e.deadlineMs?"wait":(t=e.capturedAfterDeadline,r=e.captureStartedAt,a=e.startedAt,n=e.deadlineMs,!t&&r-a<n)?"capture-again":"finish"}({captureStartedAt:s,capturedAfterDeadline:o,startedAt:n,deadlineMs:i});if("capture-again"===p){o=!0;continue}if("finish"===p)break;await rr(250)}return ix(r??n3("COMMAND_FAILED",`Expected visible but did not match: ${t.selector}`,{selector:t.selector,timeoutMs:t.timeoutMs}),a,e.baseReq)}async function iI(e,t,r,a){let n=await i_(e,t.selector,"assertVisible");if(n.visible)return iD(n.response,t.selector,a);let i=iS(e.baseReq,t,n,a);return"return"===i.kind?i.response:ix(r,n.snapshot,e.baseReq)}function iS(e,t,r,a){var n,i,o,s,l,u,p;return!(n=r.response).ok&&"COMMAND_FAILED"===n.error.code&&n.error.message.includes("React Native overlay")?{kind:"return",response:r.response}:(i=e,o=t.selector,s=r.snapshot,i.flags?.maestro?.allowAlreadyPastLoading===!0&&void 0!==s&&function(e,t){let r=ik(ie(e));if(!iN(r))return!1;let a=t.nodes.flatMap(e=>[e.label,e.value,e.identifier]).filter(e=>!!e?.trim()).map(e=>ik(e));return!a.some(e=>e.includes("something went wrong"))&&a.some(e=>e!==r&&!iN(e))}(o,s))?{kind:"return",response:(l=t.selector,u=t.timeoutMs,p=a,{ok:!0,data:{selector:l,alreadyPastLoading:!0,waitedMs:Date.now()-p,timeoutMs:u}})}:{kind:"continue"}}function ib(e,t){let[r,a=String(t.defaultTimeoutMs)]=e;if(!r)return{ok:!1,response:n3("INVALID_ARGS",`${t.command} requires a selector.`)};let n=Number(a);return!Number.isFinite(n)||n<0?{ok:!1,response:n3("INVALID_ARGS",`${t.command} timeout must be a non-negative number.`)}:{ok:!0,selector:r,timeoutMs:n}}async function i_(e,t,r){let a=await n5(e);return function(e,t,r,a){var n;if(!a.ok)return{visible:!1,response:a,infrastructureFailure:!0};let i=n6(a.data);if(!i)return{visible:!1,response:n3("COMMAND_FAILED",`Unable to read snapshot data for ${r}.`),infrastructureFailure:!0};let o=n4(i,t,n9(e.baseReq.flags),Q(i));return o.ok?(n=e.scope,n&&n2.set(n,{selector:t}),{visible:!0,response:{ok:!0,data:{selector:t,matches:o.matches,nodeIndex:o.node.index,nodeType:o.node.type,nodeLabel:o.node.label,nodeIdentifier:o.node.identifier,rect:o.rect}}}):{visible:!1,response:n3("COMMAND_FAILED",o.message,{selector:t}),infrastructureFailure:!1,snapshot:i}}(e,t,r,a)}function ik(e){return e?.trim().toLowerCase().replace(/\u2026/g,"...")??""}function iN(e){return"loading"===e||"loading..."===e}function iD(e,t,r){return e.ok?{ok:!0,data:{selector:t,...e.data,waitedMs:Date.now()-r}}:e}function ix(e,a,n){var i;if(e.ok||!a)return e;let o="string"==typeof n.flags?.artifactsDir?n.flags.artifactsDir:void 0;if(!o)return e;let s=function(e,a){try{t.mkdirSync(a,{recursive:!0});let n=r.join(a,"failure-snapshot.json"),i=r.join(a,"failure-snapshot.txt");t.writeFileSync(n,`${JSON.stringify(e,null,2)}
26
+ `);let o=ra(e.nodes,{summarizeTextSurfaces:!0}).map(e=>e.text);return t.writeFileSync(i,`${o.join("\n")}
27
+ `),[n,i]}catch{return[]}}(a,o);return 0===s.length?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},artifactPaths:[...new Set([...Array.isArray(i=e.error.details?.artifactPaths)?i.filter(e=>"string"==typeof e):[],...s])]}}}}async function iR(e){let t,r=ib(e.positionals,{command:"assertNotVisible",defaultTimeoutMs:3e3});if(!r.ok)return r.response;let a=Date.now(),n=0;for(;Date.now()-a<=r.timeoutMs;){let i=await i_(e,r.selector,"assertNotVisible");if(!i.visible&&i.infrastructureFailure)return i.response;if(i.visible)n=0,t=i.response;else{n+=1;let e=Date.now()-a;if(n>=2||e>=r.timeoutMs)return{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:e,timeoutMs:r.timeoutMs}}}await rr(250)}return n>0?{ok:!0,data:{pass:!0,selector:r.selector,stableSamples:n,waitedMs:Date.now()-a,timeoutMs:r.timeoutMs}}:n3("COMMAND_FAILED",`Expected not visible but matched: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs,lastResponse:t})}async function iM(e){let t,r,a=Number(e.positionals[0]??15e3);if(!Number.isFinite(a)||a<0)return n3("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let n=Date.now();for(;Date.now()-n<a;){let n=await n5(e),i=function(e,t,r){let a=function(e){if(!e.ok)return null;let t=n6(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?a?t===a?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:a}:{done:!0,response:e}:{done:!1}}(n,t,a);if(i.done)return i.response;t=i.signature??t,r=n,await rr(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:a}}}let iP=.35,iL=120,iO=360,iE=8;function iC(e,t){return Math.round(Math.min(iO,Math.max(iL,"number"==typeof e?e*iP:0,1.5*t)))}async function i$(e){var t,r,a;let[n,i="5000",o="down"]=e.positionals;if(!n)return n3("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return n3("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=ie(n),u=Math.max(1,Math.ceil(s/500)),p=null;for(let t=0;t<u;t+=1){let r=await iK(e,n,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(p=r,t===u-1)break;let a=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!a.ok)return a}return t=p,r=n,a=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${a}ms for selector: ${r}. Last wait: ${t.error.message}`}}:n3("COMMAND_FAILED",`scrollUntilVisible timed out after ${a}ms for selector: ${r}`)}async function iV(e){let[t,r]=e.positionals,a=Number(t),n=Number(r);if(!Number.isFinite(a)||!Number.isFinite(n))return n3("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await n5(e);if(!i.ok)return i;let o=n6(i.data);if(!o)return n3("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=Q(o);if(!s)return n3("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.");let l=ez(s,a,n);return await e.invoke({...e.baseReq,command:"click",positionals:[String(l.x),String(l.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}})}async function iU(e){let t=await iF(e);if(t)return t;let r=await iB(e);return r.ok?await iT(e,r,r.durationMs):r.response}async function iF(e){let[t,r,a]=e.positionals;if("direction"===t&&("left"===r||"right"===r))return await e.invoke({...e.baseReq,command:"gesture",positionals:["swipe",r,...a?[a]:[]]})}async function iG(e){var t,r,a,n;let i,[o,s]=e.positionals;if(!o)return n3("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:n3("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),p=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<p;){let t=await ij(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await rr(250)}return r=e,a=o,n=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:a}}:n??n3("COMMAND_FAILED",`tapOn timed out for selector: ${a}`)}async function iq(e){let[t,r="up",a]=e.positionals;if(!t)return n3("INVALID_ARGS","swipe.label requires a label selector.");let n=await iY(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!n.ok)return n.response;let i=function(e,t){let r=eQ(e.rect),a=e.frame,n=iC(a?.referenceWidth,e.rect.width),i=iC(a?.referenceHeight,e.rect.height),o=iE,s=a?a.referenceWidth-o:r.x+n,l=a?a.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:e7(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:e7(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:e7(r.x-n,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:e7(r.x+n,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(n.target,r);return i.ok?await iT(e,i,a):n3("INVALID_ARGS",i.message)}async function iT(e,t,r){return await e.invoke({...e.baseReq,command:"swipe",positionals:[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]]})}async function iB(e){var t;let r=((t=e.scope)?n1.get(t):void 0)??await iH(e);if(!r)return{ok:!1,response:n3("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[a,...n]=e.positionals;return"direction"===a?function(e,t){let[r,a]=e;if(!r)return{ok:!1,response:n3("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(r){case"up":case"down":var n,i,o;let s;return n=r,i=t,o=a,{ok:!0,start:e1({x:(s=eJ({direction:n,amount:.6,referenceWidth:i.referenceWidth,referenceHeight:i.referenceHeight})).x1,y:s.y1},i,8),end:e1({x:s.x2,y:s.y2},i,8),durationMs:o};default:return{ok:!1,response:n3("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(n,r):"percent"===a?function(e,t,r){var a,n,i,o,s,l,u,p,d,c,f;let[m,h,g,w,y]=e,v=[m,h,g,w].map(Number);if(v.some(e=>!Number.isFinite(e)))return{ok:!1,response:n3("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[A,I,S,b]=v,_=(a=r,n=A,i=I,o=S,s=b,"android"!==a||i!==s||50!==i||30>Math.abs(o-n)?{startY:i,endY:s}:{startY:65,endY:65}),k=(l=r,u=t,p=A,d=I,c=S,f=b,"ios"!==l||d!==f||30>Math.abs(c-p)?1:Math.max(1,Math.round(.15*u.referenceWidth)));return{ok:!0,start:ez(t,A,_.startY,{marginPx:k}),end:ez(t,S,_.endY,{marginPx:k}),durationMs:y}}(n,r,n9(e.baseReq.flags)):{ok:!1,response:n3("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function iH(e){let t=await n5(e);if(t.ok)return Q(n6(t.data))}async function iK(e,t,r,a){let n=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(a)]});return n.ok||!r?n:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(a)]})}async function ij(e,t,r){let a=ie(t),n=await iz(e,t,r);return n.response.ok?{retry:!1,response:n.response}:n.targetResolved&&a?await iJ(e,a):{retry:!0,response:n.response}}async function iz(e,t,r){let a=await iY(e,t,r,"tapOn",{promoteTapTarget:!0});return a.ok?await iW(e,t,a.target):{response:a.response,targetResolved:!1}}async function iW(e,t,r){var a;let n=eQ(r.rect);tv({level:"debug",phase:"maestro_tap_target",data:{selector:t,node:{index:r.node.index,type:r.node.type,label:r.node.label,value:r.node.value,identifier:r.node.identifier,visibleToUser:r.node.visibleToUser},rect:r.rect,point:n}});let i=await e.invoke({...e.baseReq,command:"click",positionals:[String(n.x),String(n.y)],flags:{...e.baseReq.flags,postGestureStabilization:!0}});return i.ok&&(a=e.scope)&&n2.delete(a),{response:i,targetResolved:!0}}async function iJ(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0,postGestureStabilization:!0}});return(tv({level:r.ok?"info":"debug",phase:"maestro_fuzzy_tap_fallback",data:{query:t,ok:r.ok}}),r.ok)?{retry:!1,response:r}:{retry:!0,response:r}}async function iY(e,t,r,a,n){let i=await n5({...e,raw:!0});return function(e,t,r,a,n,i){if(!i.ok)return{ok:!1,response:i};let o=n6(i.data);if(!o)return{ok:!1,response:n3("COMMAND_FAILED",`Unable to read snapshot data for ${a}.`)};let s=Q(o),l=n9(e.baseReq.flags),u=function(e,t,r,a){var n;let i=(n=e.scope)?n2.get(n):void 0;if(!i)return;let o=n4(t,i.selector,r,a);if(o.ok)return tv({level:"debug",phase:"maestro_preferred_context",data:{selector:i.selector,node:{index:o.node.index,type:o.node.type,label:o.node.label,value:o.node.value,identifier:o.node.identifier},rect:o.rect}}),{node:o.node,rect:o.rect}}(e,o,l,s),p=function(e,t,r,a,n,i={}){let o=it(e,t,a);if(r.childOf){let t=it(e,r.childOf,a);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let n=t6(e.nodes);o=o.filter(r=>t.some(t=>tQ(e.nodes,r,t,n)))}let s=n7({nodes:e.nodes,matches:o,platform:a}),l=ii(e.nodes,s.matches,r.index,ie(t),n,!0===i.requireOnScreen,i.promoteTapTarget,i.preferredContext);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`React Native overlay is covering app content: ${t}`:o.length>0&&0===s.matches.length?`Maestro selector matched ${o.length} element(s), but none were visible: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}(o,t,r,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(!p.ok){let e=ie(t);if(e){let t=function(e,t,r,a,n={}){let i=function(e,t){let r=rt(t);if(!r)return[];let a=[],n=[];for(let t of e.nodes){let e=[t.label,tX(t),t.identifier,t.value].filter(e=>!!e).map(e=>rt(e));e.some(e=>e===r)?a.push(t):e.some(e=>e.includes(r))&&n.push(t)}return a.length>0?a:n}(e,t),o=n7({nodes:e.nodes,matches:i,platform:r}),s=ii(e.nodes,o.matches,void 0,t,a,!0===n.requireOnScreen,n.promoteTapTarget,n.preferredContext);return s?{ok:!0,node:s.node,rect:s.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,l,s,{...n,preferredContext:u,requireOnScreen:!0});if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return p.ok?{ok:!0,target:{node:p.node,rect:p.rect,frame:s}}:{ok:!1,response:n3("ELEMENT_NOT_FOUND",p.message,{selector:t,options:r,command:a})}}(e,t,r,a,n,i)}async function iX(e){switch(e.command){case aX:return await iw(e);case aZ:return await iR(e);case aQ:return await iZ(e);case a0:return await iM(e);case a1:return await i$(e);case a2:return await iU(e);case a3:return await iq(e);case a5:return await iG(e);case a6:return await iV(e);case aY:return function(e){let[r]=e.positionals;if(!r)return n3("INVALID_ARGS","runScript requires a file path.");try{let n=function(e){let{scriptPath:r,env:n}=e,i=t.readFileSync(r,"utf8"),o=Object.create(null);try{var l,u;a.runInNewContext(i,(l=n,u=o,{...l,output:u,json:nd,http:{post:(e,t)=>(function(e,t,r){let a=tJ(process.execPath,["-e",np],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==a.exitCode){let r;throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=a.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:a.exitCode,stderr:a.stderr})}try{return JSON.parse(a.stdout)}catch(r){throw new s("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:a.stdout.slice(0,1e3),stderr:a.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:r,timeout:3e4})}catch(e){throw new s("COMMAND_FAILED",`Maestro runScript failed for ${r}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:r},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new s("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:r,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:n}}}catch(t){let e=i(t);return n3(e.code,e.message,e.details)}}(e);default:return}}async function iZ(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function iQ(e){for(let[t,r]of e.actions.entries()){let a=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!a.ok)return a}return{ok:!0,data:{ran:e.actions.length}}}async function i0(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let a=await iQ({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(a.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=a}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function i1(e){let t=await i2(e,e.control);return t.ok?t.matched?await i6(e):{ok:!0,data:{skipped:!0,condition:e.control.mode,selector:e.control.selector}}:t.response}async function i2(e,t){if("visible"===t.mode)return await i3(e,t);let r=await i5(e,t.selector);return r.ok?{ok:!0,matched:!r.matched}:{ok:!1,response:r.response}}async function i3(e,t){let r=Date.now();for(;;){let a=await i5(e,t.selector);if(!a.ok)return{ok:!1,response:a.response};if(a.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await rr(250)}}async function i5(e,t){var r,a;let n,i=await n5(e);return i.ok?(r=e,a=t,(n=n6(i.data))?{ok:!0,matched:n4(n,a,n9(r.baseReq.flags),Q(n)).ok}:{ok:!1,response:n3("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}):{ok:!1,response:i}}async function i6(e){let t=await iQ({actions:e.control.actions,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return t.ok?{ok:!0,data:{ran:t.data?.ran,condition:e.control.mode,selector:e.control.selector}}:t}async function i8(e){let{req:t,sessionName:r,action:a,scope:n,filePath:i,line:o,step:s,tracePath:l,invoke:u}=e,p=tz(a,n,{file:i,line:o}),d=Date.now();i9(l,{type:"replay_action_start",ts:new Date(d).toISOString(),replayPath:i,line:o,step:s,command:p.command,positionals:p.positionals??[]});let c=await i4({req:t,sessionName:r,resolved:p,scope:n,line:o,step:s,invoke:u,invokeReplayAction:e=>i8({req:t,sessionName:r,action:e.action,scope:n,filePath:i,line:e.line,step:e.step,tracePath:l,invoke:u})}),f=Date.now();return i9(l,{type:"replay_action_stop",ts:new Date(f).toISOString(),replayPath:i,line:o,step:s,command:p.command,ok:c.ok,durationMs:f-d,resultTiming:c.ok?function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.timing;if(!(!t||"object"!=typeof t||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return"number"===t||"string"===t||"boolean"===t}))}(c.data):void 0,errorCode:c.ok?void 0:c.error.code}),c}async function i4(e){var t;let{req:r,sessionName:a,resolved:n,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,p=(t=r.flags,tI(t,{...n.flags??{}})),d={token:r.token,session:a,flags:p,runtime:n.runtime,meta:r.meta,internal:r.internal},c=await i7({control:n.replayControl,baseReq:d,line:o,step:s,invoke:l,invokeReplayAction:u})??await iX({command:n.command,baseReq:d,positionals:n.positionals??[],scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...d,command:n.command,positionals:n.positionals??[]});if(c.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(c.data);e&&tW(i,e)}return c}async function i7(e){let{control:t,baseReq:r,line:a,step:n,invoke:i,invokeReplayAction:o}=e;if(t){switch(t.kind){case"retry":return await i0({actions:t.actions,maxRetries:t.maxRetries,line:a,step:n,invokeReplayAction:o});case"maestroRunFlowWhen":return await i1({baseReq:r,control:t,line:a,step:n,invoke:i,invokeReplayAction:o})}return t}}function i9(e,r){e&&t.appendFileSync(e,`${JSON.stringify(r)}
28
+ `)}async function oe(e){let{req:a,sessionName:n,logPath:o,sessionStore:l,tracePath:u,invoke:p}=e,d=a.positionals?.[0];if(!d)return E("INVALID_ARGS","replay requires a path");let c="",f=new Set;try{var m,h;c=em.expandHome(d,a.meta?.cwd);let e=t.readFileSync(c,"utf8"),i=e.trimStart()[0];if("{"===i||"["===i)return E("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let g=function(e,t,r={}){var a;let n=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=nY[t];if(!r)throw new s("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return n?{...n.parse(e,{...r,platform:t?.platform,env:(a=t,{...tC(tD(a?.replayShellEnv)),...tE(tM(a?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...tN(e),metadata:tO(e)}}(e,a.flags,{sourcePath:c}),w=g.metadata,y=w.platform||w.target?{...a,flags:(m=a.flags,h=w,{...m??{},...void 0!==h.platform&&m?.platform===void 0?{platform:h.platform}:{},...void 0!==h.target&&m?.target===void 0?{target:h.target}:{}})}:a,v=g.actions,A=g.actionLines;if(a.flags?.replayUpdate===!0&&g.updateUnsupportedMessage)return E("INVALID_ARGS",g.updateUnsupportedMessage);if(a.flags?.replayUpdate===!0&&w.env&&Object.keys(w.env).length>0)return E("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(a.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(on(t.flags)||on(t.runtime))return!0}return!1}(v))return E("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let I=tj({builtins:function(e){let{req:t,sessionName:a,metadata:n,resolvedPath:i}=e,o=t.flags??{},s=t.meta?.cwd??process.cwd(),l={AD_SESSION:a,AD_FILENAME:r.relative(s,i)||i},u=o.platform??n.platform;u&&(l.AD_PLATFORM=u);let p=o.target??n.target;p&&(l.AD_TARGET=p);let d=o.device;"string"==typeof d&&d.length>0&&(l.AD_DEVICE=d);let c="string"==typeof o.serial?o.serial:o.udid;"string"==typeof c&&c.length>0&&(l.AD_DEVICE_ID=c),"number"==typeof o.shardIndex&&(l.AD_SHARD_INDEX=String(o.shardIndex)),"number"==typeof o.shardCount&&(l.AD_SHARD_COUNT=String(o.shardCount));let f=o.artifactsDir;return"string"==typeof f&&f.length>0&&(l.AD_ARTIFACTS=f),l}({req:y,sessionName:n,metadata:w,resolvedPath:c}),fileEnv:w.env,shellEnv:tC(tD(a.flags?.replayShellEnv)),cliEnv:tE(tM(a.flags?.replayEnv))}),S=a.flags?.replayUpdate===!0,b=u??l.get(n)?.trace?.outPath,_=0;for(let e=0;e<v.length;e+=1){let t=v[e];if(!t||"replay"===t.command)continue;let r=await i8({req:y,sessionName:n,action:t,scope:I,filePath:c,line:A[e]??0,step:e+1,tracePath:b,invoke:p});if(r.ok){or(r).forEach(e=>f.add(e));continue}if(or(r).forEach(e=>f.add(e)),!S)return ot(r,t,e,c,[...f]);let a=await nZ({action:t,sessionName:n,logPath:o,sessionStore:l});if(!a)return ot(r,t,e,c,[...f]);if(v[e]=a,!(r=await i8({req:y,sessionName:n,action:a,scope:I,filePath:c,line:A[e]??0,step:e+1,tracePath:b,invoke:p})).ok)return or(r).forEach(e=>f.add(e)),ot(r,a,e,c,[...f]);or(r).forEach(e=>f.add(e)),_+=1}return S&&_>0&&tK(c,v,l.get(n)),{ok:!0,data:{replayed:v.length,healed:_,session:n,artifactPaths:[...f]}}}catch(t){let e=i(t);return E(e.code,e.message,f.size>0?{artifactPaths:[...f]}:void 0)}}function ot(e,t,r,a,n=[]){if(e.ok)return e;let i=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${i} (${t7(t)}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:a,step:i,action:t.command,positionals:t.positionals??[],artifactPaths:n}}}}function or(e){if(!e.ok){let t=e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&oa(e)))]:[]}if(!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,a="string"==typeof r.path?r.path:void 0;e?t.push(e):a&&t.push(a)}return[...new Set(t.filter(e=>oa(e)))]}function oa(e){try{return t.statSync(e).isFile()}catch{return!1}}function on(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(on):!!e&&"object"==typeof e&&Object.values(e).some(on)}async function oi(e){let{req:t,sessionName:a,logPath:n,sessionStore:i,artifactsDir:o,tracePath:s}=e;if(t.flags?.recordVideo!==!0)return;let l=i.get(a);if(!l||l.recording)return;let u=o?r.join(o,"recording.mp4"):`./recording-${Date.now()}.mp4`;os(s,{type:"video_recording_start",session:a,videoPath:u}),tv({phase:"replay_test_video_recording_start",data:{session:a,videoPath:u}});let p=await rn({req:{token:t.token,session:a,command:"record",positionals:["start",u],flags:{},meta:t.meta},sessionName:a,sessionStore:i,logPath:n});if(!p.ok)return os(s,{type:"video_recording_start_failed",session:a,videoPath:u,errorCode:p.error.code}),p;let d=Date.now();return await rr(1e3),os(s,{type:"video_preroll_done",session:a,durationMs:Date.now()-d,requestedDurationMs:1e3}),tv({phase:"replay_test_video_recording_preroll_done",durationMs:Date.now()-d,data:{session:a,requestedDurationMs:1e3}}),p}async function oo(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,tracePath:i,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!n.get(r)?.recording)return;os(i,{type:"video_tail_start",session:r,requestedDurationMs:3e3});let s=Date.now();await rr(3e3);let l=Date.now(),u=await rn({req:{token:t.token,session:r,command:"record",positionals:["stop"],flags:{},meta:t.meta},sessionName:r,sessionStore:n,logPath:a});return or(u).forEach(e=>o.add(e)),os(i,{type:"video_recording_stop",session:r,ok:u.ok,durationMs:Date.now()-l,tailDurationMs:l-s,errorCode:u.ok?void 0:u.error.code}),tv({phase:"replay_test_video_recording_stop",durationMs:Date.now()-l,data:{session:r,ok:u.ok,tailDurationMs:l-s}}),u}function os(e,t){nP(e,{...t,ts:new Date().toISOString()})}async function ol(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}=e;return"replay"===t.command?await oe({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i}):"test"===t.command?await nT({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:p,tracePath:d,shard:c})=>{let f=function(e){let{platform:t,target:r,artifactsDir:a,shard:n}=e,i=function(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}(e.parentFlags);if(void 0===t&&void 0===r&&void 0===a&&void 0===n)return i;var o={...i??{},...void 0!==t?{platform:t}:{},...void 0!==r?{target:r}:{},...void 0!==a?{artifactsDir:a}:{}};if(!n)return o;let s={...o??{},device:void 0,udid:void 0,serial:void 0,platform:n.device.platform,target:n.device.target,shardAll:void 0,shardSplit:void 0,shardCount:n.shardCount,shardIndex:n.shardIndex};return"android"===n.device.platform?{...s,serial:n.device.id}:{...s,udid:n.device.id}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u,shard:c}),m={req:t,sessionName:r,logPath:a,sessionStore:n,artifactsDir:u,tracePath:d},h=function(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await oi(e)}}(m);return await oe({req:{...t,command:"replay",session:r,positionals:[e],flags:f,meta:{...t.meta??{},...l?{requestId:l}:{}},...t.internal||h?{internal:{...t.internal??{},...h?{openLifecycle:h}:{}}}:{}},sessionName:r,logPath:a,sessionStore:n,tracePath:d,invoke:async e=>{var t;let r=await oi(m);return r&&!r.ok?r:(t=await i(e),p&&or(t).forEach(e=>p.add(e)),t)}})},finalizeAttempt:async({sessionName:e,artifactPaths:r,artifactsDir:i,tracePath:o})=>await oo({req:t,sessionName:e,logPath:a,sessionStore:n,artifactsDir:i,tracePath:o,artifactPaths:r}),cleanupSession:async e=>{n.get(e)&&await et({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:a,sessionStore:n})}}):null}async function ou(e){var t,r,a,n,i,o,s,l;let u,p,{req:d,sessionName:c,logPath:f,sessionStore:h}=e,g=d.positionals?.[0]??"";if("ios-runner"!==g)return E("INVALID_ARGS","prepare requires a subcommand: ios-runner");let w=h.get(c),y=d.flags??{},v=N(ro.prepare,w,y);if(v)return v;let A=await m({session:w,flags:y,ensureReady:!0});if(!tn(A.platform))return E("UNSUPPORTED_OPERATION","prepare ios-runner is only supported on Apple runner platforms");let I=Date.now(),S=await er(A,(t=d,r=w,a=f,p=(n=t,"number"==typeof(u=n.flags?.timeoutMs)&&Number.isFinite(u)&&u>0?u:3e5),{verbose:t.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,cleanStaleBundles:!0,startupTimeoutMs:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return Math.max(45e3,Math.floor(e))}(t.flags?.timeoutMs),requestId:t.meta?.requestId,buildTimeoutMs:p,healthTimeoutMs:Math.min(p,9e4)}));return{ok:!0,data:(i=g,o=A,s=Math.max(0,Date.now()-I),l=S,{action:i,platform:o.platform,deviceId:o.id,deviceName:o.name,kind:o.kind,durationMs:s,...l,message:`Prepared Apple runner: ${o.name}`})}}async function op(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=n.get(r),d=t.flags??{},c=N(i,u,d);if(c)return c;let f=await m({session:u,flags:d,ensureReady:!0});if(!eV(i,f))return E("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let h=await p(f,i,o,t.flags?.out,{...ec(a,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,h,f):u;n.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:h??{}}),e!==u&&n.set(r,e)}return{ok:!0,data:h??{}}}async function od(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r),o=t.flags??{},s=N(ro.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return E("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await m({session:i,flags:o,ensureReady:!0});if(!eV(ro.clipboard,u))return E("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await p(u,ro.clipboard,t.positionals??[],t.flags?.out,{...ec(a,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&n.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function oc(e){let{req:t,sessionName:r,logPath:a,sessionStore:n,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if("inventory"===y(t.command))return await rz({req:t,sessionName:r,sessionStore:n});if("runtime"===t.command)return await rA({req:t,sessionName:r,sessionStore:n});if("state"===y(t.command))return await rZ({req:t,sessionName:r,sessionStore:n});if(t.command===ro.clipboard)return await od({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ro.keyboard){let e=n.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==to((t.flags??{}).platform)?await op({req:t,sessionName:r,logPath:a,sessionStore:n,command:ro.keyboard,positionals:t.positionals??[]}):E("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if("observability"===y(t.command))return await aC({req:t,sessionName:r,sessionStore:n,androidAdbExecutor:s});if(t.command===ro.prepare)return await ou({req:t,sessionName:r,logPath:a,sessionStore:n});if(t.command===ro.install||t.command===ro.reinstall)return await rK({req:t,command:t.command,sessionName:r,sessionStore:n,deployOps:t.command===ro.install?rH:rB});if(t.command===ri.installSource)return await rc({req:t,sessionName:r,sessionStore:n});if(t.command===ri.releaseMaterializedPaths)return await rf({req:t});if(t.command===ro.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await op({req:t,sessionName:r,logPath:a,sessionStore:n,command:ro.push,positionals:[i,"file"===(e=eS(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>em.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):E("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===ro.triggerAppEvent?await op({req:t,sessionName:r,logPath:a,sessionStore:n,command:ro.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await rP(e.device,r,e.appBundleId,rR)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}}):t.command===ro.open?await rT({req:t,sessionName:r,logPath:a,sessionStore:n}):"replay"===y(t.command)?await ol({req:t,sessionName:r,logPath:a,sessionStore:n,invoke:o??i}):t.command===ro.batch?await rj(t,r,i):t.command===ro.close?await et({req:t,sessionName:r,logPath:a,sessionStore:n}):null}export{rl as session_namespaceObject};