spana-test 0.0.2 → 0.1.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.
Files changed (105) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +301 -0
  2. package/README.md +33 -4
  3. package/dist/agent/index.d.ts +81 -0
  4. package/dist/agent/index.js +21 -0
  5. package/dist/allure-PTTVORQ6.js +124 -0
  6. package/dist/allure-PTTVORQ6.js.map +1 -0
  7. package/dist/android-PAPJJWVN.js +34 -0
  8. package/dist/android-PAPJJWVN.js.map +1 -0
  9. package/dist/chunk-3FSZNKEF.js +62 -0
  10. package/dist/chunk-3FSZNKEF.js.map +1 -0
  11. package/dist/chunk-53MUJUJY.js +113 -0
  12. package/dist/chunk-53MUJUJY.js.map +1 -0
  13. package/dist/chunk-5XO6S7AI.js +134 -0
  14. package/dist/chunk-5XO6S7AI.js.map +1 -0
  15. package/dist/chunk-BZRLA4Z3.js +82 -0
  16. package/dist/chunk-BZRLA4Z3.js.map +1 -0
  17. package/dist/{chunk-VZZH66U5.js → chunk-CKJQX73M.js} +896 -844
  18. package/dist/chunk-CKJQX73M.js.map +1 -0
  19. package/dist/chunk-DGUM43GV.js +11 -0
  20. package/dist/chunk-DGUM43GV.js.map +1 -0
  21. package/dist/{chunk-CYEDLQJ4.js → chunk-GZK22EIE.js} +76 -102
  22. package/dist/chunk-GZK22EIE.js.map +1 -0
  23. package/dist/chunk-PANFRTIU.js +310 -0
  24. package/dist/chunk-PANFRTIU.js.map +1 -0
  25. package/dist/chunk-PWEOJKUF.js +473 -0
  26. package/dist/chunk-PWEOJKUF.js.map +1 -0
  27. package/dist/chunk-RJ5VPHVX.js +127 -0
  28. package/dist/chunk-RJ5VPHVX.js.map +1 -0
  29. package/dist/chunk-RK4Z6C7M.js +248 -0
  30. package/dist/chunk-RK4Z6C7M.js.map +1 -0
  31. package/dist/chunk-U564GCO2.js +259 -0
  32. package/dist/chunk-U564GCO2.js.map +1 -0
  33. package/dist/chunk-V62HFH6E.js +269 -0
  34. package/dist/chunk-V62HFH6E.js.map +1 -0
  35. package/dist/chunk-VDWWIVM6.js +303 -0
  36. package/dist/chunk-VDWWIVM6.js.map +1 -0
  37. package/dist/{discover-XIRJTZ7Z.js → chunk-WIJYK22K.js} +12 -5
  38. package/dist/{discover-XIRJTZ7Z.js.map → chunk-WIJYK22K.js.map} +1 -1
  39. package/dist/cli.js +134 -16
  40. package/dist/cli.js.map +1 -1
  41. package/dist/compiler-G75RIIYS.js +312 -0
  42. package/dist/compiler-G75RIIYS.js.map +1 -0
  43. package/dist/config-Dg9O0rcQ.d.ts +219 -0
  44. package/dist/config-loader-JJ5RPP53.js +9 -0
  45. package/dist/config-loader-JJ5RPP53.js.map +1 -0
  46. package/dist/console-FV4RJPO4.js +132 -0
  47. package/dist/console-FV4RJPO4.js.map +1 -0
  48. package/dist/discover-RWBKI5IB.js +14 -0
  49. package/dist/discover-RWBKI5IB.js.map +1 -0
  50. package/dist/element-CGteXiXB.d.ts +23 -0
  51. package/dist/flow-D-_tlLpp.d.ts +99 -0
  52. package/dist/gherkin/steps.d.ts +32 -0
  53. package/dist/gherkin/steps.js +39 -0
  54. package/dist/gherkin/steps.js.map +1 -0
  55. package/dist/{html-GRB34S6X.js → html-JP2HBIJQ.js} +54 -20
  56. package/dist/html-JP2HBIJQ.js.map +1 -0
  57. package/dist/index.d.ts +4 -157
  58. package/dist/index.js +36 -165
  59. package/dist/index.js.map +1 -1
  60. package/dist/init-command-CELKL2CX.js +105 -0
  61. package/dist/init-command-CELKL2CX.js.map +1 -0
  62. package/dist/installer-R6NX7BYQ.js +20 -0
  63. package/dist/installer-R6NX7BYQ.js.map +1 -0
  64. package/dist/ios-ZZU6DHH7.js +48 -0
  65. package/dist/ios-ZZU6DHH7.js.map +1 -0
  66. package/dist/{json-FK2NSRGC.js → json-JMRPUVY2.js} +2 -2
  67. package/dist/{junit-NAGZJOGQ.js → junit-UDY5JG22.js} +14 -3
  68. package/dist/junit-UDY5JG22.js.map +1 -0
  69. package/dist/provider-CUWPULGC.js +10 -0
  70. package/dist/provider-CUWPULGC.js.map +1 -0
  71. package/dist/redact-IDA3C4UH.js +77 -0
  72. package/dist/redact-IDA3C4UH.js.map +1 -0
  73. package/dist/runner-QEF6PJOE.js +20 -0
  74. package/dist/runner-QEF6PJOE.js.map +1 -0
  75. package/dist/server-MMK7PZIH.js +505 -0
  76. package/dist/server-MMK7PZIH.js.map +1 -0
  77. package/dist/session-FBJABNXL.js +16 -0
  78. package/dist/session-FBJABNXL.js.map +1 -0
  79. package/dist/studio-command-CDVPREMG.js +24 -0
  80. package/dist/studio-command-CDVPREMG.js.map +1 -0
  81. package/dist/test-command-SB5KYPQI.js +1929 -0
  82. package/dist/test-command-SB5KYPQI.js.map +1 -0
  83. package/dist/validator-CFQ55NUQ.js +13 -0
  84. package/dist/validator-CFQ55NUQ.js.map +1 -0
  85. package/package.json +41 -4
  86. package/studio-dist/assets/index-CPdpC9i-.css +1 -0
  87. package/studio-dist/assets/index-L1Wd0vop.js +183 -0
  88. package/studio-dist/index.html +13 -0
  89. package/dist/chunk-CYEDLQJ4.js.map +0 -1
  90. package/dist/chunk-PVNNKPBW.js +0 -64
  91. package/dist/chunk-PVNNKPBW.js.map +0 -1
  92. package/dist/chunk-VZZH66U5.js.map +0 -1
  93. package/dist/console-GPV3M3PC.js +0 -71
  94. package/dist/console-GPV3M3PC.js.map +0 -1
  95. package/dist/html-GRB34S6X.js.map +0 -1
  96. package/dist/junit-NAGZJOGQ.js.map +0 -1
  97. package/dist/runner-LBQUCG3K.js +0 -12
  98. package/dist/session-U7VP5J2C.js +0 -122
  99. package/dist/session-U7VP5J2C.js.map +0 -1
  100. package/dist/test-command-WPYLJYIK.js +0 -636
  101. package/dist/test-command-WPYLJYIK.js.map +0 -1
  102. package/dist/validator-J4YSBB66.js +0 -33
  103. package/dist/validator-J4YSBB66.js.map +0 -1
  104. /package/dist/{runner-LBQUCG3K.js.map → agent/index.js.map} +0 -0
  105. /package/dist/{json-FK2NSRGC.js.map → json-JMRPUVY2.js.map} +0 -0
@@ -1,4 +1,10 @@
1
- #!/usr/bin/env node
1
+ import {
2
+ DriverError
3
+ } from "./chunk-U564GCO2.js";
4
+ import {
5
+ allocatePort,
6
+ releasePort
7
+ } from "./chunk-RK4Z6C7M.js";
2
8
  import {
3
9
  adbClearApp,
4
10
  adbForceStop,
@@ -7,214 +13,155 @@ import {
7
13
  adbLaunchApp,
8
14
  adbOpenLink,
9
15
  adbShell,
10
- findADB,
16
+ findADB
17
+ } from "./chunk-GZK22EIE.js";
18
+ import {
11
19
  installedUrlSchemesOnSimulator,
12
20
  launchOnSimulator,
13
21
  launchWithUrlOnSimulator,
22
+ resetSimulatorKeychain,
14
23
  terminateOnSimulator
15
- } from "./chunk-CYEDLQJ4.js";
24
+ } from "./chunk-V62HFH6E.js";
16
25
 
