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.
Files changed (220) hide show
  1. package/README.md +94 -31
  2. 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
  3. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.10.apk.sha256 +1 -0
  4. 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
  5. 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
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.10.apk.sha256 +1 -0
  7. 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
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +3 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +13 -7
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +10 -117
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +4 -4
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +103 -2
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +22 -23
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +3 -23
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +10 -11
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +108 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +8 -5
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +179 -73
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +13 -12
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentation.swift +183 -0
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotPresentationTests.swift +0 -0
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +20 -18
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +19 -0
  24. package/dist/src/agent-browser-tool.js +1 -1
  25. package/dist/src/agent-device-client.js +2 -2
  26. package/dist/src/ai-sdk.d.ts +61 -0
  27. package/dist/src/ai-sdk.js +1 -0
  28. package/dist/src/android-adb.d.ts +6 -6
  29. package/dist/src/android-adb.js +1 -1
  30. package/dist/src/android.js +1 -1
  31. package/dist/src/app-helpers.js +1 -1
  32. package/dist/src/app-lifecycle.js +6 -7
  33. package/dist/src/app-lifecycle2.js +2 -2
  34. package/dist/src/app-log-reconnect.js +1 -1
  35. package/dist/src/app-log-runtime.js +3 -3
  36. package/dist/src/app-resolution.js +2 -2
  37. package/dist/src/app-state.js +2 -0
  38. package/dist/src/appearance.js +1 -0
  39. package/dist/src/apps.js +5 -5
  40. package/dist/src/artifacts.d.ts +1 -1
  41. package/dist/src/audio-probe.js +1 -1
  42. package/dist/src/auth-session.js +1 -1
  43. package/dist/src/backend-snapshot-options.js +1 -0
  44. package/dist/src/boot-diagnostics.js +2 -2
  45. package/dist/src/bounds.js +1 -0
  46. package/dist/src/byte-limit-stream.js +1 -0
  47. package/dist/src/cli-config.js +1 -1
  48. package/dist/src/cli-help.js +42 -30
  49. package/dist/src/cli-runner.js +1 -1
  50. package/dist/src/cli.js +7 -7
  51. package/dist/src/client-metro.js +1 -1
  52. package/dist/src/client-types.d.ts +1582 -0
  53. package/dist/src/command-catalog.js +1 -0
  54. package/dist/src/command-metadata.js +1 -1
  55. package/dist/src/command-schema.js +1 -1
  56. package/dist/src/command-surface.js +1 -1
  57. package/dist/src/command-tools.js +2 -0
  58. package/dist/src/config.js +1 -0
  59. package/dist/src/connection-runtime.js +1 -1
  60. package/dist/src/connection.js +3 -3
  61. package/dist/src/contracts.d.ts +1 -1
  62. package/dist/src/contracts.js +1 -1
  63. package/dist/src/daemon-shutdown-report.js +1 -1
  64. package/dist/src/daemon.js +1 -1
  65. package/dist/src/debug-symbols.js +3 -3
  66. package/dist/src/device-claim-inspection.js +1 -1
  67. package/dist/src/device-input-state.js +1 -1
  68. package/dist/src/device-ready.js +1 -1
  69. package/dist/src/device2.js +2 -2
  70. package/dist/src/dispatch.js +1 -1
  71. package/dist/src/entities.js +1 -1
  72. package/dist/src/find.js +1 -1
  73. package/dist/src/finders.js +1 -1
  74. package/dist/src/generic-settle.js +1 -1
  75. package/dist/src/generic.js +1 -1
  76. package/dist/src/harmonyos.js +1 -1
  77. package/dist/src/hdc.js +1 -1
  78. package/dist/src/helper-package-install.js +1 -0
  79. package/dist/src/helper.js +2 -2
  80. package/dist/src/host-process.js +1 -1
  81. package/dist/src/ime-lifecycle.js +2 -9
  82. package/dist/src/ime-recovery-marker.js +1 -0
  83. package/dist/src/index.d.ts +2 -1569
  84. package/dist/src/index.js +1 -1
  85. package/dist/src/input-actions.js +4 -4
  86. package/dist/src/input-actions2.js +1 -1
  87. package/dist/src/install-artifact.js +1 -1
  88. package/dist/src/install-artifact2.js +1 -1
  89. package/dist/src/install-source2.js +1 -1
  90. package/dist/src/interaction-common.js +1 -0
  91. package/dist/src/interaction-runtime.js +1 -1
  92. package/dist/src/interaction-snapshot.js +1 -1
  93. package/dist/src/interaction.js +1 -1
  94. package/dist/src/interaction2.js +1 -0
  95. package/dist/src/interactor.js +2 -2
  96. package/dist/src/interactor2.js +1 -1
  97. package/dist/src/interactors.js +1 -0
  98. package/dist/src/internal/bin.js +2 -2
  99. package/dist/src/internal/daemon.js +4 -7
  100. package/dist/src/internal/png-worker.js +1 -1
  101. package/dist/src/inventory.js +1 -1
  102. package/dist/src/keyed-lock.js +1 -0
  103. package/dist/src/lease-context.js +1 -1
  104. package/dist/src/lease.js +1 -1
  105. package/dist/src/limrun-runtime-dependencies.js +1 -1
  106. package/dist/src/limrun.d.ts +13 -3
  107. package/dist/src/limrun.js +1 -1
  108. package/dist/src/linux.js +1 -1
  109. package/dist/src/location-coordinates.js +1 -0
  110. package/dist/src/logcat.js +1 -1
  111. package/dist/src/manifest.js +1 -1
  112. package/dist/src/mobile-snapshot-semantics.js +1 -0
  113. package/dist/src/observability.js +1 -0
  114. package/dist/src/owner-identity.js +1 -1
  115. package/dist/src/perf.js +4 -0
  116. package/dist/src/physical-device-control.js +1 -1
  117. package/dist/src/platform-runtime-app-log-process.js +1 -1
  118. package/dist/src/platform-runtime-host.js +1 -1
  119. package/dist/src/platform-runtime-network-web-transport.js +1 -1
  120. package/dist/src/platform-runtime-open-target.js +1 -0
  121. package/dist/src/platform-runtime-operation-host.js +4 -4
  122. package/dist/src/platform-runtime-runtime-hints.js +2 -0
  123. package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
  124. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  125. package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
  126. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  127. package/dist/src/platform-runtime-screen-recording-web-host.js +1 -1
  128. package/dist/src/platform-runtime.js +1 -1
  129. package/dist/src/platform-runtime2.js +1 -0
  130. package/dist/src/plist.js +1 -1
  131. package/dist/src/png-resize.js +1 -0
  132. package/dist/src/png-worker-contract.js +1 -1
  133. package/dist/src/process-lock.js +1 -1
  134. package/dist/src/project-runtime.js +1 -0
  135. package/dist/src/provider-webdriver.js +1 -1
  136. package/dist/src/provider.js +1 -0
  137. package/dist/src/proxy.js +1 -1
  138. package/dist/src/react-native.js +1 -1
  139. package/dist/src/record-runtime.js +1 -1
  140. package/dist/src/record-trace.js +1 -1
  141. package/dist/src/recording-export-quality.js +1 -0
  142. package/dist/src/registry.js +29 -26
  143. package/dist/src/remote-config2.js +1 -1
  144. package/dist/src/replay.js +2 -2
  145. package/dist/src/reporting.js +5 -5
  146. package/dist/src/rolldown-runtime.js +1 -0
  147. package/dist/src/runner-client.js +1 -0
  148. package/dist/src/runner-disposal.js +1 -1
  149. package/dist/src/runner-lease.js +1 -1
  150. package/dist/src/runner-sequence.js +1 -1
  151. package/dist/src/runtime-transport.js +1 -1
  152. package/dist/src/runtime.js +3 -3
  153. package/dist/src/runtime2.js +4 -3
  154. package/dist/src/runtime3.js +1 -3
  155. package/dist/src/runtime4.js +3 -1
  156. package/dist/src/runtime5.js +1 -1
  157. package/dist/src/runtime6.js +1 -1
  158. package/dist/src/runtime7.js +1 -1
  159. package/dist/src/runtime8.js +1 -0
  160. package/dist/src/runtime9.js +1 -0
  161. package/dist/src/scoped-provider.js +1 -0
  162. package/dist/src/screenshot-density.js +1 -0
  163. package/dist/src/screenshot-result.js +4 -4
  164. package/dist/src/screenshot.js +1 -1
  165. package/dist/src/script-source-bundle.js +16 -0
  166. package/dist/src/sdk-android-adb.d.ts +44 -26
  167. package/dist/src/sdk-android-adb.js +4 -4
  168. package/dist/src/sdk-batch-runner.js +3 -3
  169. package/dist/src/sdk-contracts.d.ts +125 -88
  170. package/dist/src/sdk-contracts.js +2 -2
  171. package/dist/src/sdk-device.js +1 -1
  172. package/dist/src/sdk-finders.d.ts +1 -1
  173. package/dist/src/sdk-finders.js +1 -1
  174. package/dist/src/sdk-io.js +1 -1
  175. package/dist/src/sdk-remote-config.js +1 -1
  176. package/dist/src/sdk-selectors.d.ts +107 -95
  177. package/dist/src/sdk-selectors.js +1 -1
  178. package/dist/src/sdk.js +1 -0
  179. package/dist/src/selector-runtime.js +1 -1
  180. package/dist/src/selectors.d.ts +1 -1
  181. package/dist/src/selectors.js +1 -1
  182. package/dist/src/server.js +10 -3
  183. package/dist/src/session-target-evidence.js +1 -1
  184. package/dist/src/session.js +1 -30
  185. package/dist/src/session2.js +27 -0
  186. package/dist/src/setting-state.js +1 -1
  187. package/dist/src/shared.js +1 -1
  188. package/dist/src/simctl.js +1 -0
  189. package/dist/src/simulator-state.js +1 -0
  190. package/dist/src/simulator.js +1 -1
  191. package/dist/src/snapshot-runtime.js +1 -1
  192. package/dist/src/snapshot-scope.js +1 -0
  193. package/dist/src/snapshot-session.js +1 -1
  194. package/dist/src/snapshot.js +8 -1
  195. package/dist/src/snapshot2.js +1 -1
  196. package/dist/src/snapshot3.js +1 -0
  197. package/dist/src/src.js +1 -1
  198. package/dist/src/src2.js +1 -2
  199. package/dist/src/src3.js +2 -1
  200. package/dist/src/src4.js +1 -0
  201. package/dist/src/string-enum.js +1 -0
  202. package/dist/src/tool-provider.js +3 -3
  203. package/dist/src/tool-provider2.js +1 -1
  204. package/dist/src/tool-provider3.js +1 -1
  205. package/dist/src/update-check.js +1 -1
  206. package/dist/src/verdict.js +1 -0
  207. package/dist/src/verified-file.js +1 -0
  208. package/dist/src/version.js +1 -1
  209. package/dist/src/video.js +1 -1
  210. package/dist/src/web.js +1 -1
  211. package/package.json +27 -10
  212. package/server.json +3 -3
  213. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.8.apk.sha256 +0 -1
  214. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.8.apk.sha256 +0 -1
  215. package/dist/src/interaction-touch-reference-frame.js +0 -1
  216. package/dist/src/notifications.js +0 -1
  217. package/dist/src/platform-runtime-toolchain-host.js +0 -1
  218. package/dist/src/prepare-kind.js +0 -15
  219. package/dist/src/selector-vocabulary.js +0 -1
  220. package/dist/src/text-surface.js +0 -1
