@limrun/ui 0.21.0-rc.1 → 0.22.0
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 +36 -8
- package/dist/BufferGeometryUtils-Dm5SmmmT.mjs +64 -0
- package/dist/BufferGeometryUtils-Dne8i0aT.js +1 -0
- package/dist/GLTFLoader-DzSwAt9C.js +1 -0
- package/dist/{GLTFLoader-C4EgJezB.mjs → GLTFLoader-L51A9w-A.mjs} +138 -137
- package/dist/components/device-view.d.ts +29 -0
- package/dist/components/duo-frame.d.ts +5 -1
- package/dist/components/duo-model.d.ts +2 -1
- package/dist/components/macbook-frame.d.ts +30 -0
- package/dist/components/macbook-geometry.d.ts +77 -0
- package/dist/components/model-source.d.ts +8 -0
- package/dist/components/remote-control.d.ts +40 -1
- package/dist/components/studio-environment.d.ts +6 -0
- package/dist/core/mac-pointer.d.ts +56 -0
- package/dist/{core-C5BY3i_b.js → core-BCBQrYsk.js} +1 -1
- package/dist/{core-DbDGdVUi.mjs → core-nbvkIrvp.mjs} +29 -29
- package/dist/core.cjs +1 -1
- package/dist/core.js +12 -12
- package/dist/duo-frame-CHI6g7BR.mjs +758 -0
- package/dist/duo-frame-Cj-xHHW3.js +11 -0
- package/dist/duo-model-BYgtCaCR.mjs +4 -0
- package/dist/duo-model-CDWgmLRF.js +1 -0
- package/dist/duo-model.d.ts +2 -0
- package/dist/{duo-view-ChJLXqxO.mjs → duo-view-Biy9MAlH.mjs} +84 -86
- package/dist/duo-view-D0Ndj2Ee.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.css +1 -1
- package/dist/index.js +32 -25
- package/dist/lite.cjs +1 -1
- package/dist/lite.js +2 -2
- package/dist/macbook-frame-BHQtQNGV.mjs +349 -0
- package/dist/macbook-frame-CQyZhRFn.js +3 -0
- package/dist/macbook-model-BiMxLpmf.mjs +4 -0
- package/dist/macbook-model-BpUdvtlU.js +1 -0
- package/dist/macbook-model.d.ts +2 -0
- package/dist/meshopt_decoder.module-C4Z_evpr.mjs +217 -0
- package/dist/meshopt_decoder.module-DxJdu6ez.js +1 -0
- package/dist/{duo-frame-CRvwXOCX.mjs → model-source-BjSq5Any.mjs} +5353 -6125
- package/dist/model-source-S12HoOoQ.js +4049 -0
- package/dist/remote-control-BGKETUbE.mjs +1746 -0
- package/dist/remote-control-OLgfUSR1.js +1 -0
- package/package.json +1 -1
- package/dist/GLTFLoader-fmKnVrWB.js +0 -1
- package/dist/duo-frame-BIAhHcnD.js +0 -4059
- package/dist/duo-view-BJaUyddX.js +0 -1
- package/dist/remote-control-BDzL0og6.mjs +0 -1299
- package/dist/remote-control-C1N4foYE.js +0 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type DeviceViewMode = '2d' | '3d';
|
|
2
|
+
/** The 2D and 3D choice of a device frame, the iPhone Duo's or the MacBook's. */
|
|
3
|
+
export interface DeviceView {
|
|
4
|
+
/** What the viewer picked. */
|
|
5
|
+
mode: DeviceViewMode;
|
|
6
|
+
/**
|
|
7
|
+
* What is on screen and takes input. 3D shows only once the 3D view says it is ready, so the 2D
|
|
8
|
+
* view stays until then.
|
|
9
|
+
*/
|
|
10
|
+
shown: DeviceViewMode;
|
|
11
|
+
/** The viewer picked 3D and its code and model are still on their way. */
|
|
12
|
+
loading: boolean;
|
|
13
|
+
choose(mode: DeviceViewMode): void;
|
|
14
|
+
/**
|
|
15
|
+
* The 3D view is ready. Each pick of 3D gets its own callback, so one left from an earlier pick,
|
|
16
|
+
* such as a load that finished after the viewer went back to 2D, changes nothing.
|
|
17
|
+
*/
|
|
18
|
+
onReady(): void;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* useDeviceView keeps a device frame's 2D and 3D choice. `onShow3d` runs as the 3D view takes over
|
|
22
|
+
* from the 2D one, before the 2D view stops taking input, so it can let go of what the 2D view holds.
|
|
23
|
+
*/
|
|
24
|
+
export declare function useDeviceView(onShow3d?: () => void): DeviceView;
|
|
25
|
+
/** The 2D and 3D switch above a device frame. The 3D button spins while 3D downloads. */
|
|
26
|
+
export declare function DeviceModeToggle({ view, label }: {
|
|
27
|
+
view: DeviceView;
|
|
28
|
+
label: string;
|
|
29
|
+
}): import("react").JSX.Element;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { default as React } from 'react';
|
|
2
|
+
import { RemoteControlModel } from './remote-control';
|
|
2
3
|
import { DuoButton, DuoState, DuoOrientation } from '../core/duo';
|
|
3
4
|
export interface DuoFrameProps {
|
|
4
5
|
watchOnly?: boolean;
|
|
5
|
-
|
|
6
|
+
/** The prepared Duo appearance to draw over the built-in body. */
|
|
7
|
+
model?: RemoteControlModel;
|
|
6
8
|
outer: HTMLVideoElement | null;
|
|
7
9
|
inner: HTMLVideoElement | null;
|
|
8
10
|
state: DuoState;
|
|
@@ -12,6 +14,8 @@ export interface DuoFrameProps {
|
|
|
12
14
|
touch: (action: number, screenId: number, x: number, y: number) => void;
|
|
13
15
|
onKeyDown: React.KeyboardEventHandler<HTMLDivElement>;
|
|
14
16
|
onKeyUp: React.KeyboardEventHandler<HTMLDivElement>;
|
|
17
|
+
/** The appearance has loaded, or failed to and left the built-in body, or there is none to load. */
|
|
18
|
+
onReady?: () => void;
|
|
15
19
|
}
|
|
16
20
|
/** A procedural titanium frame. Each glass panel carries its own native video texture. */
|
|
17
21
|
export default function DuoFrame(props: DuoFrameProps): React.JSX.Element;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DuoButton } from '../core/duo';
|
|
2
|
+
import { RemoteControlModel } from './remote-control';
|
|
2
3
|
import * as THREE from 'three';
|
|
3
4
|
/** Independent of WebGL so fold geometry and touch occlusion can be tested directly. */
|
|
4
5
|
export declare function createDuoModel(outerTexture: THREE.Texture, innerTexture: THREE.Texture, environment?: THREE.Texture): {
|
|
@@ -12,7 +13,7 @@ export declare function createDuoModel(outerTexture: THREE.Texture, innerTexture
|
|
|
12
13
|
}[];
|
|
13
14
|
getBounds: (bounds: THREE.Box3) => THREE.Box3;
|
|
14
15
|
pick: (ray: THREE.Raycaster) => THREE.Intersection<THREE.Object3D<THREE.Object3DEventMap>>;
|
|
15
|
-
loadAppearance: (
|
|
16
|
+
loadAppearance: (source: RemoteControlModel) => Promise<void>;
|
|
16
17
|
highlightButton: (name?: DuoButton, pressed?: boolean) => void;
|
|
17
18
|
animateButtons: (dt: number) => boolean;
|
|
18
19
|
dispose: () => void;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { default as React } from 'react';
|
|
2
|
+
import { RemoteControlModel } from './remote-control';
|
|
3
|
+
export interface MacbookFrameProps {
|
|
4
|
+
video: HTMLVideoElement | null;
|
|
5
|
+
/** The screen's aspect ratio, which the stream sets. */
|
|
6
|
+
aspect: number;
|
|
7
|
+
watchOnly?: boolean;
|
|
8
|
+
/** A desktop pointer event at a point of the screen, 0 to 1 from its top left. */
|
|
9
|
+
pointer: (action: 'down' | 'move' | 'up', x: number, y: number, buttons: number) => void;
|
|
10
|
+
/** A scroll at a point of the screen, in CSS pixels as WheelEvent reports them. */
|
|
11
|
+
scroll: (x: number, y: number, deltaX: number, deltaY: number) => void;
|
|
12
|
+
onKeyDown: React.KeyboardEventHandler<HTMLDivElement>;
|
|
13
|
+
onKeyUp: React.KeyboardEventHandler<HTMLDivElement>;
|
|
14
|
+
/** The stage lost focus, so every key the guest holds must go up. */
|
|
15
|
+
onBlur: () => void;
|
|
16
|
+
/**
|
|
17
|
+
* A prepared MacBook model to draw instead of the built-in one; scripts/prepare-macbook-model.mjs
|
|
18
|
+
* describes the nodes it must have.
|
|
19
|
+
*/
|
|
20
|
+
model?: RemoteControlModel;
|
|
21
|
+
/** Opens the lid when the MacBook appears, unless the viewer prefers reduced motion. */
|
|
22
|
+
animateLid?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* The MacBook has drawn its first frame, or the reason it cannot is on screen. Until then the
|
|
25
|
+
* stage is unseen, so the host can keep showing what it had.
|
|
26
|
+
*/
|
|
27
|
+
onReady?: () => void;
|
|
28
|
+
}
|
|
29
|
+
/** The MacBook in 3D with the stream on its screen. The screen takes the guest's pointer. */
|
|
30
|
+
export default function MacbookFrame(props: MacbookFrameProps): React.JSX.Element;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MacBook Pro drawn around a macOS guest. Lengths are hundredths of the screen's width, so
|
|
3
|
+
* the model fits any guest display: only the screen's height, and with it the lid's height and
|
|
4
|
+
* the base's depth, follows the stream's aspect ratio.
|
|
5
|
+
*
|
|
6
|
+
* The CSS frame (`.rc-macbook` in remote-control.css), the WebGL lid opening and the three.js
|
|
7
|
+
* 3D mode all draw this one shape. Seen straight on with the lid upright, the 3D model covers
|
|
8
|
+
* exactly the CSS frame, so either hands over to the other without a jump.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MACBOOK: {
|
|
11
|
+
sideBezel: number;
|
|
12
|
+
topBezel: number;
|
|
13
|
+
chin: number;
|
|
14
|
+
baseHeight: number;
|
|
15
|
+
baseOverhang: number;
|
|
16
|
+
screenRadius: number;
|
|
17
|
+
lidThickness: number;
|
|
18
|
+
};
|
|
19
|
+
export declare const MACBOOK_LID_WIDTH: number;
|
|
20
|
+
export declare const MACBOOK_WIDTH: number;
|
|
21
|
+
export declare const MACBOOK_EXTRA_HEIGHT: number;
|
|
22
|
+
export declare const MACBOOK_SCREEN_RAISE: number;
|
|
23
|
+
export type MacbookPart = 'lid' | 'base';
|
|
24
|
+
export type MacbookKind = 'shell' | 'glass' | 'screen' | 'camera' | 'well' | 'keys' | 'trackpad' | 'scoop';
|
|
25
|
+
/** Interleaved position (3), normal (3) and texture coordinate (2) per vertex, in triangles. */
|
|
26
|
+
export type MacbookMesh = {
|
|
27
|
+
part: MacbookPart;
|
|
28
|
+
kind: MacbookKind;
|
|
29
|
+
vertices: Float32Array;
|
|
30
|
+
};
|
|
31
|
+
export declare const MACBOOK_VERTEX_FLOATS = 8;
|
|
32
|
+
/**
|
|
33
|
+
* The model's coordinates: x to the right, y up, z toward the viewer. The hinge is the x axis.
|
|
34
|
+
* Lid parts are given upright, standing on the base with the screen facing +z; turning them by
|
|
35
|
+
* `macbookLidAngle` about the hinge closes the lid. The base's top is y = 0, and it reaches from
|
|
36
|
+
* just behind the lid to the front edge at z = `depth`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function macbookDimensions(aspect: number): {
|
|
39
|
+
screenHeight: number;
|
|
40
|
+
lidHeight: number;
|
|
41
|
+
depth: number;
|
|
42
|
+
};
|
|
43
|
+
export declare const MACBOOK_LID_CLOSED: number;
|
|
44
|
+
export declare const MACBOOK_LID_MAX_DEGREES = 135;
|
|
45
|
+
export declare const MACBOOK_LID_OPEN_DEGREES = 100;
|
|
46
|
+
export declare const MACBOOK_LID_OPENING_MS = 2400;
|
|
47
|
+
/** The lid's turn about the hinge, in radians, for an opening in degrees from closed. */
|
|
48
|
+
export declare function lidRotation(degrees: number): number;
|
|
49
|
+
/** A lid's progress through a move, 0 to 1: it starts fast and slows to a stop, as one pushed does. */
|
|
50
|
+
export declare function lidEase(progress: number): number;
|
|
51
|
+
/**
|
|
52
|
+
* Builds the model for a screen of the given aspect ratio. The screen's texture coordinates put
|
|
53
|
+
* (0, 0) at its bottom left, as WebGL and three.js expect for an upright image.
|
|
54
|
+
*/
|
|
55
|
+
export declare function macbookMeshes(aspect: number): MacbookMesh[];
|
|
56
|
+
/**
|
|
57
|
+
* How a stream fills a display of another shape: the texture transform that keeps its shape,
|
|
58
|
+
* centered, with black bars on the sides it does not reach. Texture coordinates outside 0 to 1
|
|
59
|
+
* after it are the bars. A display with a notch keeps the stream below it, in the band macOS keeps
|
|
60
|
+
* clear of the notch, right under it, so the strip beside the notch can show the stream's menu bar
|
|
61
|
+
* reaching up; `notch` is the share of the display's height the notch takes at its top.
|
|
62
|
+
*/
|
|
63
|
+
export declare function streamFit(videoAspect: number, screenAspect: number, notch?: number): {
|
|
64
|
+
readonly repeat: readonly [number, number];
|
|
65
|
+
readonly offset: readonly [number, number];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* The stream's point, 0 to 1 from its top left, at a point of the display given as texture
|
|
69
|
+
* coordinates from its bottom left; undefined on a black bar.
|
|
70
|
+
*/
|
|
71
|
+
export declare function streamPoint(u: number, v: number, fit: {
|
|
72
|
+
repeat: readonly number[];
|
|
73
|
+
offset: readonly number[];
|
|
74
|
+
}): {
|
|
75
|
+
x: number;
|
|
76
|
+
y: number;
|
|
77
|
+
} | undefined;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { GLTF, GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
|
2
|
+
import { RemoteControlModel } from './remote-control';
|
|
3
|
+
/**
|
|
4
|
+
* Loads a 3D device's model from a URL, or from the function that resolves to one. A bundled model
|
|
5
|
+
* arrives as a data URL, which is decoded here rather than fetched, so a page whose content
|
|
6
|
+
* security policy limits connect-src still loads it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function loadModel(loader: GLTFLoader, source: RemoteControlModel): Promise<GLTF>;
|
|
@@ -24,13 +24,28 @@ export interface RemoteControlProps {
|
|
|
24
24
|
sessionId?: string;
|
|
25
25
|
openUrl?: string;
|
|
26
26
|
showFrame?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Opens a macOS guest's MacBook's lid, with the stream on its screen, each time the 3D MacBook
|
|
29
|
+
* appears. Defaults to true. It never plays for a viewer who prefers reduced motion, and other
|
|
30
|
+
* platforms and the 2D frame ignore it.
|
|
31
|
+
*/
|
|
32
|
+
animateLid?: boolean;
|
|
27
33
|
/**
|
|
28
34
|
* The iOS model behind the stream. iphone-duo enables the official iPhone Duo's native displays and
|
|
29
35
|
* interactive folding frame; iphone-se and iphone-17e pick their own device frames.
|
|
30
36
|
*/
|
|
31
37
|
deviceModel?: RemoteControlDeviceModel;
|
|
32
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* A prepared iPhone Duo GLB for the 3D Duo, in place of the one the default entry bundles.
|
|
40
|
+
* Without either, as with the lite entry, a simpler built-in Duo is drawn.
|
|
41
|
+
*/
|
|
33
42
|
duoModelUrl?: string;
|
|
43
|
+
/**
|
|
44
|
+
* A prepared MacBook GLB for a macOS guest's 3D MacBook, in place of the one the default entry
|
|
45
|
+
* bundles. scripts/prepare-macbook-model.mjs makes one. Without either, as with the lite entry,
|
|
46
|
+
* a simpler built-in MacBook is drawn.
|
|
47
|
+
*/
|
|
48
|
+
macbookModelUrl?: string;
|
|
34
49
|
autoReconnect?: boolean;
|
|
35
50
|
/**
|
|
36
51
|
* Preferred playback jitter buffer duration in milliseconds (0–4000), for
|
|
@@ -237,7 +252,31 @@ export type RemoteControlPlatformAssets = {
|
|
|
237
252
|
frame: string;
|
|
238
253
|
frameLandscape: string;
|
|
239
254
|
}>>;
|
|
255
|
+
/**
|
|
256
|
+
* Where a macOS frame image's screen opening sits, as fractions of the image's width and height
|
|
257
|
+
* from its top left. A macOS `frame` needs it; without both, the MacBook is drawn in CSS. `notch`
|
|
258
|
+
* is the share of the opening's height a notch takes at its top: the stream sits below it, and
|
|
259
|
+
* the strip either side of the notch shows the stream's top row, as if its menu bar reached up.
|
|
260
|
+
*/
|
|
261
|
+
screen?: {
|
|
262
|
+
left: number;
|
|
263
|
+
top: number;
|
|
264
|
+
width: number;
|
|
265
|
+
height: number;
|
|
266
|
+
notch?: number;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* The prepared GLB the platform's 3D device draws: the iPhone Duo for iOS, and the MacBook for
|
|
270
|
+
* macOS, whose nodes scripts/prepare-macbook-model.mjs describes. The default entry's load only
|
|
271
|
+
* when the 3D view appears.
|
|
272
|
+
*/
|
|
273
|
+
model?: RemoteControlModel;
|
|
240
274
|
loadingLogo?: string;
|
|
241
275
|
};
|
|
276
|
+
/**
|
|
277
|
+
* A prepared 3D model, as a URL or a function that resolves to one when the 3D view first needs it.
|
|
278
|
+
* A function keeps a large model out of the page until then; pass the same function each render.
|
|
279
|
+
*/
|
|
280
|
+
export type RemoteControlModel = string | (() => Promise<string>);
|
|
242
281
|
export type RemoteControlAssets = Partial<Record<DevicePlatform, RemoteControlPlatformAssets>>;
|
|
243
282
|
export declare const RemoteControl: React.ForwardRefExoticComponent<RemoteControlProps & React.RefAttributes<RemoteControlHandle>>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
/**
|
|
3
|
+
* A procedural studio for the 3D device frames to reflect. Continuous light-to-dark sweeps give
|
|
4
|
+
* broad metal faces reflections at every viewing angle. The caller disposes the returned target.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createStudioEnvironment(renderer: THREE.WebGLRenderer): THREE.WebGLRenderTarget;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** A point on a macOS guest's screen, in its pixels, with the screen's size. */
|
|
2
|
+
export interface MacScreenPoint {
|
|
3
|
+
x: number;
|
|
4
|
+
y: number;
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
}
|
|
8
|
+
/** Where a touch screen's fingers land on the guest's screen, from client coordinates. */
|
|
9
|
+
export interface MacTouchScreen {
|
|
10
|
+
/** The guest's point under a client point. */
|
|
11
|
+
map(x: number, y: number): MacScreenPoint | undefined;
|
|
12
|
+
/** Whether a client point is on the guest's screen, not on a frame or a letterbox bar. */
|
|
13
|
+
contains(x: number, y: number): boolean;
|
|
14
|
+
/** Guest pixels per CSS pixel, so content follows the fingers. */
|
|
15
|
+
scale: number;
|
|
16
|
+
}
|
|
17
|
+
export type MacTouchType = 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel';
|
|
18
|
+
export declare const MAC_TOUCH_HOLD_MS = 150;
|
|
19
|
+
export declare const MAC_TOUCH_SLOP = 8;
|
|
20
|
+
/**
|
|
21
|
+
* MacPointer is the one sender of a macOS guest's pointer. Every view sends its mouse, touch and
|
|
22
|
+
* scroll input through it, so it knows which button the guest holds and can let go of it when input
|
|
23
|
+
* moves to another view, the stream goes away, or input is blocked.
|
|
24
|
+
*
|
|
25
|
+
* A touch screen has no hover and no wheel. One finger presses the left button and drags with it
|
|
26
|
+
* held, and lets go where it lifts; limacvm rests the pointer at a new spot before a press, as macOS
|
|
27
|
+
* needs. The press waits until the finger moves, holds still a moment, or lifts as a tap, so a second
|
|
28
|
+
* finger landing just after it scrolls without a click. Two fingers scroll, content following them
|
|
29
|
+
* as on a trackpad. A gesture that becomes a scroll lets its press go first, and stays a scroll until
|
|
30
|
+
* every finger lifts. A cancelled touch, which the system took for its own gesture, is no tap.
|
|
31
|
+
*/
|
|
32
|
+
export declare class MacPointer {
|
|
33
|
+
private send;
|
|
34
|
+
/** Input is blocked, as in inspect's select mode. A release of a button the guest holds still goes out. */
|
|
35
|
+
private blocked;
|
|
36
|
+
private last;
|
|
37
|
+
private gesture;
|
|
38
|
+
private screen;
|
|
39
|
+
constructor(send: (data: ArrayBuffer) => void,
|
|
40
|
+
/** Input is blocked, as in inspect's select mode. A release of a button the guest holds still goes out. */
|
|
41
|
+
blocked?: () => boolean);
|
|
42
|
+
pointer(action: number, point: MacScreenPoint, buttons: number): void;
|
|
43
|
+
scroll(point: MacScreenPoint, deltaX: number, deltaY: number): void;
|
|
44
|
+
/**
|
|
45
|
+
* A touch event, its fingers in client coordinates. Returns true when a finger lands on the screen
|
|
46
|
+
* and starts a gesture, so the caller can give the screen the keyboard.
|
|
47
|
+
*/
|
|
48
|
+
touch(type: MacTouchType, touches: {
|
|
49
|
+
x: number;
|
|
50
|
+
y: number;
|
|
51
|
+
}[], screen: MacTouchScreen): boolean;
|
|
52
|
+
/** Drops a pending touch and lets go of any button the guest holds, where it was pressed. */
|
|
53
|
+
release(): void;
|
|
54
|
+
private press;
|
|
55
|
+
private lift;
|
|
56
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";const Z={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11,INJECT_MOUSE_EVENT:40,INJECT_MAC_KEY:41,INJECT_MAC_SCROLL:42},Re={DOWN:0,UP:1,MOVE:2},Ue={ACTION_DOWN:0,ACTION_UP:1,ACTION_MOVE:2,ACTION_CANCEL:3,ACTION_POINTER_DOWN:5,ACTION_POINTER_UP:6,BUTTON_PRIMARY:1,BUTTON_SECONDARY:2,BUTTON_TERTIARY:4},o={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},wt={KeyA:o.KEYCODE_A,KeyB:o.KEYCODE_B,KeyC:o.KEYCODE_C,KeyD:o.KEYCODE_D,KeyE:o.KEYCODE_E,KeyF:o.KEYCODE_F,KeyG:o.KEYCODE_G,KeyH:o.KEYCODE_H,KeyI:o.KEYCODE_I,KeyJ:o.KEYCODE_J,KeyK:o.KEYCODE_K,KeyL:o.KEYCODE_L,KeyM:o.KEYCODE_M,KeyN:o.KEYCODE_N,KeyO:o.KEYCODE_O,KeyP:o.KEYCODE_P,KeyQ:o.KEYCODE_Q,KeyR:o.KEYCODE_R,KeyS:o.KEYCODE_S,KeyT:o.KEYCODE_T,KeyU:o.KEYCODE_U,KeyV:o.KEYCODE_V,KeyW:o.KEYCODE_W,KeyX:o.KEYCODE_X,KeyY:o.KEYCODE_Y,KeyZ:o.KEYCODE_Z,Digit0:o.KEYCODE_0,Digit1:o.KEYCODE_1,Digit2:o.KEYCODE_2,Digit3:o.KEYCODE_3,Digit4:o.KEYCODE_4,Digit5:o.KEYCODE_5,Digit6:o.KEYCODE_6,Digit7:o.KEYCODE_7,Digit8:o.KEYCODE_8,Digit9:o.KEYCODE_9,Backquote:o.KEYCODE_GRAVE,Minus:o.KEYCODE_MINUS,Equal:o.KEYCODE_EQUALS,BracketLeft:o.KEYCODE_LEFT_BRACKET,BracketRight:o.KEYCODE_RIGHT_BRACKET,Backslash:o.KEYCODE_BACKSLASH,Semicolon:o.KEYCODE_SEMICOLON,Quote:o.KEYCODE_APOSTROPHE,Comma:o.KEYCODE_COMMA,Period:o.KEYCODE_PERIOD,Slash:o.KEYCODE_SLASH,Space:o.KEYCODE_SPACE,Tab:o.KEYCODE_TAB,Escape:o.KEYCODE_ESCAPE,ArrowUp:o.DPAD_UP,ArrowDown:o.DPAD_DOWN,ArrowLeft:o.DPAD_LEFT,ArrowRight:o.DPAD_RIGHT,Enter:o.ENTER,Backspace:o.DEL,Delete:o.FORWARD_DEL,Home:o.KEYCODE_MOVE_HOME,End:o.KEYCODE_MOVE_END,PageUp:o.KEYCODE_PAGE_UP,PageDown:o.KEYCODE_PAGE_DOWN,Insert:o.KEYCODE_INSERT,F1:o.KEYCODE_F1,F2:o.KEYCODE_F2,F3:o.KEYCODE_F3,F4:o.KEYCODE_F4,F5:o.KEYCODE_F5,F6:o.KEYCODE_F6,F7:o.KEYCODE_F7,F8:o.KEYCODE_F8,F9:o.KEYCODE_F9,F10:o.KEYCODE_F10,F11:o.KEYCODE_F11,F12:o.KEYCODE_F12,ShiftLeft:o.KEYCODE_SHIFT_LEFT,ShiftRight:o.KEYCODE_SHIFT_RIGHT,ControlLeft:o.KEYCODE_CTRL_LEFT,ControlRight:o.KEYCODE_CTRL_RIGHT,AltLeft:o.KEYCODE_ALT_LEFT,AltRight:o.KEYCODE_ALT_RIGHT,MetaLeft:o.KEYCODE_META_LEFT,MetaRight:o.KEYCODE_META_RIGHT,ContextMenu:o.MENU,Numpad0:o.KEYCODE_NUMPAD_0,Numpad1:o.KEYCODE_NUMPAD_1,Numpad2:o.KEYCODE_NUMPAD_2,Numpad3:o.KEYCODE_NUMPAD_3,Numpad4:o.KEYCODE_NUMPAD_4,Numpad5:o.KEYCODE_NUMPAD_5,Numpad6:o.KEYCODE_NUMPAD_6,Numpad7:o.KEYCODE_NUMPAD_7,Numpad8:o.KEYCODE_NUMPAD_8,Numpad9:o.KEYCODE_NUMPAD_9,NumpadDivide:o.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:o.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:o.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:o.KEYCODE_NUMPAD_ADD,NumpadDecimal:o.KEYCODE_NUMPAD_DOT,NumpadComma:o.KEYCODE_NUMPAD_COMMA,NumpadEnter:o.KEYCODE_NUMPAD_ENTER,NumpadEqual:o.KEYCODE_NUMPAD_EQUALS},or={KeyA:0,KeyS:1,KeyD:2,KeyF:3,KeyH:4,KeyG:5,KeyZ:6,KeyX:7,KeyC:8,KeyV:9,IntlBackslash:10,KeyB:11,KeyQ:12,KeyW:13,KeyE:14,KeyR:15,KeyY:16,KeyT:17,Digit1:18,Digit2:19,Digit3:20,Digit4:21,Digit6:22,Digit5:23,Equal:24,Digit9:25,Digit7:26,Minus:27,Digit8:28,Digit0:29,BracketRight:30,KeyO:31,KeyU:32,BracketLeft:33,KeyI:34,KeyP:35,Enter:36,KeyL:37,KeyJ:38,Quote:39,KeyK:40,Semicolon:41,Backslash:42,Comma:43,Slash:44,KeyN:45,KeyM:46,Period:47,Tab:48,Space:49,Backquote:50,Backspace:51,Escape:53,MetaRight:54,MetaLeft:55,ShiftLeft:56,CapsLock:57,AltLeft:58,ControlLeft:59,ShiftRight:60,AltRight:61,ControlRight:62,Fn:63,F17:64,NumpadDecimal:65,NumpadMultiply:67,NumpadAdd:69,NumLock:71,NumpadDivide:75,NumpadEnter:76,NumpadSubtract:78,F18:79,F19:80,NumpadEqual:81,Numpad0:82,Numpad1:83,Numpad2:84,Numpad3:85,Numpad4:86,Numpad5:87,Numpad6:88,Numpad7:89,F20:90,Numpad8:91,Numpad9:92,F5:96,F6:97,F7:98,F3:99,F8:100,F9:101,F11:103,F13:105,F16:106,F14:107,F10:109,ContextMenu:110,F12:111,F15:113,Help:114,Insert:114,Home:115,PageUp:116,Delete:117,F4:118,End:119,F2:120,PageDown:121,F1:122,ArrowLeft:123,ArrowRight:124,ArrowDown:125,ArrowUp:126};function ct(t){return or[t]}function Nt(t,e,r,a,u,l,i=1,E=0,O=0){const m=new ArrayBuffer(32),S=new DataView(m);let w=0;S.setUint8(w,Z.INJECT_TOUCH_EVENT),w+=1;const N=t===Ue.ACTION_POINTER_DOWN?Ue.ACTION_DOWN:t===Ue.ACTION_POINTER_UP?Ue.ACTION_UP:t;return S.setUint8(w,N),w+=1,S.setBigInt64(w,BigInt(e),!0),w+=8,S.setInt32(w,Math.round(u),!0),w+=4,S.setInt32(w,Math.round(l),!0),w+=4,S.setUint16(w,r,!0),w+=2,S.setUint16(w,a,!0),w+=2,S.setInt16(w,Math.round(i*65535),!0),w+=2,S.setInt32(w,E,!0),w+=4,S.setInt32(w,O,!0),m}function ar(t,e,r,a,u,l,i){const E=new ArrayBuffer(24),O=new DataView(E);let m=0;return O.setUint8(m,Z.INJECT_TWO_FINGER_TOUCH_EVENT),m+=1,O.setUint8(m,t),m+=1,O.setInt32(m,Math.round(a),!0),m+=4,O.setInt32(m,Math.round(u),!0),m+=4,O.setInt32(m,Math.round(l),!0),m+=4,O.setInt32(m,Math.round(i),!0),m+=4,O.setUint16(m,e,!0),m+=2,O.setUint16(m,r,!0),m+=2,O.setUint16(m,0,!0),E}function bt(t,e=!0){const a=new TextEncoder().encode(t),u=new ArrayBuffer(14+a.length),l=new DataView(u);let i=0;return l.setUint8(i,Z.SET_CLIPBOARD),i+=1,l.setBigInt64(i,BigInt(0),!1),i+=8,l.setUint8(i,e?1:0),i+=1,l.setUint32(i,a.length,!1),i+=4,new Uint8Array(u,i).set(a),u}function Xe(t,e,r=0,a=0){const u=new ArrayBuffer(14),l=new DataView(u);let i=0;return l.setUint8(i,Z.INJECT_KEYCODE),i+=1,l.setUint8(i,t),i+=1,l.setInt32(i,e,!0),i+=4,l.setInt32(i,r,!0),i+=4,l.setInt32(i,a,!0),u}function sr(t,e,r,a,u,l){const i=new ArrayBuffer(18),E=new DataView(i);return E.setUint8(0,Z.INJECT_MOUSE_EVENT),E.setUint8(1,t),E.setInt32(2,Math.round(a),!0),E.setInt32(6,Math.round(u),!0),E.setUint16(10,e,!0),E.setUint16(12,r,!0),E.setInt32(14,l,!0),i}function Yt(t,e){const r=new ArrayBuffer(4),a=new DataView(r);return a.setUint8(0,Z.INJECT_MAC_KEY),a.setUint8(1,t),a.setUint16(2,e,!0),r}function cr(t,e,r,a,u,l){const i=new ArrayBuffer(21),E=new DataView(i);return E.setUint8(0,Z.INJECT_MAC_SCROLL),E.setInt32(1,Math.round(r),!0),E.setInt32(5,Math.round(a),!0),E.setUint16(9,t,!0),E.setUint16(11,e,!0),E.setFloat32(13,u,!0),E.setFloat32(17,l,!0),i}function lr(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function It(t){return t===2?2:t===3?1:t===4?3:0}class dr{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,r=It(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==r)&&this.release(),this.screenId=e?.screenId,this.turns=r}touch(e,r,a,u=!1){if(this.screenId===void 0)return;const l=Rt(r,a,u?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...l}),this.held&&(Object.assign(this.held,l),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,l.x,l.y))}release(){if(!this.held)return;const{screenId:e,x:r,y:a}=this.held;this.held=void 0,this.send(1,e,r,a)}}const ur={width:164.6,height:117.8,depth:5.2};function Rt(t,e,r){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),r===1?{x:e,y:1-t}:r===2?{x:1-t,y:1-e}:r===3?{x:1-e,y:t}:{x:t,y:e}}function fr(t){return Number.isFinite(t)&&t>=0&&t<=180}function Er(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function hr(t,e,r){return e&&(t||!r)?"touch":t?"ignore":"orbit"}function Ut(t,e,r,a){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(r)||!Number.isFinite(a)||r<0||r>1||a<0||a>1)throw new RangeError("Invalid display touch coordinates");const u=new ArrayBuffer(12),l=new DataView(u);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,r,!0),l.setFloat32(8,a,!0),u}class mr{constructor(e,r){this.send=e,this.failed=r}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!fr(e)||(this.latest=e,this.flush())}stop(){this.stopped=!0,this.latest=void 0}async flush(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.latest!==void 0&&!this.stopped;){const e=this.latest;this.latest=void 0,await this.send(e)}}catch(e){this.latest=void 0,this.stopped||this.failed(e)}finally{this.running=!1}}}}const pr={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class Cr{constructor(e,r){this.send=e,this.failed=r}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,r){this.tail=this.tail.then(()=>this.send(e,r)).catch(this.failed)}}const Qe="Accessibility unavailable on this device.",ze=500,kt=(t,e)=>Math.abs(t.x-e.x)<.5&&Math.abs(t.y-e.y)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5,Or=t=>Math.max(0,t.width)*Math.max(0,t.height),Dr=t=>{const e=t.find(r=>r.frame&&r.frame.width>0&&r.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},_r=t=>{const e={};return typeof t.AXUniqueId=="string"&&t.AXUniqueId.length>0&&(e.AXUniqueId=t.AXUniqueId),typeof t.AXLabel=="string"&&t.AXLabel.length>0&&(e.AXLabel=t.AXLabel),typeof t.type=="string"&&t.type.length>0&&(e.className=t.type),e},gr=t=>{const e={};for(const[r,a]of Object.entries(t))r!=="children"&&(e[r]=a);return e};function Pt(t){const e=Array.isArray(t)?t:[t],r=Dr(e),a=[],u=(l,i)=>{if(a.length>=ze)return;const E=l.frame;if(E&&E.width>0&&E.height>0&&!kt(E,r)){const m=l.role_description||l.role||"",S=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";a.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:i,path:i,label:S,value:typeof l.AXValue=="string"?l.AXValue:"",role:m,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:E.x,y:E.y,width:E.width,height:E.height},selectors:_r(l),raw:gr(l)})}const O=Array.isArray(l.children)?l.children:[];for(let m=0;m<O.length&&a.length<ze;m++)u(O[m],`${i}.${m}`)};for(let l=0;l<e.length&&a.length<ze;l++)u(e[l],String(l));return{platform:"ios",screen:{width:r.width,height:r.height},elements:a,capturedAt:Date.now()}}const Tr=t=>{let e={x:0,y:0,width:1,height:1},r=0;for(const a of t){const u=a.parsedBounds;if(!u)continue;const l=u.right-u.left,i=u.bottom-u.top,E=Math.max(0,l)*Math.max(0,i);E>r&&(r=E,e={x:0,y:0,width:l,height:i})}return e},yr=t=>{const e={};return typeof t.resourceId=="string"&&t.resourceId.length>0&&(e.resourceId=t.resourceId),typeof t.contentDesc=="string"&&t.contentDesc.length>0&&(e.contentDesc=t.contentDesc),typeof t.text=="string"&&t.text.length>0&&(e.text=t.text),typeof t.className=="string"&&t.className.length>0&&(e.className=t.className),e};function Lt(t){const e=Tr(t),r=[];for(let a=0;a<t.length&&r.length<ze;a++){const u=t[a],l=u.parsedBounds;if(!l)continue;const i=Math.max(0,l.right-l.left),E=Math.max(0,l.bottom-l.top);if(i<=0||E<=0)continue;const O={x:l.left,y:l.top,width:i,height:E};if(kt(O,{x:0,y:0,width:e.width,height:e.height}))continue;const m=u.contentDesc||u.text||"",S=u.className||"";r.push({id:u.resourceId&&u.resourceId.length>0?u.resourceId:u.contentDesc&&u.contentDesc.length>0?`cd:${u.contentDesc}`:String(a),path:String(a),label:m,value:typeof u.text=="string"?u.text:"",role:S,type:S,enabled:u.enabled!==!1,focused:u.focused===!0,frame:O,selectors:yr(u),raw:{...u}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:r,capturedAt:Date.now()}}function Sr(t,e){const r=Math.max(0,t.x),a=Math.max(0,t.y),u=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),i=Math.max(0,u-r),E=Math.max(0,l-a);return i>0&&E>0?{x:r,y:a,width:i,height:E}:null}function Ft(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const r=t.frame,a=e.frame;return r.x===a.x&&r.y===a.y&&r.width===a.width&&r.height===a.height}function Bt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let r=0;r<t.elements.length;r++)if(!Ft(t.elements[r],e.elements[r]))return!1;return!0}function Kr(t,e,r){let a=null,u=1/0;for(const l of t.elements){const i=l.frame;if(e<i.x||r<i.y||e>i.x+i.width||r>i.y+i.height)continue;const E=Or(i);E<u&&(u=E,a=l)}return a}function Ar(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const r=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${r} })`}return null}return t.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })`:t.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })`:t.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })`:null}function xt(t){const e=t.role||t.type||"";if(!e)return"element";let r=e.replace(/^AX/,"");return r.includes(".")&&(r=r.split(".").pop()),r==="GenericElement"?"Element":(r=r.replace(/([a-z])([A-Z])/g,"$1 $2"),r)}const yt=80;function Mr(t){const e=xt(t),r=t.label||t.value||"";if(!r)return e;const a=r.length>yt?r.slice(0,yt).trimEnd()+"…":r;return`${e} · ${a}`}const vr=500,wr=2e3,St=5e3,Nr=8e3,br=1200,Yr=250,Ir=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class Rr{platform;send;onSnapshot;onStatusChange;baseIntervalMs;maxBackoffMs;androidElementTreeOptions;pending=new Map;running=!1;timer;currentInterval;lastSnapshot=null;inflight=!1;lastBumpAtMs=0;boostUntilMs=0;status="idle";constructor(e){this.platform=e.platform,this.send=e.send,this.onSnapshot=e.onSnapshot,this.onStatusChange=e.onStatusChange,this.baseIntervalMs=e.baseIntervalMs??vr,this.maxBackoffMs=e.maxBackoffMs??wr,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.failAllPending("Inspector stopped"),this.lastSnapshot=null,this.setStatus("idle"),this.onSnapshot(null))}getStatus(){return this.status}setStatus(e,r){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,r)}catch(a){console.error("[AxFetcher] onStatusChange threw:",a)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+br;const r=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<r){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const r=e.id;if(!this.pending.get(r))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const E=typeof e.error=="string"?e.error:null;if(E)return this.settleReject(r,new Error(E)),!0;const O=typeof e.json=="string"?e.json:"";try{const m=JSON.parse(O),S=Pt(m);this.settleResolve(r,S)}catch(m){this.settleReject(r,m instanceof Error?m:new Error(String(m)))}return!0}if(e.type!=="getElementTreeResult")return!1;const u=e.error;if(u&&typeof u=="object"){const E=typeof u.message=="string"?u.message:"getElementTree failed";return this.settleReject(r,new Error(E)),!0}const l=e.payload,i=Array.isArray(l?.nodes)?l.nodes:[];try{const E=Lt(i);this.settleResolve(r,E)}catch(E){this.settleReject(r,E instanceof Error?E:new Error(String(E)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=Ir();return new Promise((r,a)=>{const u=window.setTimeout(()=>{this.pending.delete(e),a(new Error("elementTree request timed out"))},Nr+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:r,reject:a,timer:u}),this.send(this.buildRequest(e))||(window.clearTimeout(u),this.pending.delete(e),a(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const r=e instanceof Error?e.message:String(e),a=/unavailable|not (yet )?running|failed|timeout/i.test(r);this.currentInterval=a?St:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(a?"unavailable":"error",r)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const r=this.lastSnapshot;if(Bt(r,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(Qe)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(Qe)?(this.currentInterval=St,this.setStatus("unavailable",Qe)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(Yr,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,r){const a=this.pending.get(e);a&&(window.clearTimeout(a.timer),this.pending.delete(e),a.resolve(r))}settleReject(e,r){const a=this.pending.get(e);a&&(window.clearTimeout(a.timer),this.pending.delete(e),a.reject(r))}failAllPending(e){for(const[r,a]of this.pending.entries())window.clearTimeout(a.timer),a.reject(new Error(e)),this.pending.delete(r)}}function Kt(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const r=e??null;try{t.jitterBufferTarget!==r&&(t.jitterBufferTarget=r)}catch(a){console.warn("RemoteControl: could not set the jitter buffer target.",a)}}const Wt=`(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
|
|
2
|
-
`,At=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Wt],{type:"text/javascript;charset=utf-8"});function Ur(t){let e;try{if(e=At&&(self.URL||self.webkitURL).createObjectURL(At),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Wt),{name:t?.name})}}function kr(t,e,r){const{MediaStreamTrackProcessor:a,MediaStreamTrackGenerator:u}=globalThis,l=e.getVideoTracks()[0];let i,E,O,m,S=!1;const w=()=>{S||(S=!0,i?.stop(),E?.stop(),O&&(O.postMessage({type:"stop"}),m=setTimeout(()=>O?.terminate(),1e3)))},N=D=>{t.srcObject=D,t.play().catch(()=>{})},q=D=>{S||(w(),r(D),N(e))};try{if(l&&a&&u){i=l.clone();const D=new a({track:i,maxBufferSize:1}),H=new u({kind:"video"});E=H,O=new Ur,O.onmessage=({data:L})=>{L.type==="error"?q(new Error(L.message)):L.type==="stopped"&&(clearTimeout(m),O?.terminate())},O.onerror=L=>q(new Error(L.message)),O.postMessage({type:"start",readable:D.readable,writable:H.writable},[D.readable,H.writable]),N(new MediaStream(e.getTracks().map(L=>L===l?H:L)))}else N(e)}catch(D){q(D)}return w}function ke(t){return typeof t=="number"&&Number.isFinite(t)}function Te(t,e){if(!(!ke(t)||!ke(e)||t<e||e<0))return t-e}class Pr{previous=new Map;reset(){this.previous.clear()}read(e,r,a){const u={timestamp:0,video:[],audio:[]};a==null?u.requestedTargetMs=null:ke(a)&&a>=0&&a<=4e3&&(u.requestedTargetMs=a);const l=new Map;return e.forEach(i=>{if(i.type!=="inbound-rtp"||!ke(i.timestamp))return;const E=i.kind??i.mediaType;if(E!=="video"&&E!=="audio")return;const O=r.filter(P=>P.kind===E),m=i.trackIdentifier?O.find(P=>P.trackId===i.trackIdentifier):i.mid!=null?O.find(P=>P.mid===i.mid):O.length===1?O[0]:void 0;if(!m)return;const S=this.previous.get(i.id),N=S?.trackId===m.trackId&&S.stats.ssrc===i.ssrc?S.stats:void 0,q=N?i.timestamp-N.timestamp:void 0,D={id:i.id,trackId:m.trackId,timestamp:i.timestamp};if(q!==void 0&&q>0){D.intervalMs=q;const P=Te(i.jitterBufferEmittedCount,N?.jitterBufferEmittedCount),B=Te(i.jitterBufferDelay,N?.jitterBufferDelay);P!==void 0&&P>0&&B!==void 0&&(D.bufferDelayMs=B/P*1e3);const V=Te(i.bytesReceived,N?.bytesReceived);V!==void 0&&(D.bitrateBps=V*8e3/q)}if(E==="video"){const P={...D,display:m.display??"primary"};if(D.intervalMs!==void 0){const B=Te(i.framesDecoded,N?.framesDecoded);B!==void 0&&(P.fps=B*1e3/D.intervalMs),P.droppedFrames=Te(i.framesDropped,N?.framesDropped),P.freezes=Te(i.freezeCount,N?.freezeCount)}u.video.push(P)}else u.audio.push(D);u.timestamp=Math.max(u.timestamp,i.timestamp),l.set(i.id,N&&i.timestamp<=N.timestamp?S:{stats:i,trackId:m.trackId});const H=i.transportId?e.get(i.transportId):void 0,L=H?.selectedCandidatePairId?e.get(H.selectedCandidatePairId):void 0;L?.state==="succeeded"&&ke(L.currentRoundTripTime)&&L.currentRoundTripTime>=0&&(u.rttMs=L.currentRoundTripTime*1e3)}),this.previous=l,u.video.length||u.audio.length?u:null}}const at=new WeakSet;function Lr(t,e,r){const{peer:a,displays:u}=t,l=new Pr;let i,E=!1,O=!1,m=!1,S=0,w=!1,N=!1;const q=()=>!E&&!document.hidden&&a.connectionState==="connected",D=B=>{if(!(!B&&!w)){w=B!==null;try{e()?.(B)}catch(V){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',V)}}},H=()=>{O=!1,S++,clearTimeout(i),l.reset(),D(null)},L=async()=>{if(m||!q())return;if(at.has(a)){i=setTimeout(()=>{L()},2e3);return}m=!0,at.add(a);const B=S;try{const V=await a.getStats();if(B!==S||!q())return;const ce=a.getTransceivers().filter(Y=>(Y.currentDirection==="recvonly"||Y.currentDirection==="sendrecv")&&Y.receiver.track.readyState!=="ended").map(Y=>({trackId:Y.receiver.track.id,kind:Y.receiver.track.kind,mid:Y.mid,display:u.get(Y.receiver)}));D(l.read(V,ce,r())),N=!1}catch(V){if(B!==S||!q())return;N||console.warn("[RemoteControl] could not read playback stats:",V),N=!0,l.reset(),D(null)}finally{m=!1,at.delete(a),O&&q()&&(i=setTimeout(()=>{L()},B===S?2e3:0))}},P=()=>{if(!q()){H();return}O||(O=!0,L())};return document.addEventListener("visibilitychange",P),a.addEventListener("connectionstatechange",P),P(),()=>{E=!0,document.removeEventListener("visibilitychange",P),a.removeEventListener("connectionstatechange",P),H()}}function Fr(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let a=!1,u=!1,l=0;return r.onmessage=i=>{if(u)return;let E;try{E=JSON.parse(i.data)}catch(O){console.warn("Invalid latency trace message",O);return}E&&typeof E=="object"&&!Array.isArray(E)&&e(E)},r.onclose=()=>{u=!0,a=!1},{accept(i){a=!u&&i===1},wrap(i){if(!a||i.byteLength===0)return i;const E=new DataView(i),O=E.getUint8(0),m=O===Z.INJECT_MOUSE_EVENT||O===Z.INJECT_MAC_KEY||O===Z.INJECT_MAC_SCROLL,S=i.byteLength===32&&O===Z.INJECT_TOUCH_EVENT&&E.getUint8(1)<=2;if(!m&&!S)return i;const w=new ArrayBuffer(6+i.byteLength),N=new DataView(w);return N.setUint8(0,240),N.setUint8(1,1),N.setUint32(2,++l,!0),new Uint8Array(w,6).set(new Uint8Array(i)),w},close(){u=!0,a=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Br{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const a={generation:e,isCurrent:()=>e===this.generation},u=this.tail.then(()=>r(a));return this.tail=u.catch(()=>{}),u}invalidate(){++this.generation}}function xr(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function Wr(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function qr(t,e){return!t||t.facingMode!==e.facingMode}function Vr(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function $r(t){return{type:"cameraResult",granted:!0,camera:Vr(t)}}const se=(...t)=>{window.debugRemoteControl&&console.log(...t)},y=(...t)=>{window.debugRemoteControl&&console.warn(...t)},F=(t,e,...r)=>{if(e)try{e(...r)}catch(a){console.error(`[RemoteControl] customer callback "${t}" threw:`,a)}},qt=t=>t.includes("/android_")?"android":t.includes("/macos_")?"macos":"ios",Mt=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},st=3,Hr=1e3,Jr=15e3,Gr=3e3,jr=4e3;function vt(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Xr(t){let e={...t};const{url:r,deviceModel:a}=e;let u=e.token;const l=e.watchOnly??!1,i=e.sessionId??vt(),E=e.platform??qt(r??"");let O={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const m=n=>{O={...O,...n},F("onStateChange",e.onStateChange,O)},S=n=>m({videoReady:n}),w=n=>m({duoState:n}),N=n=>m({duoError:n}),q=n=>m({duo:n}),D=n=>se(n);let H=null,L;const P=()=>{L?.(),L=H&&e.onPlaybackStats?Lr(H,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},B=new Map,V=new Set,ce=new Set,Y=new Map;let ye=!1;const Pe=new Map,lt=(n,f,c)=>{f.stop?.(),f.stop=kr(n,c,d=>y("Video playback fallback:",d))},Vt=()=>{Pe.clear();for(const[n,f]of B)f.clear?.(),f.stop?.(),f.stop=void 0,n.srcObject=null};let Ee=!1,Se=!1,Le=0,g=null,I=null,x=null,Fe=null,he,Ke,Ae,Be,me,de=0,xe=0,re=!1,ue=null,Q=null,fe;const Ze=new Br;let Me=null,We=null,et=!l&&(e.microphoneEnabled??!1),tt=!1,ve=null,te=null,qe=0,dt=Promise.resolve(),pe=null,we=!1,ne=new Map,ee=new Map,le=new Map,ie=new Map,$=null,Ne=null,ut=0;const Ve=n=>{if(n===null&&Ne===null)return;Ne=n;const f=++ut;queueMicrotask(()=>{f===ut&&F("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let Ce=null,Oe=new Map;const $t=(n,f)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const K=g;if(!K||K.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const p=vt(),C=setTimeout(()=>{Oe.delete(p),d(new Error("Device control timed out"))},5e3);Oe.set(p,{resolve:c,reject:d,timer:C}),K.send(JSON.stringify({type:n,id:p,...f}))}),De=n=>{Ce!==n&&(Ce=n,m({connection:n}),F("onConnectionStateChange",e.onConnectionStateChange,n))},oe=n=>{l||!x||x.readyState!=="open"||(x.send(Fe?.wrap(n)??n),$?.bumpActivity())},Ht=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:i}))},ft=()=>{he&&window.clearInterval(he),he=window.setInterval(Ht,1e4)},be=()=>{he&&(window.clearInterval(he),he=void 0)},$e=()=>{Ke&&(window.clearTimeout(Ke),Ke=void 0)},He=()=>{Ae&&(window.clearTimeout(Ae),Ae=void 0)},Ye=()=>{Be&&(window.clearInterval(Be),Be=void 0)},Ie=()=>{me!==void 0&&(window.clearTimeout(me),me=void 0)},Jt=()=>{we||(we=!0,Ye(),S(!0),De("connected"))},J=n=>{for(const f of n.getTracks())try{f.stop()}catch(c){y("track.stop() failed:",c)}},Gt=()=>{const n=Q;n&&(Q=null,J(n))},Et=n=>{const f=dt.then(n).catch(c=>{y("microphone operation failed:",c)});return dt=f,f},rt=()=>et||tt,ht=n=>{const f=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;pe=f,n.send(JSON.stringify({type:"microphoneStart",id:f}))},nt=()=>Et(()=>jt()),jt=async()=>{const n=qe,f=()=>n===qe&&rt(),c=h=>{F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:h})};if(!f())return;const d=g,K=ve;if(!d||d.readyState!==WebSocket.OPEN||!K||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),c("Microphone capture requires a secure context (https)");return}let p=null;try{p=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(h){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",h)}if(!f()){p&&J(p);return}if(!p){c("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){J(p),c("Captured stream has no audio track");return}try{await K.replaceTrack(C)}catch(h){y("replaceTrack(audioTrack) failed:",h),J(p),c("Failed to attach the microphone track to the connection");return}if(!f()){try{await K.replaceTrack(null)}catch(h){y("replaceTrack(null) on stale mic attach failed:",h)}J(p);return}te=p,C.onended=()=>{te===p&&Je("microphone capture ended by the browser")},ht(d),F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},Je=n=>(++qe,pe=null,Et(async()=>{const f=ve,c=te;if(te=null,f&&c)try{await f.replaceTrack(null)}catch(K){y("replaceTrack(null) on mic detach failed:",K)}c&&J(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const K=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:K}))}(c||n)&&F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),mt=(n,f)=>{let c;try{c=$r(f),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){y("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:f.label||void 0}}}n.send(JSON.stringify(c)),F("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},Xt=n=>{if(!n)return;const f=n.indexOf("/"),d=(f>=0?n.slice(f+1):n).toUpperCase();return d==="HEVC"?"H265":d},Qt=async()=>{const n=ue,f=e.onCameraStats;if(!n||!f)return;let c;try{c=await n.getStats()}catch{return}let d,K,p;if(c.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?d=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(p=U)}),d?.codecId){const U=c.get(d.codecId);U&&(K=U.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),h=We;let R,b,G;if(h&&C>h.timestamp){const U=(C-h.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof h.framesEncoded=="number"&&(R=Math.max(0,(d.framesEncoded-h.framesEncoded)/U)),typeof d.bytesSent=="number"&&typeof h.bytesSent=="number"&&(b=Math.max(0,(d.bytesSent-h.bytesSent)*8/U)),typeof d.packetsSent=="number"&&typeof h.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof h.packetsLost=="number"){const A=d.packetsSent-h.packetsSent,je=p.packetsLost-h.packetsLost;A>0&&(G=Math.max(0,Math.min(100,je/A*100)))}}We={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:p?.packetsLost};const v={codec:Xt(K),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:R,framesEncoded:d.framesEncoded,bitrateBps:b,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof p?.roundTripTime=="number"?p.roundTripTime*1e3:void 0,packetsLostPct:G};F("onCameraStats",e.onCameraStats,v)},pt=()=>{Me===null&&(We=null,Me=setInterval(()=>{Qt()},1e3))},Ge=()=>{Me!==null&&(clearInterval(Me),Me=null),We=null,F("onCameraStats",e.onCameraStats,null)},zt=(n,f,c,d)=>Ze.enqueue(async({isCurrent:K})=>{const p=()=>K()&&d()&&g===f&&ue===c;if(!p())return;if(!n.active){const v=Q;try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) on camera detach failed:",U)}if(Q===v&&(Q=null,fe=void 0,v&&J(v)),Ge(),!p())return;F("onCameraDemandChange",e.onCameraDemandChange,!1);return}F("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,h=C?.getVideoTracks()[0],R=fe;if(h?.readyState==="live"&&R&&!qr(R,n)){fe=n,mt(f,h),pt();return}if(C){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) before camera switch failed:",v)}if(Q===C&&(Q=null,fe=void 0,J(C)),Ge(),!p())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let b=null;try{b=await navigator.mediaDevices.getUserMedia({video:Wr(n),audio:!1})}catch(v){console.warn("[RemoteControl] getUserMedia denied/failed:",v)}if(!p()){b&&J(b);return}if(!b){f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const G=b.getVideoTracks()[0]??null;if(!G){if(J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{G.contentHint="motion"}catch{}try{await c.replaceTrack(G)}catch(v){if(y("replaceTrack(videoTrack) failed:",v),J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera attach failed:",v)}J(b);return}try{const v=c.getParameters();(!v.encodings||v.encodings.length===0)&&(v.encodings=[{}]),v.encodings[0].maxBitrate=8e6,v.encodings[0].maxFramerate=30,v.degradationPreference="maintain-framerate",await c.setParameters(v)}catch(v){y("setParameters on outbound camera failed:",v)}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera finalize failed:",v)}J(b);return}Q=b,fe=n,G.onended=()=>{Q===b&&Ze.enqueueCurrent(async({isCurrent:v})=>{if(!(!v()||Q!==b||!d()||g!==f||ue!==c)){try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) after camera ended failed:",U)}!v()||Q!==b||!d()||g!==f||ue!==c||(Q=null,fe=void 0,J(b),Ge(),f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(v=>y("camera ended cleanup failed:",v))},p()&&(mt(f,G),pt())}),_e=()=>{for(const n of ce)n();ce.clear();for(const n of Y.values())clearTimeout(n);Y.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),ne.clear(),ie.clear(),le.clear(),L?.(),L=void 0,Vt(),H=null;for(const n of Oe.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));Oe.clear(),w(null),m({controlReady:!1,videoReady:!1}),He(),Ie(),Ye(),$&&($.stop(),$=null),Ne!==null&&Ve(null),Ze.invalidate(),Ge(),Gt(),fe=void 0,ue=null,++qe,tt=!1,pe=null,te&&(J(te),te=null,F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),ve=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),Fe?.close(),Fe=null,I&&(I.onconnectionstatechange=null,I.oniceconnectionstatechange=null,I.ontrack=null,I.onicecandidate=null,I.close(),I=null),x&&(x.onopen=null,x.onclose=null,x.onerror=null,x.close(),x=null)},Ct=()=>{document.hidden?be():ft()},Zt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const d=new URL(r);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,n=Mt(d.toString(),u)}catch{return!1}const f=new AbortController,c=window.setTimeout(()=>f.abort(),jr);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:f.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},er=()=>{Ee||(Ee=!0,de+=1,$e(),He(),Ie(),_e(),D("Instance terminated"),be(),De("terminated"),F("onTerminated",e.onTerminated))},tr=()=>{if(Ee||Se)return;Se=!0;const n=Le;Zt().catch(()=>!1).then(f=>{n===Le&&(Se=!1,f&&er())})},ge=(n,f)=>{if(Ee||f!==de)return;if(tr(),re){if(e.autoReconnect===!1){D(`Connection failed after it was established: ${n}`),be(),De("failed"),_e();return}D(`Reconnecting after established session dropped: ${n}`),re=!1,xe=-1}$e();const c=xe+1;if(c>=st){D(`Connection failed after ${st} attempts: ${n}`),be(),De("failed"),_e();return}D(`Retrying connection (${c+1}/${st})`),De("reconnecting"),_e(),Ke=window.setTimeout(()=>{Ke=void 0,f===de&&Ot(c)},Hr)},Ot=async(n=0)=>{const{openUrl:f,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:K}=e;if(Ee)return;const p=de+1;de=p,xe=n,re=!1,n===0&&Ce!=="reconnecting"&&De("connecting"),$e(),He(),Ye(),we=!1,S(!1),_e();const C=()=>p===de;Ae=window.setTimeout(()=>{Ae=void 0,!(!C()||re)&&ge("Connection did not succeed within 15 seconds",p)},Jr);try{const h=e.transport?await e.transport.connect():new WebSocket(Mt(r,u));if(!C()){h.close();return}if(g=h,await new Promise((_,s)=>{let k=!1;const W=()=>M(()=>s(new Error("Connection stopped")));ce.add(W);const T=window.setTimeout(()=>M(()=>s(new Error("WebSocket connection timeout"))),3e4),M=z=>{k||(k=!0,ce.delete(W),window.clearTimeout(T),z())};h.onopen=()=>{!C()||g!==h||M(_)},h.onerror=z=>{!C()||g!==h||(D("WebSocket error: "+z),M(()=>s(new Error("WebSocket connection failed"))))},h.onclose=()=>{!C()||g!==h||(D("WebSocket closed"),M(()=>s(new Error("WebSocket closed before connection was established"))))},h.readyState===WebSocket.OPEN?M(_):h.readyState!==WebSocket.CONNECTING&&M(()=>s(new Error("WebSocket is closed")))}),!C()||g!==h)return;h.onerror=_=>{!C()||g!==h||D("WebSocket error: "+_)},h.onclose=()=>{!C()||g!==h||D("WebSocket closed")};const R=new Promise((_,s)=>{let k=!1;const W=()=>T(()=>s(new Error("Connection stopped")));ce.add(W);const T=j=>{k||(k=!0,ce.delete(W),window.clearTimeout(M),h.removeEventListener("message",z),j())},M=window.setTimeout(()=>T(()=>s(new Error("RTCConfiguration timeout"))),3e4),z=j=>{if(!(!C()||g!==h))try{const X=JSON.parse(j.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===i){const ir=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>s(new Error(ir)))}else X.type==="rtcConfiguration"&&T(()=>_({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>s(X))}};h.addEventListener("message",z),h.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:i}))}),{rtcConfiguration:b,cameraSupported:G,foldSupported:v}=await R;if(!C()||g!==h)return;const U=a==="iphone-duo"||v;q(U);const A=new RTCPeerConnection({...b,iceTransportPolicy:"relay"});I=A;const je={peer:A,displays:new Map};H=je,P(),A.addTransceiver("audio",{direction:"recvonly"});const rr=A.addTransceiver("video",{direction:"recvonly"}),nr=U?A.addTransceiver("video",{direction:"recvonly"}):null,Tt=!l&&(E==="ios"||G),it=Tt?A.addTransceiver("video",{direction:"sendonly"}):null;if(ue=it?.sender??null,ve=(Tt?A.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const _=RTCRtpReceiver.getCapabilities("video");if(_&&_.codecs){const k=_.codecs.sort((W,T)=>{const M=z=>{const j=z.mimeType.toLowerCase();return j.includes("h265")||j.includes("hevc")?1:j.includes("h264")||j.includes("avc")?2:3};return M(W)-M(T)});rr.setCodecPreferences(k),nr?.setCodecPreferences(k),se("Set codec preferences:",k.map(W=>W.mimeType).join(", "))}}if(it&&RTCRtpSender.getCapabilities){const _=RTCRtpSender.getCapabilities("video");if(_&&_.codecs){const s=new Set(["42e01f","42e028","640c1f"]),k=T=>{const M=T.mimeType.toLowerCase(),j=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=j?j[1]:"";return M==="video/h265"||M==="video/hevc"?1:M==="video/h264"&&s.has(X)?2:M==="video/h264"?3:M==="video/vp9"?4:M==="video/vp8"?5:M==="video/rtx"||M==="video/red"||M==="video/ulpfec"?0:6},W=[..._.codecs].sort((T,M)=>k(T)-k(M));try{it.setCodecPreferences(W),se("Outbound camera codec preferences:",W.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){y("Failed to set outbound camera codec preferences:",T)}}}const ae=A.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});x=ae;const ot=!l&&!U&&e.onTrace?Fr(A,_=>{C()&&I===A&&F("onTrace",e.onTrace,_)}):null;if(Fe=ot,ae.onopen=()=>{if(!C()||x!==ae||g!==h)return;re=!0,m({controlReady:!l}),He(),D("Control channel opened"),U&&h.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),!$&&E!=="macos"&&($=new Rr({platform:E,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:K,send:s=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(s)),!0}catch{return!1}},onSnapshot:Ve,onStatusChange:(s,k)=>{F("onAxStatusChange",e.onAxStatusChange,s,k)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&$.start());const _=()=>{!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN||h.send(JSON.stringify({type:"requestFrame",sessionId:i}))};if(_(),Ye(),Be=window.setInterval(()=>{if(!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN){Ye();return}_()},250),!l&&f){try{const s=decodeURIComponent(f);D("Opening URL"),h.send(JSON.stringify({type:"openUrl",url:s,sessionId:i}))}catch(s){console.error({error:s},"Error decoding URL, falling back to the original URL"),h.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}$?.bumpActivity()}},ae.onclose=()=>{!C()||x!==ae||(m({controlReady:!1}),D("Control channel closed"))},ae.onerror=_=>{!C()||x!==ae||(console.error("Control channel error:",_),D("Control channel error: "+_))},A.onconnectionstatechange=()=>{!C()||I!==A||(D("Connection state: "+A.connectionState),A.connectionState==="failed"&&re&&ge("WebRTC connection entered failed state",p))},A.oniceconnectionstatechange=()=>{if(!C()||I!==A)return;const _=A.iceConnectionState;if(D("ICE state: "+_),_==="connected"||_==="completed"){Ie(),rt()&&!te&&nt();return}if(_==="failed"){Ie(),re&&ge("ICE connection entered failed state",p);return}_==="disconnected"&&re&&e.autoReconnect!==!1&&me===void 0&&(me=window.setTimeout(()=>{me=void 0,!(!C()||I!==A)&&A.iceConnectionState==="disconnected"&&ge("ICE stayed disconnected past grace period",p)},Gr))},A.ontrack=_=>{if(!C()||I!==A)return;Kt(_.receiver,e.jitterBufferTargetMs);const s=_.track.id==="duo-inner"||_.streams.some(k=>k.id==="duo-inner");if(_.track.kind==="video"&&je.displays.set(_.receiver,s?"inner":"primary"),D("Received remote track: "+_.track.kind),_.track.kind==="video"){const k=s?"inner":"primary",W=U?new MediaStream([_.track]):_.streams[0]??new MediaStream([_.track]);Pe.set(k,W);for(const[T,M]of B)M.display===k&<(T,M,W)}},A.onicecandidate=_=>{if(!(!C()||I!==A||g!==h))if(_.candidate&&h.readyState===WebSocket.OPEN){const s={type:"candidate",candidate:_.candidate.candidate,sdpMid:_.candidate.sdpMid,sdpMLineIndex:_.candidate.sdpMLineIndex,sessionId:i};h.send(JSON.stringify(s)),D("Sent ICE candidate")}else D("ICE candidate gathering completed")},h.onmessage=async _=>{if(!C()||g!==h)return;let s;try{s=JSON.parse(_.data)}catch(k){y("Error parsing message:",k);return}if(!$?.handleMessage(s))switch(D("Received: "+s.type),s.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!U)break;s.state?(w(s.state),N(void 0)):s.id==="duo-capabilities"&&N(s.error||"This instance does not support native iPhone Duo displays.");const T=Oe.get(s.id);T&&(clearTimeout(T.timer),Oe.delete(s.id),s.error?T.reject(new Error(s.error)):T.resolve());break}case"signalingError":{if(s.requestType!=="offer"||s.sessionId!==i)break;const T=typeof s.error=="string"?s.error:"Unable to establish the streaming connection";D("Error: "+T),ge(T,p);break}case"answer":if(!I||I!==A){D("No peer connection, skipping answer");break}if(ot?.accept(s.latencyTraceVersion),await A.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:s.sdp})),!C()||I!==A)return;D("Set remote description");break;case"candidate":if(!I||I!==A){D("No peer connection, skipping candidate");break}if(await A.addIceCandidate(new RTCIceCandidate({candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex})),!C()||I!==A)return;D("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof s.id!="string"){y("Received invalid screenshot success message:",s);break}const T=Qr(s);if(T){const j=ee.get(s.id);if(typeof j!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${T}`),j(new Error(T)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const M=zr(s);if(!M){y("Received screenshot message without image data:",s);break}const z=ne.get(s.id);if(typeof z!="function"){y(`Received screenshot data for unknown or handled id: ${s.id}`);break}se(`Received screenshot data for id ${s.id}`),z(M),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}case"screenshotError":if(typeof s.id!="string"||typeof s.message!="string"){y("Received invalid screenshot error message:",s);break}const k=ee.get(s.id);if(typeof k!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${s.message}`),k(new Error(s.message)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;case"cameraRequest":{const T=ue;if(!T)break;const M=xr(s);if(!M){y("Received invalid cameraRequest:",s);break}console.info("[RemoteControl] cameraRequest received:",M.active,M.facingMode),await zt(M,h,T,C);break}case"microphoneRequest":{if(!ve)break;const T=s.active===!0;if(tt=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){et||await Je();break}if(te){ht(h);break}await nt();break}case"microphoneStartResult":{if(pe===null||s.id!==pe)break;pe=null,typeof s.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",s.error),Je(s.error));break}case"terminateAppResult":if(typeof s.id!="string"){y("Received invalid terminateApp result message:",s);break}if(typeof s.error=="string"){const T=ie.get(s.id);if(typeof T!="function"){y(`Received terminateApp error for unknown or handled id: ${s.id}`);break}y(`Received terminateApp error for id ${s.id}: ${s.error}`),T(new Error(s.error)),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const W=le.get(s.id);if(typeof W!="function"){y(`Received terminateApp result for unknown or handled id: ${s.id}`);break}se(`Received terminateApp success for id ${s.id}`),W(),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;default:y(`Received unhandled message type: ${s.type}`,s);break}},I===A){const _=await A.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!C()||I!==A||(await A.setLocalDescription(_),!C()||I!==A))return;C()&&g===h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({type:"offer",...U?{displayStreams:!0}:{},...ot?{latencyTraceVersion:1}:{},sdp:_.sdp,sessionId:i})),D("Sent offer")}}catch(h){if(!C()||h instanceof Error&&h.message==="Connection stopped")return;const R=h instanceof Error?h.message:String(h);D("Error: "+R),ge(R,p)}},Dt=()=>{if(ye)throw new Error("Device stream is disposed");Le++,Se=!1,Ve(null),Ce!=="reconnecting"&&(Ce=null),document.addEventListener("visibilitychange",Ct),document.hidden||ft(),Ee=!1,Ot(0)},_t=()=>{Le++,Se=!1,be(),document.removeEventListener("visibilitychange",Ct),de+=1,xe=0,re=!1,$e(),Ie(),_e(),Ce=null,m({connection:"idle",videoReady:!1,controlReady:!1}),D("Stopped")},gt=(n,f="primary")=>{if(ye)throw new Error("Device stream is disposed");if(B.has(n))throw new Error("Video element is already attached");const c={display:f};B.set(n,c);const d=()=>{f==="primary"&&Pe.has(f)&&Jt()};n.addEventListener("loadeddata",d);const K=Pe.get(f);K&<(n,c,K);let p=!1;const C=()=>{p||(p=!0,V.delete(C),n.removeEventListener("loadeddata",d),c.stop?.(),B.delete(n),n.srcObject=null)};return V.add(C),C};return{start:Dt,stop:_t,attachVideo:gt,attachFrameSink:(n,f="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=gt(c,f);let K=!1,p=0,C=0;const h=()=>{c.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},R=()=>{K||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&F("present",(...v)=>n.present(...v),c,c.videoWidth,c.videoHeight,f),!(K||!c.srcObject)&&(c.requestVideoFrameCallback?p=c.requestVideoFrameCallback(R):C=requestAnimationFrame(R)))},b=()=>{h(),R()};B.get(c).clear=h,c.addEventListener("loadeddata",b);const G=()=>{K||(K=!0,V.delete(G),h(),c.removeEventListener("loadeddata",b),d(),c.remove())};return V.delete(d),V.add(G),c.readyState>=2&&b(),G},dispose:()=>{if(!ye){ye=!0,_t();for(const n of V)n();V.clear()}},getState:()=>O,updateOptions:({token:n,...f})=>{if(ye)throw new Error("Device stream is disposed");n!==void 0&&!e.transport&&(u=n);const c=e;if(e={...e,...f},c.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const d of I?.getTransceivers()??[])(d.currentDirection==="recvonly"||d.currentDirection==="sendrecv")&&Kt(d.receiver,e.jitterBufferTargetMs);!!c.onPlaybackStats!=!!e.onPlaybackStats&&P(),!!c.microphoneEnabled!=!!e.microphoneEnabled&&(et=!l&&(e.microphoneEnabled??!1),rt()?nt():Je()),!!c.inspectMode!=!!e.inspectMode&&(e.inspectMode?$?.start():($?.stop(),Ne!==null&&Ve(null)))},sendControl:oe,sendTouch:(n,f,c,d,K,p=0)=>oe(Nt(n==="begin"?0:n==="end"?1:2,p,d,K,f,c,n==="end"?0:1)),sendText:n=>oe(bt(n)),sendDisplayTouch:(n,f,c,d)=>oe(Ut(n,f,c,d)),sendDuoControl:$t,pressButton:n=>{const f={home:3,back:4,recents:187,power:26}[n];oe(Xe(0,f,0,0)),oe(Xe(1,f,0,0))},rotate:()=>oe(new Uint8Array([11]).buffer),bumpActivity:()=>$?.bumpActivity(),getAxStatus:()=>$?.getStatus()??"idle",openUrl:n=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){y("WebSocket not open, cannot send open_url command.");return}try{const f=decodeURIComponent(n);D("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}catch(f){y("Error decoding or sending URL :",{error:f,url:n}),g.send(JSON.stringify({type:"openUrl",url:n,sessionId:i}))}$?.bumpActivity()}},sendKeyEvent:n=>{if(!x||x.readyState!=="open"){y("Data channel not ready for imperative key command:",x?.readyState);return}if(E==="macos"){const p=ct(n.code);if(p===void 0){y(`Unknown event.code for imperative command: ${n.code}`);return}const C=[[n.metaKey,"MetaLeft"],[n.ctrlKey,"ControlLeft"],[n.altKey,"AltLeft"],[n.shiftKey,"ShiftLeft"]].filter(([R,b])=>R&&b!==n.code).map(([,R])=>ct(R)),h=(R,b)=>oe(Yt(R,b));if(n.type==="keydown"){for(const R of C)h(Re.DOWN,R);h(Re.DOWN,p)}else{h(Re.UP,p);for(const R of[...C].reverse())h(Re.UP,R)}return}const f=wt[n.code];if(!f){y(`Unknown event.code for imperative command: ${n.code}`);return}let c=o.META_NONE;n.shiftKey&&(c|=o.META_SHIFT_ON),n.altKey&&(c|=o.META_ALT_ON),n.ctrlKey&&(c|=o.META_CTRL_ON),n.metaKey&&(c|=o.META_META_ON);const d=n.type==="keydown"?o.ACTION_DOWN:o.ACTION_UP;se(`Sending Imperative Key Command: code=${n.code}, keycode=${f}, action=${d}, meta=${c}`);const K=Xe(d,f,0,c);K&&oe(K)},screenshot:n=>new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:d};ne.set(d,f),ee.set(d,c),se("Sending screenshot request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send screenshot request immediately:",p),ne.delete(d),ee.delete(d),c(p);return}Y.set(d,setTimeout(()=>{Y.delete(d),ne.has(d)&&(y(`Screenshot request timed out for id ${d}`),ee.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),ee.delete(d))},3e4))}),terminateApp:n=>l?Promise.reject(new Error("Device is watch-only")):new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:"terminateApp",id:d,bundleId:n};le.set(d,f),ie.set(d,c),se("Sending terminateApp request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send terminateApp request immediately:",p),le.delete(d),ie.delete(d),c(p);return}$?.bumpActivity(),Y.set(d,setTimeout(()=>{Y.delete(d),le.has(d)&&(y(`terminateApp request timed out for id ${d}`),ie.get(d)?.(new Error("terminateApp request timed out")),le.delete(d),ie.delete(d))},3e4))}),reconnect:()=>Dt(),refreshAxTree:async()=>{const n=$;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ne}}const Qr=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,zr=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Ue;exports.ANDROID_KEYS=o;exports.AX_UNAVAILABLE_ERROR=Qe;exports.CONTROL_MSG_TYPE=Z;exports.DUO_BUTTONS=pr;exports.DUO_DIMENSIONS=ur;exports.DuoButtonSender=Cr;exports.DuoTouchController=dr;exports.HingeSender=mr;exports.MAC_INPUT_ACTION=Re;exports.axElementAtPoint=Kr;exports.axElementRoleLabel=xt;exports.axElementSelectorExpression=Ar;exports.axElementSummary=Mr;exports.axElementsEqual=Ft;exports.axSnapshotsEqual=Bt;exports.clampAxFrameForScreen=Sr;exports.codeMap=wt;exports.createDeviceStream=Xr;exports.createDisplayTouchMessage=Ut;exports.createInjectKeycodeMessage=Xe;exports.createMacKeyMessage=Yt;exports.createMacScrollMessage=cr;exports.createMouseControlMessage=sr;exports.createSetClipboardMessage=bt;exports.createTouchControlMessage=Nt;exports.createTwoFingerTouchControlMessage=ar;exports.debugLog=se;exports.debugWarn=y;exports.detectPlatform=qt;exports.duoDisplayTurns=It;exports.duoPointerMode=hr;exports.flatDisplayTouch=Rt;exports.getDuoDisplay=lr;exports.macKeyCodeFor=ct;exports.normalizeAndroidTree=Lt;exports.normalizeIosTree=Pt;exports.panelTouch=Er;exports.safeInvoke=F;
|
|
2
|
+
`,At=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Wt],{type:"text/javascript;charset=utf-8"});function Ur(t){let e;try{if(e=At&&(self.URL||self.webkitURL).createObjectURL(At),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Wt),{name:t?.name})}}function kr(t,e,r){const{MediaStreamTrackProcessor:a,MediaStreamTrackGenerator:u}=globalThis,l=e.getVideoTracks()[0];let i,E,O,m,S=!1;const w=()=>{S||(S=!0,i?.stop(),E?.stop(),O&&(O.postMessage({type:"stop"}),m=setTimeout(()=>O?.terminate(),1e3)))},N=D=>{t.srcObject=D,t.play().catch(()=>{})},q=D=>{S||(w(),r(D),N(e))};try{if(l&&a&&u){i=l.clone();const D=new a({track:i,maxBufferSize:1}),H=new u({kind:"video"});E=H,O=new Ur,O.onmessage=({data:L})=>{L.type==="error"?q(new Error(L.message)):L.type==="stopped"&&(clearTimeout(m),O?.terminate())},O.onerror=L=>q(new Error(L.message)),O.postMessage({type:"start",readable:D.readable,writable:H.writable},[D.readable,H.writable]),N(new MediaStream(e.getTracks().map(L=>L===l?H:L)))}else N(e)}catch(D){q(D)}return w}function ke(t){return typeof t=="number"&&Number.isFinite(t)}function Te(t,e){if(!(!ke(t)||!ke(e)||t<e||e<0))return t-e}class Pr{previous=new Map;reset(){this.previous.clear()}read(e,r,a){const u={timestamp:0,video:[],audio:[]};a==null?u.requestedTargetMs=null:ke(a)&&a>=0&&a<=4e3&&(u.requestedTargetMs=a);const l=new Map;return e.forEach(i=>{if(i.type!=="inbound-rtp"||!ke(i.timestamp))return;const E=i.kind??i.mediaType;if(E!=="video"&&E!=="audio")return;const O=r.filter(P=>P.kind===E),m=i.trackIdentifier?O.find(P=>P.trackId===i.trackIdentifier):i.mid!=null?O.find(P=>P.mid===i.mid):O.length===1?O[0]:void 0;if(!m)return;const S=this.previous.get(i.id),N=S?.trackId===m.trackId&&S.stats.ssrc===i.ssrc?S.stats:void 0,q=N?i.timestamp-N.timestamp:void 0,D={id:i.id,trackId:m.trackId,timestamp:i.timestamp};if(q!==void 0&&q>0){D.intervalMs=q;const P=Te(i.jitterBufferEmittedCount,N?.jitterBufferEmittedCount),B=Te(i.jitterBufferDelay,N?.jitterBufferDelay);P!==void 0&&P>0&&B!==void 0&&(D.bufferDelayMs=B/P*1e3);const V=Te(i.bytesReceived,N?.bytesReceived);V!==void 0&&(D.bitrateBps=V*8e3/q)}if(E==="video"){const P={...D,display:m.display??"primary"};if(D.intervalMs!==void 0){const B=Te(i.framesDecoded,N?.framesDecoded);B!==void 0&&(P.fps=B*1e3/D.intervalMs),P.droppedFrames=Te(i.framesDropped,N?.framesDropped),P.freezes=Te(i.freezeCount,N?.freezeCount)}u.video.push(P)}else u.audio.push(D);u.timestamp=Math.max(u.timestamp,i.timestamp),l.set(i.id,N&&i.timestamp<=N.timestamp?S:{stats:i,trackId:m.trackId});const H=i.transportId?e.get(i.transportId):void 0,L=H?.selectedCandidatePairId?e.get(H.selectedCandidatePairId):void 0;L?.state==="succeeded"&&ke(L.currentRoundTripTime)&&L.currentRoundTripTime>=0&&(u.rttMs=L.currentRoundTripTime*1e3)}),this.previous=l,u.video.length||u.audio.length?u:null}}const at=new WeakSet;function Lr(t,e,r){const{peer:a,displays:u}=t,l=new Pr;let i,E=!1,O=!1,m=!1,S=0,w=!1,N=!1;const q=()=>!E&&!document.hidden&&a.connectionState==="connected",D=B=>{if(!(!B&&!w)){w=B!==null;try{e()?.(B)}catch(V){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',V)}}},H=()=>{O=!1,S++,clearTimeout(i),l.reset(),D(null)},L=async()=>{if(m||!q())return;if(at.has(a)){i=setTimeout(()=>{L()},2e3);return}m=!0,at.add(a);const B=S;try{const V=await a.getStats();if(B!==S||!q())return;const ce=a.getTransceivers().filter(Y=>(Y.currentDirection==="recvonly"||Y.currentDirection==="sendrecv")&&Y.receiver.track.readyState!=="ended").map(Y=>({trackId:Y.receiver.track.id,kind:Y.receiver.track.kind,mid:Y.mid,display:u.get(Y.receiver)}));D(l.read(V,ce,r())),N=!1}catch(V){if(B!==S||!q())return;N||console.warn("[RemoteControl] could not read playback stats:",V),N=!0,l.reset(),D(null)}finally{m=!1,at.delete(a),O&&q()&&(i=setTimeout(()=>{L()},B===S?2e3:0))}},P=()=>{if(!q()){H();return}O||(O=!0,L())};return document.addEventListener("visibilitychange",P),a.addEventListener("connectionstatechange",P),P(),()=>{E=!0,document.removeEventListener("visibilitychange",P),a.removeEventListener("connectionstatechange",P),H()}}function Fr(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let a=!1,u=!1,l=0;return r.onmessage=i=>{if(u)return;let E;try{E=JSON.parse(i.data)}catch(O){console.warn("Invalid latency trace message",O);return}E&&typeof E=="object"&&!Array.isArray(E)&&e(E)},r.onclose=()=>{u=!0,a=!1},{accept(i){a=!u&&i===1},wrap(i){if(!a||i.byteLength===0)return i;const E=new DataView(i),O=E.getUint8(0),m=O===Z.INJECT_MOUSE_EVENT||O===Z.INJECT_MAC_KEY||O===Z.INJECT_MAC_SCROLL,S=i.byteLength===32&&O===Z.INJECT_TOUCH_EVENT&&E.getUint8(1)<=2;if(!m&&!S)return i;const w=new ArrayBuffer(6+i.byteLength),N=new DataView(w);return N.setUint8(0,240),N.setUint8(1,1),N.setUint32(2,++l,!0),new Uint8Array(w,6).set(new Uint8Array(i)),w},close(){u=!0,a=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Br{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const a={generation:e,isCurrent:()=>e===this.generation},u=this.tail.then(()=>r(a));return this.tail=u.catch(()=>{}),u}invalidate(){++this.generation}}function xr(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function Wr(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function qr(t,e){return!t||t.facingMode!==e.facingMode}function Vr(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function $r(t){return{type:"cameraResult",granted:!0,camera:Vr(t)}}const se=(...t)=>{window.debugRemoteControl&&console.log(...t)},y=(...t)=>{window.debugRemoteControl&&console.warn(...t)},F=(t,e,...r)=>{if(e)try{e(...r)}catch(a){console.error(`[RemoteControl] customer callback "${t}" threw:`,a)}},qt=t=>t.includes("/android_")?"android":t.includes("/macos_")?"macos":"ios",Mt=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},st=3,Hr=1e3,Jr=15e3,Gr=3e3,jr=4e3;function vt(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Xr(t){let e={...t};const{url:r,deviceModel:a}=e;let u=e.token;const l=e.watchOnly??!1,i=e.sessionId??vt(),E=e.platform??qt(r??"");let O={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const m=n=>{O={...O,...n},F("onStateChange",e.onStateChange,O)},S=n=>m({videoReady:n}),w=n=>m({duoState:n}),N=n=>m({duoError:n}),q=n=>m({duo:n}),D=n=>se(n);let H=null,L;const P=()=>{L?.(),L=H&&e.onPlaybackStats?Lr(H,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},B=new Map,V=new Set,ce=new Set,Y=new Map;let ye=!1;const Pe=new Map,lt=(n,f,c)=>{f.stop?.(),f.stop=kr(n,c,d=>y("Video playback fallback:",d))},Vt=()=>{Pe.clear();for(const[n,f]of B)f.clear?.(),f.stop?.(),f.stop=void 0,n.srcObject=null};let Ee=!1,Se=!1,Le=0,g=null,I=null,x=null,Fe=null,he,Ke,Ae,Be,me,de=0,xe=0,re=!1,ue=null,Q=null,fe;const Ze=new Br;let Me=null,We=null,et=!l&&(e.microphoneEnabled??!1),tt=!1,ve=null,te=null,qe=0,dt=Promise.resolve(),pe=null,we=!1,ne=new Map,ee=new Map,le=new Map,ie=new Map,$=null,Ne=null,ut=0;const Ve=n=>{if(n===null&&Ne===null)return;Ne=n;const f=++ut;queueMicrotask(()=>{f===ut&&F("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let Ce=null,Oe=new Map;const $t=(n,f)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const K=g;if(!K||K.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const p=vt(),C=setTimeout(()=>{Oe.delete(p),d(new Error("Device control timed out"))},5e3);Oe.set(p,{resolve:c,reject:d,timer:C}),K.send(JSON.stringify({type:n,id:p,...f}))}),De=n=>{Ce!==n&&(Ce=n,m({connection:n}),F("onConnectionStateChange",e.onConnectionStateChange,n))},oe=n=>{l||!x||x.readyState!=="open"||(x.send(Fe?.wrap(n)??n),$?.bumpActivity())},Ht=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:i}))},ft=()=>{he&&window.clearInterval(he),he=window.setInterval(Ht,1e4)},be=()=>{he&&(window.clearInterval(he),he=void 0)},$e=()=>{Ke&&(window.clearTimeout(Ke),Ke=void 0)},He=()=>{Ae&&(window.clearTimeout(Ae),Ae=void 0)},Ye=()=>{Be&&(window.clearInterval(Be),Be=void 0)},Ie=()=>{me!==void 0&&(window.clearTimeout(me),me=void 0)},Jt=()=>{we||(we=!0,Ye(),S(!0),De("connected"))},J=n=>{for(const f of n.getTracks())try{f.stop()}catch(c){y("track.stop() failed:",c)}},Gt=()=>{const n=Q;n&&(Q=null,J(n))},Et=n=>{const f=dt.then(n).catch(c=>{y("microphone operation failed:",c)});return dt=f,f},rt=()=>et||tt,ht=n=>{const f=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;pe=f,n.send(JSON.stringify({type:"microphoneStart",id:f}))},nt=()=>Et(()=>jt()),jt=async()=>{const n=qe,f=()=>n===qe&&rt(),c=h=>{F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:h})};if(!f())return;const d=g,K=ve;if(!d||d.readyState!==WebSocket.OPEN||!K||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),c("Microphone capture requires a secure context (https)");return}let p=null;try{p=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(h){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",h)}if(!f()){p&&J(p);return}if(!p){c("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){J(p),c("Captured stream has no audio track");return}try{await K.replaceTrack(C)}catch(h){y("replaceTrack(audioTrack) failed:",h),J(p),c("Failed to attach the microphone track to the connection");return}if(!f()){try{await K.replaceTrack(null)}catch(h){y("replaceTrack(null) on stale mic attach failed:",h)}J(p);return}te=p,C.onended=()=>{te===p&&Je("microphone capture ended by the browser")},ht(d),F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},Je=n=>(++qe,pe=null,Et(async()=>{const f=ve,c=te;if(te=null,f&&c)try{await f.replaceTrack(null)}catch(K){y("replaceTrack(null) on mic detach failed:",K)}c&&J(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const K=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:K}))}(c||n)&&F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),mt=(n,f)=>{let c;try{c=$r(f),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){y("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:f.label||void 0}}}n.send(JSON.stringify(c)),F("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},Xt=n=>{if(!n)return;const f=n.indexOf("/"),d=(f>=0?n.slice(f+1):n).toUpperCase();return d==="HEVC"?"H265":d},Qt=async()=>{const n=ue,f=e.onCameraStats;if(!n||!f)return;let c;try{c=await n.getStats()}catch{return}let d,K,p;if(c.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?d=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(p=U)}),d?.codecId){const U=c.get(d.codecId);U&&(K=U.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),h=We;let R,b,G;if(h&&C>h.timestamp){const U=(C-h.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof h.framesEncoded=="number"&&(R=Math.max(0,(d.framesEncoded-h.framesEncoded)/U)),typeof d.bytesSent=="number"&&typeof h.bytesSent=="number"&&(b=Math.max(0,(d.bytesSent-h.bytesSent)*8/U)),typeof d.packetsSent=="number"&&typeof h.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof h.packetsLost=="number"){const A=d.packetsSent-h.packetsSent,je=p.packetsLost-h.packetsLost;A>0&&(G=Math.max(0,Math.min(100,je/A*100)))}}We={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:p?.packetsLost};const v={codec:Xt(K),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:R,framesEncoded:d.framesEncoded,bitrateBps:b,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof p?.roundTripTime=="number"?p.roundTripTime*1e3:void 0,packetsLostPct:G};F("onCameraStats",e.onCameraStats,v)},pt=()=>{Me===null&&(We=null,Me=setInterval(()=>{Qt()},1e3))},Ge=()=>{Me!==null&&(clearInterval(Me),Me=null),We=null,F("onCameraStats",e.onCameraStats,null)},zt=(n,f,c,d)=>Ze.enqueue(async({isCurrent:K})=>{const p=()=>K()&&d()&&g===f&&ue===c;if(!p())return;if(!n.active){const v=Q;try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) on camera detach failed:",U)}if(Q===v&&(Q=null,fe=void 0,v&&J(v)),Ge(),!p())return;F("onCameraDemandChange",e.onCameraDemandChange,!1);return}F("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,h=C?.getVideoTracks()[0],R=fe;if(h?.readyState==="live"&&R&&!qr(R,n)){fe=n,mt(f,h),pt();return}if(C){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) before camera switch failed:",v)}if(Q===C&&(Q=null,fe=void 0,J(C)),Ge(),!p())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let b=null;try{b=await navigator.mediaDevices.getUserMedia({video:Wr(n),audio:!1})}catch(v){console.warn("[RemoteControl] getUserMedia denied/failed:",v)}if(!p()){b&&J(b);return}if(!b){f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const G=b.getVideoTracks()[0]??null;if(!G){if(J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{G.contentHint="motion"}catch{}try{await c.replaceTrack(G)}catch(v){if(y("replaceTrack(videoTrack) failed:",v),J(b),!p())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera attach failed:",v)}J(b);return}try{const v=c.getParameters();(!v.encodings||v.encodings.length===0)&&(v.encodings=[{}]),v.encodings[0].maxBitrate=8e6,v.encodings[0].maxFramerate=30,v.degradationPreference="maintain-framerate",await c.setParameters(v)}catch(v){y("setParameters on outbound camera failed:",v)}if(!p()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera finalize failed:",v)}J(b);return}Q=b,fe=n,G.onended=()=>{Q===b&&Ze.enqueueCurrent(async({isCurrent:v})=>{if(!(!v()||Q!==b||!d()||g!==f||ue!==c)){try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) after camera ended failed:",U)}!v()||Q!==b||!d()||g!==f||ue!==c||(Q=null,fe=void 0,J(b),Ge(),f.send(JSON.stringify({type:"cameraResult",granted:!1})),F("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(v=>y("camera ended cleanup failed:",v))},p()&&(mt(f,G),pt())}),_e=()=>{for(const n of ce)n();ce.clear();for(const n of Y.values())clearTimeout(n);Y.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),ne.clear(),ie.clear(),le.clear(),L?.(),L=void 0,Vt(),H=null;for(const n of Oe.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));Oe.clear(),w(null),m({controlReady:!1,videoReady:!1}),He(),Ie(),Ye(),$&&($.stop(),$=null),Ne!==null&&Ve(null),Ze.invalidate(),Ge(),Gt(),fe=void 0,ue=null,++qe,tt=!1,pe=null,te&&(J(te),te=null,F("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),ve=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),Fe?.close(),Fe=null,I&&(I.onconnectionstatechange=null,I.oniceconnectionstatechange=null,I.ontrack=null,I.onicecandidate=null,I.close(),I=null),x&&(x.onopen=null,x.onclose=null,x.onerror=null,x.close(),x=null)},Ct=()=>{document.hidden?be():ft()},Zt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const d=new URL(r);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,n=Mt(d.toString(),u)}catch{return!1}const f=new AbortController,c=window.setTimeout(()=>f.abort(),jr);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:f.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},er=()=>{Ee||(Ee=!0,de+=1,$e(),He(),Ie(),_e(),D("Instance terminated"),be(),De("terminated"),F("onTerminated",e.onTerminated))},tr=()=>{if(Ee||Se)return;Se=!0;const n=Le;Zt().catch(()=>!1).then(f=>{n===Le&&(Se=!1,f&&er())})},ge=(n,f)=>{if(Ee||f!==de)return;if(tr(),re){if(e.autoReconnect===!1){D(`Connection failed after it was established: ${n}`),be(),De("failed"),_e();return}D(`Reconnecting after established session dropped: ${n}`),re=!1,xe=-1}$e();const c=xe+1;if(c>=st){D(`Connection failed after ${st} attempts: ${n}`),be(),De("failed"),_e();return}D(`Retrying connection (${c+1}/${st})`),De("reconnecting"),_e(),Ke=window.setTimeout(()=>{Ke=void 0,f===de&&Ot(c)},Hr)},Ot=async(n=0)=>{const{openUrl:f,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:K}=e;if(Ee)return;const p=de+1;de=p,xe=n,re=!1,n===0&&Ce!=="reconnecting"&&De("connecting"),$e(),He(),Ye(),we=!1,S(!1),_e();const C=()=>p===de;Ae=window.setTimeout(()=>{Ae=void 0,!(!C()||re)&&ge("Connection did not succeed within 15 seconds",p)},Jr);try{const h=e.transport?await e.transport.connect():new WebSocket(Mt(r,u));if(!C()){h.close();return}if(g=h,await new Promise((_,s)=>{let k=!1;const W=()=>M(()=>s(new Error("Connection stopped")));ce.add(W);const T=window.setTimeout(()=>M(()=>s(new Error("WebSocket connection timeout"))),3e4),M=z=>{k||(k=!0,ce.delete(W),window.clearTimeout(T),z())};h.onopen=()=>{!C()||g!==h||M(_)},h.onerror=z=>{!C()||g!==h||(D("WebSocket error: "+z),M(()=>s(new Error("WebSocket connection failed"))))},h.onclose=()=>{!C()||g!==h||(D("WebSocket closed"),M(()=>s(new Error("WebSocket closed before connection was established"))))},h.readyState===WebSocket.OPEN?M(_):h.readyState!==WebSocket.CONNECTING&&M(()=>s(new Error("WebSocket is closed")))}),!C()||g!==h)return;h.onerror=_=>{!C()||g!==h||D("WebSocket error: "+_)},h.onclose=()=>{!C()||g!==h||D("WebSocket closed")};const R=new Promise((_,s)=>{let k=!1;const W=()=>T(()=>s(new Error("Connection stopped")));ce.add(W);const T=j=>{k||(k=!0,ce.delete(W),window.clearTimeout(M),h.removeEventListener("message",z),j())},M=window.setTimeout(()=>T(()=>s(new Error("RTCConfiguration timeout"))),3e4),z=j=>{if(!(!C()||g!==h))try{const X=JSON.parse(j.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===i){const ir=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>s(new Error(ir)))}else X.type==="rtcConfiguration"&&T(()=>_({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>s(X))}};h.addEventListener("message",z),h.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:i}))}),{rtcConfiguration:b,cameraSupported:G,foldSupported:v}=await R;if(!C()||g!==h)return;const U=a==="iphone-duo"||v;q(U);const A=new RTCPeerConnection({...b,iceTransportPolicy:"relay"});I=A;const je={peer:A,displays:new Map};H=je,P(),A.addTransceiver("audio",{direction:"recvonly"});const rr=A.addTransceiver("video",{direction:"recvonly"}),nr=U?A.addTransceiver("video",{direction:"recvonly"}):null,Tt=!l&&(E==="ios"||G),it=Tt?A.addTransceiver("video",{direction:"sendonly"}):null;if(ue=it?.sender??null,ve=(Tt?A.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const _=RTCRtpReceiver.getCapabilities("video");if(_&&_.codecs){const k=_.codecs.sort((W,T)=>{const M=z=>{const j=z.mimeType.toLowerCase();return j.includes("h265")||j.includes("hevc")?1:j.includes("h264")||j.includes("avc")?2:3};return M(W)-M(T)});rr.setCodecPreferences(k),nr?.setCodecPreferences(k),se("Set codec preferences:",k.map(W=>W.mimeType).join(", "))}}if(it&&RTCRtpSender.getCapabilities){const _=RTCRtpSender.getCapabilities("video");if(_&&_.codecs){const s=new Set(["42e01f","42e028","640c1f"]),k=T=>{const M=T.mimeType.toLowerCase(),j=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=j?j[1]:"";return M==="video/h265"||M==="video/hevc"?1:M==="video/h264"&&s.has(X)?2:M==="video/h264"?3:M==="video/vp9"?4:M==="video/vp8"?5:M==="video/rtx"||M==="video/red"||M==="video/ulpfec"?0:6},W=[..._.codecs].sort((T,M)=>k(T)-k(M));try{it.setCodecPreferences(W),se("Outbound camera codec preferences:",W.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){y("Failed to set outbound camera codec preferences:",T)}}}const ae=A.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});x=ae;const ot=!l&&!U&&e.onTrace?Fr(A,_=>{C()&&I===A&&F("onTrace",e.onTrace,_)}):null;if(Fe=ot,ae.onopen=()=>{if(!C()||x!==ae||g!==h)return;re=!0,m({controlReady:!l}),He(),D("Control channel opened"),U&&h.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),!$&&E!=="macos"&&($=new Rr({platform:E,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:K,send:s=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(s)),!0}catch{return!1}},onSnapshot:Ve,onStatusChange:(s,k)=>{F("onAxStatusChange",e.onAxStatusChange,s,k)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&$.start());const _=()=>{!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN||h.send(JSON.stringify({type:"requestFrame",sessionId:i}))};if(_(),Ye(),Be=window.setInterval(()=>{if(!C()||we||x!==ae||g!==h||h.readyState!==WebSocket.OPEN){Ye();return}_()},250),!l&&f){try{const s=decodeURIComponent(f);D("Opening URL"),h.send(JSON.stringify({type:"openUrl",url:s,sessionId:i}))}catch(s){console.error({error:s},"Error decoding URL, falling back to the original URL"),h.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}$?.bumpActivity()}},ae.onclose=()=>{!C()||x!==ae||(m({controlReady:!1}),D("Control channel closed"))},ae.onerror=_=>{!C()||x!==ae||(console.error("Control channel error:",_),D("Control channel error: "+_))},A.onconnectionstatechange=()=>{!C()||I!==A||(D("Connection state: "+A.connectionState),A.connectionState==="failed"&&re&&ge("WebRTC connection entered failed state",p))},A.oniceconnectionstatechange=()=>{if(!C()||I!==A)return;const _=A.iceConnectionState;if(D("ICE state: "+_),_==="connected"||_==="completed"){Ie(),rt()&&!te&&nt();return}if(_==="failed"){Ie(),re&&ge("ICE connection entered failed state",p);return}_==="disconnected"&&re&&e.autoReconnect!==!1&&me===void 0&&(me=window.setTimeout(()=>{me=void 0,!(!C()||I!==A)&&A.iceConnectionState==="disconnected"&&ge("ICE stayed disconnected past grace period",p)},Gr))},A.ontrack=_=>{if(!C()||I!==A)return;Kt(_.receiver,e.jitterBufferTargetMs);const s=_.track.id==="duo-inner"||_.streams.some(k=>k.id==="duo-inner");if(_.track.kind==="video"&&je.displays.set(_.receiver,s?"inner":"primary"),D("Received remote track: "+_.track.kind),_.track.kind==="video"){const k=s?"inner":"primary",W=U?new MediaStream([_.track]):_.streams[0]??new MediaStream([_.track]);Pe.set(k,W);for(const[T,M]of B)M.display===k&<(T,M,W)}},A.onicecandidate=_=>{if(!(!C()||I!==A||g!==h))if(_.candidate&&h.readyState===WebSocket.OPEN){const s={type:"candidate",candidate:_.candidate.candidate,sdpMid:_.candidate.sdpMid,sdpMLineIndex:_.candidate.sdpMLineIndex,sessionId:i};h.send(JSON.stringify(s)),D("Sent ICE candidate")}else D("ICE candidate gathering completed")},h.onmessage=async _=>{if(!C()||g!==h)return;let s;try{s=JSON.parse(_.data)}catch(k){y("Error parsing message:",k);return}if(!$?.handleMessage(s))switch(D("Received: "+s.type),s.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!U)break;s.state?(w(s.state),N(void 0)):s.id==="duo-capabilities"&&N(s.error||"This instance does not support native iPhone Duo displays.");const T=Oe.get(s.id);T&&(clearTimeout(T.timer),Oe.delete(s.id),s.error?T.reject(new Error(s.error)):T.resolve());break}case"signalingError":{if(s.requestType!=="offer"||s.sessionId!==i)break;const T=typeof s.error=="string"?s.error:"Unable to establish the streaming connection";D("Error: "+T),ge(T,p);break}case"answer":if(!I||I!==A){D("No peer connection, skipping answer");break}if(ot?.accept(s.latencyTraceVersion),await A.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:s.sdp})),!C()||I!==A)return;D("Set remote description");break;case"candidate":if(!I||I!==A){D("No peer connection, skipping candidate");break}if(await A.addIceCandidate(new RTCIceCandidate({candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex})),!C()||I!==A)return;D("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof s.id!="string"){y("Received invalid screenshot success message:",s);break}const T=Qr(s);if(T){const j=ee.get(s.id);if(typeof j!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${T}`),j(new Error(T)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const M=zr(s);if(!M){y("Received screenshot message without image data:",s);break}const z=ne.get(s.id);if(typeof z!="function"){y(`Received screenshot data for unknown or handled id: ${s.id}`);break}se(`Received screenshot data for id ${s.id}`),z(M),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}case"screenshotError":if(typeof s.id!="string"||typeof s.message!="string"){y("Received invalid screenshot error message:",s);break}const k=ee.get(s.id);if(typeof k!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${s.message}`),k(new Error(s.message)),ne.delete(s.id),ee.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;case"cameraRequest":{const T=ue;if(!T)break;const M=xr(s);if(!M){y("Received invalid cameraRequest:",s);break}console.info("[RemoteControl] cameraRequest received:",M.active,M.facingMode),await zt(M,h,T,C);break}case"microphoneRequest":{if(!ve)break;const T=s.active===!0;if(tt=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){et||await Je();break}if(te){ht(h);break}await nt();break}case"microphoneStartResult":{if(pe===null||s.id!==pe)break;pe=null,typeof s.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",s.error),Je(s.error));break}case"terminateAppResult":if(typeof s.id!="string"){y("Received invalid terminateApp result message:",s);break}if(typeof s.error=="string"){const T=ie.get(s.id);if(typeof T!="function"){y(`Received terminateApp error for unknown or handled id: ${s.id}`);break}y(`Received terminateApp error for id ${s.id}: ${s.error}`),T(new Error(s.error)),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break}const W=le.get(s.id);if(typeof W!="function"){y(`Received terminateApp result for unknown or handled id: ${s.id}`);break}se(`Received terminateApp success for id ${s.id}`),W(),le.delete(s.id),ie.delete(s.id),clearTimeout(Y.get(s.id)),Y.delete(s.id);break;default:y(`Received unhandled message type: ${s.type}`,s);break}},I===A){const _=await A.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!C()||I!==A||(await A.setLocalDescription(_),!C()||I!==A))return;C()&&g===h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({type:"offer",...U?{displayStreams:!0}:{},...ot?{latencyTraceVersion:1}:{},sdp:_.sdp,sessionId:i})),D("Sent offer")}}catch(h){if(!C()||h instanceof Error&&h.message==="Connection stopped")return;const R=h instanceof Error?h.message:String(h);D("Error: "+R),ge(R,p)}},Dt=()=>{if(ye)throw new Error("Device stream is disposed");Le++,Se=!1,Ve(null),Ce!=="reconnecting"&&(Ce=null),document.addEventListener("visibilitychange",Ct),document.hidden||ft(),Ee=!1,Ot(0)},_t=()=>{Le++,Se=!1,be(),document.removeEventListener("visibilitychange",Ct),de+=1,xe=0,re=!1,$e(),Ie(),_e(),Ce=null,m({connection:"idle",videoReady:!1,controlReady:!1}),D("Stopped")},gt=(n,f="primary")=>{if(ye)throw new Error("Device stream is disposed");if(B.has(n))throw new Error("Video element is already attached");const c={display:f};B.set(n,c);const d=()=>{f==="primary"&&Pe.has(f)&&Jt()};n.addEventListener("loadeddata",d);const K=Pe.get(f);K&<(n,c,K);let p=!1;const C=()=>{p||(p=!0,V.delete(C),n.removeEventListener("loadeddata",d),c.stop?.(),B.delete(n),n.srcObject=null)};return V.add(C),C};return{start:Dt,stop:_t,attachVideo:gt,attachFrameSink:(n,f="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=gt(c,f);let K=!1,p=0,C=0;const h=()=>{c.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},R=()=>{K||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&F("present",(...v)=>n.present(...v),c,c.videoWidth,c.videoHeight,f),!(K||!c.srcObject)&&(c.requestVideoFrameCallback?p=c.requestVideoFrameCallback(R):C=requestAnimationFrame(R)))},b=()=>{h(),R()};B.get(c).clear=h,c.addEventListener("loadeddata",b);const G=()=>{K||(K=!0,V.delete(G),h(),c.removeEventListener("loadeddata",b),d(),c.remove())};return V.delete(d),V.add(G),c.readyState>=2&&b(),G},dispose:()=>{if(!ye){ye=!0,_t();for(const n of V)n();V.clear()}},getState:()=>O,updateOptions:({token:n,...f})=>{if(ye)throw new Error("Device stream is disposed");n!==void 0&&!e.transport&&(u=n);const c=e;if(e={...e,...f},c.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const d of I?.getTransceivers()??[])(d.currentDirection==="recvonly"||d.currentDirection==="sendrecv")&&Kt(d.receiver,e.jitterBufferTargetMs);!!c.onPlaybackStats!=!!e.onPlaybackStats&&P(),!!c.microphoneEnabled!=!!e.microphoneEnabled&&(et=!l&&(e.microphoneEnabled??!1),rt()?nt():Je()),!!c.inspectMode!=!!e.inspectMode&&(e.inspectMode?$?.start():($?.stop(),Ne!==null&&Ve(null)))},sendControl:oe,sendTouch:(n,f,c,d,K,p=0)=>oe(Nt(n==="begin"?0:n==="end"?1:2,p,d,K,f,c,n==="end"?0:1)),sendText:n=>oe(bt(n)),sendDisplayTouch:(n,f,c,d)=>oe(Ut(n,f,c,d)),sendDuoControl:$t,pressButton:n=>{const f={home:3,back:4,recents:187,power:26}[n];oe(Xe(0,f,0,0)),oe(Xe(1,f,0,0))},rotate:()=>oe(new Uint8Array([11]).buffer),bumpActivity:()=>$?.bumpActivity(),getAxStatus:()=>$?.getStatus()??"idle",openUrl:n=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){y("WebSocket not open, cannot send open_url command.");return}try{const f=decodeURIComponent(n);D("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}catch(f){y("Error decoding or sending URL :",{error:f,url:n}),g.send(JSON.stringify({type:"openUrl",url:n,sessionId:i}))}$?.bumpActivity()}},sendKeyEvent:n=>{if(!x||x.readyState!=="open"){y("Data channel not ready for imperative key command:",x?.readyState);return}if(E==="macos"){const p=ct(n.code);if(p===void 0){y(`Unknown event.code for imperative command: ${n.code}`);return}const C=[[n.metaKey,"Meta"],[n.ctrlKey,"Control"],[n.altKey,"Alt"],[n.shiftKey,"Shift"]].filter(([R,b])=>R&&!n.code.startsWith(b)).map(([,R])=>ct(`${R}Left`)),h=(R,b)=>oe(Yt(R,b));if(n.type==="keydown"){for(const R of C)h(Re.DOWN,R);h(Re.DOWN,p)}else{h(Re.UP,p);for(const R of[...C].reverse())h(Re.UP,R)}return}const f=wt[n.code];if(!f){y(`Unknown event.code for imperative command: ${n.code}`);return}let c=o.META_NONE;n.shiftKey&&(c|=o.META_SHIFT_ON),n.altKey&&(c|=o.META_ALT_ON),n.ctrlKey&&(c|=o.META_CTRL_ON),n.metaKey&&(c|=o.META_META_ON);const d=n.type==="keydown"?o.ACTION_DOWN:o.ACTION_UP;se(`Sending Imperative Key Command: code=${n.code}, keycode=${f}, action=${d}, meta=${c}`);const K=Xe(d,f,0,c);K&&oe(K)},screenshot:n=>new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:d};ne.set(d,f),ee.set(d,c),se("Sending screenshot request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send screenshot request immediately:",p),ne.delete(d),ee.delete(d),c(p);return}Y.set(d,setTimeout(()=>{Y.delete(d),ne.has(d)&&(y(`Screenshot request timed out for id ${d}`),ee.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),ee.delete(d))},3e4))}),terminateApp:n=>l?Promise.reject(new Error("Device is watch-only")):new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:"terminateApp",id:d,bundleId:n};le.set(d,f),ie.set(d,c),se("Sending terminateApp request:",K);try{g.send(JSON.stringify(K))}catch(p){y("Failed to send terminateApp request immediately:",p),le.delete(d),ie.delete(d),c(p);return}$?.bumpActivity(),Y.set(d,setTimeout(()=>{Y.delete(d),le.has(d)&&(y(`terminateApp request timed out for id ${d}`),ie.get(d)?.(new Error("terminateApp request timed out")),le.delete(d),ie.delete(d))},3e4))}),reconnect:()=>Dt(),refreshAxTree:async()=>{const n=$;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ne}}const Qr=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,zr=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Ue;exports.ANDROID_KEYS=o;exports.AX_UNAVAILABLE_ERROR=Qe;exports.CONTROL_MSG_TYPE=Z;exports.DUO_BUTTONS=pr;exports.DUO_DIMENSIONS=ur;exports.DuoButtonSender=Cr;exports.DuoTouchController=dr;exports.HingeSender=mr;exports.MAC_INPUT_ACTION=Re;exports.axElementAtPoint=Kr;exports.axElementRoleLabel=xt;exports.axElementSelectorExpression=Ar;exports.axElementSummary=Mr;exports.axElementsEqual=Ft;exports.axSnapshotsEqual=Bt;exports.clampAxFrameForScreen=Sr;exports.codeMap=wt;exports.createDeviceStream=Xr;exports.createDisplayTouchMessage=Ut;exports.createInjectKeycodeMessage=Xe;exports.createMacKeyMessage=Yt;exports.createMacScrollMessage=cr;exports.createMouseControlMessage=sr;exports.createSetClipboardMessage=bt;exports.createTouchControlMessage=Nt;exports.createTwoFingerTouchControlMessage=ar;exports.debugLog=se;exports.debugWarn=y;exports.detectPlatform=qt;exports.duoDisplayTurns=It;exports.duoPointerMode=hr;exports.flatDisplayTouch=Rt;exports.getDuoDisplay=lr;exports.macKeyCodeFor=ct;exports.normalizeAndroidTree=Lt;exports.normalizeIosTree=Pt;exports.panelTouch=Er;exports.safeInvoke=F;
|