spana-test 0.1.0 → 0.2.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 (120) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +4 -1
  2. package/README.md +277 -86
  3. package/dist/agent/index.d.ts +34 -5
  4. package/dist/agent/index.js +14 -10
  5. package/dist/{chunk-RK4Z6C7M.js → chunk-3YR4GUGE.js} +3 -2
  6. package/dist/chunk-3YR4GUGE.js.map +1 -0
  7. package/dist/{chunk-WIJYK22K.js → chunk-AEKDFFPJ.js} +2 -2
  8. package/dist/chunk-BF37W5EG.js +125 -0
  9. package/dist/chunk-BF37W5EG.js.map +1 -0
  10. package/dist/chunk-EXLUY7KT.js +21 -0
  11. package/dist/chunk-EXLUY7KT.js.map +1 -0
  12. package/dist/chunk-FNDOEMOL.js +62 -0
  13. package/dist/chunk-FNDOEMOL.js.map +1 -0
  14. package/dist/chunk-HWFDXIXR.js +183 -0
  15. package/dist/chunk-HWFDXIXR.js.map +1 -0
  16. package/dist/chunk-IJIASIX5.js +314 -0
  17. package/dist/chunk-IJIASIX5.js.map +1 -0
  18. package/dist/chunk-KJPHH2TW.js +168 -0
  19. package/dist/chunk-KJPHH2TW.js.map +1 -0
  20. package/dist/{chunk-RJ5VPHVX.js → chunk-L7MFJF46.js} +16 -6
  21. package/dist/chunk-L7MFJF46.js.map +1 -0
  22. package/dist/{chunk-5XO6S7AI.js → chunk-MRH7SK52.js} +4 -4
  23. package/dist/chunk-MRH7SK52.js.map +1 -0
  24. package/dist/{chunk-53MUJUJY.js → chunk-P7JQRLP4.js} +5 -4
  25. package/dist/{chunk-53MUJUJY.js.map → chunk-P7JQRLP4.js.map} +1 -1
  26. package/dist/chunk-S2XNAKSO.js +1087 -0
  27. package/dist/chunk-S2XNAKSO.js.map +1 -0
  28. package/dist/{chunk-VDWWIVM6.js → chunk-S4R4OR7T.js} +108 -53
  29. package/dist/chunk-S4R4OR7T.js.map +1 -0
  30. package/dist/{chunk-V62HFH6E.js → chunk-SFBRFB2N.js} +14 -6
  31. package/dist/chunk-SFBRFB2N.js.map +1 -0
  32. package/dist/{chunk-PWEOJKUF.js → chunk-VNYF5BHX.js} +28 -7
  33. package/dist/chunk-VNYF5BHX.js.map +1 -0
  34. package/dist/chunk-WBU34APM.js +38 -0
  35. package/dist/chunk-WBU34APM.js.map +1 -0
  36. package/dist/{chunk-CKJQX73M.js → chunk-WQ4GXUUE.js} +921 -352
  37. package/dist/chunk-WQ4GXUUE.js.map +1 -0
  38. package/dist/chunk-YBZCOQXJ.js +311 -0
  39. package/dist/chunk-YBZCOQXJ.js.map +1 -0
  40. package/dist/cli.js +316 -40
  41. package/dist/cli.js.map +1 -1
  42. package/dist/{compiler-G75RIIYS.js → compiler-74VGKZO6.js} +2 -2
  43. package/dist/{compiler-G75RIIYS.js.map → compiler-74VGKZO6.js.map} +1 -1
  44. package/dist/config-loader-BJJ3IJJ7.js +9 -0
  45. package/dist/{console-FV4RJPO4.js → console-XWKUTP3D.js} +39 -7
  46. package/dist/console-XWKUTP3D.js.map +1 -0
  47. package/dist/{config-Dg9O0rcQ.d.ts → coordinator-BbUjvvnX.d.ts} +165 -1
  48. package/dist/{discover-RWBKI5IB.js → discover-KZKXHZZA.js} +3 -3
  49. package/dist/doctor-command-T2UX5RV5.js +732 -0
  50. package/dist/doctor-command-T2UX5RV5.js.map +1 -0
  51. package/dist/{element-CGteXiXB.d.ts → element-DZ0HyJ3C.d.ts} +2 -0
  52. package/dist/{flow-D-_tlLpp.d.ts → flow-BUC9Mf8W.d.ts} +38 -9
  53. package/dist/gherkin/steps.d.ts +2 -2
  54. package/dist/{html-JP2HBIJQ.js → html-GE6Q4DCG.js} +23 -3
  55. package/dist/html-GE6Q4DCG.js.map +1 -0
  56. package/dist/index.d.ts +171 -3
  57. package/dist/index.js +6 -3
  58. package/dist/index.js.map +1 -1
  59. package/dist/{init-command-CELKL2CX.js → init-command-GVMRXIMY.js} +37 -21
  60. package/dist/init-command-GVMRXIMY.js.map +1 -0
  61. package/dist/init-flow-command-R76AXF4Z.js +34 -0
  62. package/dist/init-flow-command-R76AXF4Z.js.map +1 -0
  63. package/dist/{installer-R6NX7BYQ.js → installer-YZJ4DV3F.js} +4 -2
  64. package/dist/{ios-ZZU6DHH7.js → ios-ZW6XVNLG.js} +4 -2
  65. package/dist/json-KS67BZYU.js +39 -0
  66. package/dist/json-KS67BZYU.js.map +1 -0
  67. package/dist/{junit-UDY5JG22.js → junit-HLC62MK6.js} +2 -2
  68. package/dist/junit-HLC62MK6.js.map +1 -0
  69. package/dist/provider-A57C3MU6.js +12 -0
  70. package/dist/{redact-IDA3C4UH.js → redact-U72BUBBR.js} +2 -2
  71. package/dist/{redact-IDA3C4UH.js.map → redact-U72BUBBR.js.map} +1 -1
  72. package/dist/{runner-QEF6PJOE.js → runner-UXNHVVGG.js} +2 -2
  73. package/dist/{server-MMK7PZIH.js → server-W7OA3DDN.js} +49 -24
  74. package/dist/server-W7OA3DDN.js.map +1 -0
  75. package/dist/session-TMNOKYLG.js +17 -0
  76. package/dist/{studio-command-CDVPREMG.js → studio-command-6VHTHDUK.js} +2 -2
  77. package/dist/{test-command-SB5KYPQI.js → test-command-AHMOZLV4.js} +1280 -357
  78. package/dist/test-command-AHMOZLV4.js.map +1 -0
  79. package/dist/validator-35624P7S.js +20 -0
  80. package/package.json +1 -1
  81. package/studio-dist/assets/index-DC6DIXfl.js +188 -0
  82. package/studio-dist/assets/index-DDKsnBwD.css +1 -0
  83. package/studio-dist/index.html +2 -2
  84. package/dist/chunk-5XO6S7AI.js.map +0 -1
  85. package/dist/chunk-BZRLA4Z3.js +0 -82
  86. package/dist/chunk-BZRLA4Z3.js.map +0 -1
  87. package/dist/chunk-CKJQX73M.js.map +0 -1
  88. package/dist/chunk-PANFRTIU.js +0 -310
  89. package/dist/chunk-PANFRTIU.js.map +0 -1
  90. package/dist/chunk-PWEOJKUF.js.map +0 -1
  91. package/dist/chunk-RJ5VPHVX.js.map +0 -1
  92. package/dist/chunk-RK4Z6C7M.js.map +0 -1
  93. package/dist/chunk-U564GCO2.js +0 -259
  94. package/dist/chunk-U564GCO2.js.map +0 -1
  95. package/dist/chunk-V62HFH6E.js.map +0 -1
  96. package/dist/chunk-VDWWIVM6.js.map +0 -1
  97. package/dist/config-loader-JJ5RPP53.js +0 -9
  98. package/dist/console-FV4RJPO4.js.map +0 -1
  99. package/dist/html-JP2HBIJQ.js.map +0 -1
  100. package/dist/init-command-CELKL2CX.js.map +0 -1
  101. package/dist/json-JMRPUVY2.js +0 -20
  102. package/dist/json-JMRPUVY2.js.map +0 -1
  103. package/dist/junit-UDY5JG22.js.map +0 -1
  104. package/dist/provider-CUWPULGC.js +0 -10
  105. package/dist/server-MMK7PZIH.js.map +0 -1
  106. package/dist/session-FBJABNXL.js +0 -16
  107. package/dist/test-command-SB5KYPQI.js.map +0 -1
  108. package/dist/validator-CFQ55NUQ.js +0 -13
  109. package/studio-dist/assets/index-CPdpC9i-.css +0 -1
  110. package/studio-dist/assets/index-L1Wd0vop.js +0 -183
  111. /package/dist/{chunk-WIJYK22K.js.map → chunk-AEKDFFPJ.js.map} +0 -0
  112. /package/dist/{config-loader-JJ5RPP53.js.map → config-loader-BJJ3IJJ7.js.map} +0 -0
  113. /package/dist/{discover-RWBKI5IB.js.map → discover-KZKXHZZA.js.map} +0 -0
  114. /package/dist/{installer-R6NX7BYQ.js.map → installer-YZJ4DV3F.js.map} +0 -0
  115. /package/dist/{ios-ZZU6DHH7.js.map → ios-ZW6XVNLG.js.map} +0 -0
  116. /package/dist/{provider-CUWPULGC.js.map → provider-A57C3MU6.js.map} +0 -0
  117. /package/dist/{runner-QEF6PJOE.js.map → runner-UXNHVVGG.js.map} +0 -0
  118. /package/dist/{session-FBJABNXL.js.map → session-TMNOKYLG.js.map} +0 -0
  119. /package/dist/{studio-command-CDVPREMG.js.map → studio-command-6VHTHDUK.js.map} +0 -0
  120. /package/dist/{validator-CFQ55NUQ.js.map → validator-35624P7S.js.map} +0 -0
