@limrun/api 0.76.0 → 0.77.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +26 -1
  3. package/client.d.mts +3 -0
  4. package/client.d.mts.map +1 -1
  5. package/client.d.ts +3 -0
  6. package/client.d.ts.map +1 -1
  7. package/client.js +3 -0
  8. package/client.js.map +1 -1
  9. package/client.mjs +3 -0
  10. package/client.mjs.map +1 -1
  11. package/index.d.mts +1 -0
  12. package/index.d.mts.map +1 -1
  13. package/index.d.ts +1 -0
  14. package/index.d.ts.map +1 -1
  15. package/index.js +5 -2
  16. package/index.js.map +1 -1
  17. package/index.mjs +1 -0
  18. package/index.mjs.map +1 -1
  19. package/ios-argent.d.mts +63 -0
  20. package/ios-argent.d.mts.map +1 -0
  21. package/ios-argent.d.ts +63 -0
  22. package/ios-argent.d.ts.map +1 -0
  23. package/ios-argent.js +690 -0
  24. package/ios-argent.js.map +1 -0
  25. package/ios-argent.mjs +683 -0
  26. package/ios-argent.mjs.map +1 -0
  27. package/package.json +11 -1
  28. package/resources/analytics.d.mts +22 -2
  29. package/resources/analytics.d.mts.map +1 -1
  30. package/resources/analytics.d.ts +22 -2
  31. package/resources/analytics.d.ts.map +1 -1
  32. package/resources/analytics.js.map +1 -1
  33. package/resources/analytics.mjs.map +1 -1
  34. package/resources/index.d.mts +1 -0
  35. package/resources/index.d.mts.map +1 -1
  36. package/resources/index.d.ts +1 -0
  37. package/resources/index.d.ts.map +1 -1
  38. package/resources/index.js +3 -1
  39. package/resources/index.js.map +1 -1
  40. package/resources/index.mjs +1 -0
  41. package/resources/index.mjs.map +1 -1
  42. package/resources/macos-instances.d.mts +224 -0
  43. package/resources/macos-instances.d.mts.map +1 -0
  44. package/resources/macos-instances.d.ts +224 -0
  45. package/resources/macos-instances.d.ts.map +1 -0
  46. package/resources/macos-instances.js +51 -0
  47. package/resources/macos-instances.js.map +1 -0
  48. package/resources/macos-instances.mjs +47 -0
  49. package/resources/macos-instances.mjs.map +1 -0
  50. package/src/client.ts +19 -0
  51. package/src/index.ts +7 -0
  52. package/src/ios-argent.ts +789 -0
  53. package/src/resources/analytics.ts +22 -2
  54. package/src/resources/index.ts +8 -0
  55. package/src/resources/macos-instances.ts +296 -0
  56. package/src/version.ts +1 -1
  57. package/version.d.mts +1 -1
  58. package/version.d.ts +1 -1
  59. package/version.js +1 -1
  60. package/version.mjs +1 -1
