agent-device 0.20.8 → 0.20.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -31
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.8.apk → agent-device-android-ime-helper-0.20.10.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.10.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.8.manifest.json → agent-device-android-ime-helper-0.20.10.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.8.apk → agent-device-android-snapshot-helper-0.20.10.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.10.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.8.manifest.json → agent-device-android-snapshot-helper-0.20.10.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +3 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +13 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +10 -117
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +4 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +103 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +22 -23
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +3 -23
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +10 -11
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +108 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +8 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +179 -73
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +13 -12
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentation.swift +183 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentationTests.swift +0 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +20 -18
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +19 -0
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.d.ts +61 -0
- package/dist/src/ai-sdk.js +1 -0
- package/dist/src/android-adb.d.ts +6 -6
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-lifecycle.js +6 -7
- package/dist/src/app-lifecycle2.js +2 -2
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state.js +2 -0
- package/dist/src/appearance.js +1 -0
- package/dist/src/apps.js +5 -5
- package/dist/src/artifacts.d.ts +1 -1
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/auth-session.js +1 -1
- package/dist/src/backend-snapshot-options.js +1 -0
- package/dist/src/boot-diagnostics.js +2 -2
- package/dist/src/bounds.js +1 -0
- package/dist/src/byte-limit-stream.js +1 -0
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +42 -30
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +7 -7
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +1582 -0
- package/dist/src/command-catalog.js +1 -0
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-surface.js +1 -1
- package/dist/src/command-tools.js +2 -0
- package/dist/src/config.js +1 -0
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +3 -3
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/daemon.js +1 -1
- package/dist/src/debug-symbols.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device-ready.js +1 -1
- package/dist/src/device2.js +2 -2
- package/dist/src/dispatch.js +1 -1
- package/dist/src/entities.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper-package-install.js +1 -0
- package/dist/src/helper.js +2 -2
- package/dist/src/host-process.js +1 -1
- package/dist/src/ime-lifecycle.js +2 -9
- package/dist/src/ime-recovery-marker.js +1 -0
- package/dist/src/index.d.ts +2 -1569
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +4 -4
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-artifact.js +1 -1
- package/dist/src/install-artifact2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-common.js +1 -0
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -0
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/interactors.js +1 -0
- package/dist/src/internal/bin.js +2 -2
- package/dist/src/internal/daemon.js +4 -7
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory.js +1 -1
- package/dist/src/keyed-lock.js +1 -0
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +13 -3
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/location-coordinates.js +1 -0
- package/dist/src/logcat.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/mobile-snapshot-semantics.js +1 -0
- package/dist/src/observability.js +1 -0
- package/dist/src/owner-identity.js +1 -1
- package/dist/src/perf.js +4 -0
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-network-web-transport.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -0
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-runtime-hints.js +2 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-web-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -0
- package/dist/src/plist.js +1 -1
- package/dist/src/png-resize.js +1 -0
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/process-lock.js +1 -1
- package/dist/src/project-runtime.js +1 -0
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/provider.js +1 -0
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-export-quality.js +1 -0
- package/dist/src/registry.js +29 -26
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/reporting.js +5 -5
- package/dist/src/rolldown-runtime.js +1 -0
- package/dist/src/runner-client.js +1 -0
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime2.js +4 -3
- package/dist/src/runtime3.js +1 -3
- package/dist/src/runtime4.js +3 -1
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -0
- package/dist/src/runtime9.js +1 -0
- package/dist/src/scoped-provider.js +1 -0
- package/dist/src/screenshot-density.js +1 -0
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/screenshot.js +1 -1
- package/dist/src/script-source-bundle.js +16 -0
- package/dist/src/sdk-android-adb.d.ts +44 -26
- package/dist/src/sdk-android-adb.js +4 -4
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +125 -88
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +107 -95
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/sdk.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +10 -3
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +1 -30
- package/dist/src/session2.js +27 -0
- package/dist/src/setting-state.js +1 -1
- package/dist/src/shared.js +1 -1
- package/dist/src/simctl.js +1 -0
- package/dist/src/simulator-state.js +1 -0
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-scope.js +1 -0
- package/dist/src/snapshot-session.js +1 -1
- package/dist/src/snapshot.js +8 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -0
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +1 -2
- package/dist/src/src3.js +2 -1
- package/dist/src/src4.js +1 -0
- package/dist/src/string-enum.js +1 -0
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/verdict.js +1 -0
- package/dist/src/verified-file.js +1 -0
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/web.js +1 -1
- package/package.json +27 -10
- package/server.json +3 -3
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.8.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.8.apk.sha256 +0 -1
- package/dist/src/interaction-touch-reference-frame.js +0 -1
- package/dist/src/notifications.js +0 -1
- package/dist/src/platform-runtime-toolchain-host.js +0 -1
- package/dist/src/prepare-kind.js +0 -15
- package/dist/src/selector-vocabulary.js +0 -1
- package/dist/src/text-surface.js +0 -1
package/dist/src/runtime4.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{F as t,L as n,P as r,W as i}from"./sdk-batch-runner.js";import{C as a}from"./sdk-device.js";import{S as o,b as s,c,h as l,m as u,p as d,s as f}from"./src2.js";import{randomUUID as p}from"node:crypto";const m=Object.freeze({resourceKind:t,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!g(e.outputPath)||!g(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function h(e){return s({resourceKind:t,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:o(m,e.descriptor)})}function g(e){return typeof e==`string`&&e.trim().length>0}function _(e){return f(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:m,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await v(e,r);return{resolvePid:async r=>await c(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>h({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function v(t,n){n.throwIfAborted(),await y(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await y(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function y(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}const b=Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&C(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function x(e){let{device:t,owner:n,input:i,descriptor:c}=e;return s({resourceKind:r,sessionId:i.sessionId,device:a(t),owner:n,fence:i.fence,lifecycle:`open`,descriptor:o(b,c)})}function S(e){return b.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function C(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function w(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function T(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await E({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>S(e.envelope.descriptor.body)})}async function E(t){let{host:n,device:r,owner:a,input:o,signal:s}=t;if(o.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);d(o,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),s.throwIfAborted(),await n.screenRecording.outputs.prepare(o.outputPath);let c=`agent-device-recording-${p()}.mp4`,u={backend:`harmony-screen-recorder`,fileName:c,remotePath:`/data/local/tmp/${c}`},f;try{f=await n.screenRecording.harmony.start(r,c,s),s.throwIfAborted()}catch(e){throw s.aborted?(await A(n,r,u).catch(()=>{}),s.reason):e}N(f,`start`);try{s.throwIfAborted()}catch(e){throw await A(n,r,u).catch(()=>{}),e}let m=D(o),h=!1,g=async()=>{h||=(N(await n.screenRecording.harmony.stop(r),`stop`),!0)},_=l(m,{finish:async e=>await O(n,r,e,u,g),forceCleanup:async()=>await A(n,r,u,g)});return Object.freeze({pendingHandle:new i(_),envelope:x({device:r,owner:a,input:o,descriptor:u})})}function D(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function O(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await k(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);let o=!1;try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`});return o=!0,u(n,i,!1)}finally{await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),o&&await e.screenRecording.harmony.removeMedia(t,a).catch(()=>{})}}async function k(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function A(e,t,n,r=async()=>{N(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await M(r),await M(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await M(async()=>await j(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function j(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function M(e){try{await e();return}catch(e){return e}}function N(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}const P=n(`harmonyos`),F=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function I(e){let t=_(e);return Object.freeze({owner:P,ownsDevice:e=>e.platform===`harmonyos`,bind:async n=>{let r=await t.bind(n),i=w(n.device);return Object.freeze({device:r.device,owner:P,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:F,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i}}),operations:Object.freeze({...r.operations,...i.available?T({host:e,device:n.device,owner:P,signal:n.scope.signal}):{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{I as createHarmonyPlatformRuntime};
|
|
1
|
+
import{_ as e,v as t}from"./sdk-contracts.js";import{At as n,Et as r,G as i,J as a,V as o,W as s,dt as c,ft as l,gt as u,ht as ee,lt as d,nt as f,rt as p,st as te,ut as ne}from"./sdk-batch-runner.js";import{C as re,c as m,l as h,s as ie,x as g}from"./sdk-device.js";import{c as ae,f as oe,g as se,h as ce,i as _,l as le,m as ue,n as v,p as de,r as y,s as b,t as fe,u as pe,v as me,x}from"./src3.js";import{n as S,t as he}from"./simulator-state.js";import ge from"node:path";const C=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function w(e){return h(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const _e=Object.freeze({resourceKind:p,version:1,encode:e=>({...e}),decode:e=>!ye(e.transport)||!be(e.backend)||!we(e.outputPath)||!Se(e.pidPath)||!xe(e.transport,e.backend)?ve():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function ve(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function ye(e){return e===`apple-log-stream`||e===`coredevice-console`}function be(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function xe(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function Se(e){return e===void 0||we(e)}function Ce(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return me({resourceKind:p,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:x(_e,e.descriptor)})}function we(e){return typeof e==`string`&&e.trim().length>0}const Te={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},Ee={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function De(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function Oe(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(h(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await _(async()=>y(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(C);else{i.devicectlAvailable=await _(async()=>y(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await De(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?Te:Ee;a.push(`${e.message} ${e.hint}`)}}return{backend:w(t),checks:i,notes:a}}function T(e,t){let n=E(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=E(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function ke(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,T(e.appBundleId,e.executableName)]}function Ae(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function E(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}async function je(e,t,n,r,i){Me(t),ae(e,n);let a=w(t),o=await Pe(e,t,n.appBundleId,i),s=new ee,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Ne(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let ee=Ie(e,u,l,a,n.outputPath),d={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},f=se(ee,Ce({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:d}));return c=!0,f}finally{await s[Symbol.asyncDispose]()}}function Me(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(m(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,C,{hint:C})}async function Ne(t,n,r,i,a,o){if(m(n)&&n.kind===`device`){let n=await De(t,o);if(!n.supported){let t=n.reason===`unsupported`?Te:Ee;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return o?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function Pe(e,t,n,r){if(h(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,T(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:Ae(t.id,n),allowFailure:!0};let i=await Fe(e,t,n,r);return{executable:`xcrun`,args:ke({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function Fe(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,ge.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function Ie(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return ue({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await Le([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function Le(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const D=r(`apple`),O=Object.freeze({available:!0});function Re(t){return Object.freeze({owner:D,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>k(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,D))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return ze(t,r.device,r.scope.signal)},shutdown:async()=>void 0})}function ze(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=ce({codec:_e,reattach:async(e,r)=>e.backend!==w(n)||!b(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await pe(t,e.pidPath),cleanup:async(e,r)=>e.backend===w(n)&&b(t,r.sessionId,e)?await le(t,e.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:w(n)}),appLogDoctor:async({appBundleId:e})=>await Oe(t,n,e,r),appLogStart:async e=>await je(t,n,e,D,r),...i});return Object.freeze({device:n,owner:D,facts:k(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function k(e){if(e.appleOs===`watchos`)return Be(e);let t=m(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:C}:O;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:O,appLogCleanup:O}})}function Be(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function Ve(e,t,n,r){let i=w(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=v(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(He(t,n,o)){let i=await Ue(e,t,n,a.path,r);i&&(i.dump.entries.length>0?(o=fe(i.dump,o,n.maxEntries),s.push(`Recovered ${i.dump.entries.length} iOS simulator HTTP entr${i.dump.entries.length===1?`y`:`ies`} from simctl log show (${i.lineCount} app log lines scanned).`)):i.lineCount>0&&s.push(`Recovered ${i.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return Ge(s,t,n),o.entries.length===0&&s.push(Ke(t)),Object.freeze({source:`app-log`,backend:i,dump:o,notes:Object.freeze(s)})}function He(e,t,n){return m(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Ue(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,We(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
|
|
2
|
+
`).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{dump:v(`${c.join(`
|
|
3
|
+
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function We(e){let t=e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function Ge(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(m(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function Ke(e){return m(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:m(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function A(e,n,r){if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let i;try{i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:n.invalidatedReason?!1:n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.runnerStartedAtUptimeMs!==void 0&&n.targetAppReadyUptimeMs!==void 0?{trimStartMs:Math.max(0,n.targetAppReadyUptimeMs-n.runnerStartedAtUptimeMs)}:{},targetLabel:r})}catch(e){throw t(e,`COMMAND_FAILED`)}return oe(n,{...i,...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}})}const j=Object.freeze({resourceKind:f,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Qe(e)});function qe(e){let{device:t,owner:n,input:r,descriptor:i}=e;return me({resourceKind:f,sessionId:r.sessionId,device:re(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:x(j,i)})}async function Je(e,t,n){let r=j.decode(n);return r.status!==`decoded`||!P(t,r.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:r.descriptor.backend===`simctl`?await Ye(e,r.descriptor.processes):await Xe(e,t,r.descriptor)}async function Ye(e,t){let n=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(n.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(n.every(e=>e===`missing`))return{status:`already-missing`};let r=await Promise.all(t.flatMap((t,r)=>n[r]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return r.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:r.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`}}async function Xe(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Ze(e,t,n){let r=j.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!P(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function Qe(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?F():e.backend===`simctl`?$e(e,e.outputPath):e.backend===`runner`?et(e,e.outputPath):F()}function $e(e,t){let n=rt(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:F()}function et(e,t){return!M(e.appBundleId)||!M(e.runnerSessionId)||!tt(e.runnerAuthority)||!nt(e.remotePath)?F():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function M(e){return typeof e==`string`&&e.length>0}function tt(e){return e===`local-lease`||e===`scoped-provider`}function nt(e){return e===void 0||N(e)}function N(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function P(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:m(e)?t.remotePath!==void 0&&N(t.remotePath):t.remotePath===void 0:!1}function rt(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function F(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function it(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}function at(e){return e.appleOs===`watchos`?z(`unsupported-platform-leaf`,`watchOS recording is not supported.`):m(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?z(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function ot(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await st({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Ze(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await Je(t,n,e.envelope.descriptor.body)})}async function st(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await ct(e):await lt(e)}async function ct(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await it(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0;await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.startSimulator(n,i.outputPath,a),c=s.markers;if(!c||c.length===0)throw await I(s).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted()}catch(e){throw await I(s).catch(()=>{}),e}return L({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:i.outputPath,processes:c},snapshot:R(i,`simctl recordVideo`,{},o),finish:async e=>{await s.terminate();let n=await s.wait;if(n.exitCode!==0)throw Error(`simctl recordVideo exited with code ${n.exitCode}`);return await A(t,e,`iOS recording`)},cleanup:async()=>await ft(s)})}async function lt(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>l??=ut(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0));if(!dt(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return L({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:R(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await A(t,e,n.appleOs===`macos`?`macOS recording`:`iOS recording`)),cleanup:async()=>(await u(),{status:`cleaned`})})}async function ut(e){try{return await e()}catch(e){throw t(e,`COMMAND_FAILED`)}}function dt(e,t){return e.appleOs===`macos`||!m(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function I(e){return await e.terminate(),await e.wait}async function ft(e){try{return await I(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function L(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=de(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new u(c),envelope:qe({device:t,owner:n,input:r,descriptor:i})})}function R(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.targetAppReadyUptimeMs===void 0?{}:{targetAppReadyUptimeMs:n.targetAppReadyUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}function z(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const B=12e4;async function V(e,t,n,r={}){return n.throwIfAborted(),h(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?(await H(e,t,n)!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await pt(e,t,n),await mt(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function pt(t,n,r){let i=!1;try{let a=await t.appleTools.run({tool:`simctl`,args:S(n,[`boot`,n.id]),allowFailure:!0,timeoutMs:B},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new e(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});i=!s;let c=await t.appleTools.run({tool:`simctl`,args:S(n,[`bootstatus`,n.id,`-b`]),allowFailure:!0,timeoutMs:B},r);if(c.exitCode!==0)throw new e(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode});if(await H(t,n,r)!==`Booted`)throw new e(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:n.id})}catch(e){throw i&&r.aborted&&ht(t,n),r.throwIfAborted(),e}}async function H(e,t,n){return await he(e.appleTools,t,n,15e3)}async function mt(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function ht(e,t){e.appleTools.run({tool:`simctl`,args:S(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}function gt(e){let t=o({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await V(e.host,e.device,e.signal,{onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await _t(e.host,t,n),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await Dt(e.host,t,n),finalizeApplicationClose:async t=>await Ot(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await kt(e.host,e.device,e.signal,t),configureProviderPortReverse:Nt})}async function _t(e,t,n){let r={},i=U(t.device),a=At(e,t,n,r),o=m(t.device)&&n.surface===`app`&&n.positionals.length>0&&!!n.appBundleId;i&&o&&!n.prewarmRunnerBeforeOpen&&a.schedule(),await vt(e,t,n,i,r),await yt(n,r),await bt(a,o,n.prewarmRunnerBeforeOpen);let s=a.wasAwaited();return await xt(t,n,i,r),await Ct(a,o,n.relaunch),await wt(e,t,n,i,s),await Tt(e,t,i,r),{appBundleId:n.appBundleId,timing:r}}async function vt(e,t,n,r,i){if(!Et(n,r)||!n.target)return;let a=Date.now();ie(t.device.platform)&&!r&&await e.appleApplications.stopRunnerSession(t.device.id),await s({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),i.relaunchCloseDurationMs=W(a)}async function yt(t,n){if(!l(t.runtimeHints))return;if(!t.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let r=Date.now();await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints}),n.runtimeHintsDurationMs=W(r)}async function bt(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function xt(e,t,n,r){let a=jt(t,n),o=Date.now();await i({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:a.positionals,appBundleId:t.appBundleId,execution:t.execution,...n&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),r.openDispatchDurationMs=W(o),await St(e,t,a.followUpUrl,r)}async function St(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let a={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},o=Date.now();await i({device:e.device,interactor:await e.resolveInteractor(a,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:a}),r.launchUrlDurationMs=W(o)}async function Ct(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function wt(e,t,n,r,i){!r||!n.relaunch&&!i||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}async function Tt(e,t,n,r){let i=Date.now();n&&await e.clock.sleep(300,t.signal),r.postOpenSettleDurationMs=W(i)}function Et(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}async function Dt(e,t,n){n.ensureReady&&await V(e,t.device,t.signal),ie(t.device.platform)&&!U(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await s({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),U(t.device)&&await e.clock.sleep(300,t.signal)}async function Ot(e,t,n,r){r.daemonShutdown?await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{}):r.retainRunner?(e.appleApplications.scheduleRunnerIdleStop(t.id),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{})):(await e.appleApplications.stopRunnerSession(t.id),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{}));let i=r.shutdownTarget&&U(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function kt(e,t,n,r){return await V(e,t,n),await e.appleApplications.prepareRunner(t,r,n)}function At(e,t,n,r){let i,a=!1;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=W(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function jt(e,t){let n=e.runtimeLaunchUrl?.trim(),r=e.positionals.length===1?e.positionals[0]?.trim():void 0;return!n||!r||a(r)?{positionals:e.positionals}:t&&!Mt(e)?{positionals:[r,n]}:{positionals:e.positionals,followUpUrl:n}}function Mt(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function U(e){return m(e)&&e.kind===`simulator`}function W(e){return Math.max(0,Date.now()-e)}async function Nt(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const G=Object.freeze({available:!0}),Pt=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),Ft=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),K=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),It=Object.freeze({available:!1,reason:`unsupported-device-kind`});function q(e){let t=Wt(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:Gt(e)})}function Lt(e){let{host:t,device:n,signal:r}=e,i=q(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await Rt(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await zt(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Ht(t,n,e,r),{})}:{}})}async function Rt(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Vt(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Bt(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await zt(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function zt(e,t,n,r){return await Bt(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function Bt(e,t,n,r){await V(e,t,r),J(await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:S(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:12e4},r),`Apple app install failed`)}async function Vt(e,t,n,r){await V(e,t,r);let i=await e.appleTools.run(t.kind===`simulator`?{tool:`simctl`,args:S(t,[`uninstall`,t.id,n]),allowFailure:!0}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n],allowFailure:!0},r);i.exitCode===0||Ut(`${i.stdout}\n${i.stderr}`)||J(i,`Apple app uninstall failed for ${n}`)}async function Ht(t,n,r,i){if(n.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await V(t,n,i);let a=await t.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),J(await t.appleTools.run({tool:`simctl`,args:S(n,[`push`,n.id,r.appId,a.path])},i),`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}function Ut(e){let t=e.toLowerCase();return t.includes(`not installed`)||t.includes(`not found`)||t.includes(`no such file`)}function J(t,n){if(t.exitCode!==0)throw new e(`COMMAND_FAILED`,n,{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}function Wt(e){return Kt(e)?e.kind!==`simulator`&&e.kind!==`device`?It:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Pt:G:K}function Gt(e){return Kt(e)?e.kind===`simulator`?G:Ft:K}function Kt(e){return m(e)&&e.appleOs!==`watchos`}function qt(e,t){let n=te({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),r=async r=>h(t.device)&&r.options?.surface!==void 0&&r.options.surface!==`app`?await e.snapshot.captureSurface(t.device,r.options,t.signal):await n.captureSnapshot(r);return Object.freeze({captureSnapshot:r,captureSnapshotWithCustomActions:r,captureSnapshotWithoutActiveApp:r})}const Y=r(`apple`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Jt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple appstate reads the active session state; a sessionless runtime foreground probe is unavailable.`}),Yt=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is supported only for local Android emulators.`}),Xt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS open is not supported because XCUITest cannot drive watchOS UI.`}),Zt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`}),Qt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS close is not supported because XCUITest cannot drive watchOS UI.`}),$t=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Runtime hints are supported only for local iOS-family simulators and Android devices.`}),en=$(`open is supported only for Apple simulators and devices.`),tn=$(`prepare is supported only for Apple simulators and devices.`),nn=$(`close is supported only for Apple simulators and devices.`),rn=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),an=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`shutdown is supported only for Apple simulators and Android emulators.`}),Q=$(`snapshot is supported only for Apple simulators and devices.`),on=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),sn=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`Open the app under test before capturing its snapshot.`});function $(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function cn(e){return!m(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:an}function ln(e){let t=un(e),n=dn(e),r=fn(e),i=pn(e);return ne({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:rn})}function un(e){return g(e)===`watchos`?Xt:e.kind===`simulator`||e.kind===`device`?X:en}function dn(e){return g(e)===`watchos`?Zt:e.kind===`simulator`||e.kind===`device`?X:tn}function fn(e){return g(e)===`watchos`?Qt:e.kind===`simulator`||e.kind===`device`?X:nn}function pn(e){return g(e)!==`watchos`&&m(e)&&e.kind===`simulator`?X:$t}function mn(e){return e.appleOs===`watchos`?Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app inventory is not supported.`}):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`App inventory is available only on CoreDevice-backed physical iOS devices.`}):X}function hn(e){let t=Re(e),n=async n=>{let r=await t.inspectFacts(n),i=q(n),a=at(n),o=a.available?await e.screenRecording.apple.availability(n):void 0,s=a.available&&o?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:o.hint}):a,c=n.appleOs===`watchos`?Z:X,l=h(n)||n.appleOs===`watchos`?Z:X,u=mn(n);return Object.freeze({device:r.device,operations:{...r.operations,...i,appState:Jt,networkDump:X,screenRecordingStart:s,screenRecordingReattach:s,screenRecordingCleanup:s,..._n(n),ensureReady:c,bootTarget:l,bootTargetHeadless:Yt,listApps:u,...ln(n),shutdownTarget:cn(n)}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:n,bind:async r=>{let i=await t.bind(r),a=await n(r.device),o=a.operations.screenRecordingStart;return Object.freeze({device:i.device,owner:Y,facts:a,operations:Object.freeze({...i.operations,...Lt({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await Ve(e,r.device,t,r.scope.signal),...o.available?ot({host:e,device:r.device,owner:Y,signal:r.scope.signal}):{},...a.operations.captureSnapshot.available?qt(e,{device:r.device,signal:r.scope.signal}):{},...a.operations.ensureReady.available?{ensureReady:async()=>await V(e,r.device,r.scope.signal)}:{},...a.operations.bootTarget.available?{bootTarget:async()=>await V(e,r.device,r.scope.signal)}:{},...a.operations.listApps.available?{listApps:async t=>await e.appInventory.apple.listApps(t.device,t.filter,r.scope.signal)}:{},...c(gt({host:e,device:r.device,signal:r.scope.signal}),a.operations),...a.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await i[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function gn(e){return g(e)===`watchos`?Q:e.kind===`simulator`||e.kind===`device`?X:Q}function _n(e){let t=gn(e);return d({capture:t,customActions:t.available&&m(e)&&e.kind===`simulator`?X:on,withoutActiveApp:m(e)?sn:t})}export{hn as createApplePlatformRuntime};
|
package/dist/src/runtime5.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{E as e}from"./sdk-contracts.js";import{c as t}from"./sdk-device.js";import{n,t as r}from"./simulator-state.js";const i=15e3;function a(e){return Object.freeze({canShutdownTarget:o,shutdownTarget:async(t,n)=>await s(e.appleTools,t,n)})}function o(e){return t(e)&&e.appleOs!==`watchos`&&e.kind===`simulator`}async function s(t,r,a){if(r.booted===!1)return u();a.throwIfAborted();try{let e=await t.run({tool:`simctl`,args:n(r,[`shutdown`,r.id]),allowFailure:!0,timeoutMs:i},a);a.throwIfAborted();let o=l(e);return o.success?o:await c(t,r,a)===`Shutdown`?{...o,success:!0,exitCode:0}:o}catch(t){a.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function c(e,t,n){try{return await r(e,t,n,i)}catch{return n.throwIfAborted(),null}}function l(e){let t=e.exitCode??-1;return{success:t===0,exitCode:t,stdout:e.stdout,stderr:e.stderr}}function u(){return{success:!0,exitCode:0,stdout:``,stderr:``}}export{a as createAppleShutdownRuntime};
|
package/dist/src/runtime6.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./src2.js";const t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function n(){return e(`vega`,{appLog:t,network:t})}export{n as createVegaPlatformRuntime};
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{B as t,Et as n,V as r,dt as i,gt as a,lt as o,nt as s,rt as c,st as l,ut as u}from"./sdk-batch-runner.js";import{C as d}from"./sdk-device.js";import{a as f,d as p,f as m,o as h,p as ee,v as g,x as _}from"./src3.js";import{randomUUID as v}from"node:crypto";import{setTimeout as y}from"node:timers/promises";const b=Object.freeze({resourceKind:c,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!S(e.outputPath)||!S(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function x(e){return g({resourceKind:c,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:_(b,e.descriptor)})}function S(e){return typeof e==`string`&&e.trim().length>0}function C(e){return f(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:b,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await w(e,r);return{resolvePid:async r=>await h(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>x({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function w(t,n){n.throwIfAborted(),await T(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await T(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function T(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}const E=Object.freeze({resourceKind:s,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&re(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function te(e){let{device:t,owner:n,input:r,descriptor:i}=e;return g({resourceKind:s,sessionId:r.sessionId,device:d(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:_(E,i)})}function ne(e){return E.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function re(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function ie(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function ae(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await oe({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>ne(e.envelope.descriptor.body)})}async function oe(t){let{host:n,device:r,owner:i,input:o,signal:s}=t;if(o.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);p(o,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),s.throwIfAborted(),await n.screenRecording.outputs.prepare(o.outputPath);let c=`agent-device-recording-${v()}.mp4`,l={backend:`harmony-screen-recorder`,fileName:c,remotePath:`/data/local/tmp/${c}`},u;try{u=await n.screenRecording.harmony.start(r,c,s),s.throwIfAborted()}catch(e){throw s.aborted?(await N(n,r,l).catch(()=>{}),s.reason):e}I(u,`start`);try{s.throwIfAborted()}catch(e){throw await N(n,r,l).catch(()=>{}),e}let d=D(o),f=!1,m=async()=>{f||=(I(await n.screenRecording.harmony.stop(r),`stop`),!0)},h=ee(d,{finish:async e=>await O(n,r,e,l,m),forceCleanup:async()=>await N(n,r,l,m)});return Object.freeze({pendingHandle:new a(h),envelope:te({device:r,owner:i,input:o,descriptor:l})})}function D(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function O(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await M(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await k(e,t,r,a);return m(n,{...i,...j(i.warning,o)},!1)}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function k(e,t,n,r){let i=[];return await A(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await A(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function A(e){try{return await e()}catch{return!1}}function j(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function M(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function N(e,t,n,r=async()=>{I(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await F(r),await F(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await F(async()=>await P(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function P(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function F(e){try{await e();return}catch(e){return e}}function I(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function L(t,n,r){r.throwIfAborted();let i=await t.run(n,{args:[`shell`,`aa`,`dump`,`-l`],timeoutMs:15e3},r);r.throwIfAborted();let a=R(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function R(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}function z(e){return t({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,binding:r({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const B=Object.freeze({available:!0}),V=Object.freeze({available:!1,reason:`unsupported-device-kind`}),H=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function U(e){let t=e.kind===`emulator`||e.kind===`device`?B:V;return Object.freeze({deployApp:t,materializeAppSource:H,deployMaterializedApp:H,sendPushNotification:H})}function W(e){return U(e.device).deployApp.available?Object.freeze({deployApp:async t=>await G(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function G(t,n,r,i){let a=await K(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await J(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await y(1e3,void 0,{signal:i}),await q(t,n,a,i)),{packageName:a,launchTarget:a}}async function K(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(!(r.exitCode!==0||r.stdout.trim().length===0))try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function q(t,n,r,i){let a=se((await J(t,n,[`shell`,`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await J(t,n,[`shell`,`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function se(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function J(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}const Y=n(`harmonyos`),X=Object.freeze({available:!0}),Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ce=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`}),le=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),Q=Object.freeze({available:!0}),ue=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for HarmonyOS emulators and devices.`}),de=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for HarmonyOS emulators and devices.`}),fe=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),$=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for HarmonyOS emulators and devices.`}),pe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`});function me(e){let t=he(e),n=ge(e);return u({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:Z,clearRuntimeHints:Z,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:le,configureProviderPortReverse:fe})}function he(e){return e.kind===`emulator`||e.kind===`device`?Q:ue}function ge(e){return e.kind===`emulator`||e.kind===`device`?Q:de}function _e(e){let t=C(e),n=async e=>{let n=await t.inspectFacts(e),r=U(e),i=ie(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?ce:X,networkDump:Z,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...o({capture:e.kind===`emulator`||e.kind===`device`?X:$,customActions:pe,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?X:$}),ensureReady:X,bootTarget:Z,bootTargetHeadless:Z,listApps:X,...me(e),shutdownTarget:Z}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async r=>{let a=await t.bind(r),o=await n(r.device),s=o.operations.screenRecordingStart;return Object.freeze({device:a.device,owner:Y,facts:o,operations:Object.freeze({...a.operations,...W({commands:e.commands,device:r.device,signal:r.scope.signal}),...o.operations.appState.available?{appState:async()=>await L(e.appState.harmonyos,r.device,r.scope.signal)}:{},ensureReady:async()=>({...r.device,booted:!0}),...s.available?ae({host:e,device:r.device,owner:Y,signal:r.scope.signal}):{},...o.operations.captureSnapshot.available?l({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},listApps:async t=>await e.appInventory.harmonyos.listApps(t.device,t.filter,r.scope.signal),...i(z({host:e.localInteractors,device:r.device,signal:r.scope.signal}),o.operations)}),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{_e as createHarmonyPlatformRuntime};
|
package/dist/src/runtime7.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{At as t,B as n,Et as r,V as i,dt as a,lt as o,ot as s,ut as c}from"./sdk-batch-runner.js";function l(e){return n({owner:`Linux`,openTargetIdentity:`app-name`,binding:i({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const u=Object.freeze({available:!0}),d=r(`linux`),f=C(`unsupported-platform-leaf`),p=C(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),m=C(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),h=C(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),g=C(`unsupported-device-kind`,`open is supported only for the Linux desktop device.`),_=C(`unsupported-device-kind`,`close is supported only for the Linux desktop device.`),v=C(`unsupported-device-kind`,`snapshot is supported only for the Linux desktop device.`),y=C(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`);function b(n){return Object.freeze({owner:d,ownsDevice:e=>e.platform===`linux`,inspectFacts:async e=>x(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,d))throw new e(`UNSUPPORTED_OPERATION`,`Linux runtime owner identity does not match`);if(r.device.platform!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`Linux runtime cannot bind this device`);let i=x(r.device),o=l({host:n.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:d,facts:i,operations:Object.freeze({...a(o,i.operations),...i.operations.captureSnapshot.available?S(n,r):{}}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function x(e){let t=e.kind===`device`?u:g,n=e.kind===`device`?u:_,r=s(e,d,{appLog:f,network:f,snapshot:v,readiness:f,lifecycle:c({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:p,clearRuntimeHints:p,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:m,configureProviderPortReverse:h})});return Object.freeze({device:r.device,operations:{...r.operations,...o({capture:e.kind===`device`?u:v,customActions:y,withoutActiveApp:e.kind===`device`?u:v})}})}function S(e,t){let n=async n=>await e.snapshot.captureSurface(t.device,n.options,t.scope.signal);return Object.freeze({captureSnapshot:n,captureSnapshotWithCustomActions:n,captureSnapshotWithoutActiveApp:n})}function C(e,t){return Object.freeze(t===void 0?{available:!1,reason:e}:{available:!1,reason:e,hint:t})}export{b as createLinuxPlatformRuntime};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{At as t,B as n,Et as r,V as i,dt as a,ot as o,ut as s}from"./sdk-batch-runner.js";function c(e){return n({owner:`Vega`,openTargetIdentity:`app-name`,binding:i({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const l=r(`vega`),u=Object.freeze({available:!0}),d=y(`unsupported-platform-leaf`),f=y(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),p=y(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),m=y(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),h=y(`unsupported-device-kind`,`open currently supports only Vega Virtual Devices.`),g=y(`unsupported-device-kind`,`close currently supports only Vega Virtual Devices.`);function _(n){return Object.freeze({owner:l,ownsDevice:e=>e.platform===`vega`,inspectFacts:async e=>v(e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,l))throw new e(`UNSUPPORTED_OPERATION`,`Vega runtime owner identity does not match`);if(r.device.platform!==`vega`)throw new e(`UNSUPPORTED_PLATFORM`,`Vega runtime cannot bind this device`);let i=v(r.device),o=c({host:n.localInteractors,device:r.device,signal:r.scope.signal});return Object.freeze({device:r.device,owner:l,facts:i,operations:Object.freeze(a(o,i.operations)),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function v(e){let t=e.kind===`emulator`&&e.target===`tv`,n=t?u:h,r=t?u:g;return o(e,l,{appLog:d,network:d,snapshot:d,readiness:d,lifecycle:s({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:f,clearRuntimeHints:f,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:p,configureProviderPortReverse:m})})}function y(e,t){let n={available:!1,reason:e,...t===void 0?{}:{hint:t}};return Object.freeze(n)}export{_ as createVegaPlatformRuntime};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{At as t,B as n,Et as r,V as i,dt as a,gt as o,lt as s,nt as c,st as l,ut as u}from"./sdk-batch-runner.js";import{C as d}from"./sdk-device.js";import{d as f,f as p,p as m,v as h,x as g}from"./src3.js";const _=Object.freeze({resourceKind:c,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function v(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await y({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>b()}}:{available:!1,operations:{}}}async function y(t){let{host:n,transport:r,device:i,owner:a,input:s,signal:l}=t;if(s.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!s.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);f(s,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),l.throwIfAborted(),await n.screenRecording.outputs.prepare(s.outputPath);let u=!1;try{await r.start(s.outputPath,l),u=!0,l.throwIfAborted()}catch(e){throw u&&await r.stop().catch(()=>{}),l.throwIfAborted(),e}let v=!1,y=async()=>{v||=(await r.stop(),!0)},b=m({backend:`agent-browser`,outPath:s.outputPath,...s.clientOutputPath===void 0?{}:{clientOutPath:s.clientOutputPath},startedAt:Date.now(),scope:s.scope,showTouches:!1,recordOnlySession:s.recordOnlySession,...s.activeSessionApp===void 0?{}:{activeSessionApp:s.activeSessionApp},gestureEvents:[]},{finish:async e=>(await y(),p(e,await n.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`}),!1)),forceCleanup:async()=>{try{return await y(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new o(b),envelope:h({resourceKind:c,sessionId:s.sessionId,device:d(i),owner:a,fence:s.fence,lifecycle:`open`,descriptor:g(_,{backend:`agent-browser`,outputPath:s.outputPath})})})}function b(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}function x(e){return n({owner:`web`,openTargetIdentity:`app-name`,binding:i({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const S=r(`web`),C=Object.freeze({available:!0}),w=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),T=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`}),E=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),D=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),O=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`apps is not supported on web targets.`}),k=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),A=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),j=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for web browser devices.`}),M=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for web browser devices.`}),N=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`});function P(e){let t=F(e),n=I(e);return u({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:D,clearRuntimeHints:D,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:A,configureProviderPortReverse:N})}function F(e){return e.kind===`device`?C:j}function I(e){return e.kind===`device`?C:M}function L(n){return Object.freeze({owner:S,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>z(e,await n.networkTransports.resolve(e),(await v({host:n,device:e,owner:S,signal:new AbortController().signal})).available),bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,S))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(r.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${r.device.platform}`);let i=await n.networkTransports.resolve(r.device),a=await v({host:n,device:r.device,owner:S,signal:r.scope.signal});return R(n,r.device,r.scope.signal,i,a,z(r.device,i,a.available))},shutdown:async()=>void 0})}function R(e,t,n,r,i,o){let s=r.dump,c={...s?{networkDump:async e=>{let t=await s({maxEntries:e.maxEntries,include:e.include},n);return Object.freeze({source:`provider`,...t})}}:{},...i.operations,...o.operations.captureSnapshot.available?l({device:t,signal:n,resolveInteractor:e.localInteractors.resolve}):{},...a(x({host:e.localInteractors,device:t,signal:n}),o.operations)};return Object.freeze({device:t,owner:S,facts:o,operations:Object.freeze(c),[Symbol.asyncDispose]:async()=>void 0})}function z(e,t,n){let r=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`});return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:w,appLogDoctor:w,appLogStart:w,appLogReattach:w,appLogCleanup:w,appState:k,networkDump:t.dump?C:r,screenRecordingStart:n?C:T,screenRecordingReattach:n?C:T,screenRecordingCleanup:n?C:T,...s({capture:e.kind===`device`?C:j,customActions:E,withoutActiveApp:e.kind===`device`?C:j}),ensureReady:D,bootTarget:D,bootTargetHeadless:D,listApps:O,deployApp:D,materializeAppSource:D,deployMaterializedApp:D,sendPushNotification:D,shutdownTarget:D,...P(e)}})}export{L as createWebPlatformRuntime};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";function t(t,n=e=>e){let r=new e;return{resolve(e){return e?n(e):r.getStore()??t},async run(e,t){return e?await r.run(n(e),t):await t()},hasScope(){return!!r.getStore()}}}export{t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{c as t}from"./sdk-device.js";import{promises as n}from"node:fs";async function r(t){let r=await n.open(t,`r`);try{let t=Buffer.alloc(24),{bytesRead:n}=await r.read(t,0,t.length,0);if(n<t.length||t.toString(`ascii`,12,16)!==`IHDR`)throw new e(`COMMAND_FAILED`,`Screenshot file is not a valid PNG`);return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}finally{await r.close()}}function i(t,n){if(!(n===void 0||c(t)))throw new e(`UNSUPPORTED_OPERATION`,`--pixel-density is currently supported only on iOS-family simulators`)}function a(e,t,n){let r=s(n);if(t!==r)return{width:Math.max(1,Math.round(e.width/t*r)),height:Math.max(1,Math.round(e.height/t*r))}}async function o(e){let t=c(e.device),n;try{n=await r(e.path)}catch(e){if(t)throw e;return{}}let i={width:n.width,height:n.height};if(!t||e.scale!==void 0&&e.scale!==1)return i;let a=s(e.requestedPixelDensity);return{...i,logicalWidth:Math.round(n.width/a),logicalHeight:Math.round(n.height/a),pixelDensity:a}}function s(e){return e??1}function c(e){return t(e)&&e.kind===`simulator`}export{r as i,a as n,o as r,i as t};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{E as e,_ as t,h as n}from"./sdk-contracts.js";import{$ as r,At as i,Et as a,H as o,S as s,Tt as c,U as l,jt as u,lt as d,n as ee,pt as te,t as ne}from"./version.js";import{Gn as f,It as re,Kn as ie,Lt as ae,Rt as oe,ct as se,gt as ce,qn as le,ut as p,x as ue,zt as de}from"./sdk-batch-runner.js";import{_ as fe,i as pe,r as me,t as he}from"./sdk-device.js";import{$t as ge,Xt as m,Yt as _e,gn as ve,qt as ye,rn as be}from"./prepare-kind.js";import{t as xe}from"./device.js";import{N as h,j as g}from"./sdk-android-adb.js";import{n as Se,t as Ce}from"./path-resolution.js";import{c as we,d as Te,n as Ee,s as De}from"./host-process.js";import _ from"node:path";import Oe from"node:crypto";import v from"node:fs";import{StringDecoder as ke}from"node:string_decoder";function y(e){return e.startsWith(`@`)?n(e)?.base??e:e}const Ae=/^-?\d+(\.\d+)?$/,je=/^[^\s"\\]+$/,Me=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Ne=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Pe=new Map([[`--pointer-count`,`pointerCount`]]),Fe=new Map([[`--delay-ms`,`delayMs`]]);function b(e){return e===`click`||e===`press`}function Ie(e){return b(e)||e===`longpress`}function Le(e){return e===`type`||e===`fill`}function x(e){return ze(e,Be)}function Re(e){return JSON.stringify(e)}function S(e){return ze(e,Ve)}function ze(e,t){return t(e)?e:Re(e)}function Be(e){return Ve(e)&&e.startsWith(`@`)||Ae.test(e)}function Ve(e){return je.test(e)}const He=new Set([`fill`,`type`]);function Ue(e){if(!He.has(e.command)){let t=(e.positionals??[]).map(e=>x(e));return[e.command,...t].join(` `)}let t=We(e).map(e=>x(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function We(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&Ae.test(n)&&Ae.test(t[1]??``)?[n,t[1]]:[n]}function C(e,t){let n=t.flags??{};if(b(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}Le(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Ge(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,S(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,S(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,S(t.launchUrl)))}function Ke(e,t){let[n,...r]=t.positionals??[];n&&e.push(S(n));for(let t of r)e.push(x(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function qe(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,x(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Je(e,t){for(let n of t.positionals??[])e.push(x(n));i(e,t.flags)}function Ye(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(S(t));Ge(e,t.flags)}function Xe(e,t){for(let n of t.positionals??[])e.push(x(t.command===`wait`?y(n):n));C(e,t)}function Ze(e,t){let n=[],r={},i=b(e)?Me:e===`swipe`?Ne:e===`gesture`?Pe:Le(e)?Fe:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(b(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(b(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=$e(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function Qe(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=$e(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function $e(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function et(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function tt(e,t){for(let n of t.positionals??[])e.push(x(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),Ge(e,t.runtime)}function nt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=Qe(t);return{positionals:r.positionals,flags:n,runtime:rt(r.flags)?r.flags:void 0}}function rt(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const it=/^[A-Z_][A-Z0-9_]*$/,at=new Set(me.filter(e=>e!==`web`)),ot=new Set([`mobile`,`tv`,`desktop`]);function st(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,s,c=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,l]of i.entries()){let i=l.trim();if(i.length===0){s&&c(s,e,`is blank`);continue}if(i.startsWith(`#`)){let t=oe(i);if(t.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=de(i);if(n.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`single`,evidence:n.evidence,line:e+1};continue}s&&c(s,e,`is a comment`);continue}if(lt(i)){if(s&&c(s,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let u=pt(l);if(!u){s&&c(s,e,`did not parse as an action`);continue}let d=o(u.command,u.positionals??[],`line ${e+1}`);if(d)throw new t(`INVALID_ARGS`,d);s&&=(s.kind===`single`?u.targetEvidence=s.evidence:u.targetEvidences=s.evidence,void 0),n.push(u),r.push(e+1),a=!0}if(s)throw new t(`INVALID_ARGS`,`${s.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${s.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function ct(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(lt(t)){ft(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&at.has(e)&&w(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&ot.has(e)&&w(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&w(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&w(n,`retries`,Math.floor(e))}}return n}function lt(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function ut(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!it.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:dt(r.slice(i+1),n)}}function dt(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function ft(e,n,r){let{key:i,value:a}=ut(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function w(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function pt(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[r,...i]=ht(n);if(r===void 0||r===`context`)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if(r===`snapshot`){a.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if(t===`-i`){a.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){a.flags.snapshotRaw=!0;continue}if(t===`--force-full`){a.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<i.length){a.flags.snapshotScope=i[e+1],e+=1;continue}if(t===`--backend`&&e+1<i.length){e+=1;continue}}}return a}if(r===`open`){let e=nt(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if(r===`runtime`){let e=Qe(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(b(r)){let e=Ze(r,i);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(t===void 0)return a;if(t.startsWith(`@`))return a.positionals=[y(t)],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let n=e.positionals[0],o=e.positionals[1];return T(n)&&T(o)&&e.positionals.length>=2?(a.positionals=[n,o],a):(a.positionals=[e.positionals.join(` `)],a)}if(r===`fill`){let e=Ze(r,i);if(Object.assign(a.flags,e.flags),!mt(e.positionals))return a.positionals=e.positionals,a;let[t,n,...o]=e.positionals;if(T(t)&&T(n))return a.positionals=[t,n,o.join(` `)],a;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=y(s);return l.length>0?(a.positionals=[e,l.join(` `)],a.result={refLabel:c},a):(a.positionals=[e,c],a)}return a.positionals=[s,[c,...l].join(` `)],a}if(r===`get`){let e=i[0],t=i[1];return e===void 0||t===void 0?(a.positionals=i,a):t.startsWith(`@`)?(a.positionals=[e,y(t)],i[2]&&(a.result={refLabel:i[2]}),a):(a.positionals=[e,i.slice(1).join(` `)],a)}if(r===`swipe`||r===`type`||r===`gesture`){let e=Ze(r,i);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if(r===`record`){let e=[];for(let n=0;n<i.length;n+=1){let r=i[n];if(r===c.cliToken)throw new t(`INVALID_ARGS`,c.migration.record);if(r===`--hide-touches`){a.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<i.length){let e=Number(i[n+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<i.length){let e=i[n+1],t=be(e);t!==void 0&&(a.flags.quality=t),n+=1;continue}e.push(r)}return a.positionals=e,a}if(r===`screenshot`){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=u({args:i,index:t,flags:a.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return a.positionals=e,a}return a.positionals=r===`wait`||r===`longpress`?i.map(e=>y(e)):i,a}function mt(e){return e.length>=2}function T(e){return e?!Number.isNaN(Number(e)):!1}function ht(e){let t=[],n=0;for(;n<e.length&&(n=gt(e,n),!(n>=e.length));){let r=e[n]===`"`?_t(e,n):vt(e,n);t.push(r.value),n=r.nextCursor}return t}function gt(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function _t(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function vt(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function yt(e,t={}){let n=[e.command];return e.command===`snapshot`?qe(n,e):e.command===`open`?tt(n,e):e.command===`runtime`?Ye(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?Ke(n,e):e.command===`screenshot`?Je(n,e):Xe(n,e),n.join(` `)}function bt(e){return e.targetEvidences?[re(e.targetEvidences)]:e.targetEvidence?[ae(e.targetEvidence)]:[]}async function xt(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function St(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function Ct(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}const wt=`/agent-device`,Tt=`x-agent-device-tenant`;function Et(e){return Dt(e,wt)}function Dt(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ot(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function kt(e){let t=e?.trim();return t?{[Tt]:t}:{}}const E={kind:`none`};function D(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function At(e){return e.kind===`repair`?{...e,status:`armed`}:e}function jt(e){return e.kind===`none`?void 0:e.target}function Mt(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Nt(e){return e.kind===`authoring`&&e.status===`aborted`}function Pt(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function Ft(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function It(e){return{kind:`authoring`,status:`armed`,target:D(void 0,e)}}function Lt(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Rt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function zt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:D(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function Bt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Vt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Ht(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function Ut(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function Wt(e){return e.kind===`repair`?e.boundary:void 0}function Gt(e){return e.kind===`repair`?e.sourcePath:void 0}function Kt(e){return e.kind===`repair`&&e.status!==`committed`}function qt(e){let t=jt(e);return t?.kind===`explicit`?t.path:void 0}function Jt(e){return jt(e)?.force===!0}function O(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function k(e,t){return Se(e,{cwd:t})}function A(e){return e?.scriptPublication??E}function Yt(e){let t=A(e);return t.kind===`authoring`&&t.status===`armed`}function Xt(e,t){e.scriptPublication=It({path:t.path===void 0?void 0:k(t.path),force:t.force===!0})}function Zt(e){e.scriptPublication=Lt(A(e))}function Qt(e){return Pt(A(e))}function $t(e,t){if(!t.saveScript||Nt(A(e)))return;let n={path:typeof t.saveScript==`string`?k(t.saveScript):void 0,force:t.force===!0},r=A(e);if(r.kind===`repair`){e.scriptPublication=zt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:D(r.target,n)};return}e.scriptPublication=It(n)}function en(e,t){let n=A(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:D(n.target,{path:t.explicitPath===void 0?void 0:k(t.explicitPath),force:t.liveForce===!0})})}function tn(e,t){e.scriptPublication=Rt(A(e),t)}function nn(e,t){let n=A(e);n.kind===`authoring`&&(e.scriptPublication=Rt(n,t))}function rn(e,t){return t===!0||Jt(A(e))}function an(e){return Ft(A(e))}function j(e){return e?.scriptPublication??E}function on(e,t){let n=j(e);e.scriptPublication=zt(n,{requested:{path:typeof t.saveScript==`string`?k(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function sn(e){e.scriptPublication=At(j(e))}function cn(e){e.scriptPublication=Bt(j(e))}function ln(e,t){e.scriptPublication=Vt(j(e),t)}function un(e){e.scriptPublication=Ut(j(e))}function dn(e,t){let n=j(e);return n.kind===`repair`&&n.closeReceipt===t}function fn(e){return j(e).kind===`repair`}function pn(e){return Kt(j(e))}function M(e){return Wt(j(e))}function mn(e){return Gt(j(e))}function N(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const hn=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function gn(e){if(e!==e.trim()||!it.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function _n(e){return`\${${e}}`}function vn(e){let t=hn.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const yn=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),bn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),xn=new Set([`cost`,`evidence`,`resolution`,`settle`]),Sn=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),Cn=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function wn(e,t,n){if(!e)return e;let r=jn(e.selectorChain);return{...Dn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!En(e,t))}:{}}}function Tn(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function En(e,t){return ce(e,t)}function Dn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[yn.has(e)?e:F(e,t,n),On(r,e,t,n)]))}function On(e,t,n,r){return typeof e==`string`&&bn.has(t)?e:t===`selectorChain`&&An(e)?kn(e,n):P(e,n,r,xn.has(t)?t:void 0)}function P(e,t,n,r){if(typeof e==`string`)return r&&Cn.has(r)?e:F(e,t,n);if(Array.isArray(e))return e.map(e=>P(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Sn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:F(e,t,n),P(a,t,n,o?`${r}.${e}`:void 0)]}))}function kn(e,t){return e.filter(e=>!En(e,t))}function F(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function An(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function jn(e){return An(e)?e:void 0}function Mn(e,t){if(t.flags?.noRecord||Ln(e,t))return;t.flags&&$t(e,t.flags);let n=Nn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:zn(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),g({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Nn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=_n(gn(e.flags.recordAs)),n=N({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:Pn(e.positionals,t),result:wn(e.result,n,t),targetEvidence:Tn(e.targetEvidence,n,t)}}function Pn(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Fn=new Set([`snapshot`,`get`,`is`,`find`]);function In(e){return e.internal?.replayPlanStep===!0?!1:Fn.has(e.command)}function Ln(e,t){return!t.interactiveObservation||M(e)===void 0?!1:t.flags?.record!==!0}const Rn=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...a,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function zn(e){if(!e)return{};let t={};for(let n of Rn)e[n]!==void 0&&(t[n]=e[n]);return t}function Bn(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())ue({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Kn))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Vn(e){for(let n of e){if(Hn(n)){Un(n);continue}let e=qn(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ue(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!p(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Hn(e){return Wn(e)!==void 0}function Un(e){let n=Wn(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!p(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Wn(e){return e.command===`gesture`?l(e.positionals):void 0}function Gn(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Kn(e){if(e.command!==`wait`)return!1;let t=se(e.positionals);return t?.kind!==`selector`||!p(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function qn(e){if(e.command===`get`)return e.positionals[1];if(Ie(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Jn(t)&&Jn(n)?void 0:t}}function Jn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Yn(e){let t=e.scriptPublication??E;return t.kind===`repair`?t.status===`committed`?!0:!Mt(t):!1}function Xn(e){return Pt(e.scriptPublication??E)?Yn(e):!0}var Zn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=fn(e),r=t?.publication===`active`,i;try{if(Xn(e))return{written:!1};let a=Qn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=_.dirname(i);return v.existsSync(o)||v.mkdirSync(o,{recursive:!0}),tr({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Ht(e.scriptPublication??E)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return $n({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=qt(e.scriptPublication??E);if(t)return k(t);let n=O(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return _.join(this.sessionsDir,`${n}-${r}.ad`)}};function Qn(e,t){let n=nr(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Bn(n),{script:fr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function $n(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(g({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:er(r,i)};if(o)return{written:!1,error:Gn(r,i)};if(r instanceof t)throw r;return{written:!1}}function er(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function tr(e){let{scriptPath:n,script:r,force:i}=e,a=_.dirname(n),o=_.join(a,`.${_.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);v.writeFileSync(o,r);try{if(i){v.renameSync(o,n);return}v.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{v.rmSync(o,{force:!0})}}function nr(e,t={}){let n=M(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=ar(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&rr(n);let o=dr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Vn(a),a}function rr(e){let n=e.command===`gesture`?l(e.positionals??[]):void 0;if(n){ir(n);return}if(!I(e.command))return;let r=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function ir(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function ar(e){let t=or(e);if(!(!t||!I(e.command)))return b(e.command)?{...e,positionals:[t]}:e.command===`longpress`?cr(e,t):e.command===`fill`?sr(e,t):lr(e,t)}function or(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function I(e){return Ie(e)||e===`fill`||e===`get`}function sr(e,t){let n=N(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function cr(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):ur(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function lr(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function ur(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function dr(e,t){if(!I(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function fr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${fe(e.device)} device=${Re(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...bt(e)),r.push(pr(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function pr(e){return mr([e.command],e)||yt(e)}function mr(e,t){if(b(t.command))return hr(e,t);if(t.command===`fill`)return gr(e,t);if(t.command===`get`)return _r(e,t)}function hr(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(x(y(n))),L(e,t),C(e,t),e.join(` `);if(t.positionals.length===1)return e.push(x(n)),C(e,t),e.join(` `)}}function gr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(x(y(n))),L(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(x(r)),C(e,t),e.join(` `)}function _r(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(x(n)),e.push(x(y(r))),r.startsWith(`@`)&&L(e,t),e.join(` `)}function L(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(x(n))}const vr=[`status`,`get`,`dismiss`,`enter`,`return`];function R(e){return vr.includes(e)}const yr=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],br={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function xr(e,t){let n=t??{};switch(e.command){case m.devices:return Sr(n.devices);case m.apps:return Cr(n.apps,e.flags?.appsFilter);case m.boot:return wr(`Booted`,n,!0);case m.shutdown:return wr(`Shut down`,n,!1);case m.install:return Tr(`Installed`,n);case m.reinstall:return Tr(`Reinstalled`,n);case m.screenshot:return Er(e,n);default:return{}}}function Sr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Or(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Rr(`Found ${t.length} ${zr(`device`,t.length)}`,i.map(e=>Fr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Cr(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=B(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Rr(`Found ${n.length} ${zr(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function wr(e,t,n){let r=kr(t);if(!r)return{};let i={device:r,...Pr(t),booted:n};return{summary:`${e} ${Fr(i,!1)}`,details:i}}function Tr(e,t){let n=B(t.appName),r=B(t.bundleId),i=Lr(t,[`packageName`,`package`]),a=B(t.platform),o=B(t.launchTarget),s=Lr(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Ir(n,s);if(!c)return{};let l={};return z(l,`appName`,n),z(l,`bundleId`,r),z(l,`packageName`,i),z(l,`platform`,a),o!==s&&z(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Er(e,t){let n=Dr(e,t);return n?{details:{requestedFileName:n}}:{}}function Dr(e,t){let n=K(e.meta?.clientArtifactPaths?.path)??K(t.path);if(n)return G(n)}function Or(e){if(!f(e))return;let t=kr(e);if(t)return{name:t,...Pr(e)}}function kr(e){let t=Lr(e,[`name`,`deviceName`,`device`]);return!t||!Ar(e,t)?t:Mr(e)}function Ar(e,t){let n=jr(t);return yr.some(t=>{let r=B(e[t]);return r!==void 0&&jr(r)===n})}function jr(e){return e.toLowerCase()}function Mr(e){let t=B(e.appleOs),n=B(e.platform),r=B(e.kind),i=Nr(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Nr(e,t){let n=e??t;if(!(!n||!Object.hasOwn(br,n)))return br[n]}function Pr(e){let t=B(e.platform),n=B(e.appleOs),r=B(e.kind),i=B(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Fr(e,t){let n=B(e.name)??B(e.device)??`device`,r=B(e.platform),i=B(e.appleOs),a=[r,i===r?void 0:i,B(e.kind),B(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Ir(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function Lr(e,t){for(let n of t){let t=B(e[n]);if(t)return t}}function z(e,t,n){n&&(e[t]=n)}function Rr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function zr(e,t){return t===1?e:`${e}s`}function B(e){let t=K(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function V(e){return B(e)}function H(e){return typeof e==`boolean`?e:void 0}function U(e,t){let n=V(e);return n&&t.includes(n)?n:void 0}function W(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function G(e){let t=K(e);return t?B(t.split(/[\\/]/).at(-1)):void 0}function K(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Br=[`up`,`down`,`left`,`right`],Vr=[`top`,`bottom`];function Hr(e){return`${e.command===m.reinstall?`Reinstalled`:`Installed`} ${Kr(e.result??{})??`app`}`}function Ur(e){let t=e.result??{};switch(e.command){case m.scroll:return Jr(t);case m.screenshot:return Zr(t);case m.home:return`Went home`;case m.back:return $r(t);case m.appSwitcher:return`Opened app switcher`;case m.orientation:return ei(t);case m.viewport:return ti(t);case m.clipboard:return ni(t);case m.keyboard:return ri(t);case m.tvRemote:return oi(t);case m.gesture:return si(t);case m.swipe:return ci(t);case m.trace:return ui(`trace`,e);case m.record:return ui(`recording`,e);default:return}}function Wr(e){let t=e.result??{};switch(e.command){case m.scroll:return W({direction:U(t.direction,Br),edge:U(t.edge,Vr),passes:q(t.passes),amount:q(t.amount),pixels:q(t.pixels),durationMs:q(t.durationMs),x1:q(t.x1),y1:q(t.y1),x2:q(t.x2),y2:q(t.y2)});case m.screenshot:return W({requestedFileName:Qr(t)});case m.back:return W({mode:U(t.mode,te)});case m.orientation:return W({orientation:U(t.orientation,xe)});case m.viewport:return W({width:q(t.width),height:q(t.height)});case m.clipboard:return W({action:U(t.action,[`read`,`write`])});case m.keyboard:return ai(t);case m.tvRemote:return W({button:U(t.button,s),durationMs:q(t.durationMs)});case m.gesture:case m.swipe:return li(t);case m.trace:case m.record:return W({action:U(t.action,[`start`,`stop`]),fileName:fi(e),showTouches:H(t.showTouches)});default:return{}}}function Gr(e,t){if(e.command!==m.screenshot)return t;let n=Dr(e,t);return n?{...t,requestedFileName:n}:t}function Kr(e){let t=V(e.appName),n=pi(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??qr(e)}function qr(e){let t=V(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Jr(e){let t=U(e.direction,Br),n=U(e.edge,Vr),r=q(e.passes);return n?Yr(n,r):t?Xr(t,e):`Scrolled`}function Yr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Xr(e,t){let n=q(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=q(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Zr(e){let t=Qr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Qr(e){return G(e.requestedFileName)??G(e.path)}function $r(e){return U(e.mode,te)===`system`?`Went back using system navigation`:`Went back`}function ei(e){let t=U(e.orientation,xe);return t?`Rotated to ${t}`:`Changed orientation`}function ti(e){let t=q(e.width),n=q(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ni(e){let t=U(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ri(e){let t=K(e.action);if(!t||!R(t))return`Used keyboard`;if(t===`dismiss`)return ii(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=H(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ii(e){return H(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function ai(e){let t=K(e.action);return W({action:t&&R(t)?t:void 0,platform:U(e.platform,[`ios`,`android`]),visible:H(e.visible),wasVisible:H(e.wasVisible),dismissed:H(e.dismissed),attempts:q(e.attempts),mechanism:U(e.mechanism,[`dismissKey`])})}function oi(e){let t=U(e.button,s);return t?`Pressed TV remote ${t}`:`Used TV remote`}function si(e){let t=U(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function ci(e){let t=q(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function li(e){return W({kind:U(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:q(e.durationMs),pointerCount:q(e.pointerCount),x1:q(e.x1),y1:q(e.y1),x2:q(e.x2),y2:q(e.y2),count:q(e.count),pauseMs:q(e.pauseMs),pattern:U(e.pattern,[`one-way`,`ping-pong`]),scale:q(e.scale)})}function ui(e,t){let n=di(e,U(t.result?.action,[`start`,`stop`])),r=fi(t);return r?`${n} ${r}`:n}function di(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function fi(e){let t=e.result??{};return G(t.requestedFileName)??G(t.outPath)??G(t.path)??G(e.positionals[1])}function pi(e,t){for(let n of t){let t=V(e[n]);if(t)return t}}function mi(e){switch(e.command){case m.open:return`Opened ${J(e)??`session`}`;case m.close:return`Closed ${V(e.result?.session)??`session`}`;case m.click:case m.press:return`Tapped ${J(e)??`target`}`;case m.longPress:return`Long pressed ${J(e)??`target`}`;case m.fill:return`Filled ${J(e)??`target`}`;case m.type:return`Typed text`;case m.install:case m.reinstall:case _e.installSource:return Hr(e);default:return Ur(e)??`Ran ${e.command}`}}function hi(e){return W({command:e.command,positionals:wi(e),flags:Fi(e),...gi(e),..._i(e),...vi(e),...Wr(e)})}function gi(e){if(!yi(e.command))return{};let t=e.result??{};return W({ref:Z(t),targetLabel:J(e),selectorChainLength:Mi(t.selectorChain)?.length,x:q(t.x),y:q(t.y),x2:q(t.x2),y2:q(t.y2),durationMs:q(t.durationMs)})}function _i(e){if(!bi(e.command))return{};let t=e.result??{};return W({platform:U(t.platform,pe),target:U(t.target,he),appName:V(t.appName),appBundleId:V(t.appBundleId),bundleId:V(t.bundleId),packageName:V(t.packageName),launchTarget:V(t.launchTarget)})}function vi(e){let t=e.result??{};return e.command===m.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==m.wait&&e.command!==m.find&&e.command!==m.get&&e.command!==m.is?{}:W({waitedMs:q(t.waitedMs),found:H(t.found)})}function yi(e){return e===m.click||e===m.press||e===m.longPress||e===m.focus||e===m.fill}function bi(e){return e===m.open||e===m.install||e===m.reinstall||e===_e.installSource}function J(e){let t=e.result??{};return xi(t)??Si(t)??Ci(t)??Ai(e.positionals[0])}function xi(e){let t=Z(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Si(e){let t=q(e.x),n=q(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Ci(e){return V(e.appName)??V(e.appBundleId)??V(e.bundleId)??V(e.packageName)}function wi(e){if(e.positionals.length!==0)return e.command===m.type?[X(`text`)]:e.command===m.fill?Ti(e):e.command===m.find?Ei(e):e.command===m.clipboard?Di(e):e.command===m.push?Oi(e,`app`,`payload`):e.command===m.triggerAppEvent?Oi(e,`event`,`payload`):e.positionals.map(Y)}function Ti(e){let t=X(`text`),n=e.result??{},r=Z(n);if(r)return[`@${r}`,t];if(V(n.selector))return[X(`target`),t];let i=q(n.x),a=q(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Ei(e){let t=+!!ji(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],X(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,X(`text`)]:[...r,...e.positionals.slice(n).map(ki)]:r}function Di(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,X(`text`)]:e.positionals.map(Y)}function Oi(e,t,n){let[r,i,...a]=e.positionals;return[...r?[X(t)]:[],...i?[X(n)]:[],...a.map(Y)]}function ki(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:Y(e)}function Y(e){return Ai(e)??X(`arg`)}function Ai(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function X(e){return`<${e}>`}function ji(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Mi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Ni={enums:[{source:`platform`,values:me},{source:`target`,values:he}]},Pi={[m.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:ye}]},[m.click]:Ii(),[m.press]:Ii(),[m.longPress]:Ii(),[m.fill]:Li(),[m.type]:Li(),[m.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[m.gesture]:Ri(),[m.swipe]:Ri(),[m.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[m.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[m.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:te}]},[m.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ge}]},[m.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[m.boot]:{booleans:[{source:`headless`}]},[m.close]:{booleans:[{source:`shutdown`}]}};function Fi(e){let t=e.flags??{},n={},r=Object.hasOwn(Pi,e.command)?Pi[e.command]:void 0;return zi(n,t,Ni),zi(n,t,r),Object.keys(n).length>0?n:void 0}function Ii(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:d}]}}function Li(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Ri(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:r}]}}function zi(e,t,n){n&&(Bi(e,t,n.booleans??[]),Vi(e,t,n.numbers??[]),Hi(e,t,n.enums??[]))}function Bi(e,t,n){for(let r of n)Ui(e,r.output??r.source,t[r.source])}function Vi(e,t,n){for(let r of n)Wi(e,r.output??r.source,t[r.source])}function Hi(e,t,n){for(let r of n)Gi(e,r.output??r.source,t[r.source],r.values)}function Z(e){let t=V(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Ui(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Wi(e,t,n){let r=q(n);r!==void 0&&(e[t]=r)}function Gi(e,t,n,r){let i=U(n,r);i!==void 0&&(e[t]=i)}const Q=new Map,Ki=new Set;function qi(e){return _.join(e,`events.ndjson`)}function Ji(e){return e.command!==m.events}function Yi(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Zi(t,`${JSON.stringify(i)}\n`)}async function Xi(e){await(e?Q.get(e):Promise.all(Q.values()))}function Zi(e,t){let n=(Q.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Qi(e),await v.promises.appendFile(e,t,`utf8`)}).catch(t=>{g({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Q.get(e)===n&&Q.delete(e)});Q.set(e,n)}async function Qi(e){let t=_.dirname(e);if(!Ki.has(t))try{await v.promises.mkdir(t,{recursive:!0}),Ki.add(t)}catch(t){throw g({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function $i(e,t,n){Yi(e,t,{kind:`action.recorded`,requestId:h().requestId,command:n.command,summary:mi(n),details:hi(n)})}function ea(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??h().requestId,command:t.command,summary:`Started ${t.command}`}}function ta(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=xr(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function na(e,t={}){let n=sa(t.cursor),r=ca(t.limit);if(!v.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=ra(e,n,r),a=i.lines.flatMap(e=>{let t=la(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function ra(e,t,n){let r=v.openSync(e,`r`);try{let e=new ke(`utf8`),i=Buffer.allocUnsafe(65536),a=ia(t,n),o=``,s=0;do{s=v.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=aa(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&oa(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{v.closeSync(r)}}function ia(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function aa(e,t){let n=0;for(let r=e.indexOf(`
|
|
1
|
+
import{_ as e,j as t}from"./sdk-contracts.js";import{v as n}from"./location-coordinates.js";import{$t as r,Bn as i,Lr as a,Rr as o,Vn as s,Zt as c,b as l,rn as ee,zr as te}from"./sdk-batch-runner.js";import{_ as ne,i as re,r as ie,t as ae}from"./sdk-device.js";import{Gt as oe,Ht as se,Jt as ce,Qt as le,Xt as ue,Yt as de,Zt as u,an as fe,en as d,in as f,nn as pe,qt as me,rn as he,tn as ge,yn as _e}from"./script-source-bundle.js";import{C as ve,H as ye,K as p,N as be,n as xe}from"./interaction.js";import{n as m,t as Se}from"./command-catalog.js";import{t as Ce}from"./session.js";import{t as we}from"./device.js";import{n as Te,t as Ee}from"./path-resolution.js";import{A as h,M as g}from"./sdk-android-adb.js";import{n as De,t as _}from"./version.js";import{c as Oe,d as ke,n as Ae,s as je}from"./host-process.js";import v from"node:path";import Me from"node:crypto";import y from"node:fs";import{StringDecoder as Ne}from"node:string_decoder";function Pe(e,t={}){let n=[e.command];return e.command===`snapshot`?le(n,e):e.command===`open`?oe(n,e):e.command===`runtime`?de(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ce(n,e):e.command===`screenshot`?ue(n,e):me(n,e),n.join(` `)}function Fe(e){return e.targetEvidences?[i(e.targetEvidences)]:e.targetEvidence?[s(e.targetEvidence)]:[]}async function Ie(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function Le(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function Re(t,n,r){let i=[],a=0;for await(let o of t){let t=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=t.length,a>n)throw new e(`INVALID_ARGS`,r);i.push(t)}return Buffer.concat(i)}const ze=`/agent-device`,Be=`x-agent-device-tenant`;function Ve(e){return He(e,ze)}function He(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ue(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function We(e){let t=e?.trim();return t?{[Be]:t}:{}}const b={kind:`none`};function x(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function Ge(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Ke(e){return e.kind===`none`?void 0:e.target}function qe(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Je(e){return e.kind===`authoring`&&e.status===`aborted`}function Ye(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function Xe(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Ze(e){return{kind:`authoring`,status:`armed`,target:x(void 0,e)}}function Qe(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function $e(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function et(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:x(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function tt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function nt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function rt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function it(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function at(e){return e.kind===`repair`?e.boundary:void 0}function ot(e){return e.kind===`repair`?e.sourcePath:void 0}function st(e){return e.kind===`repair`&&e.status!==`committed`}function S(e){let t=Ke(e);return t?.kind===`explicit`?t.path:void 0}function ct(e){return Ke(e)?.force===!0}function C(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function lt(e){let t=C(e);return t.length>0&&t!==`.`&&t!==`..`}function w(e,t){return Te(e,{cwd:t})}function T(e){return e?.scriptPublication??b}function ut(e){let t=T(e);return t.kind===`authoring`&&t.status===`armed`}function dt(e,t){e.scriptPublication=Ze({path:t.path===void 0?void 0:w(t.path),force:t.force===!0})}function ft(e){e.scriptPublication=Qe(T(e))}function pt(e){return Ye(T(e))}function mt(e,t){if(!t.saveScript||Je(T(e)))return;let n={path:typeof t.saveScript==`string`?w(t.saveScript):void 0,force:t.force===!0},r=T(e);if(r.kind===`repair`){e.scriptPublication=et(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:x(r.target,n)};return}e.scriptPublication=Ze(n)}function ht(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:x(n.target,{path:t.explicitPath===void 0?void 0:w(t.explicitPath),force:t.liveForce===!0})})}function gt(e,t){e.scriptPublication=$e(T(e),t)}function _t(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication=$e(n,t))}function vt(e,t){return t===!0||ct(T(e))}function yt(e){return Xe(T(e))}function E(e){return e?.scriptPublication??b}function bt(e,t){let n=E(e);e.scriptPublication=et(n,{requested:{path:typeof t.saveScript==`string`?w(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function xt(e){e.scriptPublication=Ge(E(e))}function St(e){e.scriptPublication=tt(E(e))}function Ct(e,t){e.scriptPublication=nt(E(e),t)}function wt(e){e.scriptPublication=it(E(e))}function Tt(e,t){let n=E(e);return n.kind===`repair`&&n.closeReceipt===t}function Et(e){return E(e).kind===`repair`}function Dt(e){return st(E(e))}function D(e){return at(E(e))}function Ot(e){return ot(E(e))}function O(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const kt=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function k(t){if(t!==t.trim()||!se.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function At(e){return`\${${e}}`}function jt(e){let t=kt.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const Mt=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),Nt=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Pt=new Set([`cost`,`evidence`,`resolution`,`settle`]),Ft=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),It=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function Lt(e,t,n){if(!e)return e;let r=Wt(e.selectorChain);return{...Bt(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!zt(e,t))}:{}}}function Rt(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function zt(e,t){return ee(e,t)}function Bt(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[Mt.has(e)?e:j(e,t,n),Vt(r,e,t,n)]))}function Vt(e,t,n,r){return typeof e==`string`&&Nt.has(t)?e:t===`selectorChain`&&Ut(e)?Ht(e,n):A(e,n,r,Pt.has(t)?t:void 0)}function A(e,t,n,r){if(typeof e==`string`)return r&&It.has(r)?e:j(e,t,n);if(Array.isArray(e))return e.map(e=>A(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Ft.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:j(e,t,n),A(a,t,n,o?`${r}.${e}`:void 0)]}))}function Ht(e,t){return e.filter(e=>!zt(e,t))}function j(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function Ut(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Wt(e){return Ut(e)?e:void 0}function Gt(e,t){if(t.flags?.noRecord||Xt(e,t))return;t.flags&&mt(e,t.flags);let n=Kt(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Qt(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),h({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Kt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=At(k(e.flags.recordAs)),n=O({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:qt(e.positionals,t),result:Lt(e.result,n,t),targetEvidence:Rt(e.targetEvidence,n,t)}}function qt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Jt=new Set([`snapshot`,`get`,`is`,`find`]);function Yt(e){return e.internal?.replayPlanStep===!0?!1:Jt.has(e.command)}function Xt(e,t){return!t.interactiveObservation||D(e)===void 0?!1:t.flags?.record!==!0}const Zt=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...n,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Qt(e){if(!e)return{};let t={};for(let n of Zt)e[n]!==void 0&&(t[n]=e[n]);return t}function $t(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())l({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(on))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function en(t){for(let n of t){if(tn(n)){nn(n);continue}let t=sn(n),i=t??(n.command===`wait`?n.positionals[0]:void 0);if(i?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&l(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let a=t;if(!(!a||!r(a)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${a}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function tn(e){return rn(e)!==void 0}function nn(t){let n=rn(t);if(!n)return;let i=[n.source,n.destination];for(let n of i){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!r(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function rn(e){return e.command===`gesture`?ve(e.positionals):void 0}function an(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function on(e){if(e.command!==`wait`)return!1;let t=c(e.positionals);return t?.kind!==`selector`||!r(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function sn(e){if(e.command===`get`)return e.positionals[1];if(he(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&cn(t)&&cn(n)?void 0:t}}function cn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function ln(e){let t=e.scriptPublication??b;return t.kind===`repair`?t.status===`committed`?!0:!qe(t):!1}function un(e){return Ye(e.scriptPublication??b)?ln(e):!0}var dn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=Et(e),r=t?.publication===`active`,i;try{if(un(e))return{written:!1};let a=fn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=v.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),hn({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=rt(e.scriptPublication??b)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return pn({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=S(e.scriptPublication??b);if(t)return w(t);let n=C(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return v.join(this.sessionsDir,`${n}-${r}.ad`)}};function fn(e,t){let n=gn(e,{strictPortableRefs:t.activePublication});return t.activePublication&&$t(n),{script:En(e,n,t.appendCompleteSentinel),actionCount:n.length}}function pn(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(h({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:mn(r,i)};if(o)return{written:!1,error:an(r,i)};if(r instanceof e)throw r;return{written:!1}}function mn(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function hn(t){let{scriptPath:n,script:r,force:i}=t,a=v.dirname(n),o=v.join(a,`.${v.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);y.writeFileSync(o,r);try{if(i){y.renameSync(o,n);return}y.linkSync(o,n)}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}finally{y.rmSync(o,{force:!0})}}function gn(e,t={}){let n=D(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=yn(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&_n(n);let o=Tn(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&en(a),a}function _n(t){let n=t.command===`gesture`?ve(t.positionals??[]):void 0;if(n){vn(n);return}if(!M(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function vn(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function yn(e){let t=bn(e);if(!(!t||!M(e.command)))return pe(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Sn(e,t):e.command===`fill`?xn(e,t):Cn(e,t)}function bn(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function M(e){return he(e)||e===`fill`||e===`get`}function xn(e,t){let n=O(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Sn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):wn(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Cn(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function wn(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Tn(e,t){if(!M(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function En(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${ne(e.device)} device=${ge(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Fe(e)),r.push(Dn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
+
`)}\n`}function Dn(e){return On([e.command],e)||Pe(e)}function On(e,t){if(pe(t.command))return kn(e,t);if(t.command===`fill`)return An(e,t);if(t.command===`get`)return jn(e,t)}function kn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(d(f(n))),N(e,t),u(e,t),e.join(` `);if(t.positionals.length===1)return e.push(d(n)),u(e,t),e.join(` `)}}function An(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(d(f(n))),N(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(d(r)),u(e,t),e.join(` `)}function jn(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(d(n)),e.push(d(f(r))),r.startsWith(`@`)&&N(e,t),e.join(` `)}function N(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(d(n))}const Mn=[`status`,`get`,`dismiss`,`enter`,`return`];function P(e){return Mn.includes(e)}const Nn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Pn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Fn(e,t){let n=t??{};switch(e.command){case m.devices:return In(n.devices);case m.apps:return Ln(n.apps,e.flags?.appsFilter);case m.boot:return Rn(`Booted`,n,!0);case m.shutdown:return Rn(`Shut down`,n,!1);case m.install:return zn(`Installed`,n);case m.reinstall:return zn(`Reinstalled`,n);case m.screenshot:return Bn(e,n);default:return{}}}function In(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Hn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Zn(`Found ${t.length} ${Qn(`device`,t.length)}`,i.map(e=>Yn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Ln(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=L(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Zn(`Found ${n.length} ${Qn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Rn(e,t,n){let r=Un(t);if(!r)return{};let i={device:r,...Jn(t),booted:n};return{summary:`${e} ${Yn(i,!1)}`,details:i}}function zn(e,t){let n=L(t.appName),r=L(t.bundleId),i=F(t,[`packageName`,`package`]),a=L(t.platform),o=L(t.launchTarget),s=F(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Xn(n,s);if(!c)return{};let l={};return I(l,`appName`,n),I(l,`bundleId`,r),I(l,`packageName`,i),I(l,`platform`,a),o!==s&&I(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Bn(e,t){let n=Vn(e,t);return n?{details:{requestedFileName:n}}:{}}function Vn(e,t){let n=U(e.meta?.clientArtifactPaths?.path)??U(t.path);if(n)return H(n)}function Hn(e){if(!a(e))return;let t=Un(e);if(t)return{name:t,...Jn(e)}}function Un(e){let t=F(e,[`name`,`deviceName`,`device`]);return!t||!Wn(e,t)?t:Kn(e)}function Wn(e,t){let n=Gn(t);return Nn.some(t=>{let r=L(e[t]);return r!==void 0&&Gn(r)===n})}function Gn(e){return e.toLowerCase()}function Kn(e){let t=L(e.appleOs),n=L(e.platform),r=L(e.kind),i=qn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function qn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Pn,n)))return Pn[n]}function Jn(e){let t=L(e.platform),n=L(e.appleOs),r=L(e.kind),i=L(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Yn(e,t){let n=L(e.name)??L(e.device)??`device`,r=L(e.platform),i=L(e.appleOs),a=[r,i===r?void 0:i,L(e.kind),L(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Xn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function F(e,t){for(let n of t){let t=L(e[n]);if(t)return t}}function I(e,t,n){n&&(e[t]=n)}function Zn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Qn(e,t){return t===1?e:`${e}s`}function L(e){let t=U(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function R(e){return L(e)}function z(e){return typeof e==`boolean`?e:void 0}function B(e,t){let n=R(e);return n&&t.includes(n)?n:void 0}function V(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function H(e){let t=U(e);return t?L(t.split(/[\\/]/).at(-1)):void 0}function U(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function W(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const $n=[`up`,`down`,`left`,`right`],er=[`top`,`bottom`];function tr(e){return`${e.command===m.reinstall?`Reinstalled`:`Installed`} ${ar(e.result??{})??`app`}`}function nr(e){let t=e.result??{};switch(e.command){case m.scroll:return sr(t);case m.screenshot:return ur(t);case m.home:return`Went home`;case m.back:return fr(t);case m.appSwitcher:return`Opened app switcher`;case m.orientation:return pr(t);case m.viewport:return mr(t);case m.clipboard:return hr(t);case m.keyboard:return gr(t);case m.tvRemote:return yr(t);case m.gesture:return br(t);case m.swipe:return xr(t);case m.trace:return Cr(`trace`,e);case m.record:return Cr(`recording`,e);default:return}}function rr(e){let t=e.result??{};switch(e.command){case m.scroll:return V({direction:B(t.direction,$n),edge:B(t.edge,er),passes:W(t.passes),amount:W(t.amount),pixels:W(t.pixels),durationMs:W(t.durationMs),x1:W(t.x1),y1:W(t.y1),x2:W(t.x2),y2:W(t.y2)});case m.screenshot:return V({requestedFileName:dr(t)});case m.back:return V({mode:B(t.mode,p)});case m.orientation:return V({orientation:B(t.orientation,we)});case m.viewport:return V({width:W(t.width),height:W(t.height)});case m.clipboard:return V({action:B(t.action,[`read`,`write`])});case m.keyboard:return vr(t);case m.tvRemote:return V({button:B(t.button,xe),durationMs:W(t.durationMs)});case m.gesture:case m.swipe:return Sr(t);case m.trace:case m.record:return V({action:B(t.action,[`start`,`stop`]),fileName:Tr(e),showTouches:z(t.showTouches)});default:return{}}}function ir(e,t){if(e.command!==m.screenshot)return t;let n=Vn(e,t);return n?{...t,requestedFileName:n}:t}function ar(e){let t=R(e.appName),n=Er(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??or(e)}function or(e){let t=R(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function sr(e){let t=B(e.direction,$n),n=B(e.edge,er),r=W(e.passes);return n?cr(n,r):t?lr(t,e):`Scrolled`}function cr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function lr(e,t){let n=W(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=W(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function ur(e){let t=dr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function dr(e){return H(e.requestedFileName)??H(e.path)}function fr(e){return B(e.mode,p)===`system`?`Went back using system navigation`:`Went back`}function pr(e){let t=B(e.orientation,we);return t?`Rotated to ${t}`:`Changed orientation`}function mr(e){let t=W(e.width),n=W(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function hr(e){let t=B(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function gr(e){let t=U(e.action);if(!t||!P(t))return`Used keyboard`;if(t===`dismiss`)return _r(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=z(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function _r(e){return z(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function vr(e){let t=U(e.action);return V({action:t&&P(t)?t:void 0,platform:B(e.platform,[`ios`,`android`]),visible:z(e.visible),wasVisible:z(e.wasVisible),dismissed:z(e.dismissed),attempts:W(e.attempts),mechanism:B(e.mechanism,[`dismissKey`])})}function yr(e){let t=B(e.button,xe);return t?`Pressed TV remote ${t}`:`Used TV remote`}function br(e){let t=B(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function xr(e){let t=W(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Sr(e){return V({kind:B(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:W(e.durationMs),pointerCount:W(e.pointerCount),x1:W(e.x1),y1:W(e.y1),x2:W(e.x2),y2:W(e.y2),count:W(e.count),pauseMs:W(e.pauseMs),pattern:B(e.pattern,[`one-way`,`ping-pong`]),scale:W(e.scale)})}function Cr(e,t){let n=wr(e,B(t.result?.action,[`start`,`stop`])),r=Tr(t);return r?`${n} ${r}`:n}function wr(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Tr(e){let t=e.result??{};return H(t.requestedFileName)??H(t.outPath)??H(t.path)??H(e.positionals[1])}function Er(e,t){for(let n of t){let t=R(e[n]);if(t)return t}}function Dr(e){switch(e.command){case m.open:return`Opened ${G(e)??`session`}`;case m.close:return`Closed ${R(e.result?.session)??`session`}`;case m.click:case m.press:return`Tapped ${G(e)??`target`}`;case m.longPress:return`Long pressed ${G(e)??`target`}`;case m.hover:return`Hovered ${G(e)??`target`}`;case m.fill:return`Filled ${G(e)??`target`}`;case m.type:return`Typed text`;case m.install:case m.reinstall:case Se.installSource:return tr(e);default:return nr(e)??`Ran ${e.command}`}}function Or(e){return V({command:e.command,positionals:Lr(e),flags:Jr(e),...kr(e),...Ar(e),...jr(e),...rr(e)})}function kr(e){if(!Mr(e.command))return{};let t=e.result??{};return V({ref:Y(t),targetLabel:G(e),selectorChainLength:Gr(t.selectorChain)?.length,x:W(t.x),y:W(t.y),x2:W(t.x2),y2:W(t.y2),durationMs:W(t.durationMs)})}function Ar(e){if(!Nr(e.command))return{};let t=e.result??{};return V({platform:B(t.platform,re),target:B(t.target,ae),appName:R(t.appName),appBundleId:R(t.appBundleId),bundleId:R(t.bundleId),packageName:R(t.packageName),launchTarget:R(t.launchTarget)})}function jr(e){let t=e.result??{};return e.command===m.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==m.wait&&e.command!==m.find&&e.command!==m.get&&e.command!==m.is?{}:V({waitedMs:W(t.waitedMs),found:z(t.found)})}function Mr(e){return e===m.click||e===m.press||e===m.longPress||e===m.hover||e===m.focus||e===m.fill}function Nr(e){return e===m.open||e===m.install||e===m.reinstall||e===Se.installSource}function G(e){let t=e.result??{};return Pr(t)??Fr(t)??Ir(t)??Ur(e.positionals[0])}function Pr(e){let t=Y(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Fr(e){let t=W(e.x),n=W(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Ir(e){return R(e.appName)??R(e.appBundleId)??R(e.bundleId)??R(e.packageName)}function Lr(e){if(e.positionals.length!==0)return e.command===m.type?[q(`text`)]:e.command===m.fill?Rr(e):e.command===m.find?zr(e):e.command===m.clipboard?Br(e):e.command===m.push?Vr(e,`app`,`payload`):e.command===m.triggerAppEvent?Vr(e,`event`,`payload`):e.positionals.map(K)}function Rr(e){let t=q(`text`),n=e.result??{},r=Y(n);if(r)return[`@${r}`,t];if(R(n.selector))return[q(`target`),t];let i=W(n.x),a=W(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function zr(e){let t=+!!Wr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,q(`text`)]:[...r,...e.positionals.slice(n).map(Hr)]:r}function Br(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,q(`text`)]:e.positionals.map(K)}function Vr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[q(t)]:[],...i?[q(n)]:[],...a.map(K)]}function Hr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:K(e)}function K(e){return Ur(e)??q(`arg`)}function Ur(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function q(e){return`<${e}>`}function Wr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Gr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Kr={enums:[{source:`platform`,values:ie},{source:`target`,values:ae}]},qr={[m.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Ce}]},[m.click]:J(),[m.press]:J(),[m.longPress]:J(),[m.hover]:J(),[m.fill]:Yr(),[m.type]:Yr(),[m.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[m.gesture]:Xr(),[m.swipe]:Xr(),[m.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[m.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[m.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:p}]},[m.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:fe}]},[m.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[m.boot]:{booleans:[{source:`headless`}]},[m.close]:{booleans:[{source:`shutdown`}]}};function Jr(e){let t=e.flags??{},n={},r=Object.hasOwn(qr,e.command)?qr[e.command]:void 0;return Zr(n,t,Kr),Zr(n,t,r),Object.keys(n).length>0?n:void 0}function J(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ye}]}}function Yr(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Xr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:be}]}}function Zr(e,t,n){n&&(Qr(e,t,n.booleans??[]),$r(e,t,n.numbers??[]),ei(e,t,n.enums??[]))}function Qr(e,t,n){for(let r of n)ti(e,r.output??r.source,t[r.source])}function $r(e,t,n){for(let r of n)ni(e,r.output??r.source,t[r.source])}function ei(e,t,n){for(let r of n)ri(e,r.output??r.source,t[r.source],r.values)}function Y(e){let t=R(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function ti(e,t,n){typeof n==`boolean`&&(e[t]=n)}function ni(e,t,n){let r=W(n);r!==void 0&&(e[t]=r)}function ri(e,t,n,r){let i=B(n,r);i!==void 0&&(e[t]=i)}const X=new Map,ii=new Set;function ai(e){return v.join(e,`events.ndjson`)}function oi(e){return e.command!==m.events}function si(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});li(e,`${JSON.stringify(i)}\n`)}async function ci(e){await(e?X.get(e):Promise.all(X.values()))}function li(e,t){let n=(X.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ui(e),await y.promises.appendFile(e,t,`utf8`)}).catch(t=>{h({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{X.get(e)===n&&X.delete(e)});X.set(e,n)}async function ui(e){let t=v.dirname(e);if(!ii.has(t))try{await y.promises.mkdir(t,{recursive:!0}),ii.add(t)}catch(t){throw h({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function di(e,t,n){si(e,t,{kind:`action.recorded`,requestId:g().requestId,command:n.command,summary:Dr(n),details:Or(n)})}function fi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??g().requestId,command:t.command,summary:`Started ${t.command}`}}function pi(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Fn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??g().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??g().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function mi(e,t={}){let n=yi(t.cursor),r=bi(t.limit);if(!y.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=hi(e,n,r),a=i.lines.flatMap(e=>{let t=xi(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function hi(e,t,n){let r=y.openSync(e,`r`);try{let e=new Ne(`utf8`),i=Buffer.allocUnsafe(65536),a=gi(t,n),o=``,s=0;do{s=y.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=_i(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&vi(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{y.closeSync(r)}}function gi(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function _i(e,t){let n=0;for(let r=e.indexOf(`
|
|
3
3
|
`);r!==-1;r=e.indexOf(`
|
|
4
|
-
`,n))if(
|
|
4
|
+
`,n))if(vi(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function vi(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0){if(t.lineIndex>=t.cursor+t.limit){t.nextCursor=t.cursor+t.limit;return}t.lineIndex>=t.cursor&&t.lines.push(n),t.lineIndex+=1}}function yi(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function bi(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function xi(e){try{let t=Si(JSON.parse(e));return t?Ci(t):void 0}catch{return}}function Si(e){if(a(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&wi(e.kind))return e}function Ci(e){let t=a(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...Ti(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function wi(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Ti(e){return e===`ok`||e===`error`}const Ei=60*6e4;var Di=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new dn(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=Gt(e,t);if(n){let t=this.resolveStoredSessionName(e);di(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){si(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return mi(this.resolveEventLogPath(e),t)}async flushEvents(e){await ci(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&h({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:vt(e,void 0)});Dt(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,Ei,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){qe(e.scriptPublication??b)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,..._e(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=Ei,n){try{let r=this.resolveSessionDir(e.name);y.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...Ot(e)?{sourcePath:Ot(e)}:{},...n?{commitFailure:n}:{}};y.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){h({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Oi(this.repairTombstonePath(e))}clearRepairTombstone(e){try{y.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return v.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=C(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return v.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!lt(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return v.join(this.sessionsDir,C(t))}resolveDaemonStateDir(){return v.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return y.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return v.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return v.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return ai(this.resolveSessionDir(e))}static expandHome(e,t){return w(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function Oi(e){let t;try{t=y.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||n.expiresAt<=Date.now()))return n}function ki(e){let t;try{t=y.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=Oi(v.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function Ai(e){return v.join(e,`runner.log`)}function Z(e,t){let n=C(t&&t.length>0?t:`unknown`);return v.join(e,`requests`,`${n}.ndjson`)}function ji(e){return{path:Z(e.sessionDir,e.requestId),ref:{session:e.session,requestId:e.requestId&&e.requestId.length>0?e.requestId:`unknown`}}}function Mi(e,t){return Z(v.join(e,`remote-diagnostics`,C(t.session)),t.requestId)}function Ni(e,t={}){let n=Pi(e,t);return{baseDir:n,infoPath:v.join(n,`daemon.json`),lockPath:v.join(n,`daemon.lock`),logPath:v.join(n,`daemon.log`),sessionsDir:v.join(n,`sessions`)}}function Pi(e,t){let n=(e??``).trim();return n?Te(n,{env:t.env}):Fi(t)}function Fi(e={}){let t=v.join(Ee(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??_();return Ii(n)?v.join(t,`dev`,Li(n)):t}function Ii(e){return y.existsSync(v.join(e,`package.json`))&&y.existsSync(v.join(e,`src`,`daemon.ts`))}function Li(e){let t=Ri(e),n=v.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=Me.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function Ri(e){try{return y.realpathSync.native(e)}catch{return v.resolve(e)}}function zi(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function Bi(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Vi(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function Hi(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Ui=/(['"])(\.\.?\/[^'"]*)\1/g,Wi=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function Gi(){let e=process.argv[1];return e?Ki(e):`unknown`}function Ki(e,t=_()){try{let n=v.resolve(t),r=[v.resolve(e)],i=new Set,a=[];for(;r.length>0;){let e=r.pop();if(!e||i.has(e))continue;i.add(e);let t=y.statSync(e);if(!t.isFile())continue;let o=v.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=y.readFileSync(e,`utf8`);for(let t of qi(s)){let n=Ji(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=Me.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function qi(e){let t=new Set;Ui.lastIndex=0;let n=null;for(;(n=Ui.exec(e))!==null;)t.add(n[2]);return[...t]}function Ji(e,t){let n=v.resolve(v.dirname(e),t),r=Q(n);if(r)return r;for(let e of Wi){let t=Q(`${n}${e}`);if(t)return t}for(let e of Wi){let t=Q(v.join(n,`index${e}`));if(t)return t}return null}function Q(e){try{return y.statSync(e).isFile()?e:null}catch{return null}}const Yi=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Xi(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Yi.some(e=>e.test(t)):!1}function Zi(e,t){if(!Ae(e))return!1;if(t){let n=Oe(e);if(!n||n!==t)return!1}let n=je(e);return n?Xi(n):!1}function $(e,t){try{return process.kill(e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}async function Qi(e,t){Zi(e,t.expectedStartTime)&&$(e,`SIGTERM`)&&(await ke(e,t.termTimeoutMs)||$(e,`SIGKILL`)&&await ke(e,t.killTimeoutMs))}function $i(e,t){let n=[],r=e+t.toString(),i=r.indexOf(`
|
|
5
5
|
`);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e&&n.push(e),i=r.indexOf(`
|
|
6
|
-
`)}return{lines:n,buffer:r}}function
|
|
6
|
+
`)}return{lines:n,buffer:r}}function ea(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function ta(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function na(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function ra(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function ia(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function aa(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function oa(e,t={}){return{ok:!0,service:e,version:De(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function sa(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{}}}function ca(e){if(a(e))return sa({path:typeof e.path==`string`?e.path:void 0,width:typeof e.width==`number`?e.width:void 0,height:typeof e.height==`number`?e.height:void 0,logicalWidth:typeof e.logicalWidth==`number`?e.logicalWidth:void 0,logicalHeight:typeof e.logicalHeight==`number`?e.logicalHeight:void 0,pixelDensity:typeof e.pixelDensity==`number`?e.pixelDensity:void 0,overlayRefs:Array.isArray(e.overlayRefs)?e.overlayRefs.filter(fa).flatMap(e=>{let t=la(e);return t?[t]:[]}):void 0})}function la(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=ua(e);if(t)return{ref:e.ref,...da(e),...t}}function ua(e){let t=te(e.rect);if(!t)return;let n=te(e.overlayRect);if(!n)return;let r=o(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function da(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function fa(e){return a(e)}export{yt as $,Lr as A,bt as B,Mi as C,pi as D,Ai as E,jt as F,Ct as G,Et as H,At as I,ft as J,D as K,k as L,P as M,Yt as N,fi as O,Lt as P,pt as Q,O as R,ki as S,Z as T,Dt as U,Tt as V,St as W,vt as X,dt as Y,ut as Z,Ni as _,Le as _t,na as a,C as at,Vi as b,aa as c,S as ct,Zi as d,Ue as dt,gt as et,Qi as f,Ve as ft,Hi as g,Re as gt,Gi as h,Ie as ht,ta as i,lt as it,ir as j,oi as k,ea as l,ze as lt,Ki as m,He as mt,ca as n,ht as nt,ra as o,b as ot,$ as p,We as pt,xt as q,oa as r,w as rt,ia as s,ct as st,sa as t,_t as tt,$i as u,Be as ut,zi as v,ji as w,Di as x,Bi as y,wt as z};
|
package/dist/src/screenshot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,a as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e,a as t}from"./sdk-contracts.js";import{vt as n,yt as r}from"./script-source-bundle.js";import{t as i}from"./screenshot-result.js";import{n as a}from"./path-resolution.js";import{t as o}from"./shared.js";import{t as s}from"./cli-runner.js";const c=async({positionals:e,flags:n,client:r})=>{let a=await s({client:r,command:`screenshot`,positionals:e,flags:n});return t(n.responseLevel)?(o(n,a,()=>JSON.stringify(a,null,2)),!0):(o(n,i(a),()=>a.overlayRefs?`Annotated ${a.overlayRefs.length} refs onto ${a.path}`:d(a)),!0)},l=async({positionals:t,flags:i,client:c})=>{if(t[0]===`snapshot`){let e=await s({client:c,command:`diff`,positionals:t,flags:i});return o(i,e,()=>r(e)),!0}if(t[0]!==`screenshot`)return!1;let l=i.baseline;if(!l||typeof l!=`string`)throw new e(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let d=a(l),f=typeof i.out==`string`?a(i.out):void 0,m=t[1];if(t.length>2)throw new e(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:h,localCommandPolicy:g},{createLocalArtifactAdapter:_}]=await Promise.all([import(`./runtime.js`).then(e=>e.r),import(`./sdk-io.js`).then(e=>e.n)]),v=await h({backend:u(c,i),artifacts:_(),sessions:{get:e=>({name:e}),set:()=>{}},policy:g()}).capture.diffScreenshot({session:i.session,baseline:{kind:`path`,path:d},current:m?{kind:`path`,path:a(m)}:{kind:`live`},...f?{out:{kind:`path`,path:f}}:{},threshold:p(i.threshold),overlayRefs:i.overlayRefs,normalizeStatusBar:i.screenshotNormalizeStatusBar,surface:i.surface});return o(i,v,()=>n(v)),!0};function u(e,t){return{platform:f(t),captureScreenshot:async(t,n,r)=>i(await e.capture.screenshot({path:n,session:t.session,overlayRefs:r?.overlayRefs,pixelDensity:r?.pixelDensity,fullscreen:r?.fullscreen,normalizeStatusBar:r?.normalizeStatusBar,stabilize:r?.stabilize,surface:r?.surface}))}}function d(e){if(typeof e.width!=`number`||typeof e.height!=`number`)return e.path;let t=typeof e.pixelDensity==`number`?` @${e.pixelDensity}x`:``;return`${e.path} (${e.width}x${e.height}${t})`}function f(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function p(e){if(!(e==null||e===``))return Number(e)}export{l as diffCommand,c as screenshotCommand};
|