spana-test 0.7.0 → 0.8.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/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +9 -9
- package/dist/{allure-RNMEYTXS.js → allure-RAEK4SIH.js} +2 -2
- package/dist/allure-RAEK4SIH.js.map +1 -0
- package/dist/{android-4NVTZMHL.js → android-6BOQTMM3.js} +2 -2
- package/dist/app-CgbLADmF.d.ts +1191 -0
- package/dist/{chunk-H27IBIGA.js → chunk-2AFWVHQK.js} +63 -43
- package/dist/chunk-2AFWVHQK.js.map +1 -0
- package/dist/{chunk-JYFPZRCN.js → chunk-2T4K7BJ3.js} +3 -1
- package/dist/chunk-2T4K7BJ3.js.map +1 -0
- package/dist/{chunk-6B5Y75V4.js → chunk-3FXDOTFI.js} +840 -271
- package/dist/chunk-3FXDOTFI.js.map +1 -0
- package/dist/{chunk-T5CROOR7.js → chunk-AJCSETN6.js} +1329 -245
- package/dist/chunk-AJCSETN6.js.map +1 -0
- package/dist/chunk-JPZCZHL4.js +79 -0
- package/dist/chunk-JPZCZHL4.js.map +1 -0
- package/dist/{chunk-RURZVMZ7.js → chunk-NS2HLJO4.js} +3 -3
- package/dist/{chunk-2IXXEXTL.js → chunk-PMXSU5MS.js} +2 -2
- package/dist/{chunk-HYSTRWYN.js → chunk-QP4MDUBY.js} +4 -4
- package/dist/chunk-RKYKRGHB.js +236 -0
- package/dist/chunk-RKYKRGHB.js.map +1 -0
- package/dist/{chunk-HCG4CJKR.js → chunk-SF7UYW4I.js} +3 -3
- package/dist/{chunk-T3EBOYLS.js → chunk-SNL4X67N.js} +1043 -99
- package/dist/chunk-SNL4X67N.js.map +1 -0
- package/dist/{chunk-KNSAHEXI.js → chunk-WKVU24B6.js} +8 -8
- package/dist/{chunk-S5JNNDXS.js → chunk-WV3ALL3H.js} +65 -37
- package/dist/chunk-WV3ALL3H.js.map +1 -0
- package/dist/cli.js +23 -11
- package/dist/cli.js.map +1 -1
- package/dist/config-loader-5FU45FXK.js +9 -0
- package/dist/{console-MI2XB5RG.js → console-BGAK7Z2L.js} +11 -1
- package/dist/{console-MI2XB5RG.js.map → console-BGAK7Z2L.js.map} +1 -1
- package/dist/{daemon-manager-FBISTX24.js → daemon-manager-DDYQITPD.js} +4 -2
- package/dist/{discover-LHEBSUIP.js → discover-RLSKEBAX.js} +5 -5
- package/dist/{doctor-command-WPEVZEZ4.js → doctor-command-HEQQOYUR.js} +26 -18
- package/dist/doctor-command-HEQQOYUR.js.map +1 -0
- package/dist/{flow-g6AICPAl.d.ts → flow-Md5xLwbX.d.ts} +3 -29
- package/dist/gherkin/steps.d.ts +2 -2
- package/dist/{html-IKCTZH2U.js → html-JO2YNRWX.js} +3 -3
- package/dist/html-JO2YNRWX.js.map +1 -0
- package/dist/index.d.ts +184 -20
- package/dist/index.js +230 -147
- package/dist/index.js.map +1 -1
- package/dist/{installer-VUPFWP5X.js → installer-IYGMG7LS.js} +4 -4
- package/dist/{ios-JPK43TFZ.js → ios-Y4TO5MBR.js} +7 -3
- package/dist/{server-IGLBFEU7.js → server-4PEREPHY.js} +2 -2
- package/dist/{server-EBPYK3VE.js → server-JPNH33MX.js} +50 -36
- package/dist/server-JPNH33MX.js.map +1 -0
- package/dist/{session-cJ_tZjCL.d.ts → session-D9e30RVS.d.ts} +1 -1
- package/dist/session-V4PYJXNB.js +18 -0
- package/dist/{studio-command-FLA5HKRK.js → studio-command-JOIFCOHC.js} +2 -2
- package/dist/{test-command-P5W7UD52.js → test-command-JCO2HPYI.js} +221 -27
- package/dist/test-command-JCO2HPYI.js.map +1 -0
- package/native/darwin-arm64/libspana_native.dylib +0 -0
- package/native/darwin-x64/libspana_native.dylib +0 -0
- package/native/linux-arm64/libspana_native.so +0 -0
- package/native/linux-x64/libspana_native.so +0 -0
- package/native/win32-x64/spana_native.dll +0 -0
- package/package.json +1 -1
- package/studio-dist/assets/index-CBFsOh-9.js +193 -0
- package/studio-dist/assets/index-DH_18EyL.css +1 -0
- package/studio-dist/index.html +2 -2
- package/dist/allure-RNMEYTXS.js.map +0 -1
- package/dist/app-D_UyZBsl.d.ts +0 -915
- package/dist/chunk-6B5Y75V4.js.map +0 -1
- package/dist/chunk-DTNK54C2.js +0 -127
- package/dist/chunk-DTNK54C2.js.map +0 -1
- package/dist/chunk-H27IBIGA.js.map +0 -1
- package/dist/chunk-JYFPZRCN.js.map +0 -1
- package/dist/chunk-OBCFACUW.js +0 -28
- package/dist/chunk-OBCFACUW.js.map +0 -1
- package/dist/chunk-S5JNNDXS.js.map +0 -1
- package/dist/chunk-T3EBOYLS.js.map +0 -1
- package/dist/chunk-T5CROOR7.js.map +0 -1
- package/dist/config-loader-NIDQGP3K.js +0 -9
- package/dist/doctor-command-WPEVZEZ4.js.map +0 -1
- package/dist/html-IKCTZH2U.js.map +0 -1
- package/dist/server-EBPYK3VE.js.map +0 -1
- package/dist/session-QRWH3SPW.js +0 -18
- package/dist/test-command-P5W7UD52.js.map +0 -1
- package/studio-dist/assets/index-C-Io44gy.js +0 -193
- package/studio-dist/assets/index-DfM9lK4p.css +0 -1
- /package/dist/{android-4NVTZMHL.js.map → android-6BOQTMM3.js.map} +0 -0
- /package/dist/{chunk-RURZVMZ7.js.map → chunk-NS2HLJO4.js.map} +0 -0
- /package/dist/{chunk-2IXXEXTL.js.map → chunk-PMXSU5MS.js.map} +0 -0
- /package/dist/{chunk-HYSTRWYN.js.map → chunk-QP4MDUBY.js.map} +0 -0
- /package/dist/{chunk-HCG4CJKR.js.map → chunk-SF7UYW4I.js.map} +0 -0
- /package/dist/{chunk-KNSAHEXI.js.map → chunk-WKVU24B6.js.map} +0 -0
- /package/dist/{config-loader-NIDQGP3K.js.map → config-loader-5FU45FXK.js.map} +0 -0
- /package/dist/{daemon-manager-FBISTX24.js.map → daemon-manager-DDYQITPD.js.map} +0 -0
- /package/dist/{discover-LHEBSUIP.js.map → discover-RLSKEBAX.js.map} +0 -0
- /package/dist/{installer-VUPFWP5X.js.map → installer-IYGMG7LS.js.map} +0 -0
- /package/dist/{ios-JPK43TFZ.js.map → ios-Y4TO5MBR.js.map} +0 -0
- /package/dist/{server-IGLBFEU7.js.map → server-4PEREPHY.js.map} +0 -0
- /package/dist/{session-QRWH3SPW.js.map → session-V4PYJXNB.js.map} +0 -0
- /package/dist/{studio-command-FLA5HKRK.js.map → studio-command-JOIFCOHC.js.map} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
connectPlaywrightOverCDP,
|
|
3
3
|
connectPlaywrightOverWS,
|
|
4
|
-
createCoordinator,
|
|
5
4
|
createPromiseApp,
|
|
5
|
+
createPromiseExpect,
|
|
6
6
|
createUiAutomator2Driver,
|
|
7
7
|
createWDADriver,
|
|
8
8
|
ensureWarmBrowserDaemon,
|
|
@@ -16,144 +16,41 @@ import {
|
|
|
16
16
|
parseWebHierarchy,
|
|
17
17
|
resolveNetworkConditions,
|
|
18
18
|
setupUiAutomator2
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-AJCSETN6.js";
|
|
20
20
|
import {
|
|
21
21
|
CdpDomChannel,
|
|
22
22
|
DriverError,
|
|
23
|
+
SPANA_INJECTED_RUNTIME_SCRIPT,
|
|
24
|
+
buildDomFindElementScript,
|
|
23
25
|
createSpanaBridgeChannel,
|
|
24
26
|
makeElectrobunDriver
|
|
25
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-SNL4X67N.js";
|
|
26
28
|
import {
|
|
27
29
|
setupWDA
|
|
28
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-QP4MDUBY.js";
|
|
29
31
|
import {
|
|
30
32
|
getHealthyWarmDaemon,
|
|
31
33
|
registerWarmDaemon,
|
|
32
34
|
updateWarmDaemonSession
|
|
33
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-RKYKRGHB.js";
|
|
34
36
|
import {
|
|
35
37
|
connectPhysicalDevice,
|
|
36
38
|
ensureAppInstalled,
|
|
37
39
|
ensureIOSSimulator,
|
|
38
40
|
firstIOSPhysicalDevice
|
|
39
|
-
} from "./chunk-
|
|
41
|
+
} from "./chunk-WV3ALL3H.js";
|
|
40
42
|
import {
|
|
43
|
+
allocateFreePort,
|
|
41
44
|
allocatePort
|
|
42
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-JPZCZHL4.js";
|
|
43
46
|
import {
|
|
44
47
|
adbReverse,
|
|
45
48
|
adbReverseRemove,
|
|
46
49
|
ensureAndroidDevice
|
|
47
|
-
} from "./chunk-
|
|
48
|
-
|
|
49
|
-
// src/api/expect.ts
|
|
50
|
-
import { Effect } from "effect";
|
|
51
|
-
function selectorToCss(sel) {
|
|
52
|
-
if (typeof sel === "string") return sel;
|
|
53
|
-
if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
|
|
54
|
-
return `[data-testid="${sel.testID}"]`;
|
|
55
|
-
if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
|
|
56
|
-
return `[aria-label="${sel.accessibilityLabel}"]`;
|
|
57
|
-
return "";
|
|
58
|
-
}
|
|
59
|
-
function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
|
|
60
|
-
const ctx = flowContext ?? {
|
|
61
|
-
flowFilePath: "",
|
|
62
|
-
flowName: "unknown",
|
|
63
|
-
platform: "web"
|
|
64
|
-
};
|
|
65
|
-
const coord = createCoordinator(driver, config);
|
|
66
|
-
const run = (effect) => Effect.runPromise(effect);
|
|
67
|
-
const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
|
|
68
|
-
return (selector) => ({
|
|
69
|
-
toBeVisible: (opts) => runStep(
|
|
70
|
-
"expect.toBeVisible",
|
|
71
|
-
selector,
|
|
72
|
-
() => run(coord.assertVisible(selector, opts)).then(() => {
|
|
73
|
-
})
|
|
74
|
-
),
|
|
75
|
-
toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
|
|
76
|
-
toHaveText: (expected, opts) => runStep(
|
|
77
|
-
`expect.toHaveText(${JSON.stringify(expected)})`,
|
|
78
|
-
selector,
|
|
79
|
-
() => run(coord.assertText(selector, expected, opts))
|
|
80
|
-
),
|
|
81
|
-
toMatchText: (pattern, opts) => runStep(
|
|
82
|
-
`expect.toMatchText(${pattern})`,
|
|
83
|
-
selector,
|
|
84
|
-
() => run(coord.assertMatchesText(selector, pattern, opts))
|
|
85
|
-
),
|
|
86
|
-
toHaveValue: (expected, opts) => runStep(
|
|
87
|
-
`expect.toHaveValue(${JSON.stringify(expected)})`,
|
|
88
|
-
selector,
|
|
89
|
-
() => run(coord.assertValue(selector, expected, opts))
|
|
90
|
-
),
|
|
91
|
-
toHaveAttribute: (name, value, opts) => runStep(
|
|
92
|
-
`expect.toHaveAttribute(${JSON.stringify(name)})`,
|
|
93
|
-
selector,
|
|
94
|
-
() => run(coord.assertAttribute(selector, name, value, opts))
|
|
95
|
-
),
|
|
96
|
-
toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
|
|
97
|
-
toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
|
|
98
|
-
toContainText: (expected, opts) => runStep(
|
|
99
|
-
`expect.toContainText(${JSON.stringify(expected)})`,
|
|
100
|
-
selector,
|
|
101
|
-
() => run(coord.assertContainsText(selector, expected, opts))
|
|
102
|
-
),
|
|
103
|
-
toMatchScreenshot: (name, options) => runStep(
|
|
104
|
-
`expect.toMatchScreenshot(${JSON.stringify(name)})`,
|
|
105
|
-
selector,
|
|
106
|
-
() => run(
|
|
107
|
-
coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
|
|
108
|
-
threshold: options?.threshold ?? visualRegression?.threshold,
|
|
109
|
-
maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
|
|
110
|
-
mask: [],
|
|
111
|
-
updateBaselines: ctx.updateBaselines,
|
|
112
|
-
baselinesDir: visualRegression?.baselinesDir
|
|
113
|
-
})
|
|
114
|
-
)
|
|
115
|
-
),
|
|
116
|
-
toPassAccessibilityAudit: (options) => {
|
|
117
|
-
const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
|
|
118
|
-
const targetCss = selectorToCss(selector);
|
|
119
|
-
return runStep(
|
|
120
|
-
"expect.toPassAccessibilityAudit",
|
|
121
|
-
selector,
|
|
122
|
-
() => run(
|
|
123
|
-
coord.assertAccessibilityAudit(ctx.platform, {
|
|
124
|
-
severity: options?.severity,
|
|
125
|
-
rules: options?.rules,
|
|
126
|
-
targetSelector: targetCss || void 0,
|
|
127
|
-
excludeSelectors: excludeCss
|
|
128
|
-
})
|
|
129
|
-
)
|
|
130
|
-
);
|
|
131
|
-
},
|
|
132
|
-
toHaveAccessibilityLabel: (expected) => runStep(
|
|
133
|
-
`expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
|
|
134
|
-
selector,
|
|
135
|
-
() => run(coord.assertAccessibilityLabel(selector, expected))
|
|
136
|
-
),
|
|
137
|
-
toBeFocusable: () => runStep(
|
|
138
|
-
"expect.toBeFocusable",
|
|
139
|
-
selector,
|
|
140
|
-
() => run(coord.assertFocusable(selector, ctx.platform))
|
|
141
|
-
),
|
|
142
|
-
toHaveRole: (expected) => runStep(
|
|
143
|
-
`expect.toHaveRole(${JSON.stringify(expected)})`,
|
|
144
|
-
selector,
|
|
145
|
-
() => run(coord.assertRole(selector, expected, ctx.platform))
|
|
146
|
-
),
|
|
147
|
-
toHaveMinTouchTarget: (size = 44) => runStep(
|
|
148
|
-
`expect.toHaveMinTouchTarget(${size})`,
|
|
149
|
-
selector,
|
|
150
|
-
() => run(coord.assertMinTouchTarget(selector, size))
|
|
151
|
-
)
|
|
152
|
-
});
|
|
153
|
-
}
|
|
50
|
+
} from "./chunk-2AFWVHQK.js";
|
|
154
51
|
|
|
155
52
|
// src/core/session-manager.ts
|
|
156
|
-
import { Effect
|
|
53
|
+
import { Effect } from "effect";
|
|
157
54
|
function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
158
55
|
const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
|
|
159
56
|
return {
|
|
@@ -164,7 +61,7 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
164
61
|
}
|
|
165
62
|
const driver = await driverFactory(opts);
|
|
166
63
|
const baseUrl = opts.baseUrl ?? "http://localhost:3000";
|
|
167
|
-
await
|
|
64
|
+
await Effect.runPromise(driver.launchApp(baseUrl));
|
|
168
65
|
const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
|
|
169
66
|
platform: "web"
|
|
170
67
|
});
|
|
@@ -175,12 +72,12 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
|
|
|
175
72
|
app,
|
|
176
73
|
expect,
|
|
177
74
|
async disconnect() {
|
|
178
|
-
await
|
|
75
|
+
await Effect.runPromise(driver.killApp(baseUrl));
|
|
179
76
|
manager.remove(opts.name);
|
|
180
77
|
}
|
|
181
78
|
};
|
|
182
79
|
const cleanup = async () => {
|
|
183
|
-
await
|
|
80
|
+
await Effect.runPromise(driver.killApp(baseUrl));
|
|
184
81
|
};
|
|
185
82
|
manager.register(session, cleanup);
|
|
186
83
|
return session;
|
|
@@ -224,7 +121,7 @@ import { existsSync, mkdtempSync, rmSync } from "fs";
|
|
|
224
121
|
import { copyFile, readFile, writeFile } from "fs/promises";
|
|
225
122
|
import { tmpdir } from "os";
|
|
226
123
|
import { join } from "path";
|
|
227
|
-
import { Effect as
|
|
124
|
+
import { Effect as Effect2 } from "effect";
|
|
228
125
|
var INSTANT_ANIMATIONS_CDP_SCRIPT = `
|
|
229
126
|
(() => {
|
|
230
127
|
const inject = () => {
|
|
@@ -243,7 +140,7 @@ var INSTANT_ANIMATIONS_CDP_SCRIPT = `
|
|
|
243
140
|
`;
|
|
244
141
|
function resolveDirectCdpScopeKey(scope) {
|
|
245
142
|
if (scope && scope.trim().length > 0) return scope.trim();
|
|
246
|
-
const cwdHash = createHash("
|
|
143
|
+
const cwdHash = createHash("sha256").update(process.cwd()).digest("hex").slice(0, 10);
|
|
247
144
|
return `cdp-${cwdHash}`;
|
|
248
145
|
}
|
|
249
146
|
function resolveChromiumExecutable(explicit) {
|
|
@@ -318,7 +215,7 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
318
215
|
}
|
|
319
216
|
}
|
|
320
217
|
execPath = resolveChromiumExecutable(execPath);
|
|
321
|
-
const port =
|
|
218
|
+
const port = await allocateFreePort(9350);
|
|
322
219
|
const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
|
|
323
220
|
const chromeArgs = [
|
|
324
221
|
...options.headless !== false ? ["--headless=new"] : [],
|
|
@@ -350,7 +247,17 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
350
247
|
child.unref();
|
|
351
248
|
}
|
|
352
249
|
const httpEndpoint = `http://127.0.0.1:${port}`;
|
|
353
|
-
|
|
250
|
+
let browserWsUrl;
|
|
251
|
+
try {
|
|
252
|
+
browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
|
|
253
|
+
} catch (err) {
|
|
254
|
+
try {
|
|
255
|
+
child.kill("SIGKILL");
|
|
256
|
+
} catch {
|
|
257
|
+
}
|
|
258
|
+
rmSync(userDataDir, { recursive: true, force: true });
|
|
259
|
+
throw err;
|
|
260
|
+
}
|
|
354
261
|
if (options.warmBrowser) {
|
|
355
262
|
registerWarmDaemon({
|
|
356
263
|
kind: "chromium",
|
|
@@ -358,6 +265,7 @@ async function launchDirectCdpBrowser(options = {}) {
|
|
|
358
265
|
host: "127.0.0.1",
|
|
359
266
|
port,
|
|
360
267
|
pid: child.pid,
|
|
268
|
+
userDataDir,
|
|
361
269
|
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
362
270
|
});
|
|
363
271
|
}
|
|
@@ -405,6 +313,76 @@ function matchUrl(matcher, url) {
|
|
|
405
313
|
}
|
|
406
314
|
return url.includes(matcher);
|
|
407
315
|
}
|
|
316
|
+
var CDP_SPECIAL_KEYS = {
|
|
317
|
+
Enter: { code: "Enter", keyCode: 13, text: "\r" },
|
|
318
|
+
Backspace: { code: "Backspace", keyCode: 8 },
|
|
319
|
+
Tab: { code: "Tab", keyCode: 9 },
|
|
320
|
+
Escape: { code: "Escape", keyCode: 27 },
|
|
321
|
+
Delete: { code: "Delete", keyCode: 46 },
|
|
322
|
+
ArrowLeft: { code: "ArrowLeft", keyCode: 37 },
|
|
323
|
+
ArrowUp: { code: "ArrowUp", keyCode: 38 },
|
|
324
|
+
ArrowRight: { code: "ArrowRight", keyCode: 39 },
|
|
325
|
+
ArrowDown: { code: "ArrowDown", keyCode: 40 },
|
|
326
|
+
Home: { code: "Home", keyCode: 36 },
|
|
327
|
+
End: { code: "End", keyCode: 35 },
|
|
328
|
+
PageUp: { code: "PageUp", keyCode: 33 },
|
|
329
|
+
PageDown: { code: "PageDown", keyCode: 34 },
|
|
330
|
+
Space: { code: "Space", keyCode: 32, text: " " },
|
|
331
|
+
" ": { code: "Space", keyCode: 32, text: " " }
|
|
332
|
+
};
|
|
333
|
+
function parseCdpKeyDescriptor(rawKey) {
|
|
334
|
+
const parts = rawKey.split("+");
|
|
335
|
+
let modifiers = 0;
|
|
336
|
+
let baseKey = rawKey;
|
|
337
|
+
if (parts.length > 1) {
|
|
338
|
+
baseKey = parts[parts.length - 1] ?? rawKey;
|
|
339
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
340
|
+
const mod = (parts[i] ?? "").toLowerCase();
|
|
341
|
+
if (mod === "alt" || mod === "option") modifiers |= 1;
|
|
342
|
+
else if (mod === "control" || mod === "ctrl") modifiers |= 2;
|
|
343
|
+
else if (mod === "meta" || mod === "cmd" || mod === "command") modifiers |= 4;
|
|
344
|
+
else if (mod === "shift") modifiers |= 8;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const special = CDP_SPECIAL_KEYS[baseKey];
|
|
348
|
+
if (special) {
|
|
349
|
+
return {
|
|
350
|
+
key: baseKey === "Space" ? " " : baseKey,
|
|
351
|
+
code: special.code,
|
|
352
|
+
windowsVirtualKeyCode: special.keyCode,
|
|
353
|
+
modifiers,
|
|
354
|
+
...special.text ? { text: special.text } : {}
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
if (baseKey.length === 1) {
|
|
358
|
+
const upper = baseKey.toUpperCase();
|
|
359
|
+
const charCode = upper.charCodeAt(0);
|
|
360
|
+
const isLetter = charCode >= 65 && charCode <= 90;
|
|
361
|
+
const isDigit = charCode >= 48 && charCode <= 57;
|
|
362
|
+
const commands = [];
|
|
363
|
+
if ((modifiers & (2 | 4)) !== 0) {
|
|
364
|
+
if (baseKey.toLowerCase() === "a") commands.push("selectAll");
|
|
365
|
+
else if (baseKey.toLowerCase() === "c") commands.push("copy");
|
|
366
|
+
else if (baseKey.toLowerCase() === "v") commands.push("paste");
|
|
367
|
+
else if (baseKey.toLowerCase() === "x") commands.push("cut");
|
|
368
|
+
else if (baseKey.toLowerCase() === "z") commands.push("undo");
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
key: baseKey,
|
|
372
|
+
code: isLetter ? `Key${upper}` : isDigit ? `Digit${baseKey}` : "",
|
|
373
|
+
windowsVirtualKeyCode: charCode,
|
|
374
|
+
modifiers,
|
|
375
|
+
...modifiers === 0 || modifiers === 8 ? { text: baseKey } : {},
|
|
376
|
+
...commands.length > 0 ? { commands } : {}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
key: baseKey,
|
|
381
|
+
code: baseKey,
|
|
382
|
+
windowsVirtualKeyCode: 0,
|
|
383
|
+
modifiers
|
|
384
|
+
};
|
|
385
|
+
}
|
|
408
386
|
var RESOURCE_BLOCK_PATTERNS = {
|
|
409
387
|
image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
|
|
410
388
|
font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
|
|
@@ -412,7 +390,7 @@ var RESOURCE_BLOCK_PATTERNS = {
|
|
|
412
390
|
stylesheet: ["*.css"]
|
|
413
391
|
};
|
|
414
392
|
function makeLightweightCdpDriver(options) {
|
|
415
|
-
return
|
|
393
|
+
return Effect2.gen(function* () {
|
|
416
394
|
const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
|
|
417
395
|
const useContexts = Boolean(
|
|
418
396
|
options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
|
|
@@ -421,7 +399,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
421
399
|
const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
|
|
422
400
|
let connectWsUrl = isWs ? options.cdpUrl : void 0;
|
|
423
401
|
if (useContexts && !connectWsUrl) {
|
|
424
|
-
connectWsUrl = yield*
|
|
402
|
+
connectWsUrl = yield* Effect2.tryPromise({
|
|
425
403
|
try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
|
|
426
404
|
catch: (e) => new DriverError({
|
|
427
405
|
message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
|
|
@@ -434,7 +412,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
434
412
|
fetchFn: options.fetchFn,
|
|
435
413
|
createWebSocket: options.createWebSocket
|
|
436
414
|
});
|
|
437
|
-
yield*
|
|
415
|
+
yield* Effect2.tryPromise({
|
|
438
416
|
try: () => cdpChannel.connect(),
|
|
439
417
|
catch: (e) => new DriverError({
|
|
440
418
|
message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
|
|
@@ -499,6 +477,8 @@ function makeLightweightCdpDriver(options) {
|
|
|
499
477
|
);
|
|
500
478
|
return res?.authenticatorId ?? "cdp-virtual-auth-1";
|
|
501
479
|
};
|
|
480
|
+
const useInjectedRuntime = options.useInjectedRuntime ?? !options.createWebSocket;
|
|
481
|
+
cdpChannel.enableInjectedRuntime(useInjectedRuntime);
|
|
502
482
|
const configureSession = async (sessionId, storageStatePath) => {
|
|
503
483
|
const state = await loadStorageStateFile(storageStatePath);
|
|
504
484
|
const needsNetworkDomain = Boolean(
|
|
@@ -509,6 +489,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
509
489
|
}),
|
|
510
490
|
cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
|
|
511
491
|
}),
|
|
492
|
+
...useInjectedRuntime ? [
|
|
493
|
+
cdpChannel.sendCommand(
|
|
494
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
495
|
+
{ source: SPANA_INJECTED_RUNTIME_SCRIPT },
|
|
496
|
+
sessionId
|
|
497
|
+
).catch(() => {
|
|
498
|
+
})
|
|
499
|
+
] : [],
|
|
512
500
|
cdpChannel.sendCommand(
|
|
513
501
|
"Target.setAutoAttach",
|
|
514
502
|
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
|
|
@@ -619,7 +607,9 @@ function makeLightweightCdpDriver(options) {
|
|
|
619
607
|
backgroundDisposals.push(p);
|
|
620
608
|
};
|
|
621
609
|
const schedulePrefetch = () => {
|
|
622
|
-
if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise)
|
|
610
|
+
if (!useContexts || !options.freshContextPerFlow || options.contextIsolation === "hot-cache" || prefetchedSlotPromise) {
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
623
613
|
prefetchedSlotPromise = createContextSlot(options.storageState);
|
|
624
614
|
prefetchedSlotPromise.catch(() => {
|
|
625
615
|
prefetchedSlotPromise = void 0;
|
|
@@ -635,6 +625,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
635
625
|
});
|
|
636
626
|
void cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
|
|
637
627
|
});
|
|
628
|
+
if (useInjectedRuntime) {
|
|
629
|
+
void cdpChannel.sendCommand(
|
|
630
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
631
|
+
{ source: SPANA_INJECTED_RUNTIME_SCRIPT },
|
|
632
|
+
childSid
|
|
633
|
+
).catch(() => {
|
|
634
|
+
});
|
|
635
|
+
}
|
|
638
636
|
}
|
|
639
637
|
});
|
|
640
638
|
cdpChannel.onEvent("Target.detachedFromTarget", (params) => {
|
|
@@ -713,7 +711,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
713
711
|
});
|
|
714
712
|
});
|
|
715
713
|
if (useContexts) {
|
|
716
|
-
activeSlot = yield*
|
|
714
|
+
activeSlot = yield* Effect2.tryPromise({
|
|
717
715
|
try: () => createContextSlot(options.storageState),
|
|
718
716
|
catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
|
|
719
717
|
});
|
|
@@ -729,7 +727,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
729
727
|
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
730
728
|
return;
|
|
731
729
|
}
|
|
732
|
-
const waitUntil = options.waitUntil ?? "
|
|
730
|
+
const waitUntil = options.waitUntil ?? "domcontentloaded";
|
|
733
731
|
const targetSid = activeSlot?.sessionId;
|
|
734
732
|
if (waitUntil === "commit" || target === "about:blank") {
|
|
735
733
|
await cdpChannel.sendCommand("Page.navigate", { url: target });
|
|
@@ -753,34 +751,62 @@ function makeLightweightCdpDriver(options) {
|
|
|
753
751
|
};
|
|
754
752
|
const service = {
|
|
755
753
|
domChannel: cdpChannel,
|
|
756
|
-
beginFlow: (_flowName) =>
|
|
754
|
+
beginFlow: (_flowName) => Effect2.tryPromise({
|
|
757
755
|
try: async () => {
|
|
758
756
|
consoleLogs.length = 0;
|
|
759
757
|
jsErrors.length = 0;
|
|
760
758
|
cdpChannel.clearChildSessions();
|
|
761
759
|
if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
760
|
+
if (options.contextIsolation === "hot-cache" && activeSlot) {
|
|
761
|
+
const origin = options.baseUrl ? (() => {
|
|
762
|
+
try {
|
|
763
|
+
return new URL(options.baseUrl).origin;
|
|
764
|
+
} catch {
|
|
765
|
+
return "*";
|
|
766
|
+
}
|
|
767
|
+
})() : "*";
|
|
768
|
+
await Promise.all([
|
|
769
|
+
cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
770
|
+
}),
|
|
771
|
+
cdpChannel.sendCommand("Storage.clearDataForOrigin", {
|
|
772
|
+
origin,
|
|
773
|
+
storageTypes: "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers"
|
|
774
|
+
}).catch(() => {
|
|
775
|
+
}),
|
|
776
|
+
cdpChannel.evaluate("try { localStorage.clear(); sessionStorage.clear(); } catch {}").catch(() => {
|
|
777
|
+
}),
|
|
778
|
+
cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }).catch(() => {
|
|
779
|
+
})
|
|
780
|
+
]);
|
|
781
|
+
const state = await loadStorageStateFile(options.storageState);
|
|
782
|
+
if (state?.cookies && state.cookies.length > 0) {
|
|
783
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
} else {
|
|
787
|
+
const previousSlot = activeSlot;
|
|
788
|
+
const pending = prefetchedSlotPromise;
|
|
789
|
+
prefetchedSlotPromise = void 0;
|
|
790
|
+
activeSlot = pending ? await pending : await createContextSlot(options.storageState);
|
|
791
|
+
cdpChannel.setSessionId(activeSlot.sessionId);
|
|
792
|
+
activeAuthenticatorId = activeSlot.authenticatorId;
|
|
793
|
+
if (previousSlot) {
|
|
794
|
+
disposeSlotInBackground(previousSlot);
|
|
795
|
+
}
|
|
770
796
|
}
|
|
771
797
|
}
|
|
772
798
|
hasRunFirstFlow = true;
|
|
773
799
|
},
|
|
774
800
|
catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
|
|
775
801
|
}),
|
|
776
|
-
dumpHierarchy: () =>
|
|
802
|
+
dumpHierarchy: () => Effect2.tryPromise({
|
|
777
803
|
try: async () => {
|
|
778
804
|
const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
|
|
779
805
|
return raw ?? "{}";
|
|
780
806
|
},
|
|
781
807
|
catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
|
|
782
808
|
}),
|
|
783
|
-
tapAtCoordinate: (x, y) =>
|
|
809
|
+
tapAtCoordinate: (x, y) => Effect2.tryPromise({
|
|
784
810
|
try: async () => {
|
|
785
811
|
await Promise.all([
|
|
786
812
|
cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
@@ -806,7 +832,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
806
832
|
},
|
|
807
833
|
catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
|
|
808
834
|
}),
|
|
809
|
-
doubleTapAtCoordinate: (x, y) =>
|
|
835
|
+
doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
|
|
810
836
|
try: async () => {
|
|
811
837
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
812
838
|
type: "mousePressed",
|
|
@@ -825,7 +851,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
825
851
|
},
|
|
826
852
|
catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
|
|
827
853
|
}),
|
|
828
|
-
longPressAtCoordinate: (x, y, duration) =>
|
|
854
|
+
longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
|
|
829
855
|
try: async () => {
|
|
830
856
|
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
831
857
|
type: "mousePressed",
|
|
@@ -845,7 +871,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
845
871
|
},
|
|
846
872
|
catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
|
|
847
873
|
}),
|
|
848
|
-
swipe: (startX, startY, endX, endY) =>
|
|
874
|
+
swipe: (startX, startY, endX, endY) => Effect2.tryPromise({
|
|
849
875
|
try: async () => {
|
|
850
876
|
const dx = startX - endX;
|
|
851
877
|
const dy = startY - endY;
|
|
@@ -853,21 +879,77 @@ function makeLightweightCdpDriver(options) {
|
|
|
853
879
|
},
|
|
854
880
|
catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
|
|
855
881
|
}),
|
|
856
|
-
inputText: (text) =>
|
|
882
|
+
inputText: (text) => Effect2.tryPromise({
|
|
857
883
|
try: async () => {
|
|
858
884
|
await cdpChannel.sendCommand("Input.insertText", { text });
|
|
859
885
|
},
|
|
860
886
|
catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
|
|
861
887
|
}),
|
|
862
|
-
pressKey: (key) =>
|
|
888
|
+
pressKey: (key) => Effect2.tryPromise({
|
|
863
889
|
try: async () => {
|
|
864
|
-
|
|
865
|
-
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
890
|
+
const desc = parseCdpKeyDescriptor(key);
|
|
891
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
892
|
+
type: desc.text ? "keyDown" : "rawKeyDown",
|
|
893
|
+
key: desc.key,
|
|
894
|
+
...desc.code ? { code: desc.code } : {},
|
|
895
|
+
...desc.windowsVirtualKeyCode ? {
|
|
896
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
897
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
898
|
+
} : {},
|
|
899
|
+
modifiers: desc.modifiers,
|
|
900
|
+
...desc.text ? { text: desc.text, unmodifiedText: desc.text } : {},
|
|
901
|
+
...desc.commands ? { commands: desc.commands } : {}
|
|
902
|
+
});
|
|
903
|
+
await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
|
|
904
|
+
type: "keyUp",
|
|
905
|
+
key: desc.key,
|
|
906
|
+
...desc.code ? { code: desc.code } : {},
|
|
907
|
+
...desc.windowsVirtualKeyCode ? {
|
|
908
|
+
windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
|
|
909
|
+
nativeVirtualKeyCode: desc.windowsVirtualKeyCode
|
|
910
|
+
} : {},
|
|
911
|
+
modifiers: desc.modifiers
|
|
912
|
+
});
|
|
866
913
|
},
|
|
867
914
|
catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
|
|
868
915
|
}),
|
|
869
|
-
|
|
870
|
-
|
|
916
|
+
hoverAtCoordinate: (x, y) => Effect2.tryPromise({
|
|
917
|
+
try: async () => {
|
|
918
|
+
await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
|
|
919
|
+
type: "mouseMoved",
|
|
920
|
+
x,
|
|
921
|
+
y
|
|
922
|
+
});
|
|
923
|
+
},
|
|
924
|
+
catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
|
|
925
|
+
}),
|
|
926
|
+
reload: (reloadOpts) => Effect2.tryPromise({
|
|
927
|
+
try: async () => {
|
|
928
|
+
const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
|
|
929
|
+
const targetSid = activeSlot?.sessionId;
|
|
930
|
+
const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
|
|
931
|
+
const waiter = cdpChannel.waitForEvent(
|
|
932
|
+
eventName,
|
|
933
|
+
15e3,
|
|
934
|
+
(_p, sid) => !targetSid || !sid || sid === targetSid
|
|
935
|
+
);
|
|
936
|
+
await cdpChannel.sendCommand("Page.reload", {});
|
|
937
|
+
await waiter.catch(() => {
|
|
938
|
+
});
|
|
939
|
+
},
|
|
940
|
+
catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
|
|
941
|
+
}),
|
|
942
|
+
getUrl: () => Effect2.tryPromise({
|
|
943
|
+
try: async () => {
|
|
944
|
+
const url = await cdpChannel.evaluate(
|
|
945
|
+
"typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
|
|
946
|
+
);
|
|
947
|
+
return url ?? "";
|
|
948
|
+
},
|
|
949
|
+
catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
|
|
950
|
+
}),
|
|
951
|
+
hideKeyboard: () => Effect2.void,
|
|
952
|
+
takeScreenshot: () => Effect2.tryPromise({
|
|
871
953
|
try: async () => {
|
|
872
954
|
const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
|
|
873
955
|
format: "png"
|
|
@@ -876,7 +958,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
876
958
|
},
|
|
877
959
|
catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
|
|
878
960
|
}),
|
|
879
|
-
getDeviceInfo: () =>
|
|
961
|
+
getDeviceInfo: () => Effect2.succeed({
|
|
880
962
|
platform: "web",
|
|
881
963
|
deviceId: `${label}:${options.cdpUrl}`,
|
|
882
964
|
name: `${label} (CDP-direct)`,
|
|
@@ -885,7 +967,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
885
967
|
screenHeight: height,
|
|
886
968
|
driverType: "cdp"
|
|
887
969
|
}),
|
|
888
|
-
launchApp: (url, opts) =>
|
|
970
|
+
launchApp: (url, opts) => Effect2.tryPromise({
|
|
889
971
|
try: async () => {
|
|
890
972
|
if (opts?.clearState) {
|
|
891
973
|
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
@@ -898,11 +980,11 @@ function makeLightweightCdpDriver(options) {
|
|
|
898
980
|
},
|
|
899
981
|
catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
|
|
900
982
|
}),
|
|
901
|
-
stopApp: () =>
|
|
983
|
+
stopApp: () => Effect2.tryPromise({
|
|
902
984
|
try: () => navigate("about:blank"),
|
|
903
985
|
catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
|
|
904
986
|
}),
|
|
905
|
-
killApp: () =>
|
|
987
|
+
killApp: () => Effect2.tryPromise({
|
|
906
988
|
try: async () => {
|
|
907
989
|
const pendingPrefetch = prefetchedSlotPromise;
|
|
908
990
|
prefetchedSlotPromise = void 0;
|
|
@@ -935,7 +1017,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
935
1017
|
},
|
|
936
1018
|
catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
|
|
937
1019
|
}),
|
|
938
|
-
clearAppState: () =>
|
|
1020
|
+
clearAppState: () => Effect2.tryPromise({
|
|
939
1021
|
try: async () => {
|
|
940
1022
|
await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
|
|
941
1023
|
});
|
|
@@ -945,17 +1027,17 @@ function makeLightweightCdpDriver(options) {
|
|
|
945
1027
|
},
|
|
946
1028
|
catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
|
|
947
1029
|
}),
|
|
948
|
-
openLink: (url) =>
|
|
1030
|
+
openLink: (url) => Effect2.tryPromise({
|
|
949
1031
|
try: () => navigate(url),
|
|
950
1032
|
catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
|
|
951
1033
|
}),
|
|
952
|
-
back: () =>
|
|
1034
|
+
back: () => Effect2.tryPromise({
|
|
953
1035
|
try: async () => {
|
|
954
1036
|
await cdpChannel.evaluate("window.history.back()");
|
|
955
1037
|
},
|
|
956
1038
|
catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
|
|
957
1039
|
}),
|
|
958
|
-
evaluate: (fn, ...args) =>
|
|
1040
|
+
evaluate: (fn, ...args) => Effect2.tryPromise({
|
|
959
1041
|
try: async () => {
|
|
960
1042
|
if (typeof fn === "string") {
|
|
961
1043
|
return await cdpChannel.evaluate(fn);
|
|
@@ -971,21 +1053,34 @@ function makeLightweightCdpDriver(options) {
|
|
|
971
1053
|
sessionId: activeSlot?.sessionId ?? null,
|
|
972
1054
|
browserContextId: activeSlot?.browserContextId ?? null
|
|
973
1055
|
}),
|
|
974
|
-
|
|
1056
|
+
getCdpSession: () => ({
|
|
1057
|
+
send: (method, params) => cdpChannel.sendCommand(method, params ?? {}),
|
|
1058
|
+
on: (event, listener) => cdpChannel.onEvent(event, (params, sid) => {
|
|
1059
|
+
if (activeSlot && sid && sid !== activeSlot.sessionId) return;
|
|
1060
|
+
listener(params ?? {});
|
|
1061
|
+
}),
|
|
1062
|
+
get sessionId() {
|
|
1063
|
+
return activeSlot?.sessionId;
|
|
1064
|
+
},
|
|
1065
|
+
get browserContextId() {
|
|
1066
|
+
return activeSlot?.browserContextId;
|
|
1067
|
+
}
|
|
1068
|
+
}),
|
|
1069
|
+
mockNetwork: (matcher, response) => Effect2.tryPromise({
|
|
975
1070
|
try: async () => {
|
|
976
1071
|
routeRules.push({ kind: "mock", matcher, response });
|
|
977
1072
|
await ensureFetchIntercept();
|
|
978
1073
|
},
|
|
979
1074
|
catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
|
|
980
1075
|
}),
|
|
981
|
-
blockNetwork: (matcher) =>
|
|
1076
|
+
blockNetwork: (matcher) => Effect2.tryPromise({
|
|
982
1077
|
try: async () => {
|
|
983
1078
|
routeRules.push({ kind: "block", matcher });
|
|
984
1079
|
await ensureFetchIntercept();
|
|
985
1080
|
},
|
|
986
1081
|
catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
|
|
987
1082
|
}),
|
|
988
|
-
clearNetworkMocks: () =>
|
|
1083
|
+
clearNetworkMocks: () => Effect2.tryPromise({
|
|
989
1084
|
try: async () => {
|
|
990
1085
|
routeRules.length = 0;
|
|
991
1086
|
if (fetchInterceptEnabled) {
|
|
@@ -996,14 +1091,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
996
1091
|
},
|
|
997
1092
|
catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
|
|
998
1093
|
}),
|
|
999
|
-
saveCookies: (path) =>
|
|
1094
|
+
saveCookies: (path) => Effect2.tryPromise({
|
|
1000
1095
|
try: async () => {
|
|
1001
1096
|
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
1002
1097
|
await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
|
|
1003
1098
|
},
|
|
1004
1099
|
catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
|
|
1005
1100
|
}),
|
|
1006
|
-
loadCookies: (path) =>
|
|
1101
|
+
loadCookies: (path) => Effect2.tryPromise({
|
|
1007
1102
|
try: async () => {
|
|
1008
1103
|
const cookies = JSON.parse(await readFile(path, "utf8"));
|
|
1009
1104
|
if (Array.isArray(cookies)) {
|
|
@@ -1012,7 +1107,116 @@ function makeLightweightCdpDriver(options) {
|
|
|
1012
1107
|
},
|
|
1013
1108
|
catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
|
|
1014
1109
|
}),
|
|
1015
|
-
|
|
1110
|
+
getCookies: (urls) => Effect2.tryPromise({
|
|
1111
|
+
try: async () => {
|
|
1112
|
+
const res = await cdpChannel.sendCommand(
|
|
1113
|
+
"Network.getCookies",
|
|
1114
|
+
urls && urls.length > 0 ? { urls } : {}
|
|
1115
|
+
);
|
|
1116
|
+
return Array.isArray(res?.cookies) ? res.cookies : [];
|
|
1117
|
+
},
|
|
1118
|
+
catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
|
|
1119
|
+
}),
|
|
1120
|
+
setCookies: (cookies) => Effect2.tryPromise({
|
|
1121
|
+
try: async () => {
|
|
1122
|
+
if (cookies.length === 0) return;
|
|
1123
|
+
await cdpChannel.sendCommand("Network.setCookies", { cookies });
|
|
1124
|
+
},
|
|
1125
|
+
catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
|
|
1126
|
+
}),
|
|
1127
|
+
clearCookies: () => Effect2.tryPromise({
|
|
1128
|
+
try: async () => {
|
|
1129
|
+
await cdpChannel.sendCommand("Network.clearBrowserCookies");
|
|
1130
|
+
},
|
|
1131
|
+
catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
|
|
1132
|
+
}),
|
|
1133
|
+
waitForResponse: (matcher, waitOpts) => Effect2.tryPromise({
|
|
1134
|
+
try: async () => {
|
|
1135
|
+
const timeoutMs = waitOpts?.timeout ?? 15e3;
|
|
1136
|
+
const targetSid = activeSlot?.sessionId;
|
|
1137
|
+
await cdpChannel.sendCommand("Network.enable").catch(() => {
|
|
1138
|
+
});
|
|
1139
|
+
const requestMethods = /* @__PURE__ */ new Map();
|
|
1140
|
+
return await new Promise((resolve, reject) => {
|
|
1141
|
+
const cleanup = () => {
|
|
1142
|
+
clearTimeout(timer);
|
|
1143
|
+
offReq();
|
|
1144
|
+
offRes();
|
|
1145
|
+
};
|
|
1146
|
+
const timer = setTimeout(() => {
|
|
1147
|
+
cleanup();
|
|
1148
|
+
reject(new Error(`Timed out waiting for response after ${timeoutMs}ms`));
|
|
1149
|
+
}, timeoutMs);
|
|
1150
|
+
const offReq = cdpChannel.onEvent("Network.requestWillBeSent", (params, sid) => {
|
|
1151
|
+
if (targetSid && sid && sid !== targetSid) return;
|
|
1152
|
+
if (params?.requestId && params?.request?.method) {
|
|
1153
|
+
requestMethods.set(String(params.requestId), String(params.request.method));
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
1156
|
+
const offRes = cdpChannel.onEvent("Network.responseReceived", (params, sid) => {
|
|
1157
|
+
if (targetSid && sid && sid !== targetSid) return;
|
|
1158
|
+
const resp = params?.response;
|
|
1159
|
+
if (!resp) return;
|
|
1160
|
+
const requestId = String(params?.requestId ?? "");
|
|
1161
|
+
const rawHeaders = resp.headers ?? {};
|
|
1162
|
+
const headers = {};
|
|
1163
|
+
for (const [k, v] of Object.entries(rawHeaders)) {
|
|
1164
|
+
headers[k.toLowerCase()] = String(v);
|
|
1165
|
+
}
|
|
1166
|
+
const info = {
|
|
1167
|
+
url: String(resp.url ?? ""),
|
|
1168
|
+
status: Number(resp.status ?? 0),
|
|
1169
|
+
statusText: String(resp.statusText ?? ""),
|
|
1170
|
+
headers,
|
|
1171
|
+
method: requestMethods.get(requestId),
|
|
1172
|
+
body: async () => {
|
|
1173
|
+
const bodyRes = await cdpChannel.sendCommand("Network.getResponseBody", {
|
|
1174
|
+
requestId
|
|
1175
|
+
});
|
|
1176
|
+
if (bodyRes?.base64Encoded && bodyRes.body) {
|
|
1177
|
+
return Buffer.from(bodyRes.body, "base64").toString("utf8");
|
|
1178
|
+
}
|
|
1179
|
+
return bodyRes?.body ?? "";
|
|
1180
|
+
},
|
|
1181
|
+
json: async () => {
|
|
1182
|
+
const text = await info.body();
|
|
1183
|
+
return JSON.parse(text);
|
|
1184
|
+
}
|
|
1185
|
+
};
|
|
1186
|
+
const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
|
|
1187
|
+
if (matched) {
|
|
1188
|
+
cleanup();
|
|
1189
|
+
resolve(info);
|
|
1190
|
+
}
|
|
1191
|
+
});
|
|
1192
|
+
});
|
|
1193
|
+
},
|
|
1194
|
+
catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
|
|
1195
|
+
}),
|
|
1196
|
+
createIsolatedContext: (ctxOpts) => Effect2.tryPromise({
|
|
1197
|
+
try: async () => {
|
|
1198
|
+
const childDriver = await Effect2.runPromise(
|
|
1199
|
+
makeLightweightCdpDriver({
|
|
1200
|
+
...options,
|
|
1201
|
+
cdpUrl: connectWsUrl ?? options.cdpUrl,
|
|
1202
|
+
useBrowserContexts: true,
|
|
1203
|
+
freshContextPerFlow: false
|
|
1204
|
+
})
|
|
1205
|
+
);
|
|
1206
|
+
if (ctxOpts?.url) {
|
|
1207
|
+
await Effect2.runPromise(childDriver.openLink(ctxOpts.url));
|
|
1208
|
+
}
|
|
1209
|
+
return {
|
|
1210
|
+
driver: childDriver,
|
|
1211
|
+
close: async () => {
|
|
1212
|
+
await Effect2.runPromise(childDriver.killApp("isolated-context")).catch(() => {
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
},
|
|
1217
|
+
catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
|
|
1218
|
+
}),
|
|
1219
|
+
saveAuthState: (path) => Effect2.tryPromise({
|
|
1016
1220
|
try: async () => {
|
|
1017
1221
|
const res = await cdpChannel.sendCommand("Network.getCookies");
|
|
1018
1222
|
const originState = await cdpChannel.evaluate(
|
|
@@ -1035,7 +1239,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1035
1239
|
},
|
|
1036
1240
|
catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
|
|
1037
1241
|
}),
|
|
1038
|
-
loadAuthState: (path) =>
|
|
1242
|
+
loadAuthState: (path) => Effect2.tryPromise({
|
|
1039
1243
|
try: async () => {
|
|
1040
1244
|
if (useContexts) {
|
|
1041
1245
|
const previousSlot = activeSlot;
|
|
@@ -1052,7 +1256,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1052
1256
|
},
|
|
1053
1257
|
catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
|
|
1054
1258
|
}),
|
|
1055
|
-
enableVirtualAuthenticator: (opts) =>
|
|
1259
|
+
enableVirtualAuthenticator: (opts) => Effect2.tryPromise({
|
|
1056
1260
|
try: async () => {
|
|
1057
1261
|
activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
|
|
1058
1262
|
activeSlot?.sessionId ?? null,
|
|
@@ -1062,7 +1266,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1062
1266
|
},
|
|
1063
1267
|
catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
|
|
1064
1268
|
}),
|
|
1065
|
-
removeVirtualAuthenticator: (authenticatorId) =>
|
|
1269
|
+
removeVirtualAuthenticator: (authenticatorId) => Effect2.tryPromise({
|
|
1066
1270
|
try: async () => {
|
|
1067
1271
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1068
1272
|
if (!id) return;
|
|
@@ -1073,7 +1277,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1073
1277
|
},
|
|
1074
1278
|
catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
|
|
1075
1279
|
}),
|
|
1076
|
-
getVirtualCredentials: (authenticatorId) =>
|
|
1280
|
+
getVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
|
|
1077
1281
|
try: async () => {
|
|
1078
1282
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1079
1283
|
if (!id) return [];
|
|
@@ -1084,7 +1288,29 @@ function makeLightweightCdpDriver(options) {
|
|
|
1084
1288
|
},
|
|
1085
1289
|
catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
|
|
1086
1290
|
}),
|
|
1087
|
-
|
|
1291
|
+
addVirtualCredential: (credential, authenticatorId) => Effect2.tryPromise({
|
|
1292
|
+
try: async () => {
|
|
1293
|
+
let id = authenticatorId ?? activeAuthenticatorId;
|
|
1294
|
+
if (!id) {
|
|
1295
|
+
id = await attachVirtualAuthenticatorForSession(activeSlot?.sessionId ?? null);
|
|
1296
|
+
activeAuthenticatorId = id;
|
|
1297
|
+
}
|
|
1298
|
+
await cdpChannel.sendCommand("WebAuthn.addCredential", {
|
|
1299
|
+
authenticatorId: id,
|
|
1300
|
+
credential: {
|
|
1301
|
+
credentialId: credential.credentialId,
|
|
1302
|
+
isResidentCredential: credential.isResidentCredential,
|
|
1303
|
+
privateKey: credential.privateKey,
|
|
1304
|
+
signCount: credential.signCount ?? 0,
|
|
1305
|
+
...credential.rpId !== void 0 ? { rpId: credential.rpId } : {},
|
|
1306
|
+
...credential.userHandle !== void 0 ? { userHandle: credential.userHandle } : {},
|
|
1307
|
+
...credential.userName !== void 0 ? { userName: credential.userName } : {}
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
},
|
|
1311
|
+
catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
|
|
1312
|
+
}),
|
|
1313
|
+
clearVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
|
|
1088
1314
|
try: async () => {
|
|
1089
1315
|
const id = authenticatorId ?? activeAuthenticatorId;
|
|
1090
1316
|
if (!id) return;
|
|
@@ -1092,9 +1318,9 @@ function makeLightweightCdpDriver(options) {
|
|
|
1092
1318
|
},
|
|
1093
1319
|
catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
|
|
1094
1320
|
}),
|
|
1095
|
-
getConsoleLogs: () =>
|
|
1096
|
-
getJSErrors: () =>
|
|
1097
|
-
setNetworkConditions: (conditions) =>
|
|
1321
|
+
getConsoleLogs: () => Effect2.succeed([...consoleLogs]),
|
|
1322
|
+
getJSErrors: () => Effect2.succeed([...jsErrors]),
|
|
1323
|
+
setNetworkConditions: (conditions) => Effect2.tryPromise({
|
|
1098
1324
|
try: async () => {
|
|
1099
1325
|
const resolved = resolveNetworkConditions(conditions);
|
|
1100
1326
|
await cdpChannel.sendCommand("Network.enable");
|
|
@@ -1107,39 +1333,39 @@ function makeLightweightCdpDriver(options) {
|
|
|
1107
1333
|
},
|
|
1108
1334
|
catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
|
|
1109
1335
|
}),
|
|
1110
|
-
uploadFile: (selector, filePath) =>
|
|
1336
|
+
uploadFile: (selector, filePath) => Effect2.tryPromise({
|
|
1111
1337
|
try: async () => {
|
|
1112
|
-
const
|
|
1113
|
-
const expr =
|
|
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})`;
|
|
1338
|
+
const files = Array.isArray(filePath) ? filePath : [filePath];
|
|
1339
|
+
const expr = buildDomFindElementScript(selector);
|
|
1122
1340
|
await cdpChannel.sendCommand("DOM.enable");
|
|
1341
|
+
await cdpChannel.sendCommand("DOM.getDocument", { depth: 0 }).catch(() => {
|
|
1342
|
+
});
|
|
1123
1343
|
const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
|
|
1124
1344
|
expression: expr,
|
|
1125
1345
|
returnByValue: false
|
|
1126
1346
|
});
|
|
1127
1347
|
const objectId = evalRes?.result?.objectId;
|
|
1128
1348
|
if (!objectId) {
|
|
1129
|
-
throw new Error(
|
|
1349
|
+
throw new Error(
|
|
1350
|
+
`No matching file input found for selector ${JSON.stringify(selector)}`
|
|
1351
|
+
);
|
|
1130
1352
|
}
|
|
1131
|
-
const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
|
|
1132
|
-
if (
|
|
1133
|
-
|
|
1353
|
+
const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId }).catch(() => ({}));
|
|
1354
|
+
if (nodeRes?.nodeId && nodeRes.nodeId > 0) {
|
|
1355
|
+
await cdpChannel.sendCommand("DOM.setFileInputFiles", {
|
|
1356
|
+
nodeId: nodeRes.nodeId,
|
|
1357
|
+
files
|
|
1358
|
+
});
|
|
1359
|
+
} else {
|
|
1360
|
+
await cdpChannel.sendCommand("DOM.setFileInputFiles", {
|
|
1361
|
+
objectId,
|
|
1362
|
+
files
|
|
1363
|
+
});
|
|
1134
1364
|
}
|
|
1135
|
-
await cdpChannel.sendCommand("DOM.setFileInputFiles", {
|
|
1136
|
-
nodeId: nodeRes.nodeId,
|
|
1137
|
-
files: [filePath]
|
|
1138
|
-
});
|
|
1139
1365
|
},
|
|
1140
1366
|
catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
|
|
1141
1367
|
}),
|
|
1142
|
-
downloadFile: (destPath) =>
|
|
1368
|
+
downloadFile: (destPath) => Effect2.tryPromise({
|
|
1143
1369
|
try: async () => {
|
|
1144
1370
|
if (!downloadDir) {
|
|
1145
1371
|
downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
|
|
@@ -1173,7 +1399,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1173
1399
|
},
|
|
1174
1400
|
catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
|
|
1175
1401
|
}),
|
|
1176
|
-
newTab: (url) =>
|
|
1402
|
+
newTab: (url) => Effect2.tryPromise({
|
|
1177
1403
|
try: async () => {
|
|
1178
1404
|
if (!activeSlot) {
|
|
1179
1405
|
throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
|
|
@@ -1207,7 +1433,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1207
1433
|
},
|
|
1208
1434
|
catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
|
|
1209
1435
|
}),
|
|
1210
|
-
switchToTab: (index) =>
|
|
1436
|
+
switchToTab: (index) => Effect2.tryPromise({
|
|
1211
1437
|
try: async () => {
|
|
1212
1438
|
if (!activeSlot || !activeSlot.tabs[index]) {
|
|
1213
1439
|
throw new Error(`Tab index ${index} is out of range.`);
|
|
@@ -1221,7 +1447,7 @@ function makeLightweightCdpDriver(options) {
|
|
|
1221
1447
|
},
|
|
1222
1448
|
catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
|
|
1223
1449
|
}),
|
|
1224
|
-
closeTab: () =>
|
|
1450
|
+
closeTab: () => Effect2.tryPromise({
|
|
1225
1451
|
try: async () => {
|
|
1226
1452
|
if (!activeSlot) return;
|
|
1227
1453
|
if (activeSlot.tabs.length <= 1) {
|
|
@@ -1240,14 +1466,14 @@ function makeLightweightCdpDriver(options) {
|
|
|
1240
1466
|
},
|
|
1241
1467
|
catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
|
|
1242
1468
|
}),
|
|
1243
|
-
getTabIds: () =>
|
|
1469
|
+
getTabIds: () => Effect2.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
|
|
1244
1470
|
};
|
|
1245
1471
|
return service;
|
|
1246
1472
|
});
|
|
1247
1473
|
}
|
|
1248
1474
|
|
|
1249
1475
|
// src/runtime/local.ts
|
|
1250
|
-
import { Effect as
|
|
1476
|
+
import { Effect as Effect3 } from "effect";
|
|
1251
1477
|
async function safeCleanup(...fns) {
|
|
1252
1478
|
for (const fn of fns) {
|
|
1253
1479
|
try {
|
|
@@ -1375,13 +1601,14 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1375
1601
|
});
|
|
1376
1602
|
targetCdpUrl = launchedDirectCdp.browserWsUrl;
|
|
1377
1603
|
}
|
|
1378
|
-
rawDriver = await
|
|
1604
|
+
rawDriver = await Effect3.runPromise(
|
|
1379
1605
|
makeLightweightCdpDriver({
|
|
1380
1606
|
cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
|
|
1381
1607
|
baseUrl: webUrl,
|
|
1382
1608
|
engineLabel: engine,
|
|
1383
1609
|
useBrowserContexts: useContexts,
|
|
1384
1610
|
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1611
|
+
contextIsolation: webExecution?.contextIsolation,
|
|
1385
1612
|
waitUntil: webExecution?.waitUntil,
|
|
1386
1613
|
instantAnimations: webExecution?.instantAnimations,
|
|
1387
1614
|
blockResources: webExecution?.blockResources,
|
|
@@ -1390,7 +1617,7 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1390
1617
|
})
|
|
1391
1618
|
);
|
|
1392
1619
|
} else {
|
|
1393
|
-
rawDriver = await
|
|
1620
|
+
rawDriver = await Effect3.runPromise(
|
|
1394
1621
|
makePlaywrightDriver({
|
|
1395
1622
|
browser: webExecution?.browser,
|
|
1396
1623
|
headless: webExecution?.headless ?? true,
|
|
@@ -1414,12 +1641,12 @@ async function buildWebRuntime(config, prelaunched) {
|
|
|
1414
1641
|
);
|
|
1415
1642
|
}
|
|
1416
1643
|
const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
|
|
1417
|
-
const deviceInfo = await
|
|
1644
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1418
1645
|
return {
|
|
1419
1646
|
runtime: {
|
|
1420
1647
|
driver,
|
|
1421
1648
|
cleanup: () => safeCleanup(
|
|
1422
|
-
() =>
|
|
1649
|
+
() => Effect3.runPromise(driver.killApp("")),
|
|
1423
1650
|
() => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
|
|
1424
1651
|
() => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
|
|
1425
1652
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
@@ -1476,13 +1703,14 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1476
1703
|
const results2 = [];
|
|
1477
1704
|
for (let i = 0; i < workerCount; i++) {
|
|
1478
1705
|
const bucket = handles[i % handles.length];
|
|
1479
|
-
const driver = await
|
|
1706
|
+
const driver = await Effect3.runPromise(
|
|
1480
1707
|
makeLightweightCdpDriver({
|
|
1481
1708
|
cdpUrl: bucket.cdpUrl,
|
|
1482
1709
|
baseUrl: webUrl,
|
|
1483
1710
|
engineLabel: "cdp",
|
|
1484
1711
|
useBrowserContexts: true,
|
|
1485
1712
|
freshContextPerFlow: webExecution?.freshContextPerFlow,
|
|
1713
|
+
contextIsolation: webExecution?.contextIsolation,
|
|
1486
1714
|
waitUntil: webExecution?.waitUntil,
|
|
1487
1715
|
instantAnimations: webExecution?.instantAnimations,
|
|
1488
1716
|
blockResources: webExecution?.blockResources,
|
|
@@ -1490,7 +1718,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1490
1718
|
storageState: webExecution?.storageState
|
|
1491
1719
|
})
|
|
1492
1720
|
);
|
|
1493
|
-
const deviceInfo = await
|
|
1721
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1494
1722
|
let cleaned = false;
|
|
1495
1723
|
results2.push({
|
|
1496
1724
|
runtime: {
|
|
@@ -1498,7 +1726,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1498
1726
|
cleanup: () => safeCleanup(async () => {
|
|
1499
1727
|
if (cleaned) return;
|
|
1500
1728
|
cleaned = true;
|
|
1501
|
-
await
|
|
1729
|
+
await Effect3.runPromise(driver.killApp(""));
|
|
1502
1730
|
bucket.remaining -= 1;
|
|
1503
1731
|
if (bucket.remaining <= 0 && bucket.handle) {
|
|
1504
1732
|
await bucket.handle.close();
|
|
@@ -1571,7 +1799,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1571
1799
|
const results = [];
|
|
1572
1800
|
for (let i = 0; i < workerCount; i++) {
|
|
1573
1801
|
const bucket = browserBuckets[i % browserBuckets.length];
|
|
1574
|
-
const driver = await
|
|
1802
|
+
const driver = await Effect3.runPromise(
|
|
1575
1803
|
makePlaywrightDriver({
|
|
1576
1804
|
browser: webExecution?.browser,
|
|
1577
1805
|
headless: webExecution?.headless ?? true,
|
|
@@ -1590,7 +1818,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1590
1818
|
warmBrowserScope: webExecution?.warmBrowserScope
|
|
1591
1819
|
})
|
|
1592
1820
|
);
|
|
1593
|
-
const deviceInfo = await
|
|
1821
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1594
1822
|
let cleaned = false;
|
|
1595
1823
|
results.push({
|
|
1596
1824
|
runtime: {
|
|
@@ -1598,7 +1826,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1598
1826
|
cleanup: () => safeCleanup(async () => {
|
|
1599
1827
|
if (cleaned) return;
|
|
1600
1828
|
cleaned = true;
|
|
1601
|
-
await
|
|
1829
|
+
await Effect3.runPromise(driver.killApp(""));
|
|
1602
1830
|
bucket.remaining -= 1;
|
|
1603
1831
|
if (bucket.remaining <= 0 && bucket.owns) {
|
|
1604
1832
|
await bucket.browser.close();
|
|
@@ -1621,7 +1849,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
|
|
|
1621
1849
|
async function buildElectronRuntime(config, resolveFromConfig) {
|
|
1622
1850
|
const electronCfg = config.apps?.electron ?? {};
|
|
1623
1851
|
const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
|
|
1624
|
-
const driver = await
|
|
1852
|
+
const driver = await Effect3.runPromise(
|
|
1625
1853
|
makeElectronDriver({
|
|
1626
1854
|
entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
|
|
1627
1855
|
executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
|
|
@@ -1637,12 +1865,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
1637
1865
|
domChannel: bridge
|
|
1638
1866
|
})
|
|
1639
1867
|
);
|
|
1640
|
-
const deviceInfo = await
|
|
1868
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1641
1869
|
return {
|
|
1642
1870
|
runtime: {
|
|
1643
1871
|
driver,
|
|
1644
1872
|
cleanup: () => safeCleanup(
|
|
1645
|
-
() =>
|
|
1873
|
+
() => Effect3.runPromise(driver.killApp("")),
|
|
1646
1874
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
1647
1875
|
),
|
|
1648
1876
|
metadata: {
|
|
@@ -1666,7 +1894,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
|
|
|
1666
1894
|
async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
1667
1895
|
const electrobunCfg = config.apps?.electrobun ?? {};
|
|
1668
1896
|
const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
|
|
1669
|
-
const driver = await
|
|
1897
|
+
const driver = await Effect3.runPromise(
|
|
1670
1898
|
makeElectrobunDriver({
|
|
1671
1899
|
executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
|
|
1672
1900
|
appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
|
|
@@ -1684,12 +1912,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
|
|
|
1684
1912
|
domChannel: bridge
|
|
1685
1913
|
})
|
|
1686
1914
|
);
|
|
1687
|
-
const deviceInfo = await
|
|
1915
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1688
1916
|
return {
|
|
1689
1917
|
runtime: {
|
|
1690
1918
|
driver,
|
|
1691
1919
|
cleanup: () => safeCleanup(
|
|
1692
|
-
() =>
|
|
1920
|
+
() => Effect3.runPromise(driver.killApp("")),
|
|
1693
1921
|
() => bridge?.disconnect() ?? Promise.resolve()
|
|
1694
1922
|
),
|
|
1695
1923
|
metadata: {
|
|
@@ -1724,7 +1952,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
1724
1952
|
const androidAppPath = config.apps?.android?.appPath;
|
|
1725
1953
|
if (androidAppPath && packageName) {
|
|
1726
1954
|
try {
|
|
1727
|
-
const { adbShell, adbInstall } = await import("./android-
|
|
1955
|
+
const { adbShell, adbInstall } = await import("./android-6BOQTMM3.js");
|
|
1728
1956
|
const output = adbShell(device.serial, `pm list packages ${packageName}`);
|
|
1729
1957
|
if (!output.includes(packageName)) {
|
|
1730
1958
|
console.log(`Installing ${packageName} on Android device...`);
|
|
@@ -1732,7 +1960,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
1732
1960
|
}
|
|
1733
1961
|
} catch {
|
|
1734
1962
|
console.log(`Installing ${packageName} on Android device...`);
|
|
1735
|
-
const { adbInstall } = await import("./android-
|
|
1963
|
+
const { adbInstall } = await import("./android-6BOQTMM3.js");
|
|
1736
1964
|
adbInstall(device.serial, resolveFromConfig(androidAppPath));
|
|
1737
1965
|
}
|
|
1738
1966
|
}
|
|
@@ -1751,18 +1979,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
|
|
|
1751
1979
|
warm: warmDaemons?.enabled,
|
|
1752
1980
|
daemonStateFile: warmDaemons?.stateFile
|
|
1753
1981
|
});
|
|
1754
|
-
const driver = await
|
|
1982
|
+
const driver = await Effect3.runPromise(
|
|
1755
1983
|
createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
|
|
1756
1984
|
domChannel: bridge,
|
|
1757
1985
|
cdpPort: config.apps?.android?.cdpPort
|
|
1758
1986
|
})
|
|
1759
1987
|
);
|
|
1760
|
-
const deviceInfo = await
|
|
1988
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1761
1989
|
return {
|
|
1762
1990
|
runtime: {
|
|
1763
1991
|
driver,
|
|
1764
1992
|
cleanup: () => safeCleanup(
|
|
1765
|
-
() =>
|
|
1993
|
+
() => Effect3.runPromise(driver.killApp("")),
|
|
1766
1994
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1767
1995
|
() => {
|
|
1768
1996
|
if (reversedBridgePort !== null) {
|
|
@@ -1799,7 +2027,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1799
2027
|
const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
|
|
1800
2028
|
const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
|
|
1801
2029
|
const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
|
|
1802
|
-
const driver = await
|
|
2030
|
+
const driver = await Effect3.runPromise(
|
|
1803
2031
|
createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
|
|
1804
2032
|
domChannel: bridge,
|
|
1805
2033
|
webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
|
|
@@ -1809,12 +2037,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1809
2037
|
onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
|
|
1810
2038
|
})
|
|
1811
2039
|
);
|
|
1812
|
-
const deviceInfo = await
|
|
2040
|
+
const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
|
|
1813
2041
|
return {
|
|
1814
2042
|
runtime: {
|
|
1815
2043
|
driver,
|
|
1816
2044
|
cleanup: () => safeCleanup(
|
|
1817
|
-
() =>
|
|
2045
|
+
() => Effect3.runPromise(driver.killApp("")),
|
|
1818
2046
|
() => bridge?.disconnect() ?? Promise.resolve(),
|
|
1819
2047
|
() => conn.cleanup?.() ?? Promise.resolve()
|
|
1820
2048
|
),
|
|
@@ -1843,7 +2071,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1843
2071
|
});
|
|
1844
2072
|
}
|
|
1845
2073
|
if (signing?.teamId) {
|
|
1846
|
-
const { setupWDAForDevice } = await import("./installer-
|
|
2074
|
+
const { setupWDAForDevice } = await import("./installer-IYGMG7LS.js");
|
|
1847
2075
|
const wdaPort2 = allocatePort(8100);
|
|
1848
2076
|
conn = await setupWDAForDevice(
|
|
1849
2077
|
physicalDevice2.udid,
|
|
@@ -1945,13 +2173,105 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
|
|
|
1945
2173
|
}
|
|
1946
2174
|
}
|
|
1947
2175
|
|
|
2176
|
+
// src/report/code-frame.ts
|
|
2177
|
+
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
2178
|
+
import { fileURLToPath } from "url";
|
|
2179
|
+
var INTERNAL_FRAME_PATTERNS = [
|
|
2180
|
+
/node_modules\//,
|
|
2181
|
+
/^node:/,
|
|
2182
|
+
/^bun:/,
|
|
2183
|
+
/^internal\//,
|
|
2184
|
+
/\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
|
|
2185
|
+
/\/spana(?:-test)?\/dist\//
|
|
2186
|
+
];
|
|
2187
|
+
function normalizeStackFile(raw) {
|
|
2188
|
+
const trimmed = raw.trim();
|
|
2189
|
+
if (trimmed.startsWith("file://")) {
|
|
2190
|
+
try {
|
|
2191
|
+
return fileURLToPath(trimmed);
|
|
2192
|
+
} catch {
|
|
2193
|
+
return trimmed.replace(/^file:\/\//, "");
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
return trimmed;
|
|
2197
|
+
}
|
|
2198
|
+
function parseStackFrames(stack) {
|
|
2199
|
+
const frames = [];
|
|
2200
|
+
for (const rawLine of stack.split("\n")) {
|
|
2201
|
+
const line = rawLine.trim();
|
|
2202
|
+
if (!line.startsWith("at ")) continue;
|
|
2203
|
+
const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
|
|
2204
|
+
if (!match) continue;
|
|
2205
|
+
const file = normalizeStackFile(match[1]);
|
|
2206
|
+
const lineNum = Number.parseInt(match[2], 10);
|
|
2207
|
+
const colNum = Number.parseInt(match[3], 10);
|
|
2208
|
+
if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
|
|
2209
|
+
frames.push({
|
|
2210
|
+
file,
|
|
2211
|
+
line: lineNum,
|
|
2212
|
+
column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
return frames;
|
|
2216
|
+
}
|
|
2217
|
+
function isInternalFrame(file) {
|
|
2218
|
+
const normalized = file.replaceAll("\\", "/");
|
|
2219
|
+
return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
|
|
2220
|
+
}
|
|
2221
|
+
function formatCodeFrame(source, line, column, contextLines = 3) {
|
|
2222
|
+
const lines = source.split(/\r?\n/);
|
|
2223
|
+
if (line < 1 || line > lines.length) return "";
|
|
2224
|
+
const startLine = Math.max(1, line - contextLines);
|
|
2225
|
+
const endLine = Math.min(lines.length, line + contextLines);
|
|
2226
|
+
const gutterWidth = String(endLine).length;
|
|
2227
|
+
const out = [];
|
|
2228
|
+
for (let current = startLine; current <= endLine; current++) {
|
|
2229
|
+
const marker = current === line ? ">" : " ";
|
|
2230
|
+
const num = String(current).padStart(gutterWidth, " ");
|
|
2231
|
+
const content = lines[current - 1] ?? "";
|
|
2232
|
+
out.push(`${marker} ${num} | ${content}`);
|
|
2233
|
+
if (current === line) {
|
|
2234
|
+
const caretOffset = Math.max(0, Math.min(column - 1, content.length));
|
|
2235
|
+
out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
return out.join("\n");
|
|
2239
|
+
}
|
|
2240
|
+
function extractCodeFrame(stack, preferredFile, contextLines = 3) {
|
|
2241
|
+
if (!stack) return void 0;
|
|
2242
|
+
const frames = parseStackFrames(stack);
|
|
2243
|
+
if (frames.length === 0) return void 0;
|
|
2244
|
+
const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
|
|
2245
|
+
let chosen = normalizedPreferred ? frames.find(
|
|
2246
|
+
(f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
|
|
2247
|
+
) : void 0;
|
|
2248
|
+
if (!chosen) {
|
|
2249
|
+
chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
|
|
2250
|
+
}
|
|
2251
|
+
if (!chosen) {
|
|
2252
|
+
chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
|
|
2253
|
+
}
|
|
2254
|
+
if (!chosen) return void 0;
|
|
2255
|
+
try {
|
|
2256
|
+
const source = readFileSync(chosen.file, "utf8");
|
|
2257
|
+
const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
|
|
2258
|
+
if (!frame) return void 0;
|
|
2259
|
+
return {
|
|
2260
|
+
location: { file: chosen.file, line: chosen.line, column: chosen.column },
|
|
2261
|
+
frame
|
|
2262
|
+
};
|
|
2263
|
+
} catch {
|
|
2264
|
+
return void 0;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
|
|
1948
2268
|
// src/core/video-recorder.ts
|
|
1949
2269
|
import { execFileSync, spawn as spawn2 } from "child_process";
|
|
1950
2270
|
import {
|
|
1951
|
-
existsSync as
|
|
2271
|
+
existsSync as existsSync3,
|
|
1952
2272
|
mkdirSync,
|
|
1953
2273
|
mkdtempSync as mkdtempSync2,
|
|
1954
|
-
readFileSync,
|
|
2274
|
+
readFileSync as readFileSync2,
|
|
1955
2275
|
rmSync as rmSync2,
|
|
1956
2276
|
unlinkSync,
|
|
1957
2277
|
writeFileSync
|
|
@@ -2013,7 +2333,7 @@ async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
|
|
|
2013
2333
|
child.on("error", () => resolve(false));
|
|
2014
2334
|
child.on("close", (code) => resolve(code === 0));
|
|
2015
2335
|
});
|
|
2016
|
-
return ok &&
|
|
2336
|
+
return ok && existsSync3(outputPath) ? outputPath : void 0;
|
|
2017
2337
|
} catch {
|
|
2018
2338
|
return void 0;
|
|
2019
2339
|
} finally {
|
|
@@ -2062,7 +2382,26 @@ async function startCdpScreencastRecorder(cdp, options) {
|
|
|
2062
2382
|
unsubscribe();
|
|
2063
2383
|
await cdp.sendCommand("Page.stopScreencast").catch(() => {
|
|
2064
2384
|
});
|
|
2065
|
-
if (!stopOpts.keep
|
|
2385
|
+
if (!stopOpts.keep) {
|
|
2386
|
+
return { frameCount: 0 };
|
|
2387
|
+
}
|
|
2388
|
+
if (frames.length === 0) {
|
|
2389
|
+
try {
|
|
2390
|
+
const snap = await cdp.sendCommand("Page.captureScreenshot", {
|
|
2391
|
+
format: "jpeg",
|
|
2392
|
+
quality: options.quality ?? 65
|
|
2393
|
+
});
|
|
2394
|
+
if (typeof snap?.data === "string" && snap.data.length > 0) {
|
|
2395
|
+
frames.push({
|
|
2396
|
+
timestampMs: Math.max(0, Date.now() - startedAt),
|
|
2397
|
+
dataBase64: snap.data,
|
|
2398
|
+
mimeType: "image/jpeg"
|
|
2399
|
+
});
|
|
2400
|
+
}
|
|
2401
|
+
} catch {
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
if (frames.length === 0) {
|
|
2066
2405
|
return { frameCount: 0 };
|
|
2067
2406
|
}
|
|
2068
2407
|
mkdirSync(stopOpts.outputDir, { recursive: true });
|
|
@@ -2119,7 +2458,7 @@ function startAndroidVideoRecorder(serial, options) {
|
|
|
2119
2458
|
execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
|
|
2120
2459
|
stdio: "ignore"
|
|
2121
2460
|
});
|
|
2122
|
-
if (
|
|
2461
|
+
if (existsSync3(options.outputPath)) savedPath = options.outputPath;
|
|
2123
2462
|
} catch {
|
|
2124
2463
|
}
|
|
2125
2464
|
}
|
|
@@ -2156,14 +2495,14 @@ function startIosSimulatorVideoRecorder(udid, options) {
|
|
|
2156
2495
|
});
|
|
2157
2496
|
if (!keep) {
|
|
2158
2497
|
try {
|
|
2159
|
-
if (
|
|
2498
|
+
if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
|
|
2160
2499
|
} catch {
|
|
2161
2500
|
}
|
|
2162
2501
|
return { frameCount: 0 };
|
|
2163
2502
|
}
|
|
2164
2503
|
return {
|
|
2165
|
-
videoPath:
|
|
2166
|
-
frameCount:
|
|
2504
|
+
videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
|
|
2505
|
+
frameCount: existsSync3(options.outputPath) ? 1 : 0
|
|
2167
2506
|
};
|
|
2168
2507
|
}
|
|
2169
2508
|
};
|
|
@@ -2188,9 +2527,9 @@ function buildPlaybackTraceFromSteps(input) {
|
|
|
2188
2527
|
const img = step.attachments?.find(
|
|
2189
2528
|
(a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
|
|
2190
2529
|
);
|
|
2191
|
-
if (img &&
|
|
2530
|
+
if (img && existsSync3(img.path)) {
|
|
2192
2531
|
try {
|
|
2193
|
-
const dataBase64 =
|
|
2532
|
+
const dataBase64 = readFileSync2(img.path).toString("base64");
|
|
2194
2533
|
frames.push({
|
|
2195
2534
|
timestampMs: cursorMs + step.durationMs,
|
|
2196
2535
|
dataBase64,
|
|
@@ -2225,12 +2564,12 @@ function extractTapPointFromStep(step) {
|
|
|
2225
2564
|
}
|
|
2226
2565
|
|
|
2227
2566
|
// src/core/engine.ts
|
|
2228
|
-
import { Effect as
|
|
2567
|
+
import { Effect as Effect6 } from "effect";
|
|
2229
2568
|
|
|
2230
2569
|
// src/core/artifacts.ts
|
|
2231
2570
|
import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
2232
2571
|
import { join as join3 } from "path";
|
|
2233
|
-
import { Effect as
|
|
2572
|
+
import { Effect as Effect4 } from "effect";
|
|
2234
2573
|
var DEFAULT_ARTIFACT_CONFIG = {
|
|
2235
2574
|
outputDir: "./spana-output",
|
|
2236
2575
|
captureOnFailure: true,
|
|
@@ -2282,7 +2621,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2282
2621
|
const dir = flowArtifactDir(config, flowName, platform);
|
|
2283
2622
|
if (config.screenshot) {
|
|
2284
2623
|
try {
|
|
2285
|
-
const screenshot = await
|
|
2624
|
+
const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
|
|
2286
2625
|
const path = join3(dir, "screenshot.png");
|
|
2287
2626
|
writeFileSync2(path, screenshot);
|
|
2288
2627
|
attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
|
|
@@ -2291,7 +2630,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2291
2630
|
}
|
|
2292
2631
|
if (config.uiHierarchy) {
|
|
2293
2632
|
try {
|
|
2294
|
-
const hierarchy = await
|
|
2633
|
+
const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
|
|
2295
2634
|
const path = join3(dir, "hierarchy.json");
|
|
2296
2635
|
writeFileSync2(path, hierarchy, "utf-8");
|
|
2297
2636
|
attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
|
|
@@ -2300,7 +2639,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2300
2639
|
}
|
|
2301
2640
|
if (config.consoleLogs && driver.getConsoleLogs) {
|
|
2302
2641
|
try {
|
|
2303
|
-
const consoleLogs = await
|
|
2642
|
+
const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
|
|
2304
2643
|
if (consoleLogs.length > 0) {
|
|
2305
2644
|
attachments.push(
|
|
2306
2645
|
writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
|
|
@@ -2311,7 +2650,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2311
2650
|
}
|
|
2312
2651
|
if (config.jsErrors && driver.getJSErrors) {
|
|
2313
2652
|
try {
|
|
2314
|
-
const jsErrors = await
|
|
2653
|
+
const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
|
|
2315
2654
|
if (jsErrors.length > 0) {
|
|
2316
2655
|
attachments.push(
|
|
2317
2656
|
writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
|
|
@@ -2322,7 +2661,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2322
2661
|
}
|
|
2323
2662
|
if (config.har && driver.getHAR) {
|
|
2324
2663
|
try {
|
|
2325
|
-
const har = await
|
|
2664
|
+
const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
|
|
2326
2665
|
if (har.log.entries.length > 0) {
|
|
2327
2666
|
attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
|
|
2328
2667
|
}
|
|
@@ -2331,7 +2670,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
|
|
|
2331
2670
|
}
|
|
2332
2671
|
if (status === "failed" && driver.getDriverLogs) {
|
|
2333
2672
|
try {
|
|
2334
|
-
const driverLogs = await
|
|
2673
|
+
const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
|
|
2335
2674
|
if (driverLogs.length > 0) {
|
|
2336
2675
|
attachments.push(
|
|
2337
2676
|
writeTextAttachment(
|
|
@@ -2354,7 +2693,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
|
|
|
2354
2693
|
mkdirSync2(dir, { recursive: true });
|
|
2355
2694
|
const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
|
|
2356
2695
|
const path = join3(dir, fileName);
|
|
2357
|
-
const bytes = screenshot ?? await
|
|
2696
|
+
const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
|
|
2358
2697
|
writeFileSync2(path, bytes);
|
|
2359
2698
|
return createAttachment(stepName, "image/png", path);
|
|
2360
2699
|
} catch {
|
|
@@ -2364,7 +2703,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
|
|
|
2364
2703
|
|
|
2365
2704
|
// src/core/debug-repl.ts
|
|
2366
2705
|
import * as repl from "repl";
|
|
2367
|
-
import { Effect as
|
|
2706
|
+
import { Effect as Effect5 } from "effect";
|
|
2368
2707
|
var didStartDebugRepl = false;
|
|
2369
2708
|
function toSuggestedSelectors(root) {
|
|
2370
2709
|
return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
|
|
@@ -2385,7 +2724,7 @@ async function runDebugReplOnce(context) {
|
|
|
2385
2724
|
console.log("Skipping debug REPL because stdin/stdout is not interactive.");
|
|
2386
2725
|
return false;
|
|
2387
2726
|
}
|
|
2388
|
-
const hierarchy = async () => context.parseHierarchy(await
|
|
2727
|
+
const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
|
|
2389
2728
|
const selectors = async () => toSuggestedSelectors(await hierarchy());
|
|
2390
2729
|
console.log("");
|
|
2391
2730
|
console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
|
|
@@ -2435,9 +2774,11 @@ function createStepResult(command, durationMs, status, selector, error, attachme
|
|
|
2435
2774
|
}
|
|
2436
2775
|
function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
2437
2776
|
const steps = [];
|
|
2777
|
+
let lastFailureStack;
|
|
2438
2778
|
return {
|
|
2439
2779
|
async runStep(command, action, opts) {
|
|
2440
2780
|
const startedAt = Date.now();
|
|
2781
|
+
const callSiteStack = new Error().stack;
|
|
2441
2782
|
try {
|
|
2442
2783
|
const result = await action();
|
|
2443
2784
|
const attachments = [];
|
|
@@ -2464,6 +2805,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
|
2464
2805
|
);
|
|
2465
2806
|
return result;
|
|
2466
2807
|
} catch (error) {
|
|
2808
|
+
lastFailureStack = callSiteStack;
|
|
2467
2809
|
steps.push(
|
|
2468
2810
|
createStepResult(
|
|
2469
2811
|
command,
|
|
@@ -2478,6 +2820,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
|
2478
2820
|
},
|
|
2479
2821
|
async runScreenshotStep(command, action, opts) {
|
|
2480
2822
|
const startedAt = Date.now();
|
|
2823
|
+
const callSiteStack = new Error().stack;
|
|
2481
2824
|
try {
|
|
2482
2825
|
const screenshot = await action();
|
|
2483
2826
|
const attachment = await captureStepScreenshot(
|
|
@@ -2501,6 +2844,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
|
2501
2844
|
);
|
|
2502
2845
|
return screenshot;
|
|
2503
2846
|
} catch (error) {
|
|
2847
|
+
lastFailureStack = callSiteStack;
|
|
2504
2848
|
steps.push(
|
|
2505
2849
|
createStepResult(
|
|
2506
2850
|
command,
|
|
@@ -2515,6 +2859,9 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
|
|
|
2515
2859
|
},
|
|
2516
2860
|
getSteps() {
|
|
2517
2861
|
return steps;
|
|
2862
|
+
},
|
|
2863
|
+
getLastFailureStack() {
|
|
2864
|
+
return lastFailureStack;
|
|
2518
2865
|
}
|
|
2519
2866
|
};
|
|
2520
2867
|
}
|
|
@@ -2767,14 +3114,16 @@ function categorize(error) {
|
|
|
2767
3114
|
}
|
|
2768
3115
|
return { category: "unknown" };
|
|
2769
3116
|
}
|
|
2770
|
-
function classifyError(error) {
|
|
3117
|
+
function classifyError(error, opts) {
|
|
2771
3118
|
const tagged = error;
|
|
2772
3119
|
const { category, suggestion } = categorize(tagged);
|
|
3120
|
+
const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
|
|
2773
3121
|
return {
|
|
2774
3122
|
message: error.message,
|
|
2775
3123
|
stack: error.stack,
|
|
2776
3124
|
category,
|
|
2777
|
-
suggestion
|
|
3125
|
+
suggestion,
|
|
3126
|
+
...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
|
|
2778
3127
|
};
|
|
2779
3128
|
}
|
|
2780
3129
|
|
|
@@ -2783,7 +3132,7 @@ import { writeFileSync as writeFileSync4 } from "fs";
|
|
|
2783
3132
|
import { join as join5 } from "path";
|
|
2784
3133
|
|
|
2785
3134
|
// src/report/failure-bundle.ts
|
|
2786
|
-
import { writeFileSync as writeFileSync3, readFileSync as
|
|
3135
|
+
import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
|
|
2787
3136
|
import { join as join4, basename } from "path";
|
|
2788
3137
|
function levenshtein(a, b) {
|
|
2789
3138
|
const m = a.length;
|
|
@@ -2893,9 +3242,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2893
3242
|
if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
|
|
2894
3243
|
const hierarchyPath = join4(artifactDir, "hierarchy.json");
|
|
2895
3244
|
let hierarchyJson = null;
|
|
2896
|
-
if (
|
|
3245
|
+
if (existsSync4(hierarchyPath)) {
|
|
2897
3246
|
try {
|
|
2898
|
-
hierarchyJson =
|
|
3247
|
+
hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
|
|
2899
3248
|
} catch {
|
|
2900
3249
|
}
|
|
2901
3250
|
}
|
|
@@ -2910,15 +3259,15 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2910
3259
|
let runtimeDiagnostics;
|
|
2911
3260
|
const consolePath = join4(artifactDir, "console-logs.json");
|
|
2912
3261
|
const jsErrPath = join4(artifactDir, "js-errors.json");
|
|
2913
|
-
if (
|
|
3262
|
+
if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
|
|
2914
3263
|
let consoleErrorCount = 0;
|
|
2915
3264
|
let consoleWarnCount = 0;
|
|
2916
3265
|
const recentConsoleErrors = [];
|
|
2917
3266
|
let jsErrorCount = 0;
|
|
2918
3267
|
const recentJsErrors = [];
|
|
2919
|
-
if (
|
|
3268
|
+
if (existsSync4(consolePath)) {
|
|
2920
3269
|
try {
|
|
2921
|
-
const logs = JSON.parse(
|
|
3270
|
+
const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
|
|
2922
3271
|
if (Array.isArray(logs)) {
|
|
2923
3272
|
for (const entry of logs) {
|
|
2924
3273
|
const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
|
|
@@ -2934,9 +3283,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2934
3283
|
} catch {
|
|
2935
3284
|
}
|
|
2936
3285
|
}
|
|
2937
|
-
if (
|
|
3286
|
+
if (existsSync4(jsErrPath)) {
|
|
2938
3287
|
try {
|
|
2939
|
-
const errs = JSON.parse(
|
|
3288
|
+
const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
|
|
2940
3289
|
if (Array.isArray(errs)) {
|
|
2941
3290
|
jsErrorCount = errs.length;
|
|
2942
3291
|
for (const e of errs.slice(-5)) {
|
|
@@ -2968,7 +3317,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
|
|
|
2968
3317
|
message: error.message,
|
|
2969
3318
|
category: error.category,
|
|
2970
3319
|
suggestion: error.suggestion,
|
|
2971
|
-
errorCode: error.errorCode
|
|
3320
|
+
errorCode: error.errorCode,
|
|
3321
|
+
...error.location ? { location: error.location } : {},
|
|
3322
|
+
...error.codeFrame ? { codeFrame: error.codeFrame } : {}
|
|
2972
3323
|
},
|
|
2973
3324
|
selectorContext,
|
|
2974
3325
|
...runtimeDiagnostics ? { runtimeDiagnostics } : {},
|
|
@@ -3030,17 +3381,21 @@ async function executeFlow(flow, driver, config) {
|
|
|
3030
3381
|
typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
|
|
3031
3382
|
hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
|
|
3032
3383
|
} : coordinatorConfig;
|
|
3033
|
-
const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
|
|
3034
|
-
platform,
|
|
3035
|
-
storybook: config.storybook,
|
|
3036
|
-
launchOptions
|
|
3037
|
-
});
|
|
3038
3384
|
const flowMeta = {
|
|
3039
3385
|
flowFilePath: flow.sourcePath ?? "",
|
|
3040
3386
|
flowName: flow.name,
|
|
3041
3387
|
platform,
|
|
3042
3388
|
updateBaselines: config.updateBaselines ?? false
|
|
3043
3389
|
};
|
|
3390
|
+
const extraCleanups = [];
|
|
3391
|
+
const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
|
|
3392
|
+
platform,
|
|
3393
|
+
storybook: config.storybook,
|
|
3394
|
+
launchOptions,
|
|
3395
|
+
onRegisterCleanup: (fn) => extraCleanups.push(fn),
|
|
3396
|
+
flowContext: flowMeta,
|
|
3397
|
+
visualRegression: config.visualRegression
|
|
3398
|
+
});
|
|
3044
3399
|
const expect = createPromiseExpect(
|
|
3045
3400
|
driver,
|
|
3046
3401
|
mergedCoordinatorConfig,
|
|
@@ -3053,7 +3408,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
3053
3408
|
const sessions = createSessions(
|
|
3054
3409
|
sessionManager,
|
|
3055
3410
|
async (opts) => {
|
|
3056
|
-
const pwDriver = await
|
|
3411
|
+
const pwDriver = await Effect6.runPromise(
|
|
3057
3412
|
makePlaywrightDriver({
|
|
3058
3413
|
browser: opts.browser,
|
|
3059
3414
|
headless: opts.headless ?? true,
|
|
@@ -3078,7 +3433,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
3078
3433
|
const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
|
|
3079
3434
|
let viewport;
|
|
3080
3435
|
try {
|
|
3081
|
-
const info = await
|
|
3436
|
+
const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
|
|
3082
3437
|
if (info.screenWidth > 0 && info.screenHeight > 0) {
|
|
3083
3438
|
viewport = { width: info.screenWidth, height: info.screenHeight };
|
|
3084
3439
|
}
|
|
@@ -3148,7 +3503,10 @@ async function executeFlow(flow, driver, config) {
|
|
|
3148
3503
|
platform,
|
|
3149
3504
|
status: "failed",
|
|
3150
3505
|
durationMs,
|
|
3151
|
-
error: classifyError(normalized
|
|
3506
|
+
error: classifyError(normalized, {
|
|
3507
|
+
flowFilePath: flow.sourcePath,
|
|
3508
|
+
fallbackStack: stepRecorder.getLastFailureStack?.()
|
|
3509
|
+
}),
|
|
3152
3510
|
attachments,
|
|
3153
3511
|
steps,
|
|
3154
3512
|
scenarioSteps: flowCtx.__scenarioSteps
|
|
@@ -3156,7 +3514,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
3156
3514
|
};
|
|
3157
3515
|
if (driver.beginFlow) {
|
|
3158
3516
|
try {
|
|
3159
|
-
await
|
|
3517
|
+
await Effect6.runPromise(driver.beginFlow(flow.name));
|
|
3160
3518
|
} catch (error) {
|
|
3161
3519
|
return buildFailureResult(error);
|
|
3162
3520
|
}
|
|
@@ -3170,7 +3528,7 @@ async function executeFlow(flow, driver, config) {
|
|
|
3170
3528
|
exportMp4: artifactConfig.video !== "off"
|
|
3171
3529
|
});
|
|
3172
3530
|
} else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
|
|
3173
|
-
const info = await
|
|
3531
|
+
const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
|
|
3174
3532
|
() => void 0
|
|
3175
3533
|
);
|
|
3176
3534
|
if (info?.deviceId) {
|
|
@@ -3239,7 +3597,10 @@ async function executeFlow(flow, driver, config) {
|
|
|
3239
3597
|
platform,
|
|
3240
3598
|
status: "failed",
|
|
3241
3599
|
durationMs,
|
|
3242
|
-
error: classifyError(flowError
|
|
3600
|
+
error: classifyError(flowError, {
|
|
3601
|
+
flowFilePath: flow.sourcePath,
|
|
3602
|
+
fallbackStack: stepRecorder.getLastFailureStack?.()
|
|
3603
|
+
}),
|
|
3243
3604
|
attachments,
|
|
3244
3605
|
steps,
|
|
3245
3606
|
scenarioSteps: flowCtx.__scenarioSteps
|
|
@@ -3256,7 +3617,8 @@ async function executeFlow(flow, driver, config) {
|
|
|
3256
3617
|
stepRecorder.getSteps(),
|
|
3257
3618
|
result.error,
|
|
3258
3619
|
artDir,
|
|
3259
|
-
attachments
|
|
3620
|
+
attachments,
|
|
3621
|
+
flow.sourcePath
|
|
3260
3622
|
);
|
|
3261
3623
|
writeFailureBundle(bundle, artDir);
|
|
3262
3624
|
} catch {
|
|
@@ -3274,6 +3636,12 @@ async function executeFlow(flow, driver, config) {
|
|
|
3274
3636
|
});
|
|
3275
3637
|
}
|
|
3276
3638
|
}
|
|
3639
|
+
for (const cleanup of extraCleanups.toReversed()) {
|
|
3640
|
+
try {
|
|
3641
|
+
await cleanup();
|
|
3642
|
+
} catch {
|
|
3643
|
+
}
|
|
3644
|
+
}
|
|
3277
3645
|
try {
|
|
3278
3646
|
await sessionManager.disconnectAll();
|
|
3279
3647
|
} catch {
|
|
@@ -3306,7 +3674,8 @@ async function runParallel(config) {
|
|
|
3306
3674
|
retries = 0,
|
|
3307
3675
|
retryDelay = 0,
|
|
3308
3676
|
bail,
|
|
3309
|
-
durationHintsMs
|
|
3677
|
+
durationHintsMs,
|
|
3678
|
+
claimNextFlow
|
|
3310
3679
|
} = config;
|
|
3311
3680
|
const flows = orderFlowsLongestFirst(rawFlows, durationHintsMs);
|
|
3312
3681
|
const start2 = Date.now();
|
|
@@ -3318,9 +3687,16 @@ async function runParallel(config) {
|
|
|
3318
3687
|
const stats = { flowCount: 0, totalMs: 0 };
|
|
3319
3688
|
while (true) {
|
|
3320
3689
|
if (bail !== void 0 && failureCount >= bail) break;
|
|
3321
|
-
|
|
3322
|
-
if (
|
|
3323
|
-
|
|
3690
|
+
let flow;
|
|
3691
|
+
if (claimNextFlow) {
|
|
3692
|
+
const claimed = await claimNextFlow();
|
|
3693
|
+
if (!claimed) break;
|
|
3694
|
+
flow = claimed;
|
|
3695
|
+
} else {
|
|
3696
|
+
const flowIdx = nextFlowIndex++;
|
|
3697
|
+
if (flowIdx >= flows.length) break;
|
|
3698
|
+
flow = flows[flowIdx];
|
|
3699
|
+
}
|
|
3324
3700
|
let result;
|
|
3325
3701
|
let attempts = 0;
|
|
3326
3702
|
onFlowStart?.(flow.name, worker.name);
|
|
@@ -3347,7 +3723,7 @@ async function runParallel(config) {
|
|
|
3347
3723
|
return { workerId: worker.id, stats };
|
|
3348
3724
|
});
|
|
3349
3725
|
const workerResults = await Promise.all(workerPromises);
|
|
3350
|
-
if (bail !== void 0 && failureCount >= bail) {
|
|
3726
|
+
if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
|
|
3351
3727
|
bailedOut = true;
|
|
3352
3728
|
while (nextFlowIndex < flows.length) {
|
|
3353
3729
|
const flow = flows[nextFlowIndex++];
|
|
@@ -3376,6 +3752,191 @@ async function runParallel(config) {
|
|
|
3376
3752
|
};
|
|
3377
3753
|
}
|
|
3378
3754
|
|
|
3755
|
+
// src/core/worker-pool.ts
|
|
3756
|
+
import { spawn as spawn3 } from "child_process";
|
|
3757
|
+
import { readFile as readFile2, unlink } from "fs/promises";
|
|
3758
|
+
import { createServer } from "http";
|
|
3759
|
+
var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
|
|
3760
|
+
async function startSharedFlowQueueServer(orderedFlowNames) {
|
|
3761
|
+
const queue = [...orderedFlowNames];
|
|
3762
|
+
let cursor = 0;
|
|
3763
|
+
const server = createServer((req, res) => {
|
|
3764
|
+
if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
|
|
3765
|
+
const flowName = cursor < queue.length ? queue[cursor++] : null;
|
|
3766
|
+
const body = JSON.stringify({ flowName });
|
|
3767
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
3768
|
+
res.end(body);
|
|
3769
|
+
return;
|
|
3770
|
+
}
|
|
3771
|
+
res.writeHead(404);
|
|
3772
|
+
res.end();
|
|
3773
|
+
});
|
|
3774
|
+
await new Promise((resolve, reject) => {
|
|
3775
|
+
server.once("error", reject);
|
|
3776
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
3777
|
+
});
|
|
3778
|
+
const addr = server.address();
|
|
3779
|
+
const url = `http://127.0.0.1:${addr.port}`;
|
|
3780
|
+
return {
|
|
3781
|
+
url,
|
|
3782
|
+
remaining: () => Math.max(0, queue.length - cursor),
|
|
3783
|
+
close: () => new Promise((resolve) => {
|
|
3784
|
+
server.close(() => resolve());
|
|
3785
|
+
})
|
|
3786
|
+
};
|
|
3787
|
+
}
|
|
3788
|
+
function createRemoteFlowClaimer(queueUrl) {
|
|
3789
|
+
const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
|
|
3790
|
+
return async () => {
|
|
3791
|
+
const res = await fetch(endpoint, { method: "POST" });
|
|
3792
|
+
if (!res.ok) return null;
|
|
3793
|
+
const data = await res.json();
|
|
3794
|
+
return typeof data.flowName === "string" ? data.flowName : null;
|
|
3795
|
+
};
|
|
3796
|
+
}
|
|
3797
|
+
function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
|
|
3798
|
+
const safeTotal = Math.max(1, Math.floor(totalWorkers));
|
|
3799
|
+
const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
|
|
3800
|
+
const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
|
|
3801
|
+
if (processCount <= 1) {
|
|
3802
|
+
return {
|
|
3803
|
+
totalWorkers: safeTotal,
|
|
3804
|
+
maxWorkersPerProcess: safeMax,
|
|
3805
|
+
processCount: 1,
|
|
3806
|
+
workersPerProcess: [safeTotal]
|
|
3807
|
+
};
|
|
3808
|
+
}
|
|
3809
|
+
const base = Math.floor(safeTotal / processCount);
|
|
3810
|
+
const remainder = safeTotal % processCount;
|
|
3811
|
+
const workersPerProcess = Array.from(
|
|
3812
|
+
{ length: processCount },
|
|
3813
|
+
(_v, i) => base + (i < remainder ? 1 : 0)
|
|
3814
|
+
);
|
|
3815
|
+
return {
|
|
3816
|
+
totalWorkers: safeTotal,
|
|
3817
|
+
maxWorkersPerProcess: safeMax,
|
|
3818
|
+
processCount,
|
|
3819
|
+
workersPerProcess
|
|
3820
|
+
};
|
|
3821
|
+
}
|
|
3822
|
+
function partitionFlowsAcrossProcesses(items, processCount, options) {
|
|
3823
|
+
const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
|
|
3824
|
+
if (count === 1 || items.length === 0) {
|
|
3825
|
+
return items.length === 0 ? [] : [items];
|
|
3826
|
+
}
|
|
3827
|
+
const hints = options?.durationHintsMs;
|
|
3828
|
+
const getName = options?.getName;
|
|
3829
|
+
const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
|
|
3830
|
+
const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
|
|
3831
|
+
const indexed = items.map((item, idx) => ({
|
|
3832
|
+
item,
|
|
3833
|
+
idx,
|
|
3834
|
+
weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
|
|
3835
|
+
}));
|
|
3836
|
+
const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
|
|
3837
|
+
const loads = Array.from({ length: count }, () => 0);
|
|
3838
|
+
const buckets = Array.from({ length: count }, () => []);
|
|
3839
|
+
for (const entry of ordered) {
|
|
3840
|
+
let best = 0;
|
|
3841
|
+
for (let i = 1; i < count; i++) {
|
|
3842
|
+
if (loads[i] < loads[best]) best = i;
|
|
3843
|
+
}
|
|
3844
|
+
loads[best] = loads[best] + entry.weight;
|
|
3845
|
+
buckets[best].push({ item: entry.item, idx: entry.idx });
|
|
3846
|
+
}
|
|
3847
|
+
return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
|
|
3848
|
+
}
|
|
3849
|
+
async function defaultReadJsonReport(reportJsonPath) {
|
|
3850
|
+
let content;
|
|
3851
|
+
try {
|
|
3852
|
+
content = await readFile2(reportJsonPath, "utf8");
|
|
3853
|
+
} catch {
|
|
3854
|
+
return [];
|
|
3855
|
+
}
|
|
3856
|
+
const raw = JSON.parse(content);
|
|
3857
|
+
return Array.isArray(raw.results) ? raw.results : [];
|
|
3858
|
+
}
|
|
3859
|
+
async function runMultiProcessPool(options) {
|
|
3860
|
+
const plan = planProcessPool(
|
|
3861
|
+
options.totalWorkers,
|
|
3862
|
+
options.maxWorkersPerProcess,
|
|
3863
|
+
options.processes
|
|
3864
|
+
);
|
|
3865
|
+
const spawnFn = options.spawnFn ?? spawn3;
|
|
3866
|
+
const readReport = options.readReportFn ?? defaultReadJsonReport;
|
|
3867
|
+
const shouldCleanup = options.cleanupReportFiles !== false;
|
|
3868
|
+
const startedAt = Date.now();
|
|
3869
|
+
const processResults = await Promise.all(
|
|
3870
|
+
plan.workersPerProcess.map(async (workerCount, shardIdx) => {
|
|
3871
|
+
const shardStart = Date.now();
|
|
3872
|
+
const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
|
|
3873
|
+
let exitCode = null;
|
|
3874
|
+
let spawnError;
|
|
3875
|
+
try {
|
|
3876
|
+
exitCode = await new Promise((resolve, reject) => {
|
|
3877
|
+
const child = spawnFn(spec.command, spec.args, {
|
|
3878
|
+
env: { ...process.env, ...spec.env },
|
|
3879
|
+
stdio: "inherit"
|
|
3880
|
+
});
|
|
3881
|
+
child.on("error", reject);
|
|
3882
|
+
child.on("close", (code) => resolve(code));
|
|
3883
|
+
});
|
|
3884
|
+
} catch (err) {
|
|
3885
|
+
spawnError = err instanceof Error ? err.message : String(err);
|
|
3886
|
+
}
|
|
3887
|
+
let shardResults = [];
|
|
3888
|
+
try {
|
|
3889
|
+
shardResults = await readReport(spec.reportJsonPath);
|
|
3890
|
+
} catch (err) {
|
|
3891
|
+
if (!spawnError) {
|
|
3892
|
+
spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
if (shouldCleanup) {
|
|
3896
|
+
try {
|
|
3897
|
+
await unlink(spec.reportJsonPath);
|
|
3898
|
+
} catch {
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
if (exitCode !== 0 && shardResults.length === 0) {
|
|
3902
|
+
shardResults.push({
|
|
3903
|
+
name: `worker-process-${shardIdx + 1}`,
|
|
3904
|
+
platform: "web",
|
|
3905
|
+
status: "failed",
|
|
3906
|
+
durationMs: Date.now() - shardStart,
|
|
3907
|
+
error: {
|
|
3908
|
+
category: "driver-error",
|
|
3909
|
+
message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
|
|
3910
|
+
}
|
|
3911
|
+
});
|
|
3912
|
+
}
|
|
3913
|
+
return {
|
|
3914
|
+
shardIndex: shardIdx + 1,
|
|
3915
|
+
workerCount,
|
|
3916
|
+
exitCode,
|
|
3917
|
+
durationMs: Date.now() - shardStart,
|
|
3918
|
+
results: shardResults,
|
|
3919
|
+
...spawnError ? { error: spawnError } : {}
|
|
3920
|
+
};
|
|
3921
|
+
})
|
|
3922
|
+
);
|
|
3923
|
+
const results = processResults.flatMap((p) => p.results);
|
|
3924
|
+
const passed = results.filter((r) => r.status === "passed").length;
|
|
3925
|
+
const failed = results.filter((r) => r.status === "failed").length;
|
|
3926
|
+
const skipped = results.filter((r) => r.status === "skipped").length;
|
|
3927
|
+
const flaky = results.filter((r) => r.flaky).length;
|
|
3928
|
+
return {
|
|
3929
|
+
results,
|
|
3930
|
+
totalDurationMs: Date.now() - startedAt,
|
|
3931
|
+
passed,
|
|
3932
|
+
failed,
|
|
3933
|
+
skipped,
|
|
3934
|
+
flaky,
|
|
3935
|
+
processCount: plan.processCount,
|
|
3936
|
+
processResults
|
|
3937
|
+
};
|
|
3938
|
+
}
|
|
3939
|
+
|
|
3379
3940
|
export {
|
|
3380
3941
|
launchDirectCdpBrowser,
|
|
3381
3942
|
makeLightweightCdpDriver,
|
|
@@ -3387,6 +3948,8 @@ export {
|
|
|
3387
3948
|
buildElectrobunRuntime,
|
|
3388
3949
|
buildLocalAndroidRuntime,
|
|
3389
3950
|
buildLocalIOSRuntime,
|
|
3951
|
+
formatCodeFrame,
|
|
3952
|
+
extractCodeFrame,
|
|
3390
3953
|
classifyError,
|
|
3391
3954
|
exportFramesToMp4,
|
|
3392
3955
|
startCdpScreencastRecorder,
|
|
@@ -3395,6 +3958,12 @@ export {
|
|
|
3395
3958
|
buildPlaybackTraceFromSteps,
|
|
3396
3959
|
executeFlow,
|
|
3397
3960
|
orderFlowsLongestFirst,
|
|
3398
|
-
runParallel
|
|
3961
|
+
runParallel,
|
|
3962
|
+
DEFAULT_MAX_WORKERS_PER_PROCESS,
|
|
3963
|
+
startSharedFlowQueueServer,
|
|
3964
|
+
createRemoteFlowClaimer,
|
|
3965
|
+
planProcessPool,
|
|
3966
|
+
partitionFlowsAcrossProcesses,
|
|
3967
|
+
runMultiProcessPool
|
|
3399
3968
|
};
|
|
3400
|
-
//# sourceMappingURL=chunk-
|
|
3969
|
+
//# sourceMappingURL=chunk-3FXDOTFI.js.map
|