package/ios-argent.mjs ADDED
@@ -0,0 +1,683 @@
1
+ import fs from 'fs';
2
+ import http from 'http';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import { WebSocketServer } from 'ws';
6
+ /**
7
+ * Mechanisms the provider descriptor grants Argent on the simulator. Each one
8
+ * is served by the bridge instead of a process on a local Mac.
9
+ */
10
+ export const ARGENT_PROVIDER_CAPABILITIES = ['simulator-server', 'simctl', 'ax-service'];
11
+ /**
12
+ * Offer this instance's simulator to a locally installed Argent through its
13
+ * device-provider contract.
14
+ *
15
+ * Argent expects a simulator on the same Mac: it runs `xcrun simctl`, attaches
16
+ * to a local simulator-server for input and screenshots, and spawns an
17
+ * accessibility daemon inside the simulator. The bridge stands in for all
18
+ * three, so an unmodified Argent drives the remote simulator:
19
+ *
20
+ * - a provider descriptor points Argent at a local HTTP and WebSocket server
21
+ * that speaks the simulator-server protocol,
22
+ * - an `xcrun` executable for PATH forwards simctl calls for this simulator,
23
+ * - the same executable answers the accessibility daemon's requests when
24
+ * Argent spawns it.
25
+ *
26
+ * The Argent tool-server must start with the returned `env`, because it
27
+ * resolves `xcrun` from its own PATH.
28
+ */
29
+ export async function startArgentBridge(client, options = {}) {
30
+ const udid = client.deviceInfo.udid;
31
+ const providerId = `limrun-${udid.slice(0, 8).toLowerCase()}`;
32
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'limrun-argent-'));
33
+ const mediaDir = path.join(workDir, 'media');
34
+ fs.mkdirSync(mediaDir);
35
+ const session = new BridgeSession(client, mediaDir);
36
+ const server = http.createServer((req, res) => void session.handleHttp(req, res));
37
+ const sockets = new WebSocketServer({ server, path: '/ws' });
38
+ sockets.on('connection', (socket) => {
39
+ socket.on('message', (raw) => {
40
+ void session.handleCommand(raw.toString()).then((reply) => socket.send(JSON.stringify(reply)));
41
+ });
42
+ });
43
+ const cleanup = async (descriptorPath) => {
44
+ if (descriptorPath)
45
+ fs.rmSync(descriptorPath, { force: true });
46
+ sockets.close();
47
+ await new Promise((resolve) => server.close(() => resolve()));
48
+ fs.rmSync(workDir, { recursive: true, force: true });
49
+ };
50
+ try {
51
+ await new Promise((resolve, reject) => {
52
+ server.once('error', reject);
53
+ server.listen(0, '127.0.0.1', () => {
54
+ server.off('error', reject);
55
+ resolve();
56
+ });
57
+ });
58
+ const address = server.address();
59
+ if (!address || typeof address === 'string') {
60
+ throw new Error('Failed to start the Argent bridge server.');
61
+ }
62
+ const baseUrl = `http://127.0.0.1:${address.port}`;
63
+ session.baseUrl = baseUrl;
64
+ const shimDir = path.join(workDir, 'bin');
65
+ fs.mkdirSync(shimDir);
66
+ const shimPath = path.join(shimDir, 'xcrun');
67
+ fs.writeFileSync(shimPath, xcrunShimSource({ baseUrl, device: simctlDevice(client.deviceInfo) }), 'utf8');
68
+ fs.chmodSync(shimPath, 0o755);
69
+ const providersDir = options.providersDir ?? path.join(os.homedir(), '.argent', 'providers');
70
+ fs.mkdirSync(providersDir, { recursive: true });
71
+ const descriptorPath = path.join(providersDir, `${providerId}.json`);
72
+ fs.writeFileSync(descriptorPath, JSON.stringify({
73
+ schemaVersion: 1,
74
+ id: providerId,
75
+ name: 'Limrun',
76
+ // Lets `argent providers prune` drop the descriptor if this process dies.
77
+ pid: process.pid,
78
+ supportUrl: 'https://docs.limrun.com',
79
+ devices: [
80
+ {
81
+ nativeId: udid,
82
+ platform: 'ios',
83
+ kind: 'simulator',
84
+ name: client.deviceInfo.model,
85
+ state: 'Booted',
86
+ capabilities: ARGENT_PROVIDER_CAPABILITIES,
87
+ // The contract requires streamUrl. The bridge serves no video stream.
88
+ simulatorServer: { apiUrl: baseUrl, streamUrl: `${baseUrl}/stream.mjpeg` },
89
+ },
90
+ ],
91
+ }, null, 2), 'utf8');
92
+ return {
93
+ deviceId: `ext:${providerId}:${udid}`,
94
+ descriptorPath,
95
+ env: { PATH: `${shimDir}${path.delimiter}${process.env['PATH'] ?? ''}` },
96
+ close: () => cleanup(descriptorPath),
97
+ };
98
+ }
99
+ catch (error) {
100
+ await cleanup();
101
+ throw error;
102
+ }
103
+ }
104
+ /** Keeps this many screenshots on disk; Argent reads each one right after the call. */
105
+ const MEDIA_FILES_KEPT = 32;
106
+ class BridgeSession {
107
+ constructor(client, mediaDir) {
108
+ this.client = client;
109
+ this.mediaDir = mediaDir;
110
+ this.baseUrl = '';
111
+ this.queue = [];
112
+ this.mediaFiles = [];
113
+ this.info = client.deviceInfo;
114
+ }
115
+ // ---- input ---------------------------------------------------------------
116
+ /**
117
+ * Runs actions in arrival order. Actions that arrive while a batch is on the
118
+ * wire go out together in the next one, so a typed word costs a few round
119
+ * trips instead of two per character.
120
+ */
121
+ enqueue(actions) {
122
+ const done = new Promise((resolve, reject) => this.queue.push({ actions, resolve, reject }));
123
+ this.draining ?? (this.draining = this.drain());
124
+ return done;
125
+ }
126
+ async drain() {
127
+ while (this.queue.length > 0) {
128
+ const batch = this.queue.splice(0);
129
+ try {
130
+ await this.client.performActions(batch.flatMap((entry) => entry.actions));
131
+ batch.forEach((entry) => entry.resolve());
132
+ }
133
+ catch (error) {
134
+ batch.forEach((entry) => entry.reject(asError(error)));
135
+ }
136
+ }
137
+ this.draining = undefined;
138
+ }
139
+ /**
140
+ * Keys and buttons are acknowledged before they reach the simulator, to keep
141
+ * Argent's own typing pace. A failure is reported on the next call instead.
142
+ */
143
+ enqueueUnacknowledged(actions) {
144
+ this.enqueue(actions).catch((error) => {
145
+ this.deferredError = error;
146
+ });
147
+ }
148
+ /** Reads wait for pending input, so a screenshot never overtakes a tap. */
149
+ async settled() {
150
+ while (this.draining)
151
+ await this.draining;
152
+ const error = this.deferredError;
153
+ this.deferredError = undefined;
154
+ if (error)
155
+ throw error;
156
+ }
157
+ screen() {
158
+ return {
159
+ width: this.info.displayWidth ?? this.info.screenWidth,
160
+ height: this.info.displayHeight ?? this.info.screenHeight,
161
+ };
162
+ }
163
+ touch(type, cmd) {
164
+ const { width, height } = this.screen();
165
+ const action = { type, x: Number(cmd['x']) * width, y: Number(cmd['y']) * height };
166
+ const secondX = cmd['second_x'];
167
+ const secondY = cmd['second_y'];
168
+ if (typeof secondX === 'number' && typeof secondY === 'number') {
169
+ return { ...action, x2: secondX * width, y2: secondY * height };
170
+ }
171
+ return action;
172
+ }
173
+ /** One simulator-server WebSocket command. Argent sends coordinates as 0..1 fractions. */
174
+ async handleCommand(raw) {
175
+ let cmd;
176
+ try {
177
+ cmd = JSON.parse(raw);
178
+ }
179
+ catch {
180
+ return { status: 'error', message: 'parse error: invalid JSON' };
181
+ }
182
+ try {
183
+ await this.runCommand(cmd);
184
+ return { id: String(cmd['id']), status: 'ok' };
185
+ }
186
+ catch (error) {
187
+ // simulator-server omits the id on a rejected command, and Argent matches on that.
188
+ return { status: 'error', message: asError(error).message };
189
+ }
190
+ }
191
+ async runCommand(cmd) {
192
+ const pressed = cmd['direction'] === 'Down';
193
+ switch (cmd['cmd']) {
194
+ case 'touch':
195
+ case 'edgeTouch': {
196
+ const now = Date.now();
197
+ if (cmd['type'] === 'Down') {
198
+ this.gesture = { actions: [this.touch('touchDown', cmd)], last: now };
199
+ return;
200
+ }
201
+ const gesture = this.gesture;
202
+ if (!gesture)
203
+ throw new Error(`touch ${String(cmd['type'])} arrived without a Down`);
204
+ // Argent paces a gesture by when it sends each event; replay that pace.
205
+ if (now > gesture.last)
206
+ gesture.actions.push({ type: 'wait', durationMs: now - gesture.last });
207
+ gesture.last = now;
208
+ if (cmd['type'] === 'Move') {
209
+ gesture.actions.push(this.touch('touchMove', cmd));
210
+ return;
211
+ }
212
+ gesture.actions.push(this.touch('touchUp', cmd));
213
+ this.gesture = undefined;
214
+ // The whole gesture goes out as one batch, and only its Up waits for it.
215
+ await this.enqueue(gesture.actions);
216
+ return;
217
+ }
218
+ case 'key':
219
+ // Argent sends USB HID keyboard usages, which is HID usage page 7.
220
+ this.enqueueUnacknowledged([
221
+ { type: pressed ? 'usageDown' : 'usageUp', usagePage: 7, usage: Number(cmd['code']) },
222
+ ]);
223
+ return;
224
+ case 'button': {
225
+ const button = ARGENT_BUTTONS[String(cmd['button'])];
226
+ if (!button)
227
+ throw new Error(`button ${String(cmd['button'])} is not supported on Limrun simulators`);
228
+ this.enqueueUnacknowledged([{ type: pressed ? 'buttonDown' : 'buttonUp', button }]);
229
+ return;
230
+ }
231
+ case 'rotate':
232
+ await this.settled();
233
+ await this.client.setOrientation(cmd['direction']);
234
+ this.info = await this.client.getDeviceInfo();
235
+ return;
236
+ case 'capture_on_demand':
237
+ return;
238
+ default:
239
+ throw new Error(`parse error: unknown variant \`${String(cmd['cmd'])}\``);
240
+ }
241
+ }
242
+ // ---- http ----------------------------------------------------------------
243
+ async handleHttp(req, res) {
244
+ const url = req.url ?? '/';
245
+ try {
246
+ if (req.method === 'GET' && url.startsWith('/media/')) {
247
+ // Serve only screenshots this bridge wrote and still keeps; anything
248
+ // else, a deleted screenshot included, is not found.
249
+ const name = url.slice('/media/'.length);
250
+ const file = this.mediaFiles.find((kept) => path.basename(kept) === name);
251
+ let image;
252
+ try {
253
+ if (!file)
254
+ throw new Error('not kept');
255
+ image = await fs.promises.readFile(file);
256
+ }
257
+ catch {
258
+ return sendJson(res, 404, { error: 'not found' });
259
+ }
260
+ res.writeHead(200, { 'content-type': 'image/png', 'content-length': image.length });
261
+ res.end(image);
262
+ return;
263
+ }
264
+ // Argent probes apiUrl to check that the provider is alive.
265
+ if (req.method === 'GET' && url === '/')
266
+ return sendJson(res, 200, { status: 'ok' });
267
+ if (req.method !== 'POST')
268
+ return sendJson(res, 404, { error: 'not found' });
269
+ const body = (await readJson(req));
270
+ if (url === '/api/screenshot')
271
+ return sendJson(res, 200, await this.screenshot(body));
272
+ if (url === '/api/pointer')
273
+ return sendJson(res, 200, { status: 'ok' });
274
+ if (url === '/api/clipboard/text') {
275
+ await this.settled();
276
+ const copied = await this.client
277
+ .simctl(['pbcopy', this.info.udid], { stdin: String(body['text'] ?? '') })
278
+ .wait();
279
+ return sendJson(res, 200, copied.code === 0 ? { status: 'ok' } : { error: copied.stderr });
280
+ }
281
+ if (url === '/xcrun')
282
+ return sendJson(res, 200, await this.simctl(body['args'] ?? []));
283
+ if (url === '/ax') {
284
+ return sendJson(res, 200, await this.accessibilityReply(String(body['command']), body['params']));
285
+ }
286
+ return sendJson(res, 404, { error: 'not found' });
287
+ }
288
+ catch (error) {
289
+ const message = asError(error).message;
290
+ // One body serves both callers: Argent reads `error`, the xcrun shim reads the rest.
291
+ sendJson(res, 200, { error: message, code: 1, stdout: '', stderr: `limrun: ${message}\n` });
292
+ }
293
+ }
294
+ async screenshot(body) {
295
+ await this.settled();
296
+ // Argent omits `scale` only when it wants native pixels. Every smaller
297
+ // scale gets the point-sized image, the nearest size the simulator serves.
298
+ const data = await this.client.screenshot({
299
+ format: 'png',
300
+ size: body['scale'] === undefined ? 'full' : 'scaled',
301
+ });
302
+ const name = `screenshot-${Date.now()}-${this.mediaFiles.length}.png`;
303
+ const file = path.join(this.mediaDir, name);
304
+ fs.writeFileSync(file, Buffer.from(data.base64, 'base64'));
305
+ this.mediaFiles.push(file);
306
+ while (this.mediaFiles.length > MEDIA_FILES_KEPT) {
307
+ fs.rmSync(this.mediaFiles.shift(), { force: true });
308
+ }
309
+ return { url: `${this.baseUrl}/media/${name}`, path: file };
310
+ }
311
+ // ---- simctl --------------------------------------------------------------
312
+ /** A simctl call for this simulator, as the xcrun shim forwards it (without `xcrun simctl`). */
313
+ async simctl(args) {
314
+ const udid = this.info.udid;
315
+ const command = args[0];
316
+ const rest = args.slice(args.indexOf(udid) + 1);
317
+ if (command === 'spawn') {
318
+ // Argent reads this flag to decide whether accessibility is degraded. It
319
+ // describes Argent's own daemon, which does not run here.
320
+ if (rest.join(' ') === 'defaults read com.apple.Accessibility IgnoreAXServerEntitlements') {
321
+ return { code: 0, stdout: '1\n', stderr: '' };
322
+ }
323
+ if (rest[0] === 'launchctl' && rest[1] === 'list') {
324
+ // Argent parses running apps out of `launchctl list`, which the
325
+ // simulator does not let callers run.
326
+ const running = (await this.client.listApps()).filter((app) => app.pid !== undefined);
327
+ const lines = running.map((app) => `${app.pid}\t0\tUIKitApplication:${app.bundleId}[0000][rb-legacy]`);
328
+ return { code: 0, stdout: ['PID\tStatus\tLabel', ...lines].join('\n') + '\n', stderr: '' };
329
+ }
330
+ }
331
+ await this.settled();
332
+ if (command === 'bootstatus')
333
+ return { code: 0, stdout: '', stderr: '' };
334
+ if (command === 'install') {
335
+ const appPath = rest[0];
336
+ if (!appPath)
337
+ return { code: 64, stdout: '', stderr: 'simctl install requires a local .app path.\n' };
338
+ await this.client.syncApp(appPath, { install: true, launchMode: 'None', watch: false });
339
+ return { code: 0, stdout: '', stderr: '' };
340
+ }
341
+ return await this.client.simctl(args).wait();
342
+ }
343
+ // ---- accessibility -------------------------------------------------------
344
+ /** The reply to one accessibility daemon request, as `{result}` or `{error}`. */
345
+ async accessibilityReply(command, params) {
346
+ try {
347
+ await this.settled();
348
+ return { result: await this.accessibility(command, (params ?? {})) };
349
+ }
350
+ catch (error) {
351
+ return { error: asError(error).message };
352
+ }
353
+ }
354
+ async accessibility(command, params) {
355
+ if (command === 'ping')
356
+ return { status: 'ok' };
357
+ if (command === 'live_panel')
358
+ return { displayId: null };
359
+ if (command === 'orientation') {
360
+ this.info = await this.client.getDeviceInfo();
361
+ return { interfaceOrientation: this.info.orientation ?? 'portrait', screenFrame: this.screen() };
362
+ }
363
+ if (command === 'fill' && params['check'] !== true) {
364
+ // Without a selector the simulator resolves the focused field itself.
365
+ try {
366
+ await this.client.setElementValue(String(params['text'] ?? ''));
367
+ }
368
+ catch {
369
+ throw new Error('no_focused_field');
370
+ }
371
+ return { verified: true };
372
+ }
373
+ if (!TREE_COMMANDS.has(command)) {
374
+ // Argent treats this code as "the daemon predates the command" and
375
+ // probes with it, so answer before reading the tree.
376
+ throw new Error('unknown_command');
377
+ }
378
+ const tree = await this.client.elementTree(undefined, { visibleOnly: true });
379
+ const screen = this.screen();
380
+ const base = {
381
+ alertVisible: someNode(tree, (node) => node.type === 'Alert' || node.type === 'Sheet'),
382
+ screenFrame: screen,
383
+ interfaceOrientation: this.info.orientation ?? 'portrait',
384
+ };
385
+ switch (command) {
386
+ case 'alert_check':
387
+ return { alertVisible: base.alertVisible };
388
+ case 'fill':
389
+ return { verified: someNode(tree, (node) => node.AXValue === params['text']) };
390
+ case 'foreground_app':
391
+ return { alertVisible: base.alertVisible, ...(await this.foregroundApp(tree)) };
392
+ case 'describe':
393
+ return { ...base, elements: toArgentElements(tree, screen) };
394
+ case 'tree': {
395
+ const app = await this.foregroundApp(tree);
396
+ return {
397
+ ...base,
398
+ nodes: toArgentTreeNodes(tree, screen, app.bundleId),
399
+ truncated: false,
400
+ ...(app.bundleId ? { foregroundApp: app.bundleId } : {}),
401
+ treeVersion: 1,
402
+ };
403
+ }
404
+ default:
405
+ throw new Error('unknown_command');
406
+ }
407
+ }
408
+ async foregroundApp(tree) {
409
+ const root = tree[0];
410
+ if (!root)
411
+ return {};
412
+ const apps = await this.client.listApps();
413
+ const app = apps.find((candidate) => candidate.pid === root.pid);
414
+ const name = root.AXLabel ?? app?.name;
415
+ return { ...(app ? { bundleId: app.bundleId } : {}), ...(name ? { name } : {}) };
416
+ }
417
+ }
418
+ /** The accessibility commands answered from the element tree. */
419
+ const TREE_COMMANDS = new Set(['alert_check', 'fill', 'foreground_app', 'describe', 'tree']);
420
+ const ARGENT_BUTTONS = {
421
+ home: 'home',
422
+ power: 'lock',
423
+ volumeUp: 'volumeUp',
424
+ volumeDown: 'volumeDown',
425
+ };
426
+ // Argent derives an element's role from these trait names.
427
+ const TRAIT_BY_TYPE = {
428
+ Button: 'button',
429
+ Cell: 'button',
430
+ Switch: 'button',
431
+ StaticText: 'staticText',
432
+ Heading: 'header',
433
+ Link: 'link',
434
+ Image: 'image',
435
+ TextField: 'textEntry',
436
+ SecureTextField: 'textEntry',
437
+ TextView: 'textEntry',
438
+ SearchField: 'searchField',
439
+ TabBar: 'tabBar',
440
+ Slider: 'adjustable',
441
+ };
442
+ const CONTAINER_TYPES = new Set([
443
+ 'Application',
444
+ 'Window',
445
+ 'Group',
446
+ 'Other',
447
+ 'ScrollView',
448
+ 'Table',
449
+ 'CollectionView',
450
+ ]);
451
+ /** The node's fields in Argent's shape, with the frame left out when it is empty. */
452
+ function toArgentFields(node, screen) {
453
+ const { x, y, width, height } = node.frame;
454
+ const traits = new Set(node.traits.map((trait) => trait.charAt(0).toLowerCase() + trait.slice(1)));
455
+ const fromType = TRAIT_BY_TYPE[node.type];
456
+ if (fromType)
457
+ traits.add(fromType);
458
+ if (!node.enabled)
459
+ traits.add('notEnabled');
460
+ const label = node.AXLabel ?? node.title;
461
+ return {
462
+ ...(label ? { label } : {}),
463
+ ...(node.help ? { hint: node.help } : {}),
464
+ // Argent expects frames as fractions of the screen. It treats a node without
465
+ // a frame as unframed, but hides a 0x0 frame together with its subtree.
466
+ ...(width > 0 && height > 0 ?
467
+ {
468
+ frame: {
469
+ x: x / screen.width,
470
+ y: y / screen.height,
471
+ width: width / screen.width,
472
+ height: height / screen.height,
473
+ },
474
+ }
475
+ : {}),
476
+ traits: [...traits],
477
+ ...(node.AXValue ? { value: node.AXValue } : {}),
478
+ ...(node.AXUniqueId ? { identifier: node.AXUniqueId } : {}),
479
+ };
480
+ }
481
+ /** One `describe` element; describe has no use for an element without a frame. */
482
+ function toArgentElement(node, screen) {
483
+ const fields = toArgentFields(node, screen);
484
+ return fields.frame ? { ...fields, frame: fields.frame } : undefined;
485
+ }
486
+ /** The flat element list behind Argent's `describe`: every node except unnamed containers. */
487
+ export function toArgentElements(tree, screen) {
488
+ const elements = [];
489
+ const visit = (nodes) => {
490
+ for (const node of nodes) {
491
+ const named = node.AXLabel || node.AXValue || node.title || node.AXUniqueId;
492
+ const element = CONTAINER_TYPES.has(node.type) && !named ? undefined : toArgentElement(node, screen);
493
+ if (element)
494
+ elements.push(element);
495
+ visit(node.children ?? []);
496
+ }
497
+ };
498
+ visit(tree);
499
+ return elements;
500
+ }
501
+ /** The nested tree behind Argent's `ui-tree`, in document order with parent links. */
502
+ export function toArgentTreeNodes(tree, screen, rootBundleId) {
503
+ const nodes = [];
504
+ const visit = (children, parentIndex) => {
505
+ for (const node of children) {
506
+ const index = nodes.length;
507
+ nodes.push({
508
+ index,
509
+ ...(parentIndex === undefined ?
510
+ rootBundleId ? { bundleId: rootBundleId }
511
+ : {}
512
+ : { parentIndex }),
513
+ ...toArgentFields(node, screen),
514
+ roleDescription: node.role_description,
515
+ });
516
+ visit(node.children ?? [], index);
517
+ }
518
+ };
519
+ visit(tree, undefined);
520
+ return nodes;
521
+ }
522
+ function someNode(tree, matches) {
523
+ return tree.some((node) => matches(node) || someNode(node.children ?? [], matches));
524
+ }
525
+ /** This simulator as an entry of `xcrun simctl list devices --json`. */
526
+ function simctlDevice(info) {
527
+ const version = (info.osVersion ?? '26.0').replace(/\./g, '-');
528
+ return {
529
+ runtime: `com.apple.CoreSimulator.SimRuntime.iOS-${version}`,
530
+ entry: {
531
+ udid: info.udid,
532
+ name: info.model,
533
+ state: 'Booted',
534
+ isAvailable: true,
535
+ deviceTypeIdentifier: `com.apple.CoreSimulator.SimDeviceType.${info.model.replace(/[^A-Za-z0-9]+/g, '-')}`,
536
+ },
537
+ };
538
+ }
539
+ // Argent execs this for every simctl call. It handles this simulator and hands
540
+ // every other call to the real xcrun, so local simulators and devices keep
541
+ // working beside the remote one. The Go SDK embeds the same script as
542
+ // websocket/ios/shim/argent-xcrun.js; keep the two identical.
543
+ const ARGENT_XCRUN_SHIM = `#!/usr/bin/env node
544
+ const fs = require('node:fs');
545
+ const http = require('node:http');
546
+ const net = require('node:net');
547
+ const { spawnSync } = require('node:child_process');
548
+
549
+ const bridgeUrl = process.env.LIMRUN_ARGENT_BRIDGE_URL;
550
+ const device = JSON.parse(process.env.LIMRUN_ARGENT_DEVICE || 'null');
551
+ const udid = device.entry.udid;
552
+ const realXcrun = process.env.LIMRUN_REAL_XCRUN || '/usr/bin/xcrun';
553
+ const hasRealXcrun = fs.existsSync(realXcrun);
554
+ const args = process.argv.slice(2);
555
+
556
+ function delegate() {
557
+ if (!hasRealXcrun) {
558
+ process.stderr.write('limrun xcrun shim: unsupported without Xcode: xcrun ' + args.join(' ') + '\\n');
559
+ process.exit(127);
560
+ }
561
+ const result = spawnSync(realXcrun, args, { stdio: 'inherit' });
562
+ process.exit(result.status ?? 1);
563
+ }
564
+
565
+ function post(route, body) {
566
+ return new Promise((resolve, reject) => {
567
+ const payload = JSON.stringify(body);
568
+ const req = http.request(bridgeUrl + route, {
569
+ method: 'POST',
570
+ headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
571
+ }, (res) => {
572
+ const chunks = [];
573
+ res.on('data', (chunk) => chunks.push(chunk));
574
+ res.on('end', () => {
575
+ try {
576
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
577
+ } catch (error) {
578
+ reject(error);
579
+ }
580
+ });
581
+ });
582
+ req.on('error', reject);
583
+ req.end(payload);
584
+ });
585
+ }
586
+
587
+ // \\\`simctl list devices --json\\\`: the local simulators plus the remote one.
588
+ function listDevices() {
589
+ let listing = { devices: {} };
590
+ if (hasRealXcrun) {
591
+ const real = spawnSync(realXcrun, args, { encoding: 'utf8' });
592
+ try {
593
+ listing = JSON.parse(real.stdout);
594
+ } catch {}
595
+ }
596
+ listing.devices = listing.devices || {};
597
+ listing.devices[device.runtime] = [...(listing.devices[device.runtime] || []), device.entry];
598
+ process.stdout.write(JSON.stringify(listing) + '\\n');
599
+ process.exit(0);
600
+ }
601
+
602
+ // Argent listens on a socket and spawns its accessibility daemon, which dials
603
+ // in. This process takes the daemon's place and answers from the bridge.
604
+ function accessibilityDaemon(endpoint) {
605
+ const socket = net.connect(endpoint);
606
+ let buffered = '';
607
+ socket.on('data', (chunk) => {
608
+ buffered += chunk.toString('utf8');
609
+ let end;
610
+ while ((end = buffered.indexOf('\\n')) >= 0) {
611
+ const line = buffered.slice(0, end).trim();
612
+ buffered = buffered.slice(end + 1);
613
+ if (!line) continue;
614
+ const { id, command, params } = JSON.parse(line);
615
+ post('/ax', { command, params })
616
+ .catch((error) => ({ error: String(error.message || error) }))
617
+ .then((reply) => socket.write(JSON.stringify({ id, ...reply }) + '\\n'));
618
+ }
619
+ });
620
+ socket.on('close', () => process.exit(0));
621
+ socket.on('error', (error) => {
622
+ process.stderr.write('limrun xcrun shim: ' + error.message + '\\n');
623
+ process.exit(1);
624
+ });
625
+ }
626
+
627
+ function main() {
628
+ if (args[0] !== 'simctl') return delegate();
629
+ // Argent scopes simctl to a device set; the remote simulator has none here.
630
+ const simctlArgs = args[1] === '--set' ? args.slice(3) : args.slice(1);
631
+ const command = simctlArgs[0];
632
+ const wantsJson = simctlArgs.includes('--json') || simctlArgs.includes('-j');
633
+ if (command === 'list' && simctlArgs[1] === 'devices' && wantsJson) return listDevices();
634
+ if (!simctlArgs.includes(udid)) return delegate();
635
+
636
+ if (command === 'spawn' && /(^|\\/)ax-service$/.test(simctlArgs[2] || '')) {
637
+ const socketAt = simctlArgs.indexOf('--socket');
638
+ const portAt = simctlArgs.indexOf('--port');
639
+ if (socketAt > 0) return accessibilityDaemon({ path: simctlArgs[socketAt + 1] });
640
+ if (portAt > 0) return accessibilityDaemon({ host: '127.0.0.1', port: Number(simctlArgs[portAt + 1]) });
641
+ }
642
+ post('/xcrun', { args: simctlArgs }).then((result) => {
643
+ if (result.stdout) process.stdout.write(result.stdout);
644
+ if (result.stderr) process.stderr.write(result.stderr);
645
+ process.exit(typeof result.code === 'number' ? result.code : 1);
646
+ }, (error) => {
647
+ process.stderr.write('limrun xcrun shim: ' + error.message + '\\n');
648
+ process.exit(1);
649
+ });
650
+ }
651
+
652
+ main();
653
+ `;
654
+ function xcrunShimSource(options) {
655
+ return ARGENT_XCRUN_SHIM.replace('const bridgeUrl = process.env.LIMRUN_ARGENT_BRIDGE_URL;', `const bridgeUrl = ${JSON.stringify(options.baseUrl)};`).replace("const device = JSON.parse(process.env.LIMRUN_ARGENT_DEVICE || 'null');", `const device = ${JSON.stringify(options.device)};`);
656
+ }
657
+ function asError(error) {
658
+ return error instanceof Error ? error : new Error(String(error));
659
+ }
660
+ function readJson(req) {
661
+ return new Promise((resolve, reject) => {
662
+ const chunks = [];
663
+ req.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
664
+ req.on('end', () => {
665
+ try {
666
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
667
+ }
668
+ catch (error) {
669
+ reject(error);
670
+ }
671
+ });
672
+ req.on('error', reject);
673
+ });
674
+ }
675
+ function sendJson(res, statusCode, payload) {
676
+ const body = JSON.stringify(payload);
677
+ res.writeHead(statusCode, {
678
+ 'content-type': 'application/json',
679
+ 'content-length': Buffer.byteLength(body),
680
+ });
681
+ res.end(body);
682
+ }
683
+ //# sourceMappingURL=ios-argent.mjs.map