serve-sim 0.1.50-beta.158.1 → 0.1.50-beta.159.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/Sources/SimNative/sim-module.swift +21 -0
- package/Sources/SimNativeSupport/RecordingFrameReader.swift +161 -0
- package/dist/middleware.js +2 -2
- package/dist/native/serve-sim-native.node +0 -0
- package/dist/serve-sim.js +106 -83
- package/package.json +1 -1
- package/src/native.ts +37 -0
package/README.md
CHANGED
|
@@ -122,6 +122,11 @@ serve-sim record [-d udid] Record the screen to an MP4 (native resolu
|
|
|
122
122
|
60 fps H.264); Ctrl+C stops. -o <file>,
|
|
123
123
|
-t <duration>, --codec h264|hevc, --fps, --bitrate,
|
|
124
124
|
--no-index (skip the .index.jsonl sidecar)
|
|
125
|
+
serve-sim record frame <mp4> -t <s> Frame nearest a time as a PNG (-o <file>|-, --index)
|
|
126
|
+
serve-sim record diff <mp4> --from <s> --to <s>
|
|
127
|
+
Highlight PNG + {changedPixels, bbox} between two times
|
|
128
|
+
serve-sim record changes <mp4> [--from <s>] [--to <s>]
|
|
129
|
+
Changed frames + nearby input, from the sidecar only
|
|
125
130
|
serve-sim ax [-d udid] Dump the accessibility tree as JSON
|
|
126
131
|
serve-sim ax --refs [--all] [--text] Compact snapshot with element refs (@e1…)
|
|
127
132
|
serve-sim tap @e2 [--settle] [--timeout <ms>]
|
|
@@ -289,6 +294,31 @@ Limitations:
|
|
|
289
294
|
- **Rotation is fixed at start.** The file's orientation comes from the simulator's orientation when recording starts; rotating mid-recording leaves the rest of the footage sideways. Stop and start a new recording after rotating.
|
|
290
295
|
- **Size changes freeze the video.** A track can't change dimensions, so if the screen size changes mid-recording (e.g. switching the Duo's active panel), frames at the new size are dropped and the rest of the video repeats the last frame at the original size.
|
|
291
296
|
|
|
297
|
+
#### Inspecting a recording
|
|
298
|
+
|
|
299
|
+
Three offline commands read a finished recording so an agent can check what happened without opening the video. They need no server or simulator. `frame` and `diff` decode with AVFoundation through the native addon, so no ffmpeg is needed. Each prints one JSON line. The sidecar is found at `<name>.index.jsonl` next to the MP4, or wherever `--index <path>` points. Times are seconds (`1.5`, `2s`, `250ms`).
|
|
300
|
+
|
|
301
|
+
```bash
|
|
302
|
+
# The sample nearest t as a PNG (default rec-t2.3.png next to the MP4; -o - pipes it to stdout)
|
|
303
|
+
serve-sim record frame rec.mp4 -t 2.3
|
|
304
|
+
# {"i":138,"pts":2.3,"decodedPts":2.3,"changed":true,"path":"rec-t2.3.png","width":1206,"height":2622}
|
|
305
|
+
|
|
306
|
+
# What changed between two times: the later frame dimmed, changed pixels magenta, bbox outlined
|
|
307
|
+
serve-sim record diff rec.mp4 --from 0.9 --to 1.0
|
|
308
|
+
# {"from":{"i":54,"pts":0.9,"decodedPts":0.9},"to":{"i":60,"pts":1,"decodedPts":1},"changedPixels":124722,
|
|
309
|
+
# "bbox":{"x":79,"y":271,"w":493,"h":493},"threshold":40,"maxDelta":255,"path":"rec-diff-0.9-1.png",…}
|
|
310
|
+
|
|
311
|
+
# Changed frames in a window and the input near them (sidecar only, never decodes)
|
|
312
|
+
serve-sim record changes rec.mp4 --from 2.2 --to 2.4
|
|
313
|
+
# {"fps":60,"durationSec":5.016667,"clock":{…},"window":{"from":2.2,"to":2.4},"complete":true,"truncated":false,
|
|
314
|
+
# "eventsDropped":0,"changedFrames":9,"frames":[{"i":136,"pts":2.266667},…],
|
|
315
|
+
# "events":[{"t":2.2811,"kind":"tap",…,"nextChange":{"i":137,"pts":2.283333}}],"unmatchedEvents":[]}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
- `frame` and `diff` pick the sample whose `pts` is nearest each time. They use the sidecar's frame times (and report `changed`) when it exists. Without one, or when it is `truncated`, they read the MP4's own sample times, and `i` counts the MP4's samples. A time outside `0…duration` is an error. They decode the middle of the chosen sample and check the decoder returned that sample (`decodedPts` is its MP4 time, which can differ from a sidecar `pts` by the MP4's 1/600 s rounding); a mismatch is an error rather than a mislabelled frame.
|
|
319
|
+
- `diff` counts a pixel as changed when a color channel differs by more than `--threshold` (default 40, above the H.264 noise between identical frames). `threshold` echoes the value used and `maxDelta` is the largest channel difference anywhere, so when `changedPixels` is 0 but `maxDelta` is close to `threshold`, retry with a `--threshold` below `maxDelta`. `--from` after `--to` is an error. `bbox` is in pixels of the displayed frame and is `null` when nothing changed.
|
|
320
|
+
- `changes` keeps an event when a changed frame in the window is within `--near` seconds (default 0.5) of it. Each kept event gets `nextChange`, the first changed frame at or after it. Events in the window with no changed frame that near (e.g. a tap the app ignored) are listed in `unmatchedEvents`. `complete` is false when the sidecar has no footer (cut short), `truncated` is true when it hit its frame cap, and `eventsDropped` counts input it didn't record; each also prints a warning on stderr. Without a sidecar `changes` exits 1: re-record without `--no-index`.
|
|
321
|
+
|
|
292
322
|
### Accessibility refs for agents
|
|
293
323
|
|
|
294
324
|
`serve-sim ax --refs` prints a compact snapshot of the visible screen: each interesting element gets a short ref (`@e1`, `@e2`, …, in tree order), its role, label, value (when set), `enabled: false` (only when disabled), and its frame and center in device points. `--all` includes offscreen elements; `--text` prints one line per element.
|
|
@@ -342,4 +342,25 @@ private func axQuery(
|
|
|
342
342
|
return String(decoding: data, as: UTF8.self)
|
|
343
343
|
}
|
|
344
344
|
},
|
|
345
|
+
// videoInfo(path): Promise<string> — JSON `{ duration, width, height,
|
|
346
|
+
// sampleTimes }` for a local movie, read compressed (no decode). Used by
|
|
347
|
+
// `serve-sim record frame|diff`; errors reject with their description.
|
|
348
|
+
"videoInfo": try NodeFunction { (path: String) async throws -> String in
|
|
349
|
+
let info = try await RecordingFrameReader.info(path: path)
|
|
350
|
+
let data = try JSONSerialization.data(withJSONObject: info.jsonObject())
|
|
351
|
+
return String(decoding: data, as: UTF8.self)
|
|
352
|
+
},
|
|
353
|
+
// videoFrame(path, seconds): Promise<{ width, height, time, rgba }> — the
|
|
354
|
+
// sample shown at `seconds`, decoded to RGBA (alpha 255).
|
|
355
|
+
"videoFrame": try NodeFunction { (path: String, seconds: Double) async throws -> NodeValueConvertible in
|
|
356
|
+
let frame = try await RecordingFrameReader.frame(path: path, seconds: seconds)
|
|
357
|
+
let buffer = try NodeArrayBuffer(capacity: frame.rgba.count)
|
|
358
|
+
_ = try buffer.withUnsafeMutableBytes { frame.rgba.copyBytes(to: $0) }
|
|
359
|
+
return try NodeObject([
|
|
360
|
+
"width": frame.width,
|
|
361
|
+
"height": frame.height,
|
|
362
|
+
"time": frame.time,
|
|
363
|
+
"rgba": try NodeTypedArray<UInt8>(for: buffer, count: frame.rgba.count),
|
|
364
|
+
])
|
|
365
|
+
},
|
|
345
366
|
])
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import AVFoundation
|
|
2
|
+
import CoreGraphics
|
|
3
|
+
import Foundation
|
|
4
|
+
|
|
5
|
+
/// Offline reads of a finished `serve-sim record` MP4 (or any local movie)
|
|
6
|
+
/// for `serve-sim record frame|diff`: the video track's sample times without
|
|
7
|
+
/// decoding, and one decoded frame as RGBA pixels. Read-only; never touches
|
|
8
|
+
/// the recorder.
|
|
9
|
+
public enum RecordingFrameReader {
|
|
10
|
+
public enum ReadError: Error, CustomStringConvertible {
|
|
11
|
+
case noVideoTrack(String)
|
|
12
|
+
case unreadable(String, String)
|
|
13
|
+
case decodeFailed(String, Double, String)
|
|
14
|
+
|
|
15
|
+
public var description: String {
|
|
16
|
+
switch self {
|
|
17
|
+
case .noVideoTrack(let path): return "\(path) has no video track"
|
|
18
|
+
case .unreadable(let path, let reason): return "Could not read \(path): \(reason)"
|
|
19
|
+
case .decodeFailed(let path, let seconds, let reason):
|
|
20
|
+
return "Could not decode the frame at \(seconds)s of \(path): \(reason)"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public struct Info: Sendable {
|
|
26
|
+
/// Container duration, seconds.
|
|
27
|
+
public let duration: Double
|
|
28
|
+
/// Displayed size (track transform applied), pixels.
|
|
29
|
+
public let width: Int
|
|
30
|
+
public let height: Int
|
|
31
|
+
/// Presentation time of every video sample, ascending, seconds.
|
|
32
|
+
public let sampleTimes: [Double]
|
|
33
|
+
|
|
34
|
+
public func jsonObject() -> [String: Any] {
|
|
35
|
+
["duration": duration, "width": width, "height": height, "sampleTimes": sampleTimes]
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public struct Frame: Sendable {
|
|
40
|
+
public let width: Int
|
|
41
|
+
public let height: Int
|
|
42
|
+
/// Presentation time of the decoded sample, seconds.
|
|
43
|
+
public let time: Double
|
|
44
|
+
/// Tightly packed 8-bit RGBA (alpha 255), row-major, top row first.
|
|
45
|
+
public let rgba: Data
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private static func videoTrack(_ asset: AVURLAsset, _ path: String) async throws -> AVAssetTrack {
|
|
49
|
+
let tracks: [AVAssetTrack]
|
|
50
|
+
do {
|
|
51
|
+
tracks = try await asset.loadTracks(withMediaType: .video)
|
|
52
|
+
} catch {
|
|
53
|
+
throw ReadError.unreadable(path, error.localizedDescription)
|
|
54
|
+
}
|
|
55
|
+
guard let track = tracks.first else { throw ReadError.noVideoTrack(path) }
|
|
56
|
+
return track
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Duration, displayed size, and sample times. Sample buffers are read
|
|
60
|
+
/// compressed (no decode), so this is cheap even for long recordings.
|
|
61
|
+
public static func info(path: String) async throws -> Info {
|
|
62
|
+
let asset = AVURLAsset(url: URL(fileURLWithPath: path))
|
|
63
|
+
let track = try await videoTrack(asset, path)
|
|
64
|
+
let (duration, size, transform, segments) = try await (
|
|
65
|
+
asset.load(.duration), track.load(.naturalSize), track.load(.preferredTransform), track.load(.segments)
|
|
66
|
+
)
|
|
67
|
+
let shown = size.applying(transform)
|
|
68
|
+
|
|
69
|
+
let reader: AVAssetReader
|
|
70
|
+
do {
|
|
71
|
+
reader = try AVAssetReader(asset: asset)
|
|
72
|
+
} catch {
|
|
73
|
+
throw ReadError.unreadable(path, error.localizedDescription)
|
|
74
|
+
}
|
|
75
|
+
let output = AVAssetReaderTrackOutput(track: track, outputSettings: nil)
|
|
76
|
+
reader.add(output)
|
|
77
|
+
guard reader.startReading() else {
|
|
78
|
+
throw ReadError.unreadable(path, reader.error?.localizedDescription ?? "reader did not start")
|
|
79
|
+
}
|
|
80
|
+
var times: [Double] = []
|
|
81
|
+
while let sample = output.copyNextSampleBuffer() {
|
|
82
|
+
// Skip empty marker buffers (no media data).
|
|
83
|
+
guard CMSampleBufferGetNumSamples(sample) > 0 else { continue }
|
|
84
|
+
let pts = CMSampleBufferGetPresentationTimeStamp(sample)
|
|
85
|
+
if pts.isValid, let shownAt = presentationTime(pts, segments) { times.append(shownAt) }
|
|
86
|
+
}
|
|
87
|
+
if reader.status == .failed {
|
|
88
|
+
throw ReadError.unreadable(path, reader.error?.localizedDescription ?? "read failed")
|
|
89
|
+
}
|
|
90
|
+
times.sort()
|
|
91
|
+
return Info(
|
|
92
|
+
duration: duration.seconds,
|
|
93
|
+
width: Int(abs(shown.width).rounded()),
|
|
94
|
+
height: Int(abs(shown.height).rounded()),
|
|
95
|
+
sampleTimes: times
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Sample buffers carry media-timeline times; the edit list (track
|
|
100
|
+
/// segments) maps them to the presentation timeline the image generator
|
|
101
|
+
/// and players use. Samples outside every segment are never shown (nil).
|
|
102
|
+
static func presentationTime(_ mediaTime: CMTime, _ segments: [AVAssetTrackSegment]) -> Double? {
|
|
103
|
+
if segments.isEmpty { return mediaTime.seconds }
|
|
104
|
+
for segment in segments where !segment.isEmpty {
|
|
105
|
+
let mapping = segment.timeMapping
|
|
106
|
+
let source = mapping.source
|
|
107
|
+
guard source.containsTime(mediaTime) else { continue }
|
|
108
|
+
let rate = mapping.target.duration.seconds / max(source.duration.seconds, .leastNonzeroMagnitude)
|
|
109
|
+
return mapping.target.start.seconds + (mediaTime.seconds - source.start.seconds) * rate
|
|
110
|
+
}
|
|
111
|
+
return nil
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Decode the sample shown at `seconds` exactly (zero tolerance), with
|
|
115
|
+
/// the track transform applied, as RGBA.
|
|
116
|
+
public static func frame(path: String, seconds: Double) async throws -> Frame {
|
|
117
|
+
let asset = AVURLAsset(url: URL(fileURLWithPath: path))
|
|
118
|
+
_ = try await videoTrack(asset, path)
|
|
119
|
+
let generator = AVAssetImageGenerator(asset: asset)
|
|
120
|
+
generator.appliesPreferredTrackTransform = true
|
|
121
|
+
generator.requestedTimeToleranceBefore = .zero
|
|
122
|
+
generator.requestedTimeToleranceAfter = .zero
|
|
123
|
+
let image: CGImage
|
|
124
|
+
let actual: CMTime
|
|
125
|
+
do {
|
|
126
|
+
(image, actual) = try await generator.image(at: CMTime(seconds: seconds, preferredTimescale: 600_000))
|
|
127
|
+
} catch {
|
|
128
|
+
throw ReadError.decodeFailed(path, seconds, error.localizedDescription)
|
|
129
|
+
}
|
|
130
|
+
let width = image.width
|
|
131
|
+
let height = image.height
|
|
132
|
+
var data = Data(count: width * height * 4)
|
|
133
|
+
let drawn = data.withUnsafeMutableBytes { raw -> Bool in
|
|
134
|
+
guard let context = CGContext(
|
|
135
|
+
data: raw.baseAddress,
|
|
136
|
+
width: width,
|
|
137
|
+
height: height,
|
|
138
|
+
bitsPerComponent: 8,
|
|
139
|
+
bytesPerRow: width * 4,
|
|
140
|
+
// Keep the frame's own RGB space: converting to sRGB would
|
|
141
|
+
// shift colors and make "unchanged" pixels look different.
|
|
142
|
+
space: image.colorSpace.flatMap { $0.model == .rgb ? $0 : nil }
|
|
143
|
+
?? CGColorSpace(name: CGColorSpace.sRGB)!,
|
|
144
|
+
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
|
|
145
|
+
) else { return false }
|
|
146
|
+
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
|
|
147
|
+
return true
|
|
148
|
+
}
|
|
149
|
+
guard drawn else { throw ReadError.decodeFailed(path, seconds, "could not create a bitmap context") }
|
|
150
|
+
// noneSkipLast leaves the fourth byte undefined; make it opaque.
|
|
151
|
+
data.withUnsafeMutableBytes { raw in
|
|
152
|
+
let bytes = raw.bindMemory(to: UInt8.self)
|
|
153
|
+
var i = 3
|
|
154
|
+
while i < bytes.count {
|
|
155
|
+
bytes[i] = 255
|
|
156
|
+
i += 4
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return Frame(width: width, height: height, time: actual.seconds, rgba: data)
|
|
160
|
+
}
|
|
161
|
+
}
|
package/dist/middleware.js
CHANGED
|
@@ -64,7 +64,7 @@ Content-Length: ${Z.length}\r
|
|
|
64
64
|
Content-Type: image/jpeg\r
|
|
65
65
|
Content-Length: ${$}\r
|
|
66
66
|
\r
|
|
67
|
-
`,"ascii")}function c2($){let Z=Buffer.allocUnsafe(5+$.length);return Z.writeUInt32BE($.length+1,0),Z[4]=x2,Z.set($,5),Z}var p2={portrait:A6.portrait,portrait_upside_down:A6.portraitUpsideDown,landscape_left:A6.landscapeLeft,landscape_right:A6.landscapeRight};function A7($){if($.writableEnded||$.destroyed||!$.writableNeedDrain)return Promise.resolve();return new Promise((Z)=>{let Q=()=>{J(),Z()},J=()=>{$.off("drain",Q),$.off("close",Q),$.off("error",Q)};$.once("drain",Q),$.once("close",Q),$.once("error",Q)})}async function T7($,Z){if(await A7($),$.writableEnded||$.destroyed)return!1;if(!Z()||$.writableNeedDrain)await A7($);return!$.writableEnded&&!$.destroyed}function I$(){return{open:0,frames:0,last_frame_at:null,last_error:null}}function l2($){return{error:"duo_renderer_unavailable",reason:O0($.reason),stage:$.stage,details:O0($.details)}}var d2=4,i2=1800000;class I7{udid;dependencies;capture;hid;unsubscribeMjpeg;unsubscribeSize;phase="unstarted";startPromise;width=0;height=0;orientation="portrait";latestJpegBuffer=null;latestJpegLength=0;hidSockets=new Set;duo;duoMonitor;followedCover;primaryDuoPanel;poseQueue=Promise.resolve();forwardedTypingKey=!1;hardwareKeyboardQueue=Promise.resolve();duoStateQueue=Promise.resolve();streamResponses=new Set;touchGestureLog;streamHealth={mjpeg:I$(),avcc:I$(),"3d":I$()};deviceHubShadowed;recording;recordingIndexes=new Map;rendererFailureEvent;axAgent;constructor($,Z){this.udid=$;this.dependencies=Z;this.hid=Z?.hid??new o9($),this.capture=Z?.capture??new a9($),this.duo=new L$({createRenderer:(Q)=>Z?.createDuoRenderer?Z.createDuoRenderer(Q):new N$(Q),onProjection:(Q)=>{for(let J of this.hidSockets)J.send(Q)},onStreamError:(Q,J)=>this.handleStreamError(Q,J,"3d"),onRendererEvent:(Q)=>this.recordRendererEvent(Q),onFrameDelivered:()=>this.noteStreamFrame("3d")})}start(){if(this.phase==="stopped")return Promise.reject(Error(`Device session ${this.udid} is closed`));if(this.startPromise)return this.startPromise;this.phase="starting";let $=(async()=>{if(await this.capture.start(),this.isStopped())throw Error(`Device session ${this.udid} closed while starting`);let Z=await this.capture.subscribeSize((Q)=>this.onScreenSize(Q.width,Q.height));if(this.isStopped())throw await Z(),Error(`Device session ${this.udid} closed while starting`);if(this.unsubscribeSize=Z,this.phase="running",await this.hid.isFoldable?.()&&!this.isStopped()){let Q=await this.capture.subscribeMjpeg((Y)=>this.onSharedMjpegFrame(Y));if(this.isStopped()){await Q();return}if(this.unsubscribeMjpeg=Q,!this.dependencies?.createDuoMonitor)S4(this.udid).then((Y)=>{this.deviceHubShadowed=Y});let J=this.dependencies?.createDuoMonitor??((Y,W,X)=>new O$(Y,W,{duoHelper:X}));this.duoMonitor=J(this.udid,(Y)=>{this.followDuoState(Y).catch((W)=>{console.error("[duo] State update failed:",W)})},n9)}})().catch((Z)=>{if(this.phase==="starting")this.phase="failed";throw Z});return $.catch(()=>{}),this.startPromise=$,$}isStopped(){return this.phase==="stopped"}close(){if(this.phase==="stopped")return;this.phase="stopped",this.duo.close(),this.duoMonitor?.close();for(let $ of this.hidSockets)this.runCleanup("HID socket close",()=>$.close());for(let $ of this.streamResponses)this.runCleanup("stream response close",()=>{$.destroy()});if(this.streamResponses.clear(),this.unsubscribeMjpeg)this.runCleanup("shared MJPEG unsubscribe",this.unsubscribeMjpeg);if(this.unsubscribeSize)this.runCleanup("size unsubscribe",this.unsubscribeSize);if(this.hidSockets.clear(),this.recording){let $=this.recording;if(this.recording=void 0,$.limitTimer)clearTimeout($.limitTimer);if($.holdTimer)clearTimeout($.holdTimer);if(L9($),$.phase!=="stopping"){let Z=$.finalizing?.catch(()=>{})??Promise.resolve();this.runCleanup("recording cleanup",()=>Z.then(()=>l0($.path,{force:!0})))}}for(let $ of this.recordingIndexes.values())clearTimeout($.expiry);this.recordingIndexes.clear(),this.runCleanup("HID close",()=>this.hid.close?.()),this.runCleanup("capture stop",()=>this.capture.stop())}followDuoState($){let Z=this.duoStateQueue.then(()=>this.applyDuoState($));return this.duoStateQueue=Z.catch(()=>{}),Z}activePanel(){return o4({primaryPanel:this.primaryDuoPanel,hingeDegrees:this.duo.hinge})}async applyDuoState($){if(this.isStopped())return;if($.hingeDegrees!=null)this.duo.noteHinge($.hingeDegrees);if($.primaryPanel)this.primaryDuoPanel=$.primaryPanel;let Z=this.activePanel(),Q=a4(Z);if(($.hingeDegrees!=null||$.primaryPanel)&&Z==="cover"!==this.followedCover)await this.capture.setPreferredScreenSize(Q.width,Q.height),this.followedCover=Z==="cover";let J=$.orientations[Z];if(J)this.orientation=J;this.duo.setPanel(Z),this.broadcastConfig(),this.duo.requestFrame()}onScreenSize($,Z){if($===this.width&&Z===this.height)return;this.width=$,this.height=Z,this.broadcastConfig()}async onSharedMjpegFrame($){let{width:Z,height:Q,data:J}=$;if(this.onScreenSize(Z,Q),!this.latestJpegBuffer||this.latestJpegBuffer.length<J.length){let W=this.latestJpegBuffer?.length??0;this.latestJpegBuffer=Buffer.allocUnsafe(Math.max(J.length,W*2))}this.latestJpegBuffer.set(J,0),this.latestJpegLength=J.length;let Y=this.latestJpeg();if(Y)this.duo.onCapturedFrame(Y)}latestJpeg(){if(!this.latestJpegBuffer)return null;return this.latestJpegBuffer.subarray(0,this.latestJpegLength)}sharedJpegCopy(){let $=this.unsubscribeMjpeg?this.latestJpeg():null;return $?Buffer.from($):null}async seedJpeg(){let $=this.sharedJpegCopy();if($)return $;try{return await this.capture.snapshotJpeg()}catch{return null}}writeMjpegFrame($,Z){let Q=$.write(m2(Z.length)),J=$.write(Z),Y=$.write(b2);return Q&&J&&Y}handleDuoMjpeg($,Z){(async()=>{if(await this.start(),Z.destroyed||Z.writableEnded)return;if(!await this.hid.isFoldable?.()){this.sendJson(Z,400,{error:"This device has no Duo model"});return}let Q=new URL($.url??"","http://x").searchParams.get("raw")==="1";if(!this.trackStreamResponse(Z,"3d"))return;this.duo.setPanel(this.activePanel()),Z.once("close",()=>this.duo.detach(Z)),this.duo.attach(Z,{onFirstFrame:()=>{Z.writeHead(200,{"Content-Type":Q?"application/octet-stream":"multipart/x-mixed-replace; boundary=frame","Cache-Control":"no-store"})}})})().catch((Q)=>this.handleStreamError(Z,Q,"3d"))}handleMjpeg($,Z){this.serveMjpeg($,Z).catch((Q)=>this.handleStreamError(Z,Q,"mjpeg"))}async serveMjpeg($,Z){if(await this.start(),Z.writableEnded||Z.destroyed)return;let Q=new URL($.url??"","http://x").searchParams.get("raw")==="1";if(Z.writeHead(200,{"Content-Type":Q?"application/octet-stream":"multipart/x-mixed-replace; boundary=frame","Cache-Control":"no-cache, no-store",Connection:"keep-alive"}),!this.trackStreamResponse(Z,"mjpeg"))return;let J=!1,Y=0,W=null,X=0,V=(B)=>{if(!W||W.length<B.length)W=Buffer.allocUnsafe(Math.max(B.length,(W?.length??0)*2));W.set(B,0),X=B.length},z=async(B)=>{if(J||Z.writableEnded||Z.destroyed)return;J=!0;try{if(await T7(Z,()=>this.writeMjpegFrame(Z,B)))Y=Date.now(),this.noteStreamFrame("mjpeg")}catch(O){if(!Z.destroyed)Z.destroy(O instanceof Error?O:Error(String(O)))}finally{J=!1}},K=this.sharedJpegCopy();if(K)V(K),await z(K);let G=await this.capture.subscribeMjpeg(async(B)=>{V(B.data),await z(B.data)}),H=setInterval(()=>{if(Z.writableEnded||Z.destroyed)return;if(Date.now()-Y<R7)return;if(W)z(Buffer.from(W.subarray(0,X)))},R7);this.bindSubscription(Z,async()=>{clearInterval(H),await G()})}handleAvcc($,Z){this.serveAvcc(Z).catch((Q)=>this.handleStreamError(Z,Q,"avcc"))}async serveAvcc($){if(await this.start(),$.writableEnded||$.destroyed)return;if($.writeHead(200,{"Content-Type":"application/octet-stream","Cache-Control":"no-cache, no-store",Connection:"keep-alive"}),!this.trackStreamResponse($,"avcc"))return;let Z=!1;this.seedJpeg().then((J)=>{if(J&&!Z&&!$.writableEnded&&!$.destroyed)$.write(c2(J))});let Q=await this.capture.subscribeAvcc(async(J)=>{Z=!0,await T7($,()=>$.write(J.data)),this.noteStreamFrame("avcc")});this.bindSubscription($,Q)}handleConfig($,Z){this.sendJson(Z,200,this.screenConfig())}handleHealth($,Z){this.sendJson(Z,200,{status:"ok"})}handleAx($,Z){return this.serveAxJson(Z,()=>Z6(this.udid),"ax_unavailable")}handleAxAgent($,Z,Q){return this.axAgent??=new K$({collect:()=>r9(this.udid,this.dependencies?.axDescribe??((J)=>Z6(J,"agent"))),contentFrames:()=>this.contentFrameCount(),tap:(J,Y)=>this.injectTap(J,Y)}),P4(this.axAgent,$,Z,Q)}async contentFrameCount(){if(!this.capture.contentChangeCount||this.phase!=="running")return null;try{let $=this.capture.contentChangeCount();return typeof $==="number"?$:null}catch{return null}}async injectTap($,Z){if(await this.start(),this.width===0||this.height===0)throw Error("Screen size is not known yet; retry in a moment.");let Q=Y7(this.screenConfig()),J=async(Y)=>{let W=W7({type:Y,x:$.x,y:$.y},Q);this.recordTouchEvent(W),await this.hid.touch(Y,W.x,W.y,this.width,this.height,0)};await J("begin"),await new Promise((Y)=>setTimeout(Y,Z)),await J("end")}handleForeground($,Z){return this.serveAxJson(Z,()=>$9(this.udid),"foreground_unavailable")}async serveAxJson($,Z,Q){try{let J=await Z();if($.writableEnded)return;this.sendJsonString($,200,J)}catch(J){if($.writableEnded)return;this.sendJson($,503,{error:Q,message:J instanceof Error?J.message:String(J)})}}recordingStatus(){let $=this.recording;if(!$)return{recording:!1};let Z=$.finalizing&&$.phase==="recording";return{recording:!0,startedAt:$.startedAt,...Z?{limitReached:!0}:{},...Z&&$.heldAt!=null?{holdExpiresAt:new Date($.heldAt+this.recordingHoldMs()).toISOString()}:{}}}recordingHoldMs(){return this.dependencies?.recordingHoldMs??$7}async discardExpiredHold(){let $=this.recording;if(!$||!$.holdExpired||$.phase!=="recording")return;this.recording=void 0,console.error(`[record] ${this.udid}: discarding the uncollected recording held at the duration limit`),await $.finalizing?.catch(()=>{}),await l0($.path,{force:!0}).catch(()=>{})}async handleRecording($,Z,Q){let J=($.method??"GET").toUpperCase();if(Q==="status"){this.sendJson(Z,200,this.recordingStatus());return}if(Q==="index"){if(J!=="GET"&&J!=="HEAD"){Z.setHeader("Allow","GET, HEAD"),this.sendJson(Z,405,{error:"method_not_allowed"});return}await this.sendRecordingIndex($,Z);return}if(J!=="POST"){Z.setHeader("Allow","POST"),this.sendJson(Z,405,{error:"method_not_allowed"});return}try{if(Q==="start")await this.startRecording($,Z);else await this.stopRecording($,Z)}catch(Y){if(Z.headersSent||Z.writableEnded){Z.destroy();return}this.sendJson(Z,500,{error:"recording_failed",message:O0(Y instanceof Error?Y.message:String(Y))})}}async startRecording($,Z){if(!this.capture.startRecording||!this.capture.stopRecording||this.capture.supportsRecording===!1){this.sendJson(Z,501,{error:"recording_unsupported",message:"This native build cannot record"});return}let Q=Z7(new URL($.url??"","http://x").searchParams);if("error"in Q){this.sendJson(Z,400,{error:"invalid_recording_options",message:Q.error});return}if(await this.discardExpiredHold(),this.recording){this.sendJson(Z,409,{error:"already_recording",...this.recordingStatus()});return}let J=L7(w2(),"serve-sim-recordings"),Y=L7(J,`${this.udid}-${C7()}.mp4`),W=new Date().toISOString(),X=C7(),V={path:Y,startedAt:W,token:X,phase:"starting"};if(this.recording=V,Q.index){let G=new A$(this.udid);V.events=G,V.unsubscribeEvents=(this.dependencies?.subscribeEventLog??N9)((H)=>G.add(H))}let z=()=>{L9(V),this.runCleanup("recording cleanup",()=>l0(Y,{force:!0})),this.sendJson(Z,409,{error:"session_closed",message:"The device session closed while the recording was starting"})};try{await this.start(),await I2(J,{recursive:!0}),await this.capture.startRecording(Y,{...Q,rotation:Q7(this.screenConfig())})}catch(G){if(this.recording!==V)return z();throw this.recording=void 0,L9(V),await l0(Y,{force:!0}).catch(()=>{}),G}if(this.recording!==V)return z();V.phase="recording";let K=this.dependencies?.maxRecordingMs??e4;V.limitTimer=setTimeout(()=>{if(this.recording!==V||V.phase!=="recording")return;console.error(`[record] ${this.udid}: reached the ${Math.round(K/60000)} min limit; finalizing`),this.finalizeRecording(V).catch((G)=>{console.error(`[record] ${this.udid}: finalize at the duration limit failed:`,G instanceof Error?G.message:G)}).finally(()=>this.holdForOwner(V))},K),V.limitTimer.unref?.(),this.sendJson(Z,200,{recording:!0,startedAt:W,token:X})}holdForOwner($){if(this.recording!==$||$.phase!=="recording")return;$.heldAt=Date.now(),$.holdTimer=setTimeout(()=>{if($.holdTimer=void 0,this.recording!==$||$.phase!=="recording")return;$.holdExpired=!0,console.error(`[record] ${this.udid}: the recording held at the duration limit is now available to any client`)},this.recordingHoldMs()),$.holdTimer.unref?.()}finalizeRecording($){if($.limitTimer)clearTimeout($.limitTimer);return $.limitTimer=void 0,L9($),$.finalizing??=this.capture.stopRecording(),$.finalizing}async stopRecording($,Z){let Q=this.recording;if(!Q||Q.phase!=="recording"||!this.capture.stopRecording){this.sendJson(Z,409,{error:"not_recording",...this.recordingStatus()});return}if(Q.finalizing&&!Q.holdExpired&&new URL($.url??"","http://x").searchParams.get("token")!==Q.token){this.sendJson(Z,409,{error:"not_owner",message:"This recording hit the time limit and is held for the client that started it"+(Q.heldAt!=null?` until ${new Date(Q.heldAt+this.recordingHoldMs()).toLocaleTimeString()}`:""),...this.recordingStatus()});return}if(Q.holdTimer)clearTimeout(Q.holdTimer);Q.holdTimer=void 0,Q.phase="stopping";let J=$.aborted||Z.destroyed,Y=()=>{J=!0};$.once("aborted",Y),Z.once("close",Y);let W=()=>{$.off("aborted",Y),Z.off("close",Y)},X,V;try{X=await this.finalizeRecording(Q),{size:V}=await E2(Q.path)}catch(G){throw await l0(Q.path,{force:!0}).catch(()=>{}),G}finally{if(W(),this.recording===Q)this.recording=void 0}if(J||$.aborted||Z.destroyed||$.socket?.destroyed){await l0(Q.path,{force:!0}).catch(()=>{});return}let z=J7(),K;if(Q.events){let G=V7(X);K=D7(G.summary);try{this.storeRecordingIndex(Q,Q.events,G,z)}catch(H){console.error(`[record] ${this.udid}: could not keep the recording index:`,H)}}else K=D7(X);Z.writeHead(200,{"Content-Type":"video/mp4","Content-Length":String(V),"Content-Disposition":`attachment; filename="${z}"`,"Cache-Control":"no-store",[t4]:K});try{await new Promise((G)=>{let H=(this.dependencies?.openRecordingFile??q2)(Q.path),B=()=>{H.destroy(),l0(Q.path,{force:!0}).finally(G)};H.once("error",()=>{Z.destroy(),B()}),Z.once("close",B),H.pipe(Z)})}finally{if(Q.events)this.armRecordingIndexExpiry(Q.token)}}storeRecordingIndex($,Z,{summary:Q,index:J},Y){if(!J)return;let W=P$(J),X=typeof Q.duration==="number"?Q.duration:0,V=W?K7(Z.entries(),W,{durationSec:X}):[];this.recordingIndexes.set($.token,{fileName:Y,summary:Q,index:J,events:V,eventsDropped:Z.dropped});while(this.recordingIndexes.size>d2){let[z,K]=this.recordingIndexes.entries().next().value;clearTimeout(K.expiry),this.recordingIndexes.delete(z)}}armRecordingIndexExpiry($){let Z=this.recordingIndexes.get($);if(!Z||Z.expiry)return;let Q=setTimeout(()=>{if(this.recordingIndexes.get($)===Z)this.recordingIndexes.delete($)},this.dependencies?.recordingIndexTtlMs??i2);Q.unref?.(),Z.expiry=Q}async sendRecordingIndex($,Z){let Q=new URL($.url??"","http://x").searchParams,J=Q.get("token");if(!J){this.sendJson(Z,400,{error:"missing_token",message:"Pass the token /recording/start returned"});return}let Y=this.recordingIndexes.get(J);if(!Y){this.sendJson(Z,404,{error:"index_not_found",message:"No index for this token (not collected yet, expired, or recorded by a build without indexes)"});return}let W=n2(Q.get("file"))??Y.fileName;if(Z.writeHead(200,{"Content-Type":G7,"Content-Disposition":`attachment; filename="${q7(H7(W))}"`,"Cache-Control":"no-store"}),($.method??"GET").toUpperCase()==="HEAD"){Z.end();return}let{summary:X,index:V,events:z,eventsDropped:K}=Y;for(let G of z7({file:W,summary:X,index:V,events:z,eventsDropped:K})){if(Z.destroyed)return;if(!Z.write(G))await new Promise((H)=>{let B=()=>{Z.off("drain",B),Z.off("close",B),H()};Z.once("drain",B),Z.once("close",B)})}Z.end()}attachHidSocket($){this.hidSockets.add($);let Z=this.configFrame(),Q=this.duo.projectionFrame();if(Q)$.send(Q);if(Z)$.send(Z);$.on("message",(J)=>{let Y=Buffer.isBuffer(J)?J:Buffer.from(J);if(Y[0]===14)this.poseQueue=this.poseQueue.then(async()=>{if(this.isStopped())return;let W=!1;try{W=await this.handleHidMessage(Y)===!0}catch(X){console.error("[hid] Pose failed:",X)}if(this.hidSockets.has($))$.send(Buffer.concat([Buffer.from([14]),Buffer.from(JSON.stringify({ok:W}))]))}).catch((W)=>{console.error("[hid] Pose reply failed:",W)});else{let W=f2(Y),X=this.handleHidMessage(Y);if(W===void 0)X.catch((V)=>{console.error("[hid] Input failed:",V)});else X.then((V)=>V===!0,(V)=>{return console.error("[hid] Input failed:",V),!1}).then((V)=>{if(this.hidSockets.has($))$.send(Buffer.concat([Buffer.from([k2]),Buffer.from(JSON.stringify({ack:W,ok:V}))]))})}}),$.on("close",()=>this.hidSockets.delete($)),$.on("error",()=>this.hidSockets.delete($))}async handleHidMessage($){if($.length<1)return;let Z=$[0],Q=$.length>1?$.subarray(1):null,J=()=>{if(!Q)return null;try{return JSON.parse(Q.toString("utf8"))}catch{return null}},Y=this.width,W=this.height;switch(Z){case 3:{let X=J();if(!X)return!1;let V=O7(X);return this.recordTouchEvent(V),this.hid.touch(V.type,V.x,V.y,Y,W,V.edge??0)}case 4:{let X=J();if(!X)return!1;let V=O7(X);if(this.recordHidEvent(Z,V),V.page!=null&&V.usage!=null)return this.hid.buttonHid(V.page,V.usage,V.phase??"press");return this.hid.button(V.button)}case 5:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.multiTouch(X.type,X.x1,X.y1,X.x2,X.y2,Y,W);break}case 6:{let X=J();if(X){if(this.recordHidEvent(Z,X),this.hid.key(X.type,X.usage),X.type==="down"&&!o6(X.usage))this.forwardedTypingKey=!0}break}case 7:{let X=J();if(!X)break;let V=p2[X.orientation];if(V!=null&&await this.hid.orientation(V)){if(this.recordHidEvent(Z,X),X.orientation!==this.orientation||X.orientation!==this.duo.viewOrientationName){if(this.duo.hinge==null)this.orientation=X.orientation;this.duo.animateRotation(X.orientation),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame()}}break}case 8:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.caDebug(X.option,X.enabled);break}case 9:this.recordHidEvent(Z,{}),this.hid.memoryWarning();break;case 10:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.digitalCrown(X.delta);break}case 11:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.scroll(X.dx*Y,X.dy*W,Y,W,X.x,X.y);break}case 12:this.recordHidEvent(Z,{}),this.hid.softwareKeyboard();break;case 15:{let X=this.dependencies?.hardwareKeyboardState??{read:(K)=>v4(K),write:(K,G)=>h4(K,G)},V=this.dependencies?.softwareKeyboardVisible??g2,z=this.hardwareKeyboardQueue.then(async()=>{let K=X.read(this.udid),G;if(K!=null)G=!K;else G=await u2(V(this.udid),h2).catch(()=>null)??!this.forwardedTypingKey;if(!await this.hid.hardwareKeyboard(G))return;X.write(this.udid,G),this.recordHidEvent(Z,{enabled:G})});this.hardwareKeyboardQueue=z.catch(()=>{}),await z;break}case 13:{let X=J();if(!X)break;let V=Number(X.width),z=Number(X.height);if(!Number.isFinite(V)||!Number.isFinite(z))break;this.recordHidEvent(Z,X),await this.capture.setPreferredScreenSize(Math.round(V),Math.round(z));break}case 14:{let X=J();if(!X)break;if(this.recordHidEvent(Z,X),typeof X.pose==="string"&&X.pose.trim()){let V=B9(X.pose);if(!V)break;let z=this.duo.displayAngle();if(this.duo.beginPose(z,V.hingeDegrees),!await this.hid.pose(X.pose,z)){this.duo.cancelPose();break}return this.duo.finishPose(V.hingeDegrees),await this.followDuoState({hingeDegrees:V.hingeDegrees,orientations:{}}),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame(),!0}else if(typeof X.hinge==="number"&&Number.isFinite(X.hinge)&&X.hinge>=0&&X.hinge<=180){if(!await this.hid.hinge(X.hinge))break;return this.duo.cancelPose(),await this.followDuoState({hingeDegrees:X.hinge,orientations:{}}),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame(),!0}break}}}recordTouchEvent($){if($.type==="begin"){this.touchGestureLog=P7($);return}if($.type==="move"){let Z=this.touchGestureLog;if(!Z)Z=P7($),this.touchGestureLog=Z;if(Z.lastX=$.x,Z.lastY=$.y,Z.moveCount++,$.edge!=null)Z.edge=$.edge;if(_7(Z))if(Z.eventId==null){let Q=T0({device:this.udid,source:"hid",kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","move")});Z.eventId=Q.id}else{let Q={kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","move")},J=F9(Z.eventId,Q,{notify:!1});if(J)this.recording?.events?.add(J);else this.recording?.events?.update(Z.eventId,Q)}return}if($.type==="end"){let Z=this.touchGestureLog;if(Z){if(Z.lastX=$.x,Z.lastY=$.y,$.edge!=null)Z.edge=$.edge;if(Z.moveCount>0&&_7(Z))if(Z.eventId==null)T0({device:this.udid,source:"hid",kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","end")});else{let Q={kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","end")};if(!F9(Z.eventId,Q))this.recording?.events?.update(Z.eventId,Q)}else T0({device:this.udid,source:"hid",kind:"tap",action:"tap",summary:`Tap ${V6($.x,$.y)}`,details:this.touchGestureDetails(Z,"tap")});this.touchGestureLog=void 0;return}}this.recordHidEvent(3,$)}eventLogScreen(){return this.width>0&&this.height>0?{width:this.width,height:this.height}:void 0}touchGestureDetails($,Z,Q){return{type:Z,...Q?{phase:Q}:{},start:{x:$.startX,y:$.startY},current:{x:$.lastX,y:$.lastY},moveCount:$.moveCount,...$.edge!=null?{edge:$.edge}:{},...this.eventLogScreen()?{screen:this.eventLogScreen()}:{}}}recordHidEvent($,Z){let Q=U7(this.udid,$,Z,this.eventLogScreen());if(Q)T0(Q)}screenConfig(){let $=this.duo.hinge;return{width:this.width,height:this.height,orientation:this.orientation,...$==null?{}:{hingeDegrees:$,duoViewOrientation:this.duo.viewOrientationName}}}configFrame(){if(this.width===0&&this.height===0)return null;return Buffer.concat([Buffer.from([S2]),Buffer.from(JSON.stringify(this.screenConfig()))])}broadcastConfig(){let $=this.configFrame();if(!$)return;for(let Z of this.hidSockets)Z.send($)}bindSubscription($,Z){let Q=!1,J=()=>{if(Q)return;Q=!0,this.streamResponses.delete($),this.runCleanup("stream unsubscribe",Z)};if($.writableEnded||$.destroyed){J();return}$.once("close",J),$.once("error",J)}trackStreamResponse($,Z){if(this.isStopped()||$.writableEnded||$.destroyed){if(!$.writableEnded&&!$.destroyed)$.destroy();return!1}this.streamResponses.add($),this.streamHealth[Z].open++;let Q=()=>{if($.off("close",Q),$.off("error",Q),this.streamResponses.delete($))this.streamHealth[Z].open--};return $.once("close",Q),$.once("error",Q),!0}runCleanup($,Z){try{Promise.resolve(Z()).catch((Q)=>this.logCleanupError($,Q))}catch(Q){this.logCleanupError($,Q)}}logCleanupError($,Z){console.error(`[capture] ${$} failed for ${this.udid}:`,Z instanceof Error?Z.message:Z)}noteStreamFrame($){let Z=this.streamHealth[$];Z.frames++,Z.last_frame_at=new Date().toISOString()}recordRendererEvent($){if($.phase==="ready"){this.rendererFailureEvent=void 0,T0({device:this.udid,source:"capture",kind:"duo.renderer",action:"ready",status:"ok",summary:`Duo renderer ready (${$.firstFrameMs} ms to first frame)`,details:{phase:"ready","duo.first_frame_ms":$.firstFrameMs}});return}let{error:Z}=$;p4(Z);let Q=`${Z.stage}\x00${Z.reason}`,J=O0(Z.reason),Y={phase:"failed",stage:Z.stage,reason:J,...O0(Z.details)},W=this.rendererFailureEvent;if(W?.key===Q&&F9(W.id,{details:{...Y,count:W.count+1}})){W.count++;return}let X=T0({device:this.udid,source:"capture",kind:"duo.renderer",action:"failed",status:"error",summary:`Duo renderer ${Z.stage} failed: ${J}`,details:{...Y,count:1}});this.rendererFailureEvent={id:X.id,key:Q,count:1}}async diagnostics(){let $=null;if(this.capture.diagnostics)try{$=JSON.parse(await this.capture.diagnostics())}catch(Z){$={error:Z instanceof Error?Z.message:String(Z)}}else $={error:"native capture diagnostics unavailable in this build"};return{udid:this.udid,phase:this.phase,screen:this.screenConfig(),streams:structuredClone(this.streamHealth),native:$,duo:{...this.duo.diagnostics(),primary_panel:this.primaryDuoPanel??null,active_panel:this.activePanel(),followed_cover:this.followedCover??null},hid:{device_hub_input_shadowed:this.deviceHubShadowed??null,sockets:this.hidSockets.size}}}handleStreamError($,Z,Q){let J=O0(Z instanceof Error?Z.message:String(Z));if(Q)this.streamHealth[Q].last_error={at:new Date().toISOString(),message:J,...Z instanceof j0?{stage:Z.stage}:{}};if($.writableEnded||$.destroyed)return;if(Z instanceof j0&&!$.headersSent){this.sendJson($,503,l2(Z));return}if($.headersSent){$.destroy(Z instanceof Error?Z:Error(String(Z)));return}this.sendJson($,503,{error:"capture_unavailable",message:J})}sendJson($,Z,Q){this.sendJsonString($,Z,JSON.stringify(Q))}sendJsonString($,Z,Q){let J=Buffer.from(Q,"utf8");$.writeHead(Z,{"Content-Type":"application/json","Cache-Control":"no-cache, no-store","Content-Length":String(J.length)}),$.end(J)}}var S0=new Map;function E7($){if($){let Z=S0.get($);return Z?[Z]:[]}return[...S0.values()]}function E$($){let Z=S0.get($);if(!Z){let Q=new I7($);Z=Q,S0.set($,Q),Q.start().catch(()=>{if(S0.get($)!==Q)return;S0.delete($),Q.close()})}return Z}function w$($){let Z=S0.get($);if(Z)Z.close(),S0.delete($)}function D7($){let Z;if(typeof $==="string")try{Z=JSON.parse($)}catch{return"{}"}else Z={...$};return delete Z.path,JSON.stringify(Z).replace(/[^\x20-\x7e]/g,"")}function L9($){$.unsubscribeEvents?.(),$.unsubscribeEvents=void 0,$.events?.stop()}function n2($){if(!$)return null;let Z=q7($).replace(/[^\x20-\x7e]|["\\]/g,"").trim();return Z&&Z!=="."&&Z!==".."?Z.slice(0,200):null}import{execFile as o2}from"node:child_process";import{closeSync as Kz,existsSync as a2,openSync as zz,readdirSync as s2,readFileSync as r2,readSync as Hz,statSync as Bz}from"node:fs";import{dirname as t2,join as K6}from"node:path";import{fileURLToPath as e2}from"node:url";var $3=1;var w7=($,Z)=>new Promise((Q)=>{o2($,Z,{timeout:5000,maxBuffer:4194304},(J,Y)=>{Q(J?null:String(Y).trim())})});function Z3(){return"0.1.50-beta.158.1"}function Q3($){let Z=/^(.*?\.app)\/Contents\/Developer\/?$/.exec($);return Z?Z[1]:null}async function J3($){let Z=new Set,Q=await $("/usr/bin/mdfind",["kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'"]);for(let J of Q?.split(`
|
|
67
|
+
`,"ascii")}function c2($){let Z=Buffer.allocUnsafe(5+$.length);return Z.writeUInt32BE($.length+1,0),Z[4]=x2,Z.set($,5),Z}var p2={portrait:A6.portrait,portrait_upside_down:A6.portraitUpsideDown,landscape_left:A6.landscapeLeft,landscape_right:A6.landscapeRight};function A7($){if($.writableEnded||$.destroyed||!$.writableNeedDrain)return Promise.resolve();return new Promise((Z)=>{let Q=()=>{J(),Z()},J=()=>{$.off("drain",Q),$.off("close",Q),$.off("error",Q)};$.once("drain",Q),$.once("close",Q),$.once("error",Q)})}async function T7($,Z){if(await A7($),$.writableEnded||$.destroyed)return!1;if(!Z()||$.writableNeedDrain)await A7($);return!$.writableEnded&&!$.destroyed}function I$(){return{open:0,frames:0,last_frame_at:null,last_error:null}}function l2($){return{error:"duo_renderer_unavailable",reason:O0($.reason),stage:$.stage,details:O0($.details)}}var d2=4,i2=1800000;class I7{udid;dependencies;capture;hid;unsubscribeMjpeg;unsubscribeSize;phase="unstarted";startPromise;width=0;height=0;orientation="portrait";latestJpegBuffer=null;latestJpegLength=0;hidSockets=new Set;duo;duoMonitor;followedCover;primaryDuoPanel;poseQueue=Promise.resolve();forwardedTypingKey=!1;hardwareKeyboardQueue=Promise.resolve();duoStateQueue=Promise.resolve();streamResponses=new Set;touchGestureLog;streamHealth={mjpeg:I$(),avcc:I$(),"3d":I$()};deviceHubShadowed;recording;recordingIndexes=new Map;rendererFailureEvent;axAgent;constructor($,Z){this.udid=$;this.dependencies=Z;this.hid=Z?.hid??new o9($),this.capture=Z?.capture??new a9($),this.duo=new L$({createRenderer:(Q)=>Z?.createDuoRenderer?Z.createDuoRenderer(Q):new N$(Q),onProjection:(Q)=>{for(let J of this.hidSockets)J.send(Q)},onStreamError:(Q,J)=>this.handleStreamError(Q,J,"3d"),onRendererEvent:(Q)=>this.recordRendererEvent(Q),onFrameDelivered:()=>this.noteStreamFrame("3d")})}start(){if(this.phase==="stopped")return Promise.reject(Error(`Device session ${this.udid} is closed`));if(this.startPromise)return this.startPromise;this.phase="starting";let $=(async()=>{if(await this.capture.start(),this.isStopped())throw Error(`Device session ${this.udid} closed while starting`);let Z=await this.capture.subscribeSize((Q)=>this.onScreenSize(Q.width,Q.height));if(this.isStopped())throw await Z(),Error(`Device session ${this.udid} closed while starting`);if(this.unsubscribeSize=Z,this.phase="running",await this.hid.isFoldable?.()&&!this.isStopped()){let Q=await this.capture.subscribeMjpeg((Y)=>this.onSharedMjpegFrame(Y));if(this.isStopped()){await Q();return}if(this.unsubscribeMjpeg=Q,!this.dependencies?.createDuoMonitor)S4(this.udid).then((Y)=>{this.deviceHubShadowed=Y});let J=this.dependencies?.createDuoMonitor??((Y,W,X)=>new O$(Y,W,{duoHelper:X}));this.duoMonitor=J(this.udid,(Y)=>{this.followDuoState(Y).catch((W)=>{console.error("[duo] State update failed:",W)})},n9)}})().catch((Z)=>{if(this.phase==="starting")this.phase="failed";throw Z});return $.catch(()=>{}),this.startPromise=$,$}isStopped(){return this.phase==="stopped"}close(){if(this.phase==="stopped")return;this.phase="stopped",this.duo.close(),this.duoMonitor?.close();for(let $ of this.hidSockets)this.runCleanup("HID socket close",()=>$.close());for(let $ of this.streamResponses)this.runCleanup("stream response close",()=>{$.destroy()});if(this.streamResponses.clear(),this.unsubscribeMjpeg)this.runCleanup("shared MJPEG unsubscribe",this.unsubscribeMjpeg);if(this.unsubscribeSize)this.runCleanup("size unsubscribe",this.unsubscribeSize);if(this.hidSockets.clear(),this.recording){let $=this.recording;if(this.recording=void 0,$.limitTimer)clearTimeout($.limitTimer);if($.holdTimer)clearTimeout($.holdTimer);if(L9($),$.phase!=="stopping"){let Z=$.finalizing?.catch(()=>{})??Promise.resolve();this.runCleanup("recording cleanup",()=>Z.then(()=>l0($.path,{force:!0})))}}for(let $ of this.recordingIndexes.values())clearTimeout($.expiry);this.recordingIndexes.clear(),this.runCleanup("HID close",()=>this.hid.close?.()),this.runCleanup("capture stop",()=>this.capture.stop())}followDuoState($){let Z=this.duoStateQueue.then(()=>this.applyDuoState($));return this.duoStateQueue=Z.catch(()=>{}),Z}activePanel(){return o4({primaryPanel:this.primaryDuoPanel,hingeDegrees:this.duo.hinge})}async applyDuoState($){if(this.isStopped())return;if($.hingeDegrees!=null)this.duo.noteHinge($.hingeDegrees);if($.primaryPanel)this.primaryDuoPanel=$.primaryPanel;let Z=this.activePanel(),Q=a4(Z);if(($.hingeDegrees!=null||$.primaryPanel)&&Z==="cover"!==this.followedCover)await this.capture.setPreferredScreenSize(Q.width,Q.height),this.followedCover=Z==="cover";let J=$.orientations[Z];if(J)this.orientation=J;this.duo.setPanel(Z),this.broadcastConfig(),this.duo.requestFrame()}onScreenSize($,Z){if($===this.width&&Z===this.height)return;this.width=$,this.height=Z,this.broadcastConfig()}async onSharedMjpegFrame($){let{width:Z,height:Q,data:J}=$;if(this.onScreenSize(Z,Q),!this.latestJpegBuffer||this.latestJpegBuffer.length<J.length){let W=this.latestJpegBuffer?.length??0;this.latestJpegBuffer=Buffer.allocUnsafe(Math.max(J.length,W*2))}this.latestJpegBuffer.set(J,0),this.latestJpegLength=J.length;let Y=this.latestJpeg();if(Y)this.duo.onCapturedFrame(Y)}latestJpeg(){if(!this.latestJpegBuffer)return null;return this.latestJpegBuffer.subarray(0,this.latestJpegLength)}sharedJpegCopy(){let $=this.unsubscribeMjpeg?this.latestJpeg():null;return $?Buffer.from($):null}async seedJpeg(){let $=this.sharedJpegCopy();if($)return $;try{return await this.capture.snapshotJpeg()}catch{return null}}writeMjpegFrame($,Z){let Q=$.write(m2(Z.length)),J=$.write(Z),Y=$.write(b2);return Q&&J&&Y}handleDuoMjpeg($,Z){(async()=>{if(await this.start(),Z.destroyed||Z.writableEnded)return;if(!await this.hid.isFoldable?.()){this.sendJson(Z,400,{error:"This device has no Duo model"});return}let Q=new URL($.url??"","http://x").searchParams.get("raw")==="1";if(!this.trackStreamResponse(Z,"3d"))return;this.duo.setPanel(this.activePanel()),Z.once("close",()=>this.duo.detach(Z)),this.duo.attach(Z,{onFirstFrame:()=>{Z.writeHead(200,{"Content-Type":Q?"application/octet-stream":"multipart/x-mixed-replace; boundary=frame","Cache-Control":"no-store"})}})})().catch((Q)=>this.handleStreamError(Z,Q,"3d"))}handleMjpeg($,Z){this.serveMjpeg($,Z).catch((Q)=>this.handleStreamError(Z,Q,"mjpeg"))}async serveMjpeg($,Z){if(await this.start(),Z.writableEnded||Z.destroyed)return;let Q=new URL($.url??"","http://x").searchParams.get("raw")==="1";if(Z.writeHead(200,{"Content-Type":Q?"application/octet-stream":"multipart/x-mixed-replace; boundary=frame","Cache-Control":"no-cache, no-store",Connection:"keep-alive"}),!this.trackStreamResponse(Z,"mjpeg"))return;let J=!1,Y=0,W=null,X=0,V=(B)=>{if(!W||W.length<B.length)W=Buffer.allocUnsafe(Math.max(B.length,(W?.length??0)*2));W.set(B,0),X=B.length},z=async(B)=>{if(J||Z.writableEnded||Z.destroyed)return;J=!0;try{if(await T7(Z,()=>this.writeMjpegFrame(Z,B)))Y=Date.now(),this.noteStreamFrame("mjpeg")}catch(O){if(!Z.destroyed)Z.destroy(O instanceof Error?O:Error(String(O)))}finally{J=!1}},K=this.sharedJpegCopy();if(K)V(K),await z(K);let G=await this.capture.subscribeMjpeg(async(B)=>{V(B.data),await z(B.data)}),H=setInterval(()=>{if(Z.writableEnded||Z.destroyed)return;if(Date.now()-Y<R7)return;if(W)z(Buffer.from(W.subarray(0,X)))},R7);this.bindSubscription(Z,async()=>{clearInterval(H),await G()})}handleAvcc($,Z){this.serveAvcc(Z).catch((Q)=>this.handleStreamError(Z,Q,"avcc"))}async serveAvcc($){if(await this.start(),$.writableEnded||$.destroyed)return;if($.writeHead(200,{"Content-Type":"application/octet-stream","Cache-Control":"no-cache, no-store",Connection:"keep-alive"}),!this.trackStreamResponse($,"avcc"))return;let Z=!1;this.seedJpeg().then((J)=>{if(J&&!Z&&!$.writableEnded&&!$.destroyed)$.write(c2(J))});let Q=await this.capture.subscribeAvcc(async(J)=>{Z=!0,await T7($,()=>$.write(J.data)),this.noteStreamFrame("avcc")});this.bindSubscription($,Q)}handleConfig($,Z){this.sendJson(Z,200,this.screenConfig())}handleHealth($,Z){this.sendJson(Z,200,{status:"ok"})}handleAx($,Z){return this.serveAxJson(Z,()=>Z6(this.udid),"ax_unavailable")}handleAxAgent($,Z,Q){return this.axAgent??=new K$({collect:()=>r9(this.udid,this.dependencies?.axDescribe??((J)=>Z6(J,"agent"))),contentFrames:()=>this.contentFrameCount(),tap:(J,Y)=>this.injectTap(J,Y)}),P4(this.axAgent,$,Z,Q)}async contentFrameCount(){if(!this.capture.contentChangeCount||this.phase!=="running")return null;try{let $=this.capture.contentChangeCount();return typeof $==="number"?$:null}catch{return null}}async injectTap($,Z){if(await this.start(),this.width===0||this.height===0)throw Error("Screen size is not known yet; retry in a moment.");let Q=Y7(this.screenConfig()),J=async(Y)=>{let W=W7({type:Y,x:$.x,y:$.y},Q);this.recordTouchEvent(W),await this.hid.touch(Y,W.x,W.y,this.width,this.height,0)};await J("begin"),await new Promise((Y)=>setTimeout(Y,Z)),await J("end")}handleForeground($,Z){return this.serveAxJson(Z,()=>$9(this.udid),"foreground_unavailable")}async serveAxJson($,Z,Q){try{let J=await Z();if($.writableEnded)return;this.sendJsonString($,200,J)}catch(J){if($.writableEnded)return;this.sendJson($,503,{error:Q,message:J instanceof Error?J.message:String(J)})}}recordingStatus(){let $=this.recording;if(!$)return{recording:!1};let Z=$.finalizing&&$.phase==="recording";return{recording:!0,startedAt:$.startedAt,...Z?{limitReached:!0}:{},...Z&&$.heldAt!=null?{holdExpiresAt:new Date($.heldAt+this.recordingHoldMs()).toISOString()}:{}}}recordingHoldMs(){return this.dependencies?.recordingHoldMs??$7}async discardExpiredHold(){let $=this.recording;if(!$||!$.holdExpired||$.phase!=="recording")return;this.recording=void 0,console.error(`[record] ${this.udid}: discarding the uncollected recording held at the duration limit`),await $.finalizing?.catch(()=>{}),await l0($.path,{force:!0}).catch(()=>{})}async handleRecording($,Z,Q){let J=($.method??"GET").toUpperCase();if(Q==="status"){this.sendJson(Z,200,this.recordingStatus());return}if(Q==="index"){if(J!=="GET"&&J!=="HEAD"){Z.setHeader("Allow","GET, HEAD"),this.sendJson(Z,405,{error:"method_not_allowed"});return}await this.sendRecordingIndex($,Z);return}if(J!=="POST"){Z.setHeader("Allow","POST"),this.sendJson(Z,405,{error:"method_not_allowed"});return}try{if(Q==="start")await this.startRecording($,Z);else await this.stopRecording($,Z)}catch(Y){if(Z.headersSent||Z.writableEnded){Z.destroy();return}this.sendJson(Z,500,{error:"recording_failed",message:O0(Y instanceof Error?Y.message:String(Y))})}}async startRecording($,Z){if(!this.capture.startRecording||!this.capture.stopRecording||this.capture.supportsRecording===!1){this.sendJson(Z,501,{error:"recording_unsupported",message:"This native build cannot record"});return}let Q=Z7(new URL($.url??"","http://x").searchParams);if("error"in Q){this.sendJson(Z,400,{error:"invalid_recording_options",message:Q.error});return}if(await this.discardExpiredHold(),this.recording){this.sendJson(Z,409,{error:"already_recording",...this.recordingStatus()});return}let J=L7(w2(),"serve-sim-recordings"),Y=L7(J,`${this.udid}-${C7()}.mp4`),W=new Date().toISOString(),X=C7(),V={path:Y,startedAt:W,token:X,phase:"starting"};if(this.recording=V,Q.index){let G=new A$(this.udid);V.events=G,V.unsubscribeEvents=(this.dependencies?.subscribeEventLog??N9)((H)=>G.add(H))}let z=()=>{L9(V),this.runCleanup("recording cleanup",()=>l0(Y,{force:!0})),this.sendJson(Z,409,{error:"session_closed",message:"The device session closed while the recording was starting"})};try{await this.start(),await I2(J,{recursive:!0}),await this.capture.startRecording(Y,{...Q,rotation:Q7(this.screenConfig())})}catch(G){if(this.recording!==V)return z();throw this.recording=void 0,L9(V),await l0(Y,{force:!0}).catch(()=>{}),G}if(this.recording!==V)return z();V.phase="recording";let K=this.dependencies?.maxRecordingMs??e4;V.limitTimer=setTimeout(()=>{if(this.recording!==V||V.phase!=="recording")return;console.error(`[record] ${this.udid}: reached the ${Math.round(K/60000)} min limit; finalizing`),this.finalizeRecording(V).catch((G)=>{console.error(`[record] ${this.udid}: finalize at the duration limit failed:`,G instanceof Error?G.message:G)}).finally(()=>this.holdForOwner(V))},K),V.limitTimer.unref?.(),this.sendJson(Z,200,{recording:!0,startedAt:W,token:X})}holdForOwner($){if(this.recording!==$||$.phase!=="recording")return;$.heldAt=Date.now(),$.holdTimer=setTimeout(()=>{if($.holdTimer=void 0,this.recording!==$||$.phase!=="recording")return;$.holdExpired=!0,console.error(`[record] ${this.udid}: the recording held at the duration limit is now available to any client`)},this.recordingHoldMs()),$.holdTimer.unref?.()}finalizeRecording($){if($.limitTimer)clearTimeout($.limitTimer);return $.limitTimer=void 0,L9($),$.finalizing??=this.capture.stopRecording(),$.finalizing}async stopRecording($,Z){let Q=this.recording;if(!Q||Q.phase!=="recording"||!this.capture.stopRecording){this.sendJson(Z,409,{error:"not_recording",...this.recordingStatus()});return}if(Q.finalizing&&!Q.holdExpired&&new URL($.url??"","http://x").searchParams.get("token")!==Q.token){this.sendJson(Z,409,{error:"not_owner",message:"This recording hit the time limit and is held for the client that started it"+(Q.heldAt!=null?` until ${new Date(Q.heldAt+this.recordingHoldMs()).toLocaleTimeString()}`:""),...this.recordingStatus()});return}if(Q.holdTimer)clearTimeout(Q.holdTimer);Q.holdTimer=void 0,Q.phase="stopping";let J=$.aborted||Z.destroyed,Y=()=>{J=!0};$.once("aborted",Y),Z.once("close",Y);let W=()=>{$.off("aborted",Y),Z.off("close",Y)},X,V;try{X=await this.finalizeRecording(Q),{size:V}=await E2(Q.path)}catch(G){throw await l0(Q.path,{force:!0}).catch(()=>{}),G}finally{if(W(),this.recording===Q)this.recording=void 0}if(J||$.aborted||Z.destroyed||$.socket?.destroyed){await l0(Q.path,{force:!0}).catch(()=>{});return}let z=J7(),K;if(Q.events){let G=V7(X);K=D7(G.summary);try{this.storeRecordingIndex(Q,Q.events,G,z)}catch(H){console.error(`[record] ${this.udid}: could not keep the recording index:`,H)}}else K=D7(X);Z.writeHead(200,{"Content-Type":"video/mp4","Content-Length":String(V),"Content-Disposition":`attachment; filename="${z}"`,"Cache-Control":"no-store",[t4]:K});try{await new Promise((G)=>{let H=(this.dependencies?.openRecordingFile??q2)(Q.path),B=()=>{H.destroy(),l0(Q.path,{force:!0}).finally(G)};H.once("error",()=>{Z.destroy(),B()}),Z.once("close",B),H.pipe(Z)})}finally{if(Q.events)this.armRecordingIndexExpiry(Q.token)}}storeRecordingIndex($,Z,{summary:Q,index:J},Y){if(!J)return;let W=P$(J),X=typeof Q.duration==="number"?Q.duration:0,V=W?K7(Z.entries(),W,{durationSec:X}):[];this.recordingIndexes.set($.token,{fileName:Y,summary:Q,index:J,events:V,eventsDropped:Z.dropped});while(this.recordingIndexes.size>d2){let[z,K]=this.recordingIndexes.entries().next().value;clearTimeout(K.expiry),this.recordingIndexes.delete(z)}}armRecordingIndexExpiry($){let Z=this.recordingIndexes.get($);if(!Z||Z.expiry)return;let Q=setTimeout(()=>{if(this.recordingIndexes.get($)===Z)this.recordingIndexes.delete($)},this.dependencies?.recordingIndexTtlMs??i2);Q.unref?.(),Z.expiry=Q}async sendRecordingIndex($,Z){let Q=new URL($.url??"","http://x").searchParams,J=Q.get("token");if(!J){this.sendJson(Z,400,{error:"missing_token",message:"Pass the token /recording/start returned"});return}let Y=this.recordingIndexes.get(J);if(!Y){this.sendJson(Z,404,{error:"index_not_found",message:"No index for this token (not collected yet, expired, or recorded by a build without indexes)"});return}let W=n2(Q.get("file"))??Y.fileName;if(Z.writeHead(200,{"Content-Type":G7,"Content-Disposition":`attachment; filename="${q7(H7(W))}"`,"Cache-Control":"no-store"}),($.method??"GET").toUpperCase()==="HEAD"){Z.end();return}let{summary:X,index:V,events:z,eventsDropped:K}=Y;for(let G of z7({file:W,summary:X,index:V,events:z,eventsDropped:K})){if(Z.destroyed)return;if(!Z.write(G))await new Promise((H)=>{let B=()=>{Z.off("drain",B),Z.off("close",B),H()};Z.once("drain",B),Z.once("close",B)})}Z.end()}attachHidSocket($){this.hidSockets.add($);let Z=this.configFrame(),Q=this.duo.projectionFrame();if(Q)$.send(Q);if(Z)$.send(Z);$.on("message",(J)=>{let Y=Buffer.isBuffer(J)?J:Buffer.from(J);if(Y[0]===14)this.poseQueue=this.poseQueue.then(async()=>{if(this.isStopped())return;let W=!1;try{W=await this.handleHidMessage(Y)===!0}catch(X){console.error("[hid] Pose failed:",X)}if(this.hidSockets.has($))$.send(Buffer.concat([Buffer.from([14]),Buffer.from(JSON.stringify({ok:W}))]))}).catch((W)=>{console.error("[hid] Pose reply failed:",W)});else{let W=f2(Y),X=this.handleHidMessage(Y);if(W===void 0)X.catch((V)=>{console.error("[hid] Input failed:",V)});else X.then((V)=>V===!0,(V)=>{return console.error("[hid] Input failed:",V),!1}).then((V)=>{if(this.hidSockets.has($))$.send(Buffer.concat([Buffer.from([k2]),Buffer.from(JSON.stringify({ack:W,ok:V}))]))})}}),$.on("close",()=>this.hidSockets.delete($)),$.on("error",()=>this.hidSockets.delete($))}async handleHidMessage($){if($.length<1)return;let Z=$[0],Q=$.length>1?$.subarray(1):null,J=()=>{if(!Q)return null;try{return JSON.parse(Q.toString("utf8"))}catch{return null}},Y=this.width,W=this.height;switch(Z){case 3:{let X=J();if(!X)return!1;let V=O7(X);return this.recordTouchEvent(V),this.hid.touch(V.type,V.x,V.y,Y,W,V.edge??0)}case 4:{let X=J();if(!X)return!1;let V=O7(X);if(this.recordHidEvent(Z,V),V.page!=null&&V.usage!=null)return this.hid.buttonHid(V.page,V.usage,V.phase??"press");return this.hid.button(V.button)}case 5:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.multiTouch(X.type,X.x1,X.y1,X.x2,X.y2,Y,W);break}case 6:{let X=J();if(X){if(this.recordHidEvent(Z,X),this.hid.key(X.type,X.usage),X.type==="down"&&!o6(X.usage))this.forwardedTypingKey=!0}break}case 7:{let X=J();if(!X)break;let V=p2[X.orientation];if(V!=null&&await this.hid.orientation(V)){if(this.recordHidEvent(Z,X),X.orientation!==this.orientation||X.orientation!==this.duo.viewOrientationName){if(this.duo.hinge==null)this.orientation=X.orientation;this.duo.animateRotation(X.orientation),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame()}}break}case 8:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.caDebug(X.option,X.enabled);break}case 9:this.recordHidEvent(Z,{}),this.hid.memoryWarning();break;case 10:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.digitalCrown(X.delta);break}case 11:{let X=J();if(X)this.recordHidEvent(Z,X),this.hid.scroll(X.dx*Y,X.dy*W,Y,W,X.x,X.y);break}case 12:this.recordHidEvent(Z,{}),this.hid.softwareKeyboard();break;case 15:{let X=this.dependencies?.hardwareKeyboardState??{read:(K)=>v4(K),write:(K,G)=>h4(K,G)},V=this.dependencies?.softwareKeyboardVisible??g2,z=this.hardwareKeyboardQueue.then(async()=>{let K=X.read(this.udid),G;if(K!=null)G=!K;else G=await u2(V(this.udid),h2).catch(()=>null)??!this.forwardedTypingKey;if(!await this.hid.hardwareKeyboard(G))return;X.write(this.udid,G),this.recordHidEvent(Z,{enabled:G})});this.hardwareKeyboardQueue=z.catch(()=>{}),await z;break}case 13:{let X=J();if(!X)break;let V=Number(X.width),z=Number(X.height);if(!Number.isFinite(V)||!Number.isFinite(z))break;this.recordHidEvent(Z,X),await this.capture.setPreferredScreenSize(Math.round(V),Math.round(z));break}case 14:{let X=J();if(!X)break;if(this.recordHidEvent(Z,X),typeof X.pose==="string"&&X.pose.trim()){let V=B9(X.pose);if(!V)break;let z=this.duo.displayAngle();if(this.duo.beginPose(z,V.hingeDegrees),!await this.hid.pose(X.pose,z)){this.duo.cancelPose();break}return this.duo.finishPose(V.hingeDegrees),await this.followDuoState({hingeDegrees:V.hingeDegrees,orientations:{}}),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame(),!0}else if(typeof X.hinge==="number"&&Number.isFinite(X.hinge)&&X.hinge>=0&&X.hinge<=180){if(!await this.hid.hinge(X.hinge))break;return this.duo.cancelPose(),await this.followDuoState({hingeDegrees:X.hinge,orientations:{}}),this.duoMonitor?.refreshOrientation(),this.broadcastConfig(),this.duo.requestFrame(),!0}break}}}recordTouchEvent($){if($.type==="begin"){this.touchGestureLog=P7($);return}if($.type==="move"){let Z=this.touchGestureLog;if(!Z)Z=P7($),this.touchGestureLog=Z;if(Z.lastX=$.x,Z.lastY=$.y,Z.moveCount++,$.edge!=null)Z.edge=$.edge;if(_7(Z))if(Z.eventId==null){let Q=T0({device:this.udid,source:"hid",kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","move")});Z.eventId=Q.id}else{let Q={kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","move")},J=F9(Z.eventId,Q,{notify:!1});if(J)this.recording?.events?.add(J);else this.recording?.events?.update(Z.eventId,Q)}return}if($.type==="end"){let Z=this.touchGestureLog;if(Z){if(Z.lastX=$.x,Z.lastY=$.y,$.edge!=null)Z.edge=$.edge;if(Z.moveCount>0&&_7(Z))if(Z.eventId==null)T0({device:this.udid,source:"hid",kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","end")});else{let Q={kind:"drag",action:"drag",summary:M9(Z),details:this.touchGestureDetails(Z,"drag","end")};if(!F9(Z.eventId,Q))this.recording?.events?.update(Z.eventId,Q)}else T0({device:this.udid,source:"hid",kind:"tap",action:"tap",summary:`Tap ${V6($.x,$.y)}`,details:this.touchGestureDetails(Z,"tap")});this.touchGestureLog=void 0;return}}this.recordHidEvent(3,$)}eventLogScreen(){return this.width>0&&this.height>0?{width:this.width,height:this.height}:void 0}touchGestureDetails($,Z,Q){return{type:Z,...Q?{phase:Q}:{},start:{x:$.startX,y:$.startY},current:{x:$.lastX,y:$.lastY},moveCount:$.moveCount,...$.edge!=null?{edge:$.edge}:{},...this.eventLogScreen()?{screen:this.eventLogScreen()}:{}}}recordHidEvent($,Z){let Q=U7(this.udid,$,Z,this.eventLogScreen());if(Q)T0(Q)}screenConfig(){let $=this.duo.hinge;return{width:this.width,height:this.height,orientation:this.orientation,...$==null?{}:{hingeDegrees:$,duoViewOrientation:this.duo.viewOrientationName}}}configFrame(){if(this.width===0&&this.height===0)return null;return Buffer.concat([Buffer.from([S2]),Buffer.from(JSON.stringify(this.screenConfig()))])}broadcastConfig(){let $=this.configFrame();if(!$)return;for(let Z of this.hidSockets)Z.send($)}bindSubscription($,Z){let Q=!1,J=()=>{if(Q)return;Q=!0,this.streamResponses.delete($),this.runCleanup("stream unsubscribe",Z)};if($.writableEnded||$.destroyed){J();return}$.once("close",J),$.once("error",J)}trackStreamResponse($,Z){if(this.isStopped()||$.writableEnded||$.destroyed){if(!$.writableEnded&&!$.destroyed)$.destroy();return!1}this.streamResponses.add($),this.streamHealth[Z].open++;let Q=()=>{if($.off("close",Q),$.off("error",Q),this.streamResponses.delete($))this.streamHealth[Z].open--};return $.once("close",Q),$.once("error",Q),!0}runCleanup($,Z){try{Promise.resolve(Z()).catch((Q)=>this.logCleanupError($,Q))}catch(Q){this.logCleanupError($,Q)}}logCleanupError($,Z){console.error(`[capture] ${$} failed for ${this.udid}:`,Z instanceof Error?Z.message:Z)}noteStreamFrame($){let Z=this.streamHealth[$];Z.frames++,Z.last_frame_at=new Date().toISOString()}recordRendererEvent($){if($.phase==="ready"){this.rendererFailureEvent=void 0,T0({device:this.udid,source:"capture",kind:"duo.renderer",action:"ready",status:"ok",summary:`Duo renderer ready (${$.firstFrameMs} ms to first frame)`,details:{phase:"ready","duo.first_frame_ms":$.firstFrameMs}});return}let{error:Z}=$;p4(Z);let Q=`${Z.stage}\x00${Z.reason}`,J=O0(Z.reason),Y={phase:"failed",stage:Z.stage,reason:J,...O0(Z.details)},W=this.rendererFailureEvent;if(W?.key===Q&&F9(W.id,{details:{...Y,count:W.count+1}})){W.count++;return}let X=T0({device:this.udid,source:"capture",kind:"duo.renderer",action:"failed",status:"error",summary:`Duo renderer ${Z.stage} failed: ${J}`,details:{...Y,count:1}});this.rendererFailureEvent={id:X.id,key:Q,count:1}}async diagnostics(){let $=null;if(this.capture.diagnostics)try{$=JSON.parse(await this.capture.diagnostics())}catch(Z){$={error:Z instanceof Error?Z.message:String(Z)}}else $={error:"native capture diagnostics unavailable in this build"};return{udid:this.udid,phase:this.phase,screen:this.screenConfig(),streams:structuredClone(this.streamHealth),native:$,duo:{...this.duo.diagnostics(),primary_panel:this.primaryDuoPanel??null,active_panel:this.activePanel(),followed_cover:this.followedCover??null},hid:{device_hub_input_shadowed:this.deviceHubShadowed??null,sockets:this.hidSockets.size}}}handleStreamError($,Z,Q){let J=O0(Z instanceof Error?Z.message:String(Z));if(Q)this.streamHealth[Q].last_error={at:new Date().toISOString(),message:J,...Z instanceof j0?{stage:Z.stage}:{}};if($.writableEnded||$.destroyed)return;if(Z instanceof j0&&!$.headersSent){this.sendJson($,503,l2(Z));return}if($.headersSent){$.destroy(Z instanceof Error?Z:Error(String(Z)));return}this.sendJson($,503,{error:"capture_unavailable",message:J})}sendJson($,Z,Q){this.sendJsonString($,Z,JSON.stringify(Q))}sendJsonString($,Z,Q){let J=Buffer.from(Q,"utf8");$.writeHead(Z,{"Content-Type":"application/json","Cache-Control":"no-cache, no-store","Content-Length":String(J.length)}),$.end(J)}}var S0=new Map;function E7($){if($){let Z=S0.get($);return Z?[Z]:[]}return[...S0.values()]}function E$($){let Z=S0.get($);if(!Z){let Q=new I7($);Z=Q,S0.set($,Q),Q.start().catch(()=>{if(S0.get($)!==Q)return;S0.delete($),Q.close()})}return Z}function w$($){let Z=S0.get($);if(Z)Z.close(),S0.delete($)}function D7($){let Z;if(typeof $==="string")try{Z=JSON.parse($)}catch{return"{}"}else Z={...$};return delete Z.path,JSON.stringify(Z).replace(/[^\x20-\x7e]/g,"")}function L9($){$.unsubscribeEvents?.(),$.unsubscribeEvents=void 0,$.events?.stop()}function n2($){if(!$)return null;let Z=q7($).replace(/[^\x20-\x7e]|["\\]/g,"").trim();return Z&&Z!=="."&&Z!==".."?Z.slice(0,200):null}import{execFile as o2}from"node:child_process";import{closeSync as Kz,existsSync as a2,openSync as zz,readdirSync as s2,readFileSync as r2,readSync as Hz,statSync as Bz}from"node:fs";import{dirname as t2,join as K6}from"node:path";import{fileURLToPath as e2}from"node:url";var $3=1;var w7=($,Z)=>new Promise((Q)=>{o2($,Z,{timeout:5000,maxBuffer:4194304},(J,Y)=>{Q(J?null:String(Y).trim())})});function Z3(){return"0.1.50-beta.159.1"}function Q3($){let Z=/^(.*?\.app)\/Contents\/Developer\/?$/.exec($);return Z?Z[1]:null}async function J3($){let Z=new Set,Q=await $("/usr/bin/mdfind",["kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'"]);for(let J of Q?.split(`
|
|
68
68
|
`)??[])if(J.trim().endsWith(".app"))Z.add(J.trim());try{for(let J of s2("/Applications"))if(/^Xcode.*\.app$/.test(J))Z.add(K6("/Applications",J))}catch{}return[...Z].sort()}async function x7($={}){let Z=$.probe??w7,Q=$.env??process.env,J=$.exists??a2,[Y,W,X,V,z,K]=await Promise.all([Z("/usr/bin/sw_vers",["-productVersion"]),Z("/usr/bin/sw_vers",["-buildVersion"]),Z("/usr/sbin/sysctl",["-n","machdep.cpu.brand_string"]),Z("/usr/bin/xcode-select",["-p"]),Z("/usr/bin/xcodebuild",["-version"]),Z("/bin/ps",["-axo","pid=,command="])]),G=Q.DEVELOPER_DIR??V,H=G?Q3(G):null,B=await($.listXcodes?$.listXcodes():J3(Z)),O=await Promise.all(B.map(async(D)=>{let _=await Z("/usr/bin/defaults",["read",K6(D,"Contents","Info"),"CFBundleShortVersionString"]),L=await Z("/usr/bin/defaults",["read",K6(D,"Contents","version"),"ProductBuildVersion"]);return{path:D,version:_,build:L,selected:D===H,has_device_hub:J(K6(D,"Contents","Applications","DeviceHub.app")),has_duo_model:J(j$(K6(D,"Contents","Developer")))}})),M=(K??"").split(`
|
|
69
69
|
`).map((D)=>/^\s*(\d+)\s+(.*\/DeviceHub\.app\/Contents\/MacOS\/\S+)/.exec(D)).filter((D)=>D!=null).map((D)=>{let _=D[2],L=/^(.*?\.app)\/Contents\/Applications\/DeviceHub\.app\//.exec(_)?.[1]??null;return{pid:Number(D[1]),executable:_,xcode:L,matches_selected:L!=null&&L===H}}),C=F$(Q,()=>{if(!V)throw Error("xcode-select -p failed");return V},J);return{macos:{version:Y,build:W},chip:X,arch:process.arch,node:process.version,xcode:{xcode_select:V,developer_dir_env:Q.DEVELOPER_DIR??null,effective_developer_dir:G,xcodebuild_version:z,installed:O},device_hub:{processes:M},duo_renderer:{executable:U$(),model_path:C.modelPath,model_source:C.source,model_found:C.exists,...C.error?{model_error:C.error}:{}}}}async function S7($,Z=w7){let Q=await Z("/usr/bin/xcrun",o(["list","devices","-j"])),J=null;try{let Y=JSON.parse(Q??"{}");for(let[W,X]of Object.entries(Y.devices??{})){let V=X.find((z)=>z.udid===$);if(V){J={name:V.name,state:V.state,runtime:W,device_type:V.deviceTypeIdentifier??null};break}}}catch{}return{udid:$,...J??{error:"not found in simctl list"},device_hub_input_shadowed:await k4($,async(Y)=>{let W=await Z("/usr/bin/xcrun",Y);if(W==null)throw Error("probe failed");return W})}}function k7($){return!!$&&typeof $==="object"&&!Array.isArray($)}function Y3($){if(!k7($))return $;let Z={...$};if(Array.isArray($.errors)){let Q=new Map;for(let J of $.errors){let Y=Q.get(J.codec);if(!Y){Q.set(J.codec,{...J});continue}let W=J.last_at>Y.last_at?J:Y;Q.set(J.codec,{...W,count:Y.count+J.count,first_at:J.first_at<Y.first_at?J.first_at:Y.first_at,last_at:W.last_at,variants:(Y.variants??1)+1})}Z.errors=[...Q.values()].sort((J,Y)=>J.last_at<Y.last_at?1:J.last_at>Y.last_at?-1:0)}if(Array.isArray($.sessions)){let Q=new Map;for(let J of $.sessions){let Y=Q.get(J.codec),W=(Y?.session_count??0)+1;Q.set(J.codec,{...!Y||J.at>=Y.at?J:Y,session_count:W})}Z.sessions=[...Q.values()].sort((J,Y)=>J.at<Y.at?-1:J.at>Y.at?1:0)}return Z}function W3($){let Z=$.native;if(!k7(Z)||!("encoders"in Z))return $;return{...$,native:{...Z,encoders:Y3(Z.encoders)}}}function y7($){let Z={schema_version:$3,generated_at:($.now??new Date).toISOString(),serve_sim:{version:Z3(),pid:process.pid},host:$.host,devices:$.devices??[],sessions:($.sessions??[]).map(W3),event_log:$.event_log??[],...$.server?{server:$.server}:{},...$.crash_reports?{crash_reports:$.crash_reports}:{}};return O0(Z,$.home)}function f7($){let Z=$.now??Date.now,Q=$.burst,J=Z();return{take(){let Y=Z();if(Q=Math.min($.burst,Q+(Y-J)/$.refillMs),J=Y,Q>=1)return Q-=1,{ok:!0};return{ok:!1,retryAfterMs:Math.ceil((1-Q)*$.refillMs)}}}}function b7($,Z=Date.now){let Q=new Map;return{get(J,Y){let W=Z(),X=Q.get(J);if(X&&W-X.at<$)return X.value;for(let[K,G]of Q)if(W-G.at>=$)Q.delete(K);let V=Y(),z={at:W,value:V};return Q.set(J,z),V.catch(()=>{if(Q.get(J)===z)Q.delete(J)}),V}}}import{WebSocket as X3}from"ws";var G3=Array.from({length:10},($,Z)=>8081+Z),V3=new Set(["host.exp.Exponent"]);function x$($){return!V3.has($)}var h7=1000,g7=1200,Rz=h7+g7,v7=2;function K3($){let Z=new Map;for(let Q of $){if(!Q.appId)continue;let J=Q.reactNative?.logicalDeviceId??Q.deviceName??Q.appId;Z.set(J,Q.deviceName)}return Z}function u7($,Z,Q){return $.some((J)=>J.appId===Z&&J.deviceName===Q)}function m7($,Z,Q){if(!u7($,Z,Q))return!1;let J=K3($);return J.size===1&&[...J.values()][0]===Q}function z3($,Z,Q){if(!m7($,Z,Q))return!1;return $.every((J)=>!J.appId||J.appId===Z&&J.deviceName===Q)}function c7($,Z){let Q=[...$],J=Q.find((W)=>W.udid===Z)?.name;if(!J)return;return Q.some((W)=>W.udid!==Z&&W.name===J&&W.state==="Booted")?void 0:J}async function H3($){let Z=await fetch($,{signal:AbortSignal.timeout(800)});if(!Z.ok)throw Error(`HTTP ${Z.status}`);return Z.json()}function B3($){if(!$||typeof $!=="object")return[];return Object.entries($).filter(([,Z])=>p7(Z)!=null).map(([Z])=>Z)}function j3($){if(!$||typeof $!=="object")return[];return Object.values($).map(p7).filter((Z)=>Z!=null)}function p7($){if(typeof $==="string")return new URLSearchParams($).get("role");if($&&typeof $==="object"){let Z=$.role;return Z==null?null:String(Z)}return null}var F3="ios";function U3($,{peersTimeoutMs:Z=500,timeoutMs:Q=g7,broadcastIfSeveral:J=!1}={}){return new Promise((Y)=>{let W=new X3(`ws://127.0.0.1:${$}/message`),X=`serve-sim-peers-${Date.now()}`,V,z=!1,K=null,G=(O)=>{if(z)return;z=!0,clearTimeout(H),clearTimeout(V),Y(O);try{W.close()}catch{}},H=setTimeout(()=>G(K??"failed"),Q),B=(O,M)=>{if(z||K)return;clearTimeout(V),K=M,W.send(JSON.stringify({version:v7,...O}),(C)=>G(C?"failed":M))};W.on("open",()=>{W.send(JSON.stringify({version:v7,id:X,method:"getpeers",target:"server"})),V=setTimeout(()=>B({method:"reload"},"broadcast"),Z)}),W.on("message",(O)=>{let M;try{M=JSON.parse(O.toString())}catch{return}if(M.id!==X||K)return;if(M.error!==void 0&&M.result===void 0){B({method:"reload"},"broadcast");return}let C=B3(M.result);if(C.length===1)B({method:"reload",target:C[0]},"targeted");else if(C.length===0)G("failed");else if(J&&j3(M.result).every((D)=>D===F3))B({method:"reload"},"broadcast");else G("ambiguous")}),W.on("error",()=>G(K??"failed"))})}async function N3($,Z){let Q=await Promise.all($.map(async(Y)=>{try{let W=await Z(`http://127.0.0.1:${Y}/json/list`);return Array.isArray(W)?W:null}catch{return null}})),J=new Map;return $.forEach((Y,W)=>{if(Q[W])J.set(Y,Q[W])}),J}async function l7($,Z,Q=G3,{fetchJson:J=H3,sendReload:Y=(X,V)=>U3(X,V),lookupBudgetMs:W=h7}={}){if(!x$($))return{sent:!1,reason:"unsupported-app"};let X,V=await Promise.race([Promise.all([Promise.resolve(Z).catch(()=>null),N3(Q,J)]),new Promise((M)=>{X=setTimeout(()=>M(null),W)})]).finally(()=>clearTimeout(X));if(!V)return{sent:!1,reason:"timeout"};let[z,K]=V;if(!z)return{sent:!1,reason:"unknown-device"};let G=[...K].filter(([,M])=>u7(M,$,z));if(G.length===0)return{sent:!1,reason:"no-metro"};let H=G.map(([M])=>M);if(G.length>1||!m7(G[0][1],$,z))return{sent:!1,reason:"ambiguous",ports:H};let B=H[0],O=await Y(B,{broadcastIfSeveral:z3(G[0][1],$,z)});if(O==="targeted"||O==="broadcast")return{sent:!0,port:B,targeted:O==="targeted"};return{sent:!1,reason:O==="ambiguous"?"ambiguous":"send-failed",ports:H}}import{execFileSync as w3}from"child_process";import{createHash as x3}from"crypto";import{readFileSync as S3,unlinkSync as bz}from"fs";import{fileURLToPath as D3}from"url";import{dirname as q3}from"path";import{createHash as i7,timingSafeEqual as M3}from"crypto";var n7="SERVE_SIM_AUTH_TOKEN",S$="serve_sim_auth",o7="x-serve-sim-auth",L3=new Set(["forwarded","via","x-real-ip","x-client-ip","x-cluster-client-ip","true-client-ip","fastly-client-ip","cf-connecting-ip","cf-ray"]),C3=["x-forwarded-","tailscale-","ngrok-","x-original-forwarded"],O3=new Map;function k0($){return Array.isArray($)?$[0]:$}function k$($){let Z=$.socket;if(!Z)return;let Q=Z.remoteAddress;if(Q&&y$(Q)&&typeof Z.remotePort==="number"){let J=O3.get(Z.remotePort);if(J)return J}return Q}function y$($){if(!$)return!1;let Z=$.toLowerCase();if(Z==="::1"||Z==="0:0:0:0:0:0:0:1")return!0;let Q=Z.startsWith("::ffff:")?Z.slice(7):Z;return/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(Q)}function R3($){if(!$)return;try{return new URL(`http://${$}`).hostname.toLowerCase()}catch{return}}function a7($){if(!$)return!1;if($==="localhost"||$==="[::1]")return!0;return y$($)}function _3($){for(let Z of Object.keys($)){let Q=Z.toLowerCase();if(L3.has(Q))return!0;if(C3.some((J)=>Q.startsWith(J)))return!0}return!1}function P3($){return y$(k$($))&&!_3($.headers)}function y0($){if(!P3($))return!1;return a7(R3(k0($.headers.host)))}function z6($){let Z=k0($.headers.origin);if(!Z)return"absent";try{let Q=new URL(Z);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return"cross";let J=Q.host.toLowerCase();return[k0($.headers.host),k0($.headers["x-forwarded-host"])?.split(",")[0]?.trim()].some((W)=>!!W&&W.toLowerCase()===J)?"same":"cross"}catch{return"cross"}}function H6($){let Z=k0($.headers.origin);if(!Z)return!1;try{let Q=new URL(Z);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;if(Q.host.toLowerCase()!==(k0($.headers.host)??"").toLowerCase())return!1;return a7(Q.hostname.toLowerCase())}catch{return!1}}function d7($){return i7("sha256").update($).digest()}function C9($,Z){return M3(d7($),d7(Z))}function f$($){return i7("sha256").update(`serve-sim-auth-cookie:${$}`).digest("base64url")}function A3($,Z){if(!$)return;for(let Q of $.split(";")){let J=Q.indexOf("=");if(J===-1)continue;if(Q.slice(0,J).trim()===Z)return Q.slice(J+1).trim()}return}function T3($,Z){let Q=k0($.headers.authorization)??"",J=/^Bearer\s+(.+)$/i.exec(Q)?.[1]?.trim();if(J&&C9(J,Z))return!0;let Y=A3(k0($.headers.cookie),S$);return!!Y&&C9(Y,f$(Z))}function b$($,Z){if(!Z)return{ok:!1,status:403,message:`Remote access is disabled. Start serve-sim with --auth-token <token> (or ${n7}) and send it as "Authorization: Bearer <token>".`};if(T3($,Z))return{ok:!0};return{ok:!1,status:401,message:"Missing or invalid serve-sim auth token."}}function s7($){let Z=($??process.env[n7]??"").trim();return Z===""?void 0:Z}function r7($){return q3(D3($))}import{execSync as E3}from"child_process";function t7($){try{let Z=E3(`lsof -ti tcp:${$} -sTCP:LISTEN`,{encoding:"utf-8",stdio:"pipe"}).trim();if(!Z)return[];let Q=process.pid;return Z.split(`
|
|
70
70
|
`).map((J)=>parseInt(J,10)).filter((J)=>Number.isFinite(J)&&J!==Q)}catch{return[]}}var k3=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;function y3($){return k3.test($)}function f3($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function b3($){return/serve-sim(?:-bin)?/.test($)}function v3($){try{return S3(`/proc/${$}/cmdline`,"utf8").split(String.fromCharCode(0)).join(" ").trim()}catch{}try{return w3("ps",["-p",String($),"-o","args="],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:1000}).trim()}catch{return null}}function e7($,Z={}){let Q=Z.isAlive??f3,J=Z.portHolders??t7,Y=Z.commandLine??v3;if(Q($.pid))return $;for(let W of J($.port)){if(W===process.pid||!Q(W))continue;let X=Y(W);if(X==null||!b3(X))continue;return G$("recovered helper for %s via port %d pid %d (recorded pid %d was dead)",$.device,$.port,W,$.pid),{...$,pid:W}}return null}function $Z($){try{z9($)}catch(Z){G$("failed to rewrite recovered state for %s: %o",$.device,Z)}}function ZZ($){return $?x3("sha256").update($).digest("hex"):void 0}function QZ($,Z,Q,J){if(!s6($.deviceSet,J))return"keep";if(Z&&y3($.device)&&!Z.has($.device))return $.pid===Q?"recycle-self":"recycle-helper";return"keep"}import{execFileSync as O9}from"child_process";import{createHash as jZ}from"crypto";import{existsSync as U0,mkdirSync as FZ,readdirSync as h3,readFileSync as E0,renameSync as UZ,statSync as NZ,unlinkSync as GZ}from"fs";import{tmpdir as MZ}from"os";import{basename as LZ,dirname as R9,join as W0}from"path";import{inflateSync as g3}from"zlib";function JZ($){if($.length===0)return null;return $.reduce((Z,Q)=>Q.width*Q.height<Z.width*Z.height?Q:Z)}function YZ($){if($.length!==2)return $.map(()=>"display");return $[0]<=$[1]?["cover","inner"]:["inner","cover"]}function WZ($,Z="Display"){switch($){case"cover":return"Cover";case"inner":return"Inner";default:return Z}}function XZ($){let Z=h$(h$($).capabilities??$),Q=Array.isArray(Z.displays)?Z.displays:[],J=[];for(let Y of Q){let W=h$(Y);if(y6(W.displayType)!=="integrated")continue;if(W.hasDigitizer!==!0)continue;let X=y6(W.chromeIdentifier);if(!X)continue;let V=v$(W.width),z=v$(W.height);if(!V||!z||V<=0||z<=0)continue;let K=v$(W.scale),G=y6(W.deviceName)??(typeof W.screenID==="number"?`screen-${W.screenID}`:`display-${J.length}`);J.push({id:G,label:y6(W.displayName)??G,chromeIdentifier:X,mask:y6(W.framebufferMaskIdentifier),width:V,height:z,logicalScreenSize:K&&K>0?{width:V/K,height:z/K}:null})}return J}function v$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="string"&&$.trim()){let Z=Number($);return Number.isFinite(Z)?Z:null}return null}function y6($){return typeof $==="string"&&$?$:null}function h$($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}var n$="/Library/Developer/CoreSimulator/Profiles/DeviceTypes",CZ="/Library/Developer/DeviceKit/Chrome",VZ="com.apple.dt.devicekit.chrome.",KZ=W0(MZ(),"serve-sim-devicekit-chrome"),zZ=W0(MZ(),"serve-sim-device-placeholder-assets"),f0="/System/Library/CoreServices/CoreTypes.bundle/Contents/Library/MobileDevices.bundle/Contents/Resources",u3="/System/Library/CoreServices/CoreTypes.bundle/Contents/Library/CoreTypes-0006.bundle/Contents/Resources",HZ={"vision-pro":{paths:[W0(f0,"com.apple.vision-pro.icns"),W0(u3,"com.apple.visionpro.icns")]},"iphone-17e":{paths:[W0(f0,"com.apple.iphone-16-e-1.icns")]},"ipad-air-11-inch-m4":{paths:[W0(f0,"com.apple.ipad-air-m3-1.icns")]},"ipad-air-13-inch-m4":{paths:[W0(f0,"com.apple.ipad-air-m3-1.icns")]}},g$=null,u$=new Map,m$=new Map,c$=new Map,p$=new Map,l$=null,d$=new Map;function b6($){return $.startsWith(VZ)?$.slice(VZ.length):$}function o$($){let Z=typeof $==="string"?$:$.toString("latin1"),Q=/\/CropBox\s*\[\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\]/.exec(Z)??/\/MediaBox\s*\[\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\]/.exec(Z);if(!Q)return null;let J=Number(Q[1]),Y=Number(Q[2]),W=Number(Q[3]),X=Number(Q[4]),V=Math.abs(W-J),z=Math.abs(X-Y);return V>0&&z>0?{width:V,height:z}:null}function m3($,Z){let Q=JY($);if(Q)return Q;let J=typeof $.framebufferMask==="string"?$.framebufferMask:null;if(!J)return null;let Y=typeof $.__profileDir==="string"?$.__profileDir:null;if(!Y)return null;let W=W0(Y,`${J}.pdf`);if(!U0(W))return null;let X=o$(E0(W));if(!X)return null;let V=YY(Z);return{width:X.width/V,height:X.height/V}}function a$($){let Z=P9($);if(c$.has(Z))return c$.get(Z)??[];let Q=d3(Z);return c$.set(Z,Q),Q}function OZ($){let Z=a$($);if(Z.length>0)return JZ(Z)?.chrome??null;let Q=P9($),J=Q;if(m$.has(J))return m$.get(J)??null;let Y=i3(Q);return m$.set(J,Y),Y}function RZ($){let Z=P9($);if(p$.has(Z))return p$.get(Z)??null;let Q=c3($);return p$.set(Z,Q),Q}function c3($){let Z=o3($),Q=Z?DZ(Z):null,J=a3(Q)??s3($.name);if(!J)return null;let Y=AZ(J);return Y?{name:J,width:Y.width,height:Y.height}:null}function _Z($,Z){let Q=b6($.searchParams.get("chrome")??""),J=$.searchParams.get("image")??"";if(!/^[A-Za-z0-9_-]+$/.test(Q)||!J){B6(Z,400,"Invalid chrome asset request");return}let Y=EZ(Q);if(!Y||!Y.allowedImages.has(J)||J.includes("/")){B6(Z,404,"Chrome asset not found");return}let W=r$(Q,J);if(!U0(W)){B6(Z,404,"Chrome asset not found");return}try{let X=wZ(Q,J,W),V=E0(X);Z.writeHead(200,{"Content-Type":"image/png","Cache-Control":"public, max-age=604800, immutable","Content-Length":String(V.byteLength)}),Z.end(V)}catch(X){B6(Z,500,X instanceof Error?X.message:"Failed to render chrome asset")}}function PZ($,Z){let Q=$.searchParams.get("name")??"";try{let J=AZ(Q);if(!J){B6(Z,404,"Placeholder asset not found");return}let Y=E0(J.pngPath);Z.writeHead(200,{"Content-Type":"image/png","Cache-Control":"public, max-age=604800, immutable","Content-Length":String(Y.byteLength)}),Z.end(Y)}catch(J){B6(Z,500,J instanceof Error?J.message:"Failed to render placeholder asset")}}function AZ($){if(!/^[A-Za-z0-9._-]+$/.test($))return null;if(d$.has($))return d$.get($)??null;let Z=p3($),Q=Z?WY($,Z):null;return d$.set($,Q),Q}function p3($){let Q=l3($)?.paths.find((Y)=>U0(Y));if(Q)return Q;if(!IZ().some((Y)=>Y.iconName===$))return null;let J=W0(f0,`${$}.icns`);return U0(J)?J:null}function l3($){return Object.prototype.hasOwnProperty.call(HZ,$)?HZ[$]:null}function d3($){let Z=s$($);if(!U0(Z))return[];let Q=R9(Z),J=f6(W0(Q,"capabilities.plist")),Y=XZ(J);if(Y.length===0)return[];let W=YZ(Y.map((V)=>V.width*V.height)),X=[];for(let V=0;V<Y.length;V++){let z=Y[V],K=TZ(b6(z.chromeIdentifier),qZ(Q,z.mask),z.logicalScreenSize);if(!K)continue;let G=W[V]??"display";X.push({id:z.id,role:G,name:WZ(G,z.label),width:z.width,height:z.height,chrome:K})}return X}function i3($){let Z=s$($);if(!U0(Z))return null;let Q=DZ(Z);if(!Q?.chromeIdentifier)return null;return TZ(Q.chromeIdentifier,Q.framebufferMaskSize,Q.screenSize)}function TZ($,Z,Q){let J=EZ($);if(!J)return null;let Y=null;if(J.compositeImage)Y=i$(J.identifier,J.compositeImage);let W=J.compositeImage?VY(J.identifier,J.compositeImage):null,X=(W&&Z?GY(Z,W):null)??Q??(Y?{width:Y.width-J.insets.left-J.insets.right,height:Y.height-J.insets.top-J.insets.bottom}:null);if(!X||X.width<=0||X.height<=0)return null;let V=Y??{width:X.width+J.insets.left+J.insets.right,height:X.height+J.insets.top+J.insets.bottom},z={x:J.devicePadding.left,y:J.devicePadding.top,width:V.width,height:V.height},K={width:V.width+J.devicePadding.left+J.devicePadding.right,height:V.height+J.devicePadding.top+J.devicePadding.bottom},G={x:z.x+(V.width-X.width)/2,y:z.y+(V.height-X.height)/2,width:X.width,height:X.height},H=W?Math.max(0,W.radius-(W.width-X.width)/2):J.innerCornerRadius,B=J.slice?i$(J.identifier,J.slice.topLeft):null,O=J.identifier.startsWith("watch"),M=J.buttons.flatMap((C)=>{let D=i$(J.identifier,C.image);if(!D)return[];let _=$Y(C,D,V,J.devicePadding),L={x:D.width>0?(C.rolloverOffset.x-C.normalOffset.x)/D.width:0,y:D.height>0?(C.rolloverOffset.y-C.normalOffset.y)/D.height:0};return[{name:C.name,image:C.image,imageDown:C.imageDown,onTop:C.onTop||O,frame:{..._,...D},hover:L,usagePage:C.usagePage,usage:C.usage}]});return{identifier:J.identifier,frame:K,body:z,screen:G,insets:J.insets,outerCornerRadius:J.outerCornerRadius,innerCornerRadius:J.innerCornerRadius,screenRadius:H,compositeImage:J.compositeImage,slice:J.slice,corner:B,buttons:M}}function DZ($){let Z=f6($);if(!Z)return null;let Q=typeof Z.chromeIdentifier==="string"?Z.chromeIdentifier:null,J=Q?b6(Q):null;return{chromeIdentifier:J,modelIdentifier:typeof Z.modelIdentifier==="string"?Z.modelIdentifier:null,productClass:typeof Z.productClass==="string"?Z.productClass:null,screenSize:J?m3({...Z,__profileDir:R9($)},J):null,framebufferMaskSize:n3({...Z,__profileDir:R9($)})}}function n3($){let Z=typeof $.framebufferMask==="string"?$.framebufferMask:null,Q=typeof $.__profileDir==="string"?$.__profileDir:null;if(!Z||!Q)return null;return qZ(Q,Z)}function qZ($,Z){if(!Z)return null;let Q=W0($,`${Z}.pdf`);if(!U0(Q))return null;return o$(E0(Q))}function P9($){return ZY($.deviceTypeIdentifier)??$.name}function o3($){let Z=s$(P9($));return U0(Z)?Z:null}function s$($){return W0(n$,`${$}.simdevicetype`,"Contents","Resources","profile.plist")}function a3($){if(!$)return null;let Z=new Set;if($.modelIdentifier)Z.add($.modelIdentifier);if($.productClass)Z.add($.productClass),Z.add(`${$.productClass}AP`);if(Z.size===0)return null;for(let Q of IZ())if(Q.modelCodes.some((J)=>Z.has(J)))return Q.iconName;return null}function s3($){let Z=$.toLowerCase();if(Z.includes("vision"))return"vision-pro";if(/iphone\s+17e\b/.test(Z))return"iphone-17e";if(/ipad\s+air\s+11-inch\s+\(m4\)/.test(Z))return"ipad-air-11-inch-m4";if(/ipad\s+air\s+13-inch\s+\(m4\)/.test(Z))return"ipad-air-13-inch-m4";return null}function IZ(){if(l$)return l$;let $=f6(W0(f0,"MobileDevices-Info.plist"))??f6(W0(R9(f0),"Info.plist")),Z=Array.isArray($?.UTExportedTypeDeclarations)?$.UTExportedTypeDeclarations:[],Q=[];for(let J of Z){let Y=R0(J),W=F0(Y.UTTypeIconFile);if(!W||!W.endsWith(".icns"))continue;let X=W0(f0,W);if(!U0(X))continue;let z=R0(Y.UTTypeTagSpecification)["com.apple.device-model-code"],K=Array.isArray(z)?z.filter((G)=>typeof G==="string"&&G.length>0):[];if(K.length===0)continue;Q.push({description:F0(Y.UTTypeDescription)??"",iconFile:W,iconName:LZ(W,".icns"),modelCodes:K})}return l$=Q,Q}function EZ($){let Z=b6($);if(!/^[A-Za-z0-9_-]+$/.test(Z))return null;if(u$.has(Z))return u$.get(Z)??null;let Q=W0(CZ,`${Z}.devicechrome`,"Contents","Resources","chrome.json"),J=null;try{let Y=JSON.parse(E0(Q,"utf-8"));J=r3(Y)}catch{J=null}return u$.set(Z,J),J}function r3($){let Z=typeof $.identifier==="string"?$.identifier:null;if(!Z)return null;let Q=b6(Z),J=R0($.images),Y=R0(J.sizing),W=R0($.paths),X=I0(R0(W.simpleOutsideBorder).cornerRadiusX),V={top:I0(Y.topHeight),left:I0(Y.leftWidth),bottom:I0(Y.bottomHeight),right:I0(Y.rightWidth)},z=R0(J.devicePadding),K={top:I0(z.top),left:I0(z.left),bottom:I0(z.bottom),right:I0(z.right)},G=typeof J.composite==="string"?J.composite:null,H=t3(J),B=Array.isArray($.inputs)?$.inputs.flatMap((M)=>{let C=e3(R0(M));return C?[C]:[]}):[],O=new Set;for(let M of Object.values(J))if(typeof M==="string")O.add(M);for(let M of B)O.add(M.image);if(Array.isArray($.inputs))for(let M of $.inputs){let C=R0(M);if(typeof C.imageDown==="string")O.add(C.imageDown)}return{identifier:Q,insets:V,devicePadding:K,outerCornerRadius:X,innerCornerRadius:Math.max(X-Math.max(V.left,V.top),0),compositeImage:G,slice:H,buttons:B,allowedImages:O}}function t3($){let Z=F0($.topLeft),Q=F0($.top),J=F0($.topRight),Y=F0($.right),W=F0($.bottomRight),X=F0($.bottom),V=F0($.bottomLeft),z=F0($.left);if(!Z||!Q||!J||!Y||!W||!X||!V||!z)return null;return{topLeft:Z,top:Q,topRight:J,right:Y,bottomRight:W,bottom:X,bottomLeft:V,left:z}}function e3($){let Z=F0($.name),Q=F0($.image);if(!Z||!Q)return null;let J=F0($.anchor),Y=F0($.align),W=R0($.offsets),X=BZ(R0(W.normal)),V=BZ(R0(W.rollover));return{name:Z,image:Q,imageDown:F0($.imageDown),onTop:$.onTop===!0,anchor:J==="right"||J==="top"||J==="bottom"?J:"left",align:Y==="trailing"?"trailing":"leading",normalOffset:X??V??{x:0,y:0},rolloverOffset:V??X??{x:0,y:0},usagePage:b0($.usagePage),usage:b0($.usage)}}function $Y($,Z,Q,J){let{left:Y,top:W}=J,X=2*$.normalOffset.x-$.rolloverOffset.x,V=2*$.normalOffset.y-$.rolloverOffset.y,z=$.align==="trailing"?Y+Q.width+X-Z.width:Y+X;switch($.anchor){case"left":return{x:Y+$.rolloverOffset.x-Z.width/2,y:W+$.rolloverOffset.y};case"right":return{x:Y+Q.width+X,y:W+V};case"top":return{x:z,y:W+V-Z.height};case"bottom":return{x:z,y:W+Q.height+V}}}function ZY($){if(!$)return null;if(!g$)g$=QY();return g$.get($)??null}function QY(){let $=new Map;try{for(let Z of h3(n$)){if(!Z.endsWith(".simdevicetype"))continue;let Q=W0(n$,Z),J=f6(W0(Q,"Contents","Info.plist")),Y=typeof J?.CFBundleIdentifier==="string"?J.CFBundleIdentifier:null,W=typeof J?.CFBundleName==="string"?J.CFBundleName:LZ(Z,".simdevicetype");if(Y)$.set(Y,W)}}catch{}return $}function f6($){try{let Z=O9("plutil",["-convert","json","-o","-",$],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:2000});return JSON.parse(Z)}catch{return null}}function JY($){let Z=b0($.mainScreenWidth),Q=b0($.mainScreenHeight),J=b0($.mainScreenScale);if(!Z||!Q||!J||J<=0)return null;return{width:Z/J,height:Q/J}}function YY($){if($.startsWith("phone"))return 3;if($.startsWith("tablet"))return 2;if($.startsWith("watch"))return 2;return 1}function i$($,Z){let Q=r$($,Z);if(!U0(Q))return null;return o$(E0(Q))}function r$($,Z){return W0(CZ,`${$}.devicechrome`,"Contents","Resources",`${Z}.pdf`)}function wZ($,Z,Q){FZ(KZ,{recursive:!0});let J=NZ(Q),Y=jZ("sha1").update($).update("\x00").update(Z).update("\x00").update(String(J.mtimeMs)).update("\x00").update(String(J.size)).digest("hex"),W=W0(KZ,`${$}-${Y}.png`);if(U0(W))return W;let X=`${W}.${process.pid}.tmp`;return O9("sips",["-s","format","png",Q,"--out",X],{stdio:["ignore","ignore","ignore"],timeout:1e4}),UZ(X,W),W}function WY($,Z){FZ(zZ,{recursive:!0});let Q=NZ(Z),J=jZ("sha1").update($).update("\x00").update(Z).update("\x00").update(String(Q.mtimeMs)).update("\x00").update(String(Q.size)).digest("hex"),Y=W0(zZ,`${$}-${J}.png`);if(U0(Y)){let V=_9(E0(Y));return{sourcePath:Z,pngPath:Y,width:V.width,height:V.height}}let W=`${Y}.${process.pid}.tmp`,X=`${Y}.${process.pid}.raw.png`;try{O9("sips",["-s","format","png",Z,"--out",X],{stdio:["ignore","ignore","ignore"],timeout:1e4});let V=E0(X),z=XY(V)??{x:0,y:0,..._9(V)};return O9("sips",["-c",String(z.height),String(z.width),"--cropOffset",String(z.y),String(z.x),"-s","format","png",Z,"--out",W],{stdio:["ignore","ignore","ignore"],timeout:1e4}),UZ(W,Y),{sourcePath:Z,pngPath:Y,width:z.width,height:z.height}}finally{try{if(U0(X))GZ(X)}catch{}try{if(U0(W))GZ(W)}catch{}}}function _9($){if($.byteLength<24||$[0]!==137||$.toString("ascii",1,4)!=="PNG")throw Error("Invalid PNG placeholder asset");return{width:$.readUInt32BE(16),height:$.readUInt32BE(20)}}function xZ($,Z){let{width:Q,height:J}=_9($),Y=8,W=0,X=0,V=[];while(Y<$.byteLength){let C=$.readUInt32BE(Y);Y+=4;let D=$.toString("ascii",Y,Y+4);Y+=4;let _=$.subarray(Y,Y+C);if(Y+=C+4,D==="IHDR")W=_[8]??0,X=_[9]??0;else if(D==="IDAT")V.push(_);else if(D==="IEND")break}let z=X===6?4:X===4?2:0;if(W!==8||z===0||V.length===0)return null;let K=X===6,G=g3(Buffer.concat(V)),H=Q*z,B=new Uint8Array(Q*J),O=Buffer.alloc(H),M=0;for(let C=0;C<J;C++){let D=G[M++]??0,_=Buffer.from(G.subarray(M,M+H));M+=H,zY(_,O,z,D);for(let L=0;L<Q;L++){let A=L*z,q=_[A]??0,I=K?_[A+1]??0:q,F=K?_[A+2]??0:q,j=_[A+z-1]??0;if(Z(q,I,F,j))B[C*Q+L]=1}O=_}return{width:Q,height:J,mask:B}}function XY($){let{width:Z,height:Q}=_9($),J=xZ($,(z,K,G,H)=>H>0);if(!J)return{x:0,y:0,width:Z,height:Q};let Y=Z,W=Q,X=-1,V=-1;for(let z=0;z<Q;z++)for(let K=0;K<Z;K++){if(!J.mask[z*Z+K])continue;if(K<Y)Y=K;if(z<W)W=z;if(K>X)X=K;if(z>V)V=z}if(X<Y||V<W)return{x:0,y:0,width:Z,height:Q};return{x:Y,y:W,width:X-Y+1,height:V-W+1}}function GY($,Z){if(Z.width<=0)return null;let Q=Math.max(1,Math.round($.width/Z.width));return{width:$.width/Q,height:$.height/Q}}function VY($,Z){let Q=KY($,Z);if(!Q)return null;let J=xZ(Q,(L,A,q,I)=>I>200&&L<30&&A<30&&q<30);if(!J)return null;let{width:Y,height:W,mask:X}=J,V=Math.floor(Y/2),z=Math.floor(W/2),K=(L,A)=>L>=0&&A>=0&&L<Y&&A<W&&X[A*Y+L]===1;if(!K(V,z))return null;let G=V;while(G>0&&K(G-1,z))G--;let H=V;while(H<Y-1&&K(H+1,z))H++;let B=z;while(B>0&&K(V,B-1))B--;let O=z;while(O<W-1&&K(V,O+1))O++;let M=O-B,C=(L,A)=>{let q=0;while(q<M&&!K(L,A?B+q:O-q))q++;return q},D=[C(G,!0),C(H,!0),C(G,!1),C(H,!1)],_=D.reduce((L,A)=>L+A,0)/D.length;return{x:G,y:B,width:H-G+1,height:O-B+1,radius:_}}function KY($,Z){let Q=r$($,Z);if(!U0(Q))return null;try{return E0(wZ($,Z,Q))}catch{return null}}function zY($,Z,Q,J){for(let Y=0;Y<$.byteLength;Y++){let W=Y>=Q?$[Y-Q]:0,X=Z[Y]??0,V=Y>=Q?Z[Y-Q]:0;switch(J){case 0:break;case 1:$[Y]=$[Y]+W&255;break;case 2:$[Y]=$[Y]+X&255;break;case 3:$[Y]=$[Y]+Math.floor((W+X)/2)&255;break;case 4:$[Y]=$[Y]+HY(W,X,V)&255;break;default:throw Error(`Unsupported PNG filter ${J}`)}}}function HY($,Z,Q){let J=$+Z-Q,Y=Math.abs(J-$),W=Math.abs(J-Z),X=Math.abs(J-Q);if(Y<=W&&Y<=X)return $;return W<=X?Z:Q}function B6($,Z,Q){$.writeHead(Z,{"Content-Type":"application/json","Cache-Control":"no-store"}),$.end(JSON.stringify({ok:!1,error:Q}))}function I0($){return b0($)??0}function b0($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="string"&&$.trim()){let Z=Number($);return Number.isFinite(Z)?Z:null}return null}function F0($){return typeof $==="string"&&$?$:null}function R0($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function BZ($){let Z=b0($.x),Q=b0($.y);return Z===null||Q===null?null:{x:Z,y:Q}}import{exec as BY}from"child_process";import{timingSafeEqual as jY}from"crypto";import{request as FY}from"http";import{WebSocketServer as UY}from"ws";var NY=1e4,MY=4194304,A9="exec disabled; start with --allow-exec",SZ="exec requires the exec token",LY="host actions are only available to loopback clients";function CY($){for(let Z=0;Z<$.length;Z++){let Q=$.charCodeAt(Z);if(Q<=31||Q===127)return!0}return/\s/.test($)}function OY($,Z){if(!Z||typeof $!=="string")return!1;let Q=Buffer.from($),J=Buffer.from(Z);return Q.length===J.length&&jY(Q,J)}function RY($){let Z={};for(let Q of["host","x-forwarded-proto","authorization","cookie"]){let J=$.headers[Q];if(typeof J==="string"&&J)Z[Q]=J}return Z}function kZ($){return y0($)&&H6($)}function _Y($,Z,Q,J,Y,W){let X=!1,V=!1,z=new Map,K=J.ssePrefixes??[],G=(O)=>{if($.readyState===$.OPEN)$.send(JSON.stringify(O))},H=setTimeout(()=>{if(!X)$.close()},NY);H.unref?.();let B=(O,M)=>{if(z.has(O))return;let C=M.split("?")[0];if(!M.startsWith("/")||CY(M)||!K.some((_)=>C===_)){G({sub:O,end:!0,error:"path not allowed"});return}if(!Z){G({sub:O,end:!0,error:"no local port"});return}let D;try{D=FY({host:"127.0.0.1",port:Z,path:M,headers:{...Q,accept:"text/event-stream"}},(_)=>{_.on("data",(L)=>G({sub:O,data:L.toString("utf-8")})),_.on("end",()=>{z.delete(O),G({sub:O,end:!0})})})}catch{G({sub:O,end:!0,error:"bad path"});return}D.on("error",()=>{z.delete(O),G({sub:O,end:!0})}),D.end(),z.set(O,{destroy:()=>D.destroy()})};$.on("message",(O)=>{let M;try{M=JSON.parse(O.toString())}catch{return}if(!X){X=!0,V=OY(M.token,J.execToken),clearTimeout(H),G({ready:!0});return}if(typeof M.unsub==="number"){z.get(M.unsub)?.destroy(),z.delete(M.unsub);return}if(typeof M.sub==="number"&&typeof M.path==="string"){B(M.sub,M.path);return}if(typeof M.id==="number"&&M.rpc!==void 0){let{id:_}=M;if(!J.onRpcRequest){G({id:_,error:"rpc requests not supported"});return}if(!W){G({id:_,error:LY});return}J.onRpcRequest(M.rpc).then((L)=>G({...L,id:_})).catch((L)=>G({id:_,error:L instanceof Error?L.message:String(L)}));return}if(typeof M.id==="number"&&M.ui!==void 0){let{id:_}=M;if(!J.onUiRequest){G({id:_,error:"ui requests not supported"});return}J.onUiRequest(M.ui).then((L)=>G({id:_,...L})).catch((L)=>G({id:_,error:L instanceof Error?L.message:String(L)}));return}if(typeof M.id!=="number"||typeof M.command!=="string"||!M.command)return;let{id:C,command:D}=M;if(!J.allowExec){G({id:C,stdout:"",stderr:A9,exitCode:126,error:A9});return}if(!Y){G({id:C,stdout:"",stderr:"exec is only available to loopback clients",exitCode:126});return}if(!V){G({id:C,stdout:"",stderr:SZ,exitCode:126,error:SZ});return}BY(D,{maxBuffer:16777216},(_,L,A)=>{let q={id:C,stdout:L.toString(),stderr:A.toString(),exitCode:_?_.code??1:0};try{J.onCommandResult?.(D,q)}catch{}G(q)})}),$.on("error",()=>$.close()),$.on("close",()=>{clearTimeout(H);for(let O of z.values())O.destroy();z.clear()})}function yZ($){let Z=new UY({noServer:!0,maxPayload:MY});return function(J,Y,W){let X=J.url??"",V=X.indexOf("?"),z=V===-1?X:X.slice(0,V);if(z!==$.path&&z!==`${$.path}/`)return!1;if(z6(J)!=="same")return Y.destroy(),!0;let K=($.allowShell??kZ)(J),G=($.allowRpc??kZ)(J),H=$.serverPort?.()||Y.localPort||void 0;return Z.handleUpgrade(J,Y,W,(B)=>{_Y(B,H,RY(J),$,K,G)}),!0}}import{execFile as kY}from"child_process";import{randomUUID as yY}from"crypto";import{closeSync as fY,constants as bY,fstatSync as vY,lstatSync as pZ,openSync as hY,readFileSync as lZ,unlinkSync as dZ,writeSync as gY}from"fs";import{homedir as uY}from"os";import{basename as mY,dirname as cY,join as q9}from"path";var fZ=[{key:"camera",label:"Camera"},{key:"microphone",label:"Microphone"},{key:"photos",label:"Photos"},{key:"photos-add",label:"Add to Photos"},{key:"contacts",label:"Contacts"},{key:"calendar",label:"Calendar"},{key:"reminders",label:"Reminders"},{key:"location",label:"Location"},{key:"location-always",label:"Location (Always)"},{key:"notifications",label:"Notifications"},{key:"motion",label:"Motion"},{key:"media-library",label:"Media Library"},{key:"siri",label:"Siri"}];function PY($){return`'${$.replace(/'/g,"'\\''")}'`}function bZ($){return $.map(PY).join(" ")}import{execFile as AY}from"child_process";import{existsSync as hZ}from"fs";import{join as t$,resolve as TY}from"path";var e$=r7(import.meta.url),gZ=["extra-small","small","medium","large","extra-large","extra-extra-large","extra-extra-extra-large","accessibility-medium","accessibility-large","accessibility-extra-large","accessibility-extra-extra-large","accessibility-extra-extra-extra-large"],DY=["none","grayscale","red-green","green-red","blue-yellow"],qY={protanopia:"red-green",deuteranopia:"green-red",tritanopia:"blue-yellow"},v6=["on","off"],IY=new Set(["on","true","enabled","1","yes"]),EY=new Set(["off","false","disabled","0","no"]),d0={appearance:{via:"appearance",values:["light","dark"]},"liquid-glass":{via:"ax",values:["clear","tinted"]},"color-filter":{via:"ax",values:DY,aliases:qY},"text-size":{via:"content_size",values:gZ,extraValues:["increment","decrement"]},"reduce-motion":{via:"ax",values:v6,toggle:!0},"increase-contrast":{via:"increase_contrast",values:v6,toggle:!0},"show-borders":{via:"ax",values:v6,toggle:!0},"reduce-transparency":{via:"ax",values:v6,toggle:!0},voiceover:{via:"ax",values:v6,toggle:!0}};function uZ($,Z){let Q=d0[$];if(!Q)return null;let J=Z.toLowerCase();if(Q.toggle){if(IY.has(J))return"on";if(EY.has(J))return"off";return null}let Y=Q.aliases?.[J]??J;if(Q.values.includes(Y))return Y;if(Q.extraValues?.includes(Y))return Y;return null}function vZ(){let $=[t$(e$,"..","dist","simax","serve-sim-ax-settings"),t$(e$,"simax","serve-sim-ax-settings")];for(let Z of $)if(hZ(Z))return TY(Z);return null}var T9=null;function wY(){return T9??=(async()=>{let $=vZ();if($)return $;let Z=t$(e$,"..","Sources","SimAXSettings","build.sh");if(!hZ(Z))throw Error("sim-ax-settings binary not found — this build of serve-sim does not "+"include the simulator settings helper. Reinstall from a recent release.");console.error("[serve-sim] building sim-ax-settings (one-time)…"),await $8("bash",[Z]);let Q=vZ();if(!Q)throw Error("Build succeeded but sim-ax-settings not found.");return Q})(),T9.catch(()=>{T9=null}),T9}function $8($,Z){return new Promise((Q,J)=>{AY($,Z,{encoding:"utf-8",maxBuffer:4194304},(Y,W,X)=>{if(Y)J(Error(String(X).trim()||Y.message));else Q(String(W).trim())})})}function mZ($,Z,Q){let J=o(["ui",$,Z]);if(Q!==void 0)J.push(Q);return $8("xcrun",J)}async function Z8($,...Z){let Q=await wY();return $8("xcrun",o(["spawn",$,Q,...Z]))}function xY($){return $==="enabled"?"on":"off"}function SY($){return $==="on"?"enabled":"disabled"}async function Q8($,Z){let Q=d0[Z];if(!Q)throw Error(`unknown option: ${Z}`);if(Q.via==="ax")return Z8($,"get",Z);let J=(await mZ($,Q.via)).toLowerCase();return Q.toggle?xY(J):J}async function D9($,Z,Q){let J=d0[Z];if(!J)throw Error(`unknown option: ${Z}`);if(J.via==="ax"){await Z8($,"set",Z,Q);return}await mZ($,J.via,J.toggle?SY(Q):Q)}async function cZ($){let Z=Object.entries(d0).filter(([,W])=>W.via!=="ax"),[Q,...J]=await Promise.all([Z8($,"status").then((W)=>JSON.parse(W)).catch(()=>({})),...Z.map(([W])=>Q8($,W).catch(()=>"unsupported"))]),Y={};for(let[W,X]of Object.entries(d0))if(X.via==="ax")Y[W]=Q[W]??"unsupported";return Z.forEach(([W],X)=>{Y[W]=J[X]}),Y}var NH=`Usage: serve-sim ui [status] [--json] [-d udid]
|
|
@@ -152,5 +152,5 @@ ${z0}`)}})();return}if(!e){N.destroy();return}let Y0=e.device??y;if(e.upstreamPa
|
|
|
152
152
|
\r
|
|
153
153
|
`)};let E,x=yZ({path:`${Z}/exec-ws`,serverPort:()=>E,allowExec:V,execToken:X,allowShell:(T)=>y0(T)&&H6(T),allowRpc:(T)=>y0(T)&&H6(T),onRpcRequest:j,ssePrefixes:[`${Z}/api/events`,`${Z}/api/event-log/events`,`${Z}/appstate`,`${Z}/ax`],onUiRequest:R,onCommandResult:(T,N)=>R8(T,N)}),k=w.handleUpgrade;return w.handleUpgrade=(T,N,b)=>{let m=T.url??"",y=P8(m);if(H(y)){if(!y0(T)){let p=b$(T,z);if(!p.ok){o5(N,p.status,p.message);return}}if(z6(T)==="cross"){o5(N,403,"Cross-origin WebSocket blocked");return}}if(x(T,N,b))return;k(T,N,b)},w.setServerPort=(T)=>{E=T},w}export{EG as startDeviceInProcess,gG as simulatorName,CB as simMiddleware,g0 as selectServeSimState,b9 as rewriteStateForRequestHost,vG as resolveServeSimBin,w0 as readServeSimStates,r5 as publicState,A8 as previewConfigForState,CG as parseGridPaging,MG as parseForegroundAppLogMessage,LB as matchInstalledAppByDisplayName};
|
|
154
154
|
|
|
155
|
-
//# debugId=
|
|
155
|
+
//# debugId=C92D2CD764B0339664756E2164756E21
|
|
156
156
|
//# sourceMappingURL=middleware.js.map
|
|
Binary file
|