@@ -1,19 +1,12 @@
1
1
  import {
2
- DriverError
3
- } from "./chunk-U564GCO2.js";
4
- import {
5
- allocatePort,
6
- releasePort
7
- } from "./chunk-RK4Z6C7M.js";
2
+ DriverError,
3
+ splitGraphemes
4
+ } from "./chunk-S2XNAKSO.js";
8
5
  import {
9
6
  adbClearApp,
10
7
  adbForceStop,
11
- adbForward,
12
- adbInstall,
13
8
  adbLaunchApp,
14
- adbOpenLink,
15
- adbShell,
16
- findADB
9
+ adbOpenLink
17
10
  } from "./chunk-GZK22EIE.js";
18
11
  import {
19
12
  installedUrlSchemesOnSimulator,
@@ -21,7 +14,7 @@ import {
21
14
  launchWithUrlOnSimulator,
22
15
  resetSimulatorKeychain,
23
16
  terminateOnSimulator
24
- } from "./chunk-V62HFH6E.js";
17
+ } from "./chunk-SFBRFB2N.js";
25
18
 
26
19
  // src/drivers/playwright.ts
27
20
  import { readFile, writeFile } from "fs/promises";
@@ -89,6 +82,29 @@ function currentPageUrl(page) {
89
82
  return "about:blank";
90
83
  }
91
84
  }
