spana-test 0.5.0 → 0.7.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 +126 -246
- package/README.md +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +5 -5
- package/dist/{storybook-CxaP3YDz.d.ts → app-D_UyZBsl.d.ts} +213 -10
- package/dist/{chunk-WSA5QPTA.js → chunk-2IXXEXTL.js} +2 -2
- package/dist/{chunk-3YE2POGD.js → chunk-3SH5JQF7.js} +143 -3
- package/dist/chunk-3SH5JQF7.js.map +1 -0
- package/dist/chunk-54ASKII6.js +183 -0
- package/dist/chunk-54ASKII6.js.map +1 -0
- package/dist/{chunk-LRGT342X.js → chunk-6B5Y75V4.js} +1633 -533
- package/dist/chunk-6B5Y75V4.js.map +1 -0
- package/dist/{chunk-SQL3YRR5.js → chunk-JYFPZRCN.js} +21 -3
- package/dist/chunk-JYFPZRCN.js.map +1 -0
- package/dist/{chunk-UJQ7PID5.js → chunk-KNSAHEXI.js} +78 -3
- package/dist/chunk-KNSAHEXI.js.map +1 -0
- package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
- package/dist/chunk-PLE7RFQE.js.map +1 -0
- package/dist/{chunk-H3RWZCID.js → chunk-RURZVMZ7.js} +104 -3
- package/dist/chunk-RURZVMZ7.js.map +1 -0
- package/dist/{chunk-XENRC3YO.js → chunk-T3EBOYLS.js} +751 -59
- package/dist/chunk-T3EBOYLS.js.map +1 -0
- package/dist/{chunk-PJKIXVSO.js → chunk-T5CROOR7.js} +898 -238
- package/dist/chunk-T5CROOR7.js.map +1 -0
- package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
- package/dist/cli.js +11 -11
- package/dist/cli.js.map +1 -1
- package/dist/config-loader-NIDQGP3K.js +9 -0
- package/dist/{doctor-command-WB3O2H64.js → doctor-command-WPEVZEZ4.js} +3 -3
- package/dist/{filters-Q3ALKWZ5.js → filters-MQG2RMPX.js} +4 -2
- package/dist/flow-g6AICPAl.d.ts +95 -0
- package/dist/gherkin/steps.d.ts +2 -2
- package/dist/{html-F3X3XPSX.js → html-IKCTZH2U.js} +194 -3
- package/dist/html-IKCTZH2U.js.map +1 -0
- package/dist/index.d.ts +436 -21
- package/dist/index.js +328 -7
- package/dist/index.js.map +1 -1
- package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
- package/dist/{screenshot-compare-3QRHHSFZ.js → screenshot-compare-POTXVUTL.js} +21 -1
- package/dist/screenshot-compare-POTXVUTL.js.map +1 -0
- package/dist/{server-PRM7BVVD.js → server-EBPYK3VE.js} +5 -5
- package/dist/{server-QWJJB3WG.js → server-IGLBFEU7.js} +2 -2
- package/dist/{session-2E6OK6BH.js → session-QRWH3SPW.js} +4 -4
- package/dist/{session-Ddem-Q5n.d.ts → session-cJ_tZjCL.d.ts} +22 -1
- package/dist/{studio-command-O3NN5BCG.js → studio-command-FLA5HKRK.js} +2 -2
- package/dist/{test-command-FYOZ6QAE.js → test-command-P5W7UD52.js} +24 -10
- package/dist/test-command-P5W7UD52.js.map +1 -0
- package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
- package/package.json +3 -2
- package/dist/chunk-3TRMQCUT.js.map +0 -1
- package/dist/chunk-3YE2POGD.js.map +0 -1
- package/dist/chunk-H3RWZCID.js.map +0 -1
- package/dist/chunk-LRGT342X.js.map +0 -1
- package/dist/chunk-PJKIXVSO.js.map +0 -1
- package/dist/chunk-SQL3YRR5.js.map +0 -1
- package/dist/chunk-UJQ7PID5.js.map +0 -1
- package/dist/chunk-XENRC3YO.js.map +0 -1
- package/dist/config-loader-XGDDJGVY.js +0 -9
- package/dist/flow-CyRC-tTc.d.ts +0 -176
- package/dist/html-F3X3XPSX.js.map +0 -1
- package/dist/screenshot-compare-3QRHHSFZ.js.map +0 -1
- package/dist/test-command-FYOZ6QAE.js.map +0 -1
- /package/dist/{chunk-WSA5QPTA.js.map → chunk-2IXXEXTL.js.map} +0 -0
- /package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
- /package/dist/{config-loader-XGDDJGVY.js.map → config-loader-NIDQGP3K.js.map} +0 -0
- /package/dist/{doctor-command-WB3O2H64.js.map → doctor-command-WPEVZEZ4.js.map} +0 -0
- /package/dist/{filters-Q3ALKWZ5.js.map → filters-MQG2RMPX.js.map} +0 -0
- /package/dist/{runner-6HK62Q7B.js.map → runner-TF4OKPYP.js.map} +0 -0
- /package/dist/{server-PRM7BVVD.js.map → server-EBPYK3VE.js.map} +0 -0
- /package/dist/{server-QWJJB3WG.js.map → server-IGLBFEU7.js.map} +0 -0
- /package/dist/{session-2E6OK6BH.js.map → session-QRWH3SPW.js.map} +0 -0
- /package/dist/{studio-command-O3NN5BCG.js.map → studio-command-FLA5HKRK.js.map} +0 -0
- /package/dist/{validator-HZ2A3NEI.js.map → validator-BLOLIHUY.js.map} +0 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
buildStorybookUrl,
|
|
3
2
|
connectPlaywrightOverCDP,
|
|
3
|
+
connectPlaywrightOverWS,
|
|
4
4
|
createCoordinator,
|
|
5
|
+
createPromiseApp,
|
|
5
6
|
createUiAutomator2Driver,
|
|
6
7
|
createWDADriver,
|
|
7
8
|
ensureWarmBrowserDaemon,
|
|
@@ -13,19 +14,21 @@ import {
|
|
|
13
14
|
parseAndroidHierarchy,
|
|
14
15
|
parseIOSHierarchy,
|
|
15
16
|
parseWebHierarchy,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} from "./chunk-
|
|
17
|
+
resolveNetworkConditions,
|
|
18
|
+
setupUiAutomator2
|
|
19
|
+
} from "./chunk-T5CROOR7.js";
|
|
19
20
|
import {
|
|
20
21
|
CdpDomChannel,
|
|
21
22
|
DriverError,
|
|
22
23
|
createSpanaBridgeChannel,
|
|
23
24
|
makeElectrobunDriver
|
|
24
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-T3EBOYLS.js";
|
|
25
26
|
import {
|
|
26
27
|
setupWDA
|
|
27
28
|
} from "./chunk-HYSTRWYN.js";
|
|
28
29
|
import {
|
|
30
|
+
getHealthyWarmDaemon,
|
|
31
|
+
registerWarmDaemon,
|
|
29
32
|
updateWarmDaemonSession
|
|
30
33
|
} from "./chunk-DTNK54C2.js";
|
|
31
34
|
import {
|
|
@@ -43,336 +46,8 @@ import {
|
|
|
43
46
|
ensureAndroidDevice
|
|
44
47
|
} from "./chunk-H27IBIGA.js";
|
|
45
48
|
|
|
46
|
-
// src/api/app.ts
|
|
47
|
-
import { Effect } from "effect";
|
|
48
|
-
var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
|
|
49
|
-
function createPromiseApp(driver, appId, config, recorder, options = {}) {
|
|
50
|
-
const coord = createCoordinator(driver, config);
|
|
51
|
-
const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
|
|
52
|
-
const run = (effect) => Effect.runPromise(effect);
|
|
53
|
-
const unsupportedWebFeature = (feature) => Effect.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
|
|
54
|
-
const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
|
|
55
|
-
const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
|
|
56
|
-
const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
|
|
57
|
-
return {
|
|
58
|
-
tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
|
|
59
|
-
tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
|
|
60
|
-
selector: { point: { x, y } },
|
|
61
|
-
captureScreenshot: true
|
|
62
|
-
}),
|
|
63
|
-
doubleTap: (selector, opts) => runStep("doubleTap", () => run(coord.doubleTap(selector, opts)), {
|
|
64
|
-
selector,
|
|
65
|
-
captureScreenshot: true
|
|
66
|
-
}),
|
|
67
|
-
longPress: (selector, opts) => runStep("longPress", () => run(coord.longPress(selector, opts?.duration, opts)), {
|
|
68
|
-
selector,
|
|
69
|
-
captureScreenshot: true
|
|
70
|
-
}),
|
|
71
|
-
longPressXY: (x, y, opts) => runStep("longPressXY", () => run(coord.longPressXY(x, y, opts?.duration)), {
|
|
72
|
-
selector: { point: { x, y } },
|
|
73
|
-
captureScreenshot: true
|
|
74
|
-
}),
|
|
75
|
-
inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
|
|
76
|
-
pressKey: (key) => runStep(`pressKey(${key})`, () => run(coord.pressKey(key)), { captureScreenshot: true }),
|
|
77
|
-
hideKeyboard: () => runStep("hideKeyboard", () => run(coord.hideKeyboard()), { captureScreenshot: true }),
|
|
78
|
-
dismissKeyboard: (opts) => runStep(
|
|
79
|
-
`dismissKeyboard(${opts?.strategy ?? "auto"})`,
|
|
80
|
-
() => run(coord.dismissKeyboard(opts)),
|
|
81
|
-
{
|
|
82
|
-
selector: { strategy: opts?.strategy ?? "auto" },
|
|
83
|
-
captureScreenshot: true
|
|
84
|
-
}
|
|
85
|
-
),
|
|
86
|
-
swipe: (direction, opts) => runStep(`swipe(${direction})`, () => run(coord.swipe(direction, opts)), {
|
|
87
|
-
captureScreenshot: true
|
|
88
|
-
}),
|
|
89
|
-
scroll: (direction) => runStep(`scroll(${direction})`, () => run(coord.scroll(direction)), {
|
|
90
|
-
captureScreenshot: true
|
|
91
|
-
}),
|
|
92
|
-
scrollUntilVisible: (selector, opts) => runStep(
|
|
93
|
-
`scrollUntilVisible(${opts?.direction ?? "down"})`,
|
|
94
|
-
() => run(coord.scrollUntilVisible(selector, opts)),
|
|
95
|
-
{
|
|
96
|
-
selector: {
|
|
97
|
-
target: selector,
|
|
98
|
-
...opts,
|
|
99
|
-
direction: opts?.direction ?? "down",
|
|
100
|
-
maxScrolls: opts?.maxScrolls ?? 5
|
|
101
|
-
},
|
|
102
|
-
captureScreenshot: true
|
|
103
|
-
}
|
|
104
|
-
),
|
|
105
|
-
backUntilVisible: (selector, opts) => runStep(
|
|
106
|
-
`backUntilVisible(${opts?.maxBacks ?? 3})`,
|
|
107
|
-
() => run(coord.backUntilVisible(selector, opts)),
|
|
108
|
-
{
|
|
109
|
-
selector: {
|
|
110
|
-
target: selector,
|
|
111
|
-
...opts,
|
|
112
|
-
maxBacks: opts?.maxBacks ?? 3
|
|
113
|
-
},
|
|
114
|
-
captureScreenshot: true
|
|
115
|
-
}
|
|
116
|
-
),
|
|
117
|
-
launch: (opts) => {
|
|
118
|
-
const mergedLaunchOptions = mergeLaunchOptions(options.launchOptions, opts);
|
|
119
|
-
return runStep("launch", () => run(driver.launchApp(appId, mergedLaunchOptions)), {
|
|
120
|
-
selector: mergedLaunchOptions,
|
|
121
|
-
captureScreenshot: true
|
|
122
|
-
});
|
|
123
|
-
},
|
|
124
|
-
stop: () => runStep("stop", () => run(driver.stopApp(appId)), { captureScreenshot: true }),
|
|
125
|
-
kill: () => runStep("kill", () => run(driver.killApp(appId)), { captureScreenshot: true }),
|
|
126
|
-
clearState: () => runStep("clearState", () => run(driver.clearAppState(appId)), { captureScreenshot: true }),
|
|
127
|
-
openLink: (url) => runStep("openLink", () => run(driver.openLink(url)), {
|
|
128
|
-
selector: { url },
|
|
129
|
-
captureScreenshot: true
|
|
130
|
-
}),
|
|
131
|
-
openStory: (storyId, opts) => runStep(
|
|
132
|
-
`openStory(${storyId})`,
|
|
133
|
-
async () => {
|
|
134
|
-
if (platform !== "web") {
|
|
135
|
-
await run(unsupportedWebFeature("openStory"));
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
const url = buildStorybookUrl(storyId, opts, {
|
|
139
|
-
appBaseUrl: appId,
|
|
140
|
-
storybook: options.storybook
|
|
141
|
-
});
|
|
142
|
-
await run(driver.openLink(url));
|
|
143
|
-
},
|
|
144
|
-
{
|
|
145
|
-
selector: {
|
|
146
|
-
storyId,
|
|
147
|
-
viewMode: opts?.viewMode ?? "story",
|
|
148
|
-
args: opts?.args,
|
|
149
|
-
globals: opts?.globals,
|
|
150
|
-
baseUrl: opts?.baseUrl
|
|
151
|
-
},
|
|
152
|
-
captureScreenshot: true
|
|
153
|
-
}
|
|
154
|
-
),
|
|
155
|
-
back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
|
|
156
|
-
takeScreenshot: (name) => runScreenshotStep(
|
|
157
|
-
name ? `takeScreenshot(${name})` : "takeScreenshot",
|
|
158
|
-
() => run(driver.takeScreenshot()),
|
|
159
|
-
{ name }
|
|
160
|
-
),
|
|
161
|
-
evaluate: (fn, ...args) => runStep("evaluate", () => run(driver.evaluate(fn, ...args))),
|
|
162
|
-
mockNetwork: (matcher, response) => runStep(
|
|
163
|
-
"mockNetwork",
|
|
164
|
-
() => run(optionalMethod("mockNetwork", driver.mockNetwork)(matcher, response)),
|
|
165
|
-
{
|
|
166
|
-
selector: { matcher: describeMatcher(matcher), response }
|
|
167
|
-
}
|
|
168
|
-
),
|
|
169
|
-
blockNetwork: (matcher) => runStep(
|
|
170
|
-
"blockNetwork",
|
|
171
|
-
() => run(optionalMethod("blockNetwork", driver.blockNetwork)(matcher)),
|
|
172
|
-
{
|
|
173
|
-
selector: { matcher: describeMatcher(matcher) }
|
|
174
|
-
}
|
|
175
|
-
),
|
|
176
|
-
clearNetworkMocks: () => runStep(
|
|
177
|
-
"clearNetworkMocks",
|
|
178
|
-
() => run(optionalMethod("clearNetworkMocks", driver.clearNetworkMocks)())
|
|
179
|
-
),
|
|
180
|
-
setNetworkConditions: (conditions) => runStep(
|
|
181
|
-
"setNetworkConditions",
|
|
182
|
-
() => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
|
|
183
|
-
{ selector: conditions }
|
|
184
|
-
),
|
|
185
|
-
saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
|
|
186
|
-
selector: { path }
|
|
187
|
-
}),
|
|
188
|
-
loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
|
|
189
|
-
selector: { path }
|
|
190
|
-
}),
|
|
191
|
-
saveAuthState: (path) => runStep(
|
|
192
|
-
"saveAuthState",
|
|
193
|
-
() => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
|
|
194
|
-
{ selector: { path } }
|
|
195
|
-
),
|
|
196
|
-
loadAuthState: (path) => runStep(
|
|
197
|
-
"loadAuthState",
|
|
198
|
-
() => run(optionalMethod("loadAuthState", driver.loadAuthState)(path)),
|
|
199
|
-
{ selector: { path } }
|
|
200
|
-
),
|
|
201
|
-
downloadFile: (path) => runStep(
|
|
202
|
-
"downloadFile",
|
|
203
|
-
() => run(optionalMethod("downloadFile", driver.downloadFile)(path)),
|
|
204
|
-
{ selector: { path } }
|
|
205
|
-
),
|
|
206
|
-
uploadFile: (selector, path) => runStep(
|
|
207
|
-
"uploadFile",
|
|
208
|
-
() => run(optionalMethod("uploadFile", driver.uploadFile)(selector, path)),
|
|
209
|
-
{
|
|
210
|
-
selector: { target: selector, path },
|
|
211
|
-
captureScreenshot: true
|
|
212
|
-
}
|
|
213
|
-
),
|
|
214
|
-
newTab: (url) => runStep("newTab", () => run(optionalMethod("newTab", driver.newTab)(url)), {
|
|
215
|
-
selector: url ? { url } : void 0,
|
|
216
|
-
captureScreenshot: true
|
|
217
|
-
}),
|
|
218
|
-
switchToTab: (index) => runStep(
|
|
219
|
-
`switchToTab(${index})`,
|
|
220
|
-
() => run(optionalMethod("switchToTab", driver.switchToTab)(index)),
|
|
221
|
-
{
|
|
222
|
-
selector: { index },
|
|
223
|
-
captureScreenshot: true
|
|
224
|
-
}
|
|
225
|
-
),
|
|
226
|
-
closeTab: () => runStep("closeTab", () => run(optionalMethod("closeTab", driver.closeTab)()), {
|
|
227
|
-
captureScreenshot: true
|
|
228
|
-
}),
|
|
229
|
-
getTabIds: () => runStep("getTabIds", () => run(optionalMethod("getTabIds", driver.getTabIds)())),
|
|
230
|
-
getConsoleLogs: () => runStep(
|
|
231
|
-
"getConsoleLogs",
|
|
232
|
-
() => run(optionalMethod("getConsoleLogs", driver.getConsoleLogs)())
|
|
233
|
-
),
|
|
234
|
-
getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
|
|
235
|
-
getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
|
|
236
|
-
pinch: (selector, opts) => runStep("pinch", () => run(coord.pinch(selector, opts)), {
|
|
237
|
-
selector,
|
|
238
|
-
captureScreenshot: true
|
|
239
|
-
}),
|
|
240
|
-
zoom: (selector, opts) => runStep("zoom", () => run(coord.zoom(selector, opts)), {
|
|
241
|
-
selector,
|
|
242
|
-
captureScreenshot: true
|
|
243
|
-
}),
|
|
244
|
-
multiTouch: (sequences) => runStep("multiTouch", () => run(coord.multiTouch(sequences)), { captureScreenshot: true }),
|
|
245
|
-
getText: (selector, opts) => runStep("getText", () => run(coord.getText(selector, opts)), { selector }),
|
|
246
|
-
getAttribute: (selector, name, opts) => runStep(`getAttribute(${name})`, () => run(coord.getAttribute(selector, name, opts)), {
|
|
247
|
-
selector
|
|
248
|
-
}),
|
|
249
|
-
isVisible: (selector, opts) => {
|
|
250
|
-
const timeout = opts?.timeout ?? 1e3;
|
|
251
|
-
return run(
|
|
252
|
-
Effect.gen(function* () {
|
|
253
|
-
const result = yield* Effect.either(
|
|
254
|
-
waitForElement(
|
|
255
|
-
driver,
|
|
256
|
-
selector,
|
|
257
|
-
config.parse,
|
|
258
|
-
{ timeout, pollInterval: 100 },
|
|
259
|
-
void 0
|
|
260
|
-
)
|
|
261
|
-
);
|
|
262
|
-
return result._tag === "Right";
|
|
263
|
-
})
|
|
264
|
-
);
|
|
265
|
-
},
|
|
266
|
-
isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
|
|
267
|
-
// Web-first bridge & fast state helpers
|
|
268
|
-
waitForIdle: (opts) => runStep("waitForIdle", async () => {
|
|
269
|
-
if (driver.domChannel?.waitForIdle) {
|
|
270
|
-
await driver.domChannel.waitForIdle(opts);
|
|
271
|
-
}
|
|
272
|
-
}),
|
|
273
|
-
setStorage: (entries) => runStep("setStorage", async () => {
|
|
274
|
-
if (driver.domChannel?.setStorage) {
|
|
275
|
-
await driver.domChannel.setStorage(entries);
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
const serialized = JSON.stringify(entries);
|
|
279
|
-
await run(
|
|
280
|
-
driver.evaluate(
|
|
281
|
-
`((payload) => {
|
|
282
|
-
if (payload.localStorage) {
|
|
283
|
-
for (const [k, v] of Object.entries(payload.localStorage)) {
|
|
284
|
-
window.localStorage.setItem(k, v);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
if (payload.sessionStorage) {
|
|
288
|
-
for (const [k, v] of Object.entries(payload.sessionStorage)) {
|
|
289
|
-
window.sessionStorage.setItem(k, v);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
if (payload.cookies) {
|
|
293
|
-
for (const c of payload.cookies) {
|
|
294
|
-
const path = c.path ? '; path=' + c.path : '; path=/';
|
|
295
|
-
const domain = c.domain ? '; domain=' + c.domain : '';
|
|
296
|
-
document.cookie = encodeURIComponent(c.name) + '=' + encodeURIComponent(c.value) + path + domain;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
})(${serialized})`
|
|
300
|
-
)
|
|
301
|
-
);
|
|
302
|
-
}),
|
|
303
|
-
clearStorage: (opts) => runStep("clearStorage", async () => {
|
|
304
|
-
if (driver.domChannel?.clearStorage) {
|
|
305
|
-
await driver.domChannel.clearStorage(opts);
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
const serialized = JSON.stringify(opts ?? {});
|
|
309
|
-
await run(
|
|
310
|
-
driver.evaluate(
|
|
311
|
-
`((clearOpts) => {
|
|
312
|
-
if (clearOpts.localStorage !== false) {
|
|
313
|
-
try { window.localStorage.clear(); } catch {}
|
|
314
|
-
}
|
|
315
|
-
if (clearOpts.sessionStorage !== false) {
|
|
316
|
-
try { window.sessionStorage.clear(); } catch {}
|
|
317
|
-
}
|
|
318
|
-
})(${serialized})`
|
|
319
|
-
)
|
|
320
|
-
);
|
|
321
|
-
}),
|
|
322
|
-
resetFast: () => runStep("resetFast", async () => {
|
|
323
|
-
if (driver.resetFast) {
|
|
324
|
-
await run(driver.resetFast());
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if (driver.domChannel?.clearStorage) {
|
|
328
|
-
await driver.domChannel.clearStorage({
|
|
329
|
-
localStorage: true,
|
|
330
|
-
sessionStorage: true,
|
|
331
|
-
cookies: true,
|
|
332
|
-
indexedDB: true,
|
|
333
|
-
capacitorPreferences: true
|
|
334
|
-
});
|
|
335
|
-
if (driver.domChannel.reload) {
|
|
336
|
-
await driver.domChannel.reload();
|
|
337
|
-
}
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
await run(driver.clearAppState(appId));
|
|
341
|
-
}),
|
|
342
|
-
// WebView / hybrid context switching (low-level escape hatches)
|
|
343
|
-
getContexts: () => runStep(
|
|
344
|
-
"getContexts",
|
|
345
|
-
() => run((driver.getContexts ?? (() => Effect.succeed(["NATIVE_APP"])))())
|
|
346
|
-
),
|
|
347
|
-
getCurrentContext: () => runStep(
|
|
348
|
-
"getCurrentContext",
|
|
349
|
-
() => run((driver.getCurrentContext ?? (() => Effect.succeed("NATIVE_APP")))())
|
|
350
|
-
),
|
|
351
|
-
switchToContext: (contextId) => runStep(
|
|
352
|
-
`switchToContext(${contextId})`,
|
|
353
|
-
() => run((driver.setContext ?? ((_id) => Effect.void))(contextId))
|
|
354
|
-
),
|
|
355
|
-
switchToWebView: () => runStep("switchToWebView", async () => {
|
|
356
|
-
const contexts = await run(
|
|
357
|
-
(driver.getContexts ?? (() => Effect.succeed(["NATIVE_APP"])))()
|
|
358
|
-
);
|
|
359
|
-
const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
|
|
360
|
-
if (!webview) {
|
|
361
|
-
throw new DriverError({
|
|
362
|
-
message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
await run((driver.setContext ?? ((_id) => Effect.void))(webview));
|
|
366
|
-
}),
|
|
367
|
-
switchToNativeApp: () => runStep(
|
|
368
|
-
"switchToNativeApp",
|
|
369
|
-
() => run((driver.setContext ?? ((_id) => Effect.void))("NATIVE_APP"))
|
|
370
|
-
)
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
|
-
|
|
374
49
|
// src/api/expect.ts
|
|
375
|
-
import { Effect
|
|
50
|
+
import { Effect } from "effect";
|
|
376
51
|
function selectorToCss(sel) {
|
|
377
52
|
if (typeof sel === "string") return sel;
|
|
378
53
|
if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
|
|
@@ -388,7 +63,7 @@ function createPromiseExpect(driver, config, recorder, flowContext, visualRegres
|
|
|
388
63
|
platform: "web"
|
|
389
64
|
};
|
|
390
65
|
const coord = createCoordinator(driver, config);
|
|
391
|
-
const run = (effect) =>
|
|
66
|
+
const run = (effect) => Effect.runPromise(effect);
|
|
392
67
|
const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
|
|
393
68
|
return (selector) => ({
|
|
394
69
|
toBeVisible: (opts) => runStep(
|
|
@@ -478,7 +153,7 @@ function createPromiseExpect(driver, config, recorder, flowContext, visualRegres
|
|
|
478
153
|
}
|
|
479
154
|
|
|
480
155
|
// src/core/session-manager.ts
|
|
481
|
-
import { Effect as
|
|
156
|
+
import { Effect as Effect2 } from "effect";
|
|
482
157
|
function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
483
158
|
const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
|
|
484
159
|
return {
|
|
@@ -489,7 +164,7 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
489
164
|
}
|
|
490
165
|
const driver = await driverFactory(opts);
|
|
491
166
|
const baseUrl = opts.baseUrl ?? "http://localhost:3000";
|
|
492
|
-
await
|
|
167
|
+
await Effect2.runPromise(driver.launchApp(baseUrl));
|
|
493
168
|
const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
|
|
494
169
|
platform: "web"
|
|
495
170
|
});
|
|
@@ -500,12 +175,12 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
500
175
|
app,
|
|
501
176
|
expect,
|
|
502
177
|
async disconnect() {
|
|
503
|
-
await
|
|
178
|
+
await Effect2.runPromise(driver.killApp(baseUrl));
|
|
504
179
|
manager.remove(opts.name);
|
|
505
180
|
}
|
|
506
181
|
};
|
|
507
182
|
const cleanup = async () => {
|
|
508
|
-
await
|
|
183
|
+
await Effect2.runPromise(driver.killApp(baseUrl));
|
|
509
184
|
};
|
|
510
185
|
manager.register(session, cleanup);
|
|
511
186
|
return session;
|
|
@@ -543,7 +218,165 @@ var SessionManager = class {
|
|
|
543
218
|
};
|
|
544
219
|
|
|
545
220
|
// src/drivers/cdp-browser.ts
|
|
546
|
-
import {
|
|
221
|
+
import { spawn } from "child_process";
|
|
222
|
+
import { createHash } from "crypto";
|
|
223
|
+
import { existsSync, mkdtempSync, rmSync } from "fs";
|
|
224
|
+
import { copyFile, readFile, writeFile } from "fs/promises";
|
|
225
|
+
import { tmpdir } from "os";
|
|
226
|
+
import { join } from "path";
|
|
227
|
+
import { Effect as Effect3 } from "effect";
|
|
228
|
+
var INSTANT_ANIMATIONS_CDP_SCRIPT = `
|
|
229
|
+
(() => {
|
|
230
|
+
const inject = () => {
|
|
231
|
+
if (document.getElementById("__spana_instant_anim")) return;
|
|
232
|
+
const style = document.createElement("style");
|
|
233
|
+
style.id = "__spana_instant_anim";
|
|
234
|
+
style.textContent = "*, *::before, *::after { transition-duration: 0.001ms !important; transition-delay: 0ms !important; animation-duration: 0.001ms !important; animation-delay: 0ms !important; scroll-behavior: auto !important; }";
|
|
235
|
+
(document.head || document.documentElement).appendChild(style);
|
|
236
|
+
};
|
|
237
|
+
if (document.readyState === "loading") {
|
|
238
|
+
document.addEventListener("DOMContentLoaded", inject, { once: true });
|
|
239
|
+
} else {
|
|
240
|
+
inject();
|
|
241
|
+
}
|
|
242
|
+
})();
|
|
243
|
+
`;
|
|
244
|
+
function resolveDirectCdpScopeKey(scope) {
|
|
245
|
+
if (scope && scope.trim().length > 0) return scope.trim();
|
|
246
|
+
const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
|
|
247
|
+
return `cdp-${cwdHash}`;
|
|
248
|
+
}
|
|
249
|
+
function resolveChromiumExecutable(explicit) {
|
|
250
|
+
if (explicit && existsSync(explicit)) return explicit;
|
|
251
|
+
const candidates = process.platform === "darwin" ? [
|
|
252
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
253
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
254
|
+
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
|
|
255
|
+
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
|
|
256
|
+
] : process.platform === "linux" ? [
|
|
257
|
+
"/usr/bin/google-chrome",
|
|
258
|
+
"/usr/bin/google-chrome-stable",
|
|
259
|
+
"/usr/bin/chromium",
|
|
260
|
+
"/usr/bin/chromium-browser"
|
|
261
|
+
] : [
|
|
262
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
263
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
|
|
264
|
+
];
|
|
265
|
+
for (const path of candidates) {
|
|
266
|
+
if (existsSync(path)) return path;
|
|
267
|
+
}
|
|
268
|
+
return explicit ?? "google-chrome";
|
|
269
|
+
}
|
|
270
|
+
async function fetchBrowserWsUrl(httpEndpoint, timeoutMs = 1e4) {
|
|
271
|
+
const deadline = Date.now() + timeoutMs;
|
|
272
|
+
while (Date.now() < deadline) {
|
|
273
|
+
try {
|
|
274
|
+
const res = await fetch(`${httpEndpoint}/json/version`, {
|
|
275
|
+
signal: AbortSignal.timeout(500)
|
|
276
|
+
});
|
|
277
|
+
if (res.ok) {
|
|
278
|
+
const data = await res.json();
|
|
279
|
+
if (data.webSocketDebuggerUrl) return data.webSocketDebuggerUrl;
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
}
|
|
283
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
284
|
+
}
|
|
285
|
+
throw new Error(`Direct CDP browser did not expose /json/version on ${httpEndpoint}`);
|
|
286
|
+
}
|
|
287
|
+
async function launchDirectCdpBrowser(options = {}) {
|
|
288
|
+
const daemonKey = resolveDirectCdpScopeKey(options.warmBrowserScope);
|
|
289
|
+
if (options.warmBrowser) {
|
|
290
|
+
const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
|
|
291
|
+
statusPath: "/json/version"
|
|
292
|
+
});
|
|
293
|
+
if (existing) {
|
|
294
|
+
const httpEndpoint2 = `http://${existing.host}:${existing.port}`;
|
|
295
|
+
try {
|
|
296
|
+
const browserWsUrl2 = await fetchBrowserWsUrl(httpEndpoint2, 1500);
|
|
297
|
+
return {
|
|
298
|
+
httpEndpoint: httpEndpoint2,
|
|
299
|
+
browserWsUrl: browserWsUrl2,
|
|
300
|
+
reused: true,
|
|
301
|
+
pid: existing.pid,
|
|
302
|
+
close: async () => {
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
} catch {
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
let execPath = options.executablePath;
|
|
310
|
+
if (!execPath) {
|
|
311
|
+
try {
|
|
312
|
+
const { chromium } = await import("playwright-core");
|
|
313
|
+
const pwPath = chromium.executablePath();
|
|
314
|
+
if (pwPath && existsSync(pwPath)) {
|
|
315
|
+
execPath = pwPath;
|
|
316
|
+
}
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
execPath = resolveChromiumExecutable(execPath);
|
|
321
|
+
const port = allocatePort(9350);
|
|
322
|
+
const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
|
|
323
|
+
const chromeArgs = [
|
|
324
|
+
...options.headless !== false ? ["--headless=new"] : [],
|
|
325
|
+
`--remote-debugging-port=${port}`,
|
|
326
|
+
"--remote-debugging-address=127.0.0.1",
|
|
327
|
+
`--user-data-dir=${userDataDir}`,
|
|
328
|
+
"--no-first-run",
|
|
329
|
+
"--no-default-browser-check",
|
|
330
|
+
"--disable-background-networking",
|
|
331
|
+
"--disable-background-timer-throttling",
|
|
332
|
+
"--disable-backgrounding-occluded-windows",
|
|
333
|
+
"--disable-renderer-backgrounding",
|
|
334
|
+
"--disable-ipc-flooding-protection",
|
|
335
|
+
"--disable-hang-monitor",
|
|
336
|
+
"--disable-default-apps",
|
|
337
|
+
"--disable-extensions",
|
|
338
|
+
"--disable-sync",
|
|
339
|
+
...options.headless !== false ? ["--disable-gpu"] : [],
|
|
340
|
+
"--metrics-recording-only",
|
|
341
|
+
"--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
342
|
+
...options.args ?? [],
|
|
343
|
+
"about:blank"
|
|
344
|
+
];
|
|
345
|
+
const child = spawn(execPath, chromeArgs, {
|
|
346
|
+
detached: Boolean(options.warmBrowser),
|
|
347
|
+
stdio: "ignore"
|
|
348
|
+
});
|
|
349
|
+
if (options.warmBrowser) {
|
|
350
|
+
child.unref();
|
|
351
|
+
}
|
|
352
|
+
const httpEndpoint = `http://127.0.0.1:${port}`;
|
|
353
|
+
const browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
|
|
354
|
+
if (options.warmBrowser) {
|
|
355
|
+
registerWarmDaemon({
|
|
356
|
+
kind: "chromium",
|
|
357
|
+
deviceId: daemonKey,
|
|
358
|
+
host: "127.0.0.1",
|
|
359
|
+
port,
|
|
360
|
+
pid: child.pid,
|
|
361
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
httpEndpoint,
|
|
366
|
+
browserWsUrl,
|
|
367
|
+
reused: Boolean(options.warmBrowser),
|
|
368
|
+
pid: child.pid,
|
|
369
|
+
close: async () => {
|
|
370
|
+
if (options.warmBrowser) return;
|
|
371
|
+
try {
|
|
372
|
+
child.kill("SIGTERM");
|
|
373
|
+
} catch {
|
|
374
|
+
}
|
|
375
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
376
|
+
rmSync(userDataDir, { recursive: true, force: true });
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
547
380
|
var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
|
|
548
381
|
function walk(el) {
|
|
549
382
|
const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : { x: 0, y: 0, width: 0, height: 0 };
|
|
@@ -564,16 +397,44 @@ var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
|
|
|
564
397
|
}
|
|
565
398
|
return document.body ? JSON.stringify(walk(document.body)) : JSON.stringify({ bounds: { x: 0, y: 0, width: 0, height: 0 }, children: [] });
|
|
566
399
|
})()`;
|
|
400
|
+
function matchUrl(matcher, url) {
|
|
401
|
+
if (matcher instanceof RegExp) return matcher.test(url);
|
|
402
|
+
if (matcher.includes("*")) {
|
|
403
|
+
const escaped = matcher.replaceAll(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("**", ".*").replaceAll("*", "[^/]*");
|
|
404
|
+
return new RegExp(escaped).test(url);
|
|
405
|
+
}
|
|
406
|
+
return url.includes(matcher);
|
|
407
|
+
}
|
|
408
|
+
var RESOURCE_BLOCK_PATTERNS = {
|
|
409
|
+
image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
|
|
410
|
+
font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
|
|
411
|
+
media: ["*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.m4a"],
|
|
412
|
+
stylesheet: ["*.css"]
|
|
413
|
+
};
|
|
567
414
|
function makeLightweightCdpDriver(options) {
|
|
568
|
-
return
|
|
415
|
+
return Effect3.gen(function* () {
|
|
416
|
+
const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
|
|
417
|
+
const useContexts = Boolean(
|
|
418
|
+
options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
|
|
419
|
+
);
|
|
569
420
|
const isWs = options.cdpUrl.startsWith("ws://") || options.cdpUrl.startsWith("wss://");
|
|
421
|
+
const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
|
|
422
|
+
let connectWsUrl = isWs ? options.cdpUrl : void 0;
|
|
423
|
+
if (useContexts && !connectWsUrl) {
|
|
424
|
+
connectWsUrl = yield* Effect3.tryPromise({
|
|
425
|
+
try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
|
|
426
|
+
catch: (e) => new DriverError({
|
|
427
|
+
message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
|
|
428
|
+
})
|
|
429
|
+
});
|
|
430
|
+
}
|
|
570
431
|
const cdpChannel = new CdpDomChannel({
|
|
571
|
-
endpointUrl:
|
|
572
|
-
...
|
|
432
|
+
endpointUrl: httpEndpoint,
|
|
433
|
+
...connectWsUrl ? { webSocketUrl: connectWsUrl } : {},
|
|
573
434
|
fetchFn: options.fetchFn,
|
|
574
435
|
createWebSocket: options.createWebSocket
|
|
575
436
|
});
|
|
576
|
-
yield*
|
|
437
|
+
yield* Effect3.tryPromise({
|
|
577
438
|
try: () => cdpChannel.connect(),
|
|
578
439
|
catch: (e) => new DriverError({
|
|
579
440
|
message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
|
|
@@ -582,41 +443,370 @@ function makeLightweightCdpDriver(options) {
|
|
|
582
443
|
const width = options.viewport?.width ?? 1280;
|
|
583
444
|
const height = options.viewport?.height ?? 720;
|
|
584
445
|
const label = options.engineLabel ?? "cdp";
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
446
|
+
let activeSlot;
|
|
447
|
+
let prefetchedSlotPromise;
|
|
448
|
+
let hasRunFirstFlow = false;
|
|
449
|
+
let activeAuthenticatorId;
|
|
450
|
+
const backgroundDisposals = [];
|
|
451
|
+
const consoleLogs = [];
|
|
452
|
+
const jsErrors = [];
|
|
453
|
+
const routeRules = [];
|
|
454
|
+
let fetchInterceptEnabled = false;
|
|
455
|
+
let nextTabSeq = 1;
|
|
456
|
+
let downloadDir;
|
|
457
|
+
const completedDownloads = [];
|
|
458
|
+
const downloadWaiters = [];
|
|
459
|
+
const pendingDownloadGuids = /* @__PURE__ */ new Map();
|
|
460
|
+
cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
|
|
461
|
+
if (params?.guid && downloadDir) {
|
|
462
|
+
pendingDownloadGuids.set(String(params.guid), join(downloadDir, String(params.guid)));
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
cdpChannel.onEvent("Browser.downloadProgress", (params) => {
|
|
466
|
+
if (params?.state === "completed" && params?.guid) {
|
|
467
|
+
const filePath = pendingDownloadGuids.get(String(params.guid)) ?? (downloadDir ? join(downloadDir, String(params.guid)) : "");
|
|
468
|
+
pendingDownloadGuids.delete(String(params.guid));
|
|
469
|
+
if (!filePath) return;
|
|
470
|
+
const waiter = downloadWaiters.shift();
|
|
471
|
+
if (waiter) waiter.resolve(filePath);
|
|
472
|
+
else completedDownloads.push(filePath);
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
const loadStorageStateFile = async (path) => {
|
|
476
|
+
if (!path) return null;
|
|
477
|
+
try {
|
|
478
|
+
const raw = await readFile(path, "utf8");
|
|
479
|
+
return JSON.parse(raw);
|
|
480
|
+
} catch {
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
const attachVirtualAuthenticatorForSession = async (sessionId, opts) => {
|
|
485
|
+
await cdpChannel.sendCommand("WebAuthn.enable", { enableUI: false }, sessionId);
|
|
486
|
+
const res = await cdpChannel.sendCommand(
|
|
487
|
+
"WebAuthn.addVirtualAuthenticator",
|
|
488
|
+
{
|
|
489
|
+
options: {
|
|
490
|
+
protocol: opts?.protocol ?? "ctap2",
|
|
491
|
+
transport: opts?.transport ?? "internal",
|
|
492
|
+
hasResidentKey: opts?.hasResidentKey ?? true,
|
|
493
|
+
hasUserVerification: opts?.hasUserVerification ?? true,
|
|
494
|
+
isUserVerified: opts?.isUserVerified ?? true,
|
|
495
|
+
automaticPresenceSimulation: opts?.automaticPresenceSimulation ?? true
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
sessionId
|
|
499
|
+
);
|
|
500
|
+
return res?.authenticatorId ?? "cdp-virtual-auth-1";
|
|
501
|
+
};
|
|
502
|
+
const configureSession = async (sessionId, storageStatePath) => {
|
|
503
|
+
const state = await loadStorageStateFile(storageStatePath);
|
|
504
|
+
const needsNetworkDomain = Boolean(
|
|
505
|
+
options.blockResources && options.blockResources.length > 0 || state?.cookies && state.cookies.length > 0
|
|
506
|
+
);
|
|
507
|
+
await Promise.all([
|
|
508
|
+
cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
|
|
509
|
+
}),
|
|
510
|
+
cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
|
|
511
|
+
}),
|
|
512
|
+
cdpChannel.sendCommand(
|
|
513
|
+
"Target.setAutoAttach",
|
|
514
|
+
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
|
|
515
|
+
sessionId
|
|
516
|
+
).catch(() => {
|
|
517
|
+
}),
|
|
518
|
+
...needsNetworkDomain ? [cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
|
|
519
|
+
})] : [],
|
|
520
|
+
cdpChannel.sendCommand(
|
|
521
|
+
"Emulation.setDeviceMetricsOverride",
|
|
522
|
+
{ width, height, deviceScaleFactor: 1, mobile: false },
|
|
523
|
+
sessionId
|
|
524
|
+
).catch(() => {
|
|
525
|
+
})
|
|
526
|
+
]);
|
|
527
|
+
if (options.instantAnimations) {
|
|
528
|
+
await cdpChannel.sendCommand(
|
|
529
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
530
|
+
{ source: INSTANT_ANIMATIONS_CDP_SCRIPT },
|
|
531
|
+
sessionId
|
|
532
|
+
).catch(() => {
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
if (options.blockResources && options.blockResources.length > 0) {
|
|
536
|
+
const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
|
|
537
|
+
if (urls.length > 0) {
|
|
538
|
+
await cdpChannel.sendCommand("Network.setBlockedURLs", { urls }, sessionId).catch(() => {
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (state?.cookies && state.cookies.length > 0) {
|
|
543
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }, sessionId).catch(() => {
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
if (state?.origins && state.origins.length > 0) {
|
|
547
|
+
const originsJson = JSON.stringify(state.origins);
|
|
548
|
+
await cdpChannel.sendCommand(
|
|
549
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
550
|
+
{
|
|
551
|
+
source: `(() => {
|
|
552
|
+
const origins = ${originsJson};
|
|
553
|
+
const hit = origins.find((o) => o.origin === window.location.origin);
|
|
554
|
+
if (hit && Array.isArray(hit.localStorage)) {
|
|
555
|
+
for (const item of hit.localStorage) {
|
|
556
|
+
try { window.localStorage.setItem(item.name, item.value); } catch {}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
})();`
|
|
560
|
+
},
|
|
561
|
+
sessionId
|
|
562
|
+
).catch(() => {
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
if (routeRules.length > 0) {
|
|
566
|
+
await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
let authenticatorId;
|
|
570
|
+
if (options.virtualAuthenticator) {
|
|
571
|
+
const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
|
|
572
|
+
authenticatorId = await attachVirtualAuthenticatorForSession(sessionId, authOpts).catch(
|
|
573
|
+
() => void 0
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
return authenticatorId;
|
|
577
|
+
};
|
|
578
|
+
const createContextSlot = async (storageStatePath) => {
|
|
579
|
+
const ctxRes = await cdpChannel.sendCommand(
|
|
580
|
+
"Target.createBrowserContext",
|
|
581
|
+
{ disposeOnDetach: true },
|
|
582
|
+
null
|
|
583
|
+
);
|
|
584
|
+
const targetRes = await cdpChannel.sendCommand(
|
|
585
|
+
"Target.createTarget",
|
|
586
|
+
{ url: "about:blank", browserContextId: ctxRes.browserContextId, width, height },
|
|
587
|
+
null
|
|
588
|
+
);
|
|
589
|
+
const attachRes = await cdpChannel.sendCommand(
|
|
590
|
+
"Target.attachToTarget",
|
|
591
|
+
{ targetId: targetRes.targetId, flatten: true },
|
|
592
|
+
null
|
|
593
|
+
);
|
|
594
|
+
const authenticatorId = await configureSession(
|
|
595
|
+
attachRes.sessionId,
|
|
596
|
+
storageStatePath ?? options.storageState
|
|
597
|
+
);
|
|
598
|
+
const firstTabId = `tab-${nextTabSeq++}`;
|
|
599
|
+
return {
|
|
600
|
+
browserContextId: ctxRes.browserContextId,
|
|
601
|
+
targetId: targetRes.targetId,
|
|
602
|
+
sessionId: attachRes.sessionId,
|
|
603
|
+
authenticatorId,
|
|
604
|
+
tabs: [{ tabId: firstTabId, targetId: targetRes.targetId, sessionId: attachRes.sessionId }]
|
|
605
|
+
};
|
|
606
|
+
};
|
|
607
|
+
const disposeSlotInBackground = (slot) => {
|
|
608
|
+
const p = new Promise((r) => setTimeout(r, 120)).then(
|
|
609
|
+
() => cdpChannel.sendCommand(
|
|
610
|
+
"Target.disposeBrowserContext",
|
|
611
|
+
{ browserContextId: slot.browserContextId },
|
|
612
|
+
null
|
|
613
|
+
)
|
|
614
|
+
).catch(() => {
|
|
615
|
+
}).finally(() => {
|
|
616
|
+
const idx = backgroundDisposals.indexOf(p);
|
|
617
|
+
if (idx >= 0) backgroundDisposals.splice(idx, 1);
|
|
618
|
+
});
|
|
619
|
+
backgroundDisposals.push(p);
|
|
620
|
+
};
|
|
621
|
+
const schedulePrefetch = () => {
|
|
622
|
+
if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise) return;
|
|
623
|
+
prefetchedSlotPromise = createContextSlot(options.storageState);
|
|
624
|
+
prefetchedSlotPromise.catch(() => {
|
|
625
|
+
prefetchedSlotPromise = void 0;
|
|
626
|
+
});
|
|
627
|
+
};
|
|
628
|
+
cdpChannel.onEvent("Target.attachedToTarget", (params) => {
|
|
629
|
+
const targetInfo = params?.targetInfo;
|
|
630
|
+
const childSid = params?.sessionId;
|
|
631
|
+
if (targetInfo?.type === "iframe" && typeof childSid === "string") {
|
|
632
|
+
cdpChannel.addChildSession(childSid, {
|
|
633
|
+
targetId: typeof targetInfo.targetId === "string" ? targetInfo.targetId : void 0,
|
|
634
|
+
url: typeof targetInfo.url === "string" ? targetInfo.url : void 0
|
|
635
|
+
});
|
|
636
|
+
void cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
cdpChannel.onEvent("Target.detachedFromTarget", (params) => {
|
|
641
|
+
if (typeof params?.sessionId === "string") {
|
|
642
|
+
cdpChannel.removeChildSession(params.sessionId);
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
cdpChannel.setFrameOffsetResolver(async (child) => {
|
|
646
|
+
if (!child.targetId) return { x: 0, y: 0 };
|
|
647
|
+
try {
|
|
648
|
+
await cdpChannel.sendCommand("DOM.enable");
|
|
649
|
+
const owner = await cdpChannel.sendCommand("DOM.getFrameOwner", {
|
|
650
|
+
frameId: child.targetId
|
|
651
|
+
});
|
|
652
|
+
const boxParams = owner.backendNodeId ? { backendNodeId: owner.backendNodeId } : { nodeId: owner.nodeId };
|
|
653
|
+
const box = await cdpChannel.sendCommand("DOM.getBoxModel", boxParams);
|
|
654
|
+
const quad = box?.model?.content ?? box?.model?.border;
|
|
655
|
+
if (Array.isArray(quad) && quad.length >= 2) {
|
|
656
|
+
return { x: quad[0] ?? 0, y: quad[1] ?? 0 };
|
|
657
|
+
}
|
|
658
|
+
} catch {
|
|
659
|
+
}
|
|
660
|
+
return { x: 0, y: 0 };
|
|
661
|
+
});
|
|
662
|
+
cdpChannel.onEvent("Runtime.consoleAPICalled", (params, sid) => {
|
|
663
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
664
|
+
const args = Array.isArray(params?.args) ? params.args.map((a) => a.value ?? a.description ?? "").join(" ") : "";
|
|
665
|
+
consoleLogs.push({ type: String(params?.type ?? "log"), text: args });
|
|
666
|
+
});
|
|
667
|
+
cdpChannel.onEvent("Runtime.exceptionThrown", (params, sid) => {
|
|
668
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
669
|
+
const detail = params?.exceptionDetails;
|
|
670
|
+
jsErrors.push({
|
|
671
|
+
name: detail?.exception?.className ?? "Error",
|
|
672
|
+
message: detail?.exception?.description ?? detail?.text ?? "Uncaught exception"
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
cdpChannel.onEvent("Fetch.requestPaused", (params, sid) => {
|
|
676
|
+
const reqId = params?.requestId;
|
|
677
|
+
const url = String(params?.request?.url ?? "");
|
|
678
|
+
if (!reqId) return;
|
|
679
|
+
const rule = routeRules.find((r) => matchUrl(r.matcher, url));
|
|
680
|
+
if (!rule) {
|
|
681
|
+
void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
|
|
682
|
+
});
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
if (rule.kind === "block") {
|
|
686
|
+
void cdpChannel.sendCommand(
|
|
687
|
+
"Fetch.failRequest",
|
|
688
|
+
{ requestId: reqId, errorReason: "BlockedByClient" },
|
|
689
|
+
sid ?? null
|
|
690
|
+
).catch(() => {
|
|
691
|
+
});
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const resp = rule.response ?? {};
|
|
695
|
+
const bodyStr = resp.json !== void 0 ? JSON.stringify(resp.json) : resp.body ?? "";
|
|
696
|
+
const headersObj = { ...resp.headers };
|
|
697
|
+
if (resp.contentType && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
698
|
+
headersObj["content-type"] = resp.contentType;
|
|
699
|
+
} else if (resp.json !== void 0 && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
|
|
700
|
+
headersObj["content-type"] = "application/json";
|
|
701
|
+
}
|
|
702
|
+
const responseHeaders = Object.entries(headersObj).map(([name, value]) => ({ name, value }));
|
|
703
|
+
void cdpChannel.sendCommand(
|
|
704
|
+
"Fetch.fulfillRequest",
|
|
705
|
+
{
|
|
706
|
+
requestId: reqId,
|
|
707
|
+
responseCode: resp.status ?? 200,
|
|
708
|
+
responseHeaders,
|
|
709
|
+
body: Buffer.from(bodyStr, "utf8").toString("base64")
|
|
710
|
+
},
|
|
711
|
+
sid ?? null
|
|
712
|
+
).catch(() => {
|
|
713
|
+
});
|
|
714
|
+
});
|
|
715
|
+
if (useContexts) {
|
|
716
|
+
activeSlot = yield* Effect3.tryPromise({
|
|
717
|
+
try: () => createContextSlot(options.storageState),
|
|
718
|
+
catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
|
|
588
719
|
});
|
|
720
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
721
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
722
|
+
}
|
|
723
|
+
const resolveUrl = (rawUrl) => rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" ? rawUrl : options.baseUrl ? `${options.baseUrl.replace(/\/$/, "")}/${rawUrl.replace(/^\//, "")}` : rawUrl;
|
|
724
|
+
const navigate = async (rawUrl) => {
|
|
725
|
+
const target = resolveUrl(rawUrl);
|
|
726
|
+
if (!useContexts) {
|
|
727
|
+
await cdpChannel.sendCommand("Page.enable").catch(() => {
|
|
728
|
+
});
|
|
729
|
+
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
const waitUntil = options.waitUntil ?? "load";
|
|
733
|
+
const targetSid = activeSlot?.sessionId;
|
|
734
|
+
if (waitUntil === "commit" || target === "about:blank") {
|
|
735
|
+
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
|
|
739
|
+
const waiter = cdpChannel.waitForEvent(
|
|
740
|
+
eventName,
|
|
741
|
+
15e3,
|
|
742
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
743
|
+
);
|
|
589
744
|
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
745
|
+
await waiter.catch(() => {
|
|
746
|
+
});
|
|
747
|
+
schedulePrefetch();
|
|
748
|
+
};
|
|
749
|
+
const ensureFetchIntercept = async () => {
|
|
750
|
+
if (fetchInterceptEnabled) return;
|
|
751
|
+
fetchInterceptEnabled = true;
|
|
752
|
+
await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
|
|
590
753
|
};
|
|
591
754
|
const service = {
|
|
592
755
|
domChannel: cdpChannel,
|
|
593
|
-
|
|
756
|
+
beginFlow: (_flowName) => Effect3.tryPromise({
|
|
757
|
+
try: async () => {
|
|
758
|
+
consoleLogs.length = 0;
|
|
759
|
+
jsErrors.length = 0;
|
|
760
|
+
cdpChannel.clearChildSessions();
|
|
761
|
+
if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
|
|
762
|
+
const previousSlot = activeSlot;
|
|
763
|
+
const pending = prefetchedSlotPromise;
|
|
764
|
+
prefetchedSlotPromise = void 0;
|
|
765
|
+
activeSlot = pending ? await pending : await createContextSlot(options.storageState);
|
|
766
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
767
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
768
|
+
if (previousSlot) {
|
|
769
|
+
disposeSlotInBackground(previousSlot);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
hasRunFirstFlow = true;
|
|
773
|
+
},
|
|
774
|
+
catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
|
|
775
|
+
}),
|
|
776
|
+
dumpHierarchy: () => Effect3.tryPromise({
|
|
594
777
|
try: async () => {
|
|
595
778
|
const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
|
|
596
779
|
return raw ?? "{}";
|
|
597
780
|
},
|
|
598
781
|
catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
|
|
599
782
|
}),
|
|
600
|
-
tapAtCoordinate: (x, y) =>
|
|
783
|
+
tapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
601
784
|
try: async () => {
|
|
602
|
-
await
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
785
|
+
await Promise.all([
|
|
786
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
787
|
+
type: "mouseMoved",
|
|
788
|
+
x,
|
|
789
|
+
y
|
|
790
|
+
}),
|
|
791
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
792
|
+
type: "mousePressed",
|
|
793
|
+
x,
|
|
794
|
+
y,
|
|
795
|
+
button: "left",
|
|
796
|
+
clickCount: 1
|
|
797
|
+
}),
|
|
798
|
+
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
799
|
+
type: "mouseReleased",
|
|
800
|
+
x,
|
|
801
|
+
y,
|
|
802
|
+
button: "left",
|
|
803
|
+
clickCount: 1
|
|
804
|
+
})
|
|
805
|
+
]);
|
|
616
806
|
},
|
|
617
807
|
catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
|
|
618
808
|
}),
|
|
619
|
-
doubleTapAtCoordinate: (x, y) =>
|
|
809
|
+
doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
|
|
620
810
|
try: async () => {
|
|
621
811
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
622
812
|
type: "mousePressed",
|
|
@@ -635,7 +825,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
635
825
|
},
|
|
636
826
|
catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
|
|
637
827
|
}),
|
|
638
|
-
longPressAtCoordinate: (x, y, duration) =>
|
|
828
|
+
longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
|
|
639
829
|
try: async () => {
|
|
640
830
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
641
831
|
type: "mousePressed",
|
|
@@ -655,7 +845,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
655
845
|
},
|
|
656
846
|
catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
|
|
657
847
|
}),
|
|
658
|
-
swipe: (startX, startY, endX, endY) =>
|
|
848
|
+
swipe: (startX, startY, endX, endY) => Effect3.tryPromise({
|
|
659
849
|
try: async () => {
|
|
660
850
|
const dx = startX - endX;
|
|
661
851
|
const dy = startY - endY;
|
|
@@ -663,92 +853,401 @@ function makeLightweightCdpDriver(options) {
|
|
|
663
853
|
},
|
|
664
854
|
catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
|
|
665
855
|
}),
|
|
666
|
-
inputText: (text) =>
|
|
856
|
+
inputText: (text) => Effect3.tryPromise({
|
|
857
|
+
try: async () => {
|
|
858
|
+
await cdpChannel.sendCommand("Input.insertText", { text });
|
|
859
|
+
},
|
|
860
|
+
catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
|
|
861
|
+
}),
|
|
862
|
+
pressKey: (key) => Effect3.tryPromise({
|
|
863
|
+
try: async () => {
|
|
864
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
|
|
865
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
|
|
866
|
+
},
|
|
867
|
+
catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
|
|
868
|
+
}),
|
|
869
|
+
hideKeyboard: () => Effect3.void,
|
|
870
|
+
takeScreenshot: () => Effect3.tryPromise({
|
|
871
|
+
try: async () => {
|
|
872
|
+
const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
|
|
873
|
+
format: "png"
|
|
874
|
+
});
|
|
875
|
+
return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
|
|
876
|
+
},
|
|
877
|
+
catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
|
|
878
|
+
}),
|
|
879
|
+
getDeviceInfo: () => Effect3.succeed({
|
|
880
|
+
platform: "web",
|
|
881
|
+
deviceId: `${label}:${options.cdpUrl}`,
|
|
882
|
+
name: `${label} (CDP-direct)`,
|
|
883
|
+
isEmulator: true,
|
|
884
|
+
screenWidth: width,
|
|
885
|
+
screenHeight: height,
|
|
886
|
+
driverType: "cdp"
|
|
887
|
+
}),
|
|
888
|
+
launchApp: (url, opts) => Effect3.tryPromise({
|
|
889
|
+
try: async () => {
|
|
890
|
+
if (opts?.clearState) {
|
|
891
|
+
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
892
|
+
});
|
|
893
|
+
await cdpChannel.evaluate(
|
|
894
|
+
"try { localStorage.clear(); sessionStorage.clear(); } catch {}"
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
await navigate(opts?.deepLink || url || options.baseUrl || "about:blank");
|
|
898
|
+
},
|
|
899
|
+
catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
|
|
900
|
+
}),
|
|
901
|
+
stopApp: () => Effect3.tryPromise({
|
|
902
|
+
try: () => navigate("about:blank"),
|
|
903
|
+
catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
|
|
904
|
+
}),
|
|
905
|
+
killApp: () => Effect3.tryPromise({
|
|
906
|
+
try: async () => {
|
|
907
|
+
const pendingPrefetch = prefetchedSlotPromise;
|
|
908
|
+
prefetchedSlotPromise = void 0;
|
|
909
|
+
if (useContexts) {
|
|
910
|
+
const slotsToDispose = [];
|
|
911
|
+
if (activeSlot) slotsToDispose.push(activeSlot);
|
|
912
|
+
if (pendingPrefetch) {
|
|
913
|
+
const prefetched = await pendingPrefetch.catch(() => void 0);
|
|
914
|
+
if (prefetched) slotsToDispose.push(prefetched);
|
|
915
|
+
}
|
|
916
|
+
await Promise.allSettled([
|
|
917
|
+
...slotsToDispose.map(
|
|
918
|
+
(s) => cdpChannel.sendCommand(
|
|
919
|
+
"Target.disposeBrowserContext",
|
|
920
|
+
{ browserContextId: s.browserContextId },
|
|
921
|
+
null
|
|
922
|
+
)
|
|
923
|
+
),
|
|
924
|
+
...backgroundDisposals
|
|
925
|
+
]);
|
|
926
|
+
}
|
|
927
|
+
if (downloadDir) {
|
|
928
|
+
try {
|
|
929
|
+
rmSync(downloadDir, { recursive: true, force: true });
|
|
930
|
+
} catch {
|
|
931
|
+
}
|
|
932
|
+
downloadDir = void 0;
|
|
933
|
+
}
|
|
934
|
+
await cdpChannel.disconnect();
|
|
935
|
+
},
|
|
936
|
+
catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
|
|
937
|
+
}),
|
|
938
|
+
clearAppState: () => Effect3.tryPromise({
|
|
939
|
+
try: async () => {
|
|
940
|
+
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
941
|
+
});
|
|
942
|
+
await cdpChannel.evaluate(
|
|
943
|
+
"try { localStorage.clear(); sessionStorage.clear(); } catch {}"
|
|
944
|
+
);
|
|
945
|
+
},
|
|
946
|
+
catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
|
|
947
|
+
}),
|
|
948
|
+
openLink: (url) => Effect3.tryPromise({
|
|
949
|
+
try: () => navigate(url),
|
|
950
|
+
catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
|
|
951
|
+
}),
|
|
952
|
+
back: () => Effect3.tryPromise({
|
|
953
|
+
try: async () => {
|
|
954
|
+
await cdpChannel.evaluate("window.history.back()");
|
|
955
|
+
},
|
|
956
|
+
catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
|
|
957
|
+
}),
|
|
958
|
+
evaluate: (fn, ...args) => Effect3.tryPromise({
|
|
959
|
+
try: async () => {
|
|
960
|
+
if (typeof fn === "string") {
|
|
961
|
+
return await cdpChannel.evaluate(fn);
|
|
962
|
+
}
|
|
963
|
+
const serializedArgs = args.map((a) => JSON.stringify(a)).join(", ");
|
|
964
|
+
return await cdpChannel.evaluate(`(${fn.toString()})(${serializedArgs})`);
|
|
965
|
+
},
|
|
966
|
+
catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
|
|
967
|
+
}),
|
|
968
|
+
getRawPage: () => ({
|
|
969
|
+
kind: "cdp",
|
|
970
|
+
cdpChannel,
|
|
971
|
+
sessionId: activeSlot?.sessionId ?? null,
|
|
972
|
+
browserContextId: activeSlot?.browserContextId ?? null
|
|
973
|
+
}),
|
|
974
|
+
mockNetwork: (matcher, response) => Effect3.tryPromise({
|
|
975
|
+
try: async () => {
|
|
976
|
+
routeRules.push({ kind: "mock", matcher, response });
|
|
977
|
+
await ensureFetchIntercept();
|
|
978
|
+
},
|
|
979
|
+
catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
|
|
980
|
+
}),
|
|
981
|
+
blockNetwork: (matcher) => Effect3.tryPromise({
|
|
982
|
+
try: async () => {
|
|
983
|
+
routeRules.push({ kind: "block", matcher });
|
|
984
|
+
await ensureFetchIntercept();
|
|
985
|
+
},
|
|
986
|
+
catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
|
|
987
|
+
}),
|
|
988
|
+
clearNetworkMocks: () => Effect3.tryPromise({
|
|
989
|
+
try: async () => {
|
|
990
|
+
routeRules.length = 0;
|
|
991
|
+
if (fetchInterceptEnabled) {
|
|
992
|
+
fetchInterceptEnabled = false;
|
|
993
|
+
await cdpChannel.sendCommand("Fetch.disable").catch(() => {
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
},
|
|
997
|
+
catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
|
|
998
|
+
}),
|
|
999
|
+
saveCookies: (path) => Effect3.tryPromise({
|
|
1000
|
+
try: async () => {
|
|
1001
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
1002
|
+
await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
|
|
1003
|
+
},
|
|
1004
|
+
catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
|
|
1005
|
+
}),
|
|
1006
|
+
loadCookies: (path) => Effect3.tryPromise({
|
|
1007
|
+
try: async () => {
|
|
1008
|
+
const cookies = JSON.parse(await readFile(path, "utf8"));
|
|
1009
|
+
if (Array.isArray(cookies)) {
|
|
1010
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies });
|
|
1011
|
+
}
|
|
1012
|
+
},
|
|
1013
|
+
catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
|
|
1014
|
+
}),
|
|
1015
|
+
saveAuthState: (path) => Effect3.tryPromise({
|
|
1016
|
+
try: async () => {
|
|
1017
|
+
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
1018
|
+
const originState = await cdpChannel.evaluate(
|
|
1019
|
+
`(() => {
|
|
1020
|
+
const entries = [];
|
|
1021
|
+
try {
|
|
1022
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
1023
|
+
const k = localStorage.key(i);
|
|
1024
|
+
if (k !== null) entries.push({ name: k, value: localStorage.getItem(k) ?? "" });
|
|
1025
|
+
}
|
|
1026
|
+
} catch {}
|
|
1027
|
+
return { origin: window.location.origin, localStorage: entries };
|
|
1028
|
+
})()`
|
|
1029
|
+
).catch(() => null);
|
|
1030
|
+
const payload = {
|
|
1031
|
+
cookies: res?.cookies ?? [],
|
|
1032
|
+
origins: originState && originState.origin !== "null" ? [originState] : []
|
|
1033
|
+
};
|
|
1034
|
+
await writeFile(path, JSON.stringify(payload, null, 2), "utf8");
|
|
1035
|
+
},
|
|
1036
|
+
catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
|
|
1037
|
+
}),
|
|
1038
|
+
loadAuthState: (path) => Effect3.tryPromise({
|
|
1039
|
+
try: async () => {
|
|
1040
|
+
if (useContexts) {
|
|
1041
|
+
const previousSlot = activeSlot;
|
|
1042
|
+
activeSlot = await createContextSlot(path);
|
|
1043
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
1044
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
1045
|
+
if (previousSlot) disposeSlotInBackground(previousSlot);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
const state = await loadStorageStateFile(path);
|
|
1049
|
+
if (state?.cookies?.length) {
|
|
1050
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies });
|
|
1051
|
+
}
|
|
1052
|
+
},
|
|
1053
|
+
catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
|
|
1054
|
+
}),
|
|
1055
|
+
enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
|
|
1056
|
+
try: async () => {
|
|
1057
|
+
activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1058
|
+
activeSlot?.sessionId ?? null,
|
|
1059
|
+
opts
|
|
1060
|
+
);
|
|
1061
|
+
return activeAuthenticatorId;
|
|
1062
|
+
},
|
|
1063
|
+
catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
|
|
1064
|
+
}),
|
|
1065
|
+
removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
|
|
1066
|
+
try: async () => {
|
|
1067
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1068
|
+
if (!id) return;
|
|
1069
|
+
await cdpChannel.sendCommand("WebAuthn.removeVirtualAuthenticator", {
|
|
1070
|
+
authenticatorId: id
|
|
1071
|
+
});
|
|
1072
|
+
if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
|
|
1073
|
+
},
|
|
1074
|
+
catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
|
|
1075
|
+
}),
|
|
1076
|
+
getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
667
1077
|
try: async () => {
|
|
668
|
-
|
|
1078
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1079
|
+
if (!id) return [];
|
|
1080
|
+
const res = await cdpChannel.sendCommand("WebAuthn.getCredentials", {
|
|
1081
|
+
authenticatorId: id
|
|
1082
|
+
});
|
|
1083
|
+
return Array.isArray(res?.credentials) ? res.credentials : [];
|
|
669
1084
|
},
|
|
670
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
1085
|
+
catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
|
|
671
1086
|
}),
|
|
672
|
-
|
|
1087
|
+
clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
|
|
673
1088
|
try: async () => {
|
|
674
|
-
|
|
675
|
-
|
|
1089
|
+
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1090
|
+
if (!id) return;
|
|
1091
|
+
await cdpChannel.sendCommand("WebAuthn.clearCredentials", { authenticatorId: id });
|
|
676
1092
|
},
|
|
677
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
1093
|
+
catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
|
|
678
1094
|
}),
|
|
679
|
-
|
|
680
|
-
|
|
1095
|
+
getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
|
|
1096
|
+
getJSErrors: () => Effect3.succeed([...jsErrors]),
|
|
1097
|
+
setNetworkConditions: (conditions) => Effect3.tryPromise({
|
|
681
1098
|
try: async () => {
|
|
682
|
-
const
|
|
683
|
-
|
|
1099
|
+
const resolved = resolveNetworkConditions(conditions);
|
|
1100
|
+
await cdpChannel.sendCommand("Network.enable");
|
|
1101
|
+
await cdpChannel.sendCommand("Network.emulateNetworkConditions", {
|
|
1102
|
+
offline: resolved.offline,
|
|
1103
|
+
latency: resolved.latencyMs,
|
|
1104
|
+
downloadThroughput: resolved.downloadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.downloadThroughputKbps * 1024 / 8), 0),
|
|
1105
|
+
uploadThroughput: resolved.uploadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.uploadThroughputKbps * 1024 / 8), 0)
|
|
684
1106
|
});
|
|
685
|
-
return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
|
|
686
1107
|
},
|
|
687
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
1108
|
+
catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
|
|
688
1109
|
}),
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
1110
|
+
uploadFile: (selector, filePath) => Effect3.tryPromise({
|
|
1111
|
+
try: async () => {
|
|
1112
|
+
const serialized = JSON.stringify(selector);
|
|
1113
|
+
const expr = `(function(sel) {
|
|
1114
|
+
if (typeof sel === "object" && sel !== null && "testID" in sel) {
|
|
1115
|
+
return document.querySelector('[data-testid="' + sel.testID + '"], [testID="' + sel.testID + '"]');
|
|
1116
|
+
}
|
|
1117
|
+
if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
|
|
1118
|
+
return document.querySelector('[aria-label="' + sel.accessibilityLabel + '"]');
|
|
1119
|
+
}
|
|
1120
|
+
return document.querySelector('input[type="file"]');
|
|
1121
|
+
})(${serialized})`;
|
|
1122
|
+
await cdpChannel.sendCommand("DOM.enable");
|
|
1123
|
+
const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
|
|
1124
|
+
expression: expr,
|
|
1125
|
+
returnByValue: false
|
|
1126
|
+
});
|
|
1127
|
+
const objectId = evalRes?.result?.objectId;
|
|
1128
|
+
if (!objectId) {
|
|
1129
|
+
throw new Error(`No matching file input found for selector ${serialized}`);
|
|
1130
|
+
}
|
|
1131
|
+
const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
|
|
1132
|
+
if (!nodeRes?.nodeId) {
|
|
1133
|
+
throw new Error("Failed to resolve DOM nodeId for file input");
|
|
1134
|
+
}
|
|
1135
|
+
await cdpChannel.sendCommand("DOM.setFileInputFiles", {
|
|
1136
|
+
nodeId: nodeRes.nodeId,
|
|
1137
|
+
files: [filePath]
|
|
1138
|
+
});
|
|
1139
|
+
},
|
|
1140
|
+
catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
|
|
697
1141
|
}),
|
|
698
|
-
|
|
1142
|
+
downloadFile: (destPath) => Effect3.tryPromise({
|
|
699
1143
|
try: async () => {
|
|
700
|
-
if (
|
|
701
|
-
|
|
702
|
-
|
|
1144
|
+
if (!downloadDir) {
|
|
1145
|
+
downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
|
|
1146
|
+
await cdpChannel.sendCommand(
|
|
1147
|
+
"Browser.setDownloadBehavior",
|
|
1148
|
+
{
|
|
1149
|
+
behavior: "allowAndName",
|
|
1150
|
+
downloadPath: downloadDir,
|
|
1151
|
+
eventsEnabled: true,
|
|
1152
|
+
...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
|
|
1153
|
+
},
|
|
1154
|
+
null
|
|
703
1155
|
);
|
|
704
1156
|
}
|
|
705
|
-
await
|
|
1157
|
+
const downloaded = completedDownloads.shift() ?? await new Promise((resolve, reject) => {
|
|
1158
|
+
const timer = setTimeout(() => {
|
|
1159
|
+
reject(new Error("Timed out waiting for CDP file download"));
|
|
1160
|
+
}, 15e3);
|
|
1161
|
+
downloadWaiters.push({
|
|
1162
|
+
resolve: (fp) => {
|
|
1163
|
+
clearTimeout(timer);
|
|
1164
|
+
resolve(fp);
|
|
1165
|
+
},
|
|
1166
|
+
reject: (err) => {
|
|
1167
|
+
clearTimeout(timer);
|
|
1168
|
+
reject(err);
|
|
1169
|
+
}
|
|
1170
|
+
});
|
|
1171
|
+
});
|
|
1172
|
+
await copyFile(downloaded, destPath);
|
|
706
1173
|
},
|
|
707
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
708
|
-
}),
|
|
709
|
-
stopApp: () => Effect4.tryPromise({
|
|
710
|
-
try: () => navigate("about:blank"),
|
|
711
|
-
catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
|
|
712
|
-
}),
|
|
713
|
-
killApp: () => Effect4.tryPromise({
|
|
714
|
-
try: () => cdpChannel.disconnect(),
|
|
715
|
-
catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
|
|
1174
|
+
catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
|
|
716
1175
|
}),
|
|
717
|
-
|
|
1176
|
+
newTab: (url) => Effect3.tryPromise({
|
|
718
1177
|
try: async () => {
|
|
719
|
-
|
|
720
|
-
|
|
1178
|
+
if (!activeSlot) {
|
|
1179
|
+
throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
|
|
1180
|
+
}
|
|
1181
|
+
const targetRes = await cdpChannel.sendCommand(
|
|
1182
|
+
"Target.createTarget",
|
|
1183
|
+
{
|
|
1184
|
+
url: url ? resolveUrl(url) : "about:blank",
|
|
1185
|
+
browserContextId: activeSlot.browserContextId,
|
|
1186
|
+
width,
|
|
1187
|
+
height
|
|
1188
|
+
},
|
|
1189
|
+
null
|
|
1190
|
+
);
|
|
1191
|
+
const attachRes = await cdpChannel.sendCommand(
|
|
1192
|
+
"Target.attachToTarget",
|
|
1193
|
+
{ targetId: targetRes.targetId, flatten: true },
|
|
1194
|
+
null
|
|
721
1195
|
);
|
|
1196
|
+
await configureSession(attachRes.sessionId, options.storageState);
|
|
1197
|
+
const tabId = `tab-${nextTabSeq++}`;
|
|
1198
|
+
activeSlot.tabs.push({
|
|
1199
|
+
tabId,
|
|
1200
|
+
targetId: targetRes.targetId,
|
|
1201
|
+
sessionId: attachRes.sessionId
|
|
1202
|
+
});
|
|
1203
|
+
activeSlot.targetId = targetRes.targetId;
|
|
1204
|
+
activeSlot.sessionId = attachRes.sessionId;
|
|
1205
|
+
cdpChannel.setSessionId(attachRes.sessionId);
|
|
1206
|
+
return tabId;
|
|
722
1207
|
},
|
|
723
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
724
|
-
}),
|
|
725
|
-
openLink: (url) => Effect4.tryPromise({
|
|
726
|
-
try: () => navigate(url),
|
|
727
|
-
catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
|
|
1208
|
+
catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
|
|
728
1209
|
}),
|
|
729
|
-
|
|
1210
|
+
switchToTab: (index) => Effect3.tryPromise({
|
|
730
1211
|
try: async () => {
|
|
731
|
-
|
|
1212
|
+
if (!activeSlot || !activeSlot.tabs[index]) {
|
|
1213
|
+
throw new Error(`Tab index ${index} is out of range.`);
|
|
1214
|
+
}
|
|
1215
|
+
const target = activeSlot.tabs[index];
|
|
1216
|
+
activeSlot.targetId = target.targetId;
|
|
1217
|
+
activeSlot.sessionId = target.sessionId;
|
|
1218
|
+
cdpChannel.setSessionId(target.sessionId);
|
|
1219
|
+
await cdpChannel.sendCommand("Target.activateTarget", { targetId: target.targetId }, null).catch(() => {
|
|
1220
|
+
});
|
|
732
1221
|
},
|
|
733
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
1222
|
+
catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
|
|
734
1223
|
}),
|
|
735
|
-
|
|
1224
|
+
closeTab: () => Effect3.tryPromise({
|
|
736
1225
|
try: async () => {
|
|
737
|
-
if (
|
|
738
|
-
|
|
1226
|
+
if (!activeSlot) return;
|
|
1227
|
+
if (activeSlot.tabs.length <= 1) {
|
|
1228
|
+
await navigate("about:blank");
|
|
1229
|
+
return;
|
|
739
1230
|
}
|
|
740
|
-
const
|
|
741
|
-
|
|
1231
|
+
const idx = activeSlot.tabs.findIndex((t) => t.sessionId === activeSlot.sessionId);
|
|
1232
|
+
const closing = activeSlot.tabs[idx >= 0 ? idx : activeSlot.tabs.length - 1];
|
|
1233
|
+
activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== closing.sessionId);
|
|
1234
|
+
const fallback = activeSlot.tabs[Math.max(0, Math.min(idx - 1, activeSlot.tabs.length - 1))];
|
|
1235
|
+
activeSlot.targetId = fallback.targetId;
|
|
1236
|
+
activeSlot.sessionId = fallback.sessionId;
|
|
1237
|
+
cdpChannel.setSessionId(fallback.sessionId);
|
|
1238
|
+
await cdpChannel.sendCommand("Target.closeTarget", { targetId: closing.targetId }, null).catch(() => {
|
|
1239
|
+
});
|
|
742
1240
|
},
|
|
743
|
-
catch: (e) => new DriverError({ message: `CDP
|
|
744
|
-
})
|
|
1241
|
+
catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
|
|
1242
|
+
}),
|
|
1243
|
+
getTabIds: () => Effect3.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
|
|
745
1244
|
};
|
|
746
1245
|
return service;
|
|
747
1246
|
});
|
|
748
1247
|
}
|
|
749
1248
|
|
|
750
1249
|
// src/runtime/local.ts
|
|
751
|
-
import { Effect as
|
|
1250
|
+
import { Effect as Effect4 } from "effect";
|
|
752
1251
|
async function safeCleanup(...fns) {
|
|
753
1252
|
for (const fn of fns) {
|
|
754
1253
|
try {
|
|
@@ -802,16 +1301,55 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
|
|
|
802
1301
|
visualRegression: config.visualRegression
|
|
803
1302
|
};
|
|
804
1303
|
}
|
|
1304
|
+
function resolveWebEngine(config) {
|
|
1305
|
+
const webExecution = config.execution?.web;
|
|
1306
|
+
const requested = webExecution?.engine;
|
|
1307
|
+
if (requested === "cdp" || requested === "lightpanda" || requested === "playwright") {
|
|
1308
|
+
return requested;
|
|
1309
|
+
}
|
|
1310
|
+
if (requested === "auto") {
|
|
1311
|
+
const isChromium = (webExecution?.browser ?? "chromium") === "chromium";
|
|
1312
|
+
const needsPlaywrightOnly = Boolean(
|
|
1313
|
+
webExecution?.wsEndpoint || webExecution?.channel || config.artifacts?.har
|
|
1314
|
+
);
|
|
1315
|
+
return isChromium && !needsPlaywrightOnly ? "cdp" : "playwright";
|
|
1316
|
+
}
|
|
1317
|
+
return "playwright";
|
|
1318
|
+
}
|
|
805
1319
|
function speculativelyPrelaunchWebBrowser(config) {
|
|
806
1320
|
const webExecution = config.execution?.web;
|
|
807
|
-
|
|
1321
|
+
const engine = resolveWebEngine(config);
|
|
1322
|
+
if (engine === "lightpanda") {
|
|
808
1323
|
return void 0;
|
|
809
1324
|
}
|
|
1325
|
+
if (engine === "cdp") {
|
|
1326
|
+
if (webExecution?.cdpUrl) return void 0;
|
|
1327
|
+
const useWarm2 = webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
|
|
1328
|
+
const cdpBrowserPromise = launchDirectCdpBrowser({
|
|
1329
|
+
executablePath: webExecution?.executablePath,
|
|
1330
|
+
headless: webExecution?.headless ?? true,
|
|
1331
|
+
warmBrowser: useWarm2,
|
|
1332
|
+
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
1333
|
+
});
|
|
1334
|
+
cdpBrowserPromise.catch(() => {
|
|
1335
|
+
});
|
|
1336
|
+
return {
|
|
1337
|
+
browserPromise: Promise.resolve(void 0),
|
|
1338
|
+
ownsBrowser: false,
|
|
1339
|
+
cdpBrowserPromise
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
810
1342
|
const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
|
|
811
|
-
const ownsBrowser = !useWarm && !webExecution?.cdpUrl;
|
|
812
|
-
const browserPromise = webExecution?.
|
|
1343
|
+
const ownsBrowser = !useWarm && !webExecution?.cdpUrl && !webExecution?.wsEndpoint;
|
|
1344
|
+
const browserPromise = webExecution?.wsEndpoint ? connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser) : webExecution?.cdpUrl ? connectPlaywrightOverCDP(webExecution.cdpUrl) : useWarm ? ensureWarmBrowserDaemon({
|
|
1345
|
+
headless: webExecution?.headless ?? true,
|
|
1346
|
+
executablePath: webExecution?.executablePath,
|
|
1347
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1348
|
+
}).then((r) => r.browser) : launchPlaywrightBrowser({
|
|
813
1349
|
browser: webExecution?.browser,
|
|
814
|
-
headless: webExecution?.headless ?? true
|
|
1350
|
+
headless: webExecution?.headless ?? true,
|
|
1351
|
+
executablePath: webExecution?.executablePath,
|
|
1352
|
+
channel: webExecution?.channel
|
|
815
1353
|
});
|
|
816
1354
|
browserPromise.catch(() => {
|
|
817
1355
|
});
|
|
@@ -821,37 +1359,69 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
821
1359
|
const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
|
|
822
1360
|
const webExecution = config.execution?.web;
|
|
823
1361
|
const bridge = await maybeStartBridge(config.apps?.web?.bridge, config.execution?.bridge);
|
|
824
|
-
const prelaunchedBrowser = prelaunched ? await prelaunched.browserPromise : void 0;
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
1362
|
+
const prelaunchedBrowser = prelaunched && !prelaunched.cdpBrowserPromise ? await prelaunched.browserPromise : void 0;
|
|
1363
|
+
let launchedDirectCdp;
|
|
1364
|
+
let rawDriver;
|
|
1365
|
+
const engine = resolveWebEngine(config);
|
|
1366
|
+
if (engine === "cdp" || engine === "lightpanda") {
|
|
1367
|
+
let targetCdpUrl = webExecution?.cdpUrl;
|
|
1368
|
+
const useContexts = engine === "cdp";
|
|
1369
|
+
if (!targetCdpUrl && engine === "cdp") {
|
|
1370
|
+
launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
|
|
1371
|
+
executablePath: webExecution?.executablePath,
|
|
1372
|
+
headless: webExecution?.headless ?? true,
|
|
1373
|
+
warmBrowser: webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
|
|
1374
|
+
warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
|
|
1375
|
+
});
|
|
1376
|
+
targetCdpUrl = launchedDirectCdp.browserWsUrl;
|
|
1377
|
+
}
|
|
1378
|
+
rawDriver = await Effect4.runPromise(
|
|
1379
|
+
makeLightweightCdpDriver({
|
|
1380
|
+
cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
|
|
1381
|
+
baseUrl: webUrl,
|
|
1382
|
+
engineLabel: engine,
|
|
1383
|
+
useBrowserContexts: useContexts,
|
|
1384
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1385
|
+
waitUntil: webExecution?.waitUntil,
|
|
1386
|
+
instantAnimations: webExecution?.instantAnimations,
|
|
1387
|
+
blockResources: webExecution?.blockResources,
|
|
1388
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1389
|
+
storageState: webExecution?.storageState
|
|
1390
|
+
})
|
|
1391
|
+
);
|
|
1392
|
+
} else {
|
|
1393
|
+
rawDriver = await Effect4.runPromise(
|
|
1394
|
+
makePlaywrightDriver({
|
|
1395
|
+
browser: webExecution?.browser,
|
|
1396
|
+
headless: webExecution?.headless ?? true,
|
|
1397
|
+
executablePath: webExecution?.executablePath,
|
|
1398
|
+
channel: webExecution?.channel,
|
|
1399
|
+
baseUrl: webUrl,
|
|
1400
|
+
storageState: webExecution?.storageState,
|
|
1401
|
+
verboseLogging: webExecution?.verboseLogging,
|
|
1402
|
+
recordHar: Boolean(config.artifacts?.har),
|
|
1403
|
+
waitUntil: webExecution?.waitUntil,
|
|
1404
|
+
instantAnimations: webExecution?.instantAnimations,
|
|
1405
|
+
blockResources: webExecution?.blockResources,
|
|
1406
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1407
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1408
|
+
warmBrowserScope: webExecution?.warmBrowserScope,
|
|
1409
|
+
sharedBrowser: prelaunchedBrowser,
|
|
1410
|
+
cdpEndpoint: prelaunchedBrowser ? void 0 : webExecution?.cdpUrl,
|
|
1411
|
+
wsEndpoint: prelaunchedBrowser ? void 0 : webExecution?.wsEndpoint,
|
|
1412
|
+
warmBrowser: prelaunchedBrowser ? false : webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false
|
|
1413
|
+
})
|
|
1414
|
+
);
|
|
1415
|
+
}
|
|
847
1416
|
const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
|
|
848
|
-
const deviceInfo = await
|
|
1417
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
849
1418
|
return {
|
|
850
1419
|
runtime: {
|
|
851
1420
|
driver,
|
|
852
1421
|
cleanup: () => safeCleanup(
|
|
853
|
-
() =>
|
|
1422
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
854
1423
|
() => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
|
|
1424
|
+
() => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
|
|
855
1425
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
856
1426
|
),
|
|
857
1427
|
metadata: {
|
|
@@ -867,37 +1437,160 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
867
1437
|
}
|
|
868
1438
|
async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
869
1439
|
const webExecution = config.execution?.web;
|
|
870
|
-
|
|
1440
|
+
const engine = resolveWebEngine(config);
|
|
1441
|
+
if (workerCount <= 1 || engine === "lightpanda") {
|
|
871
1442
|
return [await buildWebRuntime(config, prelaunched)];
|
|
872
1443
|
}
|
|
873
1444
|
const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
|
|
1445
|
+
const maxPerBrowser = Math.max(
|
|
1446
|
+
1,
|
|
1447
|
+
webExecution?.maxContextsPerBrowser ?? (engine === "cdp" ? 1 : 2)
|
|
1448
|
+
);
|
|
1449
|
+
if (engine === "cdp") {
|
|
1450
|
+
const useExternalCdp = Boolean(webExecution?.cdpUrl);
|
|
1451
|
+
const browserCount2 = useExternalCdp ? 1 : Math.ceil(workerCount / maxPerBrowser);
|
|
1452
|
+
const handles = [];
|
|
1453
|
+
if (useExternalCdp) {
|
|
1454
|
+
handles.push({ cdpUrl: webExecution.cdpUrl, remaining: workerCount });
|
|
1455
|
+
} else {
|
|
1456
|
+
const useWarm2 = webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
|
|
1457
|
+
const baseScope = webExecution?.warmBrowserScope ?? "pool";
|
|
1458
|
+
const launched = await Promise.all(
|
|
1459
|
+
Array.from(
|
|
1460
|
+
{ length: browserCount2 },
|
|
1461
|
+
(_v, bIdx) => bIdx === 0 && prelaunched?.cdpBrowserPromise ? prelaunched.cdpBrowserPromise : launchDirectCdpBrowser({
|
|
1462
|
+
executablePath: webExecution?.executablePath,
|
|
1463
|
+
headless: webExecution?.headless ?? true,
|
|
1464
|
+
warmBrowser: useWarm2,
|
|
1465
|
+
warmBrowserScope: `${baseScope}-w${bIdx}`
|
|
1466
|
+
})
|
|
1467
|
+
)
|
|
1468
|
+
);
|
|
1469
|
+
for (const h of launched) {
|
|
1470
|
+
handles.push({ cdpUrl: h.browserWsUrl, handle: h, remaining: 0 });
|
|
1471
|
+
}
|
|
1472
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1473
|
+
handles[i % handles.length].remaining += 1;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
const results2 = [];
|
|
1477
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1478
|
+
const bucket = handles[i % handles.length];
|
|
1479
|
+
const driver = await Effect4.runPromise(
|
|
1480
|
+
makeLightweightCdpDriver({
|
|
1481
|
+
cdpUrl: bucket.cdpUrl,
|
|
1482
|
+
baseUrl: webUrl,
|
|
1483
|
+
engineLabel: "cdp",
|
|
1484
|
+
useBrowserContexts: true,
|
|
1485
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1486
|
+
waitUntil: webExecution?.waitUntil,
|
|
1487
|
+
instantAnimations: webExecution?.instantAnimations,
|
|
1488
|
+
blockResources: webExecution?.blockResources,
|
|
1489
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1490
|
+
storageState: webExecution?.storageState
|
|
1491
|
+
})
|
|
1492
|
+
);
|
|
1493
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1494
|
+
let cleaned = false;
|
|
1495
|
+
results2.push({
|
|
1496
|
+
runtime: {
|
|
1497
|
+
driver,
|
|
1498
|
+
cleanup: () => safeCleanup(async () => {
|
|
1499
|
+
if (cleaned) return;
|
|
1500
|
+
cleaned = true;
|
|
1501
|
+
await Effect4.runPromise(driver.killApp(""));
|
|
1502
|
+
bucket.remaining -= 1;
|
|
1503
|
+
if (bucket.remaining <= 0 && bucket.handle) {
|
|
1504
|
+
await bucket.handle.close();
|
|
1505
|
+
}
|
|
1506
|
+
}),
|
|
1507
|
+
metadata: {
|
|
1508
|
+
platform: "web",
|
|
1509
|
+
mode: "local",
|
|
1510
|
+
deviceId: `cdp-context-${i + 1}`
|
|
1511
|
+
}
|
|
1512
|
+
},
|
|
1513
|
+
engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
|
|
1514
|
+
width: deviceInfo.screenWidth,
|
|
1515
|
+
height: deviceInfo.screenHeight
|
|
1516
|
+
})
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
return results2;
|
|
1520
|
+
}
|
|
874
1521
|
const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
|
|
875
|
-
const
|
|
876
|
-
const
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
1522
|
+
const singleExternalEndpoint = Boolean(webExecution?.cdpUrl || webExecution?.wsEndpoint);
|
|
1523
|
+
const browserCount = singleExternalEndpoint ? 1 : Math.ceil(workerCount / maxPerBrowser);
|
|
1524
|
+
const launchOneBrowser = async (idx) => {
|
|
1525
|
+
if (idx === 0 && prelaunched) {
|
|
1526
|
+
return {
|
|
1527
|
+
browser: await prelaunched.browserPromise,
|
|
1528
|
+
owns: prelaunched.ownsBrowser,
|
|
1529
|
+
remaining: 0
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
if (webExecution?.wsEndpoint) {
|
|
1533
|
+
return {
|
|
1534
|
+
browser: await connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser),
|
|
1535
|
+
owns: false,
|
|
1536
|
+
remaining: 0
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
if (webExecution?.cdpUrl) {
|
|
1540
|
+
return {
|
|
1541
|
+
browser: await connectPlaywrightOverCDP(webExecution.cdpUrl),
|
|
1542
|
+
owns: false,
|
|
1543
|
+
remaining: 0
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
if (idx === 0 && useWarm) {
|
|
1547
|
+
const warm = await ensureWarmBrowserDaemon({
|
|
1548
|
+
headless: webExecution?.headless ?? true,
|
|
1549
|
+
executablePath: webExecution?.executablePath,
|
|
1550
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1551
|
+
});
|
|
1552
|
+
return { browser: warm.browser, owns: false, remaining: 0 };
|
|
1553
|
+
}
|
|
1554
|
+
return {
|
|
1555
|
+
browser: await launchPlaywrightBrowser({
|
|
1556
|
+
browser: webExecution?.browser,
|
|
1557
|
+
headless: webExecution?.headless ?? true,
|
|
1558
|
+
executablePath: webExecution?.executablePath,
|
|
1559
|
+
channel: webExecution?.channel
|
|
1560
|
+
}),
|
|
1561
|
+
owns: true,
|
|
1562
|
+
remaining: 0
|
|
1563
|
+
};
|
|
1564
|
+
};
|
|
1565
|
+
const browserBuckets = await Promise.all(
|
|
1566
|
+
Array.from({ length: browserCount }, (_v, idx) => launchOneBrowser(idx))
|
|
1567
|
+
);
|
|
1568
|
+
for (let i = 0; i < workerCount; i++) {
|
|
1569
|
+
browserBuckets[i % browserBuckets.length].remaining += 1;
|
|
1570
|
+
}
|
|
884
1571
|
const results = [];
|
|
885
1572
|
for (let i = 0; i < workerCount; i++) {
|
|
886
|
-
const
|
|
1573
|
+
const bucket = browserBuckets[i % browserBuckets.length];
|
|
1574
|
+
const driver = await Effect4.runPromise(
|
|
887
1575
|
makePlaywrightDriver({
|
|
888
1576
|
browser: webExecution?.browser,
|
|
889
1577
|
headless: webExecution?.headless ?? true,
|
|
1578
|
+
executablePath: webExecution?.executablePath,
|
|
1579
|
+
channel: webExecution?.channel,
|
|
890
1580
|
baseUrl: webUrl,
|
|
891
1581
|
storageState: webExecution?.storageState,
|
|
892
1582
|
verboseLogging: webExecution?.verboseLogging,
|
|
893
|
-
sharedBrowser:
|
|
1583
|
+
sharedBrowser: bucket.browser,
|
|
894
1584
|
recordHar: Boolean(config.artifacts?.har),
|
|
895
1585
|
waitUntil: webExecution?.waitUntil,
|
|
896
1586
|
instantAnimations: webExecution?.instantAnimations,
|
|
897
|
-
blockResources: webExecution?.blockResources
|
|
1587
|
+
blockResources: webExecution?.blockResources,
|
|
1588
|
+
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1589
|
+
virtualAuthenticator: webExecution?.virtualAuthenticator,
|
|
1590
|
+
warmBrowserScope: webExecution?.warmBrowserScope
|
|
898
1591
|
})
|
|
899
1592
|
);
|
|
900
|
-
const deviceInfo = await
|
|
1593
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
901
1594
|
let cleaned = false;
|
|
902
1595
|
results.push({
|
|
903
1596
|
runtime: {
|
|
@@ -905,10 +1598,10 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
905
1598
|
cleanup: () => safeCleanup(async () => {
|
|
906
1599
|
if (cleaned) return;
|
|
907
1600
|
cleaned = true;
|
|
908
|
-
await
|
|
909
|
-
remaining -= 1;
|
|
910
|
-
if (remaining <= 0 &&
|
|
911
|
-
await
|
|
1601
|
+
await Effect4.runPromise(driver.killApp(""));
|
|
1602
|
+
bucket.remaining -= 1;
|
|
1603
|
+
if (bucket.remaining <= 0 && bucket.owns) {
|
|
1604
|
+
await bucket.browser.close();
|
|
912
1605
|
}
|
|
913
1606
|
}),
|
|
914
1607
|
metadata: {
|
|
@@ -928,7 +1621,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
928
1621
|
async function buildElectronRuntime(config, resolveFromConfig) {
|
|
929
1622
|
const electronCfg = config.apps?.electron ?? {};
|
|
930
1623
|
const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
|
|
931
|
-
const driver = await
|
|
1624
|
+
const driver = await Effect4.runPromise(
|
|
932
1625
|
makeElectronDriver({
|
|
933
1626
|
entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
|
|
934
1627
|
executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
|
|
@@ -944,12 +1637,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
944
1637
|
domChannel: bridge
|
|
945
1638
|
})
|
|
946
1639
|
);
|
|
947
|
-
const deviceInfo = await
|
|
1640
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
948
1641
|
return {
|
|
949
1642
|
runtime: {
|
|
950
1643
|
driver,
|
|
951
1644
|
cleanup: () => safeCleanup(
|
|
952
|
-
() =>
|
|
1645
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
953
1646
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
954
1647
|
),
|
|
955
1648
|
metadata: {
|
|
@@ -973,7 +1666,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
973
1666
|
async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
974
1667
|
const electrobunCfg = config.apps?.electrobun ?? {};
|
|
975
1668
|
const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
|
|
976
|
-
const driver = await
|
|
1669
|
+
const driver = await Effect4.runPromise(
|
|
977
1670
|
makeElectrobunDriver({
|
|
978
1671
|
executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
|
|
979
1672
|
appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
|
|
@@ -991,12 +1684,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
|
991
1684
|
domChannel: bridge
|
|
992
1685
|
})
|
|
993
1686
|
);
|
|
994
|
-
const deviceInfo = await
|
|
1687
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
995
1688
|
return {
|
|
996
1689
|
runtime: {
|
|
997
1690
|
driver,
|
|
998
1691
|
cleanup: () => safeCleanup(
|
|
999
|
-
() =>
|
|
1692
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1000
1693
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
1001
1694
|
),
|
|
1002
1695
|
metadata: {
|
|
@@ -1058,18 +1751,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
1058
1751
|
warm: warmDaemons?.enabled,
|
|
1059
1752
|
daemonStateFile: warmDaemons?.stateFile
|
|
1060
1753
|
});
|
|
1061
|
-
const driver = await
|
|
1754
|
+
const driver = await Effect4.runPromise(
|
|
1062
1755
|
createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
|
|
1063
1756
|
domChannel: bridge,
|
|
1064
1757
|
cdpPort: config.apps?.android?.cdpPort
|
|
1065
1758
|
})
|
|
1066
1759
|
);
|
|
1067
|
-
const deviceInfo = await
|
|
1760
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1068
1761
|
return {
|
|
1069
1762
|
runtime: {
|
|
1070
1763
|
driver,
|
|
1071
1764
|
cleanup: () => safeCleanup(
|
|
1072
|
-
() =>
|
|
1765
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1073
1766
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1074
1767
|
() => {
|
|
1075
1768
|
if (reversedBridgePort !== null) {
|
|
@@ -1106,7 +1799,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1106
1799
|
const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
|
|
1107
1800
|
const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
|
|
1108
1801
|
const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
|
|
1109
|
-
const driver = await
|
|
1802
|
+
const driver = await Effect4.runPromise(
|
|
1110
1803
|
createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
|
|
1111
1804
|
domChannel: bridge,
|
|
1112
1805
|
webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
|
|
@@ -1116,12 +1809,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1116
1809
|
onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
|
|
1117
1810
|
})
|
|
1118
1811
|
);
|
|
1119
|
-
const deviceInfo = await
|
|
1812
|
+
const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
|
|
1120
1813
|
return {
|
|
1121
1814
|
runtime: {
|
|
1122
1815
|
driver,
|
|
1123
1816
|
cleanup: () => safeCleanup(
|
|
1124
|
-
() =>
|
|
1817
|
+
() => Effect4.runPromise(driver.killApp("")),
|
|
1125
1818
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1126
1819
|
() => conn.cleanup?.() ?? Promise.resolve()
|
|
1127
1820
|
),
|
|
@@ -1252,13 +1945,292 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1252
1945
|
}
|
|
1253
1946
|
}
|
|
1254
1947
|
|
|
1948
|
+
// src/core/video-recorder.ts
|
|
1949
|
+
import { execFileSync, spawn as spawn2 } from "child_process";
|
|
1950
|
+
import {
|
|
1951
|
+
existsSync as existsSync2,
|
|
1952
|
+
mkdirSync,
|
|
1953
|
+
mkdtempSync as mkdtempSync2,
|
|
1954
|
+
readFileSync,
|
|
1955
|
+
rmSync as rmSync2,
|
|
1956
|
+
unlinkSync,
|
|
1957
|
+
writeFileSync
|
|
1958
|
+
} from "fs";
|
|
1959
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
1960
|
+
import { join as join2 } from "path";
|
|
1961
|
+
function hasFfmpegOnPath() {
|
|
1962
|
+
try {
|
|
1963
|
+
execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
|
|
1964
|
+
stdio: "ignore"
|
|
1965
|
+
});
|
|
1966
|
+
return true;
|
|
1967
|
+
} catch {
|
|
1968
|
+
return false;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
|
|
1972
|
+
if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
|
|
1973
|
+
const tempDir = mkdtempSync2(join2(tmpdir2(), "spana-vid-"));
|
|
1974
|
+
try {
|
|
1975
|
+
const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
|
|
1976
|
+
const listLines = [];
|
|
1977
|
+
for (let i = 0; i < frames.length; i++) {
|
|
1978
|
+
const f = frames[i];
|
|
1979
|
+
const framePath = join2(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
|
|
1980
|
+
writeFileSync(framePath, Buffer.from(f.dataBase64, "base64"));
|
|
1981
|
+
const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
|
|
1982
|
+
const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
|
|
1983
|
+
listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
|
|
1984
|
+
listLines.push(`duration ${durSec.toFixed(3)}`);
|
|
1985
|
+
}
|
|
1986
|
+
const lastPath = join2(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
|
|
1987
|
+
listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
|
|
1988
|
+
const listFile = join2(tempDir, "frames.txt");
|
|
1989
|
+
writeFileSync(listFile, listLines.join("\n"), "utf8");
|
|
1990
|
+
const ok = await new Promise((resolve) => {
|
|
1991
|
+
const child = spawnFn(
|
|
1992
|
+
"ffmpeg",
|
|
1993
|
+
[
|
|
1994
|
+
"-y",
|
|
1995
|
+
"-f",
|
|
1996
|
+
"concat",
|
|
1997
|
+
"-safe",
|
|
1998
|
+
"0",
|
|
1999
|
+
"-i",
|
|
2000
|
+
listFile,
|
|
2001
|
+
"-vf",
|
|
2002
|
+
"pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
|
2003
|
+
"-c:v",
|
|
2004
|
+
"libx264",
|
|
2005
|
+
"-pix_fmt",
|
|
2006
|
+
"yuv420p",
|
|
2007
|
+
"-movflags",
|
|
2008
|
+
"+faststart",
|
|
2009
|
+
outputPath
|
|
2010
|
+
],
|
|
2011
|
+
{ stdio: "ignore" }
|
|
2012
|
+
);
|
|
2013
|
+
child.on("error", () => resolve(false));
|
|
2014
|
+
child.on("close", (code) => resolve(code === 0));
|
|
2015
|
+
});
|
|
2016
|
+
return ok && existsSync2(outputPath) ? outputPath : void 0;
|
|
2017
|
+
} catch {
|
|
2018
|
+
return void 0;
|
|
2019
|
+
} finally {
|
|
2020
|
+
try {
|
|
2021
|
+
rmSync2(tempDir, { recursive: true, force: true });
|
|
2022
|
+
} catch {
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
async function startCdpScreencastRecorder(cdp, options) {
|
|
2027
|
+
const startedAt = Date.now();
|
|
2028
|
+
const startedAtIso = new Date(startedAt).toISOString();
|
|
2029
|
+
const maxFrames = options.maxFrames ?? 180;
|
|
2030
|
+
const frames = [];
|
|
2031
|
+
let stopped = false;
|
|
2032
|
+
const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
|
|
2033
|
+
if (stopped) return;
|
|
2034
|
+
const sessionId = params?.sessionId;
|
|
2035
|
+
if (sessionId !== void 0) {
|
|
2036
|
+
void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
|
|
2037
|
+
});
|
|
2038
|
+
}
|
|
2039
|
+
if (typeof params?.data === "string" && params.data.length > 0) {
|
|
2040
|
+
if (frames.length >= maxFrames) {
|
|
2041
|
+
frames.splice(1, 1);
|
|
2042
|
+
}
|
|
2043
|
+
frames.push({
|
|
2044
|
+
timestampMs: Math.max(0, Date.now() - startedAt),
|
|
2045
|
+
dataBase64: params.data,
|
|
2046
|
+
mimeType: "image/jpeg"
|
|
2047
|
+
});
|
|
2048
|
+
}
|
|
2049
|
+
});
|
|
2050
|
+
await cdp.sendCommand("Page.startScreencast", {
|
|
2051
|
+
format: "jpeg",
|
|
2052
|
+
quality: options.quality ?? 65,
|
|
2053
|
+
maxWidth: options.maxWidth ?? 1280,
|
|
2054
|
+
maxHeight: options.maxHeight ?? 720,
|
|
2055
|
+
everyNthFrame: options.everyNthFrame ?? 2
|
|
2056
|
+
}).catch(() => {
|
|
2057
|
+
});
|
|
2058
|
+
return {
|
|
2059
|
+
stop: async (stopOpts) => {
|
|
2060
|
+
if (stopped) return { frameCount: frames.length };
|
|
2061
|
+
stopped = true;
|
|
2062
|
+
unsubscribe();
|
|
2063
|
+
await cdp.sendCommand("Page.stopScreencast").catch(() => {
|
|
2064
|
+
});
|
|
2065
|
+
if (!stopOpts.keep || frames.length === 0) {
|
|
2066
|
+
return { frameCount: 0 };
|
|
2067
|
+
}
|
|
2068
|
+
mkdirSync(stopOpts.outputDir, { recursive: true });
|
|
2069
|
+
let videoPath;
|
|
2070
|
+
if (options.exportMp4 !== false) {
|
|
2071
|
+
const mp4Target = join2(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
|
|
2072
|
+
videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
|
|
2073
|
+
}
|
|
2074
|
+
const trace = {
|
|
2075
|
+
version: 1,
|
|
2076
|
+
flowName: options.flowName,
|
|
2077
|
+
platform: options.platform,
|
|
2078
|
+
startedAtIso,
|
|
2079
|
+
durationMs: Math.max(1, Date.now() - startedAt),
|
|
2080
|
+
viewport: stopOpts.viewport,
|
|
2081
|
+
frames,
|
|
2082
|
+
steps: stopOpts.steps ?? [],
|
|
2083
|
+
...videoPath ? { videoPath } : {}
|
|
2084
|
+
};
|
|
2085
|
+
const playbackJsonPath = join2(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
|
|
2086
|
+
writeFileSync(playbackJsonPath, JSON.stringify(trace), "utf8");
|
|
2087
|
+
return { playbackJsonPath, videoPath, frameCount: frames.length };
|
|
2088
|
+
}
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
function startAndroidVideoRecorder(serial, options) {
|
|
2092
|
+
const spawnFn = options.spawnFn ?? spawn2;
|
|
2093
|
+
const execSyncFn = options.execFileSyncFn ?? execFileSync;
|
|
2094
|
+
const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
|
|
2095
|
+
const child = spawnFn(
|
|
2096
|
+
"adb",
|
|
2097
|
+
["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
|
|
2098
|
+
{ stdio: "ignore" }
|
|
2099
|
+
);
|
|
2100
|
+
let stopped = false;
|
|
2101
|
+
return {
|
|
2102
|
+
stop: async ({ keep }) => {
|
|
2103
|
+
if (stopped) return { frameCount: 0 };
|
|
2104
|
+
stopped = true;
|
|
2105
|
+
try {
|
|
2106
|
+
child.kill("SIGINT");
|
|
2107
|
+
} catch {
|
|
2108
|
+
}
|
|
2109
|
+
await new Promise((resolve) => {
|
|
2110
|
+
const timer = setTimeout(resolve, 1200);
|
|
2111
|
+
child.once("close", () => {
|
|
2112
|
+
clearTimeout(timer);
|
|
2113
|
+
resolve();
|
|
2114
|
+
});
|
|
2115
|
+
});
|
|
2116
|
+
let savedPath;
|
|
2117
|
+
if (keep) {
|
|
2118
|
+
try {
|
|
2119
|
+
execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
|
|
2120
|
+
stdio: "ignore"
|
|
2121
|
+
});
|
|
2122
|
+
if (existsSync2(options.outputPath)) savedPath = options.outputPath;
|
|
2123
|
+
} catch {
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
try {
|
|
2127
|
+
execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
|
|
2128
|
+
} catch {
|
|
2129
|
+
}
|
|
2130
|
+
return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
function startIosSimulatorVideoRecorder(udid, options) {
|
|
2135
|
+
const spawnFn = options.spawnFn ?? spawn2;
|
|
2136
|
+
const child = spawnFn(
|
|
2137
|
+
"xcrun",
|
|
2138
|
+
["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
|
|
2139
|
+
{ stdio: "ignore" }
|
|
2140
|
+
);
|
|
2141
|
+
let stopped = false;
|
|
2142
|
+
return {
|
|
2143
|
+
stop: async ({ keep }) => {
|
|
2144
|
+
if (stopped) return { frameCount: 0 };
|
|
2145
|
+
stopped = true;
|
|
2146
|
+
try {
|
|
2147
|
+
child.kill("SIGINT");
|
|
2148
|
+
} catch {
|
|
2149
|
+
}
|
|
2150
|
+
await new Promise((resolve) => {
|
|
2151
|
+
const timer = setTimeout(resolve, 1500);
|
|
2152
|
+
child.once("close", () => {
|
|
2153
|
+
clearTimeout(timer);
|
|
2154
|
+
resolve();
|
|
2155
|
+
});
|
|
2156
|
+
});
|
|
2157
|
+
if (!keep) {
|
|
2158
|
+
try {
|
|
2159
|
+
if (existsSync2(options.outputPath)) unlinkSync(options.outputPath);
|
|
2160
|
+
} catch {
|
|
2161
|
+
}
|
|
2162
|
+
return { frameCount: 0 };
|
|
2163
|
+
}
|
|
2164
|
+
return {
|
|
2165
|
+
videoPath: existsSync2(options.outputPath) ? options.outputPath : void 0,
|
|
2166
|
+
frameCount: existsSync2(options.outputPath) ? 1 : 0
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
function buildPlaybackTraceFromSteps(input) {
|
|
2172
|
+
const frames = [];
|
|
2173
|
+
const markers = [];
|
|
2174
|
+
let cursorMs = 0;
|
|
2175
|
+
for (let i = 0; i < input.steps.length; i++) {
|
|
2176
|
+
const step = input.steps[i];
|
|
2177
|
+
const tapPoint = extractTapPointFromStep(step);
|
|
2178
|
+
markers.push({
|
|
2179
|
+
index: i,
|
|
2180
|
+
command: step.command,
|
|
2181
|
+
selector: step.selector,
|
|
2182
|
+
startedAtMs: cursorMs,
|
|
2183
|
+
durationMs: step.durationMs,
|
|
2184
|
+
status: step.status,
|
|
2185
|
+
error: step.error,
|
|
2186
|
+
...tapPoint ? { tapPoint } : {}
|
|
2187
|
+
});
|
|
2188
|
+
const img = step.attachments?.find(
|
|
2189
|
+
(a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
|
|
2190
|
+
);
|
|
2191
|
+
if (img && existsSync2(img.path)) {
|
|
2192
|
+
try {
|
|
2193
|
+
const dataBase64 = readFileSync(img.path).toString("base64");
|
|
2194
|
+
frames.push({
|
|
2195
|
+
timestampMs: cursorMs + step.durationMs,
|
|
2196
|
+
dataBase64,
|
|
2197
|
+
mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
|
|
2198
|
+
});
|
|
2199
|
+
} catch {
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
cursorMs += Math.max(1, step.durationMs);
|
|
2203
|
+
}
|
|
2204
|
+
if (frames.length === 0 && !input.videoPath) return null;
|
|
2205
|
+
return {
|
|
2206
|
+
version: 1,
|
|
2207
|
+
flowName: input.flowName,
|
|
2208
|
+
platform: input.platform,
|
|
2209
|
+
startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2210
|
+
durationMs: Math.max(1, input.durationMs),
|
|
2211
|
+
viewport: input.viewport,
|
|
2212
|
+
frames,
|
|
2213
|
+
steps: markers,
|
|
2214
|
+
...input.videoPath ? { videoPath: input.videoPath } : {}
|
|
2215
|
+
};
|
|
2216
|
+
}
|
|
2217
|
+
function extractTapPointFromStep(step) {
|
|
2218
|
+
const sel = step.selector;
|
|
2219
|
+
if (!sel || typeof sel !== "object") return void 0;
|
|
2220
|
+
const pt = sel["point"];
|
|
2221
|
+
if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
|
|
2222
|
+
return { x: pt["x"], y: pt["y"] };
|
|
2223
|
+
}
|
|
2224
|
+
return void 0;
|
|
2225
|
+
}
|
|
2226
|
+
|
|
1255
2227
|
// src/core/engine.ts
|
|
1256
|
-
import { Effect as
|
|
2228
|
+
import { Effect as Effect7 } from "effect";
|
|
1257
2229
|
|
|
1258
2230
|
// src/core/artifacts.ts
|
|
1259
|
-
import { writeFileSync, mkdirSync } from "fs";
|
|
1260
|
-
import { join } from "path";
|
|
1261
|
-
import { Effect as
|
|
2231
|
+
import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
2232
|
+
import { join as join3 } from "path";
|
|
2233
|
+
import { Effect as Effect5 } from "effect";
|
|
1262
2234
|
var DEFAULT_ARTIFACT_CONFIG = {
|
|
1263
2235
|
outputDir: "./spana-output",
|
|
1264
2236
|
captureOnFailure: true,
|
|
@@ -1268,27 +2240,30 @@ var DEFAULT_ARTIFACT_CONFIG = {
|
|
|
1268
2240
|
uiHierarchy: true,
|
|
1269
2241
|
consoleLogs: true,
|
|
1270
2242
|
jsErrors: true,
|
|
1271
|
-
har: true
|
|
2243
|
+
har: true,
|
|
2244
|
+
video: "off",
|
|
2245
|
+
playback: false
|
|
1272
2246
|
};
|
|
1273
|
-
function
|
|
2247
|
+
function safeArtifactName(value) {
|
|
1274
2248
|
return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
|
|
1275
2249
|
}
|
|
2250
|
+
var safeName = safeArtifactName;
|
|
1276
2251
|
function flowArtifactDir(config, flowName, platform) {
|
|
1277
|
-
const dir =
|
|
1278
|
-
|
|
2252
|
+
const dir = join3(config.outputDir, `${safeName(flowName)}-${platform}`);
|
|
2253
|
+
mkdirSync2(dir, { recursive: true });
|
|
1279
2254
|
return dir;
|
|
1280
2255
|
}
|
|
1281
2256
|
function createAttachment(name, contentType, path) {
|
|
1282
2257
|
return { name, contentType, path };
|
|
1283
2258
|
}
|
|
1284
2259
|
function writeJsonAttachment(dir, fileName, attachmentName, value) {
|
|
1285
|
-
const path =
|
|
1286
|
-
|
|
2260
|
+
const path = join3(dir, fileName);
|
|
2261
|
+
writeFileSync2(path, JSON.stringify(value, null, 2), "utf-8");
|
|
1287
2262
|
return createAttachment(attachmentName, "application/json", path);
|
|
1288
2263
|
}
|
|
1289
2264
|
function writeTextAttachment(dir, fileName, attachmentName, value) {
|
|
1290
|
-
const path =
|
|
1291
|
-
|
|
2265
|
+
const path = join3(dir, fileName);
|
|
2266
|
+
writeFileSync2(path, value, "utf-8");
|
|
1292
2267
|
return createAttachment(attachmentName, "text/plain", path);
|
|
1293
2268
|
}
|
|
1294
2269
|
function resolveArtifactConfig(...configs) {
|
|
@@ -1307,25 +2282,25 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1307
2282
|
const dir = flowArtifactDir(config, flowName, platform);
|
|
1308
2283
|
if (config.screenshot) {
|
|
1309
2284
|
try {
|
|
1310
|
-
const screenshot = await
|
|
1311
|
-
const path =
|
|
1312
|
-
|
|
2285
|
+
const screenshot = await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
|
|
2286
|
+
const path = join3(dir, "screenshot.png");
|
|
2287
|
+
writeFileSync2(path, screenshot);
|
|
1313
2288
|
attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
|
|
1314
2289
|
} catch {
|
|
1315
2290
|
}
|
|
1316
2291
|
}
|
|
1317
2292
|
if (config.uiHierarchy) {
|
|
1318
2293
|
try {
|
|
1319
|
-
const hierarchy = await
|
|
1320
|
-
const path =
|
|
1321
|
-
|
|
2294
|
+
const hierarchy = await Effect5.runPromise(Effect5.orDie(driver.dumpHierarchy()));
|
|
2295
|
+
const path = join3(dir, "hierarchy.json");
|
|
2296
|
+
writeFileSync2(path, hierarchy, "utf-8");
|
|
1322
2297
|
attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
|
|
1323
2298
|
} catch {
|
|
1324
2299
|
}
|
|
1325
2300
|
}
|
|
1326
2301
|
if (config.consoleLogs && driver.getConsoleLogs) {
|
|
1327
2302
|
try {
|
|
1328
|
-
const consoleLogs = await
|
|
2303
|
+
const consoleLogs = await Effect5.runPromise(Effect5.orDie(driver.getConsoleLogs()));
|
|
1329
2304
|
if (consoleLogs.length > 0) {
|
|
1330
2305
|
attachments.push(
|
|
1331
2306
|
writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
|
|
@@ -1336,7 +2311,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1336
2311
|
}
|
|
1337
2312
|
if (config.jsErrors && driver.getJSErrors) {
|
|
1338
2313
|
try {
|
|
1339
|
-
const jsErrors = await
|
|
2314
|
+
const jsErrors = await Effect5.runPromise(Effect5.orDie(driver.getJSErrors()));
|
|
1340
2315
|
if (jsErrors.length > 0) {
|
|
1341
2316
|
attachments.push(
|
|
1342
2317
|
writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
|
|
@@ -1347,7 +2322,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1347
2322
|
}
|
|
1348
2323
|
if (config.har && driver.getHAR) {
|
|
1349
2324
|
try {
|
|
1350
|
-
const har = await
|
|
2325
|
+
const har = await Effect5.runPromise(Effect5.orDie(driver.getHAR()));
|
|
1351
2326
|
if (har.log.entries.length > 0) {
|
|
1352
2327
|
attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
|
|
1353
2328
|
}
|
|
@@ -1356,7 +2331,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1356
2331
|
}
|
|
1357
2332
|
if (status === "failed" && driver.getDriverLogs) {
|
|
1358
2333
|
try {
|
|
1359
|
-
const driverLogs = await
|
|
2334
|
+
const driverLogs = await Effect5.runPromise(Effect5.orDie(driver.getDriverLogs()));
|
|
1360
2335
|
if (driverLogs.length > 0) {
|
|
1361
2336
|
attachments.push(
|
|
1362
2337
|
writeTextAttachment(
|
|
@@ -1375,12 +2350,12 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
1375
2350
|
async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
|
|
1376
2351
|
if (!config.screenshot) return void 0;
|
|
1377
2352
|
try {
|
|
1378
|
-
const dir =
|
|
1379
|
-
|
|
2353
|
+
const dir = join3(flowArtifactDir(config, flowName, platform), "steps");
|
|
2354
|
+
mkdirSync2(dir, { recursive: true });
|
|
1380
2355
|
const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
|
|
1381
|
-
const path =
|
|
1382
|
-
const bytes = screenshot ?? await
|
|
1383
|
-
|
|
2356
|
+
const path = join3(dir, fileName);
|
|
2357
|
+
const bytes = screenshot ?? await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
|
|
2358
|
+
writeFileSync2(path, bytes);
|
|
1384
2359
|
return createAttachment(stepName, "image/png", path);
|
|
1385
2360
|
} catch {
|
|
1386
2361
|
return void 0;
|
|
@@ -1389,7 +2364,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
|
|
|
1389
2364
|
|
|
1390
2365
|
// src/core/debug-repl.ts
|
|
1391
2366
|
import * as repl from "repl";
|
|
1392
|
-
import { Effect as
|
|
2367
|
+
import { Effect as Effect6 } from "effect";
|
|
1393
2368
|
var didStartDebugRepl = false;
|
|
1394
2369
|
function toSuggestedSelectors(root) {
|
|
1395
2370
|
return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
|
|
@@ -1410,7 +2385,7 @@ async function runDebugReplOnce(context) {
|
|
|
1410
2385
|
console.log("Skipping debug REPL because stdin/stdout is not interactive.");
|
|
1411
2386
|
return false;
|
|
1412
2387
|
}
|
|
1413
|
-
const hierarchy = async () => context.parseHierarchy(await
|
|
2388
|
+
const hierarchy = async () => context.parseHierarchy(await Effect6.runPromise(context.driver.dumpHierarchy()));
|
|
1414
2389
|
const selectors = async () => toSuggestedSelectors(await hierarchy());
|
|
1415
2390
|
console.log("");
|
|
1416
2391
|
console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
|
|
@@ -1804,11 +2779,12 @@ function classifyError(error) {
|
|
|
1804
2779
|
}
|
|
1805
2780
|
|
|
1806
2781
|
// src/core/engine.ts
|
|
1807
|
-
import {
|
|
2782
|
+
import { writeFileSync as writeFileSync4 } from "fs";
|
|
2783
|
+
import { join as join5 } from "path";
|
|
1808
2784
|
|
|
1809
2785
|
// src/report/failure-bundle.ts
|
|
1810
|
-
import { writeFileSync as
|
|
1811
|
-
import { join as
|
|
2786
|
+
import { writeFileSync as writeFileSync3, readFileSync as readFileSync2, existsSync as existsSync3 } from "fs";
|
|
2787
|
+
import { join as join4, basename } from "path";
|
|
1812
2788
|
function levenshtein(a, b) {
|
|
1813
2789
|
const m = a.length;
|
|
1814
2790
|
const n = b.length;
|
|
@@ -1915,11 +2891,11 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1915
2891
|
} : null;
|
|
1916
2892
|
let selectorContext;
|
|
1917
2893
|
if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
|
|
1918
|
-
const hierarchyPath =
|
|
2894
|
+
const hierarchyPath = join4(artifactDir, "hierarchy.json");
|
|
1919
2895
|
let hierarchyJson = null;
|
|
1920
|
-
if (
|
|
2896
|
+
if (existsSync3(hierarchyPath)) {
|
|
1921
2897
|
try {
|
|
1922
|
-
hierarchyJson =
|
|
2898
|
+
hierarchyJson = readFileSync2(hierarchyPath, "utf-8");
|
|
1923
2899
|
} catch {
|
|
1924
2900
|
}
|
|
1925
2901
|
}
|
|
@@ -1932,17 +2908,17 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1932
2908
|
const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
|
|
1933
2909
|
const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
|
|
1934
2910
|
let runtimeDiagnostics;
|
|
1935
|
-
const consolePath =
|
|
1936
|
-
const jsErrPath =
|
|
1937
|
-
if (
|
|
2911
|
+
const consolePath = join4(artifactDir, "console-logs.json");
|
|
2912
|
+
const jsErrPath = join4(artifactDir, "js-errors.json");
|
|
2913
|
+
if (existsSync3(consolePath) || existsSync3(jsErrPath)) {
|
|
1938
2914
|
let consoleErrorCount = 0;
|
|
1939
2915
|
let consoleWarnCount = 0;
|
|
1940
2916
|
const recentConsoleErrors = [];
|
|
1941
2917
|
let jsErrorCount = 0;
|
|
1942
2918
|
const recentJsErrors = [];
|
|
1943
|
-
if (
|
|
2919
|
+
if (existsSync3(consolePath)) {
|
|
1944
2920
|
try {
|
|
1945
|
-
const logs = JSON.parse(
|
|
2921
|
+
const logs = JSON.parse(readFileSync2(consolePath, "utf-8"));
|
|
1946
2922
|
if (Array.isArray(logs)) {
|
|
1947
2923
|
for (const entry of logs) {
|
|
1948
2924
|
const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
|
|
@@ -1958,9 +2934,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
1958
2934
|
} catch {
|
|
1959
2935
|
}
|
|
1960
2936
|
}
|
|
1961
|
-
if (
|
|
2937
|
+
if (existsSync3(jsErrPath)) {
|
|
1962
2938
|
try {
|
|
1963
|
-
const errs = JSON.parse(
|
|
2939
|
+
const errs = JSON.parse(readFileSync2(jsErrPath, "utf-8"));
|
|
1964
2940
|
if (Array.isArray(errs)) {
|
|
1965
2941
|
jsErrorCount = errs.length;
|
|
1966
2942
|
for (const e of errs.slice(-5)) {
|
|
@@ -2003,12 +2979,35 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2003
2979
|
return bundle;
|
|
2004
2980
|
}
|
|
2005
2981
|
function writeFailureBundle(bundle, artifactDir) {
|
|
2006
|
-
const path =
|
|
2007
|
-
|
|
2982
|
+
const path = join4(artifactDir, "failure-bundle.json");
|
|
2983
|
+
writeFileSync3(path, JSON.stringify(bundle, null, 2), "utf-8");
|
|
2008
2984
|
return path;
|
|
2009
2985
|
}
|
|
2010
2986
|
|
|
2011
2987
|
// src/core/engine.ts
|
|
2988
|
+
function isCdpScreencastCapable(channel) {
|
|
2989
|
+
return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
|
|
2990
|
+
}
|
|
2991
|
+
function buildPlaybackStepMarkers(steps) {
|
|
2992
|
+
let cursorMs = 0;
|
|
2993
|
+
return steps.map((step, index) => {
|
|
2994
|
+
const startedAtMs = cursorMs;
|
|
2995
|
+
cursorMs += Math.max(1, step.durationMs);
|
|
2996
|
+
const sel = step.selector;
|
|
2997
|
+
const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
|
|
2998
|
+
const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
|
|
2999
|
+
return {
|
|
3000
|
+
index,
|
|
3001
|
+
command: step.command,
|
|
3002
|
+
selector: step.selector,
|
|
3003
|
+
startedAtMs,
|
|
3004
|
+
durationMs: step.durationMs,
|
|
3005
|
+
status: step.status,
|
|
3006
|
+
error: step.error,
|
|
3007
|
+
...tapPoint ? { tapPoint } : {}
|
|
3008
|
+
};
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
2012
3011
|
async function executeFlow(flow, driver, config) {
|
|
2013
3012
|
const start2 = Date.now();
|
|
2014
3013
|
const { platform, coordinatorConfig, appId } = config;
|
|
@@ -2054,7 +3053,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
2054
3053
|
const sessions = createSessions(
|
|
2055
3054
|
sessionManager,
|
|
2056
3055
|
async (opts) => {
|
|
2057
|
-
const pwDriver = await
|
|
3056
|
+
const pwDriver = await Effect7.runPromise(
|
|
2058
3057
|
makePlaywrightDriver({
|
|
2059
3058
|
browser: opts.browser,
|
|
2060
3059
|
headless: opts.headless ?? true,
|
|
@@ -2068,6 +3067,70 @@ async function executeFlow(flow, driver, config) {
|
|
|
2068
3067
|
{ parse: (raw) => parseWebHierarchy(raw) }
|
|
2069
3068
|
);
|
|
2070
3069
|
flowCtx.sessions = sessions;
|
|
3070
|
+
let videoRecorder;
|
|
3071
|
+
let recordingFinalized = false;
|
|
3072
|
+
const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
|
|
3073
|
+
const finalizeRecording = async (status, attachments, steps, durationMs) => {
|
|
3074
|
+
if (recordingFinalized || !wantRecording) return;
|
|
3075
|
+
recordingFinalized = true;
|
|
3076
|
+
const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
|
|
3077
|
+
const fileStem = safeArtifactName(flow.name);
|
|
3078
|
+
const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
|
|
3079
|
+
let viewport;
|
|
3080
|
+
try {
|
|
3081
|
+
const info = await Effect7.runPromise(Effect7.orDie(driver.getDeviceInfo()));
|
|
3082
|
+
if (info.screenWidth > 0 && info.screenHeight > 0) {
|
|
3083
|
+
viewport = { width: info.screenWidth, height: info.screenHeight };
|
|
3084
|
+
}
|
|
3085
|
+
} catch {
|
|
3086
|
+
}
|
|
3087
|
+
let stopRes;
|
|
3088
|
+
if (videoRecorder) {
|
|
3089
|
+
try {
|
|
3090
|
+
stopRes = await videoRecorder.stop({
|
|
3091
|
+
keep,
|
|
3092
|
+
outputDir,
|
|
3093
|
+
fileStem,
|
|
3094
|
+
steps: buildPlaybackStepMarkers(steps),
|
|
3095
|
+
viewport
|
|
3096
|
+
});
|
|
3097
|
+
} catch {
|
|
3098
|
+
}
|
|
3099
|
+
}
|
|
3100
|
+
if (!keep) return;
|
|
3101
|
+
if (stopRes?.videoPath) {
|
|
3102
|
+
attachments.push({
|
|
3103
|
+
name: "video",
|
|
3104
|
+
contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
|
|
3105
|
+
path: stopRes.videoPath
|
|
3106
|
+
});
|
|
3107
|
+
}
|
|
3108
|
+
if (stopRes?.playbackJsonPath) {
|
|
3109
|
+
attachments.push({
|
|
3110
|
+
name: "playback",
|
|
3111
|
+
contentType: "application/json",
|
|
3112
|
+
path: stopRes.playbackJsonPath
|
|
3113
|
+
});
|
|
3114
|
+
return;
|
|
3115
|
+
}
|
|
3116
|
+
const fallbackTrace = buildPlaybackTraceFromSteps({
|
|
3117
|
+
flowName: flow.name,
|
|
3118
|
+
platform,
|
|
3119
|
+
durationMs,
|
|
3120
|
+
steps,
|
|
3121
|
+
viewport,
|
|
3122
|
+
videoPath: stopRes?.videoPath
|
|
3123
|
+
});
|
|
3124
|
+
if (fallbackTrace) {
|
|
3125
|
+
const playbackPath = join5(outputDir, `${fileStem}-playback.json`);
|
|
3126
|
+
writeFileSync4(playbackPath, JSON.stringify(fallbackTrace), "utf8");
|
|
3127
|
+
attachments.push({
|
|
3128
|
+
name: "playback",
|
|
3129
|
+
contentType: "application/json",
|
|
3130
|
+
path: playbackPath
|
|
3131
|
+
});
|
|
3132
|
+
}
|
|
3133
|
+
};
|
|
2071
3134
|
const buildFailureResult = async (error) => {
|
|
2072
3135
|
const attachments = await captureArtifacts(
|
|
2073
3136
|
driver,
|
|
@@ -2076,25 +3139,49 @@ async function executeFlow(flow, driver, config) {
|
|
|
2076
3139
|
platform,
|
|
2077
3140
|
"failed"
|
|
2078
3141
|
);
|
|
3142
|
+
const steps = stepRecorder.getSteps();
|
|
3143
|
+
const durationMs = Date.now() - start2;
|
|
3144
|
+
await finalizeRecording("failed", attachments, steps, durationMs);
|
|
2079
3145
|
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
2080
3146
|
return {
|
|
2081
3147
|
name: flow.name,
|
|
2082
3148
|
platform,
|
|
2083
3149
|
status: "failed",
|
|
2084
|
-
durationMs
|
|
3150
|
+
durationMs,
|
|
2085
3151
|
error: classifyError(normalized),
|
|
2086
3152
|
attachments,
|
|
2087
|
-
steps
|
|
3153
|
+
steps,
|
|
2088
3154
|
scenarioSteps: flowCtx.__scenarioSteps
|
|
2089
3155
|
};
|
|
2090
3156
|
};
|
|
2091
3157
|
if (driver.beginFlow) {
|
|
2092
3158
|
try {
|
|
2093
|
-
await
|
|
3159
|
+
await Effect7.runPromise(driver.beginFlow(flow.name));
|
|
2094
3160
|
} catch (error) {
|
|
2095
3161
|
return buildFailureResult(error);
|
|
2096
3162
|
}
|
|
2097
3163
|
}
|
|
3164
|
+
if (wantRecording) {
|
|
3165
|
+
try {
|
|
3166
|
+
if (isCdpScreencastCapable(driver.domChannel)) {
|
|
3167
|
+
videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
|
|
3168
|
+
flowName: flow.name,
|
|
3169
|
+
platform,
|
|
3170
|
+
exportMp4: artifactConfig.video !== "off"
|
|
3171
|
+
});
|
|
3172
|
+
} else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
|
|
3173
|
+
const info = await Effect7.runPromise(Effect7.orDie(driver.getDeviceInfo())).catch(
|
|
3174
|
+
() => void 0
|
|
3175
|
+
);
|
|
3176
|
+
if (info?.deviceId) {
|
|
3177
|
+
const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
|
|
3178
|
+
const videoOut = join5(outDir, `${safeArtifactName(flow.name)}.mp4`);
|
|
3179
|
+
videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
|
|
3180
|
+
}
|
|
3181
|
+
}
|
|
3182
|
+
} catch {
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
2098
3185
|
if (config.hooks?.beforeEach) {
|
|
2099
3186
|
try {
|
|
2100
3187
|
await config.hooks.beforeEach({ app, platform });
|
|
@@ -2123,13 +3210,16 @@ async function executeFlow(flow, driver, config) {
|
|
|
2123
3210
|
platform,
|
|
2124
3211
|
"passed"
|
|
2125
3212
|
);
|
|
3213
|
+
const steps = stepRecorder.getSteps();
|
|
3214
|
+
const durationMs = Date.now() - start2;
|
|
3215
|
+
await finalizeRecording("passed", attachments, steps, durationMs);
|
|
2126
3216
|
result = {
|
|
2127
3217
|
name: flow.name,
|
|
2128
3218
|
platform,
|
|
2129
3219
|
status: "passed",
|
|
2130
|
-
durationMs
|
|
3220
|
+
durationMs,
|
|
2131
3221
|
attachments,
|
|
2132
|
-
steps
|
|
3222
|
+
steps,
|
|
2133
3223
|
scenarioSteps: flowCtx.__scenarioSteps
|
|
2134
3224
|
};
|
|
2135
3225
|
} catch (error) {
|
|
@@ -2140,20 +3230,23 @@ async function executeFlow(flow, driver, config) {
|
|
|
2140
3230
|
platform,
|
|
2141
3231
|
"failed"
|
|
2142
3232
|
);
|
|
3233
|
+
const steps = stepRecorder.getSteps();
|
|
3234
|
+
const durationMs = Date.now() - start2;
|
|
3235
|
+
await finalizeRecording("failed", attachments, steps, durationMs);
|
|
2143
3236
|
const flowError = error instanceof Error ? error : new Error(String(error));
|
|
2144
3237
|
result = {
|
|
2145
3238
|
name: flow.name,
|
|
2146
3239
|
platform,
|
|
2147
3240
|
status: "failed",
|
|
2148
|
-
durationMs
|
|
3241
|
+
durationMs,
|
|
2149
3242
|
error: classifyError(flowError),
|
|
2150
3243
|
attachments,
|
|
2151
|
-
steps
|
|
3244
|
+
steps,
|
|
2152
3245
|
scenarioSteps: flowCtx.__scenarioSteps
|
|
2153
3246
|
};
|
|
2154
3247
|
if (artifactConfig.captureOnFailure && result.error) {
|
|
2155
3248
|
try {
|
|
2156
|
-
const artDir =
|
|
3249
|
+
const artDir = join5(
|
|
2157
3250
|
artifactConfig.outputDir,
|
|
2158
3251
|
`${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
|
|
2159
3252
|
);
|
|
@@ -2284,7 +3377,9 @@ async function runParallel(config) {
|
|
|
2284
3377
|
}
|
|
2285
3378
|
|
|
2286
3379
|
export {
|
|
3380
|
+
launchDirectCdpBrowser,
|
|
2287
3381
|
makeLightweightCdpDriver,
|
|
3382
|
+
resolveWebEngine,
|
|
2288
3383
|
speculativelyPrelaunchWebBrowser,
|
|
2289
3384
|
buildWebRuntime,
|
|
2290
3385
|
buildWebRuntimePool,
|
|
@@ -2293,8 +3388,13 @@ export {
|
|
|
2293
3388
|
buildLocalAndroidRuntime,
|
|
2294
3389
|
buildLocalIOSRuntime,
|
|
2295
3390
|
classifyError,
|
|
3391
|
+
exportFramesToMp4,
|
|
3392
|
+
startCdpScreencastRecorder,
|
|
3393
|
+
startAndroidVideoRecorder,
|
|
3394
|
+
startIosSimulatorVideoRecorder,
|
|
3395
|
+
buildPlaybackTraceFromSteps,
|
|
2296
3396
|
executeFlow,
|
|
2297
3397
|
orderFlowsLongestFirst,
|
|
2298
3398
|
runParallel
|
|
2299
3399
|
};
|
|
2300
|
-
//# sourceMappingURL=chunk-
|
|
3400
|
+
//# sourceMappingURL=chunk-6B5Y75V4.js.map
|