@@ -1 +1 @@
1
- import{c as e}from"./tool-provider.js";const t=Object.freeze({available:!0,mode:`local`,async start({device:e,outputPath:t,signal:n}){let[{buildSimctlArgsForDevice:r},{runCmdBackground:i}]=await Promise.all([import(`./physical-device-control.js`).then(e=>e.B),import(`./sdk-android-adb.js`).then(e=>e.p)]);return n?.throwIfAborted(),i(`xcrun`,r(e,[`io`,e.id,`recordVideo`,t]),{allowFailure:!0})}}),n=Object.freeze({available:!1,mode:`transport-composed`,start:async()=>{throw Error(`Scoped Apple provider does not expose an Apple simulator screen-recording transport`)}}),r=e(t);function i(){return r.resolve()}async function a(e,t){return await r.run(e??n,t)}export{i as resolveAppleSimulatorScreenRecordingTransport,a as withAppleSimulatorScreenRecordingTransport};
1
+ import{t as e}from"./scoped-provider.js";const t=Object.freeze({available:!0,mode:`local`,async start({device:e,outputPath:t,signal:n}){let[{buildSimctlArgsForDevice:r},{runCmdBackground:i}]=await Promise.all([import(`./simctl.js`).then(e=>e.i),import(`./sdk-android-adb.js`).then(e=>e.p)]);return n?.throwIfAborted(),i(`xcrun`,r(e,[`io`,e.id,`recordVideo`,t]),{allowFailure:!0})}}),n=Object.freeze({available:!1,mode:`transport-composed`,start:async()=>{throw Error(`Scoped Apple provider does not expose an Apple simulator screen-recording transport`)}}),r=e(t);function i(){return r.resolve()}async function a(e,t){return await r.run(e??n,t)}export{i as resolveAppleSimulatorScreenRecordingTransport,a as withAppleSimulatorScreenRecordingTransport};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-contracts.js";import{t}from"./version.js";import{tn as n}from"./prepare-kind.js";import{v as r}from"./sdk-android-adb.js";import{n as i}from"./recording-telemetry.js";import{a,i as o,n as s,r as c,t as l}from"./video.js";import u from"node:path";import d from"node:fs";import{fileURLToPath as f}from"node:url";function p(e,t,n,r){let i=`apple/runner/AgentDeviceRunner/RecordingScripts/${e}`,a=`dist/${i}`;return[u.resolve(t,e),u.resolve(n,i),u.resolve(t,`../${i}`),u.resolve(t,`../../${i}`),u.resolve(t,`../../../${i}`),u.resolve(n,a),u.resolve(r,i)]}function m(n){let r=p(n,u.dirname(f(import.meta.url)),t(),process.cwd());for(let e of r)if(d.existsSync(e))return e;throw new e(`COMMAND_FAILED`,`Missing recording helper script: ${n}`,{hint:`Ensure apple/runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled under dist/apple/runner in the package.`,scriptName:n,searchedPaths:r})}let h,g;function _(e=process.platform){if(e!==`darwin`)return`touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry`}function v(){return h??=m(`recording-overlay.swift`),h}function y(){return g??=m(`recording-trim.swift`),g}async function b(t){let{videoPath:n,scriptPath:i,scriptArgs:l,commandDescription:u}=t;await c(n),await s(n);let f=x(n);try{await r(await a({sourcePath:i}),[`--input`,n,`--output`,f,...l],{timeoutMs:12e4,env:o()}),await s(f),d.renameSync(f,n)}catch(t){let r=t instanceof e?t:new e(`COMMAND_FAILED`,String(t),void 0,t instanceof Error?t:void 0);throw new e(`COMMAND_FAILED`,u,{...r.details,videoPath:n,script:i},r)}finally{d.rmSync(f,{force:!0})}}function x(e){let t=u.parse(e),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return u.join(t.dir,`.${t.name}.agent-device-${n}${t.ext||`.mp4`}`)}async function S(e){let{videoPath:t,trimStartMs:n}=e;n>0&&await b({videoPath:t,scriptPath:y(),scriptArgs:[`--trim-start-ms`,String(n)],commandDescription:`Failed to trim the start of the iOS recording`})}async function C(e){let{videoPath:t,telemetryPath:r,exportQuality:i=n,targetLabel:a=`recording`}=e;await b({videoPath:t,scriptPath:v(),scriptArgs:[`--events`,r,`--quality`,i],commandDescription:`Failed to add touch overlays to the ${a}`})}function w(){return Object.freeze({complete:T})}async function T(e){if(await c(e.outputPath),await s(e.outputPath),!await l(e.outputPath))throw Error(`recording was not finalized into a playable video: ${e.outputPath}`);e.trimStartMs&&e.trimStartMs>0&&await S({videoPath:e.outputPath,trimStartMs:e.trimStartMs});let t=i({recording:{outPath:e.outputPath,gestureEvents:[...e.gestureEvents]},...e.trimStartMs===void 0?{}:{trimStartMs:e.trimStartMs}});return!e.showTouches||e.gestureEvents.length===0?{telemetryPath:t}:await E(e,t)}async function E(e,t){let n=_();if(n)return{telemetryPath:t,overlayWarning:n};try{if(await C({videoPath:e.outputPath,telemetryPath:t,exportQuality:e.exportQuality,targetLabel:e.targetLabel}),!await l(e.outputPath))throw Error(`recording post-processing produced an unplayable video`);return{telemetryPath:t}}catch(e){return{telemetryPath:t,overlayWarning:`failed to overlay recording touches: ${e instanceof Error?e.message:String(e)}`}}}export{w as createScreenRecordingFinalizer};
1
+ import{_ as e}from"./sdk-contracts.js";import{t}from"./recording-export-quality.js";import{_ as n}from"./sdk-android-adb.js";import{t as r}from"./version.js";import{n as i}from"./recording-telemetry.js";import{a,i as o,n as s,r as c,t as l}from"./video.js";import u from"node:path";import d from"node:fs";import{fileURLToPath as f}from"node:url";function p(e,t,n,r){let i=`apple/runner/AgentDeviceRunner/RecordingScripts/${e}`,a=`dist/${i}`;return[u.resolve(t,e),u.resolve(n,i),u.resolve(t,`../${i}`),u.resolve(t,`../../${i}`),u.resolve(t,`../../../${i}`),u.resolve(n,a),u.resolve(r,i)]}function m(t){let n=p(t,u.dirname(f(import.meta.url)),r(),process.cwd());for(let e of n)if(d.existsSync(e))return e;throw new e(`COMMAND_FAILED`,`Missing recording helper script: ${t}`,{hint:`Ensure apple/runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled under dist/apple/runner in the package.`,scriptName:t,searchedPaths:n})}let h,g;function _(e=process.platform){if(e!==`darwin`)return`touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry`}function v(){return h??=m(`recording-overlay.swift`),h}function y(){return g??=m(`recording-trim.swift`),g}async function b(t){let{videoPath:r,scriptPath:i,scriptArgs:l,commandDescription:u}=t;await c(r),await s(r);let f=x(r);try{await n(await a({sourcePath:i}),[`--input`,r,`--output`,f,...l],{timeoutMs:12e4,env:o()}),await s(f),d.renameSync(f,r)}catch(t){let n=t instanceof e?t:new e(`COMMAND_FAILED`,String(t),void 0,t instanceof Error?t:void 0);throw new e(`COMMAND_FAILED`,u,{...n.details,videoPath:r,script:i},n)}finally{d.rmSync(f,{force:!0})}}function x(e){let t=u.parse(e),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return u.join(t.dir,`.${t.name}.agent-device-${n}${t.ext||`.mp4`}`)}async function S(e){let{videoPath:t,trimStartMs:n}=e;n>0&&await b({videoPath:t,scriptPath:y(),scriptArgs:[`--trim-start-ms`,String(n)],commandDescription:`Failed to trim the start of the iOS recording`})}async function C(e){let{videoPath:n,telemetryPath:r,exportQuality:i=t,targetLabel:a=`recording`}=e;await b({videoPath:n,scriptPath:v(),scriptArgs:[`--events`,r,`--quality`,i],commandDescription:`Failed to add touch overlays to the ${a}`})}function w(){return Object.freeze({complete:T})}async function T(e){if(await c(e.outputPath),await s(e.outputPath),!await l(e.outputPath))throw Error(`recording was not finalized into a playable video: ${e.outputPath}`);e.trimStartMs&&e.trimStartMs>0&&await S({videoPath:e.outputPath,trimStartMs:e.trimStartMs});let t=i({recording:{outPath:e.outputPath,gestureEvents:[...e.gestureEvents]},...e.trimStartMs===void 0?{}:{trimStartMs:e.trimStartMs}});return!e.showTouches||e.gestureEvents.length===0?{telemetryPath:t}:await E(e,t)}async function E(e,t){let n=_();if(n)return{telemetryPath:t,overlayWarning:n};try{if(await C({videoPath:e.outputPath,telemetryPath:t,exportQuality:e.exportQuality,targetLabel:e.targetLabel}),!await l(e.outputPath))throw Error(`recording post-processing produced an unplayable video`);return{telemetryPath:t}}catch(e){return{telemetryPath:t,overlayWarning:`failed to overlay recording touches: ${e instanceof Error?e.message:String(e)}`}}}export{w as createScreenRecordingFinalizer};
@@ -1 +1 @@
1
- async function e(e){if(e.platform!==`web`)return;let{hasScopedWebProvider:t,resolveWebProvider:n}=await import(`./internal/daemon.js`).then(e=>e.hn);if(!t())return;let r=n();if(!(!r.startRecording||!r.stopRecording))return Object.freeze({start:async e=>await r.startRecording(e),stop:async()=>await r.stopRecording()})}export{e as resolveWebScreenRecordingTransport};
1
+ async function e(e){if(e.platform!==`web`)return;let{hasScopedWebProvider:t,resolveWebProvider:n}=await import(`./provider.js`).then(e=>e.t);if(!t())return;let r=n();if(!(!r.startRecording||!r.stopRecording))return Object.freeze({start:async e=>await r.startRecording(e),stop:async()=>await r.stopRecording()})}export{e as resolveWebScreenRecordingTransport};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-contracts.js";import{H as t}from"./sdk-batch-runner.js";import{n,r}from"./src2.js";const i=Object.freeze({available:!0}),a=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),o=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver provider runtimes do not expose screen recording.`});function s(n){return Object.freeze({owner:n.owner,ownsDevice:n.ownsDevice,bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,n.owner))throw new e(`UNSUPPORTED_OPERATION`,`WebDriver runtime owner identity does not match`);if(!n.ownsDevice(r.device))throw new e(`UNSUPPORTED_PLATFORM`,`WebDriver runtime does not own this device`);return c(n.host,n.owner,r.device)},shutdown:async()=>void 0})}function c(e,t,s){let c=s.platform===`apple`?`ios-device`:`android`,l=r(s,t,{appLog:a,network:a,screenRecording:o}),u=Object.freeze({device:l.facts.device,operations:{appLogInspect:a,appLogDoctor:a,appLogStart:a,appLogReattach:a,appLogCleanup:a,networkDump:i,screenRecordingStart:o,screenRecordingReattach:o,screenRecordingCleanup:o}}),d=Object.freeze({networkDump:async t=>{let r=await e.appLogs.readRecent(t.sessionId,t.maxScanLines),i=n(r.text,{...t,path:r.path,exists:r.exists,lineNumberOffset:r.skippedLines,backend:c});return Object.freeze({source:`app-log`,backend:c,dump:i,notes:Object.freeze(i.entries.length===0?[`No HTTP(s) entries were found in recent session app logs.`]:[])})}});return Object.freeze({device:s,owner:t,facts:u,operations:d,[Symbol.asyncDispose]:async()=>void 0})}export{s as createWebDriverPlatformRuntimeOwner};
1
+ import{n as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import{At as n,Ot as r,T as i,at as a,kt as o,ot as s,pt as c,ut as l}from"./sdk-batch-runner.js";import{C as u,D as d,E as f,T as p,s as m}from"./sdk-device.js";import{l as h,o as g,u as _}from"./device.js";const v=Object.freeze({family:`apple`}),ee=Object.freeze({...v,loadRuntime:async e=>{let{createApplePlatformRuntime:t}=await import(`./runtime4.js`);return t(e)}}),te=Object.freeze({...v,loadInventory:async e=>{let{createAppleInventorySource:t}=await import(`./inventory2.js`);return t(e)}});async function ne(e){let{createAppleShutdownRuntime:t}=await import(`./runtime5.js`);return t(e)}const y=Object.freeze({family:`android`});async function b(e,t,n){let{readAndroidAppState:r}=await import(`./app-state.js`);return await r(e,t,n)}async function x(e){let{parseAndroidForegroundApp:t}=await import(`./app-state.js`);return t(e)}const S=Object.freeze({...y,loadRuntime:async e=>{let{createAndroidPlatformRuntime:t}=await import(`./runtime2.js`);return t(e)}});function C(e){let t=Object.freeze({sdkRoots:Object.freeze([...new Set(e.sdkRoots.map(e=>e.trim()).filter(Boolean))])});return Object.freeze({...y,loadInventory:async e=>{let{createAndroidInventory:n}=await import(`./inventory.js`);return n(e,t)}})}async function w(e){let{createAndroidShutdownRuntime:t}=await import(`./runtime3.js`);return t(e)}const T=Object.freeze({family:`harmonyos`}),re=Object.freeze({...T,loadRuntime:async e=>{let{createHarmonyPlatformRuntime:t}=await import(`./runtime6.js`);return t(e)}});function ie(e){let t=Object.freeze({hdcSdkPath:E(e.hdcSdkPath),devecoSdkHome:E(e.devecoSdkHome),commandLineToolsHome:E(e.commandLineToolsHome)});return Object.freeze({...T,loadInventory:async e=>{let{createHarmonyInventory:n}=await import(`./inventory3.js`);return n(e,t)}})}function E(e){return e?.trim()||void 0}const D=Object.freeze({family:`vega`}),ae=Object.freeze({...D,loadRuntime:async e=>{let{createVegaPlatformRuntime:t}=await import(`./runtime8.js`);return t(e)}}),oe=Object.freeze({...D,loadInventory:async e=>{let{createVegaInventory:t}=await import(`./inventory5.js`);return t(e)}}),O=Object.freeze({family:`linux`}),se=Object.freeze({...O,loadRuntime:async e=>{let{createLinuxPlatformRuntime:t}=await import(`./runtime7.js`);return t(e)}}),ce=Object.freeze({...O,loadInventory:async e=>{let{createLinuxInventory:t}=await import(`./inventory4.js`);return t(e)}}),k=Object.freeze({family:`web`}),A=Object.freeze({...k,loadRuntime:async e=>{let{createWebPlatformRuntime:t}=await import(`./runtime9.js`);return t(e)}}),j=Object.freeze({...k,loadInventory:async()=>{let{createWebInventory:e}=await import(`./inventory6.js`);return e()}});function M(e){let t=new Map,r=new Map;for(let n of e.providerModules??[]){let{runtime:e,module:i}=n,a=o(i.owner);if(i.owner.provider!==e.provider)throw K(`Provider platform runtime metadata is invalid: ${a}`);if(t.has(a))throw K(`Duplicate platform runtime owner: ${a}`);if(r.has(e))throw K(`Duplicate platform module registration for ${e.provider}`);t.set(a,n),r.set(e,i)}let i=new Map,a=new Map,s=new Map,l,u=async()=>{l??=e.loadHost();try{return await l}catch(e){throw l=void 0,e}},d,f,p=Object.freeze({recoverStartupResources:async e=>{await c(e.stateDir,async()=>{await(await u()).applicationResources.recoverStartupResources(e)})},detachForDaemonShutdown:async()=>{d??=u().then(async e=>await e.applicationResources.detachForDaemonShutdown()),await d},finalizeDaemonShutdown:async()=>{f??=u().then(async e=>await e.applicationResources.finalizeDaemonShutdown()),await f}}),m=e=>{let t=o(e.owner),n=s.get(t);if(n&&n!==e)throw K(`Duplicate platform runtime owner: ${t}`);return s.set(t,e),e},h=async t=>{let n=i.get(t);if(n)return await n;let r=e.modules.get(t);if(!r)throw K(`Missing platform runtime module for ${t}`);if(r.family!==t)throw K(`Platform runtime module registered for ${t} declares ${r.family}`);let a=u().then(async e=>{let n=await r.loadRuntime(e);if(n.owner.kind!==`local-family`||n.owner.family!==t)throw K(`Platform runtime module for ${t} returned a different local owner`);return m(n)});i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}},g=async e=>{let t=a.get(e);if(t)return await t;let r=u().then(async t=>{let r=await e.loadRuntime(t);if(!n(r.owner,e.owner))throw K(`Provider platform runtime returned a different advertised owner`);return m(r)});a.set(e,r);try{return await r}catch(t){throw a.get(e)===r&&a.delete(e),t}};return Object.freeze({applicationLifecycle:p,inspectFacts:async t=>{let n=N(e.providerRuntimes,t);if(n){let e=r.get(n);return e?await P(await g(e),t):U(n,t)}return await P(await h(t.platform),t)},bind:async n=>{if(n.intent.kind===`exact-owner`)return await F(await V(n.intent.owner,t,g,h),n);let i=N(e.providerRuntimes,n.device);if(i){let e=r.get(i);return e?await F(await g(e),n):H(i,n.device)}return await F(await h(n.device.platform),n)},shutdown:async()=>{await Promise.allSettled([...s.values()].map(async e=>await e.shutdown())),s.clear(),i.clear(),a.clear()}})}function N(e,t){let n=(e??[]).filter(e=>e.ownsDevice(t));if(n.length>1)throw K(`Multiple provider runtimes claim the selected device`);return n[0]}async function P(e,t){let n=await e.inspectFacts(t);if(!z(t,e.owner,n))throw K(`Platform runtime facts do not match the selected device and owner`);return n}async function F(e,t){let n=await e.bind(t),r=I(e,n,t);if(!r)return n;let i;try{await n[Symbol.asyncDispose]()}catch(e){i=e instanceof Error?e.message:String(e)}throw K(r,i)}function I(e,t,r){if(!n(t.owner,e.owner))return`Platform binding returned a different owner than the selected runtime`;if(!L(t.owner,r))return`Exact platform binding returned a different persisted owner`;if(!f(u(t.device),u(r.device)))return`Platform binding returned a different device identity`;if(!R(t))return`Platform binding facts do not match its device and owner`}function L(e,t){return t.intent.kind!==`exact-owner`||n(e,t.intent.owner)}function R(e){return z(e.device,e.owner,e.facts)}function z(e,t,n){return d(n.device,p(e))&&B(n.device.providerMode,t)}function B(e,t){return t.kind===`local-family`?e===`local`||e===`transport-composed`:e===`provider-runtime`}async function V(e,t,r,i){if(e.kind===`local-family`){let t=await i(e.family);if(n(t.owner,e))return t;throw G(e)}let a=t.get(o(e));if(a)return await r(a.module);throw G(e)}function H(e,t){let n=r(e.provider,`default`),i=Object.freeze({available:!1,reason:`unsupported-provider-mode`});return a(t,n,{appLog:i,appState:i,network:i,lifecycle:W(i)})}function U(e,t){let n=Object.freeze({available:!1,reason:`unsupported-provider-mode`});return s(t,r(e.provider,`default`),{appLog:n,appState:n,network:n,readiness:n,lifecycle:W(n)})}function W(e){return l({resolveOpenTarget:e,prepareApplicationOpen:e,openApplication:e,applyRuntimeHints:e,clearRuntimeHints:e,closeApplication:e,finalizeApplicationClose:e,prepareAppleRunner:e,configureProviderPortReverse:e})}function G(e){return new t(`UNSUPPORTED_OPERATION`,`The exact platform runtime owner is unavailable.`,{reason:`owner-unavailable`,owner:o(e)})}function K(e,n){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,...n?{cleanupError:n}:{}})}function le(e){let t=ue(e.registry,e.loadHost),n=e.provider,r=n?async(e,r)=>{r.signal.throwIfAborted();let i=await n.discover(_(e),r.signal);return r.signal.throwIfAborted(),Y(i),i.kind===`inventory`?{devices:h(i.devices.map(e=>({...e})),e),source:`provider`}:{devices:await t.discover(e,r),source:`local`}}:async(e,n)=>({devices:await t.discover(e,n),source:`local`}),i=Object.freeze({discover:async(e,t)=>(await r(e,t)).devices,discoverWithSource:r});return Object.freeze({providerFirst:i,localOnly:t})}function ue(e,t){let n,r=async()=>{n??=t();try{return await n}catch(e){throw n=void 0,e}},i=new Map,a=async t=>{let n=i.get(t);if(n)return await n;let a=de(e.get(t),r);i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}};return Object.freeze({discover:async(e,t)=>{if(t.signal.throwIfAborted(),e.platform)return await q(a,J(e.platform),e,t);let n=await Promise.all(g.map(async n=>{try{let r=await q(a,J(n),{...e,platform:n},t);return Array.isArray(r)?r:[]}catch{return[]}}));return t.signal.throwIfAborted(),n.flat()}})}async function de(e,t){switch(e.family){case`apple`:return await e.loadInventory(fe(await t()));case`android`:return await e.loadInventory(pe(await t()));case`harmonyos`:return await e.loadInventory(me(await t()));case`vega`:return await e.loadInventory(he(await t()));case`linux`:return await e.loadInventory(ge(await t()));case`web`:return await e.loadInventory()}}function fe(e){return Object.freeze({appleTools:e.appleTools,files:e.files,hostName:e.hostName,hostOs:e.hostOs,observations:e.observations})}function pe(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory,toolchains:e.toolchains})}function me(e){return Object.freeze({commands:e.commands,files:e.files,toolchains:e.toolchains})}function he(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory})}function ge(e){return Object.freeze({hostName:e.hostName,hostOs:e.hostOs})}async function q(e,t,n,r){let i=await e(t);r.signal.throwIfAborted();let a=await i.discover(n,r);return r.signal.throwIfAborted(),_e(t,a),h(a,n)}function J(e){return m(e)?`apple`:e}function _e(e,n){let r=n.find(t=>t.platform!==e);if(r)throw new t(`COMMAND_FAILED`,`Platform inventory source ${e} returned a ${r.platform} device.`,{expectedFamily:e,actualFamily:r.platform,deviceId:r.id})}function Y(e){if(typeof e==`object`&&e){let t=e;if(t.kind===`declined`&&!(`devices`in t)||t.kind===`inventory`&&Array.isArray(t.devices))return}throw new t(`COMMAND_FAILED`,`Provider device inventory returned an invalid outcome.`,{reason:`provider_inventory_contract_violation`})}var ve=e({createPlatformDeviceInventoryGateways:()=>Z,createPlatformRuntimeGateway:()=>$,parseAndroidForegroundApp:()=>be,platformModuleRegistry:()=>X,platformRuntimeModules:()=>Q,readAndroidAppStateWithHost:()=>ye});async function ye(e,t,n){return await b(e,t,n)}async function be(e){return await x(e)}const xe=C({sdkRoots:Ce(process.env.ANDROID_SDK_ROOT,process.env.ANDROID_HOME)}),Se=Object.freeze({apple:async e=>await ne(e),android:async e=>await w(e)}),X=i([te,xe,ie({hdcSdkPath:process.env.HDC_SDK_PATH,devecoSdkHome:process.env.DEVECO_SDK_HOME,commandLineToolsHome:process.env.HARMONYOS_COMMAND_LINE_TOOLS}),oe,ce,j]);function Z(e){return le({registry:X,loadHost:async()=>{let{createDeviceInventoryHost:e}=await import(`./platform-runtime-host.js`);return e()},provider:e})}const Q=new Map([[`apple`,ee],[`android`,S],[`harmonyos`,re],[`vega`,ae],[`linux`,se],[`web`,A]]);function $(e){return M({modules:Q,loadHost:async()=>{let{createPlatformRuntimeHost:t}=await import(`./platform-runtime-operation-host.js`);return t({sessionsDir:e.sessionsDir,resolveSessionArtifacts:e.resolveSessionArtifacts,shutdownLoaders:Se})},providerRuntimes:e.providerRuntimes,providerModules:e.providerModules})}function Ce(...e){return e.flatMap(e=>{let t=e?.trim();return t?[t]:[]})}export{$ as n,ve as r,Z as t};
@@ -0,0 +1 @@
1
+ import{_ as e}from"./sdk-contracts.js";import{At as t,B as n,H as r,ct as i,dt as a,lt as o,ot as s,ut as c}from"./sdk-batch-runner.js";import{n as l}from"./src3.js";function u(e){return n({owner:`WebDriver`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!0,binding:r({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)})})}const d=Object.freeze({available:!0}),f=Object.freeze({available:!1,reason:`unsupported-provider-mode`}),p=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver provider runtimes do not expose screen recording.`}),m=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Headless boot is unavailable for provider-owned devices.`}),h=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`WebDriver provider runtimes do not expose app inventory.`}),g=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`This WebDriver provider runtime does not expose app deployment.`}),_=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Push notifications are unavailable for WebDriver provider-owned devices.`}),v=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`}),y=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`This WebDriver provider runtime does not expose snapshot capture for this device.`}),b=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver provider runtimes do not expose iOS simulator custom snapshot actions.`}),x=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver provider runtimes do not expose a foreground app-state operation.`}),S=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Apple runner preparation is unavailable for WebDriver-owned devices.`}),C=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver open is supported only for its owned iOS or Android mobile-device sessions.`}),w=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver close is supported only for its owned iOS or Android mobile-device sessions.`}),T=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Runtime hints are not applied to provider-owned devices.`}),E=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver provider runtimes do not expose port reverse.`});function D(e){let t=e.platform===`android`&&e.kind===`device`&&e.target===`mobile`||e.platform===`apple`&&e.kind===`device`&&e.target===`mobile`&&e.appleOs===`ios`,n=t?d:C,r=t?d:w;return c({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:T,clearRuntimeHints:T,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:S,configureProviderPortReverse:E})}function O(n){return Object.freeze({owner:n.owner,ownsDevice:n.ownsDevice,inspectFacts:async e=>A(n,e),bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,n.owner))throw new e(`UNSUPPORTED_OPERATION`,`WebDriver runtime owner identity does not match`);if(!n.ownsDevice(r.device))throw new e(`UNSUPPORTED_PLATFORM`,`WebDriver runtime does not own this device`);if(!M(n,r.device))throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session is no longer active for this device.`);return k(n,r.device,r.scope.signal)},shutdown:async()=>void 0})}function k(e,t,n){let r=t.platform===`apple`?`ios-device`:`android`,o=A(e,t),s=o.operations.deployApp,c=Object.freeze({ensureReady:async()=>({...t,booted:!0}),bootTarget:async()=>({...t,booted:!0}),...a(u({device:t,signal:n,getInteractor:(t,n)=>e.getInteractor?.(t,n)}),o.operations),...o.operations.captureSnapshot.available?i({device:t,signal:n,resolveInteractor:n=>e.getInteractor?.(t,n)}):{},networkDump:async t=>{let n=await e.host.appLogs.readRecent(t.sessionId,t.maxScanLines),i=l(n.text,{...t,path:n.path,exists:n.exists,lineNumberOffset:n.skippedLines,backend:r});return Object.freeze({source:`app-log`,backend:r,dump:i,notes:Object.freeze(i.entries.length===0?[`No HTTP(s) entries were found in recent session app logs.`]:[])})},...s.available&&e.deployment?{deployApp:async r=>await e.deployment.deployApp(t,r,n),materializeAppSource:async r=>await N(e.host,t,r,n),deployMaterializedApp:async r=>await e.deployment.deployMaterializedApp(t,r,n)}:{}});return Object.freeze({device:t,owner:e.owner,facts:o,operations:c,[Symbol.asyncDispose]:async()=>void 0})}function A(e,t){if(!M(e,t)){let n=s(t,e.owner,{appLog:v,appDeployment:v,network:v,screenRecording:v,lifecycle:c({resolveOpenTarget:v,prepareApplicationOpen:v,openApplication:v,applyRuntimeHints:v,clearRuntimeHints:v,closeApplication:v,finalizeApplicationClose:v,prepareAppleRunner:v,configureProviderPortReverse:v})});return Object.freeze({device:n.device,operations:{appLogInspect:v,appLogDoctor:v,appLogStart:v,appLogReattach:v,appLogCleanup:v,deployApp:v,materializeAppSource:v,deployMaterializedApp:v,sendPushNotification:v,appState:v,networkDump:v,screenRecordingStart:v,screenRecordingReattach:v,screenRecordingCleanup:v,...o({capture:v,customActions:v,withoutActiveApp:v}),ensureReady:v,bootTarget:v,bootTargetHeadless:v,listApps:v,shutdownTarget:v,...c({resolveOpenTarget:v,prepareApplicationOpen:v,openApplication:v,applyRuntimeHints:v,clearRuntimeHints:v,closeApplication:v,finalizeApplicationClose:v,prepareAppleRunner:v,configureProviderPortReverse:v})}})}let n=e.deployment?.fact(t)??g,r=s(t,e.owner,{appLog:f,appDeployment:g,network:f,screenRecording:p,lifecycle:D(t)});return Object.freeze({device:r.device,operations:{appLogInspect:f,appLogDoctor:f,appLogStart:f,appLogReattach:f,appLogCleanup:f,deployApp:n,materializeAppSource:n,deployMaterializedApp:n,sendPushNotification:_,appState:x,networkDump:d,screenRecordingStart:p,screenRecordingReattach:p,screenRecordingCleanup:p,...o({capture:e.snapshotAvailable!==!1&&e.getInteractor!==void 0&&j(t)?d:y,customActions:b,withoutActiveApp:e.snapshotAvailable!==!1&&e.getInteractor!==void 0&&j(t)?d:y}),ensureReady:d,bootTarget:d,bootTargetHeadless:m,listApps:h,shutdownTarget:{available:!1,reason:`unsupported-provider-mode`,hint:`WebDriver owns the target lifecycle for provider-owned devices.`},...D(t)}})}function j(e){return e.kind===`device`&&e.target===`mobile`&&(e.platform===`android`||e.platform===`apple`&&e.appleOs===`ios`)}function M(e,t){return e.isSessionActive?.(t)??e.ownsDevice(t)}async function N(e,t,n,r){return t.platform===`apple`?await e.appleDeployment.prepareArtifact(n,{signal:r}):await e.androidDeployment.prepareArtifact(n,{signal:r})}export{O as createWebDriverPlatformRuntimeOwner};
package/dist/src/plist.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./parser.js";import{i as t,n}from"./tool-provider.js";import{t as r}from"./plist-xml.js";import{promises as i}from"node:fs";async function a(e,r){try{let t=(await n(e))?.[r];if(typeof t==`string`&&t.length>0)return t}catch{}try{let n=await t(`plutil`,[`-extract`,r,`raw`,`-o`,`-`,e],{allowFailure:!0});if(n.exitCode===0){let e=n.stdout.trim();if(e.length>0)return e}}catch{}try{return o(await i.readFile(e,`utf8`),r)}catch{return}}function o(t,n){let i;return r(e(t),(e,t)=>{i!==void 0||e!==n||t.name!==`string`||(i=t.text??void 0)}),i}export{a as t};
1
+ import{t as e}from"./parser.js";import{i as t,n}from"./tool-provider.js";import{t as r}from"./plist-xml.js";import{promises as i}from"node:fs";async function a(e,r,a){try{let t=(await n(e,a))?.[r];if(typeof t==`string`&&t.length>0)return t}catch{a?.throwIfAborted()}try{let n=await t(`plutil`,[`-extract`,r,`raw`,`-o`,`-`,e],{allowFailure:!0,signal:a});if(n.exitCode===0){let e=n.stdout.trim();if(e.length>0)return e}}catch{a?.throwIfAborted()}try{return o(await i.readFile(e,{encoding:`utf8`,signal:a}),r)}catch{a?.throwIfAborted();return}}function o(t,n){let i;return r(e(t),(e,t)=>{i!==void 0||e!==n||t.name!==`string`||(i=t.text??void 0)}),i}export{a as t};
@@ -0,0 +1 @@
1
+ import{A as e,_ as t}from"./sdk-contracts.js";import{b as n}from"./location-coordinates.js";import{A as r}from"./sdk-android-adb.js";import{a as i,i as a,n as o,r as s,t as c}from"./png-worker-contract.js";import l from"node:path";import u,{promises as d}from"node:fs";import{fileURLToPath as f}from"node:url";import{Worker as p}from"node:worker_threads";function m(e,t){try{let n=f(e),r=l.extname(n)||`.js`;return[l.join(l.dirname(n),`${t}${r}`),l.join(l.dirname(n),`internal`,`${t}${r}`)].find(e=>u.existsSync(e))??null}catch{return null}}var h=class extends Error{};let g=null,_=!1,v=!1,y=0;const b=new Map;function x(e){_=!0,!v&&(v=!0,r({level:`warn`,phase:`png_worker_unavailable`,data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function S(n){let r=b.get(n.id);r&&(b.delete(n.id),T(),n.ok?r.resolve(n.result):r.reject(new t(e(n.error.code),n.error.message,n.error.details)))}function C(e,t){g===e&&(x(t.message),g=null,e.terminate().catch(()=>{}),w(new h(`PNG worker failed: ${t.message}`)))}function w(e){let t=[...b.values()];b.clear();for(let n of t)n.reject(e)}function T(){g&&(b.size>0?g.ref():g.unref())}function E(){if(_)return null;if(g)return g;let e=m(import.meta.url,`png-worker`);if(!e)return x(`worker entry module not found next to the current module`),null;try{let t=new p(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,S),t.on(`error`,e=>{C(t,e)}),t.on(`exit`,e=>{C(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),g=t,t}catch(e){return x(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function D(e){let t=E();if(!t)return Promise.reject(new h(`PNG worker is unavailable`));y+=1;let n=y;return new Promise((r,i)=>{b.set(n,{resolve:r,reject:i}),T();try{t.postMessage({...e,id:n})}catch(e){b.delete(n),T(),i(new h(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function O(e,t){try{return await D(e)}catch(e){if(e instanceof h)return t();throw e}}function k(){E()}async function A(){let e=g;g=null,w(new h(`PNG worker terminated`)),e&&await e.terminate()}async function j(e,t){let n=await O({kind:`decode`,png:e,label:t},()=>{let n=a(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}),r=new i.PNG({width:n.width,height:n.height});return r.data=c(n.data),r}async function M(e){return c((await O({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:i.PNG.sync.write(e)}))).png)}async function N(e,t,n){let{kind:r,...i}=await O({kind:`rgb-difference`,firstPng:e,secondPng:t,label:n},()=>({kind:`rgb-difference`,...o(a(e,n),a(t,n))}));return i}async function P(e){let{kind:t,...n}=await O({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...s(e)}));return{...n,diffData:c(n.diffData)}}async function F(e,r){let{min:i,max:a}=n;if(!Number.isFinite(r)||r<i||r>a)throw new t(`INVALID_ARGS`,`Screenshot scale must be between ${i} and ${a}`);if(r===1)return;let o=await j(await d.readFile(e),`screenshot`),s=Math.max(1,Math.round(o.width*r)),c=Math.max(1,Math.round(o.height*r));await d.writeFile(e,await M(L(o,s,c)))}async function I(e,n,r){if(!Number.isInteger(n)||n<1||!Number.isInteger(r)||r<1)throw new t(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await j(await d.readFile(e),`screenshot`);i.width===n&&i.height===r||await d.writeFile(e,await M(L(i,n,r)))}function L(e,t,n){let r=new i.PNG({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}export{j as a,A as c,P as i,F as n,M as o,N as r,k as s,I as t};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-contracts.js";import{createRequire as t}from"node:module";var n=Object.defineProperty,r=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),i=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},a=t(import.meta.url),o=r(((e,t)=>{let n=a(`util`),r=a(`stream`),i=t.exports=function(){r.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};n.inherits(i,r),i.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},i.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},i.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},i.prototype.destroySoon=i.prototype.end,i.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},i.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},i.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},i.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},i.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),s=r((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),c=r(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),l=r(((e,t)=>{let n=s(),r=c();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});c===8?this._xComparison=s:c===16?this._xComparison=s*2:this._xComparison=1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++)t[a]=e[1+a]+(a>i?t[a-r]:0)},a.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++)t[i]=e[1+i]+(r?r[i]:0)},a.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0;t[o]=n+Math.floor((c+s)/2)}},a.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0;t[s]=n+r(l,c,u)}},a.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),u=r(((e,t)=>{let n=a(`util`),r=o(),i=l(),s=t.exports=function(e){r.call(this);let t=[],n=this;this._filter=new i(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};n.inherits(s,r)})),d=r(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),f=r(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),p=r(((e,t)=>{let n=d(),r=f(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),m=r((e=>{let t=s(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function i(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a);break}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function a(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function o(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),h=r(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),g=r(((e,t)=>{let n=a(`util`),r=a(`zlib`),i=o(),s=u(),c=p(),l=m(),d=h(),f=t.exports=function(e){i.call(this),this._parser=new c(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};n.inherits(f,i),f.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},f.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=r.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:t});let n=e,i=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&i(e)}),this._filter.on(`complete`,this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}this._inflate.write(e)},f.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new s(this._bitmapInfo)},f.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},f.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},f.prototype._simpleTransparency=function(){this._metaData.alpha=!0},f.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},f.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},f.prototype._complete=function(e){if(this.errord)return;let t;try{let n=l.dataToBitMap(e,this._bitmapInfo);t=d(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),_=r(((e,t)=>{let n=d();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),v=r(((e,t)=>{let n=c();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function a(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function o(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function s(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:a,2:s,3:u,4:f},h={0:i,1:o,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),y=r(((e,t)=>{let n=d(),r=f(),i=_(),o=v(),s=a(`zlib`),c=t.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32*1024,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null?!0:e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:n.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:n.COLORTYPE_COLOR_ALPHA,[n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};c.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},c.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},c.prototype.filterData=function(e,t,r){let a=i(e,t,r,this._options),s=n.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(a,t,r,this._options,s)},c.prototype._packChunk=function(e,t){let n=t?t.length:0,i=Buffer.alloc(n+12);return i.writeUInt32BE(n,0),i.writeUInt32BE(e,4),t&&t.copy(i,8),i.writeInt32BE(r.crc32(i.slice(4,i.length-4)),i.length-4),i},c.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*n.GAMMA_DIVISION),0),this._packChunk(n.TYPE_gAMA,t)},c.prototype.packIHDR=function(e,t){let r=Buffer.alloc(13);return r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(n.TYPE_IHDR,r)},c.prototype.packIDAT=function(e){return this._packChunk(n.TYPE_IDAT,e)},c.prototype.packIEND=function(){return this._packChunk(n.TYPE_IEND,null)}})),b=r(((e,t)=>{let n=a(`util`),r=a(`stream`),i=d(),o=y(),s=t.exports=function(e){r.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};n.inherits(s,r),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(i.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let a=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(a)}})),x=r(((e,t)=>{let n=a(`assert`).ok,r=a(`zlib`),i=a(`util`),o=a(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<r.Z_MIN_CHUNK&&(e.chunkSize=r.Z_MIN_CHUNK),r.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,i){if(typeof i==`function`)return r.Inflate._processChunk.call(this,e,t,i);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let r=c-t;if(n(r>=0,`have should not go down`),r>0){let e=a._buffer.slice(a._offset,a._offset+r);if(a._offset+=r,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0?(d+=s-e,s=e,!0):!1}n(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},i.inherits(s,r.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=r.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}t.exports=e=d,e.Inflate=s,e.createInflate=c,e.inflateSync=d})),S=r(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),C=r((e=>{let t=S(),n=l();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),w=r(((e,t)=>{let n=!0,r=a(`zlib`),i=x();r.deflateSync||(n=!1);let o=S(),s=C(),c=p(),l=m(),u=h();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let a;function d(e){a=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:d,metadata:p,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),a)throw a;let S=Buffer.concat(y);y.length=0;let C;if(f.interlace)C=r.inflateSync(S);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.height;C=i(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,f);S=null;let T=l.dataToBitMap(w,f);w=null;let E=u(T,f,t.skipRescale);return f.data=E,f.gamma=_||0,f}})),T=r(((e,t)=>{let n=!0,r=a(`zlib`);r.deflateSync||(n=!1);let i=d(),o=y();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let a=new o(t||{}),s=[];s.push(Buffer.from(i.PNG_SIGNATURE)),s.push(a.packIHDR(e.width,e.height)),e.gamma&&s.push(a.packGAMA(e.gamma));let c=a.filterData(e.data,e.width,e.height),l=r.deflateSync(c,a.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(a.packIDAT(l)),s.push(a.packIEND()),Buffer.concat(s)}})),E=r((e=>{let t=w(),n=T();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),D=r((e=>{let t=a(`util`),n=a(`stream`),r=g(),i=b(),o=E(),s=e.PNG=function(e){n.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new r(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new i(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};t.inherits(s,n),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();function O(t,n){try{return D.PNG.sync.read(t)}catch(t){throw new e(`COMMAND_FAILED`,`Failed to decode ${n} as PNG`,{label:n,reason:t instanceof Error?t.message:String(t)})}}const k=.78,A={r:220,g:0,b:0};function j(e){let{baselineData:t,currentData:n,maxColorDistance:r}=e,i=e.width*e.height,a=Buffer.alloc(i*4),o=new Uint8Array(i),s=0;for(let e=0,i=0;e<t.length;e+=4,i+=1){let c=t[e]-n[e],l=t[e+1]-n[e+1],u=t[e+2]-n[e+2];if(Math.sqrt(c**2+l**2+u**2)>r){s+=1,o[i]=1;let t=M(n,e);a[e]=N(t,A.r,k),a[e+1]=N(t,A.g,k),a[e+2]=N(t,A.b,k),a[e+3]=255;continue}let d=M(n,e);a[e]=d,a[e+1]=d,a[e+2]=d,a[e+3]=255}return{diffData:a,diffMask:o,differentPixels:s}}function M(e,t){return N(Math.round(e[t]*.299+e[t+1]*.587+e[t+2]*.114),255,.72)}function N(e,t,n){return Math.round(e*(1-n)+t*n)}function P(e,t){let n={first:{width:e.width,height:e.height,dataLength:e.data.length},second:{width:t.width,height:t.height,dataLength:t.data.length}};if(e.width!==t.width||e.height!==t.height)return{...n,status:`dimension_mismatch`};let r=e.width*e.height;if(e.data.length!==t.data.length||e.data.length!==r*4)return{...n,status:`data_length_mismatch`};let i=0;for(let n=0;n<e.data.length;n+=4)i+=Math.abs(e.data[n]-t.data[n]),i+=Math.abs(e.data[n+1]-t.data[n+1]),i+=Math.abs(e.data[n+2]-t.data[n+2]);return{...n,status:`compared`,differencePercent:100*i/(765*r)}}function F(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}export{D as a,O as i,P as n,i as o,j as r,F as t};
1
+ import{r as e,t}from"./rolldown-runtime.js";import{_ as n}from"./sdk-contracts.js";var r=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=n.exports=function(){i.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};r.inherits(a,i),a.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},a.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},a.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},a.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},a.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),i=t((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),a=t(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),o=t(((e,t)=>{let n=i(),r=a();function o(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let s=t.exports=function(e,t){let r=e.width,i=e.height,a=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],a){let e=n.getImagePasses(r,i);for(let t=0;t<e.length;t++)this._images.push({byteWidth:o(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:o(r,s,c),height:i,lineIndex:0});c===8?this._xComparison=s:c===16?this._xComparison=s*2:this._xComparison=1};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},s.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++)t[a]=e[1+a]+(a>i?t[a-r]:0)},s.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++)t[i]=e[1+i]+(r?r[i]:0)},s.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0;t[o]=n+Math.floor((c+s)/2)}},s.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0;t[s]=n+r(l,c,u)}},s.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),s=t(((t,n)=>{let i=e(`util`),a=r(),s=o(),c=n.exports=function(e){a.call(this);let t=[],n=this;this._filter=new s(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};i.inherits(c,a)})),c=t(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),l=t(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),u=t(((e,t)=>{let n=c(),r=l(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),d=t((e=>{let t=i(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function a(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a);break}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function o(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function s(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,i=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=a(e,c));let f;f=c<=8?Buffer.alloc(r*i*4):new Uint16Array(r*i*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,i),g=t.getInterlaceIterator(r,i);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:i}]}for(let t=0;t<h.length;t++)c===8?m=o(h[t],f,g,l,e,m):s(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),f=t(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),p=t(((t,n)=>{let i=e(`util`),a=e(`zlib`),o=r(),c=s(),l=u(),p=d(),m=f(),h=n.exports=function(e){o.call(this),this._parser=new l(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};i.inherits(h,o),h.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},h.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=a.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,a.Z_MIN_CHUNK);this._inflate=a.createInflate({chunkSize:t});let n=e,r=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&r(e)}),this._filter.on(`complete`,this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,i(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}this._inflate.write(e)},h.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new c(this._bitmapInfo)},h.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},h.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},h.prototype._simpleTransparency=function(){this._metaData.alpha=!0},h.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},h.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},h.prototype._complete=function(e){if(this.errord)return;let t;try{let n=p.dataToBitMap(e,this._bitmapInfo);t=m(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),m=t(((e,t)=>{let n=c();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),h=t(((e,t)=>{let n=a();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function o(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function s(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function c(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:o,2:c,3:u,4:f},h={0:i,1:s,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),g=t(((t,n)=>{let r=c(),i=l(),a=m(),o=h(),s=e(`zlib`),u=n.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32*1024,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null?!0:e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:r.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:r.COLORTYPE_COLOR_ALPHA,[r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};u.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},u.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},u.prototype.filterData=function(e,t,n){let i=a(e,t,n,this._options),s=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(i,t,n,this._options,s)},u.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(i.crc32(r.slice(4,r.length-4)),r.length-4),r},u.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*r.GAMMA_DIVISION),0),this._packChunk(r.TYPE_gAMA,t)},u.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(r.TYPE_IHDR,n)},u.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},u.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),_=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=c(),o=g(),s=n.exports=function(e){i.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};r.inherits(s,i),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(a.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(i)}})),v=t(((t,n)=>{let r=e(`assert`).ok,i=e(`zlib`),a=e(`util`),o=e(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<i.Z_MIN_CHUNK&&(e.chunkSize=i.Z_MIN_CHUNK),i.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,n){if(typeof n==`function`)return i.Inflate._processChunk.call(this,e,t,n);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let n=c-t;if(r(n>=0,`have should not go down`),n>0){let e=a._buffer.slice(a._offset,a._offset+n);if(a._offset+=n,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0?(d+=s-e,s=e,!0):!1}r(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},a.inherits(s,i.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=i.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}n.exports=t=d,t.Inflate=s,t.createInflate=c,t.inflateSync=d})),y=t(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),b=t((e=>{let t=y(),n=o();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),x=t(((t,n)=>{let r=!0,i=e(`zlib`),a=v();i.deflateSync||(r=!1);let o=y(),s=b(),c=u(),l=d(),p=f();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n;function u(e){n=e}let d;function f(e){d=e}function m(e){d.transColor=e}function h(e){d.palette=e}function g(){d.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:u,metadata:f,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),n)throw n;let S=Buffer.concat(y);y.length=0;let C;if(d.interlace)C=i.inflateSync(S);else{let e=((d.width*d.bpp*d.depth+7>>3)+1)*d.height;C=a(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,d);S=null;let T=l.dataToBitMap(w,d);w=null;let E=p(T,d,t.skipRescale);return d.data=E,d.gamma=_||0,d}})),S=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=c(),o=g();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n=new o(t||{}),s=[];s.push(Buffer.from(a.PNG_SIGNATURE)),s.push(n.packIHDR(e.width,e.height)),e.gamma&&s.push(n.packGAMA(e.gamma));let c=n.filterData(e.data,e.width,e.height),l=i.deflateSync(c,n.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(n.packIDAT(l)),s.push(n.packIEND()),Buffer.concat(s)}})),C=t((e=>{let t=x(),n=S();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),w=t((t=>{let n=e(`util`),r=e(`stream`),i=p(),a=_(),o=C(),s=t.PNG=function(e){r.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new i(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new a(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};n.inherits(s,r),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();function T(e,t){try{return w.PNG.sync.read(e)}catch(e){throw new n(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}const E=.78,D={r:220,g:0,b:0};function O(e){let{baselineData:t,currentData:n,maxColorDistance:r}=e,i=e.width*e.height,a=Buffer.alloc(i*4),o=new Uint8Array(i),s=0;for(let e=0,i=0;e<t.length;e+=4,i+=1){let c=t[e]-n[e],l=t[e+1]-n[e+1],u=t[e+2]-n[e+2];if(Math.sqrt(c**2+l**2+u**2)>r){s+=1,o[i]=1;let t=k(n,e);a[e]=A(t,D.r,E),a[e+1]=A(t,D.g,E),a[e+2]=A(t,D.b,E),a[e+3]=255;continue}let d=k(n,e);a[e]=d,a[e+1]=d,a[e+2]=d,a[e+3]=255}return{diffData:a,diffMask:o,differentPixels:s}}function k(e,t){return A(Math.round(e[t]*.299+e[t+1]*.587+e[t+2]*.114),255,.72)}function A(e,t,n){return Math.round(e*(1-n)+t*n)}function j(e,t){let n={first:{width:e.width,height:e.height,dataLength:e.data.length},second:{width:t.width,height:t.height,dataLength:t.data.length}};if(e.width!==t.width||e.height!==t.height)return{...n,status:`dimension_mismatch`};let r=e.width*e.height;if(e.data.length!==t.data.length||e.data.length!==r*4)return{...n,status:`data_length_mismatch`};let i=0;for(let n=0;n<e.data.length;n+=4)i+=Math.abs(e.data[n]-t.data[n]),i+=Math.abs(e.data[n+1]-t.data[n+1]),i+=Math.abs(e.data[n+2]-t.data[n+2]);return{...n,status:`compared`,differencePercent:100*i/(765*r)}}function M(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}export{w as a,T as i,j as n,O as r,M as t};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-contracts.js";import{t}from"./timeouts.js";import{t as n}from"./owner-identity.js";import r from"node:path";import i from"node:fs";async function a(n){let{lockDirPath:a,owner:c}=n,u=r.join(a,`owner.json`),d=Date.now()+(n.timeoutMs??3e4),f=n.pollMs??100,p=n.ownerGraceMs??5e3,m=n.description??`process lock`;for(i.mkdirSync(r.dirname(a),{recursive:!0});Date.now()<d;)try{i.mkdirSync(a),o(u,c);let e=!1;return async()=>{e||(e=!0,i.rmSync(a,{recursive:!0,force:!0}))}}catch(e){let n=e;if(n.code!==`EEXIST`)throw n;if(s(a,u,p))continue;await t(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:a,...l(a,u)})}function o(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(n,JSON.stringify(t),`utf8`),i.renameSync(n,e)}function s(e,t,n){let r=null;try{r=i.statSync(e)}catch{return!0}let a=c(t);return a?u(a)?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0)}function c(e){try{return JSON.parse(i.readFileSync(e,`utf8`))}catch{return null}}function l(e,t){let r=Date.now(),a=c(t),o;try{o=Math.max(0,Math.round(r-i.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...a?{ownerPid:a.pid,ownerStartTime:a.startTime,ownerAgeMs:Math.max(0,Math.round(r-a.acquiredAtMs)),ownerLiveness:n({owner:a})}:{}}}function u(e){return n({owner:e})!==`owner-process-dead`}export{a as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{t}from"./timeouts.js";import{t as n}from"./owner-identity.js";import r from"node:path";import i from"node:fs";async function a(n){let{lockDirPath:a,owner:c}=n,u=r.join(a,`owner.json`),d=Date.now()+(n.timeoutMs??3e4),f=n.pollMs??100,p=n.ownerGraceMs??5e3,m=n.description??`process lock`;for(i.mkdirSync(r.dirname(a),{recursive:!0});Date.now()<d;)try{i.mkdirSync(a),o(u,c);let e=!1;return async()=>{e||(e=!0,i.rmSync(a,{recursive:!0,force:!0}))}}catch(e){let n=e;if(n.code!==`EEXIST`)throw n;if(s(a,u,p))continue;await t(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:a,...l(a,u)})}function o(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(n,JSON.stringify(t),`utf8`),i.renameSync(n,e)}function s(e,t,n){let r=null;try{r=i.statSync(e)}catch{return!0}let a=c(t);return a?u(a)?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0)}function c(e){try{return JSON.parse(i.readFileSync(e,`utf8`))}catch{return null}}function l(e,t){let r=Date.now(),a=c(t),o;try{o=Math.max(0,Math.round(r-i.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...a?{ownerPid:a.pid,ownerStartTime:a.startTime,ownerAgeMs:Math.max(0,Math.round(r-a.acquiredAtMs)),ownerLiveness:n({owner:a})}:{}}}function u(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{a as t};
@@ -0,0 +1 @@
1
+ import e from"node:path";import t from"node:fs";function n(e){let t=i(e);return t?r(t):`auto`}function r(e){let t={...e.dependencies??{},...e.devDependencies??{}};return typeof t[`@callstack/repack`]==`string`?`repack`:typeof t.expo==`string`?`expo`:typeof t[`react-native`]==`string`?`react-native`:`auto`}function i(n){if(!n)return;let r=e.join(n,`package.json`);try{return JSON.parse(t.readFileSync(r,`utf8`))}catch{return}}export{r as n,i as r,n as t};
@@ -1 +1 @@
1
- import{n as e}from"./version.js";import{v as t}from"./sdk-android-adb.js";import{t as n}from"./src3.js";const r=n({clientVersion:e(),runHostCommand:async(e,n)=>({stdout:(await t(e,[...n],{maxBuffer:10*1024*1024,timeoutMs:3e4})).stdout})});export{r as t};
1
+ import{_ as e}from"./sdk-android-adb.js";import{n as t}from"./version.js";import{t as n}from"./src2.js";const r=n({clientVersion:t(),runHostCommand:async(t,n)=>({stdout:(await e(t,[...n],{maxBuffer:10*1024*1024,timeoutMs:3e4})).stdout})});export{r as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import{Jr as n,Pt as r}from"./sdk-batch-runner.js";import{A as i,_ as a,f as o}from"./sdk-android-adb.js";import{t as s}from"./timeouts.js";import{t as c}from"./scoped-provider.js";import{i as l,n as ee,o as te,r as ne}from"./agent-browser-tool.js";function u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d(e,t){return u(e)?e[t]:void 0}function f(e,t){let n=d(e,t);return typeof n==`string`?n:void 0}function re(e,t){let n=d(e,t);return typeof n==`boolean`?n:void 0}function p(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}const ie=[h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j];function ae(e){let t=ie.map(e=>`${e.toString()};`).join(``),n=se(e.action),r=m(e.durationMs),i=m(e.bucketMs);return`(()=>{${t}return ${j.name}({action:${n},durationMs:${r},bucketMs:${i}})})()`}function oe(e){let t=r(ce(e),{source:`media-elements`,backend:`agent-browser`,durationMs:0,elapsedMs:0,bucketMs:1e3,activeFallback:!1,mediaElementCount:0,sourceCount:0});return{...t,source:`media-elements`,mediaElementCount:t.mediaElementCount??0}}function se(e){switch(e){case`start`:return`'start'`;case`stop`:return`'stop'`;default:return`'status'`}}function m(e){return e===void 0||!Number.isFinite(e)?`undefined`:String(Math.trunc(e))}function h(e){return!Number.isFinite(e)||e<=0?-90:Math.max(-90,Math.min(0,Math.round(20*Math.log10(e))))}function g(e,t){e.notes.includes(t)||e.notes.push(t)}function _(){return Array.from(document.querySelectorAll(`audio,video`))}function v(e,t){if(!e||e.state===`stopped`)return e;clearInterval(e.timer),clearTimeout(e.timeout),e.timer=void 0,e.timeout=void 0,e.state=`stopped`,e.active=!1,e.reason=t,e.stoppedAt=Date.now();for(let t of e.analysers)try{t.analyser.disconnect(),t.source.disconnect(),t.audible&&t.source.connect(e.context.destination)}catch{}if(e.resumeOnGesture){for(let t of[`click`,`pointerdown`,`keydown`])window.removeEventListener(t,e.resumeOnGesture,!0);e.resumeOnGesture=void 0}return e}function y(e){let t=window.AudioContext||window.webkitAudioContext;if(!t)return;let n=window[e];if(n&&n.state!==`closed`)return n;let r=new t;return window[e]=r,r}function b(e,t,n){if(!(!t.currentSrc&&!t.src&&t.readyState===0))try{window[n]||(window[n]=new WeakMap);let r=window[n].get(t);return r||(r=e.context.createMediaElementSource(t),window[n].set(t,r)),r.disconnect(),{source:r,audible:!0}}catch{return}}function x(e,t){if(!(!t||typeof t.getAudioTracks!=`function`)&&t.getAudioTracks().length!==0)return{source:e.context.createMediaStreamSource(t),audible:!1}}function S(e,t){if(typeof t.captureStream==`function`)return x(e,t.captureStream())}function C(e,t){let n=e.context.createAnalyser();n.fftSize=2048,t.source.connect(n),n.connect(t.audible?e.context.destination:e.sink),e.analysers.push({...t,analyser:n,buffer:new Float32Array(n.fftSize)})}function w(e,t){let n=_();e.mediaElementCount=n.length;for(let r of n){if(e.seen.has(r))continue;let n=x(e,r.srcObject)??S(e,r)??b(e,r,t);if(!n){g(e,`Some media elements do not expose capturable audio to Web Audio.`);continue}e.seen.add(r),C(e,n)}e.sourceCount=e.analysers.length,e.sourceCount===0&&g(e,`No capturable page media audio sources were found yet.`)}function T(e){let t=0,n=0,r=0;for(let i of e.analysers){i.analyser.getFloatTimeDomainData(i.buffer);for(let e of i.buffer)t+=e*e,n+=1,r=Math.max(r,Math.abs(e))}return{rms:n>0?Math.sqrt(t/n):0,peak:r}}function E(e){let t=Math.ceil(e.durationMs/e.bucketMs)+2;e.rmsDbfs.length>t&&e.rmsDbfs.splice(0,e.rmsDbfs.length-t),e.peakDbfs.length>t&&e.peakDbfs.splice(0,e.peakDbfs.length-t)}function D(e,t){if(!e||e.state!==`running`)return;w(e,t);let n=T(e),r=h(n.rms),i=h(n.peak);e.rmsDbfs.push(r),e.peakDbfs.push(i),e.heard=e.heard||r>-90||i>-90,E(e),Date.now()-e.startedAt>=e.durationMs&&v(e,`duration`)}function O(e,t){return{audio:`probe`,state:`stopped`,active:!1,heard:!1,source:`media-elements`,backend:`agent-browser`,durationMs:Number(e.durationMs)||1e4,elapsedMs:0,bucketMs:Number(e.bucketMs)||1e3,sampleCount:0,mediaElementCount:_().length,sourceCount:0,rmsDbfs:[],peakDbfs:[],notes:t}}function k(e,t,n,r){return e?{audio:`probe`,state:e.state,active:e.state===`running`,heard:e.heard,source:`media-elements`,backend:`agent-browser`,durationMs:e.durationMs,elapsedMs:Math.max(0,Math.min((e.stoppedAt||Date.now())-e.startedAt,e.durationMs)),bucketMs:e.bucketMs,sampleCount:e.rmsDbfs.length,mediaElementCount:_().length,sourceCount:e.sourceCount,rmsDbfs:e.rmsDbfs.slice(),peakDbfs:e.peakDbfs.slice(),startedAt:new Date(e.startedAt).toISOString(),stoppedAt:e.stoppedAt?new Date(e.stoppedAt).toISOString():void 0,reason:e.reason,notes:[n,r,...e.notes]}:O(t,[n,r])}function A(e,t,n,r,i,a,o){t&&v(t,`restarted`);let s=y(r);if(!s)return O(e,[`Web Audio API is not available in this browser context.`]);let c=s.createGain();c.gain.value=0,c.connect(s.destination);let l={state:`running`,active:!0,context:s,sink:c,seen:new WeakSet,analysers:[],mediaElementCount:0,sourceCount:0,durationMs:Math.max(100,Number(e.durationMs)||1e4),bucketMs:Math.max(100,Number(e.bucketMs)||1e3),startedAt:Date.now(),stoppedAt:void 0,reason:void 0,heard:!1,rmsDbfs:[],peakDbfs:[],notes:[]};try{s.resume()}catch{g(l,`AudioContext could not be resumed by the probe.`)}l.resumeOnGesture=()=>{try{s.resume()}catch{g(l,`AudioContext could not be resumed from a user gesture.`)}};for(let e of[`click`,`pointerdown`,`keydown`])window.addEventListener(e,l.resumeOnGesture,{capture:!0,once:!0});return w(l,i),l.timer=setInterval(()=>D(l,i),l.bucketMs),l.timeout=setTimeout(()=>v(l,`duration`),l.durationMs),window[n]=l,k(l,e,a,o)}function j(e){let t=`__agentDeviceAudioProbe`,n=`__agentDeviceAudioProbeSources`,r=`Audio probe samples HTML media elements exposed to Web Audio; it is not whole-tab or system audio capture.`,i=`URL-backed media elements may be routed through the probe AudioContext while they are observed.`,a=window[t];return a&&a.state===`running`&&Date.now()-a.startedAt>=a.durationMs&&(D(a,n),v(a,`duration`)),e.action===`start`?A(e,a,t,`__agentDeviceAudioProbeContext`,n,r,i):e.action===`stop`?(a&&D(a,n),v(a,`manual`),k(a,e,r,i)):(a&&D(a,n),k(a,e,r,i))}function ce(e){return u(e)?u(e.result)?e.result:e:{}}function le(e,t={}){let n=ue(e),r=me(t.limit),i=t.include===`headers`||t.include===`all`,a=n.slice(-r).reverse().map(e=>fe(e,i)),o=t.include===`body`||t.include===`all`?[`agent-browser network requests does not expose request or response bodies.`]:void 0;return{entries:a,backend:`agent-browser`,redacted:!1,...o?{notes:o}:{}}}function ue(e){let t=u(e)&&Array.isArray(e.requests)?e.requests:e;return Array.isArray(t)?t.filter(de).map(e=>({headers:M(e.headers),method:f(e,`method`),mimeType:f(e,`mimeType`),requestId:f(e,`requestId`),resourceType:f(e,`resourceType`),responseHeaders:M(e.responseHeaders),status:p(e,`status`),timestamp:pe(e.timestamp),url:f(e,`url`)})):[]}function de(e){return u(e)}function fe(e,t){let r=e.timestamp===void 0?void 0:N(e.timestamp),i=n({requestId:e.requestId,resourceType:e.resourceType,mimeType:e.mimeType});return n({timestamp:r,method:e.method,url:e.url,status:e.status,requestHeaders:t?e.headers:void 0,responseHeaders:t?e.responseHeaders:void 0,metadata:Object.keys(i).length>0?i:void 0})}function M(e){if(!u(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function pe(e){if(typeof e==`number`||typeof e==`string`)return e}function N(e){if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?N(t):e}let t=e>1e10?e:e*1e3,n=new Date(t);return Number.isNaN(n.getTime())?String(e):n.toISOString()}function me(e){return typeof e!=`number`||!Number.isInteger(e)?25:Math.max(1,Math.min(e,200))}async function he(e,t){let n=_e(f(e,`snapshot`)??``,I(d(e,`refs`)));return t&&await ge(n,t),{nodes:n.map((e,t)=>({...e.node,index:t})),truncated:re(e,`truncated`)}}async function ge(e,t){for(let n=0;n<e.length;n+=8){let r=e.slice(n,n+8),i=await Promise.all(r.map(e=>t(e.ref)));for(let[e,t]of i.entries())t&&(r[e].node.rect=t)}}function _e(e,t){let n=new Map(t.map(e=>[e.ref,e])),r=[],i=new Set,a=new Map;for(let t of e.split(/\r?\n/)){let e=be(t);if(!e)continue;i.add(e);let o=n.get(e)?.data,s=ve(t),c=P(t,o,s),l=ye(a,s);l!==void 0&&(c.parentIndex=l),r.push({ref:e,node:{...c,index:r.length}}),a.set(s,r.length-1)}for(let e of t)i.has(e.ref)||r.push({ref:e.ref,node:{...F(e.data),index:r.length}});return r}function P(e,t,n){let r=xe(e)??R(t,[`role`,`type`]);return{index:0,type:r,role:r,label:Se(e)??R(t,[`label`,`name`,`text`]),value:Ce(e)??R(t,[`value`]),depth:n,enabled:z(t,[`enabled`]),focused:z(t,[`focused`])}}function F(e){let t=R(e,[`role`,`type`]);return{index:0,type:t,role:t,label:R(e,[`label`,`name`,`text`]),value:R(e,[`value`]),enabled:z(e,[`enabled`]),focused:z(e,[`focused`])}}function I(e){return Array.isArray(e)?e.flatMap(e=>{let t=u(e)?e:void 0,n=L(R(t,[`ref`,`id`])??String(e));return n?[{ref:n,data:t}]:[]}):u(e)?Object.entries(e).flatMap(([e,t])=>{let n=L(e);return n?[{ref:n,data:u(t)?t:void 0}]:[]}):[]}function ve(e){let t=e.match(/^\s*/)?.[0].length??0;return Math.floor(t/2)}function ye(e,t){for(let n=t-1;n>=0;--n){let t=e.get(n);if(t!==void 0)return t}}function be(e){return L(e.match(/\bref=['"]?(@?e\d+)['"]?/i)?.[1]??e.match(/@?(e\d+)\b/i)?.[1])}function L(e){let t=e?.trim().replace(/^@/,``);return t&&/^e\d+$/i.test(t)?t.toLowerCase():null}function xe(e){return e.replace(/\[[^\]]*ref[^\]]*\]/gi,``).replace(/@?e\d+\b/gi,``).replace(/^[\s|├└─>*-]+/g,``).trim().match(/^([A-Za-z][\w-]*)\b/)?.[1]}function Se(e){return e.match(/"([^"]+)"/)?.[1]??e.match(/'([^']+)'/)?.[1]}function Ce(e){return we(e)??e.match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/i)?.slice(1).find(B)??e.match(/\bvalue:\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/i)?.slice(1).find(B)}function we(e){return e.match(/\]\s*:\s*(.+)$/)?.[1]?.trim()||void 0}function R(e,t){if(e)for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function z(e,t){if(e)for(let n of t){let t=e[n];if(typeof t==`boolean`)return t}}function B(e){return typeof e==`string`}const V=`agent-browser`,H="Run `agent-device web setup` to install the managed web backend.";function U(e={}){let t=e.session?.trim(),n=async(n,r)=>await Pe(n,{session:t,options:e,signal:r});return{async open(e){await n([`open`,e])},async close(){await n([`close`])},async startRecording(e){await n([`record`,`start`,e])},async stopRecording(){await n([`record`,`stop`])},async snapshot(e){return await Ae(t=>n(t,e?.signal),e)},async screenshot(e,t){await n([`screenshot`,...t?.fullscreen?[`--full`]:[],e])},async setViewport(e,t){await n([`set`,`viewport`,String(e),String(t)])},async click(e,t){await W(n,e,t)},async hover(e,t){await G(n,e,t)},async hoverRef(e){await n([`hover`,J(e)])},async clickRef(e){await n([`click`,J(e)])},async fill(e,t,r){await W(n,e,t),await n([`press`,Ve()]),await n([`keyboard`,`type`,r])},async fillRef(e,t){await n([`fill`,J(e),t])},async typeText(e){await n([`keyboard`,`type`,e])},async scroll(e,t){return await Te(n,e,t),t?.durationMs===void 0?{}:{durationMs:t.durationMs}},async dumpNetwork(e){return le(await n([`network`,`requests`]),e)},async probeAudio(e){return oe(await n([`eval`,ae(e)]))}}}async function Te(e,t,n){let r=Ee(n);for(let n of r)await e(ke(t,n.distance)),n.delayAfterMs>0&&await s(n.delayAfterMs)}function Ee(e){let t=e?.pixels??e?.amount,n=e?.durationMs;if(n===void 0||n<=0)return[{distance:t,delayAfterMs:0}];let r=Math.max(1,Math.min(20,Math.ceil(n/50))),i=n/Math.max(1,r-1);return De(e,r).map((e,t)=>({distance:e,delayAfterMs:t<r-1?i:0}))}function De(e,t){let n=e?.pixels??e?.amount??300;return e?.amount!==void 0&&e.pixels===void 0?Array.from({length:t},()=>n/t):Oe(Math.round(n),t)}function Oe(e,t){let n=Math.floor(e/t),r=e-n*t;return Array.from({length:t},(e,t)=>t<r?n+1:n)}function ke(e,t){return[`scroll`,e,...t===void 0?[]:[String(t)]]}async function W(e,t,n){await G(e,t,n),await e([`mouse`,`down`]),await e([`mouse`,`up`])}async function G(e,t,n){await e([`mouse`,`move`,String(Math.round(t)),String(Math.round(n))])}async function Ae(e,t){return await he(await e(je(t)),t?.includeRects?async t=>await Me(e,t):void 0)}function je(e){return[`snapshot`,...e?.interactiveOnly?[`--interactive`]:[],...e?.raw?[]:[`--compact`],...typeof e?.depth==`number`?[`--depth`,String(e.depth)]:[],...e?.scope?[`--selector`,e.scope]:[]]}async function Me(e,t){try{return He(await e([`get`,`box`,J(t)]))}catch(e){if(Ne(e))return;throw e}}function Ne(e){let t=e instanceof Error?e.message:String(e);return!/\bstale\b/i.test(t)&&/\bbox\b|not visible|not found|no element/i.test(t)}async function Pe(e,t){let{session:n,options:r,signal:i}=t,a=[...e,`--json`,...n?[`--session`,n]:[]],o=await Fe(a,r,i);return Le(Re(o.stdout,o.stderr,a,o.exitCode),o,a)}async function Fe(e,t,n){let r=``,i=``,o=0;try{await Ie(t);let s=await l({stateDir:t.stateDir}),c=await a(s.command,e,{allowFailure:!0,env:s.env,timeoutMs:3e4,signal:n});r=c.stdout,i=c.stderr,o=c.exitCode}catch(t){throw ze(t,e)}return{stdout:r,stderr:i,exitCode:o}}async function Ie(e){if(!e.openWebSessionNames)return;let t=ee({stateDir:e.stateDir});if(t.installed)try{await te(t,{openWebSessionNames:e.openWebSessionNames()})}catch(e){i({level:`warn`,phase:`web_agent_browser_provider_orphan_cleanup_failed`,data:{error:e instanceof Error?e.message:String(e)}})}}function Le(e,n,r){if(!u(e))return e;if((e.success??e.ok)===!1)throw new t(q(e.code),Be(e),{cmd:V,args:r,hint:f(e,`hint`)??H,agentBrowserError:e.error});if(n.exitCode!==0)throw new t(`COMMAND_FAILED`,`agent-browser command failed`,o(n,{cmd:V,args:r,stdout:n.stdout.slice(0,500),stderr:n.stderr.slice(0,500),hint:f(e,`hint`)??H}));return Object.hasOwn(e,`data`)?e.data:e}function Re(e,n,r,i){try{return JSON.parse(e)}catch(a){let o=i!==0;throw new t(`COMMAND_FAILED`,o?`agent-browser command failed`:`agent-browser returned invalid JSON`,{cmd:V,args:r,...o?{exitCode:i}:{},stdout:e.slice(0,500),stderr:n.slice(0,500),hint:H},a instanceof Error?a:void 0)}}function ze(e,n){let r=ne(e);return r.code===`TOOL_MISSING`?new t(`TOOL_MISSING`,r.message,{...r.details??{},cmd:V,args:n,hint:K(r)},r):r.code===`COMMAND_FAILED`?new t(`COMMAND_FAILED`,r.message,{...r.details??{},cmd:V,args:n,hint:K(r)},r):r}function K(e){return typeof e.details?.hint==`string`?e.details.hint:H}function Be(e){let t=e.error;if(typeof t==`string`&&t.trim())return t.trim();if(u(t)){let e=f(t,`message`)??f(t,`error`);if(e)return e}return f(e,`message`)??`agent-browser command failed`}function q(e){return typeof e==`string`&&e.length>0?e:`COMMAND_FAILED`}function J(e){return e.startsWith(`@`)?e:`@${e}`}function Ve(){return process.platform===`darwin`?`Meta+a`:`Control+a`}function He(e){let t=u(e)&&u(e.box)?e.box:e;if(u(t))return Ue(t)??We(t)}function Ue(e){return Y(p(e,`x`),p(e,`y`),p(e,`width`),p(e,`height`))}function We(e){let t=p(e,`left`),n=p(e,`top`),r=p(e,`right`),i=p(e,`bottom`);return Y(t,n,X(r,t),X(i,n))}function Y(e,t,n,r){if(!(e===void 0||t===void 0||n===void 0||r===void 0))return{x:e,y:t,width:n,height:r}}function X(e,t){return e===void 0||t===void 0?void 0:e-t}var Ge=e({hasScopedWebProvider:()=>Ke,resolveWebProvider:()=>Q,withWebProvider:()=>$});const Z=c(U());function Q(e){return Z.resolve(e)}function Ke(){return Z.hasScope()}async function $(e,t){return await Z.run(e,t)}export{U as i,Q as n,$ as r,Ge as t};
package/dist/src/proxy.js CHANGED
@@ -1,2 +1,2 @@
1
- import{S as e,_ as t}from"./sdk-contracts.js";import{bt as n,mt as r}from"./prepare-kind.js";import{a as i,i as a}from"./agent-device-client.js";import{ct as o,dt as s,lt as c,ot as l,pt as u,r as d,st as f}from"./screenshot-result.js";import{t as p}from"./timing-safe-equal.js";import{t as m}from"./shared.js";import{randomBytes as h,randomUUID as g}from"node:crypto";import{pipeline as ee}from"node:stream/promises";import{Readable as _}from"node:stream";import v from"node:http";const y=`${l}/`,b=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,f],x=[`content-type`,`content-disposition`,`x-request-id`];function S(e){let t=P(e);return v.createServer((e,n)=>{C(e,n,t).catch(e=>{X(n,e)})})}async function C(e,t,n){let r=te(e.url??`/`);if(e.method===`GET`&&r===`/health`){await w(t,n);return}if(!L(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await u(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!U(e,n.clientToken,i)){Y(t,r,q(i));return}await E({req:e,res:t,route:r,options:n,rpcBody:i})}async function w(e,t){let n=await T(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,{upstream:n})))}async function T(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:V({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function E(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=B(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=V(t,i.upstreamToken,r),l=H(t,r,a,i.upstreamToken);await D({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:AbortSignal.timeout(i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}async function D(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,O(i,n),k(t,n),z(r)){await A({req:t,res:n,response:i,clientToken:a});return}await N(i,n)}function O(e,t){for(let n of x){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function k(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,J(e))}async function A(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(j(a,t,i))}function j(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let i=r;if(!i.upload||typeof i.upload.url!=`string`)return e;let a=M(i.upload.url,t);if(!a)return e;let s=i.upload.headers&&typeof i.upload.headers==`object`?{...i.upload.headers}:{};return Object.assign(s,o(n)),JSON.stringify({...r,upload:{...i.upload,url:a,headers:s}})}function M(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function N(e,t){if(!e.body){t.end();return}await ee(_.fromWeb(e.body),t)}function P(e){return{upstreamBaseUrl:F(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:I(e.upstreamToken,`upstreamToken`),clientToken:I(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function F(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function I(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function te(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(y)?`/${t.slice(y.length)}`:t}function L(e,t){return e===`/rpc`?t===`POST`:R(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)?t===`GET`:!1}function R(e,t){return e===`/upload`||z(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function z(e){return e===`/upload/preflight`}function B(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function V(e,t,n){let r=new Headers;for(let t of b){let n=e.headers[t];typeof n==`string`&&n.trim()&&r.set(t,n)}n===`/rpc`&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);for(let[e,n]of Object.entries(o(t)))r.set(e,n);return r}function H(e,t,n,r){if(!(e.method===`GET`||e.method===`HEAD`))return t===`/rpc`?G(n??``,r):e}function U(e,t,n){let r=W(e,n);return r.length>0&&p(r,t)}function W(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=K(t);if(e)return e}return``}function G(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function K(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function q(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function J(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function Y(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function X(t,n){if(t.headersSent){t.destroy(n instanceof Error?n:void 0);return}let r=e(n);t.statusCode=r.code===`INVALID_ARGS`?400:500,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const Z=async({positionals:e,flags:n})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await Q(n);return m(n,r,()=>oe(r)),await se(),!0};async function Q(e){let n=i({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:e.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await a(n),o=ne(r.info.httpPort),s=re(e),l=S({upstreamBaseUrl:o,upstreamToken:r.info.token,clientToken:s});await ie(l,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let u=l.address();if(!u||typeof u==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let d=`http://${ae(u.address)}:${u.port}`;return{proxyBaseUrl:d,agentDeviceBaseUrl:c(d),token:s,upstreamBaseUrl:o,stateDir:n.paths.baseDir}}function ne(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function re(e){return e.daemonAuthToken?.trim()||h(32).toString(`hex`)}function ie(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ae(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function oe(e,t={}){let r=t.useColor??n(),i=$(`✓`,`green`,r),a=$(e.proxyBaseUrl,`cyan`,r),o=$(`<tunnel URL>`,`cyan`,r),s=$(e.token,`yellow`,r);return[`${i} Proxy listening at ${a}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${o}`,`Daemon auth token: ${s}`].join(`
1
+ import{E as e,_ as t}from"./sdk-contracts.js";import{Ct as n,_t as r}from"./script-source-bundle.js";import{a as i,i as a}from"./agent-device-client.js";import{dt as o,ft as s,gt as c,lt as l,mt as u,r as d,ut as f}from"./screenshot-result.js";import{t as p}from"./timing-safe-equal.js";import{t as m}from"./shared.js";import{randomBytes as h,randomUUID as g}from"node:crypto";import{pipeline as ee}from"node:stream/promises";import{Readable as _}from"node:stream";import v from"node:http";const y=`${l}/`,b=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,f],x=[`content-type`,`content-disposition`,`x-request-id`];function S(e){let t=P(e);return v.createServer((e,n)=>{C(e,n,t).catch(e=>{X(n,e)})})}async function C(e,t,n){let r=te(e.url??`/`);if(e.method===`GET`&&r===`/health`){await w(t,n);return}if(!L(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await c(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!U(e,n.clientToken,i)){Y(t,r,q(i));return}await E({req:e,res:t,route:r,options:n,rpcBody:i})}async function w(e,t){let n=await T(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,{upstream:n})))}async function T(e){let t=new URL(u(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:V({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function E(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=B(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=V(t,i.upstreamToken,r),l=H(t,r,a,i.upstreamToken);await D({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:AbortSignal.timeout(i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}async function D(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,O(i,n),k(t,n),z(r)){await A({req:t,res:n,response:i,clientToken:a});return}await N(i,n)}function O(e,t){for(let n of x){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function k(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,J(e))}async function A(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(j(a,t,i))}function j(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let i=r;if(!i.upload||typeof i.upload.url!=`string`)return e;let a=M(i.upload.url,t);if(!a)return e;let s=i.upload.headers&&typeof i.upload.headers==`object`?{...i.upload.headers}:{};return Object.assign(s,o(n)),JSON.stringify({...r,upload:{...i.upload,url:a,headers:s}})}function M(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function N(e,t){if(!e.body){t.end();return}await ee(_.fromWeb(e.body),t)}function P(e){return{upstreamBaseUrl:F(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:I(e.upstreamToken,`upstreamToken`),clientToken:I(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function F(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function I(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function te(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(y)?`/${t.slice(y.length)}`:t}function L(e,t){return e===`/rpc`?t===`POST`:R(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)?t===`GET`:!1}function R(e,t){return e===`/upload`||z(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function z(e){return e===`/upload/preflight`}function B(e,t,n){let r=new URL(u(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function V(e,t,n){let r=new Headers;for(let t of b){let n=e.headers[t];typeof n==`string`&&n.trim()&&r.set(t,n)}n===`/rpc`&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);for(let[e,n]of Object.entries(o(t)))r.set(e,n);return r}function H(e,t,n,r){if(!(e.method===`GET`||e.method===`HEAD`))return t===`/rpc`?G(n??``,r):e}function U(e,t,n){let r=W(e,n);return r.length>0&&p(r,t)}function W(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=K(t);if(e)return e}return``}function G(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function K(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function q(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function J(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function Y(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function X(t,n){if(t.headersSent){t.destroy(n instanceof Error?n:void 0);return}let r=e(n);t.statusCode=r.code===`INVALID_ARGS`?400:500,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const Z=async({positionals:e,flags:n})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await Q(n);return m(n,r,()=>oe(r)),await se(),!0};async function Q(e){let n=i({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:e.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await a(n),o=ne(r.info.httpPort),c=re(e),l=S({upstreamBaseUrl:o,upstreamToken:r.info.token,clientToken:c});await ie(l,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let u=l.address();if(!u||typeof u==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let d=`http://${ae(u.address)}:${u.port}`;return{proxyBaseUrl:d,agentDeviceBaseUrl:s(d),token:c,upstreamBaseUrl:o,stateDir:n.paths.baseDir}}function ne(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function re(e){return e.daemonAuthToken?.trim()||h(32).toString(`hex`)}function ie(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ae(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function oe(e,t={}){let r=t.useColor??n(),i=$(`✓`,`green`,r),a=$(e.proxyBaseUrl,`cyan`,r),o=$(`<tunnel URL>`,`cyan`,r),s=$(e.token,`yellow`,r);return[`${i} Proxy listening at ${a}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${o}`,`Daemon auth token: ${s}`].join(`
2
2
  `)}function $(e,t,n){return n?r(e,t,{validateStream:!1}):e}function se(){return new Promise(()=>{})}export{Z as proxyCommand};
@@ -1 +1 @@
1
- import{S as e}from"./sdk-contracts.js";import{nr as t}from"./sdk-batch-runner.js";import{Xt as n,gn as r,z as i}from"./prepare-kind.js";import{p as a}from"./runtime.js";import{c as o,o as s,s as c,t as l}from"./dispatch.js";import{tn as u}from"./internal/daemon.js";import{t as d}from"./interaction-snapshot.js";import{r as f,t as p}from"./interaction-touch-reference-frame.js";async function m(t){let{req:r,sessionName:s,sessionStore:l}=t;if(r.command!==n.reactNative)return null;let u=h(r.positionals??[]);if(!u.ok)return u.response;let f=l.get(s);if(!f)return c();let p=o(n.reactNative,f.device,{message:`react-native dismiss-overlay is not supported on this device`});if(p)return p;try{let e=await d(f,r.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(i(e.snapshotQuality))return _(e.snapshotQuality);let n=a(e.nodes),o=n.primaryAction;return o?await v(t,f,e,o):g(n.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:s(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?s(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...r(`No React Native overlay detected`)}}}function _(e){return s(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,i,a){let{req:o,sessionStore:s}=e,c=Date.now();u(n);let d=await l(n.device,`press`,[String(a.point.x),String(a.point.y)],o.flags?.out,e.contextFromFlags(o.flags,n.appBundleId,n.trace?.outPath))??{},m=Date.now(),h=await y(e,n),g=t({...p(i.nodes),...d,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:h.verified,verificationRequired:!h.verified,verificationWarning:h.verificationWarning,nextCommand:h.nextCommand,...r(b(h))});return f({session:n,sessionStore:s,command:o.command,positionals:o.positionals??[],flags:o.flags,result:g,responseData:g,actionStartedAt:c,actionFinishedAt:m})}async function y(e,t){let{req:n,sessionStore:r}=e,o=await d(t,n.flags,r,e.contextFromFlags,{interactiveOnly:!0});return i(o.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:a(o.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
1
+ import{E as e}from"./sdk-contracts.js";import{Jr as t}from"./sdk-batch-runner.js";import{yn as n}from"./script-source-bundle.js";import{n as r}from"./command-catalog.js";import{t as i}from"./verdict.js";import{c as a}from"./runtime.js";import{a as o,o as s,s as c,t as l}from"./dispatch.js";import{bt as u}from"./internal/daemon.js";import{t as d}from"./interaction-snapshot.js";import{n as f,t as p}from"./interaction-common.js";async function m(t){let{req:n,sessionName:o,sessionStore:l}=t;if(n.command!==r.reactNative)return null;let u=h(n.positionals??[]);if(!u.ok)return u.response;let f=l.get(o);if(!f)return s();let p=c(r.reactNative,f.device,{message:`react-native dismiss-overlay is not supported on this device`});if(p)return p;try{let e=await d(f,n.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(i(e.snapshotQuality))return _(e.snapshotQuality);let r=a(e.nodes),o=r.primaryAction;return o?await v(t,f,e,o):g(r.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:o(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?o(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...n(`No React Native overlay detected`)}}}function _(e){return o(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,r,i,a){let{req:o,sessionStore:s}=e,c=Date.now();u(r);let d=await l(r.device,`press`,[String(a.point.x),String(a.point.y)],o.flags?.out,e.contextFromFlags(o.flags,r.appBundleId,r.trace?.outPath))??{},m=Date.now(),h=await y(e,r),g=t({...f(i.nodes),...d,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:h.verified,verificationRequired:!h.verified,verificationWarning:h.verificationWarning,nextCommand:h.nextCommand,...n(b(h))});return p({session:r,sessionStore:s,command:o.command,positionals:o.positionals??[],flags:o.flags,result:g,responseData:g,actionStartedAt:c,actionFinishedAt:m})}async function y(e,t){let{req:n,sessionStore:r}=e,o=await d(t,n.flags,r,e.contextFromFlags,{interactiveOnly:!0});return i(o.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:a(o.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
@@ -1 +1 @@
1
- import{S as e,_ as t}from"./sdk-contracts.js";import{Mt as n}from"./version.js";import{M as r,N as i,j as a}from"./sdk-batch-runner.js";import{C as o,E as s}from"./sdk-device.js";import{en as c,nn as l,rn as u}from"./prepare-kind.js";import{i as d}from"./output-path.js";import{g as f}from"./dispatch.js";import{Mt as p,Pt as m,d as h,f as g,l as _,u as v}from"./internal/daemon.js";import{t as y}from"./device-ready.js";import{t as b}from"./handler-utils.js";import{t as x}from"./recording-telemetry.js";import S from"node:path";function C(e){let r=n(`record`,e.flags);if(r)throw new t(`INVALID_ARGS`,r);let i=e.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new t(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(e.flags?.quality);if(e.flags?.quality!==void 0&&a===void 0)throw new t(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:w(e.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:e.flags?.hideTouches!==!0,hideTouchesRequested:e.flags?.hideTouches===!0}}function w(e){if(e===void 0)return`app`;if(e===`app`||e===`device`||e===`system`)return e;throw new t(`INVALID_ARGS`,`record scope must be app, device, or system`)}function T(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:p(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function E(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function D(e){return{action:`start`,...e.clientOutPath?{requestedFileName:S.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function O(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function k(e){let t=[A(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:S.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?x(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:S.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function A(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:S.basename(e.clientOutPath??e.outPath)}}async function j(t){try{return await M(t)}catch(t){return{ok:!1,error:e(t)}}}async function M(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=N(t,i);if(a.kind===`start`&&!c(o)&&!i)return T(t);let s=await P(e,i);return a.kind===`start`?await F(e,s,C(t),a.use):await z(e,s,a.kind)}function N(e,t){let n=w(e.flags?.recordingScope);return{scope:n,plan:a({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function P(e,t){let n=t?.device??await f(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t||(await y(n),H(e,n))}async function F(e,t,n,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=(await e.bindDevice(t.device,r)).facts.screenRecordingStart;if(!a.available)return O(a);let o=await e.bindDevice(t.device,i),{fence:s,outputPaths:c}=I(e,t),l=await o.operations.screenRecordingStart(L(e,t,n,s,c.outputPath));await _({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:o.owner,fence:s,...l,throwIfCanceled:e.throwIfCanceled});let u=e.sessionStore.get(e.sessionName)?.screenRecording;if(!u)throw TypeError(`Screen recording adoption did not publish a live handle`);let d=u.handle.inspect();return b(e.sessionStore,t,e.req,e.req.command,D(d)),E(d,e.sessionStore.ensureSessionDir(e.sessionName),c.requestedPath)}function I(e,t){let n=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName));return{fence:g.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:d({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function L(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:R(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function R(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function z(e,t,n){let r;try{r=n===`stop-live`?await v({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}):await V(e,t)}catch(n){throw B(e,t),n}let i=k(r);return b(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:r.outPath,...r.clientOutPath?{requestedFileName:S.basename(r.clientOutPath)}:{},showTouches:r.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),i}function B(e,t){if(!t.recordOnlySession)return;let n=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),r=g.store.read(n);r.status===`decoded`&&r.envelope.lifecycle===`completed`&&e.sessionStore.delete(e.sessionName)}async function V(e,n){let r=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),a=g.store.read(r);if(a.status!==`decoded`||a.envelope.lifecycle!==`open`)throw new t(`INVALID_ARGS`,`no active recording`);if(a.envelope.sessionId!==e.sessionName)throw new t(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!s(a.envelope.device,o(n.device)))throw new t(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`});return await h({resourcePath:r,scope:e.requestScope,acquireControl:async(t,r)=>{let a=await e.bindExactDevice(n.device,t.owner,t.fence,i,r);return{reattach:async e=>await a.operations.screenRecordingReattach({envelope:e}),cleanup:async e=>await a.operations.screenRecordingCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>{}}}})}function H(e,t){return{name:e.sessionName,sessionScope:m(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{j as t};
1
+ import{E as e,_ as t}from"./sdk-contracts.js";import{w as n}from"./location-coordinates.js";import{$ as r,et as i,tt as a}from"./sdk-batch-runner.js";import{C as o,E as s}from"./sdk-device.js";import{on as c}from"./script-source-bundle.js";import{n as l,r as u}from"./recording-export-quality.js";import{i as d}from"./output-path.js";import{p as f}from"./dispatch.js";import{C as p,Q as m,S as h,et as g,t as _,w as v,x as y}from"./internal/daemon.js";import{t as b}from"./device-ready.js";import{t as x}from"./handler-utils.js";import{t as S}from"./recording-telemetry.js";import C from"node:path";function w(e){let r=n(`record`,e.flags);if(r)throw new t(`INVALID_ARGS`,r);let i=e.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new t(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(e.flags?.quality);if(e.flags?.quality!==void 0&&a===void 0)throw new t(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:T(e.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:e.flags?.hideTouches!==!0,hideTouchesRequested:e.flags?.hideTouches===!0}}function T(e){if(e===void 0)return`app`;if(e===`app`||e===`device`||e===`system`)return e;throw new t(`INVALID_ARGS`,`record scope must be app, device, or system`)}function E(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:m(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function D(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function O(e){return{action:`start`,...e.clientOutPath?{requestedFileName:C.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function k(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function A(e){let t=[j(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?S(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:C.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function j(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:C.basename(e.clientOutPath??e.outPath)}}async function M(t){try{return await N(t)}catch(t){return{ok:!1,error:e(t)}}}async function N(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=P(t,i);if(a.kind===`start`&&!c(o)&&!i)return E(t);let s=await F(e,i);return a.kind===`start`?await I(e,s,w(t),a.use):await B(e,s,a.kind)}function P(e,t){let n=T(e.flags?.recordingScope);return{scope:n,plan:r({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function F(e,t){let n=t?.device??await f(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t||(await b(n),U(e,n))}async function I(e,t,n,r){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=(await e.bindDevice(t.device,i)).facts.screenRecordingStart;if(!a.available)return k(a);let o=await e.bindDevice(t.device,r),{fence:s,outputPaths:c}=L(e,t),l=await o.operations.screenRecordingStart(R(e,t,n,s,c.outputPath));await y({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:o.owner,fence:s,...l,throwIfCanceled:e.throwIfCanceled});let u=e.sessionStore.get(e.sessionName)?.screenRecording;if(!u)throw TypeError(`Screen recording adoption did not publish a live handle`);let d=u.handle.inspect();return x(e.sessionStore,t,e.req,e.req.command,O(d)),D(d,e.sessionStore.ensureSessionDir(e.sessionName),c.requestedPath)}function L(e,t){let n=v.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName));return{fence:v.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:d({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function R(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:z(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function z(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function B(e,t,n){let r;try{r=n===`stop-live`?await h({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}):await H(e,t)}catch(n){throw V(e,t),n}let i=A(r);return x(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:r.outPath,...r.clientOutPath?{requestedFileName:C.basename(r.clientOutPath)}:{},showTouches:r.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),i}function V(e,t){if(!t.recordOnlySession)return;let n=v.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),r=v.store.read(n);r.status===`decoded`&&r.envelope.lifecycle===`completed`&&e.sessionStore.delete(e.sessionName)}async function H(e,n){let r=v.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),i=v.store.read(r);if(i.status!==`decoded`||i.envelope.lifecycle!==`open`)throw new t(`INVALID_ARGS`,`no active recording`);if(i.envelope.sessionId!==e.sessionName)throw new t(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!s(i.envelope.device,o(n.device)))throw new t(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`});return await p({resourcePath:r,scope:e.requestScope,acquireControl:async(t,r)=>_({runtime:await e.bindExactDevice(n.device,t.owner,t.fence,a,r),dispose:async()=>{}})})}function U(e,t){return{name:e.sessionName,sessionScope:g(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{M as t};
@@ -1 +1 @@
1
- import{x as e}from"./screenshot-result.js";import{o as t}from"./dispatch.js";import{t as n}from"./handler-utils.js";import{t as r}from"./record-runtime.js";import i from"node:path";import a from"node:fs";function o(e){let n=(e.req.positionals?.[0]??``).toLowerCase();if(n!==`start`&&n!==`stop`)return t(`INVALID_ARGS`,`trace requires start|stop`);let r=e.sessionStore.get(e.sessionName);return r?n===`start`?s(e.req,e.sessionStore,r):c(e.req,e.sessionStore,r):t(`SESSION_NOT_FOUND`,`No active session`)}function s(r,o,s){if(s.trace)return t(`INVALID_ARGS`,`trace already in progress`);let c=e.expandHome(r.positionals?.[1]??o.defaultTracePath(s));return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),s.trace={outPath:c,startedAt:Date.now()},n(o,s,r,r.command,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}function c(e,r,a){if(!a.trace)return t(`INVALID_ARGS`,`no active trace`);let o=l(a.trace.outPath,e.positionals?.[1]);a.trace=void 0,n(r,a,e,e.command,{action:`stop`,outPath:o});let s=e.meta?.clientArtifactPaths?.outPath??o;return{ok:!0,data:{trace:`stopped`,outPath:o,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:o,localPath:s,fileName:i.basename(s)}]}}}function l(t,n){if(!n)return t;let r=e.expandHome(n);return a.mkdirSync(i.dirname(r),{recursive:!0}),a.existsSync(t)?a.renameSync(t,r):a.appendFileSync(r,``),r}async function u(e){let{req:t,sessionName:n,sessionStore:i}=e,a=t.command;return a===`record`?r({req:t,sessionName:n,sessionStore:i,bindDevice:e.bindDevice,bindExactDevice:e.bindExactDevice,admissionLedger:e.admissionLedger,requestScope:e.requestScope,retainDeviceExecutionLock:e.retainDeviceExecutionLock,throwIfCanceled:e.throwIfCanceled}):a===`trace`?o({req:t,sessionName:n,sessionStore:i}):null}export{u as handleRecordTraceCommands};
1
+ import{x as e}from"./screenshot-result.js";import{a as t}from"./dispatch.js";import{t as n}from"./handler-utils.js";import{t as r}from"./record-runtime.js";import i from"node:path";import a from"node:fs";function o(e){let n=(e.req.positionals?.[0]??``).toLowerCase();if(n!==`start`&&n!==`stop`)return t(`INVALID_ARGS`,`trace requires start|stop`);let r=e.sessionStore.get(e.sessionName);return r?n===`start`?s(e.req,e.sessionStore,r):c(e.req,e.sessionStore,r):t(`SESSION_NOT_FOUND`,`No active session`)}function s(r,o,s){if(s.trace)return t(`INVALID_ARGS`,`trace already in progress`);let c=e.expandHome(r.positionals?.[1]??o.defaultTracePath(s));return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),s.trace={outPath:c,startedAt:Date.now()},n(o,s,r,r.command,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}function c(e,r,a){if(!a.trace)return t(`INVALID_ARGS`,`no active trace`);let o=l(a.trace.outPath,e.positionals?.[1]);a.trace=void 0,n(r,a,e,e.command,{action:`stop`,outPath:o});let s=e.meta?.clientArtifactPaths?.outPath??o;return{ok:!0,data:{trace:`stopped`,outPath:o,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:o,localPath:s,fileName:i.basename(s)}]}}}function l(t,n){if(!n)return t;let r=e.expandHome(n);return a.mkdirSync(i.dirname(r),{recursive:!0}),a.existsSync(t)?a.renameSync(t,r):a.appendFileSync(r,``),r}async function u(e){let{req:t,sessionName:n,sessionStore:i}=e,a=t.command;return a===`record`?r({req:t,sessionName:n,sessionStore:i,bindDevice:e.bindDevice,bindExactDevice:e.bindExactDevice,admissionLedger:e.admissionLedger,requestScope:e.requestScope,retainDeviceExecutionLock:e.retainDeviceExecutionLock,throwIfCanceled:e.throwIfCanceled}):a===`trace`?o({req:t,sessionName:n,sessionStore:i}):null}export{u as handleRecordTraceCommands};
@@ -0,0 +1 @@
1
+ const e=[`medium`,`high`],t=`medium`;function n(t){return e.includes(t)}function r(e){let t=typeof e==`number`?e:i(e);return t!==void 0&&Number.isInteger(t)&&t>=5&&t<=10?t:void 0}function i(e){return typeof e==`string`&&/^\d+$/.test(e)?Number(e):void 0}function a(e){if(n(e))return e;let t=r(e);if(t!==void 0)return t<=7?`medium`:`high`}export{e as n,a as r,t};