85
+ function toHarHeaders(headers) {
86
+ return Object.entries(headers).map(([name, value]) => ({ name, value }));
87
+ }
88
+ function toHarQueryString(url) {
89
+ try {
90
+ return Array.from(new URL(url).searchParams.entries()).map(([name, value]) => ({
91
+ name,
92
+ value
93
+ }));
94
+ } catch {
95
+ return [];
96
+ }
97
+ }
98
+ function timingDuration(start, end) {
99
+ if (start < 0 || end < 0 || end < start) {
100
+ return -1;
101
+ }
102
+ return Math.max(Math.round(end - start), 0);
103
+ }
104
+ function totalHarTime(timing) {
105
+ const end = timing.responseEnd >= 0 ? timing.responseEnd : timing.responseStart >= 0 ? timing.responseStart : timing.requestStart >= 0 ? timing.requestStart : 0;
106
+ return Math.max(Math.round(end), 0);
107
+ }
92
108
  function makePlaywrightDriver(config) {
93
109
  return Effect.gen(function* () {
94
110
  const browserName = config.browser ?? "chromium";
@@ -102,6 +118,234 @@ function makePlaywrightDriver(config) {
102
118
  const routeDefinitions = [];
103
119
  let appliedRoutes = [];
104
120
  let currentNetworkConditions = {};
121
+ let currentFlowName = "unscoped";
122
+ let consoleLogs = [];
123
+ let jsErrors = [];
124
+ let tabIds = /* @__PURE__ */ new Map();
125
+ let nextTabId = 1;
126
+ let harEntries = [];
127
+ let harPages = /* @__PURE__ */ new Map();
128
+ let queuedDownloads = [];
129
+ let downloadWaiters = [];
130
+ const attachedPages = /* @__PURE__ */ new WeakSet();
131
+ const resetWebDiagnostics = () => {
132
+ consoleLogs = [];
133
+ jsErrors = [];
134
+ };
135
+ const debugLog = (...parts) => {
136
+ if (!config.verboseLogging) {
137
+ return;
138
+ }
139
+ const rendered = parts.filter((part) => part !== void 0).map((part) => String(part));
140
+ console.log("[spana:web]", `[${currentFlowName}]`, ...rendered);
141
+ };
142
+ const getTabId = (activePage) => {
143
+ const existing = tabIds.get(activePage);
144
+ if (existing) {
145
+ return existing;
146
+ }
147
+ const id = `tab-${nextTabId++}`;
148
+ tabIds.set(activePage, id);
149
+ harPages.set(activePage, {
150
+ id,
151
+ title: currentPageUrl(activePage),
152
+ startedDateTime: (/* @__PURE__ */ new Date()).toISOString(),
153
+ pageTimings: { onContentLoad: -1, onLoad: -1 }
154
+ });
155
+ return id;
156
+ };
157
+ const updateHarPage = (activePage) => {
158
+ const harPage = harPages.get(activePage);
159
+ if (harPage) {
160
+ harPage.title = currentPageUrl(activePage);
161
+ }
162
+ };
163
+ const flushDownload = (download) => {
164
+ const waiter = downloadWaiters.shift();
165
+ if (waiter) {
166
+ waiter.resolve(download);
167
+ return;
168
+ }
169
+ queuedDownloads.push(download);
170
+ };
171
+ const nextDownload = () => {
172
+ const queued = queuedDownloads.shift();
173
+ if (queued) {
174
+ return Promise.resolve(queued);
175
+ }
176
+ return new Promise((resolve, reject) => {
177
+ downloadWaiters.push({ resolve, reject });
178
+ });
179
+ };
180
+ const defaultSizes = {
181
+ requestBodySize: 0,
182
+ requestHeadersSize: -1,
183
+ responseBodySize: 0,
184
+ responseHeadersSize: -1
185
+ };
186
+ const recordRequestFinished = async (activePage, request) => {
187
+ const response = await request.response();
188
+ if (!response) {
189
+ return;
190
+ }
191
+ const [requestHeaders, responseHeaders, sizes, httpVersion, serverAddr] = await Promise.all([
192
+ request.allHeaders().catch(() => request.headers()),
193
+ response.allHeaders().catch(() => Promise.resolve(response.headers())),
194
+ request.sizes().catch(() => Promise.resolve(defaultSizes)),
195
+ response.httpVersion().catch(() => Promise.resolve("HTTP/1.1")),
196
+ response.serverAddr().catch(() => Promise.resolve(null))
197
+ ]);
198
+ const timing = request.timing();
199
+ const responseContentType = responseHeaders["content-type"] ?? response.headers()["content-type"] ?? "application/octet-stream";
200
+ const redirectURL = responseHeaders.location ?? response.headers().location ?? "";
201
+ const requestContentType = requestHeaders["content-type"] ?? "";
202
+ const postData = request.postData();
203
+ updateHarPage(activePage);
204
+ harEntries.push({
205
+ pageref: getTabId(activePage),
206
+ startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
207
+ time: totalHarTime(timing),
208
+ request: {
209
+ method: request.method(),
210
+ url: request.url(),
211
+ httpVersion,
212
+ headers: toHarHeaders(requestHeaders),
213
+ queryString: toHarQueryString(request.url()),
214
+ headersSize: sizes.requestHeadersSize,
215
+ bodySize: sizes.requestBodySize,
216
+ ...postData ? {
217
+ postData: {
218
+ mimeType: requestContentType || "application/octet-stream",
219
+ text: postData
220
+ }
221
+ } : {}
222
+ },
223
+ response: {
224
+ status: response.status(),
225
+ statusText: response.statusText(),
226
+ httpVersion,
227
+ headers: toHarHeaders(responseHeaders),
228
+ redirectURL,
229
+ headersSize: sizes.responseHeadersSize,
230
+ bodySize: sizes.responseBodySize,
231
+ content: {
232
+ size: sizes.responseBodySize,
233
+ mimeType: responseContentType
234
+ }
235
+ },
236
+ cache: {},
237
+ timings: {
238
+ blocked: 0,
239
+ dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
240
+ connect: timingDuration(timing.connectStart, timing.connectEnd),
241
+ ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
242
+ send: 0,
243
+ wait: timingDuration(timing.requestStart, timing.responseStart),
244
+ receive: timingDuration(timing.responseStart, timing.responseEnd)
245
+ },
246
+ ...serverAddr?.ipAddress ? { serverIPAddress: serverAddr.ipAddress } : {},
247
+ _resourceType: request.resourceType()
248
+ });
249
+ debugLog("network", request.method(), response.status(), request.url());
250
+ };
251
+ const recordRequestFailed = async (activePage, request) => {
252
+ const requestHeaders = await request.allHeaders().catch(() => Promise.resolve(request.headers()));
253
+ const requestContentType = requestHeaders["content-type"] ?? "";
254
+ const postData = request.postData();
255
+ const timing = request.timing();
256
+ const failureText = request.failure()?.errorText ?? "Request failed";
257
+ updateHarPage(activePage);
258
+ harEntries.push({
259
+ pageref: getTabId(activePage),
260
+ startedDateTime: timing.startTime > 0 ? new Date(timing.startTime).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
261
+ time: totalHarTime(timing),
262
+ request: {
263
+ method: request.method(),
264
+ url: request.url(),
265
+ httpVersion: "",
266
+ headers: toHarHeaders(requestHeaders),
267
+ queryString: toHarQueryString(request.url()),
268
+ headersSize: -1,
269
+ bodySize: postData ? Buffer.byteLength(postData) : 0,
270
+ ...postData ? {
271
+ postData: {
272
+ mimeType: requestContentType || "application/octet-stream",
273
+ text: postData
274
+ }
275
+ } : {}
276
+ },
277
+ response: {
278
+ status: 0,
279
+ statusText: failureText,
280
+ httpVersion: "",
281
+ headers: [],
282
+ redirectURL: "",
283
+ headersSize: -1,
284
+ bodySize: 0,
285
+ content: {
286
+ size: 0,
287
+ mimeType: "application/octet-stream"
288
+ }
289
+ },
290
+ cache: {},
291
+ timings: {
292
+ blocked: 0,
293
+ dns: timingDuration(timing.domainLookupStart, timing.domainLookupEnd),
294
+ connect: timingDuration(timing.connectStart, timing.connectEnd),
295
+ ssl: timingDuration(timing.secureConnectionStart, timing.connectEnd),
296
+ send: 0,
297
+ wait: timing.requestStart >= 0 ? Math.max(Math.round(timing.requestStart), 0) : -1,
298
+ receive: -1
299
+ },
300
+ _resourceType: request.resourceType(),
301
+ _failureText: failureText
302
+ });
303
+ debugLog("network", request.method(), "FAILED", request.url(), failureText);
304
+ };
305
+ const attachPageDiagnostics = (activePage) => {
306
+ if (attachedPages.has(activePage)) {
307
+ return;
308
+ }
309
+ attachedPages.add(activePage);
310
+ getTabId(activePage);
311
+ activePage.on("console", (message) => {
312
+ const location = message.location();
313
+ const entry = {
314
+ type: message.type(),
315
+ text: message.text()
316
+ };
317
+ if (location.url || location.lineNumber !== void 0 || location.columnNumber !== void 0) {
318
+ entry.location = {
319
+ url: location.url || void 0,
320
+ lineNumber: location.lineNumber,
321
+ columnNumber: location.columnNumber
322
+ };
323
+ }
324
+ consoleLogs.push(entry);
325
+ debugLog("console", entry.type, entry.text);
326
+ });
327
+ activePage.on("pageerror", (error) => {
328
+ jsErrors.push({
329
+ name: error.name,
330
+ message: error.message,
331
+ stack: error.stack
332
+ });
333
+ debugLog("pageerror", error.message);
334
+ });
335
+ activePage.on("download", (download) => {
336
+ debugLog("download", getTabId(activePage), download.suggestedFilename(), download.url());
337
+ flushDownload(download);
338
+ });
339
+ activePage.on("requestfinished", (request) => {
340
+ void recordRequestFinished(activePage, request);
341
+ });
342
+ activePage.on("requestfailed", (request) => {
343
+ void recordRequestFailed(activePage, request);
344
+ });
345
+ activePage.on("close", () => {
346
+ debugLog("tabClosed", tabIds.get(activePage) ?? "untracked");
347
+ });
348
+ };
105
349
  const clearStorage = async () => {
106
350
  await context.clearCookies();
107
351
  await page.evaluate(CLEAR_STORAGE_SCRIPT);
@@ -141,12 +385,47 @@ function makePlaywrightDriver(config) {
141
385
  await applyRouteDefinition(definition);
142
386
  }
143
387
  };
388
+ const setInputFiles = async (selector, path) => {
389
+ if (typeof selector === "string") {
390
+ try {
391
+ await page.getByLabel(selector, { exact: true }).setInputFiles(path);
392
+ return;
393
+ } catch {
394
+ await page.getByText(selector, { exact: true }).setInputFiles(path);
395
+ return;
396
+ }
397
+ }
398
+ if ("point" in selector) {
399
+ throw new DriverError({
400
+ message: "uploadFile() does not support point selectors on the web platform. Use testID, text, or accessibilityLabel."
401
+ });
402
+ }
403
+ if ("testID" in selector) {
404
+ await page.getByTestId(selector.testID).setInputFiles(path);
405
+ return;
406
+ }
407
+ if ("accessibilityLabel" in selector) {
408
+ await page.getByLabel(selector.accessibilityLabel, { exact: true }).setInputFiles(path);
409
+ return;
410
+ }
411
+ if ("text" in selector) {
412
+ try {
413
+ await page.getByLabel(selector.text, { exact: true }).setInputFiles(path);
414
+ return;
415
+ } catch {
416
+ await page.getByText(selector.text, { exact: true }).setInputFiles(path);
417
+ return;
418
+ }
419
+ }
420
+ };
144
421
  const createContextAndPage = async (storageStatePath) => {
145
- context = await browser.newContext(
146
- storageStatePath ? { storageState: storageStatePath } : void 0
147
- );
422
+ context = await browser.newContext({
423
+ acceptDownloads: true,
424
+ ...storageStatePath ? { storageState: storageStatePath } : {}
425
+ });
148
426
  page = await context.newPage();
149
427
  cdpSession = void 0;
428
+ attachPageDiagnostics(page);
150
429
  await reapplyRoutes();
151
430
  await applyNetworkConditions();
152
431
  };
@@ -160,11 +439,42 @@ function makePlaywrightDriver(config) {
160
439
  }
161
440
  await Promise.allSettled([previousPage.close(), previousContext.close()]);
162
441
  };
442
+ const beginFlow = async (flowName) => {
443
+ currentFlowName = flowName;
444
+ resetWebDiagnostics();
445
+ harEntries = [];
446
+ harPages = /* @__PURE__ */ new Map();
447
+ tabIds = /* @__PURE__ */ new Map();
448
+ nextTabId = 1;
449
+ queuedDownloads = [];
450
+ for (const waiter of downloadWaiters) {
451
+ waiter.reject(
452
+ new Error("A new flow started before downloadFile() received a download event.")
453
+ );
454
+ }
455
+ downloadWaiters = [];
456
+ const openPages = context.pages();
457
+ if (openPages.length === 0) {
458
+ page = await context.newPage();
459
+ } else {
460
+ const [firstPage, ...extraPages] = openPages;
461
+ page = firstPage;
462
+ await Promise.all(extraPages.map((extraPage) => extraPage.close()));
463
+ }
464
+ attachPageDiagnostics(page);
465
+ getTabId(page);
466
+ updateHarPage(page);
467
+ debugLog("beginFlow", flowName);
468
+ };
163
469
  yield* Effect.tryPromise({
164
470
  try: () => createContextAndPage(config.storageState),
165
471
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
166
472
  });
167
473
  const service = {
474
+ beginFlow: (flowName) => Effect.tryPromise({
475
+ try: () => beginFlow(flowName),
476
+ catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
477
+ }),
168
478
  dumpHierarchy: () => Effect.tryPromise({
169
479
  try: async () => {
170
480
  const tree = await page.evaluate(`
@@ -179,12 +489,14 @@ function makePlaywrightDriver(config) {
179
489
  text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
180
490
  ? (el.childNodes[0].textContent || "").trim() || undefined
181
491
  : undefined,
492
+ value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") ? (el.value !== undefined ? String(el.value) : undefined) : undefined,
182
493
  accessibilityLabel: el.getAttribute("aria-label") || undefined,
183
494
  role: el.getAttribute("role") || undefined,
184
495
  bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
185
496
  enabled: !el.hasAttribute("disabled"),
186
497
  visible: isVisible && rect.width > 0 && rect.height > 0,
187
- clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.getAttribute("role") === "button" || el.onclick !== null,
498
+ clickable: el.tagName === "BUTTON" || el.tagName === "A" || el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA" || el.getAttribute("role") === "button" || el.onclick !== null,
499
+ attributes: (function() { var a = {}; for (var i = 0; i < el.attributes.length; i++) { var attr = el.attributes[i]; a[attr.name] = attr.value; } return Object.keys(a).length > 0 ? a : undefined; })(),
188
500
  children: Array.from(el.children).map(walk),
189
501
  };
190
502
  }
@@ -196,47 +508,17 @@ function makePlaywrightDriver(config) {
196
508
  catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
197
509
  }),
198
510
  tapAtCoordinate: (x, y) => Effect.tryPromise({
199
- try: () => page.evaluate(`
511
+ try: async () => {
512
+ await page.mouse.click(x, y);
513
+ await page.evaluate(`
200
514
  (function(x, y) {
201
- function isClickable(el) {
202
- return el.tagName === "BUTTON"
203
- || el.tagName === "A"
204
- || el.getAttribute("role") === "button"
205
- || el.onclick !== null;
206
- }
207
-
208
- function area(el) {
209
- var rect = el.getBoundingClientRect();
210
- return rect.width * rect.height;
211
- }
212
-
213
- var elements = document.elementsFromPoint(x, y);
214
- var candidates = [];
215
-
216
- for (var i = 0; i < elements.length; i++) {
217
- var raw = elements[i];
218
- var candidate = raw.closest("button, a, [role=\\"button\\"]") || raw;
219
-
220
- if (
221
- candidate instanceof HTMLElement
222
- && isClickable(candidate)
223
- && candidates.indexOf(candidate) === -1
224
- ) {
225
- candidates.push(candidate);
226
- }
227
- }
228
-
229
- var target = candidates.sort(function(a, b) {
230
- return area(a) - area(b);
231
- })[0] || document.elementFromPoint(x, y);
232
-
233
- if (!(target instanceof HTMLElement)) {
234
- throw new Error("No clickable element found at tap point");
515
+ var el = document.elementFromPoint(x, y);
516
+ if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")) {
517
+ el.focus();
235
518
  }
236
-
237
- target.click();
238
519
  })(${x}, ${y})
239
- `),
520
+ `);
521
+ },
240
522
  catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
241
523
  }),
242
524
  doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
@@ -266,7 +548,7 @@ function makePlaywrightDriver(config) {
266
548
  catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
267
549
  }),
268
550
  inputText: (text) => Effect.tryPromise({
269
- try: () => page.keyboard.type(text),
551
+ try: () => page.keyboard.insertText(text),
270
552
  catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
271
553
  }),
272
554
  pressKey: (key) => Effect.tryPromise({
@@ -298,16 +580,22 @@ function makePlaywrightDriver(config) {
298
580
  }),
299
581
  launchApp: (url, opts) => Effect.tryPromise({
300
582
  try: async () => {
583
+ const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
301
584
  if (opts?.clearState) {
302
585
  await clearStorage();
303
586
  }
304
- await page.goto(opts?.deepLink || url || config.baseUrl || "about:blank");
587
+ await page.goto(targetUrl);
588
+ updateHarPage(page);
589
+ debugLog("launchApp", targetUrl);
305
590
  },
306
591
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
307
592
  }),
308
593
  stopApp: (_id) => Effect.tryPromise({
309
- try: () => page.goto("about:blank").then(() => {
310
- }),
594
+ try: async () => {
595
+ await page.goto("about:blank");
596
+ updateHarPage(page);
597
+ debugLog("stopApp");
598
+ },
311
599
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
312
600
  }),
313
601
  killApp: (_id) => Effect.tryPromise({
@@ -319,17 +607,24 @@ function makePlaywrightDriver(config) {
319
607
  clearAppState: (_id) => Effect.tryPromise({
320
608
  try: async () => {
321
609
  await clearStorage();
610
+ debugLog("clearAppState");
322
611
  },
323
612
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
324
613
  }),
325
614
  openLink: (url) => Effect.tryPromise({
326
- try: () => page.goto(url).then(() => {
327
- }),
615
+ try: async () => {
616
+ await page.goto(url);
617
+ updateHarPage(page);
618
+ debugLog("openLink", url);
619
+ },
328
620
  catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
329
621
  }),
330
622
  back: () => Effect.tryPromise({
331
- try: () => page.goBack().then(() => {
332
- }),
623
+ try: async () => {
624
+ await page.goBack();
625
+ updateHarPage(page);
626
+ debugLog("back", currentPageUrl(page));
627
+ },
333
628
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
334
629
  }),
335
630
  evaluate: (script, ...args) => Effect.tryPromise({
@@ -342,6 +637,7 @@ function makePlaywrightDriver(config) {
342
637
  const definition = { kind: "mock", matcher, response };
343
638
  routeDefinitions.push(definition);
344
639
  await applyRouteDefinition(definition);
640
+ debugLog("mockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
345
641
  },
346
642
  catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
347
643
  }),
@@ -350,6 +646,7 @@ function makePlaywrightDriver(config) {
350
646
  const definition = { kind: "block", matcher };
351
647
  routeDefinitions.push(definition);
352
648
  await applyRouteDefinition(definition);
649
+ debugLog("blockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
353
650
  },
354
651
  catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
355
652
  }),
@@ -360,6 +657,7 @@ function makePlaywrightDriver(config) {
360
657
  }
361
658
  appliedRoutes = [];
362
659
  routeDefinitions.length = 0;
660
+ debugLog("clearNetworkMocks");
363
661
  },
364
662
  catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
365
663
  }),
@@ -367,6 +665,7 @@ function makePlaywrightDriver(config) {
367
665
  try: async () => {
368
666
  currentNetworkConditions = { ...conditions };
369
667
  await applyNetworkConditions();
668
+ debugLog("setNetworkConditions", JSON.stringify(conditions));
370
669
  },
371
670
  catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
372
671
  }),
@@ -374,6 +673,7 @@ function makePlaywrightDriver(config) {
374
673
  try: async () => {
375
674
  const cookies = await context.cookies();
376
675
  await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
676
+ debugLog("saveCookies", path);
377
677
  },
378
678
  catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
379
679
  }),
@@ -385,20 +685,112 @@ function makePlaywrightDriver(config) {
385
685
  throw new Error("Cookie file must contain an array of cookies.");
386
686
  }
387
687
  await context.addCookies(cookies);
688
+ debugLog("loadCookies", path);
388
689
  },
389
690
  catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
390
691
  }),
391
692
  saveAuthState: (path) => Effect.tryPromise({
392
- try: () => context.storageState({ path }).then(() => {
393
- }),
693
+ try: async () => {
694
+ await context.storageState({ path });
695
+ debugLog("saveAuthState", path);
696
+ },
394
697
  catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
395
698
  }),
396
699
  loadAuthState: (path) => Effect.tryPromise({
397
700
  try: async () => {
398
701
  await replaceContext(path);
702
+ updateHarPage(page);
703
+ debugLog("loadAuthState", path);
399
704
  },
400
705
  catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
401
- })
706
+ }),
707
+ downloadFile: (path) => Effect.tryPromise({
708
+ try: async () => {
709
+ const download = await nextDownload();
710
+ await download.saveAs(path);
711
+ debugLog("downloadFile", path, download.suggestedFilename());
712
+ },
713
+ catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
714
+ }),
715
+ uploadFile: (selector, path) => Effect.tryPromise({
716
+ try: async () => {
717
+ await setInputFiles(selector, path);
718
+ debugLog("uploadFile", path);
719
+ },
720
+ catch: (e) => new DriverError({ message: `Failed to upload file ${path}: ${e}` })
721
+ }),
722
+ newTab: (url) => Effect.tryPromise({
723
+ try: async () => {
724
+ const nextPage = await context.newPage();
725
+ attachPageDiagnostics(nextPage);
726
+ page = nextPage;
727
+ if (url) {
728
+ await nextPage.goto(url);
729
+ }
730
+ updateHarPage(nextPage);
731
+ const tabId = getTabId(nextPage);
732
+ debugLog("newTab", tabId, url ?? "about:blank");
733
+ return tabId;
734
+ },
735
+ catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
736
+ }),
737
+ switchToTab: (index) => Effect.tryPromise({
738
+ try: async () => {
739
+ const openPages = context.pages();
740
+ const nextPage = openPages[index];
741
+ if (!nextPage) {
742
+ throw new Error(
743
+ `Tab index ${index} is out of range. Open tabs: ${Math.max(openPages.length - 1, 0)}.`
744
+ );
745
+ }
746
+ page = nextPage;
747
+ attachPageDiagnostics(page);
748
+ updateHarPage(page);
749
+ debugLog("switchToTab", index, getTabId(page));
750
+ },
751
+ catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
752
+ }),
753
+ closeTab: () => Effect.tryPromise({
754
+ try: async () => {
755
+ const openPages = context.pages();
756
+ if (openPages.length <= 1) {
757
+ await page.goto("about:blank");
758
+ updateHarPage(page);
759
+ debugLog("closeTab", "last-tab-reset");
760
+ return;
761
+ }
762
+ const currentIndex = openPages.indexOf(page);
763
+ const fallbackIndex = currentIndex <= 0 ? 1 : Math.min(currentIndex - 1, openPages.length - 1);
764
+ const fallbackPage = openPages[fallbackIndex];
765
+ const closingTabId = getTabId(page);
766
+ await page.close();
767
+ page = fallbackPage;
768
+ updateHarPage(page);
769
+ debugLog("closeTab", closingTabId, "->", getTabId(page));
770
+ },
771
+ catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
772
+ }),
773
+ getTabIds: () => Effect.sync(() => {
774
+ const ids = context.pages().map((openPage) => getTabId(openPage));
775
+ debugLog("getTabIds", ids.join(", "));
776
+ return ids;
777
+ }),
778
+ getConsoleLogs: () => Effect.succeed([...consoleLogs]),
779
+ getJSErrors: () => Effect.succeed([...jsErrors]),
780
+ getHAR: () => Effect.sync(() => ({
781
+ log: {
782
+ version: "1.2",
783
+ creator: {
784
+ name: "spana",
785
+ version: "dev"
786
+ },
787
+ browser: {
788
+ name: browserLabels[browserName]
789
+ },
790
+ pages: Array.from(harPages.values()).map((harPage) => ({ ...harPage })),
791
+ entries: [...harEntries]
792
+ }
793
+ }))
402
794
  };
403
795
  return service;
404
796
  });
@@ -503,11 +895,21 @@ var UiAutomator2Client = class {
503
895
  return value;
504
896
  }
505
897
  async getWindowSize() {
506
- const value = await this.request(
507
- "GET",
508
- this.sessionPath("/window/size")
509
- );
510
- return value;
898
+ try {
899
+ return await this.request(
900
+ "GET",
901
+ this.sessionPath("/window/current/size")
902
+ );
903
+ } catch {
904
+ try {
905
+ return await this.request(
906
+ "GET",
907
+ this.sessionPath("/window/size")
908
+ );
909
+ } catch {
910
+ return { width: 1080, height: 1920 };
911
+ }
912
+ }
511
913
  }
512
914
  // ---------------------------------------------------------------------------
513
915
  // Gestures — Appium gesture extensions
@@ -555,14 +957,139 @@ var UiAutomator2Client = class {
555
957
  ]
556
958
  });
557
959
  }
960
+ /**
961
+ * Pinch gesture (zoom out) — two fingers move toward center.
962
+ *
963
+ * @param cx - center X coordinate
964
+ * @param cy - center Y coordinate
965
+ * @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
966
+ * @param duration - gesture duration in milliseconds
967
+ */
968
+ async performPinch(cx, cy, scale, duration) {
969
+ const dist = 200 * scale;
970
+ await this.request("POST", this.sessionPath("/actions"), {
971
+ actions: [
972
+ {
973
+ type: "pointer",
974
+ id: "finger1",
975
+ parameters: { pointerType: "touch" },
976
+ actions: [
977
+ { type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
978
+ { type: "pointerDown", button: 0 },
979
+ { type: "pointerMove", duration, x: Math.round(cx - 10), y: Math.round(cy) },
980
+ { type: "pointerUp", button: 0 }
981
+ ]
982
+ },
983
+ {
984
+ type: "pointer",
985
+ id: "finger2",
986
+ parameters: { pointerType: "touch" },
987
+ actions: [
988
+ { type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
989
+ { type: "pointerDown", button: 0 },
990
+ { type: "pointerMove", duration, x: Math.round(cx + 10), y: Math.round(cy) },
991
+ { type: "pointerUp", button: 0 }
992
+ ]
993
+ }
994
+ ]
995
+ });
996
+ }
997
+ /**
998
+ * Zoom gesture (zoom in) — two fingers move away from center.
999
+ *
1000
+ * @param cx - center X coordinate
1001
+ * @param cy - center Y coordinate
1002
+ * @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
1003
+ * @param duration - gesture duration in milliseconds
1004
+ */
1005
+ async performZoom(cx, cy, scale, duration) {
1006
+ const dist = 200 * scale;
1007
+ await this.request("POST", this.sessionPath("/actions"), {
1008
+ actions: [
1009
+ {
1010
+ type: "pointer",
1011
+ id: "finger1",
1012
+ parameters: { pointerType: "touch" },
1013
+ actions: [
1014
+ { type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
1015
+ { type: "pointerDown", button: 0 },
1016
+ { type: "pointerMove", duration, x: Math.round(cx - dist), y: Math.round(cy) },
1017
+ { type: "pointerUp", button: 0 }
1018
+ ]
1019
+ },
1020
+ {
1021
+ type: "pointer",
1022
+ id: "finger2",
1023
+ parameters: { pointerType: "touch" },
1024
+ actions: [
1025
+ { type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
1026
+ { type: "pointerDown", button: 0 },
1027
+ { type: "pointerMove", duration, x: Math.round(cx + dist), y: Math.round(cy) },
1028
+ { type: "pointerUp", button: 0 }
1029
+ ]
1030
+ }
1031
+ ]
1032
+ });
1033
+ }
1034
+ /**
1035
+ * Arbitrary multi-touch gesture using W3C Actions.
1036
+ * Each sequence represents one finger with a series of actions.
1037
+ */
1038
+ async performMultiTouch(sequences) {
1039
+ const actions = sequences.map((seq) => ({
1040
+ type: "pointer",
1041
+ id: `finger${seq.id}`,
1042
+ parameters: { pointerType: "touch" },
1043
+ actions: seq.actions.map((a) => {
1044
+ switch (a.type) {
1045
+ case "move":
1046
+ return {
1047
+ type: "pointerMove",
1048
+ duration: a.duration ?? 0,
1049
+ x: Math.round(a.x),
1050
+ y: Math.round(a.y)
1051
+ };
1052
+ case "down":
1053
+ return { type: "pointerDown", button: 0 };
1054
+ case "up":
1055
+ return { type: "pointerUp", button: 0 };
1056
+ case "pause":
1057
+ return { type: "pause", duration: a.duration };
1058
+ }
1059
+ })
1060
+ }));
1061
+ await this.request("POST", this.sessionPath("/actions"), { actions });
1062
+ }
558
1063
  // ---------------------------------------------------------------------------
559
1064
  // Text / keyboard
560
1065
  // ---------------------------------------------------------------------------
561
1066
  async sendKeys(text) {
1067
+ const hasComplexChars = /[\u{10000}-\u{10FFFF}]|\u200D/u.test(text);
1068
+ if (hasComplexChars) {
1069
+ const segments = splitGraphemes(text);
1070
+ let simpleBatch = "";
1071
+ for (const segment of segments) {
1072
+ if (/[\u{10000}-\u{10FFFF}]|\u200D/u.test(segment)) {
1073
+ if (simpleBatch) {
1074
+ await this.sendKeysViaActions(simpleBatch);
1075
+ simpleBatch = "";
1076
+ }
1077
+ } else {
1078
+ simpleBatch += segment;
1079
+ }
1080
+ }
1081
+ if (simpleBatch) {
1082
+ await this.sendKeysViaActions(simpleBatch);
1083
+ }
1084
+ return;
1085
+ }
1086
+ await this.sendKeysViaActions(text);
1087
+ }
1088
+ async sendKeysViaActions(text) {
562
1089
  const keyActions = [];
563
- for (const ch of text) {
564
- keyActions.push({ type: "keyDown", value: ch });
565
- keyActions.push({ type: "keyUp", value: ch });
1090
+ for (const segment of splitGraphemes(text)) {
1091
+ keyActions.push({ type: "keyDown", value: segment });
1092
+ keyActions.push({ type: "keyUp", value: segment });
566
1093
  }
567
1094
  await this.request("POST", this.sessionPath("/actions"), {
568
1095
  actions: [
@@ -638,7 +1165,10 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
638
1165
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
639
1166
  }),
640
1167
  doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
641
- try: () => client.performDoubleTap(x, y),
1168
+ try: async () => {
1169
+ await client.performTap(x, y);
1170
+ await client.performTap(x, y);
1171
+ },
642
1172
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
643
1173
  }),
644
1174
  longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
@@ -649,6 +1179,18 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
649
1179
  try: () => client.performSwipe(sx, sy, ex, ey, dur),
650
1180
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
651
1181
  }),
1182
+ pinch: (cx, cy, scale, duration) => Effect2.tryPromise({
1183
+ try: () => client.performPinch(cx, cy, scale, duration),
1184
+ catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
1185
+ }),
1186
+ zoom: (cx, cy, scale, duration) => Effect2.tryPromise({
1187
+ try: () => client.performZoom(cx, cy, scale, duration),
1188
+ catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
1189
+ }),
1190
+ multiTouch: (sequences) => Effect2.tryPromise({
1191
+ try: () => client.performMultiTouch(sequences),
1192
+ catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
1193
+ }),
652
1194
  // -----------------------------------------------------------------------
653
1195
  // Text input
654
1196
  // -----------------------------------------------------------------------
@@ -702,13 +1244,13 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
702
1244
  }
703
1245
  if (opts?.deepLink) {
704
1246
  adbOpenLink(serial, opts.deepLink, bundleId);
705
- await new Promise((resolve2) => setTimeout(resolve2, 500));
1247
+ await new Promise((resolve) => setTimeout(resolve, 500));
706
1248
  } else {
707
1249
  adbForceStop(serial, bundleId);
708
1250
  if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
709
1251
  const { execFileSync } = await import("child_process");
710
- const { findADB: findADB2 } = await import("./android-PAPJJWVN.js");
711
- const adb = findADB2();
1252
+ const { findADB } = await import("./android-PAPJJWVN.js");
1253
+ const adb = findADB();
712
1254
  if (!adb) throw new Error("adb not found");
713
1255
  const startArgs = [
714
1256
  "-s",
@@ -730,7 +1272,7 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
730
1272
  adbLaunchApp(serial, bundleId);
731
1273
  }
732
1274
  }
733
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1275
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
734
1276
  },
735
1277
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
736
1278
  }),
@@ -759,7 +1301,7 @@ function createUiAutomator2Driver(host, port, serial, packageName) {
759
1301
  openLink: (url) => Effect2.tryPromise({
760
1302
  try: async () => {
761
1303
  adbOpenLink(serial, url, packageName);
762
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1304
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
763
1305
  },
764
1306
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
765
1307
  }),
@@ -947,7 +1489,23 @@ var WDAClient = class {
947
1489
  await this.request("POST", this.sessionPath("/wda/tap"), { x, y });
948
1490
  }
949
1491
  async doubleTap(x, y) {
950
- await this.request("POST", this.sessionPath("/wda/doubleTap"), { x, y });
1492
+ const rx = Math.round(x);
1493
+ const ry = Math.round(y);
1494
+ const singleTap = [
1495
+ {
1496
+ type: "pointer",
1497
+ id: "finger1",
1498
+ parameters: { pointerType: "touch" },
1499
+ actions: [
1500
+ { type: "pointerMove", duration: 0, x: rx, y: ry },
1501
+ { type: "pointerDown", button: 0 },
1502
+ { type: "pointerUp", button: 0 }
1503
+ ]
1504
+ }
1505
+ ];
1506
+ await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
1507
+ await new Promise((resolve) => setTimeout(resolve, 200));
1508
+ await this.request("POST", this.sessionPath("/actions"), { actions: singleTap });
951
1509
  }
952
1510
  /**
953
1511
  * Long-presses at coordinates.
@@ -975,6 +1533,130 @@ var WDAClient = class {
975
1533
  duration: durationSec
976
1534
  });
977
1535
  }
1536
+ /**
1537
+ * Pinch gesture (zoom out) — two fingers move toward center.
1538
+ *
1539
+ * @param cx - center X coordinate
1540
+ * @param cy - center Y coordinate
1541
+ * @param scale - 0..1 representing how far fingers start from center (as fraction of 200px)
1542
+ * @param durationSec - gesture duration in seconds (WDA convention)
1543
+ */
1544
+ async pinch(cx, cy, scale, durationSec) {
1545
+ const dist = 200 * scale;
1546
+ const durationMs = durationSec * 1e3;
1547
+ await this.request("POST", this.sessionPath("/actions"), {
1548
+ actions: [
1549
+ {
1550
+ type: "pointer",
1551
+ id: "finger1",
1552
+ parameters: { pointerType: "touch" },
1553
+ actions: [
1554
+ { type: "pointerMove", duration: 0, x: Math.round(cx - dist), y: Math.round(cy) },
1555
+ { type: "pointerDown", button: 0 },
1556
+ {
1557
+ type: "pointerMove",
1558
+ duration: durationMs,
1559
+ x: Math.round(cx - 10),
1560
+ y: Math.round(cy)
1561
+ },
1562
+ { type: "pointerUp", button: 0 }
1563
+ ]
1564
+ },
1565
+ {
1566
+ type: "pointer",
1567
+ id: "finger2",
1568
+ parameters: { pointerType: "touch" },
1569
+ actions: [
1570
+ { type: "pointerMove", duration: 0, x: Math.round(cx + dist), y: Math.round(cy) },
1571
+ { type: "pointerDown", button: 0 },
1572
+ {
1573
+ type: "pointerMove",
1574
+ duration: durationMs,
1575
+ x: Math.round(cx + 10),
1576
+ y: Math.round(cy)
1577
+ },
1578
+ { type: "pointerUp", button: 0 }
1579
+ ]
1580
+ }
1581
+ ]
1582
+ });
1583
+ }
1584
+ /**
1585
+ * Zoom gesture (zoom in) — two fingers move away from center.
1586
+ *
1587
+ * @param cx - center X coordinate
1588
+ * @param cy - center Y coordinate
1589
+ * @param scale - 0..1 representing how far fingers end from center (as fraction of 200px)
1590
+ * @param durationSec - gesture duration in seconds (WDA convention)
1591
+ */
1592
+ async zoom(cx, cy, scale, durationSec) {
1593
+ const dist = 200 * scale;
1594
+ const durationMs = durationSec * 1e3;
1595
+ await this.request("POST", this.sessionPath("/actions"), {
1596
+ actions: [
1597
+ {
1598
+ type: "pointer",
1599
+ id: "finger1",
1600
+ parameters: { pointerType: "touch" },
1601
+ actions: [
1602
+ { type: "pointerMove", duration: 0, x: Math.round(cx - 10), y: Math.round(cy) },
1603
+ { type: "pointerDown", button: 0 },
1604
+ {
1605
+ type: "pointerMove",
1606
+ duration: durationMs,
1607
+ x: Math.round(cx - dist),
1608
+ y: Math.round(cy)
1609
+ },
1610
+ { type: "pointerUp", button: 0 }
1611
+ ]
1612
+ },
1613
+ {
1614
+ type: "pointer",
1615
+ id: "finger2",
1616
+ parameters: { pointerType: "touch" },
1617
+ actions: [
1618
+ { type: "pointerMove", duration: 0, x: Math.round(cx + 10), y: Math.round(cy) },
1619
+ { type: "pointerDown", button: 0 },
1620
+ {
1621
+ type: "pointerMove",
1622
+ duration: durationMs,
1623
+ x: Math.round(cx + dist),
1624
+ y: Math.round(cy)
1625
+ },
1626
+ { type: "pointerUp", button: 0 }
1627
+ ]
1628
+ }
1629
+ ]
1630
+ });
1631
+ }
1632
+ /**
1633
+ * Arbitrary multi-touch gesture using W3C Actions.
1634
+ */
1635
+ async multiTouch(sequences) {
1636
+ const actions = sequences.map((seq) => ({
1637
+ type: "pointer",
1638
+ id: `finger${seq.id}`,
1639
+ parameters: { pointerType: "touch" },
1640
+ actions: seq.actions.map((a) => {
1641
+ switch (a.type) {
1642
+ case "move":
1643
+ return {
1644
+ type: "pointerMove",
1645
+ duration: a.duration ?? 0,
1646
+ x: Math.round(a.x),
1647
+ y: Math.round(a.y)
1648
+ };
1649
+ case "down":
1650
+ return { type: "pointerDown", button: 0 };
1651
+ case "up":
1652
+ return { type: "pointerUp", button: 0 };
1653
+ case "pause":
1654
+ return { type: "pause", duration: a.duration };
1655
+ }
1656
+ })
1657
+ }));
1658
+ await this.request("POST", this.sessionPath("/actions"), { actions });
1659
+ }
978
1660
  // ---------------------------------------------------------------------------
979
1661
  // Text / keyboard
980
1662
  // ---------------------------------------------------------------------------
@@ -983,10 +1665,9 @@ var WDAClient = class {
983
1665
  *
984
1666
  * @param frequency - typing speed in keys/sec (0 = WDA default ~60/s)
985
1667
  */
986
- async sendKeys(text, frequency = 0) {
1668
+ async sendKeys(text, frequency = 25) {
987
1669
  const body = {
988
- value: [...text]
989
- // spread to char array
1670
+ value: splitGraphemes(text)
990
1671
  };
991
1672
  if (frequency > 0) {
992
1673
  body["frequency"] = frequency;
@@ -1055,13 +1736,17 @@ function msToSec(ms) {
1055
1736
  return ms / 1e3;
1056
1737
  }
1057
1738
  function sleep(ms) {
1058
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1739
+ return new Promise((resolve) => setTimeout(resolve, ms));
1059
1740
  }
1060
1741
  function replaceUrlScheme(url, scheme) {
1061
1742
  const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(\/\/.*)$/);
1062
1743
  if (!match) return null;
1063
1744
  return `${scheme}:${match[2]}`;
1064
1745
  }
1746
+ function isSessionError(error) {
1747
+ const msg = String(error).toLowerCase();
1748
+ return msg.includes("session does not exist") || msg.includes("unable to connect") || msg.includes("no active session") || msg.includes("invalid session") || /status[:\s]*404/.test(msg);
1749
+ }
1065
1750
  function createWDADriver(host, port, bundleId, simulatorUdid) {
1066
1751
  return Effect3.gen(function* () {
1067
1752
  const client = new WDAClient(host, port);
@@ -1080,6 +1765,23 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1080
1765
  }
1081
1766
  throw lastError ?? new Error("Failed to create WDA session");
1082
1767
  };
1768
+ const withSessionRecovery = async (fn) => {
1769
+ try {
1770
+ return await fn();
1771
+ } catch (error) {
1772
+ if (!isSessionError(error)) throw error;
1773
+ try {
1774
+ await client.deleteSession();
1775
+ } catch {
1776
+ }
1777
+ await createSessionWithRetry(bundleId || void 0);
1778
+ try {
1779
+ await client.disableQuiescence();
1780
+ } catch {
1781
+ }
1782
+ return await fn();
1783
+ }
1784
+ };
1083
1785
  const activateSimulatorApp = async (targetBundleId) => {
1084
1786
  if (!targetBundleId) return;
1085
1787
  await client.activateApp(targetBundleId);
@@ -1156,35 +1858,60 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1156
1858
  // Hierarchy
1157
1859
  // -----------------------------------------------------------------------
1158
1860
  dumpHierarchy: () => Effect3.tryPromise({
1159
- try: () => client.getSource(),
1861
+ try: () => withSessionRecovery(() => client.getSource()),
1160
1862
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1161
1863
  }),
1162
1864
  // -----------------------------------------------------------------------
1163
1865
  // Coordinate-level actions
1164
1866
  // -----------------------------------------------------------------------
1165
1867
  tapAtCoordinate: (x, y) => Effect3.tryPromise({
1166
- try: () => client.tap(x, y),
1868
+ try: () => withSessionRecovery(() => client.tap(x, y)),
1167
1869
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1168
1870
  }),
1169
1871
  doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
1170
- try: () => client.doubleTap(x, y),
1872
+ try: () => withSessionRecovery(() => client.doubleTap(x, y)),
1171
1873
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1172
1874
  }),
1173
1875
  longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
1174
1876
  // duration arrives in ms (spana convention) → convert to seconds for WDA
1175
- try: () => client.longPress(x, y, msToSec(duration)),
1877
+ try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
1176
1878
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1177
1879
  }),
1178
1880
  swipe: (sx, sy, ex, ey, dur) => Effect3.tryPromise({
1179
- // dur arrives in ms → convert to seconds for WDA
1180
- try: () => client.swipe(sx, sy, ex, ey, msToSec(dur)),
1881
+ // dur arrives in ms → convert to seconds for WDA.
1882
+ // Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
1883
+ try: async () => {
1884
+ let csy = sy;
1885
+ let cey = ey;
1886
+ try {
1887
+ const size = await client.getWindowSize();
1888
+ const minY = size.height * 0.15;
1889
+ const maxY = size.height * 0.85;
1890
+ csy = Math.max(minY, Math.min(maxY, sy));
1891
+ cey = Math.max(minY, Math.min(maxY, ey));
1892
+ } catch {
1893
+ }
1894
+ await client.swipe(sx, csy, ex, cey, msToSec(dur));
1895
+ },
1181
1896
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1182
1897
  }),
1898
+ pinch: (cx, cy, scale, duration) => Effect3.tryPromise({
1899
+ try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
1900
+ catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
1901
+ }),
1902
+ zoom: (cx, cy, scale, duration) => Effect3.tryPromise({
1903
+ try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
1904
+ catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
1905
+ }),
1906
+ multiTouch: (sequences) => Effect3.tryPromise({
1907
+ try: () => withSessionRecovery(() => client.multiTouch(sequences)),
1908
+ catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
1909
+ }),
1183
1910
  // -----------------------------------------------------------------------
1184
1911
  // Text input
1185
1912
  // -----------------------------------------------------------------------
1186
1913
  inputText: (text) => Effect3.tryPromise({
1187
- try: () => client.sendKeys(text),
1914
+ try: () => withSessionRecovery(() => client.sendKeys(text)),
1188
1915
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1189
1916
  }),
1190
1917
  pressKey: (key) => Effect3.tryPromise({
@@ -1203,21 +1930,25 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1203
1930
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1204
1931
  }),
1205
1932
  hideKeyboard: () => Effect3.tryPromise({
1206
- // WDA hides the keyboard when no text field has focus; pressing home
1207
- // is the most reliable cross-version approach.
1208
- try: () => client.pressHome(),
1933
+ // Dismiss keyboard by tapping above the keyboard area.
1934
+ // The previous approach (pressHome) backgrounds the app on iOS.
1935
+ try: async () => {
1936
+ const size = await client.getWindowSize();
1937
+ await client.tap(size.width / 2, Math.round(size.height * 0.2));
1938
+ await sleep(300);
1939
+ },
1209
1940
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1210
1941
  }),
1211
1942
  // -----------------------------------------------------------------------
1212
1943
  // Queries
1213
1944
  // -----------------------------------------------------------------------
1214
1945
  takeScreenshot: () => Effect3.tryPromise({
1215
- try: () => client.getScreenshot(),
1946
+ try: () => withSessionRecovery(() => client.getScreenshot()),
1216
1947
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1217
1948
  }),
1218
1949
  getDeviceInfo: () => Effect3.tryPromise({
1219
1950
  try: async () => {
1220
- const size = await client.getWindowSize();
1951
+ const size = await withSessionRecovery(() => client.getWindowSize());
1221
1952
  return {
1222
1953
  platform: "ios",
1223
1954
  deviceId: `${host}:${port}`,
@@ -1238,8 +1969,8 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1238
1969
  if (opts?.clearState && simulatorUdid) {
1239
1970
  terminateOnSimulator(simulatorUdid, appBundleId);
1240
1971
  try {
1241
- const { execSync: execSync2 } = await import("child_process");
1242
- execSync2(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
1972
+ const { execSync } = await import("child_process");
1973
+ execSync(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
1243
1974
  stdio: "ignore"
1244
1975
  });
1245
1976
  } catch {
@@ -1254,9 +1985,31 @@ function createWDADriver(host, port, bundleId, simulatorUdid) {
1254
1985
  if (opts?.deepLink) {
1255
1986
  await openSimulatorUrl(opts.deepLink, appBundleId);
1256
1987
  } else {
1257
- launchOnSimulator(simulatorUdid, appBundleId);
1258
- await sleep(500);
1259
- await activateSimulatorApp(appBundleId);
1988
+ try {
1989
+ await client.terminateApp(appBundleId);
1990
+ } catch {
1991
+ try {
1992
+ terminateOnSimulator(simulatorUdid, appBundleId);
1993
+ } catch {
1994
+ }
1995
+ }
1996
+ await sleep(300);
1997
+ try {
1998
+ await client.launchApp(appBundleId);
1999
+ await sleep(500);
2000
+ } catch {
2001
+ launchOnSimulator(simulatorUdid, appBundleId);
2002
+ await sleep(500);
2003
+ try {
2004
+ await client.deleteSession();
2005
+ } catch {
2006
+ }
2007
+ await createSessionWithRetry(appBundleId);
2008
+ try {
2009
+ await client.disableQuiescence();
2010
+ } catch {
2011
+ }
2012
+ }
1260
2013
  }
1261
2014
  return;
1262
2015
  }
@@ -1340,6 +2093,7 @@ function rawNodeToElement(node) {
1340
2093
  return {
1341
2094
  ...node.id !== void 0 ? { id: node.id } : {},
1342
2095
  ...node.text !== void 0 ? { text: node.text } : {},
2096
+ ...node.value !== void 0 ? { value: node.value } : {},
1343
2097
  ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
1344
2098
  // Use role as elementType when present, otherwise fall back to HTML tag name
1345
2099
  ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
@@ -1352,6 +2106,7 @@ function rawNodeToElement(node) {
1352
2106
  ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
1353
2107
  ...node.visible !== void 0 ? { visible: node.visible } : {},
1354
2108
  ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
2109
+ ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
1355
2110
  ...children !== void 0 ? { children } : {}
1356
2111
  };
1357
2112
  }
@@ -1360,26 +2115,7 @@ function parseWebHierarchy(json) {
1360
2115
  return rawNodeToElement(raw);
1361
2116
  }
1362
2117
 
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 };
1369
- }
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 };
1375
- }
1376
- function stripResourceIdPrefix(resourceId) {
1377
- const colonSlash = resourceId.indexOf(":id/");
1378
- if (colonSlash !== -1) {
1379
- return resourceId.slice(colonSlash + 4);
1380
- }
1381
- return resourceId;
1382
- }
2118
+ // src/drivers/common/xml-tokenizer.ts
1383
2119
  function parseAttributes(tagContent) {
1384
2120
  const attrs = {};
1385
2121
  const re = /([\w-]+)="([^"]*)"/g;
@@ -1389,7 +2125,7 @@ function parseAttributes(tagContent) {
1389
2125
  }
1390
2126
  return attrs;
1391
2127
  }
1392
- function tokenizeXML(xml) {
2128
+ function tokenizeXML(xml, wrapperTag) {
1393
2129
  let pos = 0;
1394
2130
  function skipWhitespace() {
1395
2131
  while (pos < xml.length && /\s/.test(xml[pos])) pos++;
@@ -1439,10 +2175,7 @@ function tokenizeXML(xml) {
1439
2175
  }
1440
2176
  const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
1441
2177
  const attrs = parseAttributes(tagBody);
1442
- if (!attrs["class"]) {
1443
- attrs["class"] = tagName;
1444
- }
1445
- const node = { attrs, children: [] };
2178
+ const node = { tagName, attrs, children: [] };
1446
2179
  if (!selfClosing) {
1447
2180
  while (pos < xml.length) {
1448
2181
  skipWhitespace();
@@ -1461,6 +2194,7 @@ function tokenizeXML(xml) {
1461
2194
  return node;
1462
2195
  }
1463
2196
  const roots = [];
2197
+ const closingWrapper = `/${wrapperTag}`;
1464
2198
  while (pos < xml.length) {
1465
2199
  skipWhitespace();
1466
2200
  if (pos >= xml.length) break;
@@ -1472,13 +2206,13 @@ function tokenizeXML(xml) {
1472
2206
  let nameEnd = peek;
1473
2207
  while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
1474
2208
  const peekName = xml.slice(peek, nameEnd);
1475
- if (peekName === "hierarchy") {
2209
+ if (peekName === wrapperTag) {
1476
2210
  const close = xml.indexOf(">", pos);
1477
2211
  if (close === -1) break;
1478
2212
  pos = close + 1;
1479
2213
  continue;
1480
2214
  }
1481
- if (peekName === "/hierarchy") {
2215
+ if (peekName === closingWrapper) {
1482
2216
  const close = xml.indexOf(">", pos);
1483
2217
  if (close !== -1) pos = close + 1;
1484
2218
  break;
@@ -1495,6 +2229,35 @@ function tokenizeXML(xml) {
1495
2229
  }
1496
2230
  return roots;
1497
2231
  }
2232
+
2233
+ // src/drivers/uiautomator2/pagesource.ts
2234
+ function parseBounds(s) {
2235
+ const normalized = s.replace("][", ",").replaceAll(/[[\]]/g, "");
2236
+ const parts = normalized.split(",");
2237
+ if (parts.length !== 4) {
2238
+ return { x: 0, y: 0, width: 0, height: 0 };
2239
+ }
2240
+ const x1 = parseInt(parts[0], 10);
2241
+ const y1 = parseInt(parts[1], 10);
2242
+ const x2 = parseInt(parts[2], 10);
2243
+ const y2 = parseInt(parts[3], 10);
2244
+ return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };
2245
+ }
2246
+ function stripResourceIdPrefix(resourceId) {
2247
+ const colonSlash = resourceId.indexOf(":id/");
2248
+ if (colonSlash !== -1) {
2249
+ return resourceId.slice(colonSlash + 4);
2250
+ }
2251
+ return resourceId;
2252
+ }
2253
+ function prepareAndroidNode(node) {
2254
+ if (!node.attrs["class"]) {
2255
+ node.attrs["class"] = node.tagName;
2256
+ }
2257
+ for (const child of node.children) {
2258
+ prepareAndroidNode(child);
2259
+ }
2260
+ }
1498
2261
  function rawNodeToElement2(node) {
1499
2262
  const a = node.attrs;
1500
2263
  const rawId = a["resource-id"] ?? "";
@@ -1507,21 +2270,32 @@ function rawNodeToElement2(node) {
1507
2270
  const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
1508
2271
  const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1509
2272
  const clickable = a["clickable"] !== void 0 ? a["clickable"] === "true" : void 0;
2273
+ const isInput = elementType === "android.widget.EditText" || elementType === "android.widget.AutoCompleteTextView";
2274
+ const value = isInput ? text : void 0;
2275
+ const attributes = {};
2276
+ for (const [key, val] of Object.entries(a)) {
2277
+ if (key !== "bounds") attributes[key] = val;
2278
+ }
1510
2279
  const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
1511
2280
  return {
1512
2281
  ...id !== void 0 ? { id } : {},
1513
2282
  ...text !== void 0 ? { text } : {},
2283
+ ...value !== void 0 ? { value } : {},
1514
2284
  ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1515
2285
  ...elementType !== void 0 ? { elementType } : {},
1516
2286
  bounds,
1517
2287
  ...enabled !== void 0 ? { enabled } : {},
1518
2288
  ...focused !== void 0 ? { focused } : {},
1519
2289
  ...clickable !== void 0 ? { clickable } : {},
2290
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
1520
2291
  ...children !== void 0 ? { children } : {}
1521
2292
  };
1522
2293
  }
1523
2294
  function parseAndroidHierarchy(xml) {
1524
- const roots = tokenizeXML(xml);
2295
+ const roots = tokenizeXML(xml, "hierarchy");
2296
+ for (const root of roots) {
2297
+ prepareAndroidNode(root);
2298
+ }
1525
2299
  if (roots.length === 0) {
1526
2300
  throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
1527
2301
  }
@@ -1556,117 +2330,11 @@ var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
1556
2330
  "XCUIElementTypeToggle",
1557
2331
  "XCUIElementTypePageIndicator"
1558
2332
  ]);
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
- }
2333
+ function prepareIOSNode(node) {
2334
+ node.tagName = node.attrs["type"] ?? node.tagName;
2335
+ for (const child of node.children) {
2336
+ prepareIOSNode(child);
1668
2337
  }
1669
- return roots;
1670
2338
  }
1671
2339
  function rawNodeToElement3(node) {
1672
2340
  const a = node.attrs;
@@ -1674,6 +2342,8 @@ function rawNodeToElement3(node) {
1674
2342
  const id = a["name"] || void 0;
1675
2343
  const accessibilityLabel = a["label"] || void 0;
1676
2344
  const text = a["value"] || void 0;
2345
+ const isTextField = elementType === "XCUIElementTypeTextField" || elementType === "XCUIElementTypeSecureTextField" || elementType === "XCUIElementTypeTextView";
2346
+ const value = isTextField ? a["value"] || void 0 : void 0;
1677
2347
  const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
1678
2348
  const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
1679
2349
  const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
@@ -1683,10 +2353,15 @@ function rawNodeToElement3(node) {
1683
2353
  const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
1684
2354
  const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
1685
2355
  const clickable = elementType !== void 0 ? CLICKABLE_TYPES.has(elementType) : void 0;
2356
+ const attributes = {};
2357
+ for (const [key, val] of Object.entries(a)) {
2358
+ attributes[key] = val;
2359
+ }
1686
2360
  const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
1687
2361
  return {
1688
2362
  ...id !== void 0 ? { id } : {},
1689
2363
  ...text !== void 0 ? { text } : {},
2364
+ ...value !== void 0 ? { value } : {},
1690
2365
  ...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
1691
2366
  ...elementType !== void 0 ? { elementType } : {},
1692
2367
  bounds,
@@ -1694,11 +2369,15 @@ function rawNodeToElement3(node) {
1694
2369
  ...visible !== void 0 ? { visible } : {},
1695
2370
  ...focused !== void 0 ? { focused } : {},
1696
2371
  ...clickable !== void 0 ? { clickable } : {},
2372
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
1697
2373
  ...children !== void 0 ? { children } : {}
1698
2374
  };
1699
2375
  }
1700
2376
  function parseIOSHierarchy(xml) {
1701
- const roots = tokenizeXML2(xml);
2377
+ const roots = tokenizeXML(xml, "AppiumAUT");
2378
+ for (const root of roots) {
2379
+ prepareIOSNode(root);
2380
+ }
1702
2381
  if (roots.length === 0) {
1703
2382
  throw new Error("parseIOSHierarchy: no elements found in page source");
1704
2383
  }
@@ -1712,122 +2391,12 @@ function parseIOSHierarchy(xml) {
1712
2391
  };
1713
2392
  }
1714
2393
 
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) {
1724
- try {
1725
- const packageJsonPath = require2.resolve(`${packageName}/package.json`);
1726
- return resolve(dirname(packageJsonPath), subpath);
1727
- } catch {
1728
- return null;
1729
- }
1730
- }
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"
1738
- );
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) };
1749
- }
1750
- }
1751
- return null;
1752
- }
1753
- function installUiAutomator2(serial) {
1754
- const apks = findUiAutomator2APK();
1755
- if (!apks) {
1756
- throw new Error(
1757
- "UiAutomator2 server APK not found. Install appium-uiautomator2-server or place APKs in drivers/android/"
1758
- );
1759
- }
1760
- console.log(`Installing UiAutomator2 server on ${serial}...`);
1761
- adbInstall(serial, apks.serverApk);
1762
- adbInstall(serial, apks.testApk);
1763
- console.log("UiAutomator2 server installed.");
1764
- }
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
- }
1772
- }
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 {
1782
- }
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;
1801
- for (let i = 0; i < maxRetries; i++) {
1802
- try {
1803
- const res = await fetch(`http://localhost:${port}/status`);
1804
- if (res.ok) {
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 };
1815
- }
1816
- } catch {
1817
- }
1818
- await new Promise((r) => setTimeout(r, 1e3));
1819
- }
1820
- releasePort(port);
1821
- throw new Error(`UiAutomator2 server did not start within ${maxRetries} seconds`);
1822
- }
1823
-
1824
2394
  export {
1825
2395
  makePlaywrightDriver,
1826
2396
  createUiAutomator2Driver,
1827
2397
  createWDADriver,
1828
2398
  parseWebHierarchy,
1829
2399
  parseAndroidHierarchy,
1830
- parseIOSHierarchy,
1831
- setupUiAutomator2
2400
+ parseIOSHierarchy
1832
2401
  };
1833
- //# sourceMappingURL=chunk-CKJQX73M.js.map
2402
+ //# sourceMappingURL=chunk-WQ4GXUUE.js.map