spana-test 0.0.2 → 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.
- package/.agents/skills/spana-testing/SKILL.md +304 -0
- package/README.md +308 -88
- package/dist/agent/index.d.ts +110 -0
- package/dist/agent/index.js +25 -0
- package/dist/allure-PTTVORQ6.js +124 -0
- package/dist/allure-PTTVORQ6.js.map +1 -0
- package/dist/android-PAPJJWVN.js +34 -0
- package/dist/android-PAPJJWVN.js.map +1 -0
- package/dist/chunk-3FSZNKEF.js +62 -0
- package/dist/chunk-3FSZNKEF.js.map +1 -0
- package/dist/chunk-3YR4GUGE.js +249 -0
- package/dist/chunk-3YR4GUGE.js.map +1 -0
- package/dist/{discover-XIRJTZ7Z.js → chunk-AEKDFFPJ.js} +12 -5
- package/dist/{discover-XIRJTZ7Z.js.map → chunk-AEKDFFPJ.js.map} +1 -1
- package/dist/chunk-BF37W5EG.js +125 -0
- package/dist/chunk-BF37W5EG.js.map +1 -0
- package/dist/chunk-DGUM43GV.js +11 -0
- package/dist/chunk-DGUM43GV.js.map +1 -0
- package/dist/chunk-EXLUY7KT.js +21 -0
- package/dist/chunk-EXLUY7KT.js.map +1 -0
- package/dist/chunk-FNDOEMOL.js +62 -0
- package/dist/chunk-FNDOEMOL.js.map +1 -0
- package/dist/{chunk-CYEDLQJ4.js → chunk-GZK22EIE.js} +76 -102
- package/dist/chunk-GZK22EIE.js.map +1 -0
- package/dist/chunk-HWFDXIXR.js +183 -0
- package/dist/chunk-HWFDXIXR.js.map +1 -0
- package/dist/chunk-IJIASIX5.js +314 -0
- package/dist/chunk-IJIASIX5.js.map +1 -0
- package/dist/chunk-KJPHH2TW.js +168 -0
- package/dist/chunk-KJPHH2TW.js.map +1 -0
- package/dist/chunk-L7MFJF46.js +137 -0
- package/dist/chunk-L7MFJF46.js.map +1 -0
- package/dist/chunk-MRH7SK52.js +134 -0
- package/dist/chunk-MRH7SK52.js.map +1 -0
- package/dist/chunk-P7JQRLP4.js +114 -0
- package/dist/chunk-P7JQRLP4.js.map +1 -0
- package/dist/chunk-S2XNAKSO.js +1087 -0
- package/dist/chunk-S2XNAKSO.js.map +1 -0
- package/dist/chunk-S4R4OR7T.js +358 -0
- package/dist/chunk-S4R4OR7T.js.map +1 -0
- package/dist/chunk-SFBRFB2N.js +277 -0
- package/dist/chunk-SFBRFB2N.js.map +1 -0
- package/dist/chunk-VNYF5BHX.js +494 -0
- package/dist/chunk-VNYF5BHX.js.map +1 -0
- package/dist/chunk-WBU34APM.js +38 -0
- package/dist/chunk-WBU34APM.js.map +1 -0
- package/dist/chunk-WQ4GXUUE.js +2402 -0
- package/dist/chunk-WQ4GXUUE.js.map +1 -0
- package/dist/chunk-YBZCOQXJ.js +311 -0
- package/dist/chunk-YBZCOQXJ.js.map +1 -0
- package/dist/cli.js +428 -34
- package/dist/cli.js.map +1 -1
- package/dist/compiler-74VGKZO6.js +312 -0
- package/dist/compiler-74VGKZO6.js.map +1 -0
- package/dist/config-loader-BJJ3IJJ7.js +9 -0
- package/dist/config-loader-BJJ3IJJ7.js.map +1 -0
- package/dist/console-XWKUTP3D.js +164 -0
- package/dist/console-XWKUTP3D.js.map +1 -0
- package/dist/coordinator-BbUjvvnX.d.ts +383 -0
- package/dist/discover-KZKXHZZA.js +14 -0
- package/dist/discover-KZKXHZZA.js.map +1 -0
- package/dist/doctor-command-T2UX5RV5.js +732 -0
- package/dist/doctor-command-T2UX5RV5.js.map +1 -0
- package/dist/element-DZ0HyJ3C.d.ts +25 -0
- package/dist/flow-BUC9Mf8W.d.ts +128 -0
- package/dist/gherkin/steps.d.ts +32 -0
- package/dist/gherkin/steps.js +39 -0
- package/dist/gherkin/steps.js.map +1 -0
- package/dist/{html-GRB34S6X.js → html-GE6Q4DCG.js} +76 -22
- package/dist/html-GE6Q4DCG.js.map +1 -0
- package/dist/index.d.ts +159 -144
- package/dist/index.js +39 -165
- package/dist/index.js.map +1 -1
- package/dist/init-command-GVMRXIMY.js +121 -0
- package/dist/init-command-GVMRXIMY.js.map +1 -0
- package/dist/init-flow-command-R76AXF4Z.js +34 -0
- package/dist/init-flow-command-R76AXF4Z.js.map +1 -0
- package/dist/installer-YZJ4DV3F.js +22 -0
- package/dist/installer-YZJ4DV3F.js.map +1 -0
- package/dist/ios-ZW6XVNLG.js +50 -0
- package/dist/ios-ZW6XVNLG.js.map +1 -0
- package/dist/json-KS67BZYU.js +39 -0
- package/dist/json-KS67BZYU.js.map +1 -0
- package/dist/{junit-NAGZJOGQ.js → junit-HLC62MK6.js} +15 -4
- package/dist/junit-HLC62MK6.js.map +1 -0
- package/dist/provider-A57C3MU6.js +12 -0
- package/dist/provider-A57C3MU6.js.map +1 -0
- package/dist/redact-U72BUBBR.js +77 -0
- package/dist/redact-U72BUBBR.js.map +1 -0
- package/dist/runner-UXNHVVGG.js +20 -0
- package/dist/runner-UXNHVVGG.js.map +1 -0
- package/dist/server-W7OA3DDN.js +530 -0
- package/dist/server-W7OA3DDN.js.map +1 -0
- package/dist/session-TMNOKYLG.js +17 -0
- package/dist/session-TMNOKYLG.js.map +1 -0
- package/dist/studio-command-6VHTHDUK.js +24 -0
- package/dist/studio-command-6VHTHDUK.js.map +1 -0
- package/dist/test-command-AHMOZLV4.js +2852 -0
- package/dist/test-command-AHMOZLV4.js.map +1 -0
- package/dist/validator-35624P7S.js +20 -0
- package/dist/validator-35624P7S.js.map +1 -0
- package/package.json +41 -4
- package/studio-dist/assets/index-DC6DIXfl.js +188 -0
- package/studio-dist/assets/index-DDKsnBwD.css +1 -0
- package/studio-dist/index.html +13 -0
- package/dist/chunk-CYEDLQJ4.js.map +0 -1
- package/dist/chunk-PVNNKPBW.js +0 -64
- package/dist/chunk-PVNNKPBW.js.map +0 -1
- package/dist/chunk-VZZH66U5.js +0 -1781
- package/dist/chunk-VZZH66U5.js.map +0 -1
- package/dist/console-GPV3M3PC.js +0 -71
- package/dist/console-GPV3M3PC.js.map +0 -1
- package/dist/html-GRB34S6X.js.map +0 -1
- package/dist/json-FK2NSRGC.js +0 -20
- package/dist/json-FK2NSRGC.js.map +0 -1
- package/dist/junit-NAGZJOGQ.js.map +0 -1
- package/dist/runner-LBQUCG3K.js +0 -12
- package/dist/session-U7VP5J2C.js +0 -122
- package/dist/session-U7VP5J2C.js.map +0 -1
- package/dist/test-command-WPYLJYIK.js +0 -636
- package/dist/test-command-WPYLJYIK.js.map +0 -1
- package/dist/validator-J4YSBB66.js +0 -33
- package/dist/validator-J4YSBB66.js.map +0 -1
- /package/dist/{runner-LBQUCG3K.js.map → agent/index.js.map} +0 -0
|
@@ -0,0 +1,2402 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DriverError,
|
|
3
|
+
splitGraphemes
|
|
4
|
+
} from "./chunk-S2XNAKSO.js";
|
|
5
|
+
import {
|
|
6
|
+
adbClearApp,
|
|
7
|
+
adbForceStop,
|
|
8
|
+
adbLaunchApp,
|
|
9
|
+
adbOpenLink
|
|
10
|
+
} from "./chunk-GZK22EIE.js";
|
|
11
|
+
import {
|
|
12
|
+
installedUrlSchemesOnSimulator,
|
|
13
|
+
launchOnSimulator,
|
|
14
|
+
launchWithUrlOnSimulator,
|
|
15
|
+
resetSimulatorKeychain,
|
|
16
|
+
terminateOnSimulator
|
|
17
|
+
} from "./chunk-SFBRFB2N.js";
|
|
18
|
+
|
|
19
|
+
// src/drivers/playwright.ts
|
|
20
|
+
import { readFile, writeFile } from "fs/promises";
|
|
21
|
+
import { Effect, Layer } from "effect";
|
|
22
|
+
import {
|
|
23
|
+
chromium,
|
|
24
|
+
firefox,
|
|
25
|
+
webkit
|
|
26
|
+
} from "playwright-core";
|
|
27
|
+
var browserLaunchers = {
|
|
28
|
+
chromium,
|
|
29
|
+
firefox,
|
|
30
|
+
webkit
|
|
31
|
+
};
|
|
32
|
+
var browserLabels = {
|
|
33
|
+
chromium: "Chromium",
|
|
34
|
+
firefox: "Firefox",
|
|
35
|
+
webkit: "WebKit"
|
|
36
|
+
};
|
|
37
|
+
var CLEAR_STORAGE_SCRIPT = `
|
|
38
|
+
(() => {
|
|
39
|
+
try { localStorage.clear(); } catch {}
|
|
40
|
+
try { sessionStorage.clear(); } catch {}
|
|
41
|
+
})();
|
|
42
|
+
`;
|
|
43
|
+
function hasContentTypeHeader(headers) {
|
|
44
|
+
return Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
|
|
45
|
+
}
|
|
46
|
+
function buildMockResponse(response) {
|
|
47
|
+
if (response.body !== void 0 && response.json !== void 0) {
|
|
48
|
+
throw new DriverError({
|
|
49
|
+
message: "mockNetwork() response cannot include both body and json."
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
const headers = { ...response.headers };
|
|
53
|
+
if (response.contentType && !hasContentTypeHeader(headers)) {
|
|
54
|
+
headers["content-type"] = response.contentType;
|
|
55
|
+
}
|
|
56
|
+
if (response.json !== void 0) {
|
|
57
|
+
return {
|
|
58
|
+
status: response.status ?? 200,
|
|
59
|
+
json: response.json,
|
|
60
|
+
headers
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
status: response.status ?? 200,
|
|
65
|
+
body: response.body ?? "",
|
|
66
|
+
headers
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function toBytesPerSecond(kbps) {
|
|
70
|
+
if (kbps === void 0) {
|
|
71
|
+
return -1;
|
|
72
|
+
}
|
|
73
|
+
return Math.max(Math.round(kbps * 1024 / 8), 0);
|
|
74
|
+
}
|
|
75
|
+
function requiresChromiumThrottling(conditions) {
|
|
76
|
+
return conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
|
|
77
|
+
}
|
|
78
|
+
function currentPageUrl(page) {
|
|
79
|
+
try {
|
|
80
|
+
return page.url();
|
|
81
|
+
} catch {
|
|
82
|
+
return "about:blank";
|
|
83
|
+
}
|
|
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
|
+
}
|
|
108
|
+
function makePlaywrightDriver(config) {
|
|
109
|
+
return Effect.gen(function* () {
|
|
110
|
+
const browserName = config.browser ?? "chromium";
|
|
111
|
+
const browser = yield* Effect.tryPromise({
|
|
112
|
+
try: () => browserLaunchers[browserName].launch({ headless: config.headless ?? true }),
|
|
113
|
+
catch: (e) => new DriverError({ message: `Failed to launch browser: ${e}` })
|
|
114
|
+
});
|
|
115
|
+
let context;
|
|
116
|
+
let page;
|
|
117
|
+
let cdpSession;
|
|
118
|
+
const routeDefinitions = [];
|
|
119
|
+
let appliedRoutes = [];
|
|
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
|
+
};
|
|
349
|
+
const clearStorage = async () => {
|
|
350
|
+
await context.clearCookies();
|
|
351
|
+
await page.evaluate(CLEAR_STORAGE_SCRIPT);
|
|
352
|
+
};
|
|
353
|
+
const applyNetworkConditions = async () => {
|
|
354
|
+
if (browserName !== "chromium" && requiresChromiumThrottling(currentNetworkConditions)) {
|
|
355
|
+
throw new DriverError({
|
|
356
|
+
message: "setNetworkConditions() latency and throughput controls are only supported with the chromium browser. Use offline mode only for firefox or webkit."
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
await context.setOffline(currentNetworkConditions.offline ?? false);
|
|
360
|
+
const shouldUseCDP = browserName === "chromium" && (requiresChromiumThrottling(currentNetworkConditions) || cdpSession !== void 0);
|
|
361
|
+
if (!shouldUseCDP) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const session = cdpSession ?? (cdpSession = await context.newCDPSession(page));
|
|
365
|
+
await session.send("Network.enable");
|
|
366
|
+
await session.send("Network.emulateNetworkConditions", {
|
|
367
|
+
offline: currentNetworkConditions.offline ?? false,
|
|
368
|
+
latency: currentNetworkConditions.latencyMs ?? 0,
|
|
369
|
+
downloadThroughput: toBytesPerSecond(currentNetworkConditions.downloadThroughputKbps),
|
|
370
|
+
uploadThroughput: toBytesPerSecond(currentNetworkConditions.uploadThroughputKbps)
|
|
371
|
+
});
|
|
372
|
+
};
|
|
373
|
+
const applyRouteDefinition = async (definition) => {
|
|
374
|
+
const handler = definition.kind === "mock" ? async (route) => {
|
|
375
|
+
await route.fulfill(buildMockResponse(definition.response));
|
|
376
|
+
} : async (route) => {
|
|
377
|
+
await route.abort();
|
|
378
|
+
};
|
|
379
|
+
await context.route(definition.matcher, handler);
|
|
380
|
+
appliedRoutes.push({ matcher: definition.matcher, handler });
|
|
381
|
+
};
|
|
382
|
+
const reapplyRoutes = async () => {
|
|
383
|
+
appliedRoutes = [];
|
|
384
|
+
for (const definition of routeDefinitions) {
|
|
385
|
+
await applyRouteDefinition(definition);
|
|
386
|
+
}
|
|
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
|
+
};
|
|
421
|
+
const createContextAndPage = async (storageStatePath) => {
|
|
422
|
+
context = await browser.newContext({
|
|
423
|
+
acceptDownloads: true,
|
|
424
|
+
...storageStatePath ? { storageState: storageStatePath } : {}
|
|
425
|
+
});
|
|
426
|
+
page = await context.newPage();
|
|
427
|
+
cdpSession = void 0;
|
|
428
|
+
attachPageDiagnostics(page);
|
|
429
|
+
await reapplyRoutes();
|
|
430
|
+
await applyNetworkConditions();
|
|
431
|
+
};
|
|
432
|
+
const replaceContext = async (storageStatePath) => {
|
|
433
|
+
const previousContext = context;
|
|
434
|
+
const previousPage = page;
|
|
435
|
+
const url = currentPageUrl(page);
|
|
436
|
+
await createContextAndPage(storageStatePath);
|
|
437
|
+
if (url && url !== "about:blank") {
|
|
438
|
+
await page.goto(url);
|
|
439
|
+
}
|
|
440
|
+
await Promise.allSettled([previousPage.close(), previousContext.close()]);
|
|
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
|
+
};
|
|
469
|
+
yield* Effect.tryPromise({
|
|
470
|
+
try: () => createContextAndPage(config.storageState),
|
|
471
|
+
catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
|
|
472
|
+
});
|
|
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
|
+
}),
|
|
478
|
+
dumpHierarchy: () => Effect.tryPromise({
|
|
479
|
+
try: async () => {
|
|
480
|
+
const tree = await page.evaluate(`
|
|
481
|
+
(function() {
|
|
482
|
+
function walk(el) {
|
|
483
|
+
var rect = el.getBoundingClientRect();
|
|
484
|
+
var style = window.getComputedStyle(el);
|
|
485
|
+
var isVisible = style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
|
|
486
|
+
return {
|
|
487
|
+
tag: el.tagName.toLowerCase(),
|
|
488
|
+
id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
|
|
489
|
+
text: el.childNodes.length === 1 && el.childNodes[0] && el.childNodes[0].nodeType === 3
|
|
490
|
+
? (el.childNodes[0].textContent || "").trim() || undefined
|
|
491
|
+
: undefined,
|
|
492
|
+
value: (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT") ? (el.value !== undefined ? String(el.value) : undefined) : undefined,
|
|
493
|
+
accessibilityLabel: el.getAttribute("aria-label") || undefined,
|
|
494
|
+
role: el.getAttribute("role") || undefined,
|
|
495
|
+
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
496
|
+
enabled: !el.hasAttribute("disabled"),
|
|
497
|
+
visible: isVisible && rect.width > 0 && rect.height > 0,
|
|
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; })(),
|
|
500
|
+
children: Array.from(el.children).map(walk),
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
return walk(document.body);
|
|
504
|
+
})()
|
|
505
|
+
`);
|
|
506
|
+
return JSON.stringify(tree);
|
|
507
|
+
},
|
|
508
|
+
catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
|
|
509
|
+
}),
|
|
510
|
+
tapAtCoordinate: (x, y) => Effect.tryPromise({
|
|
511
|
+
try: async () => {
|
|
512
|
+
await page.mouse.click(x, y);
|
|
513
|
+
await page.evaluate(`
|
|
514
|
+
(function(x, y) {
|
|
515
|
+
var el = document.elementFromPoint(x, y);
|
|
516
|
+
if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT")) {
|
|
517
|
+
el.focus();
|
|
518
|
+
}
|
|
519
|
+
})(${x}, ${y})
|
|
520
|
+
`);
|
|
521
|
+
},
|
|
522
|
+
catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
|
|
523
|
+
}),
|
|
524
|
+
doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
|
|
525
|
+
try: () => page.mouse.dblclick(x, y),
|
|
526
|
+
catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
|
|
527
|
+
}),
|
|
528
|
+
longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
|
|
529
|
+
try: async () => {
|
|
530
|
+
await page.mouse.move(x, y);
|
|
531
|
+
await page.mouse.down();
|
|
532
|
+
await new Promise((r) => setTimeout(r, duration));
|
|
533
|
+
await page.mouse.up();
|
|
534
|
+
},
|
|
535
|
+
catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
|
|
536
|
+
}),
|
|
537
|
+
swipe: (startX, startY, endX, endY, duration) => Effect.tryPromise({
|
|
538
|
+
try: async () => {
|
|
539
|
+
await page.mouse.move(startX, startY);
|
|
540
|
+
await page.mouse.down();
|
|
541
|
+
const steps = Math.max(Math.round(duration / 16), 5);
|
|
542
|
+
for (let i = 1; i <= steps; i++) {
|
|
543
|
+
const t = i / steps;
|
|
544
|
+
await page.mouse.move(startX + (endX - startX) * t, startY + (endY - startY) * t);
|
|
545
|
+
}
|
|
546
|
+
await page.mouse.up();
|
|
547
|
+
},
|
|
548
|
+
catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
|
|
549
|
+
}),
|
|
550
|
+
inputText: (text) => Effect.tryPromise({
|
|
551
|
+
try: () => page.keyboard.insertText(text),
|
|
552
|
+
catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
|
|
553
|
+
}),
|
|
554
|
+
pressKey: (key) => Effect.tryPromise({
|
|
555
|
+
try: () => page.keyboard.press(key),
|
|
556
|
+
catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
|
|
557
|
+
}),
|
|
558
|
+
hideKeyboard: () => Effect.void,
|
|
559
|
+
takeScreenshot: () => Effect.tryPromise({
|
|
560
|
+
try: async () => {
|
|
561
|
+
const buffer = await page.screenshot();
|
|
562
|
+
return new Uint8Array(buffer);
|
|
563
|
+
},
|
|
564
|
+
catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
|
|
565
|
+
}),
|
|
566
|
+
getDeviceInfo: () => Effect.tryPromise({
|
|
567
|
+
try: async () => {
|
|
568
|
+
const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
|
|
569
|
+
return {
|
|
570
|
+
platform: "web",
|
|
571
|
+
deviceId: `playwright-${browserName}`,
|
|
572
|
+
name: browserLabels[browserName],
|
|
573
|
+
isEmulator: false,
|
|
574
|
+
screenWidth: viewport.width,
|
|
575
|
+
screenHeight: viewport.height,
|
|
576
|
+
driverType: "playwright"
|
|
577
|
+
};
|
|
578
|
+
},
|
|
579
|
+
catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
|
|
580
|
+
}),
|
|
581
|
+
launchApp: (url, opts) => Effect.tryPromise({
|
|
582
|
+
try: async () => {
|
|
583
|
+
const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
|
|
584
|
+
if (opts?.clearState) {
|
|
585
|
+
await clearStorage();
|
|
586
|
+
}
|
|
587
|
+
await page.goto(targetUrl);
|
|
588
|
+
updateHarPage(page);
|
|
589
|
+
debugLog("launchApp", targetUrl);
|
|
590
|
+
},
|
|
591
|
+
catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
|
|
592
|
+
}),
|
|
593
|
+
stopApp: (_id) => Effect.tryPromise({
|
|
594
|
+
try: async () => {
|
|
595
|
+
await page.goto("about:blank");
|
|
596
|
+
updateHarPage(page);
|
|
597
|
+
debugLog("stopApp");
|
|
598
|
+
},
|
|
599
|
+
catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
|
|
600
|
+
}),
|
|
601
|
+
killApp: (_id) => Effect.tryPromise({
|
|
602
|
+
try: async () => {
|
|
603
|
+
await Promise.allSettled([page.close(), context.close(), browser.close()]);
|
|
604
|
+
},
|
|
605
|
+
catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
|
|
606
|
+
}),
|
|
607
|
+
clearAppState: (_id) => Effect.tryPromise({
|
|
608
|
+
try: async () => {
|
|
609
|
+
await clearStorage();
|
|
610
|
+
debugLog("clearAppState");
|
|
611
|
+
},
|
|
612
|
+
catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
|
|
613
|
+
}),
|
|
614
|
+
openLink: (url) => Effect.tryPromise({
|
|
615
|
+
try: async () => {
|
|
616
|
+
await page.goto(url);
|
|
617
|
+
updateHarPage(page);
|
|
618
|
+
debugLog("openLink", url);
|
|
619
|
+
},
|
|
620
|
+
catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
|
|
621
|
+
}),
|
|
622
|
+
back: () => Effect.tryPromise({
|
|
623
|
+
try: async () => {
|
|
624
|
+
await page.goBack();
|
|
625
|
+
updateHarPage(page);
|
|
626
|
+
debugLog("back", currentPageUrl(page));
|
|
627
|
+
},
|
|
628
|
+
catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
|
|
629
|
+
}),
|
|
630
|
+
evaluate: (script, ...args) => Effect.tryPromise({
|
|
631
|
+
try: () => page.evaluate(script, ...args),
|
|
632
|
+
catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
|
|
633
|
+
}),
|
|
634
|
+
mockNetwork: (matcher, response) => Effect.tryPromise({
|
|
635
|
+
try: async () => {
|
|
636
|
+
buildMockResponse(response);
|
|
637
|
+
const definition = { kind: "mock", matcher, response };
|
|
638
|
+
routeDefinitions.push(definition);
|
|
639
|
+
await applyRouteDefinition(definition);
|
|
640
|
+
debugLog("mockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
|
|
641
|
+
},
|
|
642
|
+
catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
|
|
643
|
+
}),
|
|
644
|
+
blockNetwork: (matcher) => Effect.tryPromise({
|
|
645
|
+
try: async () => {
|
|
646
|
+
const definition = { kind: "block", matcher };
|
|
647
|
+
routeDefinitions.push(definition);
|
|
648
|
+
await applyRouteDefinition(definition);
|
|
649
|
+
debugLog("blockNetwork", typeof matcher === "string" ? matcher : matcher.toString());
|
|
650
|
+
},
|
|
651
|
+
catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
|
|
652
|
+
}),
|
|
653
|
+
clearNetworkMocks: () => Effect.tryPromise({
|
|
654
|
+
try: async () => {
|
|
655
|
+
for (const appliedRoute of appliedRoutes) {
|
|
656
|
+
await context.unroute(appliedRoute.matcher, appliedRoute.handler);
|
|
657
|
+
}
|
|
658
|
+
appliedRoutes = [];
|
|
659
|
+
routeDefinitions.length = 0;
|
|
660
|
+
debugLog("clearNetworkMocks");
|
|
661
|
+
},
|
|
662
|
+
catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
|
|
663
|
+
}),
|
|
664
|
+
setNetworkConditions: (conditions) => Effect.tryPromise({
|
|
665
|
+
try: async () => {
|
|
666
|
+
currentNetworkConditions = { ...conditions };
|
|
667
|
+
await applyNetworkConditions();
|
|
668
|
+
debugLog("setNetworkConditions", JSON.stringify(conditions));
|
|
669
|
+
},
|
|
670
|
+
catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
|
|
671
|
+
}),
|
|
672
|
+
saveCookies: (path) => Effect.tryPromise({
|
|
673
|
+
try: async () => {
|
|
674
|
+
const cookies = await context.cookies();
|
|
675
|
+
await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
|
|
676
|
+
debugLog("saveCookies", path);
|
|
677
|
+
},
|
|
678
|
+
catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
|
|
679
|
+
}),
|
|
680
|
+
loadCookies: (path) => Effect.tryPromise({
|
|
681
|
+
try: async () => {
|
|
682
|
+
const contents = await readFile(path, "utf8");
|
|
683
|
+
const cookies = JSON.parse(contents);
|
|
684
|
+
if (!Array.isArray(cookies)) {
|
|
685
|
+
throw new Error("Cookie file must contain an array of cookies.");
|
|
686
|
+
}
|
|
687
|
+
await context.addCookies(cookies);
|
|
688
|
+
debugLog("loadCookies", path);
|
|
689
|
+
},
|
|
690
|
+
catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
|
|
691
|
+
}),
|
|
692
|
+
saveAuthState: (path) => Effect.tryPromise({
|
|
693
|
+
try: async () => {
|
|
694
|
+
await context.storageState({ path });
|
|
695
|
+
debugLog("saveAuthState", path);
|
|
696
|
+
},
|
|
697
|
+
catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
|
|
698
|
+
}),
|
|
699
|
+
loadAuthState: (path) => Effect.tryPromise({
|
|
700
|
+
try: async () => {
|
|
701
|
+
await replaceContext(path);
|
|
702
|
+
updateHarPage(page);
|
|
703
|
+
debugLog("loadAuthState", path);
|
|
704
|
+
},
|
|
705
|
+
catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
|
|
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
|
+
}))
|
|
794
|
+
};
|
|
795
|
+
return service;
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// src/drivers/uiautomator2/driver.ts
|
|
800
|
+
import { Effect as Effect2 } from "effect";
|
|
801
|
+
|
|
802
|
+
// src/drivers/uiautomator2/client.ts
|
|
803
|
+
var UiAutomator2Client = class {
|
|
804
|
+
baseUrl;
|
|
805
|
+
sessionId = null;
|
|
806
|
+
constructor(host, port) {
|
|
807
|
+
this.baseUrl = `http://${host}:${port}`;
|
|
808
|
+
}
|
|
809
|
+
// ---------------------------------------------------------------------------
|
|
810
|
+
// HTTP helpers
|
|
811
|
+
// ---------------------------------------------------------------------------
|
|
812
|
+
async request(method, path, body) {
|
|
813
|
+
const url = `${this.baseUrl}${path}`;
|
|
814
|
+
const init = {
|
|
815
|
+
method,
|
|
816
|
+
headers: { "Content-Type": "application/json" }
|
|
817
|
+
};
|
|
818
|
+
if (body !== void 0) {
|
|
819
|
+
init.body = JSON.stringify(body);
|
|
820
|
+
}
|
|
821
|
+
const res = await fetch(url, init);
|
|
822
|
+
const text = await res.text();
|
|
823
|
+
let parsed;
|
|
824
|
+
try {
|
|
825
|
+
parsed = JSON.parse(text);
|
|
826
|
+
} catch {
|
|
827
|
+
throw new Error(`UiAutomator2: failed to parse response: ${text}`);
|
|
828
|
+
}
|
|
829
|
+
if (!res.ok) {
|
|
830
|
+
const val = parsed.value;
|
|
831
|
+
const msg = val?.message ?? val?.error ?? text;
|
|
832
|
+
throw new Error(`UiAutomator2 ${method} ${path} \u2192 ${res.status}: ${msg}`);
|
|
833
|
+
}
|
|
834
|
+
if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
|
|
835
|
+
const val = parsed.value;
|
|
836
|
+
throw new Error(`UiAutomator2 error: ${val.message ?? val.error}`);
|
|
837
|
+
}
|
|
838
|
+
return parsed.value;
|
|
839
|
+
}
|
|
840
|
+
sessionPath(path) {
|
|
841
|
+
if (this.sessionId === null) {
|
|
842
|
+
throw new Error("UiAutomator2: no active session");
|
|
843
|
+
}
|
|
844
|
+
return `/session/${this.sessionId}${path}`;
|
|
845
|
+
}
|
|
846
|
+
// ---------------------------------------------------------------------------
|
|
847
|
+
// Session management
|
|
848
|
+
// ---------------------------------------------------------------------------
|
|
849
|
+
async createSession(appPackage) {
|
|
850
|
+
const capabilities = {
|
|
851
|
+
platformName: "Android"
|
|
852
|
+
};
|
|
853
|
+
if (appPackage) {
|
|
854
|
+
capabilities["appium:appPackage"] = appPackage;
|
|
855
|
+
}
|
|
856
|
+
const body = { capabilities };
|
|
857
|
+
const res = await fetch(`${this.baseUrl}/session`, {
|
|
858
|
+
method: "POST",
|
|
859
|
+
headers: { "Content-Type": "application/json" },
|
|
860
|
+
body: JSON.stringify(body)
|
|
861
|
+
});
|
|
862
|
+
const text = await res.text();
|
|
863
|
+
let parsed;
|
|
864
|
+
try {
|
|
865
|
+
parsed = JSON.parse(text);
|
|
866
|
+
} catch {
|
|
867
|
+
throw new Error(`UiAutomator2: failed to parse session response: ${text}`);
|
|
868
|
+
}
|
|
869
|
+
if (!res.ok) {
|
|
870
|
+
const val = parsed["value"];
|
|
871
|
+
throw new Error(`UiAutomator2: failed to create session: ${val?.message ?? text}`);
|
|
872
|
+
}
|
|
873
|
+
let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
|
|
874
|
+
if (!sessionId) {
|
|
875
|
+
throw new Error("UiAutomator2: no sessionId in session response");
|
|
876
|
+
}
|
|
877
|
+
this.sessionId = sessionId;
|
|
878
|
+
return sessionId;
|
|
879
|
+
}
|
|
880
|
+
async deleteSession() {
|
|
881
|
+
if (this.sessionId === null) return;
|
|
882
|
+
const path = `/session/${this.sessionId}`;
|
|
883
|
+
this.sessionId = null;
|
|
884
|
+
await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
|
|
885
|
+
}
|
|
886
|
+
// ---------------------------------------------------------------------------
|
|
887
|
+
// Screen queries
|
|
888
|
+
// ---------------------------------------------------------------------------
|
|
889
|
+
async getSource() {
|
|
890
|
+
const value = await this.request("GET", this.sessionPath("/source"));
|
|
891
|
+
return value;
|
|
892
|
+
}
|
|
893
|
+
async getScreenshot() {
|
|
894
|
+
const value = await this.request("GET", this.sessionPath("/screenshot"));
|
|
895
|
+
return value;
|
|
896
|
+
}
|
|
897
|
+
async getWindowSize() {
|
|
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
|
+
}
|
|
913
|
+
}
|
|
914
|
+
// ---------------------------------------------------------------------------
|
|
915
|
+
// Gestures — Appium gesture extensions
|
|
916
|
+
// These match the endpoints used by maestro-runner's uiautomator2 client.
|
|
917
|
+
// ---------------------------------------------------------------------------
|
|
918
|
+
async performTap(x, y) {
|
|
919
|
+
await this.request("POST", this.sessionPath("/appium/gestures/click"), {
|
|
920
|
+
offset: { x, y }
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
async performDoubleTap(x, y) {
|
|
924
|
+
await this.request("POST", this.sessionPath("/appium/gestures/double_click"), {
|
|
925
|
+
offset: { x, y }
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
async performLongPress(x, y, duration) {
|
|
929
|
+
await this.request("POST", this.sessionPath("/appium/gestures/long_click"), {
|
|
930
|
+
offset: { x, y },
|
|
931
|
+
duration
|
|
932
|
+
// milliseconds
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Coordinate-based swipe from (startX, startY) to (endX, endY).
|
|
937
|
+
*
|
|
938
|
+
* The Appium swipe extension only accepts direction + percent; for arbitrary
|
|
939
|
+
* from/to coordinates we use the W3C Actions API instead.
|
|
940
|
+
*
|
|
941
|
+
* @param duration - gesture duration in milliseconds
|
|
942
|
+
*/
|
|
943
|
+
async performSwipe(startX, startY, endX, endY, duration) {
|
|
944
|
+
await this.request("POST", this.sessionPath("/actions"), {
|
|
945
|
+
actions: [
|
|
946
|
+
{
|
|
947
|
+
type: "pointer",
|
|
948
|
+
id: "finger1",
|
|
949
|
+
parameters: { pointerType: "touch" },
|
|
950
|
+
actions: [
|
|
951
|
+
{ type: "pointerMove", duration: 0, x: startX, y: startY },
|
|
952
|
+
{ type: "pointerDown", button: 0 },
|
|
953
|
+
{ type: "pointerMove", duration, x: endX, y: endY },
|
|
954
|
+
{ type: "pointerUp", button: 0 }
|
|
955
|
+
]
|
|
956
|
+
}
|
|
957
|
+
]
|
|
958
|
+
});
|
|
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
|
+
}
|
|
1063
|
+
// ---------------------------------------------------------------------------
|
|
1064
|
+
// Text / keyboard
|
|
1065
|
+
// ---------------------------------------------------------------------------
|
|
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) {
|
|
1089
|
+
const keyActions = [];
|
|
1090
|
+
for (const segment of splitGraphemes(text)) {
|
|
1091
|
+
keyActions.push({ type: "keyDown", value: segment });
|
|
1092
|
+
keyActions.push({ type: "keyUp", value: segment });
|
|
1093
|
+
}
|
|
1094
|
+
await this.request("POST", this.sessionPath("/actions"), {
|
|
1095
|
+
actions: [
|
|
1096
|
+
{
|
|
1097
|
+
type: "key",
|
|
1098
|
+
id: "keyboard",
|
|
1099
|
+
actions: keyActions
|
|
1100
|
+
}
|
|
1101
|
+
]
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
async pressKeyCode(keyCode) {
|
|
1105
|
+
await this.request("POST", this.sessionPath("/appium/device/press_keycode"), {
|
|
1106
|
+
keycode: keyCode
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
async hideKeyboard() {
|
|
1110
|
+
await this.request("POST", this.sessionPath("/appium/device/hide_keyboard"), void 0);
|
|
1111
|
+
}
|
|
1112
|
+
// ---------------------------------------------------------------------------
|
|
1113
|
+
// App lifecycle
|
|
1114
|
+
// ---------------------------------------------------------------------------
|
|
1115
|
+
async activateApp(appPackage) {
|
|
1116
|
+
await this.request("POST", this.sessionPath("/appium/device/activate_app"), {
|
|
1117
|
+
appId: appPackage
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
async terminateApp(appPackage) {
|
|
1121
|
+
await this.request("POST", this.sessionPath("/appium/device/terminate_app"), {
|
|
1122
|
+
appId: appPackage
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
// ---------------------------------------------------------------------------
|
|
1126
|
+
// WebView / hybrid context switching
|
|
1127
|
+
// ---------------------------------------------------------------------------
|
|
1128
|
+
async getContexts() {
|
|
1129
|
+
return this.request("GET", this.sessionPath("/contexts"));
|
|
1130
|
+
}
|
|
1131
|
+
async getCurrentContext() {
|
|
1132
|
+
return this.request("GET", this.sessionPath("/context"));
|
|
1133
|
+
}
|
|
1134
|
+
async setContext(contextId) {
|
|
1135
|
+
await this.request("POST", this.sessionPath("/context"), { name: contextId });
|
|
1136
|
+
}
|
|
1137
|
+
async executeScript(script, args = []) {
|
|
1138
|
+
return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
|
|
1142
|
+
// src/drivers/uiautomator2/driver.ts
|
|
1143
|
+
function createUiAutomator2Driver(host, port, serial, packageName) {
|
|
1144
|
+
return Effect2.gen(function* () {
|
|
1145
|
+
const client = new UiAutomator2Client(host, port);
|
|
1146
|
+
yield* Effect2.tryPromise({
|
|
1147
|
+
try: () => client.createSession(packageName),
|
|
1148
|
+
catch: (e) => new DriverError({
|
|
1149
|
+
message: `Failed to create UiAutomator2 session: ${e}`
|
|
1150
|
+
})
|
|
1151
|
+
});
|
|
1152
|
+
const service = {
|
|
1153
|
+
// -----------------------------------------------------------------------
|
|
1154
|
+
// Hierarchy
|
|
1155
|
+
// -----------------------------------------------------------------------
|
|
1156
|
+
dumpHierarchy: () => Effect2.tryPromise({
|
|
1157
|
+
try: () => client.getSource(),
|
|
1158
|
+
catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
|
|
1159
|
+
}),
|
|
1160
|
+
// -----------------------------------------------------------------------
|
|
1161
|
+
// Coordinate-level actions
|
|
1162
|
+
// -----------------------------------------------------------------------
|
|
1163
|
+
tapAtCoordinate: (x, y) => Effect2.tryPromise({
|
|
1164
|
+
try: () => client.performTap(x, y),
|
|
1165
|
+
catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
|
|
1166
|
+
}),
|
|
1167
|
+
doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
|
|
1168
|
+
try: async () => {
|
|
1169
|
+
await client.performTap(x, y);
|
|
1170
|
+
await client.performTap(x, y);
|
|
1171
|
+
},
|
|
1172
|
+
catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
|
|
1173
|
+
}),
|
|
1174
|
+
longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
|
|
1175
|
+
try: () => client.performLongPress(x, y, duration),
|
|
1176
|
+
catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
|
|
1177
|
+
}),
|
|
1178
|
+
swipe: (sx, sy, ex, ey, dur) => Effect2.tryPromise({
|
|
1179
|
+
try: () => client.performSwipe(sx, sy, ex, ey, dur),
|
|
1180
|
+
catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
|
|
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
|
+
}),
|
|
1194
|
+
// -----------------------------------------------------------------------
|
|
1195
|
+
// Text input
|
|
1196
|
+
// -----------------------------------------------------------------------
|
|
1197
|
+
inputText: (text) => Effect2.tryPromise({
|
|
1198
|
+
try: () => client.sendKeys(text),
|
|
1199
|
+
catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
|
|
1200
|
+
}),
|
|
1201
|
+
pressKey: (key) => Effect2.tryPromise({
|
|
1202
|
+
try: () => client.pressKeyCode(parseInt(key, 10) || 0),
|
|
1203
|
+
catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
|
|
1204
|
+
}),
|
|
1205
|
+
hideKeyboard: () => Effect2.tryPromise({
|
|
1206
|
+
try: () => client.hideKeyboard(),
|
|
1207
|
+
catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
|
|
1208
|
+
}),
|
|
1209
|
+
// -----------------------------------------------------------------------
|
|
1210
|
+
// Queries
|
|
1211
|
+
// -----------------------------------------------------------------------
|
|
1212
|
+
takeScreenshot: () => Effect2.tryPromise({
|
|
1213
|
+
try: async () => {
|
|
1214
|
+
const base64 = await client.getScreenshot();
|
|
1215
|
+
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
|
1216
|
+
},
|
|
1217
|
+
catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
|
|
1218
|
+
}),
|
|
1219
|
+
getDeviceInfo: () => Effect2.tryPromise({
|
|
1220
|
+
try: async () => {
|
|
1221
|
+
const size = await client.getWindowSize();
|
|
1222
|
+
return {
|
|
1223
|
+
platform: "android",
|
|
1224
|
+
deviceId: `${host}:${port}`,
|
|
1225
|
+
name: "Android Device",
|
|
1226
|
+
isEmulator: host === "localhost" || host === "127.0.0.1",
|
|
1227
|
+
screenWidth: size.width,
|
|
1228
|
+
screenHeight: size.height,
|
|
1229
|
+
driverType: "uiautomator2"
|
|
1230
|
+
};
|
|
1231
|
+
},
|
|
1232
|
+
catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
|
|
1233
|
+
}),
|
|
1234
|
+
// -----------------------------------------------------------------------
|
|
1235
|
+
// App lifecycle
|
|
1236
|
+
// -----------------------------------------------------------------------
|
|
1237
|
+
launchApp: (bundleId, opts) => Effect2.tryPromise({
|
|
1238
|
+
try: async () => {
|
|
1239
|
+
if (opts?.clearState) {
|
|
1240
|
+
adbClearApp(serial, bundleId);
|
|
1241
|
+
}
|
|
1242
|
+
if (opts?.clearKeychain) {
|
|
1243
|
+
console.warn("clearKeychain is not supported on Android, skipping.");
|
|
1244
|
+
}
|
|
1245
|
+
if (opts?.deepLink) {
|
|
1246
|
+
adbOpenLink(serial, opts.deepLink, bundleId);
|
|
1247
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1248
|
+
} else {
|
|
1249
|
+
adbForceStop(serial, bundleId);
|
|
1250
|
+
if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
|
|
1251
|
+
const { execFileSync } = await import("child_process");
|
|
1252
|
+
const { findADB } = await import("./android-PAPJJWVN.js");
|
|
1253
|
+
const adb = findADB();
|
|
1254
|
+
if (!adb) throw new Error("adb not found");
|
|
1255
|
+
const startArgs = [
|
|
1256
|
+
"-s",
|
|
1257
|
+
serial,
|
|
1258
|
+
"shell",
|
|
1259
|
+
"am",
|
|
1260
|
+
"start",
|
|
1261
|
+
"-a",
|
|
1262
|
+
"android.intent.action.MAIN",
|
|
1263
|
+
"-c",
|
|
1264
|
+
"android.intent.category.LAUNCHER",
|
|
1265
|
+
bundleId
|
|
1266
|
+
];
|
|
1267
|
+
for (const [k, v] of Object.entries(opts.launchArguments)) {
|
|
1268
|
+
startArgs.push("--es", k, String(v));
|
|
1269
|
+
}
|
|
1270
|
+
execFileSync(adb, startArgs, { stdio: "ignore" });
|
|
1271
|
+
} else {
|
|
1272
|
+
adbLaunchApp(serial, bundleId);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1276
|
+
},
|
|
1277
|
+
catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
|
|
1278
|
+
}),
|
|
1279
|
+
stopApp: (bundleId) => Effect2.tryPromise({
|
|
1280
|
+
try: async () => {
|
|
1281
|
+
adbForceStop(serial, bundleId);
|
|
1282
|
+
},
|
|
1283
|
+
catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
|
|
1284
|
+
}),
|
|
1285
|
+
killApp: (bundleId) => Effect2.tryPromise({
|
|
1286
|
+
try: async () => {
|
|
1287
|
+
adbForceStop(serial, bundleId);
|
|
1288
|
+
},
|
|
1289
|
+
catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
|
|
1290
|
+
}),
|
|
1291
|
+
clearAppState: (bundleId) => Effect2.tryPromise({
|
|
1292
|
+
try: async () => {
|
|
1293
|
+
adbForceStop(serial, bundleId);
|
|
1294
|
+
adbClearApp(serial, bundleId);
|
|
1295
|
+
},
|
|
1296
|
+
catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
|
|
1297
|
+
}),
|
|
1298
|
+
// -----------------------------------------------------------------------
|
|
1299
|
+
// Navigation
|
|
1300
|
+
// -----------------------------------------------------------------------
|
|
1301
|
+
openLink: (url) => Effect2.tryPromise({
|
|
1302
|
+
try: async () => {
|
|
1303
|
+
adbOpenLink(serial, url, packageName);
|
|
1304
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
1305
|
+
},
|
|
1306
|
+
catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
|
|
1307
|
+
}),
|
|
1308
|
+
back: () => Effect2.tryPromise({
|
|
1309
|
+
// KEYCODE_BACK = 4
|
|
1310
|
+
try: () => client.pressKeyCode(4),
|
|
1311
|
+
catch: (e) => new DriverError({ message: `Back failed: ${e}` })
|
|
1312
|
+
}),
|
|
1313
|
+
evaluate: (script, ...args) => Effect2.tryPromise({
|
|
1314
|
+
try: () => client.executeScript(
|
|
1315
|
+
typeof script === "function" ? `return (${script})(...arguments)` : script,
|
|
1316
|
+
args
|
|
1317
|
+
),
|
|
1318
|
+
catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
|
|
1319
|
+
}),
|
|
1320
|
+
getContexts: () => Effect2.tryPromise({
|
|
1321
|
+
try: () => client.getContexts(),
|
|
1322
|
+
catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
|
|
1323
|
+
}),
|
|
1324
|
+
getCurrentContext: () => Effect2.tryPromise({
|
|
1325
|
+
try: () => client.getCurrentContext(),
|
|
1326
|
+
catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
|
|
1327
|
+
}),
|
|
1328
|
+
setContext: (contextId) => Effect2.tryPromise({
|
|
1329
|
+
try: () => client.setContext(contextId),
|
|
1330
|
+
catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
|
|
1331
|
+
})
|
|
1332
|
+
};
|
|
1333
|
+
return service;
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
// src/drivers/wda/driver.ts
|
|
1338
|
+
import { Effect as Effect3 } from "effect";
|
|
1339
|
+
|
|
1340
|
+
// src/drivers/wda/client.ts
|
|
1341
|
+
var WDAClient = class {
|
|
1342
|
+
baseUrl;
|
|
1343
|
+
sessionId = null;
|
|
1344
|
+
constructor(host, port) {
|
|
1345
|
+
this.baseUrl = `http://${host}:${port}`;
|
|
1346
|
+
}
|
|
1347
|
+
// ---------------------------------------------------------------------------
|
|
1348
|
+
// HTTP helpers
|
|
1349
|
+
// ---------------------------------------------------------------------------
|
|
1350
|
+
async request(method, path, body) {
|
|
1351
|
+
const url = `${this.baseUrl}${path}`;
|
|
1352
|
+
const init = {
|
|
1353
|
+
method,
|
|
1354
|
+
headers: { "Content-Type": "application/json" }
|
|
1355
|
+
};
|
|
1356
|
+
if (body !== void 0) {
|
|
1357
|
+
init.body = JSON.stringify(body);
|
|
1358
|
+
}
|
|
1359
|
+
const res = await fetch(url, init);
|
|
1360
|
+
const text = await res.text();
|
|
1361
|
+
let parsed;
|
|
1362
|
+
try {
|
|
1363
|
+
parsed = JSON.parse(text);
|
|
1364
|
+
} catch {
|
|
1365
|
+
throw new Error(`WDA: failed to parse response: ${text}`);
|
|
1366
|
+
}
|
|
1367
|
+
if (!res.ok) {
|
|
1368
|
+
const val = parsed.value;
|
|
1369
|
+
const msg = val?.message ?? val?.error ?? text;
|
|
1370
|
+
throw new Error(`WDA ${method} ${path} \u2192 ${res.status}: ${msg}`);
|
|
1371
|
+
}
|
|
1372
|
+
if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
|
|
1373
|
+
const val = parsed.value;
|
|
1374
|
+
throw new Error(`WDA error: ${val.message ?? val.error}`);
|
|
1375
|
+
}
|
|
1376
|
+
return parsed.value;
|
|
1377
|
+
}
|
|
1378
|
+
sessionPath(path) {
|
|
1379
|
+
if (this.sessionId === null) {
|
|
1380
|
+
throw new Error("WDA: no active session");
|
|
1381
|
+
}
|
|
1382
|
+
return `/session/${this.sessionId}${path}`;
|
|
1383
|
+
}
|
|
1384
|
+
// ---------------------------------------------------------------------------
|
|
1385
|
+
// Session management
|
|
1386
|
+
// ---------------------------------------------------------------------------
|
|
1387
|
+
/**
|
|
1388
|
+
* Creates a new WDA session.
|
|
1389
|
+
*
|
|
1390
|
+
* @param bundleId - the app bundle ID to attach to (e.g. "com.example.app")
|
|
1391
|
+
* @param alertAction - optional auto-alert handling: "accept" | "dismiss"
|
|
1392
|
+
*/
|
|
1393
|
+
async createSession(bundleId, alertAction) {
|
|
1394
|
+
const alwaysMatch = {
|
|
1395
|
+
shouldWaitForQuiescence: false,
|
|
1396
|
+
waitForIdleTimeout: 0,
|
|
1397
|
+
shouldUseTestManagerForVisibilityDetection: false
|
|
1398
|
+
};
|
|
1399
|
+
if (bundleId) {
|
|
1400
|
+
alwaysMatch["bundleId"] = bundleId;
|
|
1401
|
+
}
|
|
1402
|
+
if (alertAction) {
|
|
1403
|
+
alwaysMatch["defaultAlertAction"] = alertAction;
|
|
1404
|
+
}
|
|
1405
|
+
const res = await fetch(`${this.baseUrl}/session`, {
|
|
1406
|
+
method: "POST",
|
|
1407
|
+
headers: { "Content-Type": "application/json" },
|
|
1408
|
+
body: JSON.stringify({
|
|
1409
|
+
capabilities: { alwaysMatch }
|
|
1410
|
+
})
|
|
1411
|
+
});
|
|
1412
|
+
const text = await res.text();
|
|
1413
|
+
let parsed;
|
|
1414
|
+
try {
|
|
1415
|
+
parsed = JSON.parse(text);
|
|
1416
|
+
} catch {
|
|
1417
|
+
throw new Error(`WDA: failed to parse session response: ${text}`);
|
|
1418
|
+
}
|
|
1419
|
+
if (!res.ok) {
|
|
1420
|
+
const val = parsed["value"];
|
|
1421
|
+
throw new Error(`WDA: failed to create session: ${val?.message ?? text}`);
|
|
1422
|
+
}
|
|
1423
|
+
let sessionId = parsed["sessionId"] ?? parsed["value"]?.["sessionId"];
|
|
1424
|
+
if (!sessionId) {
|
|
1425
|
+
throw new Error("WDA: no sessionId in session response");
|
|
1426
|
+
}
|
|
1427
|
+
this.sessionId = sessionId;
|
|
1428
|
+
return sessionId;
|
|
1429
|
+
}
|
|
1430
|
+
async deleteSession() {
|
|
1431
|
+
if (this.sessionId === null) return;
|
|
1432
|
+
const path = `/session/${this.sessionId}`;
|
|
1433
|
+
try {
|
|
1434
|
+
await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
|
|
1435
|
+
} finally {
|
|
1436
|
+
this.sessionId = null;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
hasSession() {
|
|
1440
|
+
return this.sessionId !== null;
|
|
1441
|
+
}
|
|
1442
|
+
sessionID() {
|
|
1443
|
+
return this.sessionId;
|
|
1444
|
+
}
|
|
1445
|
+
// ---------------------------------------------------------------------------
|
|
1446
|
+
// Settings
|
|
1447
|
+
// ---------------------------------------------------------------------------
|
|
1448
|
+
async updateSettings(settings) {
|
|
1449
|
+
await this.request("POST", this.sessionPath("/appium/settings"), {
|
|
1450
|
+
settings
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
async disableQuiescence() {
|
|
1454
|
+
await this.updateSettings({
|
|
1455
|
+
shouldWaitForQuiescence: false,
|
|
1456
|
+
waitForIdleTimeout: 0
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
// ---------------------------------------------------------------------------
|
|
1460
|
+
// Screen queries
|
|
1461
|
+
// ---------------------------------------------------------------------------
|
|
1462
|
+
/** Returns the UI hierarchy as XML. */
|
|
1463
|
+
async getSource() {
|
|
1464
|
+
const value = await this.request("GET", this.sessionPath("/source"));
|
|
1465
|
+
return value;
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Captures the screen and returns PNG bytes.
|
|
1469
|
+
*
|
|
1470
|
+
* The Go client calls GET /session/{id}/screenshot (session-prefixed) and
|
|
1471
|
+
* decodes the base64 value. We follow the same pattern.
|
|
1472
|
+
*/
|
|
1473
|
+
async getScreenshot() {
|
|
1474
|
+
const base64 = await this.request("GET", this.sessionPath("/screenshot"));
|
|
1475
|
+
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
|
1476
|
+
}
|
|
1477
|
+
/** Returns the screen dimensions in logical points. */
|
|
1478
|
+
async getWindowSize() {
|
|
1479
|
+
const value = await this.request(
|
|
1480
|
+
"GET",
|
|
1481
|
+
this.sessionPath("/window/size")
|
|
1482
|
+
);
|
|
1483
|
+
return value;
|
|
1484
|
+
}
|
|
1485
|
+
// ---------------------------------------------------------------------------
|
|
1486
|
+
// Touch actions — WDA-specific endpoints
|
|
1487
|
+
// ---------------------------------------------------------------------------
|
|
1488
|
+
async tap(x, y) {
|
|
1489
|
+
await this.request("POST", this.sessionPath("/wda/tap"), { x, y });
|
|
1490
|
+
}
|
|
1491
|
+
async 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 });
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Long-presses at coordinates.
|
|
1512
|
+
*
|
|
1513
|
+
* @param durationSec - hold duration in **seconds** (WDA convention)
|
|
1514
|
+
*/
|
|
1515
|
+
async longPress(x, y, durationSec) {
|
|
1516
|
+
await this.request("POST", this.sessionPath("/wda/touchAndHold"), {
|
|
1517
|
+
x,
|
|
1518
|
+
y,
|
|
1519
|
+
duration: durationSec
|
|
1520
|
+
});
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Swipes from one point to another.
|
|
1524
|
+
*
|
|
1525
|
+
* @param durationSec - gesture duration in **seconds** (WDA convention)
|
|
1526
|
+
*/
|
|
1527
|
+
async swipe(fromX, fromY, toX, toY, durationSec) {
|
|
1528
|
+
await this.request("POST", this.sessionPath("/wda/dragfromtoforduration"), {
|
|
1529
|
+
fromX,
|
|
1530
|
+
fromY,
|
|
1531
|
+
toX,
|
|
1532
|
+
toY,
|
|
1533
|
+
duration: durationSec
|
|
1534
|
+
});
|
|
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
|
+
}
|
|
1660
|
+
// ---------------------------------------------------------------------------
|
|
1661
|
+
// Text / keyboard
|
|
1662
|
+
// ---------------------------------------------------------------------------
|
|
1663
|
+
/**
|
|
1664
|
+
* Types text. WDA expects the value as an array of individual characters.
|
|
1665
|
+
*
|
|
1666
|
+
* @param frequency - typing speed in keys/sec (0 = WDA default ~60/s)
|
|
1667
|
+
*/
|
|
1668
|
+
async sendKeys(text, frequency = 25) {
|
|
1669
|
+
const body = {
|
|
1670
|
+
value: splitGraphemes(text)
|
|
1671
|
+
};
|
|
1672
|
+
if (frequency > 0) {
|
|
1673
|
+
body["frequency"] = frequency;
|
|
1674
|
+
}
|
|
1675
|
+
await this.request("POST", this.sessionPath("/wda/keys"), body);
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Presses a hardware button by name.
|
|
1679
|
+
*
|
|
1680
|
+
* @param button - "home" | "volumeUp" | "volumeDown"
|
|
1681
|
+
*/
|
|
1682
|
+
async pressButton(button) {
|
|
1683
|
+
await this.request("POST", this.sessionPath("/wda/pressButton"), {
|
|
1684
|
+
name: button
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
async pressHome() {
|
|
1688
|
+
await this.pressButton("home");
|
|
1689
|
+
}
|
|
1690
|
+
// ---------------------------------------------------------------------------
|
|
1691
|
+
// App lifecycle
|
|
1692
|
+
// ---------------------------------------------------------------------------
|
|
1693
|
+
async launchApp(bundleId, args) {
|
|
1694
|
+
const body = { bundleId };
|
|
1695
|
+
if (args && args.length > 0) {
|
|
1696
|
+
body["arguments"] = args;
|
|
1697
|
+
}
|
|
1698
|
+
await this.request("POST", this.sessionPath("/wda/apps/launch"), body);
|
|
1699
|
+
}
|
|
1700
|
+
async terminateApp(bundleId) {
|
|
1701
|
+
await this.request("POST", this.sessionPath("/wda/apps/terminate"), {
|
|
1702
|
+
bundleId
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
async activateApp(bundleId) {
|
|
1706
|
+
await this.request("POST", this.sessionPath("/wda/apps/activate"), {
|
|
1707
|
+
bundleId
|
|
1708
|
+
});
|
|
1709
|
+
}
|
|
1710
|
+
// ---------------------------------------------------------------------------
|
|
1711
|
+
// Deep link / URL
|
|
1712
|
+
// ---------------------------------------------------------------------------
|
|
1713
|
+
/** Opens a URL or deep link. Works for both simulator and real device. */
|
|
1714
|
+
async openUrl(url) {
|
|
1715
|
+
await this.request("POST", this.sessionPath("/url"), { url });
|
|
1716
|
+
}
|
|
1717
|
+
// ---------------------------------------------------------------------------
|
|
1718
|
+
// Alerts
|
|
1719
|
+
// ---------------------------------------------------------------------------
|
|
1720
|
+
async acceptAlert() {
|
|
1721
|
+
await this.request("POST", this.sessionPath("/alert/accept"), void 0);
|
|
1722
|
+
}
|
|
1723
|
+
async dismissAlert() {
|
|
1724
|
+
await this.request("POST", this.sessionPath("/alert/dismiss"), void 0);
|
|
1725
|
+
}
|
|
1726
|
+
// ---------------------------------------------------------------------------
|
|
1727
|
+
// Device status
|
|
1728
|
+
// ---------------------------------------------------------------------------
|
|
1729
|
+
async getStatus() {
|
|
1730
|
+
return this.request("GET", "/status");
|
|
1731
|
+
}
|
|
1732
|
+
};
|
|
1733
|
+
|
|
1734
|
+
// src/drivers/wda/driver.ts
|
|
1735
|
+
function msToSec(ms) {
|
|
1736
|
+
return ms / 1e3;
|
|
1737
|
+
}
|
|
1738
|
+
function sleep(ms) {
|
|
1739
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1740
|
+
}
|
|
1741
|
+
function replaceUrlScheme(url, scheme) {
|
|
1742
|
+
const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(\/\/.*)$/);
|
|
1743
|
+
if (!match) return null;
|
|
1744
|
+
return `${scheme}:${match[2]}`;
|
|
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
|
+
}
|
|
1750
|
+
function createWDADriver(host, port, bundleId, simulatorUdid) {
|
|
1751
|
+
return Effect3.gen(function* () {
|
|
1752
|
+
const client = new WDAClient(host, port);
|
|
1753
|
+
const createSessionWithRetry = async (targetBundleId) => {
|
|
1754
|
+
let lastError;
|
|
1755
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1756
|
+
try {
|
|
1757
|
+
return await client.createSession(targetBundleId);
|
|
1758
|
+
} catch (error) {
|
|
1759
|
+
lastError = error;
|
|
1760
|
+
if (attempt === 4) {
|
|
1761
|
+
throw error;
|
|
1762
|
+
}
|
|
1763
|
+
await sleep(1e3);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
throw lastError ?? new Error("Failed to create WDA session");
|
|
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
|
+
};
|
|
1785
|
+
const activateSimulatorApp = async (targetBundleId) => {
|
|
1786
|
+
if (!targetBundleId) return;
|
|
1787
|
+
await client.activateApp(targetBundleId);
|
|
1788
|
+
await sleep(1e3);
|
|
1789
|
+
};
|
|
1790
|
+
const openSimulatorUrl = async (url, targetBundleId = bundleId) => {
|
|
1791
|
+
if (!simulatorUdid) {
|
|
1792
|
+
await client.openUrl(url);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
try {
|
|
1796
|
+
await activateSimulatorApp(targetBundleId);
|
|
1797
|
+
await client.openUrl(url);
|
|
1798
|
+
await sleep(1e3);
|
|
1799
|
+
return;
|
|
1800
|
+
} catch {
|
|
1801
|
+
try {
|
|
1802
|
+
await client.deleteSession();
|
|
1803
|
+
} catch {
|
|
1804
|
+
}
|
|
1805
|
+
try {
|
|
1806
|
+
await createSessionWithRetry(targetBundleId);
|
|
1807
|
+
await client.disableQuiescence();
|
|
1808
|
+
await activateSimulatorApp(targetBundleId);
|
|
1809
|
+
await client.openUrl(url);
|
|
1810
|
+
await sleep(1e3);
|
|
1811
|
+
return;
|
|
1812
|
+
} catch {
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
const fallbackSchemes = installedUrlSchemesOnSimulator(simulatorUdid, targetBundleId);
|
|
1816
|
+
const candidates = [
|
|
1817
|
+
url,
|
|
1818
|
+
...fallbackSchemes.map((scheme) => replaceUrlScheme(url, scheme)).filter((candidate) => Boolean(candidate))
|
|
1819
|
+
].filter((candidate, index, all) => all.indexOf(candidate) === index);
|
|
1820
|
+
let lastError;
|
|
1821
|
+
for (const candidate of candidates) {
|
|
1822
|
+
try {
|
|
1823
|
+
terminateOnSimulator(simulatorUdid, targetBundleId);
|
|
1824
|
+
await sleep(500);
|
|
1825
|
+
launchWithUrlOnSimulator(simulatorUdid, targetBundleId, candidate);
|
|
1826
|
+
await sleep(1500);
|
|
1827
|
+
try {
|
|
1828
|
+
await client.deleteSession();
|
|
1829
|
+
} catch {
|
|
1830
|
+
}
|
|
1831
|
+
await createSessionWithRetry(targetBundleId);
|
|
1832
|
+
await client.disableQuiescence();
|
|
1833
|
+
await activateSimulatorApp(targetBundleId);
|
|
1834
|
+
return;
|
|
1835
|
+
} catch (error) {
|
|
1836
|
+
lastError = error;
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
if (!client.hasSession()) {
|
|
1840
|
+
try {
|
|
1841
|
+
await createSessionWithRetry(targetBundleId);
|
|
1842
|
+
await client.disableQuiescence();
|
|
1843
|
+
} catch {
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
throw lastError ?? new Error(`Failed to open URL: ${url}`);
|
|
1847
|
+
};
|
|
1848
|
+
yield* Effect3.tryPromise({
|
|
1849
|
+
try: () => createSessionWithRetry(bundleId || void 0),
|
|
1850
|
+
catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
|
|
1851
|
+
});
|
|
1852
|
+
yield* Effect3.tryPromise({
|
|
1853
|
+
try: () => client.disableQuiescence(),
|
|
1854
|
+
catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
|
|
1855
|
+
});
|
|
1856
|
+
const service = {
|
|
1857
|
+
// -----------------------------------------------------------------------
|
|
1858
|
+
// Hierarchy
|
|
1859
|
+
// -----------------------------------------------------------------------
|
|
1860
|
+
dumpHierarchy: () => Effect3.tryPromise({
|
|
1861
|
+
try: () => withSessionRecovery(() => client.getSource()),
|
|
1862
|
+
catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
|
|
1863
|
+
}),
|
|
1864
|
+
// -----------------------------------------------------------------------
|
|
1865
|
+
// Coordinate-level actions
|
|
1866
|
+
// -----------------------------------------------------------------------
|
|
1867
|
+
tapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
1868
|
+
try: () => withSessionRecovery(() => client.tap(x, y)),
|
|
1869
|
+
catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
|
|
1870
|
+
}),
|
|
1871
|
+
doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
1872
|
+
try: () => withSessionRecovery(() => client.doubleTap(x, y)),
|
|
1873
|
+
catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
|
|
1874
|
+
}),
|
|
1875
|
+
longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
|
|
1876
|
+
// duration arrives in ms (spana convention) → convert to seconds for WDA
|
|
1877
|
+
try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
|
|
1878
|
+
catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
|
|
1879
|
+
}),
|
|
1880
|
+
swipe: (sx, sy, ex, ey, dur) => Effect3.tryPromise({
|
|
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
|
+
},
|
|
1896
|
+
catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
|
|
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
|
+
}),
|
|
1910
|
+
// -----------------------------------------------------------------------
|
|
1911
|
+
// Text input
|
|
1912
|
+
// -----------------------------------------------------------------------
|
|
1913
|
+
inputText: (text) => Effect3.tryPromise({
|
|
1914
|
+
try: () => withSessionRecovery(() => client.sendKeys(text)),
|
|
1915
|
+
catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
|
|
1916
|
+
}),
|
|
1917
|
+
pressKey: (key) => Effect3.tryPromise({
|
|
1918
|
+
// WDA uses named hardware buttons; map common names, fall back to home
|
|
1919
|
+
try: async () => {
|
|
1920
|
+
const buttonMap = {
|
|
1921
|
+
home: "home",
|
|
1922
|
+
volumeup: "volumeUp",
|
|
1923
|
+
volumedown: "volumeDown"
|
|
1924
|
+
};
|
|
1925
|
+
const button = buttonMap[key.toLowerCase()];
|
|
1926
|
+
if (button) {
|
|
1927
|
+
await client.pressButton(button);
|
|
1928
|
+
}
|
|
1929
|
+
},
|
|
1930
|
+
catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
|
|
1931
|
+
}),
|
|
1932
|
+
hideKeyboard: () => Effect3.tryPromise({
|
|
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
|
+
},
|
|
1940
|
+
catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
|
|
1941
|
+
}),
|
|
1942
|
+
// -----------------------------------------------------------------------
|
|
1943
|
+
// Queries
|
|
1944
|
+
// -----------------------------------------------------------------------
|
|
1945
|
+
takeScreenshot: () => Effect3.tryPromise({
|
|
1946
|
+
try: () => withSessionRecovery(() => client.getScreenshot()),
|
|
1947
|
+
catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
|
|
1948
|
+
}),
|
|
1949
|
+
getDeviceInfo: () => Effect3.tryPromise({
|
|
1950
|
+
try: async () => {
|
|
1951
|
+
const size = await withSessionRecovery(() => client.getWindowSize());
|
|
1952
|
+
return {
|
|
1953
|
+
platform: "ios",
|
|
1954
|
+
deviceId: `${host}:${port}`,
|
|
1955
|
+
name: "iOS Device",
|
|
1956
|
+
isEmulator: host === "localhost" || host === "127.0.0.1",
|
|
1957
|
+
screenWidth: size.width,
|
|
1958
|
+
screenHeight: size.height,
|
|
1959
|
+
driverType: "wda"
|
|
1960
|
+
};
|
|
1961
|
+
},
|
|
1962
|
+
catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
|
|
1963
|
+
}),
|
|
1964
|
+
// -----------------------------------------------------------------------
|
|
1965
|
+
// App lifecycle
|
|
1966
|
+
// -----------------------------------------------------------------------
|
|
1967
|
+
launchApp: (appBundleId, opts) => Effect3.tryPromise({
|
|
1968
|
+
try: async () => {
|
|
1969
|
+
if (opts?.clearState && simulatorUdid) {
|
|
1970
|
+
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
1971
|
+
try {
|
|
1972
|
+
const { execSync } = await import("child_process");
|
|
1973
|
+
execSync(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
|
|
1974
|
+
stdio: "ignore"
|
|
1975
|
+
});
|
|
1976
|
+
} catch {
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
if (opts?.clearKeychain && simulatorUdid) {
|
|
1980
|
+
resetSimulatorKeychain(simulatorUdid);
|
|
1981
|
+
} else if (opts?.clearKeychain) {
|
|
1982
|
+
console.warn("clearKeychain is only supported on iOS simulators, skipping.");
|
|
1983
|
+
}
|
|
1984
|
+
if (simulatorUdid) {
|
|
1985
|
+
if (opts?.deepLink) {
|
|
1986
|
+
await openSimulatorUrl(opts.deepLink, appBundleId);
|
|
1987
|
+
} else {
|
|
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
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
2016
|
+
await (opts?.deepLink ? client.openUrl(opts.deepLink) : client.launchApp(appBundleId));
|
|
2017
|
+
},
|
|
2018
|
+
catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
|
|
2019
|
+
}),
|
|
2020
|
+
stopApp: (appBundleId) => Effect3.tryPromise({
|
|
2021
|
+
try: () => {
|
|
2022
|
+
if (simulatorUdid) {
|
|
2023
|
+
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
2024
|
+
return Promise.resolve();
|
|
2025
|
+
}
|
|
2026
|
+
return client.terminateApp(appBundleId);
|
|
2027
|
+
},
|
|
2028
|
+
catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
|
|
2029
|
+
}),
|
|
2030
|
+
killApp: (appBundleId) => Effect3.tryPromise({
|
|
2031
|
+
try: () => {
|
|
2032
|
+
if (simulatorUdid) {
|
|
2033
|
+
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
2034
|
+
return Promise.resolve();
|
|
2035
|
+
}
|
|
2036
|
+
return client.terminateApp(appBundleId);
|
|
2037
|
+
},
|
|
2038
|
+
catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
|
|
2039
|
+
}),
|
|
2040
|
+
clearAppState: (appBundleId) => Effect3.tryPromise({
|
|
2041
|
+
try: async () => {
|
|
2042
|
+
if (simulatorUdid) {
|
|
2043
|
+
terminateOnSimulator(simulatorUdid, appBundleId);
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
await client.terminateApp(appBundleId);
|
|
2047
|
+
},
|
|
2048
|
+
catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
|
|
2049
|
+
}),
|
|
2050
|
+
// -----------------------------------------------------------------------
|
|
2051
|
+
// Navigation
|
|
2052
|
+
// -----------------------------------------------------------------------
|
|
2053
|
+
openLink: (url) => Effect3.tryPromise({
|
|
2054
|
+
try: async () => {
|
|
2055
|
+
if (simulatorUdid) {
|
|
2056
|
+
await openSimulatorUrl(url);
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
2059
|
+
await client.openUrl(url);
|
|
2060
|
+
},
|
|
2061
|
+
catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
|
|
2062
|
+
}),
|
|
2063
|
+
back: () => Effect3.tryPromise({
|
|
2064
|
+
// iOS has no hardware back button; pressing home is the closest
|
|
2065
|
+
// equivalent for dismissing the current context.
|
|
2066
|
+
try: () => client.pressHome(),
|
|
2067
|
+
catch: (e) => new DriverError({ message: `Back failed: ${e}` })
|
|
2068
|
+
}),
|
|
2069
|
+
evaluate: () => Effect3.fail(
|
|
2070
|
+
new DriverError({
|
|
2071
|
+
message: "evaluate() requires a WebView context. Use Appium mode (--driver appium) for iOS WebView support."
|
|
2072
|
+
})
|
|
2073
|
+
),
|
|
2074
|
+
getContexts: () => Effect3.fail(
|
|
2075
|
+
new DriverError({
|
|
2076
|
+
message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
|
|
2077
|
+
})
|
|
2078
|
+
),
|
|
2079
|
+
getCurrentContext: () => Effect3.succeed("NATIVE_APP"),
|
|
2080
|
+
setContext: (contextId) => contextId === "NATIVE_APP" ? Effect3.void : Effect3.fail(
|
|
2081
|
+
new DriverError({
|
|
2082
|
+
message: "WebView context switching requires Appium mode. Use --driver appium with an Appium server that supports XCUITest."
|
|
2083
|
+
})
|
|
2084
|
+
)
|
|
2085
|
+
};
|
|
2086
|
+
return service;
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
// src/drivers/playwright-parser.ts
|
|
2091
|
+
function rawNodeToElement(node) {
|
|
2092
|
+
const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
|
|
2093
|
+
return {
|
|
2094
|
+
...node.id !== void 0 ? { id: node.id } : {},
|
|
2095
|
+
...node.text !== void 0 ? { text: node.text } : {},
|
|
2096
|
+
...node.value !== void 0 ? { value: node.value } : {},
|
|
2097
|
+
...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
|
|
2098
|
+
// Use role as elementType when present, otherwise fall back to HTML tag name
|
|
2099
|
+
...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
|
|
2100
|
+
bounds: {
|
|
2101
|
+
x: node.bounds.x,
|
|
2102
|
+
y: node.bounds.y,
|
|
2103
|
+
width: node.bounds.width,
|
|
2104
|
+
height: node.bounds.height
|
|
2105
|
+
},
|
|
2106
|
+
...node.enabled !== void 0 ? { enabled: node.enabled } : {},
|
|
2107
|
+
...node.visible !== void 0 ? { visible: node.visible } : {},
|
|
2108
|
+
...node.clickable !== void 0 ? { clickable: node.clickable } : {},
|
|
2109
|
+
...node.attributes !== void 0 ? { attributes: node.attributes } : {},
|
|
2110
|
+
...children !== void 0 ? { children } : {}
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
function parseWebHierarchy(json) {
|
|
2114
|
+
const raw = JSON.parse(json);
|
|
2115
|
+
return rawNodeToElement(raw);
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
// src/drivers/common/xml-tokenizer.ts
|
|
2119
|
+
function parseAttributes(tagContent) {
|
|
2120
|
+
const attrs = {};
|
|
2121
|
+
const re = /([\w-]+)="([^"]*)"/g;
|
|
2122
|
+
let m;
|
|
2123
|
+
while ((m = re.exec(tagContent)) !== null) {
|
|
2124
|
+
attrs[m[1]] = m[2];
|
|
2125
|
+
}
|
|
2126
|
+
return attrs;
|
|
2127
|
+
}
|
|
2128
|
+
function tokenizeXML(xml, wrapperTag) {
|
|
2129
|
+
let pos = 0;
|
|
2130
|
+
function skipWhitespace() {
|
|
2131
|
+
while (pos < xml.length && /\s/.test(xml[pos])) pos++;
|
|
2132
|
+
}
|
|
2133
|
+
function parseNode() {
|
|
2134
|
+
skipWhitespace();
|
|
2135
|
+
if (pos >= xml.length) return null;
|
|
2136
|
+
if (xml[pos] !== "<") return null;
|
|
2137
|
+
pos++;
|
|
2138
|
+
if (xml[pos] === "?" || xml[pos] === "!") {
|
|
2139
|
+
const close = xml.indexOf(">", pos);
|
|
2140
|
+
if (close === -1) return null;
|
|
2141
|
+
pos = close + 1;
|
|
2142
|
+
return null;
|
|
2143
|
+
}
|
|
2144
|
+
if (xml[pos] === "/") {
|
|
2145
|
+
const close = xml.indexOf(">", pos);
|
|
2146
|
+
if (close === -1) return null;
|
|
2147
|
+
pos = close + 1;
|
|
2148
|
+
return null;
|
|
2149
|
+
}
|
|
2150
|
+
const tagStart = pos;
|
|
2151
|
+
while (pos < xml.length && !/[\s/>]/.test(xml[pos])) pos++;
|
|
2152
|
+
const tagName = xml.slice(tagStart, pos);
|
|
2153
|
+
const tagBodyStart = pos;
|
|
2154
|
+
let selfClosing = false;
|
|
2155
|
+
let inQuote = false;
|
|
2156
|
+
let quoteChar = "";
|
|
2157
|
+
while (pos < xml.length) {
|
|
2158
|
+
const ch = xml[pos];
|
|
2159
|
+
if (inQuote) {
|
|
2160
|
+
if (ch === quoteChar) inQuote = false;
|
|
2161
|
+
} else {
|
|
2162
|
+
if (ch === '"' || ch === "'") {
|
|
2163
|
+
inQuote = true;
|
|
2164
|
+
quoteChar = ch;
|
|
2165
|
+
} else if (ch === "/" && xml[pos + 1] === ">") {
|
|
2166
|
+
selfClosing = true;
|
|
2167
|
+
pos += 2;
|
|
2168
|
+
break;
|
|
2169
|
+
} else if (ch === ">") {
|
|
2170
|
+
pos++;
|
|
2171
|
+
break;
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
pos++;
|
|
2175
|
+
}
|
|
2176
|
+
const tagBody = xml.slice(tagBodyStart, selfClosing ? pos - 2 : pos - 1);
|
|
2177
|
+
const attrs = parseAttributes(tagBody);
|
|
2178
|
+
const node = { tagName, attrs, children: [] };
|
|
2179
|
+
if (!selfClosing) {
|
|
2180
|
+
while (pos < xml.length) {
|
|
2181
|
+
skipWhitespace();
|
|
2182
|
+
if (pos >= xml.length) break;
|
|
2183
|
+
if (xml[pos] === "<" && xml[pos + 1] === "/") {
|
|
2184
|
+
const close = xml.indexOf(">", pos);
|
|
2185
|
+
if (close !== -1) pos = close + 1;
|
|
2186
|
+
break;
|
|
2187
|
+
}
|
|
2188
|
+
const child = parseNode();
|
|
2189
|
+
if (child !== null) {
|
|
2190
|
+
node.children.push(child);
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
return node;
|
|
2195
|
+
}
|
|
2196
|
+
const roots = [];
|
|
2197
|
+
const closingWrapper = `/${wrapperTag}`;
|
|
2198
|
+
while (pos < xml.length) {
|
|
2199
|
+
skipWhitespace();
|
|
2200
|
+
if (pos >= xml.length) break;
|
|
2201
|
+
if (xml[pos] !== "<") {
|
|
2202
|
+
pos++;
|
|
2203
|
+
continue;
|
|
2204
|
+
}
|
|
2205
|
+
const peek = pos + 1;
|
|
2206
|
+
let nameEnd = peek;
|
|
2207
|
+
while (nameEnd < xml.length && !/[\s/>]/.test(xml[nameEnd])) nameEnd++;
|
|
2208
|
+
const peekName = xml.slice(peek, nameEnd);
|
|
2209
|
+
if (peekName === wrapperTag) {
|
|
2210
|
+
const close = xml.indexOf(">", pos);
|
|
2211
|
+
if (close === -1) break;
|
|
2212
|
+
pos = close + 1;
|
|
2213
|
+
continue;
|
|
2214
|
+
}
|
|
2215
|
+
if (peekName === closingWrapper) {
|
|
2216
|
+
const close = xml.indexOf(">", pos);
|
|
2217
|
+
if (close !== -1) pos = close + 1;
|
|
2218
|
+
break;
|
|
2219
|
+
}
|
|
2220
|
+
if (peekName.startsWith("?") || peekName.startsWith("!")) {
|
|
2221
|
+
const close = xml.indexOf(">", pos);
|
|
2222
|
+
if (close !== -1) pos = close + 1;
|
|
2223
|
+
continue;
|
|
2224
|
+
}
|
|
2225
|
+
const node = parseNode();
|
|
2226
|
+
if (node !== null) {
|
|
2227
|
+
roots.push(node);
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
return roots;
|
|
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
|
+
}
|
|
2261
|
+
function rawNodeToElement2(node) {
|
|
2262
|
+
const a = node.attrs;
|
|
2263
|
+
const rawId = a["resource-id"] ?? "";
|
|
2264
|
+
const id = rawId ? stripResourceIdPrefix(rawId) : void 0;
|
|
2265
|
+
const text = a["text"] || void 0;
|
|
2266
|
+
const accessibilityLabel = a["content-desc"] || void 0;
|
|
2267
|
+
const elementType = a["class"] || void 0;
|
|
2268
|
+
const boundsStr = a["bounds"] ?? "[0,0][0,0]";
|
|
2269
|
+
const bounds = parseBounds(boundsStr);
|
|
2270
|
+
const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
|
|
2271
|
+
const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
|
|
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
|
+
}
|
|
2279
|
+
const children = node.children.length > 0 ? node.children.map(rawNodeToElement2) : void 0;
|
|
2280
|
+
return {
|
|
2281
|
+
...id !== void 0 ? { id } : {},
|
|
2282
|
+
...text !== void 0 ? { text } : {},
|
|
2283
|
+
...value !== void 0 ? { value } : {},
|
|
2284
|
+
...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
|
|
2285
|
+
...elementType !== void 0 ? { elementType } : {},
|
|
2286
|
+
bounds,
|
|
2287
|
+
...enabled !== void 0 ? { enabled } : {},
|
|
2288
|
+
...focused !== void 0 ? { focused } : {},
|
|
2289
|
+
...clickable !== void 0 ? { clickable } : {},
|
|
2290
|
+
...Object.keys(attributes).length > 0 ? { attributes } : {},
|
|
2291
|
+
...children !== void 0 ? { children } : {}
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
function parseAndroidHierarchy(xml) {
|
|
2295
|
+
const roots = tokenizeXML(xml, "hierarchy");
|
|
2296
|
+
for (const root of roots) {
|
|
2297
|
+
prepareAndroidNode(root);
|
|
2298
|
+
}
|
|
2299
|
+
if (roots.length === 0) {
|
|
2300
|
+
throw new Error("parseAndroidHierarchy: no root elements found in hierarchy");
|
|
2301
|
+
}
|
|
2302
|
+
if (roots.length === 1) {
|
|
2303
|
+
return rawNodeToElement2(roots[0]);
|
|
2304
|
+
}
|
|
2305
|
+
return {
|
|
2306
|
+
elementType: "hierarchy",
|
|
2307
|
+
bounds: { x: 0, y: 0, width: 0, height: 0 },
|
|
2308
|
+
children: roots.map(rawNodeToElement2)
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// src/drivers/wda/pagesource.ts
|
|
2313
|
+
var CLICKABLE_TYPES = /* @__PURE__ */ new Set([
|
|
2314
|
+
"XCUIElementTypeButton",
|
|
2315
|
+
"XCUIElementTypeLink",
|
|
2316
|
+
"XCUIElementTypeTextField",
|
|
2317
|
+
"XCUIElementTypeSecureTextField",
|
|
2318
|
+
"XCUIElementTypeSearchField",
|
|
2319
|
+
"XCUIElementTypeSwitch",
|
|
2320
|
+
"XCUIElementTypeSlider",
|
|
2321
|
+
"XCUIElementTypeStepper",
|
|
2322
|
+
"XCUIElementTypeSegmentedControl",
|
|
2323
|
+
"XCUIElementTypeCell",
|
|
2324
|
+
"XCUIElementTypeTab",
|
|
2325
|
+
"XCUIElementTypeTabBar",
|
|
2326
|
+
"XCUIElementTypeMenu",
|
|
2327
|
+
"XCUIElementTypeMenuItem",
|
|
2328
|
+
"XCUIElementTypePickerWheel",
|
|
2329
|
+
"XCUIElementTypeDatePicker",
|
|
2330
|
+
"XCUIElementTypeToggle",
|
|
2331
|
+
"XCUIElementTypePageIndicator"
|
|
2332
|
+
]);
|
|
2333
|
+
function prepareIOSNode(node) {
|
|
2334
|
+
node.tagName = node.attrs["type"] ?? node.tagName;
|
|
2335
|
+
for (const child of node.children) {
|
|
2336
|
+
prepareIOSNode(child);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
function rawNodeToElement3(node) {
|
|
2340
|
+
const a = node.attrs;
|
|
2341
|
+
const elementType = node.tagName || void 0;
|
|
2342
|
+
const id = a["name"] || void 0;
|
|
2343
|
+
const accessibilityLabel = a["label"] || void 0;
|
|
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;
|
|
2347
|
+
const x = a["x"] !== void 0 ? parseInt(a["x"], 10) : 0;
|
|
2348
|
+
const y = a["y"] !== void 0 ? parseInt(a["y"], 10) : 0;
|
|
2349
|
+
const width = a["width"] !== void 0 ? parseInt(a["width"], 10) : 0;
|
|
2350
|
+
const height = a["height"] !== void 0 ? parseInt(a["height"], 10) : 0;
|
|
2351
|
+
const bounds = { x, y, width, height };
|
|
2352
|
+
const enabled = a["enabled"] !== void 0 ? a["enabled"] === "true" : void 0;
|
|
2353
|
+
const visible = a["visible"] !== void 0 ? a["visible"] === "true" : void 0;
|
|
2354
|
+
const focused = a["focused"] !== void 0 ? a["focused"] === "true" : void 0;
|
|
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
|
+
}
|
|
2360
|
+
const children = node.children.length > 0 ? node.children.map(rawNodeToElement3) : void 0;
|
|
2361
|
+
return {
|
|
2362
|
+
...id !== void 0 ? { id } : {},
|
|
2363
|
+
...text !== void 0 ? { text } : {},
|
|
2364
|
+
...value !== void 0 ? { value } : {},
|
|
2365
|
+
...accessibilityLabel !== void 0 ? { accessibilityLabel } : {},
|
|
2366
|
+
...elementType !== void 0 ? { elementType } : {},
|
|
2367
|
+
bounds,
|
|
2368
|
+
...enabled !== void 0 ? { enabled } : {},
|
|
2369
|
+
...visible !== void 0 ? { visible } : {},
|
|
2370
|
+
...focused !== void 0 ? { focused } : {},
|
|
2371
|
+
...clickable !== void 0 ? { clickable } : {},
|
|
2372
|
+
...Object.keys(attributes).length > 0 ? { attributes } : {},
|
|
2373
|
+
...children !== void 0 ? { children } : {}
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
function parseIOSHierarchy(xml) {
|
|
2377
|
+
const roots = tokenizeXML(xml, "AppiumAUT");
|
|
2378
|
+
for (const root of roots) {
|
|
2379
|
+
prepareIOSNode(root);
|
|
2380
|
+
}
|
|
2381
|
+
if (roots.length === 0) {
|
|
2382
|
+
throw new Error("parseIOSHierarchy: no elements found in page source");
|
|
2383
|
+
}
|
|
2384
|
+
if (roots.length === 1) {
|
|
2385
|
+
return rawNodeToElement3(roots[0]);
|
|
2386
|
+
}
|
|
2387
|
+
return {
|
|
2388
|
+
elementType: "AppiumAUT",
|
|
2389
|
+
bounds: { x: 0, y: 0, width: 0, height: 0 },
|
|
2390
|
+
children: roots.map(rawNodeToElement3)
|
|
2391
|
+
};
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
export {
|
|
2395
|
+
makePlaywrightDriver,
|
|
2396
|
+
createUiAutomator2Driver,
|
|
2397
|
+
createWDADriver,
|
|
2398
|
+
parseWebHierarchy,
|
|
2399
|
+
parseAndroidHierarchy,
|
|
2400
|
+
parseIOSHierarchy
|
|
2401
|
+
};
|
|
2402
|
+
//# sourceMappingURL=chunk-WQ4GXUUE.js.map
|