agent-device-x86sim 0.1.0 → 0.1.2

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.
@@ -0,0 +1,777 @@
1
+ import path from "node:path";
2
+ import { access, constants, lstat, mkdir, readFile, readdir, readlink, realpath, rm, symlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { createConnection } from "node:net";
5
+ import { randomUUID } from "node:crypto";
6
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
7
+ //#region src/cli/install.ts
8
+ const BOOT_SCRIPT = "cli/libexec/arm64/boot-a64.sh";
9
+ /** Where x86Sim copies itself and keeps phones, as its AppImage decides it. */
10
+ const x86simDataDir = (env, home) => env.X86SIM_DATA || path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "x86sim");
11
+ /** Where x86Sim keeps its scratch files. */
12
+ const x86simCacheDir = (env, home) => env.X86SIM_CACHE || path.join(env.XDG_CACHE_HOME || path.join(home, ".cache"), "x86sim");
13
+ const versionParts = (version) => version.split(/[.-]/).map((part) => /^\d+$/.test(part) ? Number(part) : -1);
14
+ /** Compares versions part by part. A part that is not a number, such as `pre8`, sorts below a missing one. */
15
+ function compareVersions(a, b) {
16
+ const left = versionParts(a);
17
+ const right = versionParts(b);
18
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
19
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
20
+ if (difference !== 0) return difference;
21
+ }
22
+ return 0;
23
+ }
24
+ const newestVersion = (versions) => [...versions].sort(compareVersions).at(-1);
25
+ /**
26
+ * x86Sim's AppImage copies its payload into the data folder, and phones run from there after
27
+ * the launcher exits. This runs the copy the way the AppImage's `AppRun` would, with the same
28
+ * environment.
29
+ */
30
+ function dataDirInstall(parts) {
31
+ const app = path.join(parts.dataDir, "app", parts.version);
32
+ const env = {
33
+ X86SIM_DARLING_MODE: parts.darlingMode,
34
+ X86SIM_ROOT: parts.dataDir,
35
+ X86SIM_SCRATCH: parts.cacheDir,
36
+ X86SIM_APP: app,
37
+ X86SIM_VERSION: parts.version,
38
+ X86SIM_DARLING_ID: parts.darlingId,
39
+ X86SIM_PYLIB: path.join(app, "pylib"),
40
+ A64_PREFIX_HEAL: "0",
41
+ PATH: `${path.join(app, "bin")}:${parts.path}`
42
+ };
43
+ return {
44
+ label: `x86Sim ${parts.version} in ${parts.dataDir}`,
45
+ dataDir: parts.dataDir,
46
+ cli: (args) => ({
47
+ command: path.join(app, "cli", "x86sim"),
48
+ args: [...args],
49
+ env
50
+ }),
51
+ boot: () => ({
52
+ command: "/bin/sh",
53
+ args: ["-c", BOOT_SCRIPT],
54
+ env,
55
+ cwd: parts.dataDir
56
+ })
57
+ };
58
+ }
59
+ /** An AppImage the user named, which runs everything through its own entry point. */
60
+ function appImageInstall(appImage, dataDir) {
61
+ return {
62
+ label: appImage,
63
+ dataDir,
64
+ cli: (args) => ({
65
+ command: appImage,
66
+ args: ["x86sim", ...args],
67
+ env: {}
68
+ }),
69
+ boot: () => ({
70
+ command: appImage,
71
+ args: [
72
+ "shell",
73
+ "-c",
74
+ BOOT_SCRIPT
75
+ ],
76
+ env: {}
77
+ })
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/cli/discovery.ts
82
+ const QUICK_START_URL = "https://github.com/x86sim/x86sim#quick-start";
83
+ const DEVICE_PREFIX = "device-a64-";
84
+ /** x86Sim has not been set up on this machine. Callers that can run without it catch this one. */
85
+ var NotSetUpError = class extends Error {};
86
+ /**
87
+ * x86Sim as `--appimage` or `$X86SIM_APPIMAGE` names it, else the newest copy in the data
88
+ * folder. Running an AppImage copies its payload there, whatever folder the AppImage is in.
89
+ */
90
+ async function findX86Sim(flag, environment) {
91
+ const { env, home, cwd } = environment;
92
+ const dataDir = x86simDataDir(env, home);
93
+ const given = flag ?? env.X86SIM_APPIMAGE;
94
+ if (given) {
95
+ const file = path.resolve(cwd, given);
96
+ if (!await environment.isExecutable(file)) throw new Error(`The x86Sim AppImage ${file} is missing or not executable. Run: chmod +x ${file}`);
97
+ return appImageInstall(file, dataDir);
98
+ }
99
+ const appDir = path.join(dataDir, "app");
100
+ const complete = [];
101
+ for (const version of await environment.listDir(appDir)) if ((await environment.listDir(path.join(appDir, version))).includes(".complete")) complete.push(version);
102
+ const version = newestVersion(complete);
103
+ if (!version) throw new NotSetUpError(`x86Sim is not set up. Follow ${QUICK_START_URL}`);
104
+ const mode = env.X86SIM_DARLING_MODE;
105
+ const link = await environment.readLink(path.join(dataDir, "darling-prefix"));
106
+ return dataDirInstall({
107
+ dataDir,
108
+ cacheDir: x86simCacheDir(env, home),
109
+ version,
110
+ darlingId: (await environment.readText(path.join(appDir, version, "DARLING_ID")))?.trim() ?? "",
111
+ darlingMode: mode === "system" || mode === "userns" ? mode : link?.includes("darling-userns") ? "userns" : "system",
112
+ path: env.PATH ?? ""
113
+ });
114
+ }
115
+ async function listPhones(dataDir, environment) {
116
+ const varDir = path.join(dataDir, "var");
117
+ const folders = (await environment.listDir(varDir)).filter((name) => name.startsWith(DEVICE_PREFIX)).sort();
118
+ return await Promise.all(folders.map(async (folder) => ({
119
+ folder,
120
+ path: path.join(varDir, folder),
121
+ name: (await environment.readText(path.join(varDir, folder, "name")))?.trim() || folder
122
+ })));
123
+ }
124
+ const quoted = (phones) => phones.map((phone) => `"${phone.name}"`).join(", ");
125
+ const pick = (phone) => `agent-device connect x86sim --device "${phone.name}"`;
126
+ /**
127
+ * The phone to use. `--device` names it, by the name the launcher shows or by its folder, or is
128
+ * the folder's path. Without it, the phone that runs wins, else the only phone.
129
+ */
130
+ async function findPhone(flag, dataDir, environment) {
131
+ const phones = await listPhones(dataDir, environment);
132
+ if (flag?.includes("/")) {
133
+ const folder = path.resolve(environment.cwd, flag);
134
+ if (!(await environment.listDir(folder)).includes("sim.env")) throw new Error(`${folder} is not a phone folder, because it has no sim.env.`);
135
+ return {
136
+ folder: path.basename(folder),
137
+ path: folder,
138
+ name: path.basename(folder)
139
+ };
140
+ }
141
+ if (flag) {
142
+ const lower = flag.toLowerCase();
143
+ const matches = phones.filter((phone) => phone.folder === flag || phone.name.toLowerCase() === lower);
144
+ const [only] = matches;
145
+ if (only && matches.length === 1) return only;
146
+ if (only) throw new Error(`More than one phone is named "${flag}". Use a folder name: ${matches.map((p) => p.folder).join(", ")}.`);
147
+ throw new Error(phones.length === 0 ? `No phone found in ${path.join(dataDir, "var")}. Create one on the Setup page of the x86Sim launcher. ${QUICK_START_URL}` : `No phone is named "${flag}". The phones are ${quoted(phones)}.`);
148
+ }
149
+ const [first] = phones;
150
+ if (!first) throw new Error(`No phone found in ${path.join(dataDir, "var")}. Create one on the Setup page of the x86Sim launcher. ${QUICK_START_URL}`);
151
+ const running = [];
152
+ for (const phone of phones) if (await environment.isRunning(phone.path)) running.push(phone);
153
+ const [firstRunning] = running;
154
+ if (firstRunning && running.length === 1) return firstRunning;
155
+ if (phones.length === 1) return first;
156
+ throw new Error(`${running.length > 1 ? "More than one phone runs" : "There is more than one phone and none runs"}. The phones are ${quoted(running.length > 1 ? running : phones)}. Pick one with ${pick(running[0] ?? first)}.`);
157
+ }
158
+ //#endregion
159
+ //#region src/cli/running.ts
160
+ const PROBE_TIMEOUT_MS = 5e3;
161
+ /** Whether the phone in this folder runs, which is whether its simhid socket accepts a connection. */
162
+ async function isPhoneRunning(device) {
163
+ try {
164
+ const socketPath = await realpath(path.join(device, "data", "simhid.sock"));
165
+ return await new Promise((resolve) => {
166
+ const socket = createConnection(socketPath);
167
+ const done = (answer) => {
168
+ socket.destroy();
169
+ resolve(answer);
170
+ };
171
+ socket.setTimeout(PROBE_TIMEOUT_MS, () => done(false));
172
+ socket.once("connect", () => done(true));
173
+ socket.once("error", () => done(false));
174
+ });
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+ //#endregion
180
+ //#region src/cli/system.ts
181
+ /** The machine this process runs on. */
182
+ function systemEnvironment() {
183
+ return {
184
+ env: process.env,
185
+ home: homedir(),
186
+ cwd: process.cwd(),
187
+ listDir: (dir) => readdir(dir).catch(() => []),
188
+ readText: (file) => readFile(file, "utf8").catch(() => void 0),
189
+ readLink: (file) => readlink(file).catch(() => void 0),
190
+ isExecutable: (file) => access(file, constants.X_OK).then(() => true, () => false),
191
+ isRunning: isPhoneRunning
192
+ };
193
+ }
194
+ /** The x86Sim and the phone on this machine, or an error that names the fix. */
195
+ async function discoverTarget(flags, environment = systemEnvironment()) {
196
+ const x86sim = await findX86Sim(flags.appimage, environment);
197
+ const phone = await findPhone(flags.device, x86sim.dataDir, environment);
198
+ return {
199
+ x86sim,
200
+ device: phone.path,
201
+ deviceName: phone.name
202
+ };
203
+ }
204
+ //#endregion
205
+ //#region ../server/src/zip.ts
206
+ const END_OF_CENTRAL_DIRECTORY = 101010256;
207
+ const CENTRAL_HEADER = 33639248;
208
+ const LOCAL_HEADER = 67324752;
209
+ const MADE_BY_UNIX = 3;
210
+ const UTF8_NAMES = 2048;
211
+ const STORED = 0;
212
+ const DEFLATED = 8;
213
+ /** 1980-01-01, the earliest date a zip can hold. */
214
+ const DOS_DATE = 33;
215
+ const S_IFMT = 61440;
216
+ const S_IFDIR = 16384;
217
+ const S_IFREG = 32768;
218
+ const S_IFLNK = 40960;
219
+ /** The paths macOS adds when it zips a folder, which hold Finder metadata and no part of the app. */
220
+ const isMacMetadata = (name) => name.startsWith("__MACOSX/") || path.posix.basename(name).startsWith("._");
221
+ function safePath(name) {
222
+ const trimmed = name.replace(/\/+$/, "");
223
+ const normal = path.posix.normalize(trimmed);
224
+ if (trimmed.length === 0 || name.includes("\\") || path.posix.isAbsolute(normal) || normal === ".." || normal.startsWith("../")) throw new Error(`The zip has an entry outside its folder: ${name}`);
225
+ return normal;
226
+ }
227
+ function findEnd(bytes) {
228
+ for (let offset = bytes.length - 22; offset >= Math.max(0, bytes.length - 22 - 65535); offset -= 1) if (bytes.readUInt32LE(offset) === END_OF_CENTRAL_DIRECTORY) return offset;
229
+ throw new Error("The upload is not a zip file.");
230
+ }
231
+ /** Reads every entry of a zip into memory, checking each file's CRC. */
232
+ function readZip(bytes) {
233
+ const end = findEnd(bytes);
234
+ const count = bytes.readUInt16LE(end + 10);
235
+ let offset = bytes.readUInt32LE(end + 16);
236
+ if (count === 65535 || offset === 4294967295) throw new Error("ZIP64 files are not supported.");
237
+ const entries = [];
238
+ for (let index = 0; index < count; index += 1) {
239
+ if (bytes.readUInt32LE(offset) !== CENTRAL_HEADER) throw new Error("The zip central directory is damaged.");
240
+ const madeBy = bytes.readUInt16LE(offset + 4) >> 8;
241
+ const flags = bytes.readUInt16LE(offset + 8);
242
+ const method = bytes.readUInt16LE(offset + 10);
243
+ const crc = bytes.readUInt32LE(offset + 16);
244
+ const compressedSize = bytes.readUInt32LE(offset + 20);
245
+ const nameLength = bytes.readUInt16LE(offset + 28);
246
+ const extraLength = bytes.readUInt16LE(offset + 30);
247
+ const commentLength = bytes.readUInt16LE(offset + 32);
248
+ const external = bytes.readUInt32LE(offset + 38);
249
+ const localOffset = bytes.readUInt32LE(offset + 42);
250
+ const name = bytes.toString("utf8", offset + 46, offset + 46 + nameLength);
251
+ offset += 46 + nameLength + extraLength + commentLength;
252
+ if (isMacMetadata(name)) continue;
253
+ if (flags & 1) throw new Error(`The zip entry ${name} is encrypted.`);
254
+ const entryPath = safePath(name);
255
+ const unixMode = madeBy === MADE_BY_UNIX ? external >>> 16 : 0;
256
+ const type = unixMode & S_IFMT;
257
+ if (name.endsWith("/") || type === S_IFDIR) {
258
+ entries.push({
259
+ kind: "directory",
260
+ path: entryPath,
261
+ mode: unixMode & 511 || 493
262
+ });
263
+ continue;
264
+ }
265
+ if (bytes.readUInt32LE(localOffset) !== LOCAL_HEADER) throw new Error(`The zip entry ${name} is damaged.`);
266
+ const start = localOffset + 30 + bytes.readUInt16LE(localOffset + 26) + bytes.readUInt16LE(localOffset + 28);
267
+ const raw = bytes.subarray(start, start + compressedSize);
268
+ let data;
269
+ if (method === STORED) data = Buffer.from(raw);
270
+ else if (method === DEFLATED) data = inflateRawSync(raw);
271
+ else throw new Error(`The zip entry ${name} uses compression method ${method}, which is not supported.`);
272
+ if (crc32(data) !== crc) throw new Error(`The zip entry ${name} fails its CRC check.`);
273
+ entries.push(type === S_IFLNK ? {
274
+ kind: "symlink",
275
+ path: entryPath,
276
+ target: data.toString("utf8")
277
+ } : {
278
+ kind: "file",
279
+ path: entryPath,
280
+ mode: unixMode & 511 || 420,
281
+ data
282
+ });
283
+ }
284
+ return entries;
285
+ }
286
+ /** Writes a zip that keeps Unix modes and symlinks, as `zip -y` does. */
287
+ function writeZip(entries) {
288
+ const locals = [];
289
+ const centrals = [];
290
+ let offset = 0;
291
+ for (const entry of entries) {
292
+ const name = Buffer.from(entry.kind === "directory" ? `${entry.path}/` : entry.path, "utf8");
293
+ const data = entry.kind === "file" ? entry.data : entry.kind === "symlink" ? Buffer.from(entry.target) : Buffer.alloc(0);
294
+ const method = entry.kind === "file" ? DEFLATED : STORED;
295
+ const stored = method === DEFLATED ? deflateRawSync(data) : data;
296
+ const crc = crc32(data);
297
+ const external = ((entry.kind === "directory" ? S_IFDIR | entry.mode : entry.kind === "file" ? S_IFREG | entry.mode : 41471) << 16 >>> 0) + (entry.kind === "directory" ? 16 : 0);
298
+ const local = Buffer.alloc(30);
299
+ local.writeUInt32LE(LOCAL_HEADER, 0);
300
+ local.writeUInt16LE(20, 4);
301
+ local.writeUInt16LE(UTF8_NAMES, 6);
302
+ local.writeUInt16LE(method, 8);
303
+ local.writeUInt16LE(DOS_DATE, 12);
304
+ local.writeUInt32LE(crc, 14);
305
+ local.writeUInt32LE(stored.length, 18);
306
+ local.writeUInt32LE(data.length, 22);
307
+ local.writeUInt16LE(name.length, 26);
308
+ locals.push(local, name, stored);
309
+ const central = Buffer.alloc(46);
310
+ central.writeUInt32LE(CENTRAL_HEADER, 0);
311
+ central.writeUInt16LE(788, 4);
312
+ central.writeUInt16LE(20, 6);
313
+ central.writeUInt16LE(UTF8_NAMES, 8);
314
+ central.writeUInt16LE(method, 10);
315
+ central.writeUInt16LE(DOS_DATE, 14);
316
+ central.writeUInt32LE(crc, 16);
317
+ central.writeUInt32LE(stored.length, 20);
318
+ central.writeUInt32LE(data.length, 24);
319
+ central.writeUInt16LE(name.length, 28);
320
+ central.writeUInt32LE(external, 38);
321
+ central.writeUInt32LE(offset, 42);
322
+ centrals.push(central, name);
323
+ offset += local.length + name.length + stored.length;
324
+ }
325
+ const directory = Buffer.concat(centrals);
326
+ const end = Buffer.alloc(22);
327
+ end.writeUInt32LE(END_OF_CENTRAL_DIRECTORY, 0);
328
+ end.writeUInt16LE(entries.length, 8);
329
+ end.writeUInt16LE(entries.length, 10);
330
+ end.writeUInt32LE(directory.length, 12);
331
+ end.writeUInt32LE(offset, 16);
332
+ return Buffer.concat([
333
+ ...locals,
334
+ directory,
335
+ end
336
+ ]);
337
+ }
338
+ //#endregion
339
+ //#region ../server/src/app-archive.ts
340
+ const isApp = (name) => name.endsWith(".app");
341
+ async function treeEntries(root, prefix) {
342
+ const entries = [];
343
+ for (const child of await readdir(root, { withFileTypes: true })) {
344
+ const full = path.join(root, child.name);
345
+ const inZip = `${prefix}/${child.name}`;
346
+ const stats = await lstat(full);
347
+ if (stats.isSymbolicLink()) entries.push({
348
+ kind: "symlink",
349
+ path: inZip,
350
+ target: await readlink(full)
351
+ });
352
+ else if (stats.isDirectory()) {
353
+ entries.push({
354
+ kind: "directory",
355
+ path: inZip,
356
+ mode: 493
357
+ });
358
+ entries.push(...await treeEntries(full, inZip));
359
+ } else {
360
+ const mode = process.platform === "win32" ? 493 : stats.mode & 511;
361
+ entries.push({
362
+ kind: "file",
363
+ path: inZip,
364
+ mode,
365
+ data: await readFile(full)
366
+ });
367
+ }
368
+ }
369
+ return entries;
370
+ }
371
+ /** The zip to upload for `appPath`: a `.zip` as it is, or a `.app` folder zipped with its modes and symlinks. */
372
+ async function appArchive(appPath) {
373
+ const stats = await lstat(appPath).catch(() => void 0);
374
+ if (stats?.isFile() && appPath.toLowerCase().endsWith(".zip")) return await readFile(appPath);
375
+ if (stats?.isDirectory() && isApp(path.basename(appPath))) {
376
+ const name = path.basename(appPath);
377
+ return writeZip([{
378
+ kind: "directory",
379
+ path: name,
380
+ mode: 493
381
+ }, ...await treeEntries(appPath, name)]);
382
+ }
383
+ throw new Error(`x86Sim installs an arm64 iOS simulator .app folder, or a .zip that holds one. Got: ${appPath}`);
384
+ }
385
+ /** Writes the entries under `dir`. Symlinks come last and must point inside `dir`, so no file is written through one. */
386
+ async function unpack(entries, dir) {
387
+ for (const entry of entries) {
388
+ const target = path.join(dir, entry.path);
389
+ if (entry.kind === "directory") await mkdir(target, {
390
+ recursive: true,
391
+ mode: entry.mode
392
+ });
393
+ else if (entry.kind === "file") {
394
+ await mkdir(path.dirname(target), { recursive: true });
395
+ await writeFile(target, entry.data, { mode: entry.mode });
396
+ }
397
+ }
398
+ for (const entry of entries) {
399
+ if (entry.kind !== "symlink") continue;
400
+ const link = path.join(dir, entry.path);
401
+ const resolved = path.resolve(path.dirname(link), entry.target);
402
+ if (path.isAbsolute(entry.target) || !resolved.startsWith(`${dir}${path.sep}`)) throw new Error(`The zip has a link that points outside its folder: ${entry.path} -> ${entry.target}`);
403
+ await mkdir(path.dirname(link), { recursive: true });
404
+ await symlink(entry.target, link);
405
+ }
406
+ }
407
+ function createUploads(root) {
408
+ return {
409
+ async stage(zip) {
410
+ const dir = path.join(root, randomUUID());
411
+ await mkdir(dir, { recursive: true });
412
+ try {
413
+ await unpack(readZip(zip), dir);
414
+ const apps = (await readdir(dir, { withFileTypes: true })).filter((child) => child.isDirectory() && isApp(child.name));
415
+ if (apps.length !== 1) throw new Error(`The zip must hold one .app folder at its top. It holds ${apps.length}.`);
416
+ return path.join(dir, apps[0].name);
417
+ } catch (error) {
418
+ await rm(dir, {
419
+ recursive: true,
420
+ force: true
421
+ });
422
+ throw error;
423
+ }
424
+ },
425
+ async release(appPath) {
426
+ const [folder] = path.relative(root, appPath).split(path.sep);
427
+ if (!folder || folder === ".." || path.isAbsolute(folder)) return;
428
+ await rm(path.join(root, folder), {
429
+ recursive: true,
430
+ force: true
431
+ });
432
+ }
433
+ };
434
+ }
435
+ //#endregion
436
+ //#region ../server/src/errors.ts
437
+ /**
438
+ * A W3C WebDriver error. `error` is the spec's error code and the HTTP status follows the
439
+ * spec's table, so clients can tell "this route does not exist" from "this request is bad".
440
+ */
441
+ var WebDriverError = class extends Error {
442
+ error;
443
+ status;
444
+ constructor(error, status, message) {
445
+ super(message);
446
+ this.name = "WebDriverError";
447
+ this.error = error;
448
+ this.status = status;
449
+ }
450
+ };
451
+ const unknownCommand = (message) => new WebDriverError("unknown command", 404, message);
452
+ const invalidArgument = (message) => new WebDriverError("invalid argument", 400, message);
453
+ const invalidSessionId = (id) => new WebDriverError("invalid session id", 404, `No active session with id ${id}`);
454
+ const sessionNotCreated = (message) => new WebDriverError("session not created", 500, message);
455
+ const unsupportedOperation = (message) => new WebDriverError("unsupported operation", 500, message);
456
+ const unknownError = (message) => new WebDriverError("unknown error", 500, message);
457
+ //#endregion
458
+ //#region ../server/src/actions.ts
459
+ /** How often an interpolated drag reports a position. 16 ms is about one display frame. */
460
+ const MOVE_STEP_MS = 16;
461
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
462
+ function parsePointerAction(raw) {
463
+ if (!isRecord$1(raw)) throw invalidArgument("Pointer action must be an object.");
464
+ const duration = raw.duration;
465
+ if (duration !== void 0 && (typeof duration !== "number" || !(duration >= 0))) throw invalidArgument("Pointer action duration must be a non-negative number.");
466
+ switch (raw.type) {
467
+ case "pointerMove":
468
+ if (typeof raw.x !== "number" || typeof raw.y !== "number") throw invalidArgument("pointerMove needs numeric x and y.");
469
+ if (raw.origin !== void 0 && raw.origin !== "viewport") throw invalidArgument("Only the viewport pointer origin is supported.");
470
+ return {
471
+ type: "pointerMove",
472
+ x: raw.x,
473
+ y: raw.y,
474
+ ...duration === void 0 ? {} : { duration }
475
+ };
476
+ case "pointerDown":
477
+ case "pointerUp": return { type: raw.type };
478
+ case "pause": return {
479
+ type: "pause",
480
+ ...duration === void 0 ? {} : { duration }
481
+ };
482
+ default: throw invalidArgument(`Unsupported pointer action type: ${String(raw.type)}`);
483
+ }
484
+ }
485
+ /** The boundary: untrusted `POST /actions` body to typed sequences. */
486
+ function parseActions(body) {
487
+ if (!isRecord$1(body) || !Array.isArray(body.actions)) throw invalidArgument("Request body needs an \"actions\" array.");
488
+ return body.actions.map((raw) => {
489
+ if (!isRecord$1(raw) || typeof raw.id !== "string" || !Array.isArray(raw.actions)) throw invalidArgument("Each action sequence needs a string id and an actions array.");
490
+ if (raw.type === "pointer") {
491
+ const parameters = isRecord$1(raw.parameters) ? raw.parameters : void 0;
492
+ return {
493
+ type: "pointer",
494
+ id: raw.id,
495
+ ...parameters ? { parameters } : {},
496
+ actions: raw.actions.map(parsePointerAction)
497
+ };
498
+ }
499
+ if (raw.type === "key" || raw.type === "none" || raw.type === "wheel") return {
500
+ type: raw.type,
501
+ id: raw.id,
502
+ actions: raw.actions
503
+ };
504
+ throw invalidArgument(`Unsupported action source type: ${String(raw.type)}`);
505
+ });
506
+ }
507
+ function lerp(from, to, t) {
508
+ return {
509
+ x: from.x + (to.x - from.x) * t,
510
+ y: from.y + (to.y - from.y) * t
511
+ };
512
+ }
513
+ /**
514
+ * Flattens W3C pointer actions to the single-finger touch stream a simhid-style device takes.
515
+ *
516
+ * - The pointer starts at (0, 0), as in the spec, and `pointerMove` outside a press only
517
+ * repositions it, so a tap is `down` and `up` at the last position.
518
+ * - A timed drag becomes `move` steps every 16 ms, so the device sees a gesture with velocity
519
+ * rather than a jump after a wait.
520
+ * - A timed move outside a press becomes a `pause`.
521
+ * - Key, none and wheel sources are ignored here. A second pointer sequence is refused,
522
+ * because one touch point cannot play two fingers.
523
+ */
524
+ function toTouchEvents(sequences) {
525
+ const pointers = sequences.filter((sequence) => sequence.type === "pointer");
526
+ if (pointers.length > 1) throw unsupportedOperation("Multi-pointer actions are not supported by this touch backend.");
527
+ const pointer = pointers[0];
528
+ if (pointer?.type !== "pointer") return [];
529
+ const events = [];
530
+ let position = {
531
+ x: 0,
532
+ y: 0
533
+ };
534
+ let pressed = false;
535
+ for (const action of pointer.actions) switch (action.type) {
536
+ case "pointerMove": {
537
+ const target = {
538
+ x: action.x,
539
+ y: action.y
540
+ };
541
+ const duration = action.duration ?? 0;
542
+ if (!pressed) {
543
+ if (duration > 0) events.push({
544
+ kind: "pause",
545
+ ms: duration
546
+ });
547
+ } else if (duration <= MOVE_STEP_MS) events.push({
548
+ kind: "move",
549
+ at: target
550
+ });
551
+ else {
552
+ const steps = Math.ceil(duration / MOVE_STEP_MS);
553
+ for (let step = 1; step <= steps; step += 1) {
554
+ events.push({
555
+ kind: "pause",
556
+ ms: duration / steps
557
+ });
558
+ events.push({
559
+ kind: "move",
560
+ at: step === steps ? target : lerp(position, target, step / steps)
561
+ });
562
+ }
563
+ }
564
+ position = target;
565
+ break;
566
+ }
567
+ case "pointerDown":
568
+ if (!pressed) events.push({
569
+ kind: "down",
570
+ at: position
571
+ });
572
+ pressed = true;
573
+ break;
574
+ case "pointerUp":
575
+ if (pressed) events.push({
576
+ kind: "up",
577
+ at: position
578
+ });
579
+ pressed = false;
580
+ break;
581
+ case "pause": if ((action.duration ?? 0) > 0) events.push({
582
+ kind: "pause",
583
+ ms: action.duration ?? 0
584
+ });
585
+ }
586
+ return events;
587
+ }
588
+ //#endregion
589
+ //#region ../server/src/xcui-source.ts
590
+ const XML_ESCAPES = {
591
+ "&": "&amp;",
592
+ "<": "&lt;",
593
+ ">": "&gt;",
594
+ "\"": "&quot;",
595
+ "'": "&apos;",
596
+ "\n": "&#10;",
597
+ "\r": "&#13;",
598
+ " ": "&#9;"
599
+ };
600
+ function escapeAttribute(value) {
601
+ return value.replace(/[&<>"'\n\r\t]/g, (char) => XML_ESCAPES[char] ?? char);
602
+ }
603
+ function attributes(node) {
604
+ return [
605
+ ["type", node.type],
606
+ ["name", node.name],
607
+ ["label", node.label],
608
+ ["value", node.value],
609
+ ["enabled", String(node.enabled)],
610
+ ["visible", String(node.visible)],
611
+ ["x", String(node.frame.x)],
612
+ ["y", String(node.frame.y)],
613
+ ["width", String(node.frame.width)],
614
+ ["height", String(node.frame.height)]
615
+ ].flatMap(([key, value]) => value === void 0 ? [] : [`${key}="${escapeAttribute(value)}"`]).join(" ");
616
+ }
617
+ function element(node, depth) {
618
+ const indent = " ".repeat(depth);
619
+ const open = `${indent}<${node.type} ${attributes(node)}`;
620
+ if (node.children.length === 0) return `${open} />`;
621
+ return `${open}>\n${node.children.map((child) => element(child, depth + 1)).join("\n")}\n${indent}</${node.type}>`;
622
+ }
623
+ /**
624
+ * The XCUITest page source shape: an `AppiumAUT` wrapper around the element tree, one tag per
625
+ * element named by its XCUIElementType, with geometry as `x`, `y`, `width` and `height`.
626
+ * Absent `name`, `label` and `value` are omitted, as XCUITest omits null attributes.
627
+ */
628
+ function toXcuiSource(root) {
629
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<AppiumAUT>\n${element(root, 1)}\n</AppiumAUT>`;
630
+ }
631
+ //#endregion
632
+ //#region ../server/src/routes.ts
633
+ const SESSION_PREFIX = "/session/:sessionId";
634
+ /** Takes a zipped `.app` as the request body and answers the path it was unpacked to. */
635
+ const APP_UPLOAD_PATH = "/x86sim/apps";
636
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
637
+ function requireString(body, ...keys) {
638
+ if (isRecord(body)) for (const key of keys) {
639
+ const value = body[key];
640
+ if (typeof value === "string" && value.length > 0) return value;
641
+ }
642
+ throw invalidArgument(`Request body needs a string "${keys.join("\" or \"")}".`);
643
+ }
644
+ const HARDWARE_BUTTONS = {
645
+ home: "home",
646
+ volumeup: "volumeUp",
647
+ volumedown: "volumeDown"
648
+ };
649
+ /** The `mobile:` scripts of XCUITest that this server answers. Others are `unknown command`. */
650
+ const MOBILE_SCRIPTS = {
651
+ "mobile: pressButton": async (backend, args) => {
652
+ const button = HARDWARE_BUTTONS[String(args.name).toLowerCase()];
653
+ if (!button) throw invalidArgument(`Unsupported hardware button: ${String(args.name)}`);
654
+ await backend.pressButton(button);
655
+ return null;
656
+ },
657
+ "mobile: deepLink": async (backend, args) => {
658
+ await backend.openUrl(requireString(args, "url"));
659
+ return null;
660
+ },
661
+ "mobile: activateApp": async (backend, args) => {
662
+ await backend.launchApp(requireString(args, "bundleId", "appId"));
663
+ return null;
664
+ },
665
+ "mobile: terminateApp": async (backend, args) => {
666
+ await backend.terminateApp(requireString(args, "bundleId", "appId"));
667
+ return true;
668
+ }
669
+ };
670
+ function windowRect(backend) {
671
+ return backend.screen().then((size) => ({
672
+ x: 0,
673
+ y: 0,
674
+ ...size
675
+ }));
676
+ }
677
+ /** The WebDriver and Appium routes this server implements. */
678
+ function webDriverRoutes(backend, sessions, uploads) {
679
+ const inSession = (method, suffix, handler) => ({
680
+ method,
681
+ path: `${SESSION_PREFIX}${suffix}`,
682
+ handler
683
+ });
684
+ return [
685
+ {
686
+ method: "GET",
687
+ path: "/status",
688
+ handler: async () => ({
689
+ ready: true,
690
+ message: "x86sim-webdriver ready"
691
+ })
692
+ },
693
+ {
694
+ method: "POST",
695
+ path: APP_UPLOAD_PATH,
696
+ body: "bytes",
697
+ handler: async ({ body }) => {
698
+ try {
699
+ return { appPath: await uploads.stage(body) };
700
+ } catch (error) {
701
+ throw invalidArgument(error.message);
702
+ }
703
+ }
704
+ },
705
+ {
706
+ method: "POST",
707
+ path: "/session",
708
+ handler: async ({ body }) => {
709
+ if (sessions.current) throw sessionNotCreated(`Session ${sessions.current.id} is still active.`);
710
+ const requested = isRecord(body) && isRecord(body.capabilities) ? body.capabilities : {};
711
+ const alwaysMatch = isRecord(requested.alwaysMatch) ? requested.alwaysMatch : {};
712
+ const session = {
713
+ id: randomUUID(),
714
+ capabilities: {
715
+ ...alwaysMatch,
716
+ platformName: "iOS",
717
+ "appium:automationName": "XCUITest"
718
+ }
719
+ };
720
+ sessions.current = session;
721
+ return {
722
+ sessionId: session.id,
723
+ capabilities: session.capabilities
724
+ };
725
+ }
726
+ },
727
+ inSession("DELETE", "", async ({ params }) => {
728
+ if (sessions.current?.id === params.sessionId) sessions.current = void 0;
729
+ return null;
730
+ }),
731
+ inSession("GET", "/source", async () => toXcuiSource(await backend.accessibilityTree())),
732
+ inSession("GET", "/screenshot", async () => (await backend.screenshot()).toString("base64")),
733
+ inSession("GET", "/window/rect", async () => await windowRect(backend)),
734
+ inSession("POST", "/actions", async ({ body }) => {
735
+ const events = toTouchEvents(parseActions(body));
736
+ if (events.length > 0) await backend.touch(events);
737
+ return null;
738
+ }),
739
+ inSession("DELETE", "/actions", async () => null),
740
+ inSession("POST", "/keys", async ({ body }) => {
741
+ const value = isRecord(body) ? body.value : void 0;
742
+ if (!Array.isArray(value)) throw invalidArgument("Request body needs a \"value\" array.");
743
+ await backend.typeText(value.map(String).join(""));
744
+ return null;
745
+ }),
746
+ inSession("POST", "/appium/device/install_app", async ({ body }) => {
747
+ const appPath = requireString(body, "appPath");
748
+ try {
749
+ await backend.installApp(appPath);
750
+ } finally {
751
+ await uploads.release(appPath);
752
+ }
753
+ return null;
754
+ }),
755
+ inSession("POST", "/appium/device/activate_app", async ({ body }) => {
756
+ await backend.launchApp(requireString(body, "appId", "bundleId"));
757
+ return null;
758
+ }),
759
+ inSession("POST", "/appium/device/terminate_app", async ({ body }) => {
760
+ await backend.terminateApp(requireString(body, "appId", "bundleId"));
761
+ return true;
762
+ }),
763
+ inSession("POST", "/execute/sync", async ({ body }) => {
764
+ const script = requireString(body, "script");
765
+ const handler = MOBILE_SCRIPTS[script];
766
+ if (!handler) throw unknownCommand(`Unknown mobile command: ${script}`);
767
+ const args = isRecord(body) && Array.isArray(body.args) ? body.args[0] : void 0;
768
+ return await handler(backend, isRecord(args) ? args : {});
769
+ })
770
+ ];
771
+ }
772
+ function requireActiveSession(sessions, id) {
773
+ if (sessions.current?.id !== id) throw invalidSessionId(id);
774
+ return sessions.current;
775
+ }
776
+ //#endregion
777
+ export { invalidArgument as a, appArchive as c, isPhoneRunning as d, NotSetUpError as f, WebDriverError as i, createUploads as l, requireActiveSession as n, unknownCommand as o, webDriverRoutes as r, unknownError as s, APP_UPLOAD_PATH as t, discoverTarget as u };