17
- // src/smart/element-matcher.ts
18
- function flattenElements(root) {
19
- const result = [root];
20
- if (root.children) {
21
- for (const child of root.children) {
22
- result.push(...flattenElements(child));
23
- }
24
- }
25
- return result;
26
+ // src/drivers/playwright.ts
27
+ import { readFile, writeFile } from "fs/promises";
28
+ import { Effect, Layer } from "effect";
29
+ import {
30
+ chromium,
31
+ firefox,
32
+ webkit
33
+ } from "playwright-core";
34
+ var browserLaunchers = {
35
+ chromium,
36
+ firefox,
37
+ webkit
38
+ };
39
+ var browserLabels = {
40
+ chromium: "Chromium",
41
+ firefox: "Firefox",
42
+ webkit: "WebKit"
43
+ };
44
+ var CLEAR_STORAGE_SCRIPT = `
45
+ (() => {
46
+ try { localStorage.clear(); } catch {}
47
+ try { sessionStorage.clear(); } catch {}
48
+ })();
49
+ `;
50
+ function hasContentTypeHeader(headers) {
51
+ return Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
26
52
  }
27
- function matchesSelector(element, selector) {
28
- if (typeof selector === "string") {
29
- return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;
30
- }
31
- if ("testID" in selector) {
32
- return element.id === selector.testID;
33
- }
34
- if ("text" in selector) {
35
- return element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
53
+ function buildMockResponse(response) {
54
+ if (response.body !== void 0 && response.json !== void 0) {
55
+ throw new DriverError({
56
+ message: "mockNetwork() response cannot include both body and json."
57
+ });
36
58
  }
37
- if ("accessibilityLabel" in selector) {
38
- return element.accessibilityLabel === selector.accessibilityLabel;
59
+ const headers = { ...response.headers };
60
+ if (response.contentType && !hasContentTypeHeader(headers)) {
61
+ headers["content-type"] = response.contentType;
39
62
  }
40
- if ("point" in selector) {
41
- const { x, y } = selector.point;
42
- const b = element.bounds;
43
- return x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
63
+ if (response.json !== void 0) {
64
+ return {
65
+ status: response.status ?? 200,
66
+ json: response.json,
67
+ headers
68
+ };
44
69
  }
45
- return false;
46
- }
47
- function findElements(root, selector) {
48
- return flattenElements(root).filter((el) => matchesSelector(el, selector));
49
- }
50
- function isProbablyOnScreen(element) {
51
- const centerX = element.bounds.x + element.bounds.width / 2;
52
- const centerY = element.bounds.y + element.bounds.height / 2;
53
- return element.bounds.width > 0 && element.bounds.height > 0 && centerX >= 0 && centerY >= 0;
54
- }
55
- function findElement(root, selector) {
56
- const matches = findElements(root, selector).filter((el) => el.visible !== false);
57
- if (matches.length === 0) return void 0;
58
- const visibleMatches = matches.filter(isProbablyOnScreen);
59
- if (visibleMatches.length === 0) return void 0;
60
- const clickable = visibleMatches.filter((el) => el.clickable);
61
- if (clickable.length > 0) return clickable[clickable.length - 1];
62
- return visibleMatches[visibleMatches.length - 1];
63
- }
64
- function centerOf(element) {
65
70
  return {
66
- x: Math.round(element.bounds.x + element.bounds.width / 2),
67
- y: Math.round(element.bounds.y + element.bounds.height / 2)
71
+ status: response.status ?? 200,
72
+ body: response.body ?? "",
73
+ headers
68
74
  };
69
75
  }
70
-
71
- // src/drivers/playwright-parser.ts
72
- function rawNodeToElement(node) {
73
- const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
74
- return {
75
- ...node.id !== void 0 ? { id: node.id } : {},
76
- ...node.text !== void 0 ? { text: node.text } : {},
77
- ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
78
- // Use role as elementType when present, otherwise fall back to HTML tag name
79
- ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
80
- bounds: {
81
- x: node.bounds.x,
82
- y: node.bounds.y,
83
- width: node.bounds.width,
84
- height: node.bounds.height
85
- },
86
- ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
87
- ...node.visible !== void 0 ? { visible: node.visible } : {},
88
- ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
89
- ...children !== void 0 ? { children } : {}
90
- };
76
+ function toBytesPerSecond(kbps) {
77
+ if (kbps === void 0) {
78
+ return -1;
79
+ }
80
+ return Math.max(Math.round(kbps * 1024 / 8), 0);
91
81
  }
92
- function parseWebHierarchy(json) {
93
- const raw = JSON.parse(json);
94
- return rawNodeToElement(raw);
82
+ function requiresChromiumThrottling(conditions) {
83
+ return conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
95
84
  }
96
-
97
- // src/drivers/playwright.ts
98
- import { Effect, Layer } from "effect";
99
- import { chromium } from "playwright-core";
100
-
101
- // src/errors.ts
102
- import { Schema } from "effect";
103
- var ElementNotFoundError = class extends Schema.TaggedError()(
104
- "ElementNotFoundError",
105
- {
106
- message: Schema.String,
107
- selector: Schema.Unknown,
108
- timeoutMs: Schema.optional(Schema.Number)
109
- }
110
- ) {
111
- };
112
- var TextMismatchError = class extends Schema.TaggedError()(
113
- "TextMismatchError",
114
- {
115
- message: Schema.String,
116
- expected: Schema.String,
117
- actual: Schema.optional(Schema.String),
118
- selector: Schema.Unknown
119
- }
120
- ) {
121
- };
122
- var TimeoutError = class extends Schema.TaggedError()(
123
- "TimeoutError",
124
- {
125
- message: Schema.String,
126
- operation: Schema.String,
127
- timeoutMs: Schema.Number
128
- }
129
- ) {
130
- };
131
- var WaitTimeoutError = class extends Schema.TaggedError()(
132
- "WaitTimeoutError",
133
- {
134
- message: Schema.String,
135
- selector: Schema.Unknown,
136
- timeoutMs: Schema.Number
137
- }
138
- ) {
139
- };
140
- var DriverError = class extends Schema.TaggedError()(
141
- "DriverError",
142
- {
143
- message: Schema.String,
144
- command: Schema.optional(Schema.String),
145
- exitCode: Schema.optional(Schema.Number),
146
- stdout: Schema.optional(Schema.String),
147
- stderr: Schema.optional(Schema.String)
148
- }
149
- ) {
150
- };
151
- var DeviceDisconnectedError = class extends Schema.TaggedError()(
152
- "DeviceDisconnectedError",
153
- {
154
- message: Schema.String,
155
- deviceId: Schema.optional(Schema.String),
156
- platform: Schema.optional(Schema.String)
157
- }
158
- ) {
159
- };
160
- var AppCrashedError = class extends Schema.TaggedError()(
161
- "AppCrashedError",
162
- {
163
- message: Schema.String,
164
- appId: Schema.optional(Schema.String),
165
- platform: Schema.optional(Schema.String)
166
- }
167
- ) {
168
- };
169
- var AppNotInstalledError = class extends Schema.TaggedError()(
170
- "AppNotInstalledError",
171
- {
172
- message: Schema.String,
173
- appId: Schema.String,
174
- platform: Schema.optional(Schema.String)
175
- }
176
- ) {
177
- };
178
- var FlowSyntaxError = class extends Schema.TaggedError()(
179
- "FlowSyntaxError",
180
- {
181
- message: Schema.String,
182
- filePath: Schema.String
183
- }
184
- ) {
185
- };
186
- var DeviceNotFoundError = class extends Schema.TaggedError()(
187
- "DeviceNotFoundError",
188
- {
189
- message: Schema.String,
190
- platform: Schema.optional(Schema.String),
191
- deviceId: Schema.optional(Schema.String)
192
- }
193
- ) {
194
- };
195
- var ConfigError = class extends Schema.TaggedError()(
196
- "ConfigError",
197
- {
198
- message: Schema.String,
199
- filePath: Schema.optional(Schema.String)
85
+ function currentPageUrl(page) {
86
+ try {
87
+ return page.url();
88
+ } catch {
89
+ return "about:blank";
200
90
  }
201
- ) {
202
- };
203
-
204
- // src/drivers/raw-driver.ts
205
- import { Context } from "effect";
206
- var RawDriver = class extends Context.Tag("RawDriver")() {
207
- };
208
-
209
- // src/drivers/playwright.ts
91
+ }
210
92
  function makePlaywrightDriver(config) {
211
93
  return Effect.gen(function* () {
94
+ const browserName = config.browser ?? "chromium";
212
95
  const browser = yield* Effect.tryPromise({
213
- try: () => chromium.launch({ headless: config.headless ?? true }),
96
+ try: () => browserLaunchers[browserName].launch({ headless: config.headless ?? true }),
214
97
  catch: (e) => new DriverError({ message: `Failed to launch browser: ${e}` })
215
98
  });
216
- const page = yield* Effect.tryPromise({
217
- try: () => browser.newPage(),
99
+ let context;
100
+ let page;
101
+ let cdpSession;
102
+ const routeDefinitions = [];
103
+ let appliedRoutes = [];
104
+ let currentNetworkConditions = {};
105
+ const clearStorage = async () => {
106
+ await context.clearCookies();
107
+ await page.evaluate(CLEAR_STORAGE_SCRIPT);
108
+ };
109
+ const applyNetworkConditions = async () => {
110
+ if (browserName !== "chromium" && requiresChromiumThrottling(currentNetworkConditions)) {
111
+ throw new DriverError({
112
+ message: "setNetworkConditions() latency and throughput controls are only supported with the chromium browser. Use offline mode only for firefox or webkit."
113
+ });
114
+ }
115
+ await context.setOffline(currentNetworkConditions.offline ?? false);
116
+ const shouldUseCDP = browserName === "chromium" && (requiresChromiumThrottling(currentNetworkConditions) || cdpSession !== void 0);
117
+ if (!shouldUseCDP) {
118
+ return;
119
+ }
120
+ const session = cdpSession ?? (cdpSession = await context.newCDPSession(page));
121
+ await session.send("Network.enable");
122
+ await session.send("Network.emulateNetworkConditions", {
123
+ offline: currentNetworkConditions.offline ?? false,
124
+ latency: currentNetworkConditions.latencyMs ?? 0,
125
+ downloadThroughput: toBytesPerSecond(currentNetworkConditions.downloadThroughputKbps),
126
+ uploadThroughput: toBytesPerSecond(currentNetworkConditions.uploadThroughputKbps)
127
+ });
128
+ };
129
+ const applyRouteDefinition = async (definition) => {
130
+ const handler = definition.kind === "mock" ? async (route) => {
131
+ await route.fulfill(buildMockResponse(definition.response));
132
+ } : async (route) => {
133
+ await route.abort();
134
+ };
135
+ await context.route(definition.matcher, handler);
136
+ appliedRoutes.push({ matcher: definition.matcher, handler });
137
+ };
138
+ const reapplyRoutes = async () => {
139
+ appliedRoutes = [];
140
+ for (const definition of routeDefinitions) {
141
+ await applyRouteDefinition(definition);
142
+ }
143
+ };
144
+ const createContextAndPage = async (storageStatePath) => {
145
+ context = await browser.newContext(
146
+ storageStatePath ? { storageState: storageStatePath } : void 0
147
+ );
148
+ page = await context.newPage();
149
+ cdpSession = void 0;
150
+ await reapplyRoutes();
151
+ await applyNetworkConditions();
152
+ };
153
+ const replaceContext = async (storageStatePath) => {
154
+ const previousContext = context;
155
+ const previousPage = page;
156
+ const url = currentPageUrl(page);
157
+ await createContextAndPage(storageStatePath);
158
+ if (url && url !== "about:blank") {
159
+ await page.goto(url);
160
+ }
161
+ await Promise.allSettled([previousPage.close(), previousContext.close()]);
162
+ };
163
+ yield* Effect.tryPromise({
164
+ try: () => createContextAndPage(config.storageState),
218
165
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
219
166
  });
220
167
  const service = {
@@ -312,10 +259,7 @@ function makePlaywrightDriver(config) {
312
259
  const steps = Math.max(Math.round(duration / 16), 5);
313
260
  for (let i = 1; i <= steps; i++) {
314
261
  const t = i / steps;
315
- await page.mouse.move(
316
- startX + (endX - startX) * t,
317
- startY + (endY - startY) * t
318
- );
262
+ await page.mouse.move(startX + (endX - startX) * t, startY + (endY - startY) * t);
319
263
  }
320
264
  await page.mouse.up();
321
265
  },
@@ -342,8 +286,8 @@ function makePlaywrightDriver(config) {
342
286
  const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
343
287
  return {
344
288
  platform: "web",
345
- deviceId: "playwright-chromium",
346
- name: "Chromium",
289
+ deviceId: `playwright-${browserName}`,
290
+ name: browserLabels[browserName],
347
291
  isEmulator: false,
348
292
  screenWidth: viewport.width,
349
293
  screenHeight: viewport.height,
@@ -353,8 +297,12 @@ function makePlaywrightDriver(config) {
353
297
  catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
354
298
  }),
355
299
  launchApp: (url, opts) => Effect.tryPromise({
356
- try: () => page.goto(opts?.deepLink || url || config.baseUrl || "about:blank").then(() => {
357
- }),
300
+ try: async () => {
301
+ if (opts?.clearState) {
302
+ await clearStorage();
303
+ }
304
+ await page.goto(opts?.deepLink || url || config.baseUrl || "about:blank");
305
+ },
358
306
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
359
307
  }),
360
308
  stopApp: (_id) => Effect.tryPromise({
@@ -363,14 +311,14 @@ function makePlaywrightDriver(config) {
363
311
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
364
312
  }),
365
313
  killApp: (_id) => Effect.tryPromise({
366
- try: () => page.close().then(() => {
367
- }),
314
+ try: async () => {
315
+ await Promise.allSettled([page.close(), context.close(), browser.close()]);
316
+ },
368
317
  catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
369
318
  }),
370
319
  clearAppState: (_id) => Effect.tryPromise({
371
320
  try: async () => {
372
- await page.context().clearCookies();
373
- await page.evaluate(`localStorage.clear(); sessionStorage.clear();`);
321
+ await clearStorage();
374
322
  },
375
323
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
376
324
  }),
@@ -383,233 +331,123 @@ function makePlaywrightDriver(config) {
383
331
  try: () => page.goBack().then(() => {
384
332
  }),
385
333
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
334
+ }),
335
+ evaluate: (script, ...args) => Effect.tryPromise({
336
+ try: () => page.evaluate(script, ...args),
337
+ catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
338
+ }),
339
+ mockNetwork: (matcher, response) => Effect.tryPromise({
340
+ try: async () => {
341
+ buildMockResponse(response);
342
+ const definition = { kind: "mock", matcher, response };
343
+ routeDefinitions.push(definition);
344
+ await applyRouteDefinition(definition);
345
+ },
346
+ catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
347
+ }),
348
+ blockNetwork: (matcher) => Effect.tryPromise({
349
+ try: async () => {
350
+ const definition = { kind: "block", matcher };
351
+ routeDefinitions.push(definition);
352
+ await applyRouteDefinition(definition);
353
+ },
354
+ catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
355
+ }),
356
+ clearNetworkMocks: () => Effect.tryPromise({
357
+ try: async () => {
358
+ for (const appliedRoute of appliedRoutes) {
359
+ await context.unroute(appliedRoute.matcher, appliedRoute.handler);
360
+ }
361
+ appliedRoutes = [];
362
+ routeDefinitions.length = 0;
363
+ },
364
+ catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
365
+ }),
366
+ setNetworkConditions: (conditions) => Effect.tryPromise({
367
+ try: async () => {
368
+ currentNetworkConditions = { ...conditions };
369
+ await applyNetworkConditions();
370
+ },
371
+ catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
372
+ }),
373
+ saveCookies: (path) => Effect.tryPromise({
374
+ try: async () => {
375
+ const cookies = await context.cookies();
376
+ await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
377
+ },
378
+ catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
379
+ }),
380
+ loadCookies: (path) => Effect.tryPromise({
381
+ try: async () => {
382
+ const contents = await readFile(path, "utf8");
383
+ const cookies = JSON.parse(contents);
384
+ if (!Array.isArray(cookies)) {
385
+ throw new Error("Cookie file must contain an array of cookies.");
386
+ }
387
+ await context.addCookies(cookies);
388
+ },
389
+ catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
390
+ }),
391
+ saveAuthState: (path) => Effect.tryPromise({
392
+ try: () => context.storageState({ path }).then(() => {
393
+ }),
394
+ catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
395
+ }),
396
+ loadAuthState: (path) => Effect.tryPromise({
397
+ try: async () => {
398
+ await replaceContext(path);
399
+ },
400
+ catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
386
401
  })
387
402
  };
388
403
  return service;
389
404
  });
390
405
  }
391
406
 
392
- // src/drivers/uiautomator2/pagesource.ts
393
- function parseBounds(s) {
394
- const normalized = s.replace("][", ",").replace(/[[\]]/g, "");
395
- const parts = normalized.split(",");
396
- if (parts.length !== 4) {
397
- return { x: 0, y: 0, width: 0, height: 0 };
398
- }
399
- const x1 = parseInt(parts[0], 10);
400
- const y1 = parseInt(parts[1], 10);
401
- const x2 = parseInt(parts[2], 10);
402
- const y2 = parseInt(parts[3], 10);
403
- return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
404
- }
405
- function stripResourceIdPrefix(resourceId) {
406
- const colonSlash = resourceId.indexOf(":id/");
407
- if (colonSlash !== -1) {
408
- return resourceId.slice(colonSlash + 4);
409
- }
410
- return resourceId;
411
- }
412
- function parseAttributes(tagContent) {
413
- const attrs = {};
414
- const re = /([\w-]+)="([^"]*)"/g;
415
- let m;
416
- while ((m = re.exec(tagContent)) !== null) {
417
- attrs[m[1]] = m[2];
418
- }
419
- return attrs;
420
- }
421
- function tokenizeXML(xml) {
422
- let pos = 0;
423
- function skipWhitespace() {
424
- while (pos < xml.length && /\s/.test(xml[pos])) pos++;
407
+ // src/drivers/uiautomator2/driver.ts
408
+ import { Effect as Effect2 } from "effect";
409
+
410
+ // src/drivers/uiautomator2/client.ts
411
+ var UiAutomator2Client = class {
412
+ baseUrl;
413
+ sessionId = null;
414
+ constructor(host, port) {
415
+ this.baseUrl = `http://${host}:${port}`;
425
416
  }
426
- function parseNode() {
427
- skipWhitespace();
428
- if (pos >= xml.length) return null;
429
- if (xml[pos] !== "<") return null;
430
- pos++;
431
- if (xml[pos] === "?" || xml[pos] === "!") {
432
- const close = xml.indexOf(">", pos);
433
- if (close === -1) return null;
434
- pos = close + 1;
435
- return null;
436
- }
437
- if (xml[pos] === "/") {
438
- const close = xml.indexOf(">", pos);
439
- if (close === -1) return null;
440
- pos = close + 1;
441
- return null;
417
+ // ---------------------------------------------------------------------------
418
+ // HTTP helpers
419
+ // ---------------------------------------------------------------------------
420
+ async request(method, path, body) {
421
+ const url = `${this.baseUrl}${path}`;
422
+ const init = {
423
+ method,
424
+ headers: { "Content-Type": "application/json" }
425
+ };
426
+ if (body !== void 0) {
427
+ init.body = JSON.stringify(body);
442
428
  }
443
- const tagStart = pos;
444
- while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
445
- const tagName = xml.slice(tagStart, pos);
446
- const tagBodyStart = pos;
447
- let selfClosing = false;
448
- let inQuote = false;
449
- let quoteChar = "";
450
- while (pos < xml.length) {
451
- const ch = xml[pos];
452
- if (inQuote) {
453
- if (ch === quoteChar) inQuote = false;
454
- } else {
455
- if (ch === '"' || ch === "'") {
456
- inQuote = true;
457
- quoteChar = ch;
458
- } else if (ch === "/" && xml[pos + 1] === ">") {
459
- selfClosing = true;
460
- pos += 2;
461
- break;
462
- } else if (ch === ">") {
463
- pos++;
464
- break;
465
- }
466
- }
467
- pos++;
429
+ const res = await fetch(url, init);
430
+ const text = await res.text();
431
+ let parsed;
432
+ try {
433
+ parsed = JSON.parse(text);
434
+ } catch {
435
+ throw new Error(`UiAutomator2: failed to parse response: ${text}`);
468
436
  }
469
- const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
470
- const attrs = parseAttributes(tagBody);
471
- if (!attrs["class"]) {
472
- attrs["class"] = tagName;
437
+ if (!res.ok) {
438
+ const val = parsed.value;
439
+ const msg = val?.message ?? val?.error ?? text;
440
+ throw new Error(`UiAutomator2 ${method} ${path} \u2192 ${res.status}: ${msg}`);
473
441
  }
474
- const node = { attrs, children: [] };
475
- if (!selfClosing) {
476
- while (pos < xml.length) {
477
- skipWhitespace();
478
- if (pos >= xml.length) break;
479
- if (xml[pos] === "<" && xml[pos + 1] === "/") {
480
- const close = xml.indexOf(">", pos);
481
- if (close !== -1) pos = close + 1;
482
- break;
483
- }
484
- const child = parseNode();
485
- if (child !== null) {
486
- node.children.push(child);
487
- }
488
- }
442
+ if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
443
+ const val = parsed.value;
444
+ throw new Error(`UiAutomator2 error: ${val.message ?? val.error}`);
489
445
  }
490
- return node;
446
+ return parsed.value;
491
447
  }
492
- const roots = [];
493
- while (pos < xml.length) {
494
- skipWhitespace();
495
- if (pos >= xml.length) break;
496
- if (xml[pos] !== "<") {
497
- pos++;
498
- continue;
499
- }
500
- const peek = pos + 1;
501
- let nameEnd = peek;
502
- while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
503
- const peekName = xml.slice(peek, nameEnd);
504
- if (peekName === "hierarchy") {
505
- const close = xml.indexOf(">", pos);
506
- if (close === -1) break;
507
- pos = close + 1;
508
- continue;
509
- }
510
- if (peekName === "/hierarchy") {
511
- const close = xml.indexOf(">", pos);
512
- if (close !== -1) pos = close + 1;
513
- break;
514
- }
515
- if (peekName.startsWith("?") || peekName.startsWith("!")) {
516
- const close = xml.indexOf(">", pos);
517
- if (close !== -1) pos = close + 1;
518
- continue;
519
- }
520
- const node = parseNode();
521
- if (node !== null) {
522
- roots.push(node);
523
- }
524
- }
525
- return roots;
526
- }
527
- function rawNodeToElement2(node) {
528
- const a = node.attrs;
529
- const rawId = a["resource-id"] ?? "";
530
- const id = rawId ? stripResourceIdPrefix(rawId) : void 0;
531
- const text = a["text"] || void 0;
532
- const accessibilityLabel = a["content-desc"] || void 0;
533
- const elementType = a["class"] || void 0;
534
- const boundsStr = a["bounds"] ?? "[0,0][0,0]";
535
- const bounds = parseBounds(boundsStr);
536
- const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
537
- const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
538
- const clickable = a["clickable"] !== void 0 ? a["clickable"] === "true" : void 0;
539
- const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
540
- return {
541
- ...id !== void 0 ? { id } : {},
542
- ...text !== void 0 ? { text } : {},
543
- ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
544
- ...elementType !== void 0 ? { elementType } : {},
545
- bounds,
546
- ...enabled !== void 0 ? { enabled } : {},
547
- ...focused !== void 0 ? { focused } : {},
548
- ...clickable !== void 0 ? { clickable } : {},
549
- ...children !== void 0 ? { children } : {}
550
- };
551
- }
552
- function parseAndroidHierarchy(xml) {
553
- const roots = tokenizeXML(xml);
554
- if (roots.length === 0) {
555
- throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
556
- }
557
- if (roots.length === 1) {
558
- return rawNodeToElement2(roots[0]);
559
- }
560
- return {
561
- elementType: "hierarchy",
562
- bounds: { x: 0, y: 0, width: 0, height: 0 },
563
- children: roots.map(rawNodeToElement2)
564
- };
565
- }
566
-
567
- // src/drivers/uiautomator2/driver.ts
568
- import { Effect as Effect2 } from "effect";
569
-
570
- // src/drivers/uiautomator2/client.ts
571
- var UiAutomator2Client = class {
572
- baseUrl;
573
- sessionId = null;
574
- constructor(host, port) {
575
- this.baseUrl = `http://${host}:${port}`;
576
- }
577
- // ---------------------------------------------------------------------------
578
- // HTTP helpers
579
- // ---------------------------------------------------------------------------
580
- async request(method, path, body) {
581
- const url = `${this.baseUrl}${path}`;
582
- const init = {
583
- method,
584
- headers: { "Content-Type": "application/json" }
585
- };
586
- if (body !== void 0) {
587
- init.body = JSON.stringify(body);
588
- }
589
- const res = await fetch(url, init);
590
- const text = await res.text();
591
- let parsed;
592
- try {
593
- parsed = JSON.parse(text);
594
- } catch {
595
- throw new Error(`UiAutomator2: failed to parse response: ${text}`);
596
- }
597
- if (!res.ok) {
598
- const val = parsed.value;
599
- const msg = val?.message ?? val?.error ?? text;
600
- throw new Error(`UiAutomator2 ${method} ${path} \u2192 ${res.status}: ${msg}`);
601
- }
602
- if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
603
- const val = parsed.value;
604
- throw new Error(
605
- `UiAutomator2 error: ${val.message ?? val.error}`
606
- );
607
- }
608
- return parsed.value;
609
- }
610
- sessionPath(path) {
611
- if (this.sessionId === null) {
612
- throw new Error("UiAutomator2: no active session");
448
+ sessionPath(path) {
449
+ if (this.sessionId === null) {
450
+ throw new Error("UiAutomator2: no active session");
613
451
  }
614
452
  return `/session/${this.sessionId}${path}`;
615
453
  }
@@ -638,9 +476,7 @@ var UiAutomator2Client = class {
638
476
  }
639
477
  if (!res.ok) {
640
478
  const val = parsed["value"];
641
- throw new Error(
642
- `UiAutomator2: failed to create session: ${val?.message ?? text}`
643
- );
479
+ throw new Error(`UiAutomator2: failed to create session: ${val?.message ?? text}`);
644
480
  }
645
481
  let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
646
482
  if (!sessionId) {
@@ -759,6 +595,21 @@ var UiAutomator2Client = class {
759
595
  appId: appPackage
760
596
  });
761
597
  }
598
+ // ---------------------------------------------------------------------------
599
+ // WebView / hybrid context switching
600
+ // ---------------------------------------------------------------------------
601
+ async getContexts() {
602
+ return this.request("GET", this.sessionPath("/contexts"));
603
+ }
604
+ async getCurrentContext() {
605
+ return this.request("GET", this.sessionPath("/context"));
606
+ }
607
+ async setContext(contextId) {
608
+ await this.request("POST", this.sessionPath("/context"), { name: contextId });
609
+ }
610
+ async executeScript(script, args = []) {
611
+ return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
612
+ }
762
613
  };
763
614
 
764
615
  // src/drivers/uiautomator2/driver.ts
@@ -841,15 +692,45 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
841
692
  // -----------------------------------------------------------------------
842
693
  // App lifecycle
843
694
  // -----------------------------------------------------------------------
844
- launchApp: (bundleId, _opts) => Effect2.tryPromise({
695
+ launchApp: (bundleId, opts) => Effect2.tryPromise({
845
696
  try: async () => {
846
- adbForceStop(serial, bundleId);
847
- if (_opts?.deepLink) {
848
- adbOpenLink(serial, _opts.deepLink, bundleId);
697
+ if (opts?.clearState) {
698
+ adbClearApp(serial, bundleId);
699
+ }
700
+ if (opts?.clearKeychain) {
701
+ console.warn("clearKeychain is not supported on Android, skipping.");
702
+ }
703
+ if (opts?.deepLink) {
704
+ adbOpenLink(serial, opts.deepLink, bundleId);
705
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
849
706
  } else {
850
- adbLaunchApp(serial, bundleId);
707
+ adbForceStop(serial, bundleId);
708
+ if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
709
+ const { execFileSync } = await import("child_process");
710
+ const { findADB: findADB2 } = await import("./android-PAPJJWVN.js");
711
+ const adb = findADB2();
712
+ if (!adb) throw new Error("adb not found");
713
+ const startArgs = [
714
+ "-s",
715
+ serial,
716
+ "shell",
717
+ "am",
718
+ "start",
719
+ "-a",
720
+ "android.intent.action.MAIN",
721
+ "-c",
722
+ "android.intent.category.LAUNCHER",
723
+ bundleId
724
+ ];
725
+ for (const [k, v] of Object.entries(opts.launchArguments)) {
726
+ startArgs.push("--es", k, String(v));
727
+ }
728
+ execFileSync(adb, startArgs, { stdio: "ignore" });
729
+ } else {
730
+ adbLaunchApp(serial, bundleId);
731
+ }
851
732
  }
852
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
733
+ await new Promise((resolve2) => setTimeout(resolve2, 1e3));
853
734
  },
854
735
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
855
736
  }),
@@ -878,7 +759,7 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
878
759
  openLink: (url) => Effect2.tryPromise({
879
760
  try: async () => {
880
761
  adbOpenLink(serial, url, packageName);
881
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
762
+ await new Promise((resolve2) => setTimeout(resolve2, 1e3));
882
763
  },
883
764
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
884
765
  }),
@@ -886,229 +767,71 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
886
767
  // KEYCODE_BACK = 4
887
768
  try: () => client.pressKeyCode(4),
888
769
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
770
+ }),
771
+ evaluate: (script, ...args) => Effect2.tryPromise({
772
+ try: () => client.executeScript(
773
+ typeof script === "function" ? `return (${script})(...arguments)` : script,
774
+ args
775
+ ),
776
+ catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
777
+ }),
778
+ getContexts: () => Effect2.tryPromise({
779
+ try: () => client.getContexts(),
780
+ catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
781
+ }),
782
+ getCurrentContext: () => Effect2.tryPromise({
783
+ try: () => client.getCurrentContext(),
784
+ catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
785
+ }),
786
+ setContext: (contextId) => Effect2.tryPromise({
787
+ try: () => client.setContext(contextId),
788
+ catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
889
789
  })
890
790
  };
891
791
  return service;
892
792
  });
893
793
  }
894
794
 
895
- // src/drivers/wda/pagesource.ts
896
- var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
897
- "XCUIElementTypeButton",
898
- "XCUIElementTypeLink",
899
- "XCUIElementTypeTextField",
900
- "XCUIElementTypeSecureTextField",
901
- "XCUIElementTypeSearchField",
902
- "XCUIElementTypeSwitch",
903
- "XCUIElementTypeSlider",
904
- "XCUIElementTypeStepper",
905
- "XCUIElementTypeSegmentedControl",
906
- "XCUIElementTypeCell",
907
- "XCUIElementTypeTab",
908
- "XCUIElementTypeTabBar",
909
- "XCUIElementTypeMenu",
910
- "XCUIElementTypeMenuItem",
911
- "XCUIElementTypePickerWheel",
912
- "XCUIElementTypeDatePicker",
913
- "XCUIElementTypeToggle",
914
- "XCUIElementTypePageIndicator"
915
- ]);
916
- function parseAttributes2(tagContent) {
917
- const attrs = {};
918
- const re = /([\w-]+)="([^"]*)"/g;
919
- let m;
920
- while ((m = re.exec(tagContent)) !== null) {
921
- attrs[m[1]] = m[2];
922
- }
923
- return attrs;
924
- }
925
- function tokenizeXML2(xml) {
926
- let pos = 0;
927
- function skipWhitespace() {
928
- while (pos < xml.length && /\s/.test(xml[pos])) pos++;
795
+ // src/drivers/wda/driver.ts
796
+ import { Effect as Effect3 } from "effect";
797
+
798
+ // src/drivers/wda/client.ts
799
+ var WDAClient = class {
800
+ baseUrl;
801
+ sessionId = null;
802
+ constructor(host, port) {
803
+ this.baseUrl = `http://${host}:${port}`;
929
804
  }
930
- function parseNode() {
931
- skipWhitespace();
932
- if (pos >= xml.length) return null;
933
- if (xml[pos] !== "<") return null;
934
- pos++;
935
- if (xml[pos] === "?" || xml[pos] === "!") {
936
- const close = xml.indexOf(">", pos);
937
- if (close === -1) return null;
938
- pos = close + 1;
939
- return null;
805
+ // ---------------------------------------------------------------------------
806
+ // HTTP helpers
807
+ // ---------------------------------------------------------------------------
808
+ async request(method, path, body) {
809
+ const url = `${this.baseUrl}${path}`;
810
+ const init = {
811
+ method,
812
+ headers: { "Content-Type": "application/json" }
813
+ };
814
+ if (body !== void 0) {
815
+ init.body = JSON.stringify(body);
940
816
  }
941
- if (xml[pos] === "/") {
942
- const close = xml.indexOf(">", pos);
943
- if (close !== -1) pos = close + 1;
944
- return null;
817
+ const res = await fetch(url, init);
818
+ const text = await res.text();
819
+ let parsed;
820
+ try {
821
+ parsed = JSON.parse(text);
822
+ } catch {
823
+ throw new Error(`WDA: failed to parse response: ${text}`);
945
824
  }
946
- const tagStart = pos;
947
- while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
948
- const tagName = xml.slice(tagStart, pos);
949
- const tagBodyStart = pos;
950
- let selfClosing = false;
951
- let inQuote = false;
952
- let quoteChar = "";
953
- while (pos < xml.length) {
954
- const ch = xml[pos];
955
- if (inQuote) {
956
- if (ch === quoteChar) inQuote = false;
957
- } else {
958
- if (ch === '"' || ch === "'") {
959
- inQuote = true;
960
- quoteChar = ch;
961
- } else if (ch === "/" && xml[pos + 1] === ">") {
962
- selfClosing = true;
963
- pos += 2;
964
- break;
965
- } else if (ch === ">") {
966
- pos++;
967
- break;
968
- }
969
- }
970
- pos++;
825
+ if (!res.ok) {
826
+ const val = parsed.value;
827
+ const msg = val?.message ?? val?.error ?? text;
828
+ throw new Error(`WDA ${method} ${path} \u2192 ${res.status}: ${msg}`);
971
829
  }
972
- const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
973
- const attrs = parseAttributes2(tagBody);
974
- const resolvedType = attrs["type"] ?? tagName;
975
- const node = { tagName: resolvedType, attrs, children: [] };
976
- if (!selfClosing) {
977
- while (pos < xml.length) {
978
- skipWhitespace();
979
- if (pos >= xml.length) break;
980
- if (xml[pos] === "<" && xml[pos + 1] === "/") {
981
- const close = xml.indexOf(">", pos);
982
- if (close !== -1) pos = close + 1;
983
- break;
984
- }
985
- const child = parseNode();
986
- if (child !== null) {
987
- node.children.push(child);
988
- }
989
- }
830
+ if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
831
+ const val = parsed.value;
832
+ throw new Error(`WDA error: ${val.message ?? val.error}`);
990
833
  }
991
- return node;
992
- }
993
- const roots = [];
994
- while (pos < xml.length) {
995
- skipWhitespace();
996
- if (pos >= xml.length) break;
997
- if (xml[pos] !== "<") {
998
- pos++;
999
- continue;
1000
- }
1001
- const peek = pos + 1;
1002
- let nameEnd = peek;
1003
- while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1004
- const peekName = xml.slice(peek, nameEnd);
1005
- if (peekName === "AppiumAUT") {
1006
- const close = xml.indexOf(">", pos);
1007
- if (close === -1) break;
1008
- pos = close + 1;
1009
- continue;
1010
- }
1011
- if (peekName === "/AppiumAUT") {
1012
- const close = xml.indexOf(">", pos);
1013
- if (close !== -1) pos = close + 1;
1014
- break;
1015
- }
1016
- if (peekName.startsWith("?") || peekName.startsWith("!")) {
1017
- const close = xml.indexOf(">", pos);
1018
- if (close !== -1) pos = close + 1;
1019
- continue;
1020
- }
1021
- const node = parseNode();
1022
- if (node !== null) {
1023
- roots.push(node);
1024
- }
1025
- }
1026
- return roots;
1027
- }
1028
- function rawNodeToElement3(node) {
1029
- const a = node.attrs;
1030
- const elementType = node.tagName || void 0;
1031
- const id = a["name"] || void 0;
1032
- const accessibilityLabel = a["label"] || void 0;
1033
- const text = a["value"] || void 0;
1034
- const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
1035
- const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
1036
- const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
1037
- const height = a["height"] !== void 0 ? parseInt(a["height"], 10) : 0;
1038
- const bounds = { x, y, width, height };
1039
- const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
1040
- const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
1041
- const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1042
- const clickable = elementType !== void 0 ? CLICKABLE_TYPES.has(elementType) : void 0;
1043
- const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
1044
- return {
1045
- ...id !== void 0 ? { id } : {},
1046
- ...text !== void 0 ? { text } : {},
1047
- ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1048
- ...elementType !== void 0 ? { elementType } : {},
1049
- bounds,
1050
- ...enabled !== void 0 ? { enabled } : {},
1051
- ...visible !== void 0 ? { visible } : {},
1052
- ...focused !== void 0 ? { focused } : {},
1053
- ...clickable !== void 0 ? { clickable } : {},
1054
- ...children !== void 0 ? { children } : {}
1055
- };
1056
- }
1057
- function parseIOSHierarchy(xml) {
1058
- const roots = tokenizeXML2(xml);
1059
- if (roots.length === 0) {
1060
- throw new Error("parseIOSHierarchy: no elements found in page source");
1061
- }
1062
- if (roots.length === 1) {
1063
- return rawNodeToElement3(roots[0]);
1064
- }
1065
- return {
1066
- elementType: "AppiumAUT",
1067
- bounds: { x: 0, y: 0, width: 0, height: 0 },
1068
- children: roots.map(rawNodeToElement3)
1069
- };
1070
- }
1071
-
1072
- // src/drivers/wda/driver.ts
1073
- import { Effect as Effect3 } from "effect";
1074
-
1075
- // src/drivers/wda/client.ts
1076
- var WDAClient = class {
1077
- baseUrl;
1078
- sessionId = null;
1079
- constructor(host, port) {
1080
- this.baseUrl = `http://${host}:${port}`;
1081
- }
1082
- // ---------------------------------------------------------------------------
1083
- // HTTP helpers
1084
- // ---------------------------------------------------------------------------
1085
- async request(method, path, body) {
1086
- const url = `${this.baseUrl}${path}`;
1087
- const init = {
1088
- method,
1089
- headers: { "Content-Type": "application/json" }
1090
- };
1091
- if (body !== void 0) {
1092
- init.body = JSON.stringify(body);
1093
- }
1094
- const res = await fetch(url, init);
1095
- const text = await res.text();
1096
- let parsed;
1097
- try {
1098
- parsed = JSON.parse(text);
1099
- } catch {
1100
- throw new Error(`WDA: failed to parse response: ${text}`);
1101
- }
1102
- if (!res.ok) {
1103
- const val = parsed.value;
1104
- const msg = val?.message ?? val?.error ?? text;
1105
- throw new Error(`WDA ${method} ${path} \u2192 ${res.status}: ${msg}`);
1106
- }
1107
- if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
1108
- const val = parsed.value;
1109
- throw new Error(`WDA error: ${val.message ?? val.error}`);
1110
- }
1111
- return parsed.value;
834
+ return parsed.value;
1112
835
  }
1113
836
  sessionPath(path) {
1114
837
  if (this.sessionId === null) {
@@ -1165,8 +888,11 @@ var WDAClient = class {
1165
888
  async deleteSession() {
1166
889
  if (this.sessionId === null) return;
1167
890
  const path = `/session/${this.sessionId}`;
1168
- this.sessionId = null;
1169
- await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
891
+ try {
892
+ await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
893
+ } finally {
894
+ this.sessionId = null;
895
+ }
1170
896
  }
1171
897
  hasSession() {
1172
898
  return this.sessionId !== null;
@@ -1203,10 +929,7 @@ var WDAClient = class {
1203
929
  * decodes the base64 value. We follow the same pattern.
1204
930
  */
1205
931
  async getScreenshot() {
1206
- const base64 = await this.request(
1207
- "GET",
1208
- this.sessionPath("/screenshot")
1209
- );
932
+ const base64 = await this.request("GET", this.sessionPath("/screenshot"));
1210
933
  return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1211
934
  }
1212
935
  /** Returns the screen dimensions in logical points. */
@@ -1332,7 +1055,7 @@ function msToSec(ms) {
1332
1055
  return ms / 1e3;
1333
1056
  }
1334
1057
  function sleep(ms) {
1335
- return new Promise((resolve3) => setTimeout(resolve3, ms));
1058
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1336
1059
  }
1337
1060
  function replaceUrlScheme(url, scheme) {
1338
1061
  const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(\/\/.*)$/);
@@ -1342,6 +1065,21 @@ function replaceUrlScheme(url, scheme) {
1342
1065
  function createWDADriver(host, port, bundleId, simulatorUdid) {
1343
1066
  return Effect3.gen(function* () {
1344
1067
  const client = new WDAClient(host, port);
1068
+ const createSessionWithRetry = async (targetBundleId) => {
1069
+ let lastError;
1070
+ for (let attempt = 0; attempt < 5; attempt++) {
1071
+ try {
1072
+ return await client.createSession(targetBundleId);
1073
+ } catch (error) {
1074
+ lastError = error;
1075
+ if (attempt === 4) {
1076
+ throw error;
1077
+ }
1078
+ await sleep(1e3);
1079
+ }
1080
+ }
1081
+ throw lastError ?? new Error("Failed to create WDA session");
1082
+ };
1345
1083
  const activateSimulatorApp = async (targetBundleId) => {
1346
1084
  if (!targetBundleId) return;
1347
1085
  await client.activateApp(targetBundleId);
@@ -1352,6 +1090,26 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1352
1090
  await client.openUrl(url);
1353
1091
  return;
1354
1092
  }
1093
+ try {
1094
+ await activateSimulatorApp(targetBundleId);
1095
+ await client.openUrl(url);
1096
+ await sleep(1e3);
1097
+ return;
1098
+ } catch {
1099
+ try {
1100
+ await client.deleteSession();
1101
+ } catch {
1102
+ }
1103
+ try {
1104
+ await createSessionWithRetry(targetBundleId);
1105
+ await client.disableQuiescence();
1106
+ await activateSimulatorApp(targetBundleId);
1107
+ await client.openUrl(url);
1108
+ await sleep(1e3);
1109
+ return;
1110
+ } catch {
1111
+ }
1112
+ }
1355
1113
  const fallbackSchemes = installedUrlSchemesOnSimulator(simulatorUdid, targetBundleId);
1356
1114
  const candidates = [
1357
1115
  url,
@@ -1368,18 +1126,25 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1368
1126
  await client.deleteSession();
1369
1127
  } catch {
1370
1128
  }
1371
- await client.createSession(targetBundleId);
1129
+ await createSessionWithRetry(targetBundleId);
1372
1130
  await client.disableQuiescence();
1373
- await sleep(500);
1131
+ await activateSimulatorApp(targetBundleId);
1374
1132
  return;
1375
1133
  } catch (error) {
1376
1134
  lastError = error;
1377
1135
  }
1378
1136
  }
1137
+ if (!client.hasSession()) {
1138
+ try {
1139
+ await createSessionWithRetry(targetBundleId);
1140
+ await client.disableQuiescence();
1141
+ } catch {
1142
+ }
1143
+ }
1379
1144
  throw lastError ?? new Error(`Failed to open URL: ${url}`);
1380
1145
  };
1381
1146
  yield* Effect3.tryPromise({
1382
- try: () => client.createSession(bundleId || void 0),
1147
+ try: () => createSessionWithRetry(bundleId || void 0),
1383
1148
  catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
1384
1149
  });
1385
1150
  yield* Effect3.tryPromise({
@@ -1470,6 +1235,21 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1470
1235
  // -----------------------------------------------------------------------
1471
1236
  launchApp: (appBundleId, opts) => Effect3.tryPromise({
1472
1237
  try: async () => {
1238
+ if (opts?.clearState && simulatorUdid) {
1239
+ terminateOnSimulator(simulatorUdid, appBundleId);
1240
+ try {
1241
+ const { execSync: execSync2 } = await import("child_process");
1242
+ execSync2(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
1243
+ stdio: "ignore"
1244
+ });
1245
+ } catch {
1246
+ }
1247
+ }
1248
+ if (opts?.clearKeychain && simulatorUdid) {
1249
+ resetSimulatorKeychain(simulatorUdid);
1250
+ } else if (opts?.clearKeychain) {
1251
+ console.warn("clearKeychain is only supported on iOS simulators, skipping.");
1252
+ }
1473
1253
  if (simulatorUdid) {
1474
1254
  if (opts?.deepLink) {
1475
1255
  await openSimulatorUrl(opts.deepLink, appBundleId);
@@ -1532,250 +1312,522 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1532
1312
  // equivalent for dismissing the current context.
1533
1313
  try: () => client.pressHome(),
1534
1314
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
1535
- })
1315
+ }),
1316
+ evaluate: () => Effect3.fail(
1317
+ new DriverError({
1318
+ message: "evaluate() requires a WebView context. Use Appium mode (--driver appium) for iOS WebView support."
1319
+ })
1320
+ ),
1321
+ getContexts: () => Effect3.fail(
1322
+ new DriverError({
1323
+ message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
1324
+ })
1325
+ ),
1326
+ getCurrentContext: () => Effect3.succeed("NATIVE_APP"),
1327
+ setContext: (contextId) => contextId === "NATIVE_APP" ? Effect3.void : Effect3.fail(
1328
+ new DriverError({
1329
+ message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
1330
+ })
1331
+ )
1536
1332
  };
1537
1333
  return service;
1538
1334
  });
1539
1335
  }
1540
1336
 
1541
- // src/drivers/uiautomator2/installer.ts
1542
- import { execSync } from "child_process";
1543
- import { existsSync, readdirSync } from "fs";
1544
- import { createRequire } from "module";
1545
- import { dirname, resolve, join } from "path";
1546
- import { fileURLToPath } from "url";
1547
- var __dirname2 = fileURLToPath(new URL(".", import.meta.url));
1548
- var require2 = createRequire(import.meta.url);
1549
- function resolveOptionalPackageDir(packageName, subpath) {
1550
- try {
1551
- const packageJsonPath = require2.resolve(`${packageName}/package.json`);
1552
- return resolve(dirname(packageJsonPath), subpath);
1553
- } catch {
1554
- return null;
1555
- }
1337
+ // src/drivers/playwright-parser.ts
1338
+ function rawNodeToElement(node) {
1339
+ const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
1340
+ return {
1341
+ ...node.id !== void 0 ? { id: node.id } : {},
1342
+ ...node.text !== void 0 ? { text: node.text } : {},
1343
+ ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
1344
+ // Use role as elementType when present, otherwise fall back to HTML tag name
1345
+ ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
1346
+ bounds: {
1347
+ x: node.bounds.x,
1348
+ y: node.bounds.y,
1349
+ width: node.bounds.width,
1350
+ height: node.bounds.height
1351
+ },
1352
+ ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
1353
+ ...node.visible !== void 0 ? { visible: node.visible } : {},
1354
+ ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
1355
+ ...children !== void 0 ? { children } : {}
1356
+ };
1556
1357
  }
1557
- function findUiAutomator2APK() {
1558
- const appiumServerApks = resolveOptionalPackageDir("appium-uiautomator2-server", "apks");
1559
- const projectDrivers = resolve(process.cwd(), "drivers/android");
1560
- const provDrivers = resolve(__dirname2, "../../../../drivers/android");
1561
- const maestroRunnerDrivers = resolve(
1562
- __dirname2,
1563
- "../../../../../../maestro-runner/drivers/android"
1564
- );
1565
- for (const dir of [projectDrivers, provDrivers, maestroRunnerDrivers, appiumServerApks]) {
1566
- if (!dir) continue;
1567
- if (!existsSync(dir)) continue;
1568
- const files = readdirSync(dir);
1569
- const serverApk = files.find(
1570
- (f) => f.startsWith("appium-uiautomator2-server") && !f.includes("androidTest") && f.endsWith(".apk")
1571
- );
1572
- const testApk = files.find(
1573
- (f) => f.includes("androidTest") && f.endsWith(".apk")
1574
- );
1575
- if (serverApk && testApk) {
1576
- return { serverApk: join(dir, serverApk), testApk: join(dir, testApk) };
1577
- }
1578
- }
1579
- return null;
1358
+ function parseWebHierarchy(json) {
1359
+ const raw = JSON.parse(json);
1360
+ return rawNodeToElement(raw);
1580
1361
  }
1581
- function installUiAutomator2(serial) {
1582
- const apks = findUiAutomator2APK();
1583
- if (!apks) {
1584
- throw new Error(
1585
- "UiAutomator2 server APK not found. Install appium-uiautomator2-server or place APKs in drivers/android/"
1586
- );
1362
+
1363
+ // src/drivers/uiautomator2/pagesource.ts
1364
+ function parseBounds(s) {
1365
+ const normalized = s.replace("][", ",").replace(/[[\]]/g, "");
1366
+ const parts = normalized.split(",");
1367
+ if (parts.length !== 4) {
1368
+ return { x: 0, y: 0, width: 0, height: 0 };
1587
1369
  }
1588
- console.log(`Installing UiAutomator2 server on ${serial}...`);
1589
- adbInstall(serial, apks.serverApk);
1590
- adbInstall(serial, apks.testApk);
1591
- console.log("UiAutomator2 server installed.");
1370
+ const x1 = parseInt(parts[0], 10);
1371
+ const y1 = parseInt(parts[1], 10);
1372
+ const x2 = parseInt(parts[2], 10);
1373
+ const y2 = parseInt(parts[3], 10);
1374
+ return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
1592
1375
  }
1593
- function isUiAutomator2Installed(serial) {
1594
- try {
1595
- const output = adbShell(
1596
- serial,
1597
- "pm list packages io.appium.uiautomator2.server"
1598
- );
1599
- return output.includes("io.appium.uiautomator2.server");
1600
- } catch {
1601
- return false;
1376
+ function stripResourceIdPrefix(resourceId) {
1377
+ const colonSlash = resourceId.indexOf(":id/");
1378
+ if (colonSlash !== -1) {
1379
+ return resourceId.slice(colonSlash + 4);
1602
1380
  }
1381
+ return resourceId;
1603
1382
  }
1604
- function startUiAutomator2Server(serial) {
1605
- const adb = findADB();
1606
- if (!adb) throw new Error("adb not found");
1607
- try {
1608
- execSync(
1609
- `${adb} -s ${serial} shell am instrument -w -e disableAnalytics true io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner &`,
1610
- { stdio: "ignore", timeout: 5e3 }
1611
- );
1612
- } catch {
1383
+ function parseAttributes(tagContent) {
1384
+ const attrs = {};
1385
+ const re = /([\w-]+)="([^"]*)"/g;
1386
+ let m;
1387
+ while ((m = re.exec(tagContent)) !== null) {
1388
+ attrs[m[1]] = m[2];
1613
1389
  }
1390
+ return attrs;
1614
1391
  }
1615
- async function setupUiAutomator2(serial, hostPort = 8200) {
1616
- if (!isUiAutomator2Installed(serial)) {
1617
- installUiAutomator2(serial);
1392
+ function tokenizeXML(xml) {
1393
+ let pos = 0;
1394
+ function skipWhitespace() {
1395
+ while (pos < xml.length && /\s/.test(xml[pos])) pos++;
1618
1396
  }
1619
- startUiAutomator2Server(serial);
1620
- await new Promise((r) => setTimeout(r, 2e3));
1621
- const devicePort = 6790;
1622
- adbForward(serial, hostPort, devicePort);
1623
- const maxRetries = 10;
1624
- for (let i = 0; i < maxRetries; i++) {
1625
- try {
1626
- const res = await fetch(`http://localhost:${hostPort}/status`);
1627
- if (res.ok) {
1628
- console.log(`UiAutomator2 server ready on port ${hostPort}`);
1629
- return { host: "localhost", port: hostPort };
1397
+ function parseNode() {
1398
+ skipWhitespace();
1399
+ if (pos >= xml.length) return null;
1400
+ if (xml[pos] !== "<") return null;
1401
+ pos++;
1402
+ if (xml[pos] === "?" || xml[pos] === "!") {
1403
+ const close = xml.indexOf(">", pos);
1404
+ if (close === -1) return null;
1405
+ pos = close + 1;
1406
+ return null;
1407
+ }
1408
+ if (xml[pos] === "/") {
1409
+ const close = xml.indexOf(">", pos);
1410
+ if (close === -1) return null;
1411
+ pos = close + 1;
1412
+ return null;
1413
+ }
1414
+ const tagStart = pos;
1415
+ while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
1416
+ const tagName = xml.slice(tagStart, pos);
1417
+ const tagBodyStart = pos;
1418
+ let selfClosing = false;
1419
+ let inQuote = false;
1420
+ let quoteChar = "";
1421
+ while (pos < xml.length) {
1422
+ const ch = xml[pos];
1423
+ if (inQuote) {
1424
+ if (ch === quoteChar) inQuote = false;
1425
+ } else {
1426
+ if (ch === '"' || ch === "'") {
1427
+ inQuote = true;
1428
+ quoteChar = ch;
1429
+ } else if (ch === "/" && xml[pos + 1] === ">") {
1430
+ selfClosing = true;
1431
+ pos += 2;
1432
+ break;
1433
+ } else if (ch === ">") {
1434
+ pos++;
1435
+ break;
1436
+ }
1630
1437
  }
1631
- } catch {
1438
+ pos++;
1632
1439
  }
1633
- await new Promise((r) => setTimeout(r, 1e3));
1440
+ const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
1441
+ const attrs = parseAttributes(tagBody);
1442
+ if (!attrs["class"]) {
1443
+ attrs["class"] = tagName;
1444
+ }
1445
+ const node = { attrs, children: [] };
1446
+ if (!selfClosing) {
1447
+ while (pos < xml.length) {
1448
+ skipWhitespace();
1449
+ if (pos >= xml.length) break;
1450
+ if (xml[pos] === "<" && xml[pos + 1] === "/") {
1451
+ const close = xml.indexOf(">", pos);
1452
+ if (close !== -1) pos = close + 1;
1453
+ break;
1454
+ }
1455
+ const child = parseNode();
1456
+ if (child !== null) {
1457
+ node.children.push(child);
1458
+ }
1459
+ }
1460
+ }
1461
+ return node;
1634
1462
  }
1635
- throw new Error(
1636
- `UiAutomator2 server did not start within ${maxRetries} seconds`
1637
- );
1463
+ const roots = [];
1464
+ while (pos < xml.length) {
1465
+ skipWhitespace();
1466
+ if (pos >= xml.length) break;
1467
+ if (xml[pos] !== "<") {
1468
+ pos++;
1469
+ continue;
1470
+ }
1471
+ const peek = pos + 1;
1472
+ let nameEnd = peek;
1473
+ while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1474
+ const peekName = xml.slice(peek, nameEnd);
1475
+ if (peekName === "hierarchy") {
1476
+ const close = xml.indexOf(">", pos);
1477
+ if (close === -1) break;
1478
+ pos = close + 1;
1479
+ continue;
1480
+ }
1481
+ if (peekName === "/hierarchy") {
1482
+ const close = xml.indexOf(">", pos);
1483
+ if (close !== -1) pos = close + 1;
1484
+ break;
1485
+ }
1486
+ if (peekName.startsWith("?") || peekName.startsWith("!")) {
1487
+ const close = xml.indexOf(">", pos);
1488
+ if (close !== -1) pos = close + 1;
1489
+ continue;
1490
+ }
1491
+ const node = parseNode();
1492
+ if (node !== null) {
1493
+ roots.push(node);
1494
+ }
1495
+ }
1496
+ return roots;
1497
+ }
1498
+ function rawNodeToElement2(node) {
1499
+ const a = node.attrs;
1500
+ const rawId = a["resource-id"] ?? "";
1501
+ const id = rawId ? stripResourceIdPrefix(rawId) : void 0;
1502
+ const text = a["text"] || void 0;
1503
+ const accessibilityLabel = a["content-desc"] || void 0;
1504
+ const elementType = a["class"] || void 0;
1505
+ const boundsStr = a["bounds"] ?? "[0,0][0,0]";
1506
+ const bounds = parseBounds(boundsStr);
1507
+ const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
1508
+ const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1509
+ const clickable = a["clickable"] !== void 0 ? a["clickable"] === "true" : void 0;
1510
+ const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
1511
+ return {
1512
+ ...id !== void 0 ? { id } : {},
1513
+ ...text !== void 0 ? { text } : {},
1514
+ ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1515
+ ...elementType !== void 0 ? { elementType } : {},
1516
+ bounds,
1517
+ ...enabled !== void 0 ? { enabled } : {},
1518
+ ...focused !== void 0 ? { focused } : {},
1519
+ ...clickable !== void 0 ? { clickable } : {},
1520
+ ...children !== void 0 ? { children } : {}
1521
+ };
1522
+ }
1523
+ function parseAndroidHierarchy(xml) {
1524
+ const roots = tokenizeXML(xml);
1525
+ if (roots.length === 0) {
1526
+ throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
1527
+ }
1528
+ if (roots.length === 1) {
1529
+ return rawNodeToElement2(roots[0]);
1530
+ }
1531
+ return {
1532
+ elementType: "hierarchy",
1533
+ bounds: { x: 0, y: 0, width: 0, height: 0 },
1534
+ children: roots.map(rawNodeToElement2)
1535
+ };
1638
1536
  }
1639
1537
 
1640
- // src/drivers/wda/installer.ts
1641
- import { execSync as execSync2, spawn } from "child_process";
1642
- import { existsSync as existsSync2 } from "fs";
1643
- import { createRequire as createRequire2 } from "module";
1644
- import { dirname as dirname2, resolve as resolve2 } from "path";
1645
- import { fileURLToPath as fileURLToPath2 } from "url";
1646
- var __dirname3 = fileURLToPath2(new URL(".", import.meta.url));
1647
- var require3 = createRequire2(import.meta.url);
1648
- function resolveOptionalPackageDir2(packageName) {
1538
+ // src/drivers/wda/pagesource.ts
1539
+ var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
1540
+ "XCUIElementTypeButton",
1541
+ "XCUIElementTypeLink",
1542
+ "XCUIElementTypeTextField",
1543
+ "XCUIElementTypeSecureTextField",
1544
+ "XCUIElementTypeSearchField",
1545
+ "XCUIElementTypeSwitch",
1546
+ "XCUIElementTypeSlider",
1547
+ "XCUIElementTypeStepper",
1548
+ "XCUIElementTypeSegmentedControl",
1549
+ "XCUIElementTypeCell",
1550
+ "XCUIElementTypeTab",
1551
+ "XCUIElementTypeTabBar",
1552
+ "XCUIElementTypeMenu",
1553
+ "XCUIElementTypeMenuItem",
1554
+ "XCUIElementTypePickerWheel",
1555
+ "XCUIElementTypeDatePicker",
1556
+ "XCUIElementTypeToggle",
1557
+ "XCUIElementTypePageIndicator"
1558
+ ]);
1559
+ function parseAttributes2(tagContent) {
1560
+ const attrs = {};
1561
+ const re = /([\w-]+)="([^"]*)"/g;
1562
+ let m;
1563
+ while ((m = re.exec(tagContent)) !== null) {
1564
+ attrs[m[1]] = m[2];
1565
+ }
1566
+ return attrs;
1567
+ }
1568
+ function tokenizeXML2(xml) {
1569
+ let pos = 0;
1570
+ function skipWhitespace() {
1571
+ while (pos < xml.length && /\s/.test(xml[pos])) pos++;
1572
+ }
1573
+ function parseNode() {
1574
+ skipWhitespace();
1575
+ if (pos >= xml.length) return null;
1576
+ if (xml[pos] !== "<") return null;
1577
+ pos++;
1578
+ if (xml[pos] === "?" || xml[pos] === "!") {
1579
+ const close = xml.indexOf(">", pos);
1580
+ if (close === -1) return null;
1581
+ pos = close + 1;
1582
+ return null;
1583
+ }
1584
+ if (xml[pos] === "/") {
1585
+ const close = xml.indexOf(">", pos);
1586
+ if (close !== -1) pos = close + 1;
1587
+ return null;
1588
+ }
1589
+ const tagStart = pos;
1590
+ while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
1591
+ const tagName = xml.slice(tagStart, pos);
1592
+ const tagBodyStart = pos;
1593
+ let selfClosing = false;
1594
+ let inQuote = false;
1595
+ let quoteChar = "";
1596
+ while (pos < xml.length) {
1597
+ const ch = xml[pos];
1598
+ if (inQuote) {
1599
+ if (ch === quoteChar) inQuote = false;
1600
+ } else {
1601
+ if (ch === '"' || ch === "'") {
1602
+ inQuote = true;
1603
+ quoteChar = ch;
1604
+ } else if (ch === "/" && xml[pos + 1] === ">") {
1605
+ selfClosing = true;
1606
+ pos += 2;
1607
+ break;
1608
+ } else if (ch === ">") {
1609
+ pos++;
1610
+ break;
1611
+ }
1612
+ }
1613
+ pos++;
1614
+ }
1615
+ const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
1616
+ const attrs = parseAttributes2(tagBody);
1617
+ const resolvedType = attrs["type"] ?? tagName;
1618
+ const node = { tagName: resolvedType, attrs, children: [] };
1619
+ if (!selfClosing) {
1620
+ while (pos < xml.length) {
1621
+ skipWhitespace();
1622
+ if (pos >= xml.length) break;
1623
+ if (xml[pos] === "<" && xml[pos + 1] === "/") {
1624
+ const close = xml.indexOf(">", pos);
1625
+ if (close !== -1) pos = close + 1;
1626
+ break;
1627
+ }
1628
+ const child = parseNode();
1629
+ if (child !== null) {
1630
+ node.children.push(child);
1631
+ }
1632
+ }
1633
+ }
1634
+ return node;
1635
+ }
1636
+ const roots = [];
1637
+ while (pos < xml.length) {
1638
+ skipWhitespace();
1639
+ if (pos >= xml.length) break;
1640
+ if (xml[pos] !== "<") {
1641
+ pos++;
1642
+ continue;
1643
+ }
1644
+ const peek = pos + 1;
1645
+ let nameEnd = peek;
1646
+ while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1647
+ const peekName = xml.slice(peek, nameEnd);
1648
+ if (peekName === "AppiumAUT") {
1649
+ const close = xml.indexOf(">", pos);
1650
+ if (close === -1) break;
1651
+ pos = close + 1;
1652
+ continue;
1653
+ }
1654
+ if (peekName === "/AppiumAUT") {
1655
+ const close = xml.indexOf(">", pos);
1656
+ if (close !== -1) pos = close + 1;
1657
+ break;
1658
+ }
1659
+ if (peekName.startsWith("?") || peekName.startsWith("!")) {
1660
+ const close = xml.indexOf(">", pos);
1661
+ if (close !== -1) pos = close + 1;
1662
+ continue;
1663
+ }
1664
+ const node = parseNode();
1665
+ if (node !== null) {
1666
+ roots.push(node);
1667
+ }
1668
+ }
1669
+ return roots;
1670
+ }
1671
+ function rawNodeToElement3(node) {
1672
+ const a = node.attrs;
1673
+ const elementType = node.tagName || void 0;
1674
+ const id = a["name"] || void 0;
1675
+ const accessibilityLabel = a["label"] || void 0;
1676
+ const text = a["value"] || void 0;
1677
+ const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
1678
+ const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
1679
+ const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
1680
+ const height = a["height"] !== void 0 ? parseInt(a["height"], 10) : 0;
1681
+ const bounds = { x, y, width, height };
1682
+ const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
1683
+ const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
1684
+ const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1685
+ const clickable = elementType !== void 0 ? CLICKABLE_TYPES.has(elementType) : void 0;
1686
+ const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
1687
+ return {
1688
+ ...id !== void 0 ? { id } : {},
1689
+ ...text !== void 0 ? { text } : {},
1690
+ ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1691
+ ...elementType !== void 0 ? { elementType } : {},
1692
+ bounds,
1693
+ ...enabled !== void 0 ? { enabled } : {},
1694
+ ...visible !== void 0 ? { visible } : {},
1695
+ ...focused !== void 0 ? { focused } : {},
1696
+ ...clickable !== void 0 ? { clickable } : {},
1697
+ ...children !== void 0 ? { children } : {}
1698
+ };
1699
+ }
1700
+ function parseIOSHierarchy(xml) {
1701
+ const roots = tokenizeXML2(xml);
1702
+ if (roots.length === 0) {
1703
+ throw new Error("parseIOSHierarchy: no elements found in page source");
1704
+ }
1705
+ if (roots.length === 1) {
1706
+ return rawNodeToElement3(roots[0]);
1707
+ }
1708
+ return {
1709
+ elementType: "AppiumAUT",
1710
+ bounds: { x: 0, y: 0, width: 0, height: 0 },
1711
+ children: roots.map(rawNodeToElement3)
1712
+ };
1713
+ }
1714
+
1715
+ // src/drivers/uiautomator2/installer.ts
1716
+ import { execSync } from "child_process";
1717
+ import { existsSync, readdirSync } from "fs";
1718
+ import { createRequire } from "module";
1719
+ import { dirname, resolve, join } from "path";
1720
+ import { fileURLToPath } from "url";
1721
+ var __dirname2 = fileURLToPath(new URL(".", import.meta.url));
1722
+ var require2 = createRequire(import.meta.url);
1723
+ function resolveOptionalPackageDir(packageName, subpath) {
1649
1724
  try {
1650
- const packageJsonPath = require3.resolve(`${packageName}/package.json`);
1651
- return dirname2(packageJsonPath);
1725
+ const packageJsonPath = require2.resolve(`${packageName}/package.json`);
1726
+ return resolve(dirname(packageJsonPath), subpath);
1652
1727
  } catch {
1653
1728
  return null;
1654
1729
  }
1655
1730
  }
1656
- function findWDAProject() {
1657
- const appiumWDA = resolveOptionalPackageDir2("appium-webdriveragent");
1658
- const projectWDA = resolve2(process.cwd(), "drivers/ios/WebDriverAgent");
1659
- const provWDA = resolve2(__dirname3, "../../../../drivers/ios/WebDriverAgent");
1660
- const maestroRunnerWDA = resolve2(
1661
- __dirname3,
1662
- "../../../../../../maestro-runner/drivers/ios/WebDriverAgent"
1731
+ function findUiAutomator2APK() {
1732
+ const appiumServerApks = resolveOptionalPackageDir("appium-uiautomator2-server", "apks");
1733
+ const projectDrivers = resolve(process.cwd(), "drivers/android");
1734
+ const provDrivers = resolve(__dirname2, "../../../../drivers/android");
1735
+ const maestroRunnerDrivers = resolve(
1736
+ __dirname2,
1737
+ "../../../../../../maestro-runner/drivers/android"
1663
1738
  );
1664
- for (const wdaPath of [projectWDA, provWDA, maestroRunnerWDA, appiumWDA]) {
1665
- if (!wdaPath) continue;
1666
- if (existsSync2(resolve2(wdaPath, "WebDriverAgent.xcodeproj"))) {
1667
- return wdaPath;
1739
+ for (const dir of [projectDrivers, provDrivers, maestroRunnerDrivers, appiumServerApks]) {
1740
+ if (!dir) continue;
1741
+ if (!existsSync(dir)) continue;
1742
+ const files = readdirSync(dir);
1743
+ const serverApk = files.find(
1744
+ (f) => f.startsWith("appium-uiautomator2-server") && !f.includes("androidTest") && f.endsWith(".apk")
1745
+ );
1746
+ const testApk = files.find((f) => f.includes("androidTest") && f.endsWith(".apk"));
1747
+ if (serverApk && testApk) {
1748
+ return { serverApk: join(dir, serverApk), testApk: join(dir, testApk) };
1668
1749
  }
1669
1750
  }
1670
1751
  return null;
1671
1752
  }
1672
- function buildWDA(simulatorUDID) {
1673
- const wdaPath = findWDAProject();
1674
- if (!wdaPath) {
1753
+ function installUiAutomator2(serial) {
1754
+ const apks = findUiAutomator2APK();
1755
+ if (!apks) {
1675
1756
  throw new Error(
1676
- "WebDriverAgent project not found. Install appium-webdriveragent or place WDA in drivers/ios/WebDriverAgent/"
1757
+ "UiAutomator2 server APK not found. Install appium-uiautomator2-server or place APKs in drivers/android/"
1677
1758
  );
1678
1759
  }
1679
- const derivedDataPath = resolve2(wdaPath, "../../.wda-builds", simulatorUDID);
1680
- console.log("Building WebDriverAgent for simulator...");
1681
- execSync2(
1682
- [
1683
- "xcodebuild",
1684
- "build-for-testing",
1685
- `-project "${resolve2(wdaPath, "WebDriverAgent.xcodeproj")}"`,
1686
- "-scheme WebDriverAgentRunner",
1687
- `-destination "platform=iOS Simulator,id=${simulatorUDID}"`,
1688
- `-derivedDataPath "${derivedDataPath}"`,
1689
- 'CODE_SIGN_IDENTITY=""',
1690
- "CODE_SIGNING_REQUIRED=NO",
1691
- "CODE_SIGNING_ALLOWED=NO",
1692
- "GCC_TREAT_WARNINGS_AS_ERRORS=0",
1693
- "-quiet"
1694
- ].join(" "),
1695
- { stdio: "inherit", timeout: 6e5 }
1696
- // 10 min build timeout
1697
- );
1698
- console.log("WebDriverAgent built successfully.");
1699
- return derivedDataPath;
1760
+ console.log(`Installing UiAutomator2 server on ${serial}...`);
1761
+ adbInstall(serial, apks.serverApk);
1762
+ adbInstall(serial, apks.testApk);
1763
+ console.log("UiAutomator2 server installed.");
1700
1764
  }
1701
- var wdaProcess = null;
1702
- function startWDA(simulatorUDID, port = 8100, derivedDataPath) {
1703
- const wdaPath = findWDAProject();
1704
- if (!wdaPath) {
1705
- throw new Error("WebDriverAgent project not found");
1706
- }
1707
- const ddPath = derivedDataPath ?? resolve2(wdaPath, "../../.wda-builds", simulatorUDID);
1708
- const env = { ...process.env, USE_PORT: String(port) };
1709
- console.log(`Starting WebDriverAgent on port ${port}...`);
1710
- const child = spawn(
1711
- "xcodebuild",
1712
- [
1713
- "test-without-building",
1714
- "-project",
1715
- resolve2(wdaPath, "WebDriverAgent.xcodeproj"),
1716
- "-scheme",
1717
- "WebDriverAgentRunner",
1718
- "-destination",
1719
- `platform=iOS Simulator,id=${simulatorUDID}`,
1720
- "-derivedDataPath",
1721
- ddPath
1722
- ],
1723
- { env, stdio: "ignore", detached: true }
1724
- );
1725
- child.unref();
1726
- wdaProcess = child;
1727
- return child;
1765
+ function isUiAutomator2Installed(serial) {
1766
+ try {
1767
+ const output = adbShell(serial, "pm list packages io.appium.uiautomator2.server");
1768
+ return output.includes("io.appium.uiautomator2.server");
1769
+ } catch {
1770
+ return false;
1771
+ }
1728
1772
  }
1729
- async function setupWDA(simulatorUDID, port = 8100) {
1730
- const wdaPath = findWDAProject();
1731
- if (!wdaPath) {
1732
- throw new Error("WebDriverAgent project not found");
1733
- }
1734
- const derivedDataPath = resolve2(
1735
- wdaPath,
1736
- "../../.wda-builds",
1737
- simulatorUDID
1738
- );
1739
- const buildProductsDir = resolve2(
1740
- derivedDataPath,
1741
- "Build",
1742
- "Products"
1743
- );
1744
- if (!existsSync2(buildProductsDir)) {
1745
- buildWDA(simulatorUDID);
1773
+ function startUiAutomator2Server(serial) {
1774
+ const adb = findADB();
1775
+ if (!adb) throw new Error("adb not found");
1776
+ try {
1777
+ execSync(
1778
+ `${adb} -s ${serial} shell am instrument -w -e disableAnalytics true io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner &`,
1779
+ { stdio: "ignore", timeout: 5e3 }
1780
+ );
1781
+ } catch {
1746
1782
  }
1747
- startWDA(simulatorUDID, port, derivedDataPath);
1748
- const maxRetries = 30;
1783
+ }
1784
+ async function setupUiAutomator2(serial, hostPort) {
1785
+ const port = hostPort ?? allocatePort(8200);
1786
+ if (!isUiAutomator2Installed(serial)) {
1787
+ installUiAutomator2(serial);
1788
+ }
1789
+ const adb = findADB();
1790
+ if (adb) {
1791
+ try {
1792
+ execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
1793
+ } catch {
1794
+ }
1795
+ }
1796
+ startUiAutomator2Server(serial);
1797
+ await new Promise((r) => setTimeout(r, 2e3));
1798
+ const devicePort = 6790;
1799
+ adbForward(serial, port, devicePort);
1800
+ const maxRetries = 10;
1749
1801
  for (let i = 0; i < maxRetries; i++) {
1750
1802
  try {
1751
1803
  const res = await fetch(`http://localhost:${port}/status`);
1752
1804
  if (res.ok) {
1753
- console.log(`WebDriverAgent ready on port ${port}`);
1754
- return { host: "localhost", port };
1805
+ console.log(`UiAutomator2 server ready on port ${port}`);
1806
+ const cleanup = () => {
1807
+ try {
1808
+ if (adb)
1809
+ execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
1810
+ } catch {
1811
+ }
1812
+ releasePort(port);
1813
+ };
1814
+ return { host: "localhost", port, cleanup };
1755
1815
  }
1756
1816
  } catch {
1757
1817
  }
1758
1818
  await new Promise((r) => setTimeout(r, 1e3));
1759
1819
  }
1760
- throw new Error(
1761
- `WebDriverAgent did not start within ${maxRetries} seconds`
1762
- );
1820
+ releasePort(port);
1821
+ throw new Error(`UiAutomator2 server did not start within ${maxRetries} seconds`);
1763
1822
  }
1764
1823
 
1765
1824
  export {
1766
- ElementNotFoundError,
1767
- TextMismatchError,
1768
- WaitTimeoutError,
1769
- flattenElements,
1770
- findElement,
1771
- centerOf,
1772
- parseWebHierarchy,
1773
1825
  makePlaywrightDriver,
1774
- parseAndroidHierarchy,
1775
1826
  createUiAutomator2Driver,
1776
- parseIOSHierarchy,
1777
1827
  createWDADriver,
1778
- setupUiAutomator2,
1779
- setupWDA
1828
+ parseWebHierarchy,
1829
+ parseAndroidHierarchy,
1830
+ parseIOSHierarchy,
1831
+ setupUiAutomator2
1780
1832
  };
1781
- //# sourceMappingURL=chunk-VZZH66U5.js.map
1833
+ //# sourceMappingURL=chunk-CKJQX73M.js.map