Open History to see the last commit
1import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
2import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
3import type { DevicePlatform } from "@t3tools/contracts";
4
5export interface DeviceAxElement {
6 readonly id: string;
7 readonly label: string;
8 readonly role: string;
9 /** Normalized to the displayed screen: 0..1 on both axes. */
10 readonly x: number;
11 readonly y: number;
12 readonly width: number;
13 readonly height: number;
14}
15
16export interface DeviceAxTree {
17 readonly elements: ReadonlyArray<DeviceAxElement>;
18 readonly errors: ReadonlyArray<string>;
19}
20
21export interface DeviceEventLogEntry {
22 readonly id: number;
23 readonly timestamp: string;
24 readonly kind: string;
25 readonly summary: string;
26}
27
28export interface DeviceForegroundInfo {
29 readonly id: string;
30 readonly label?: string;
31 readonly pid?: number;
32 readonly isReactNative?: boolean;
33}
34
35interface Target {
36 readonly access: DeviceHubAccess;
37 readonly platform: DevicePlatform;
38 readonly deviceId: string;
39}
40
41const vendorBase = (target: Target) =>
42 `${target.access.httpBase}${target.platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu"}`;
43
44const hubUrl = (target: Target, path: string, params?: Record<string, string>) => {
45 const search = params ? `?${new URLSearchParams(params).toString()}` : "";
46 return withDeviceHubQuery(`${vendorBase(target)}${path}${search}`, target.access);
47};
48
49const fetchJson = async (target: Target, url: string, signal?: AbortSignal): Promise<unknown> => {
50 const response = await fetch(url, {
51 cache: "no-store",
52 credentials: target.access.credentials ? "include" : "same-origin",
53 ...(signal ? { signal } : {}),
54 });
55 if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
56 return response.json();
57};
58
59const isRecord = (value: unknown): value is Record<string, unknown> =>
60 typeof value === "object" && value !== null;
61
62const numberOr = (value: unknown, fallback: number) =>
63 typeof value === "number" && Number.isFinite(value) ? value : fallback;
64
65const AX_ELEMENT_LIMIT = 500;
66
67const flattenIosAxTree = (roots: ReadonlyArray<unknown>): ReadonlyArray<DeviceAxElement> => {
68 const first = roots[0];
69 const rootFrame = isRecord(first) && isRecord(first.frame) ? first.frame : null;
70 const screenWidth = Math.max(1, numberOr(rootFrame?.width, 1));
71 const screenHeight = Math.max(1, numberOr(rootFrame?.height, 1));
72 const elements: DeviceAxElement[] = [];
73 const visit = (node: unknown, path: string) => {
74 if (elements.length >= AX_ELEMENT_LIMIT || !isRecord(node) || !isRecord(node.frame)) return;
75 const frame = node.frame;
76 const width = numberOr(frame.width, 0);
77 const height = numberOr(frame.height, 0);
78 const coversScreen =
79 Math.abs(width - screenWidth) < 0.5 && Math.abs(height - screenHeight) < 0.5;
80 if (!coversScreen && width > 0 && height > 0) {
81 elements.push({
82 id: typeof node.AXUniqueId === "string" ? node.AXUniqueId : path,
83 label: typeof node.AXLabel === "string" ? node.AXLabel : "",
84 role: typeof node.type === "string" ? node.type : "",
85 x: numberOr(frame.x, 0) / screenWidth,
86 y: numberOr(frame.y, 0) / screenHeight,
87 width: width / screenWidth,
88 height: height / screenHeight,
89 });
90 }
91 const children = Array.isArray(node.children) ? node.children : [];
92 children.forEach((child, index) => visit(child, `${path}.${index}`));
93 };
94 roots.forEach((root, index) => visit(root, String(index)));
95 return elements;
96};
97
98export async function fetchDeviceAxTree(
99 target: Target,
100 signal?: AbortSignal,
101): Promise<DeviceAxTree> {
102 if (target.platform === "ios") {
103 const payload = await fetchJson(
104 target,
105 hubUrl(target, `/helper/${encodeURIComponent(target.deviceId)}/ax`),
106 signal,
107 );
108 if (!Array.isArray(payload)) {
109 const error = isRecord(payload) && typeof payload.error === "string" ? payload.error : null;
110 return { elements: [], errors: [error ?? "Unexpected accessibility payload."] };
111 }
112 return { elements: flattenIosAxTree(payload), errors: [] };
113 }
114 const payload = await fetchJson(
115 target,
116 hubUrl(target, "/api/accessibility", { device: target.deviceId }),
117 signal,
118 );
119 if (!isRecord(payload) || !Array.isArray(payload.nodes)) {
120 const error = isRecord(payload) && typeof payload.error === "string" ? payload.error : null;
121 return { elements: [], errors: [error ?? "Unexpected accessibility payload."] };
122 }
123 const nodes = payload.nodes.filter(
124 (node): node is Record<string, unknown> => isRecord(node) && isRecord(node.bounds),
125 );
126 const root = nodes[0]?.bounds as Record<string, unknown> | undefined;
127 const screenWidth = Math.max(1, numberOr(root?.right, 1));
128 const screenHeight = Math.max(1, numberOr(root?.bottom, 1));
129 const elements = nodes.slice(1).flatMap((node): DeviceAxElement[] => {
130 const bounds = node.bounds as Record<string, unknown>;
131 const left = numberOr(bounds.left, 0);
132 const top = numberOr(bounds.top, 0);
133 const width = (numberOr(bounds.right, left) - left) / screenWidth;
134 const height = (numberOr(bounds.bottom, top) - top) / screenHeight;
135 const text = typeof node.text === "string" ? node.text : "";
136 const description = typeof node.contentDescription === "string" ? node.contentDescription : "";
137 const label = text || description;
138 if (width >= 0.95 && height >= 0.9) return [];
139 if (!label && node.clickable !== true) return [];
140 const className = typeof node.className === "string" ? node.className : "";
141 return [
142 {
143 id: String(node.id ?? ""),
144 label,
145 role: className.split(".").at(-1) ?? "",
146 x: left / screenWidth,
147 y: top / screenHeight,
148 width,
149 height,
150 },
151 ];
152 });
153 return { elements, errors: [] };
154}
155
156const openEventSource = (
157 target: Target,
158 url: string,
159 onMessage: (data: unknown) => void,
160): (() => void) => {
161 const source = new EventSource(url, { withCredentials: target.access.credentials });
162 source.addEventListener("message", (event) => {
163 try {
164 onMessage(JSON.parse(String(event.data)));
165 } catch {}
166 });
167 return () => source.close();
168};
169
170export function subscribeDeviceForeground(
171 target: Target,
172 onChange: (app: DeviceForegroundInfo | null) => void,
173): () => void {
174 if (target.platform !== "ios") return () => {};
175 return openEventSource(
176 target,
177 hubUrl(target, "/appstate", { device: target.deviceId }),
178 (data) => {
179 if (!isRecord(data)) return;
180 if (data.bundleId === null || data.bundleId === "") {
181 onChange(null);
182 return;
183 }
184 if (typeof data.bundleId !== "string") return;
185 onChange({
186 id: data.bundleId,
187 ...(typeof data.pid === "number" ? { pid: data.pid } : {}),
188 ...(typeof data.isReactNative === "boolean" ? { isReactNative: data.isReactNative } : {}),
189 });
190 },
191 );
192}
193
194const toEventLogEntry = (raw: unknown): DeviceEventLogEntry | null => {
195 if (!isRecord(raw) || typeof raw.id !== "number") return null;
196 return {
197 id: raw.id,
198 timestamp: typeof raw.timestamp === "string" ? raw.timestamp : "",
199 kind: typeof raw.kind === "string" ? raw.kind : "",
200 summary:
201 typeof raw.summary === "string" ? raw.summary : typeof raw.msg === "string" ? raw.msg : "",
202 };
203};
204
205export function subscribeDeviceEventLog(
206 target: Target,
207 onEvents: (entries: ReadonlyArray<DeviceEventLogEntry>, reset: boolean) => void,
208): () => void {
209 if (target.platform !== "ios") return () => {};
210 return openEventSource(
211 target,
212 hubUrl(target, "/api/event-log/events", { device: target.deviceId, limit: "100" }),
213 (data) => {
214 if (!isRecord(data)) return;
215 if (Array.isArray(data.events)) {
216 onEvents(
217 data.events.flatMap((raw) => toEventLogEntry(raw) ?? []),
218 true,
219 );
220 return;
221 }
222 const entry = toEventLogEntry(data.event);
223 if (entry) onEvents([entry], false);
224 },
225 );
226}