spana-test 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +126 -246
  2. package/README.md +2 -2
  3. package/dist/agent/index.d.ts +2 -2
  4. package/dist/agent/index.js +5 -5
  5. package/dist/{storybook-CxaP3YDz.d.ts → app-D_UyZBsl.d.ts} +213 -10
  6. package/dist/{chunk-WSA5QPTA.js → chunk-2IXXEXTL.js} +2 -2
  7. package/dist/{chunk-3YE2POGD.js → chunk-3SH5JQF7.js} +143 -3
  8. package/dist/chunk-3SH5JQF7.js.map +1 -0
  9. package/dist/chunk-54ASKII6.js +183 -0
  10. package/dist/chunk-54ASKII6.js.map +1 -0
  11. package/dist/{chunk-LRGT342X.js → chunk-6B5Y75V4.js} +1633 -533
  12. package/dist/chunk-6B5Y75V4.js.map +1 -0
  13. package/dist/{chunk-SQL3YRR5.js → chunk-JYFPZRCN.js} +21 -3
  14. package/dist/chunk-JYFPZRCN.js.map +1 -0
  15. package/dist/{chunk-UJQ7PID5.js → chunk-KNSAHEXI.js} +78 -3
  16. package/dist/chunk-KNSAHEXI.js.map +1 -0
  17. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  18. package/dist/chunk-PLE7RFQE.js.map +1 -0
  19. package/dist/{chunk-H3RWZCID.js → chunk-RURZVMZ7.js} +104 -3
  20. package/dist/chunk-RURZVMZ7.js.map +1 -0
  21. package/dist/{chunk-XENRC3YO.js → chunk-T3EBOYLS.js} +751 -59
  22. package/dist/chunk-T3EBOYLS.js.map +1 -0
  23. package/dist/{chunk-PJKIXVSO.js → chunk-T5CROOR7.js} +898 -238
  24. package/dist/chunk-T5CROOR7.js.map +1 -0
  25. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  26. package/dist/cli.js +11 -11
  27. package/dist/cli.js.map +1 -1
  28. package/dist/config-loader-NIDQGP3K.js +9 -0
  29. package/dist/{doctor-command-WB3O2H64.js → doctor-command-WPEVZEZ4.js} +3 -3
  30. package/dist/{filters-Q3ALKWZ5.js → filters-MQG2RMPX.js} +4 -2
  31. package/dist/flow-g6AICPAl.d.ts +95 -0
  32. package/dist/gherkin/steps.d.ts +2 -2
  33. package/dist/{html-F3X3XPSX.js → html-IKCTZH2U.js} +194 -3
  34. package/dist/html-IKCTZH2U.js.map +1 -0
  35. package/dist/index.d.ts +436 -21
  36. package/dist/index.js +328 -7
  37. package/dist/index.js.map +1 -1
  38. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  39. package/dist/{screenshot-compare-3QRHHSFZ.js → screenshot-compare-POTXVUTL.js} +21 -1
  40. package/dist/screenshot-compare-POTXVUTL.js.map +1 -0
  41. package/dist/{server-PRM7BVVD.js → server-EBPYK3VE.js} +5 -5
  42. package/dist/{server-QWJJB3WG.js → server-IGLBFEU7.js} +2 -2
  43. package/dist/{session-2E6OK6BH.js → session-QRWH3SPW.js} +4 -4
  44. package/dist/{session-Ddem-Q5n.d.ts → session-cJ_tZjCL.d.ts} +22 -1
  45. package/dist/{studio-command-O3NN5BCG.js → studio-command-FLA5HKRK.js} +2 -2
  46. package/dist/{test-command-FYOZ6QAE.js → test-command-P5W7UD52.js} +24 -10
  47. package/dist/test-command-P5W7UD52.js.map +1 -0
  48. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  49. package/package.json +3 -2
  50. package/dist/chunk-3TRMQCUT.js.map +0 -1
  51. package/dist/chunk-3YE2POGD.js.map +0 -1
  52. package/dist/chunk-H3RWZCID.js.map +0 -1
  53. package/dist/chunk-LRGT342X.js.map +0 -1
  54. package/dist/chunk-PJKIXVSO.js.map +0 -1
  55. package/dist/chunk-SQL3YRR5.js.map +0 -1
  56. package/dist/chunk-UJQ7PID5.js.map +0 -1
  57. package/dist/chunk-XENRC3YO.js.map +0 -1
  58. package/dist/config-loader-XGDDJGVY.js +0 -9
  59. package/dist/flow-CyRC-tTc.d.ts +0 -176
  60. package/dist/html-F3X3XPSX.js.map +0 -1
  61. package/dist/screenshot-compare-3QRHHSFZ.js.map +0 -1
  62. package/dist/test-command-FYOZ6QAE.js.map +0 -1
  63. /package/dist/{chunk-WSA5QPTA.js.map → chunk-2IXXEXTL.js.map} +0 -0
  64. /package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  65. /package/dist/{config-loader-XGDDJGVY.js.map → config-loader-NIDQGP3K.js.map} +0 -0
  66. /package/dist/{doctor-command-WB3O2H64.js.map → doctor-command-WPEVZEZ4.js.map} +0 -0
  67. /package/dist/{filters-Q3ALKWZ5.js.map → filters-MQG2RMPX.js.map} +0 -0
  68. /package/dist/{runner-6HK62Q7B.js.map → runner-TF4OKPYP.js.map} +0 -0
  69. /package/dist/{server-PRM7BVVD.js.map → server-EBPYK3VE.js.map} +0 -0
  70. /package/dist/{server-QWJJB3WG.js.map → server-IGLBFEU7.js.map} +0 -0
  71. /package/dist/{session-2E6OK6BH.js.map → session-QRWH3SPW.js.map} +0 -0
  72. /package/dist/{studio-command-O3NN5BCG.js.map → studio-command-FLA5HKRK.js.map} +0 -0
  73. /package/dist/{validator-HZ2A3NEI.js.map → validator-BLOLIHUY.js.map} +0 -0
@@ -3,15 +3,18 @@ import {
3
3
  ElementNotFoundError,
4
4
  TextMismatchError,
5
5
  WaitTimeoutError,
6
+ buildDomFillScript,
6
7
  buildDomQueryScript,
7
8
  buildDomScrollIntoViewScript,
8
9
  buildDomTapScript,
10
+ buildDomWaitForHiddenScript,
11
+ buildDomWaitForMatchScript,
9
12
  buildDomWaitForSelectorScript,
10
13
  createAndroidWebViewCdpChannel,
11
14
  createCompositeDomChannel,
12
15
  createWebKitInspectorChannel,
13
16
  domMatchToElement
14
- } from "./chunk-XENRC3YO.js";
17
+ } from "./chunk-T3EBOYLS.js";
15
18
  import {
16
19
  getHealthyWarmDaemon,
17
20
  registerWarmDaemon
@@ -556,6 +559,39 @@ function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts,
556
559
  let waitedForIdle = false;
557
560
  let isFirstPoll = true;
558
561
  const canReactiveDomWait = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector));
562
+ const initialDomChannel = driver.domChannel;
563
+ if (opts?.platform === "web" && canReactiveDomWait && settleTimeout === 0 && initialDomChannel?.isConnected() && initialDomChannel.waitForSelector) {
564
+ const reactiveMatches = yield* Effect2.tryPromise({
565
+ try: () => initialDomChannel.waitForSelector(selector, {
566
+ timeoutMs: timeout,
567
+ forAction,
568
+ failFastWhenIdle: opts?.failFastWhenIdle,
569
+ idleQuietMs: opts?.idleQuietMs
570
+ }),
571
+ catch: () => null
572
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
573
+ if (Array.isArray(reactiveMatches) && reactiveMatches.length > 0) {
574
+ const match = reactiveMatches[reactiveMatches.length - 1];
575
+ return {
576
+ element: domMatchToElement(match),
577
+ channel: "dom",
578
+ tapMode: opts?.tapMode ?? "native",
579
+ domMatch: match
580
+ };
581
+ }
582
+ if (Array.isArray(reactiveMatches) && reactiveMatches.length === 0 && (opts?.failFastWhenIdle || Date.now() - start >= timeout)) {
583
+ if (cache) cache.invalidate();
584
+ const diagRoot2 = yield* getHierarchy(driver, parse, cache);
585
+ const diagnostic2 = diagnoseElementNotFound(diagRoot2, selector);
586
+ const diagMessage2 = formatDiagnostic(diagnostic2);
587
+ return yield* new ElementNotFoundError({
588
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}
589
+ ${diagMessage2}`,
590
+ selector,
591
+ timeoutMs: timeout
592
+ });
593
+ }
594
+ }
559
595
  while (Date.now() - start < timeout) {
560
596
  if (!isFirstPoll && cache) cache.invalidate();
561
597
  isFirstPoll = false;
@@ -644,6 +680,22 @@ function waitForNotVisible(driver, selector, parse, opts, cache) {
644
680
  const start = Date.now();
645
681
  let waitedForIdle = false;
646
682
  let isFirstPoll = true;
683
+ const domChannel = driver.domChannel;
684
+ const canReactiveHidden = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector));
685
+ if (canReactiveHidden && domChannel?.isConnected() && domChannel.waitForHidden) {
686
+ const hidden = yield* Effect2.tryPromise({
687
+ try: () => domChannel.waitForHidden(selector, { timeoutMs: timeout }),
688
+ catch: () => null
689
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
690
+ if (hidden === true) return;
691
+ if (hidden === false) {
692
+ return yield* new WaitTimeoutError({
693
+ message: `Element still visible after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
694
+ selector,
695
+ timeoutMs: timeout
696
+ });
697
+ }
698
+ }
647
699
  while (Date.now() - start < timeout) {
648
700
  if (!isFirstPoll && cache) cache.invalidate();
649
701
  isFirstPoll = false;
@@ -718,6 +770,10 @@ function computeSwipeCoords(direction, screenW, screenH, offsetFraction) {
718
770
  right: { startX: cx - offset, startY: cy, endX: cx + offset, endY: cy }
719
771
  }[direction];
720
772
  }
773
+ function isRelativeSelectorLike2(selector) {
774
+ if (typeof selector !== "object" || selector === null) return false;
775
+ return "below" in selector || "above" in selector || "leftOf" in selector || "rightOf" in selector || "childOf" in selector;
776
+ }
721
777
  function createCoordinator(driver, config) {
722
778
  const { parse, defaults } = config;
723
779
  const cacheConfig = {
@@ -794,11 +850,32 @@ function createCoordinator(driver, config) {
794
850
  };
795
851
  return directionMap[direction];
796
852
  };
797
- const pollUntilMatch = (selector, opts, check, formatError) => Effect4.gen(function* () {
853
+ const pollUntilMatch = (selector, opts, check, formatError, domMatchSpec) => Effect4.gen(function* () {
798
854
  const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
799
855
  const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
800
856
  const start = Date.now();
801
857
  let lastActual;
858
+ const domChannel = driver.domChannel;
859
+ if (domMatchSpec && config.platform === "web" && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
860
+ const reactive = yield* Effect4.tryPromise({
861
+ try: () => domChannel.waitForMatch(selector, {
862
+ ...domMatchSpec,
863
+ timeoutMs: timeout
864
+ }),
865
+ catch: () => null
866
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
867
+ if (reactive) {
868
+ if (reactive.matched) return;
869
+ lastActual = reactive.actual;
870
+ const err2 = formatError(lastActual, timeout);
871
+ return yield* new TextMismatchError({
872
+ message: err2.message,
873
+ expected: err2.expected,
874
+ actual: lastActual,
875
+ selector
876
+ });
877
+ }
878
+ }
802
879
  while (Date.now() - start < timeout) {
803
880
  if (cache) cache.invalidate();
804
881
  const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
@@ -879,7 +956,8 @@ function createCoordinator(driver, config) {
879
956
  (actual, timeout) => ({
880
957
  message: `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
881
958
  expected
882
- })
959
+ }),
960
+ { kind: "text", expected }
883
961
  ),
884
962
  assertContainsText: (selector, expected, opts) => pollUntilMatch(
885
963
  selector,
@@ -894,7 +972,8 @@ function createCoordinator(driver, config) {
894
972
  (actual, timeout) => ({
895
973
  message: `Expected text to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
896
974
  expected
897
- })
975
+ }),
976
+ { kind: "containsText", expected }
898
977
  ),
899
978
  assertEnabled: (selector, opts) => assertEnabledState(selector, true, opts),
900
979
  assertDisabled: (selector, opts) => assertEnabledState(selector, false, opts),
@@ -930,7 +1009,8 @@ function createCoordinator(driver, config) {
930
1009
  (actual, timeout) => ({
931
1010
  message: `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
932
1011
  expected: expectedStr
933
- })
1012
+ }),
1013
+ { kind: "value", expected: expectedStr }
934
1014
  );
935
1015
  },
936
1016
  assertAttribute: (selector, name, expectedValue, opts) => pollUntilMatch(
@@ -949,7 +1029,8 @@ function createCoordinator(driver, config) {
949
1029
  } : {
950
1030
  message: `Expected attribute "${name}" to be "${expectedValue}" but got "${actual ?? "(not found)"}" after ${timeout}ms`,
951
1031
  expected: expectedValue
952
- }
1032
+ },
1033
+ { kind: "attribute", attributeName: name, expected: expectedValue }
953
1034
  ),
954
1035
  assertMatchesText: (selector, pattern, opts) => pollUntilMatch(
955
1036
  selector,
@@ -961,7 +1042,8 @@ function createCoordinator(driver, config) {
961
1042
  (actual, timeout) => ({
962
1043
  message: `Expected text to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms`,
963
1044
  expected: String(pattern)
964
- })
1045
+ }),
1046
+ { kind: "matchesText", patternSource: pattern.source, patternFlags: pattern.flags }
965
1047
  ),
966
1048
  getAttribute: (selector, name, opts) => Effect4.gen(function* () {
967
1049
  const element = yield* waitForElement(
@@ -978,7 +1060,7 @@ function createCoordinator(driver, config) {
978
1060
  () => import("./baseline-manager-5TIUCNP5.js")
979
1061
  );
980
1062
  const { cropToElement, applyMask, compareScreenshots } = yield* Effect4.promise(
981
- () => import("./screenshot-compare-3QRHHSFZ.js")
1063
+ () => import("./screenshot-compare-POTXVUTL.js")
982
1064
  );
983
1065
  const raw = yield* driver.takeScreenshot();
984
1066
  let screenshotBuf;
@@ -1046,7 +1128,8 @@ function createCoordinator(driver, config) {
1046
1128
  } : {
1047
1129
  message: `Expected accessibilityLabel "${expected}" but got "${actual ?? "(none)"}" after ${timeout}ms`,
1048
1130
  expected
1049
- }
1131
+ },
1132
+ { kind: "accessibilityLabel", expected }
1050
1133
  ),
1051
1134
  assertFocusable: (selector, platform, opts) => Effect4.gen(function* () {
1052
1135
  const { isFocusable } = yield* Effect4.promise(
@@ -1234,6 +1317,41 @@ function createCoordinator(driver, config) {
1234
1317
  }
1235
1318
  yield* afterMutation();
1236
1319
  }),
1320
+ /**
1321
+ * Atomic 1-round-trip form fill: on web/DOM channels, waits for actionability,
1322
+ * focuses, clears, sets the React/Vue-safe value, and dispatches `input` + `change`
1323
+ * in ONE single round trip (~1-2ms). Falls back to `tap` + `inputText` on native mobile.
1324
+ */
1325
+ fill: (selector, text, opts) => Effect4.gen(function* () {
1326
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1327
+ const domChannel = driver.domChannel;
1328
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.fillDom) {
1329
+ const filled = yield* Effect4.tryPromise({
1330
+ try: () => domChannel.fillDom(selector, text, { timeoutMs: timeout }),
1331
+ catch: (e) => new DriverError({ message: `DOM fill failed: ${e}` })
1332
+ });
1333
+ if (filled) {
1334
+ yield* afterMutation();
1335
+ return;
1336
+ }
1337
+ return yield* new ElementNotFoundError({
1338
+ message: `Element not fillable within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1339
+ selector,
1340
+ timeoutMs: timeout
1341
+ });
1342
+ }
1343
+ const element = yield* waitForActionElement(
1344
+ driver,
1345
+ selector,
1346
+ parse,
1347
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1348
+ cache
1349
+ );
1350
+ const { x, y } = centerOf(element);
1351
+ yield* driver.tapAtCoordinate(x, y);
1352
+ yield* driver.inputText(text);
1353
+ yield* afterMutation();
1354
+ }),
1237
1355
  pressKey: (key) => Effect4.gen(function* () {
1238
1356
  yield* driver.pressKey(key);
1239
1357
  cache.invalidate();
@@ -1403,48 +1521,8 @@ function buildStorybookUrl(storyId, options, runtime) {
1403
1521
  return url.toString();
1404
1522
  }
1405
1523
 
1406
- // src/drivers/playwright-parser.ts
1407
- function rawNodeToElement(node) {
1408
- const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
1409
- return {
1410
- ...node.id !== void 0 ? { id: node.id } : {},
1411
- ...node.text !== void 0 ? { text: node.text } : {},
1412
- ...node.value !== void 0 ? { value: node.value } : {},
1413
- ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
1414
- // Use role as elementType when present, otherwise fall back to HTML tag name
1415
- ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
1416
- bounds: {
1417
- x: node.bounds.x,
1418
- y: node.bounds.y,
1419
- width: node.bounds.width,
1420
- height: node.bounds.height
1421
- },
1422
- ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
1423
- ...node.visible !== void 0 ? { visible: node.visible } : {},
1424
- ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
1425
- ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
1426
- ...children !== void 0 ? { children } : {}
1427
- };
1428
- }
1429
- function parseWebHierarchy(json) {
1430
- const raw = JSON.parse(json);
1431
- return rawNodeToElement(raw);
1432
- }
1433
-
1434
- // src/drivers/raw-driver.ts
1435
- import { Context, Effect as Effect5 } from "effect";
1436
- var RawDriver = class extends Context.Tag("RawDriver")() {
1437
- };
1438
-
1439
- // src/drivers/playwright.ts
1440
- import { spawn } from "child_process";
1441
- import { readFile, writeFile } from "fs/promises";
1442
- import { Effect as Effect6, Layer } from "effect";
1443
- import {
1444
- chromium,
1445
- firefox,
1446
- webkit
1447
- } from "playwright-core";
1524
+ // src/api/app.ts
1525
+ import { Effect as Effect5 } from "effect";
1448
1526
 
1449
1527
  // src/drivers/launch-options.ts
1450
1528
  function mergeRecord(base, override) {
@@ -1550,6 +1628,418 @@ function buildIOSLaunchConfiguration(options) {
1550
1628
  };
1551
1629
  }
1552
1630
 
1631
+ // src/api/app.ts
1632
+ var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
1633
+ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1634
+ const coord = createCoordinator(driver, config);
1635
+ const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
1636
+ const run = (effect) => Effect5.runPromise(effect);
1637
+ const unsupportedWebFeature = (feature) => Effect5.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
1638
+ const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
1639
+ const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
1640
+ const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
1641
+ return {
1642
+ tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
1643
+ tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
1644
+ selector: { point: { x, y } },
1645
+ captureScreenshot: true
1646
+ }),
1647
+ doubleTap: (selector, opts) => runStep("doubleTap", () => run(coord.doubleTap(selector, opts)), {
1648
+ selector,
1649
+ captureScreenshot: true
1650
+ }),
1651
+ longPress: (selector, opts) => runStep("longPress", () => run(coord.longPress(selector, opts?.duration, opts)), {
1652
+ selector,
1653
+ captureScreenshot: true
1654
+ }),
1655
+ longPressXY: (x, y, opts) => runStep("longPressXY", () => run(coord.longPressXY(x, y, opts?.duration)), {
1656
+ selector: { point: { x, y } },
1657
+ captureScreenshot: true
1658
+ }),
1659
+ inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
1660
+ fill: (selector, value, opts) => runStep("fill", () => run(coord.fill(selector, value, opts)), {
1661
+ selector,
1662
+ captureScreenshot: true
1663
+ }),
1664
+ pressKey: (key) => runStep(`pressKey(${key})`, () => run(coord.pressKey(key)), { captureScreenshot: true }),
1665
+ hideKeyboard: () => runStep("hideKeyboard", () => run(coord.hideKeyboard()), { captureScreenshot: true }),
1666
+ dismissKeyboard: (opts) => runStep(
1667
+ `dismissKeyboard(${opts?.strategy ?? "auto"})`,
1668
+ () => run(coord.dismissKeyboard(opts)),
1669
+ {
1670
+ selector: { strategy: opts?.strategy ?? "auto" },
1671
+ captureScreenshot: true
1672
+ }
1673
+ ),
1674
+ swipe: (direction, opts) => runStep(`swipe(${direction})`, () => run(coord.swipe(direction, opts)), {
1675
+ captureScreenshot: true
1676
+ }),
1677
+ scroll: (direction) => runStep(`scroll(${direction})`, () => run(coord.scroll(direction)), {
1678
+ captureScreenshot: true
1679
+ }),
1680
+ scrollUntilVisible: (selector, opts) => runStep(
1681
+ `scrollUntilVisible(${opts?.direction ?? "down"})`,
1682
+ () => run(coord.scrollUntilVisible(selector, opts)),
1683
+ {
1684
+ selector: {
1685
+ target: selector,
1686
+ ...opts,
1687
+ direction: opts?.direction ?? "down",
1688
+ maxScrolls: opts?.maxScrolls ?? 5
1689
+ },
1690
+ captureScreenshot: true
1691
+ }
1692
+ ),
1693
+ backUntilVisible: (selector, opts) => runStep(
1694
+ `backUntilVisible(${opts?.maxBacks ?? 3})`,
1695
+ () => run(coord.backUntilVisible(selector, opts)),
1696
+ {
1697
+ selector: {
1698
+ target: selector,
1699
+ ...opts,
1700
+ maxBacks: opts?.maxBacks ?? 3
1701
+ },
1702
+ captureScreenshot: true
1703
+ }
1704
+ ),
1705
+ launch: (opts) => {
1706
+ const mergedLaunchOptions = mergeLaunchOptions(options.launchOptions, opts);
1707
+ return runStep("launch", () => run(driver.launchApp(appId, mergedLaunchOptions)), {
1708
+ selector: mergedLaunchOptions,
1709
+ captureScreenshot: true
1710
+ });
1711
+ },
1712
+ stop: () => runStep("stop", () => run(driver.stopApp(appId)), { captureScreenshot: true }),
1713
+ kill: () => runStep("kill", () => run(driver.killApp(appId)), { captureScreenshot: true }),
1714
+ clearState: () => runStep("clearState", () => run(driver.clearAppState(appId)), { captureScreenshot: true }),
1715
+ openLink: (url) => runStep("openLink", () => run(driver.openLink(url)), {
1716
+ selector: { url },
1717
+ captureScreenshot: true
1718
+ }),
1719
+ openStory: (storyId, opts) => runStep(
1720
+ `openStory(${storyId})`,
1721
+ async () => {
1722
+ if (platform !== "web") {
1723
+ await run(unsupportedWebFeature("openStory"));
1724
+ return;
1725
+ }
1726
+ const url = buildStorybookUrl(storyId, opts, {
1727
+ appBaseUrl: appId,
1728
+ storybook: options.storybook
1729
+ });
1730
+ await run(driver.openLink(url));
1731
+ },
1732
+ {
1733
+ selector: {
1734
+ storyId,
1735
+ viewMode: opts?.viewMode ?? "story",
1736
+ args: opts?.args,
1737
+ globals: opts?.globals,
1738
+ baseUrl: opts?.baseUrl
1739
+ },
1740
+ captureScreenshot: true
1741
+ }
1742
+ ),
1743
+ back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
1744
+ takeScreenshot: (name) => runScreenshotStep(
1745
+ name ? `takeScreenshot(${name})` : "takeScreenshot",
1746
+ () => run(driver.takeScreenshot()),
1747
+ { name }
1748
+ ),
1749
+ evaluate: (fn, ...args) => runStep("evaluate", () => run(driver.evaluate(fn, ...args))),
1750
+ mockNetwork: (matcher, response) => runStep(
1751
+ "mockNetwork",
1752
+ () => run(optionalMethod("mockNetwork", driver.mockNetwork)(matcher, response)),
1753
+ {
1754
+ selector: { matcher: describeMatcher(matcher), response }
1755
+ }
1756
+ ),
1757
+ blockNetwork: (matcher) => runStep(
1758
+ "blockNetwork",
1759
+ () => run(optionalMethod("blockNetwork", driver.blockNetwork)(matcher)),
1760
+ {
1761
+ selector: { matcher: describeMatcher(matcher) }
1762
+ }
1763
+ ),
1764
+ clearNetworkMocks: () => runStep(
1765
+ "clearNetworkMocks",
1766
+ () => run(optionalMethod("clearNetworkMocks", driver.clearNetworkMocks)())
1767
+ ),
1768
+ setNetworkConditions: (conditions) => runStep(
1769
+ "setNetworkConditions",
1770
+ () => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
1771
+ { selector: conditions }
1772
+ ),
1773
+ saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
1774
+ selector: { path }
1775
+ }),
1776
+ loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
1777
+ selector: { path }
1778
+ }),
1779
+ saveAuthState: (path) => runStep(
1780
+ "saveAuthState",
1781
+ () => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
1782
+ { selector: { path } }
1783
+ ),
1784
+ loadAuthState: (path) => runStep(
1785
+ "loadAuthState",
1786
+ () => run(optionalMethod("loadAuthState", driver.loadAuthState)(path)),
1787
+ { selector: { path } }
1788
+ ),
1789
+ downloadFile: (path) => runStep(
1790
+ "downloadFile",
1791
+ () => run(optionalMethod("downloadFile", driver.downloadFile)(path)),
1792
+ { selector: { path } }
1793
+ ),
1794
+ uploadFile: (selector, path) => runStep(
1795
+ "uploadFile",
1796
+ () => run(optionalMethod("uploadFile", driver.uploadFile)(selector, path)),
1797
+ {
1798
+ selector: { target: selector, path },
1799
+ captureScreenshot: true
1800
+ }
1801
+ ),
1802
+ newTab: (url) => runStep("newTab", () => run(optionalMethod("newTab", driver.newTab)(url)), {
1803
+ selector: url ? { url } : void 0,
1804
+ captureScreenshot: true
1805
+ }),
1806
+ switchToTab: (index) => runStep(
1807
+ `switchToTab(${index})`,
1808
+ () => run(optionalMethod("switchToTab", driver.switchToTab)(index)),
1809
+ {
1810
+ selector: { index },
1811
+ captureScreenshot: true
1812
+ }
1813
+ ),
1814
+ closeTab: () => runStep("closeTab", () => run(optionalMethod("closeTab", driver.closeTab)()), {
1815
+ captureScreenshot: true
1816
+ }),
1817
+ getTabIds: () => runStep("getTabIds", () => run(optionalMethod("getTabIds", driver.getTabIds)())),
1818
+ getConsoleLogs: () => runStep(
1819
+ "getConsoleLogs",
1820
+ () => run(optionalMethod("getConsoleLogs", driver.getConsoleLogs)())
1821
+ ),
1822
+ getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
1823
+ getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
1824
+ getPage: () => {
1825
+ if (!driver.getRawPage) {
1826
+ throw new DriverError({
1827
+ message: "getPage() is only available when running with a browser driver that exposes a raw page."
1828
+ });
1829
+ }
1830
+ return driver.getRawPage();
1831
+ },
1832
+ enableVirtualAuthenticator: (opts) => runStep(
1833
+ "enableVirtualAuthenticator",
1834
+ () => run(
1835
+ optionalMethod("enableVirtualAuthenticator", driver.enableVirtualAuthenticator)(opts)
1836
+ ),
1837
+ { selector: opts }
1838
+ ),
1839
+ removeVirtualAuthenticator: (authenticatorId) => runStep(
1840
+ "removeVirtualAuthenticator",
1841
+ () => run(
1842
+ optionalMethod(
1843
+ "removeVirtualAuthenticator",
1844
+ driver.removeVirtualAuthenticator
1845
+ )(authenticatorId)
1846
+ )
1847
+ ),
1848
+ getVirtualCredentials: (authenticatorId) => runStep(
1849
+ "getVirtualCredentials",
1850
+ () => run(optionalMethod("getVirtualCredentials", driver.getVirtualCredentials)(authenticatorId))
1851
+ ),
1852
+ clearVirtualCredentials: (authenticatorId) => runStep(
1853
+ "clearVirtualCredentials",
1854
+ () => run(
1855
+ optionalMethod(
1856
+ "clearVirtualCredentials",
1857
+ driver.clearVirtualCredentials
1858
+ )(authenticatorId)
1859
+ )
1860
+ ),
1861
+ pinch: (selector, opts) => runStep("pinch", () => run(coord.pinch(selector, opts)), {
1862
+ selector,
1863
+ captureScreenshot: true
1864
+ }),
1865
+ zoom: (selector, opts) => runStep("zoom", () => run(coord.zoom(selector, opts)), {
1866
+ selector,
1867
+ captureScreenshot: true
1868
+ }),
1869
+ multiTouch: (sequences) => runStep("multiTouch", () => run(coord.multiTouch(sequences)), { captureScreenshot: true }),
1870
+ getText: (selector, opts) => runStep("getText", () => run(coord.getText(selector, opts)), { selector }),
1871
+ getAttribute: (selector, name, opts) => runStep(`getAttribute(${name})`, () => run(coord.getAttribute(selector, name, opts)), {
1872
+ selector
1873
+ }),
1874
+ isVisible: (selector, opts) => {
1875
+ const timeout = opts?.timeout ?? 1e3;
1876
+ return run(
1877
+ Effect5.gen(function* () {
1878
+ const result = yield* Effect5.either(
1879
+ waitForElement(
1880
+ driver,
1881
+ selector,
1882
+ config.parse,
1883
+ { timeout, pollInterval: 100 },
1884
+ void 0
1885
+ )
1886
+ );
1887
+ return result._tag === "Right";
1888
+ })
1889
+ );
1890
+ },
1891
+ isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
1892
+ // Web-first bridge & fast state helpers
1893
+ waitForIdle: (opts) => runStep("waitForIdle", async () => {
1894
+ if (driver.domChannel?.waitForIdle) {
1895
+ await driver.domChannel.waitForIdle(opts);
1896
+ }
1897
+ }),
1898
+ setStorage: (entries) => runStep("setStorage", async () => {
1899
+ if (driver.domChannel?.setStorage) {
1900
+ await driver.domChannel.setStorage(entries);
1901
+ return;
1902
+ }
1903
+ const serialized = JSON.stringify(entries);
1904
+ await run(
1905
+ driver.evaluate(
1906
+ `((payload) => {
1907
+ if (payload.localStorage) {
1908
+ for (const [k, v] of Object.entries(payload.localStorage)) {
1909
+ window.localStorage.setItem(k, v);
1910
+ }
1911
+ }
1912
+ if (payload.sessionStorage) {
1913
+ for (const [k, v] of Object.entries(payload.sessionStorage)) {
1914
+ window.sessionStorage.setItem(k, v);
1915
+ }
1916
+ }
1917
+ if (payload.cookies) {
1918
+ for (const c of payload.cookies) {
1919
+ const path = c.path ? '; path=' + c.path : '; path=/';
1920
+ const domain = c.domain ? '; domain=' + c.domain : '';
1921
+ document.cookie = encodeURIComponent(c.name) + '=' + encodeURIComponent(c.value) + path + domain;
1922
+ }
1923
+ }
1924
+ })(${serialized})`
1925
+ )
1926
+ );
1927
+ }),
1928
+ clearStorage: (opts) => runStep("clearStorage", async () => {
1929
+ if (driver.domChannel?.clearStorage) {
1930
+ await driver.domChannel.clearStorage(opts);
1931
+ return;
1932
+ }
1933
+ const serialized = JSON.stringify(opts ?? {});
1934
+ await run(
1935
+ driver.evaluate(
1936
+ `((clearOpts) => {
1937
+ if (clearOpts.localStorage !== false) {
1938
+ try { window.localStorage.clear(); } catch {}
1939
+ }
1940
+ if (clearOpts.sessionStorage !== false) {
1941
+ try { window.sessionStorage.clear(); } catch {}
1942
+ }
1943
+ })(${serialized})`
1944
+ )
1945
+ );
1946
+ }),
1947
+ resetFast: () => runStep("resetFast", async () => {
1948
+ if (driver.resetFast) {
1949
+ await run(driver.resetFast());
1950
+ return;
1951
+ }
1952
+ if (driver.domChannel?.clearStorage) {
1953
+ await driver.domChannel.clearStorage({
1954
+ localStorage: true,
1955
+ sessionStorage: true,
1956
+ cookies: true,
1957
+ indexedDB: true,
1958
+ capacitorPreferences: true
1959
+ });
1960
+ if (driver.domChannel.reload) {
1961
+ await driver.domChannel.reload();
1962
+ }
1963
+ return;
1964
+ }
1965
+ await run(driver.clearAppState(appId));
1966
+ }),
1967
+ // WebView / hybrid context switching (low-level escape hatches)
1968
+ getContexts: () => runStep(
1969
+ "getContexts",
1970
+ () => run((driver.getContexts ?? (() => Effect5.succeed(["NATIVE_APP"])))())
1971
+ ),
1972
+ getCurrentContext: () => runStep(
1973
+ "getCurrentContext",
1974
+ () => run((driver.getCurrentContext ?? (() => Effect5.succeed("NATIVE_APP")))())
1975
+ ),
1976
+ switchToContext: (contextId) => runStep(
1977
+ `switchToContext(${contextId})`,
1978
+ () => run((driver.setContext ?? ((_id) => Effect5.void))(contextId))
1979
+ ),
1980
+ switchToWebView: () => runStep("switchToWebView", async () => {
1981
+ const contexts = await run(
1982
+ (driver.getContexts ?? (() => Effect5.succeed(["NATIVE_APP"])))()
1983
+ );
1984
+ const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
1985
+ if (!webview) {
1986
+ throw new DriverError({
1987
+ message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
1988
+ });
1989
+ }
1990
+ await run((driver.setContext ?? ((_id) => Effect5.void))(webview));
1991
+ }),
1992
+ switchToNativeApp: () => runStep(
1993
+ "switchToNativeApp",
1994
+ () => run((driver.setContext ?? ((_id) => Effect5.void))("NATIVE_APP"))
1995
+ )
1996
+ };
1997
+ }
1998
+
1999
+ // src/drivers/playwright-parser.ts
2000
+ function rawNodeToElement(node) {
2001
+ const children = node.children && node.children.length > 0 ? node.children.map(rawNodeToElement) : void 0;
2002
+ return {
2003
+ ...node.id !== void 0 ? { id: node.id } : {},
2004
+ ...node.text !== void 0 ? { text: node.text } : {},
2005
+ ...node.value !== void 0 ? { value: node.value } : {},
2006
+ ...node.accessibilityLabel !== void 0 ? { accessibilityLabel: node.accessibilityLabel } : {},
2007
+ // Use role as elementType when present, otherwise fall back to HTML tag name
2008
+ ...node.role !== void 0 ? { elementType: node.role } : node.tag !== void 0 ? { elementType: node.tag } : {},
2009
+ bounds: {
2010
+ x: node.bounds.x,
2011
+ y: node.bounds.y,
2012
+ width: node.bounds.width,
2013
+ height: node.bounds.height
2014
+ },
2015
+ ...node.enabled !== void 0 ? { enabled: node.enabled } : {},
2016
+ ...node.visible !== void 0 ? { visible: node.visible } : {},
2017
+ ...node.clickable !== void 0 ? { clickable: node.clickable } : {},
2018
+ ...node.attributes !== void 0 ? { attributes: node.attributes } : {},
2019
+ ...children !== void 0 ? { children } : {}
2020
+ };
2021
+ }
2022
+ function parseWebHierarchy(json) {
2023
+ const raw = JSON.parse(json);
2024
+ return rawNodeToElement(raw);
2025
+ }
2026
+
2027
+ // src/drivers/raw-driver.ts
2028
+ import { Context, Effect as Effect6 } from "effect";
2029
+ var RawDriver = class extends Context.Tag("RawDriver")() {
2030
+ };
2031
+
2032
+ // src/drivers/playwright.ts
2033
+ import { spawn } from "child_process";
2034
+ import { createHash } from "crypto";
2035
+ import { readFile, writeFile } from "fs/promises";
2036
+ import { Effect as Effect7, Layer } from "effect";
2037
+ import {
2038
+ chromium,
2039
+ firefox,
2040
+ webkit
2041
+ } from "playwright-core";
2042
+
1553
2043
  // src/drivers/network-profiles.ts
1554
2044
  var PROFILES = {
1555
2045
  wifi: {
@@ -1582,6 +2072,30 @@ function resolveNetworkConditions(conditions) {
1582
2072
  }
1583
2073
 
1584
2074
  // src/drivers/playwright.ts
2075
+ async function evaluateOnPage(activePage, script, args) {
2076
+ if (typeof script === "string") {
2077
+ return await activePage.evaluate(script);
2078
+ }
2079
+ if (args.length === 0) {
2080
+ return await activePage.evaluate(script);
2081
+ }
2082
+ if (args.length === 1) {
2083
+ return await activePage.evaluate(script, args[0]);
2084
+ }
2085
+ const fnSource = script.toString();
2086
+ return await activePage.evaluate(
2087
+ ({ src, params }) => {
2088
+ const compiled = (0, eval)(`(${src})`);
2089
+ return compiled(...params);
2090
+ },
2091
+ { src: fnSource, params: args }
2092
+ );
2093
+ }
2094
+ function resolveWarmBrowserKey(scope) {
2095
+ if (scope && scope.trim().length > 0) return scope.trim();
2096
+ const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
2097
+ return `scope-${cwdHash}`;
2098
+ }
1585
2099
  var INSTANT_ANIMATIONS_INIT_SCRIPT = `
1586
2100
  (() => {
1587
2101
  const inject = () => {
@@ -1599,7 +2113,8 @@ var INSTANT_ANIMATIONS_INIT_SCRIPT = `
1599
2113
  })();
1600
2114
  `;
1601
2115
  async function ensureWarmBrowserDaemon(config = {}) {
1602
- const existing = await getHealthyWarmDaemon("chromium", "default", {
2116
+ const daemonKey = resolveWarmBrowserKey(config.warmBrowserScope);
2117
+ const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
1603
2118
  statusPath: "/json/version"
1604
2119
  });
1605
2120
  if (existing) {
@@ -1619,7 +2134,11 @@ async function ensureWarmBrowserDaemon(config = {}) {
1619
2134
  `--remote-debugging-port=${port}`,
1620
2135
  "--no-first-run",
1621
2136
  "--no-default-browser-check",
1622
- "--disable-gpu",
2137
+ "--disable-background-timer-throttling",
2138
+ "--disable-backgrounding-occluded-windows",
2139
+ "--disable-renderer-backgrounding",
2140
+ "--disable-ipc-flooding-protection",
2141
+ ...config.headless !== false ? ["--disable-gpu"] : [],
1623
2142
  "about:blank"
1624
2143
  ],
1625
2144
  { detached: true, stdio: "ignore" }
@@ -1644,7 +2163,7 @@ async function ensureWarmBrowserDaemon(config = {}) {
1644
2163
  }
1645
2164
  registerWarmDaemon({
1646
2165
  kind: "chromium",
1647
- deviceId: "default",
2166
+ deviceId: daemonKey,
1648
2167
  host: "127.0.0.1",
1649
2168
  port,
1650
2169
  pid: child.pid,
@@ -1656,6 +2175,9 @@ async function ensureWarmBrowserDaemon(config = {}) {
1656
2175
  async function connectPlaywrightOverCDP(cdpEndpoint) {
1657
2176
  return chromium.connectOverCDP(cdpEndpoint);
1658
2177
  }
2178
+ async function connectPlaywrightOverWS(wsEndpoint, browserName = "chromium") {
2179
+ return browserLaunchers[browserName].connect(wsEndpoint);
2180
+ }
1659
2181
  async function launchPlaywrightBrowser(config = {}) {
1660
2182
  const browserName = config.browser ?? "chromium";
1661
2183
  return browserLaunchers[browserName].launch({
@@ -1743,18 +2265,23 @@ function totalHarTime(timing) {
1743
2265
  return Math.max(Math.round(end), 0);
1744
2266
  }
1745
2267
  function makePlaywrightDriver(config) {
1746
- return Effect6.gen(function* () {
2268
+ return Effect7.gen(function* () {
1747
2269
  const browserName = config.browser ?? "chromium";
1748
- const ownsBrowser = !config.sharedBrowser && !config.cdpEndpoint && !config.warmBrowser;
1749
- const browser = config.sharedBrowser ? config.sharedBrowser : config.cdpEndpoint ? yield* Effect6.tryPromise({
2270
+ const ownsBrowser = !config.sharedBrowser && !config.cdpEndpoint && !config.wsEndpoint && !config.warmBrowser;
2271
+ const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect7.tryPromise({
2272
+ try: () => browserLaunchers[browserName].connect(config.wsEndpoint),
2273
+ catch: (e) => new DriverError({
2274
+ message: `Failed to connect to remote Playwright server (${config.wsEndpoint}): ${e}`
2275
+ })
2276
+ }) : config.cdpEndpoint ? yield* Effect7.tryPromise({
1750
2277
  try: () => chromium.connectOverCDP(config.cdpEndpoint),
1751
2278
  catch: (e) => new DriverError({
1752
2279
  message: `Failed to connect to browser over CDP (${config.cdpEndpoint}): ${e}`
1753
2280
  })
1754
- }) : config.warmBrowser && browserName === "chromium" ? yield* Effect6.tryPromise({
2281
+ }) : config.warmBrowser && browserName === "chromium" ? yield* Effect7.tryPromise({
1755
2282
  try: async () => (await ensureWarmBrowserDaemon(config)).browser,
1756
2283
  catch: (e) => new DriverError({ message: `Failed to connect to warm Chromium daemon: ${e}` })
1757
- }) : yield* Effect6.tryPromise({
2284
+ }) : yield* Effect7.tryPromise({
1758
2285
  try: () => browserLaunchers[browserName].launch({
1759
2286
  headless: config.headless ?? true,
1760
2287
  ...config.channel ? { channel: config.channel } : {},
@@ -1765,6 +2292,10 @@ function makePlaywrightDriver(config) {
1765
2292
  let context;
1766
2293
  let page;
1767
2294
  let cdpSession;
2295
+ let activeAuthenticatorId;
2296
+ let hasRunFirstFlow = false;
2297
+ let prefetchedSlotPromise;
2298
+ const backgroundCloses = [];
1768
2299
  const routeDefinitions = [];
1769
2300
  let appliedRoutes = [];
1770
2301
  let currentNetworkConditions = {};
@@ -2090,14 +2621,80 @@ function makePlaywrightDriver(config) {
2090
2621
  });
2091
2622
  }
2092
2623
  };
2093
- const createContextAndPage = async (storageStatePath) => {
2094
- context = await browser.newContext({
2624
+ const ensureCdpSession = async (targetCtx = context, targetPage = page) => {
2625
+ if (targetCtx === context && targetPage === page && cdpSession) {
2626
+ return cdpSession;
2627
+ }
2628
+ const session = await targetCtx.newCDPSession(targetPage);
2629
+ if (targetCtx === context && targetPage === page) {
2630
+ cdpSession = session;
2631
+ }
2632
+ return session;
2633
+ };
2634
+ const attachVirtualAuthenticatorOn = async (targetCtx, targetPage, opts) => {
2635
+ if (browserName !== "chromium") {
2636
+ throw new DriverError({
2637
+ message: "enableVirtualAuthenticator() is only supported on Chromium browsers."
2638
+ });
2639
+ }
2640
+ const session = await ensureCdpSession(targetCtx, targetPage);
2641
+ await session.send("WebAuthn.enable", { enableUI: false });
2642
+ const res = await session.send("WebAuthn.addVirtualAuthenticator", {
2643
+ options: {
2644
+ protocol: opts?.protocol ?? "ctap2",
2645
+ transport: opts?.transport ?? "internal",
2646
+ hasResidentKey: opts?.hasResidentKey ?? true,
2647
+ hasUserVerification: opts?.hasUserVerification ?? true,
2648
+ isUserVerified: opts?.isUserVerified ?? true,
2649
+ automaticPresenceSimulation: opts?.automaticPresenceSimulation ?? true
2650
+ }
2651
+ });
2652
+ return { session, authenticatorId: res?.authenticatorId ?? "virtual-auth-1" };
2653
+ };
2654
+ const closeContextInBackground = (oldContext, oldPage, delayMs = 0) => {
2655
+ const trigger = delayMs > 0 ? new Promise((r) => setTimeout(r, delayMs)) : Promise.resolve();
2656
+ const p = trigger.then(() => Promise.allSettled([...oldPage ? [oldPage.close()] : [], oldContext.close()])).catch(() => {
2657
+ }).finally(() => {
2658
+ const idx = backgroundCloses.indexOf(p);
2659
+ if (idx >= 0) backgroundCloses.splice(idx, 1);
2660
+ });
2661
+ backgroundCloses.push(p);
2662
+ };
2663
+ const prepareContextSlot = async (storageStatePath) => {
2664
+ const nextCtx = await browser.newContext({
2095
2665
  acceptDownloads: true,
2096
2666
  ...storageStatePath ? { storageState: storageStatePath } : {}
2097
2667
  });
2098
- await applyContextSpeedOptions(context);
2099
- page = await context.newPage();
2100
- cdpSession = void 0;
2668
+ await applyContextSpeedOptions(nextCtx);
2669
+ const nextPage = await nextCtx.newPage();
2670
+ let nextCdp;
2671
+ let nextAuthId;
2672
+ if (config.virtualAuthenticator && browserName === "chromium") {
2673
+ const authOpts = typeof config.virtualAuthenticator === "object" ? config.virtualAuthenticator : void 0;
2674
+ const attached = await attachVirtualAuthenticatorOn(nextCtx, nextPage, authOpts);
2675
+ nextCdp = attached.session;
2676
+ nextAuthId = attached.authenticatorId;
2677
+ }
2678
+ return {
2679
+ context: nextCtx,
2680
+ page: nextPage,
2681
+ cdpSession: nextCdp,
2682
+ authenticatorId: nextAuthId
2683
+ };
2684
+ };
2685
+ const schedulePrefetchNextContext = () => {
2686
+ if (!config.freshContextPerFlow || prefetchedSlotPromise) return;
2687
+ prefetchedSlotPromise = prepareContextSlot(config.storageState);
2688
+ prefetchedSlotPromise.catch(() => {
2689
+ prefetchedSlotPromise = void 0;
2690
+ });
2691
+ };
2692
+ const createContextAndPage = async (storageStatePath) => {
2693
+ const slot = await prepareContextSlot(storageStatePath);
2694
+ context = slot.context;
2695
+ page = slot.page;
2696
+ cdpSession = slot.cdpSession;
2697
+ activeAuthenticatorId = slot.authenticatorId;
2101
2698
  attachPageDiagnostics(page);
2102
2699
  await reapplyRoutes();
2103
2700
  await applyNetworkConditions();
@@ -2110,7 +2707,7 @@ function makePlaywrightDriver(config) {
2110
2707
  if (url && url !== "about:blank") {
2111
2708
  await page.goto(url);
2112
2709
  }
2113
- await Promise.allSettled([previousPage.close(), previousContext.close()]);
2710
+ closeContextInBackground(previousContext, previousPage);
2114
2711
  };
2115
2712
  const beginFlow = async (flowName) => {
2116
2713
  currentFlowName = flowName;
@@ -2126,20 +2723,36 @@ function makePlaywrightDriver(config) {
2126
2723
  );
2127
2724
  }
2128
2725
  downloadWaiters = [];
2129
- const openPages = context.pages();
2130
- if (openPages.length === 0) {
2131
- page = await context.newPage();
2726
+ if (config.freshContextPerFlow && hasRunFirstFlow) {
2727
+ const previousContext = context;
2728
+ const pendingSlot = prefetchedSlotPromise;
2729
+ prefetchedSlotPromise = void 0;
2730
+ const slot = pendingSlot ? await pendingSlot : await prepareContextSlot(config.storageState);
2731
+ context = slot.context;
2732
+ page = slot.page;
2733
+ cdpSession = slot.cdpSession;
2734
+ activeAuthenticatorId = slot.authenticatorId;
2735
+ attachPageDiagnostics(page);
2736
+ await reapplyRoutes();
2737
+ await applyNetworkConditions();
2738
+ closeContextInBackground(previousContext, void 0, 120);
2132
2739
  } else {
2133
- const [firstPage, ...extraPages] = openPages;
2134
- page = firstPage;
2135
- await Promise.all(extraPages.map((extraPage) => extraPage.close()));
2740
+ const openPages = context.pages();
2741
+ if (openPages.length === 0) {
2742
+ page = await context.newPage();
2743
+ } else {
2744
+ const [firstPage, ...extraPages] = openPages;
2745
+ page = firstPage;
2746
+ await Promise.all(extraPages.map((extraPage) => extraPage.close()));
2747
+ }
2136
2748
  }
2749
+ hasRunFirstFlow = true;
2137
2750
  attachPageDiagnostics(page);
2138
2751
  getTabId(page);
2139
2752
  updateHarPage(page);
2140
2753
  debugLog("beginFlow", flowName);
2141
2754
  };
2142
- yield* Effect6.tryPromise({
2755
+ yield* Effect7.tryPromise({
2143
2756
  try: () => createContextAndPage(config.storageState),
2144
2757
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
2145
2758
  });
@@ -2150,12 +2763,7 @@ function makePlaywrightDriver(config) {
2150
2763
  },
2151
2764
  disconnect: async () => {
2152
2765
  },
2153
- evaluate: async (script, ...args) => {
2154
- if (typeof script === "string") {
2155
- return await page.evaluate(script);
2156
- }
2157
- return await page.evaluate(script, ...args);
2158
- },
2766
+ evaluate: async (script, ...args) => evaluateOnPage(page, script, args),
2159
2767
  query: async (selector) => {
2160
2768
  const res = await page.evaluate(buildDomQueryScript(selector));
2161
2769
  return Array.isArray(res) ? res : [];
@@ -2164,6 +2772,18 @@ function makePlaywrightDriver(config) {
2164
2772
  const res = await page.evaluate(buildDomWaitForSelectorScript(selector, opts));
2165
2773
  return Array.isArray(res) ? res : [];
2166
2774
  },
2775
+ waitForHidden: async (selector, opts) => {
2776
+ const res = await page.evaluate(buildDomWaitForHiddenScript(selector, opts));
2777
+ return Boolean(res);
2778
+ },
2779
+ waitForMatch: async (selector, opts) => {
2780
+ const res = await page.evaluate(buildDomWaitForMatchScript(selector, opts));
2781
+ return res && typeof res === "object" ? res : { matched: false };
2782
+ },
2783
+ fillDom: async (selector, value, opts) => {
2784
+ const res = await page.evaluate(buildDomFillScript(selector, value, opts));
2785
+ return Boolean(res);
2786
+ },
2167
2787
  scrollIntoView: async (selector) => {
2168
2788
  const res = await page.evaluate(buildDomScrollIntoViewScript(selector));
2169
2789
  return res && typeof res === "object" ? res : null;
@@ -2175,11 +2795,11 @@ function makePlaywrightDriver(config) {
2175
2795
  };
2176
2796
  const service = {
2177
2797
  ...domChannel ? { domChannel } : {},
2178
- beginFlow: (flowName) => Effect6.tryPromise({
2798
+ beginFlow: (flowName) => Effect7.tryPromise({
2179
2799
  try: () => beginFlow(flowName),
2180
2800
  catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
2181
2801
  }),
2182
- dumpHierarchy: () => Effect6.tryPromise({
2802
+ dumpHierarchy: () => Effect7.tryPromise({
2183
2803
  try: async () => {
2184
2804
  const tree = await page.evaluate(`
2185
2805
  (function() {
@@ -2214,36 +2834,17 @@ function makePlaywrightDriver(config) {
2214
2834
  },
2215
2835
  catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
2216
2836
  }),
2217
- tapAtCoordinate: (x, y) => Effect6.tryPromise({
2837
+ tapAtCoordinate: (x, y) => Effect7.tryPromise({
2218
2838
  try: async () => {
2219
2839
  await page.mouse.click(x, y);
2220
- await page.evaluate(`
2221
- (function() {
2222
- var el = document.elementFromPoint(${x}, ${y});
2223
- if (!el || (el.tagName !== "INPUT" && el.tagName !== "TEXTAREA" && el.tagName !== "SELECT")) {
2224
- return;
2225
- }
2226
- el.focus();
2227
- return new Promise(function(resolve) {
2228
- requestAnimationFrame(function() {
2229
- var cur = document.elementFromPoint(${x}, ${y});
2230
- if (cur && (cur.tagName === "INPUT" || cur.tagName === "TEXTAREA" || cur.tagName === "SELECT")) {
2231
- cur.focus();
2232
- }
2233
- resolve();
2234
- });
2235
- });
2236
- })()
2237
- `).catch(() => {
2238
- });
2239
2840
  },
2240
2841
  catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
2241
2842
  }),
2242
- doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
2843
+ doubleTapAtCoordinate: (x, y) => Effect7.tryPromise({
2243
2844
  try: () => page.mouse.dblclick(x, y),
2244
2845
  catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
2245
2846
  }),
2246
- longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
2847
+ longPressAtCoordinate: (x, y, duration) => Effect7.tryPromise({
2247
2848
  try: async () => {
2248
2849
  await page.mouse.move(x, y);
2249
2850
  await page.mouse.down();
@@ -2252,7 +2853,7 @@ function makePlaywrightDriver(config) {
2252
2853
  },
2253
2854
  catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
2254
2855
  }),
2255
- swipe: (startX, startY, endX, endY, duration) => Effect6.tryPromise({
2856
+ swipe: (startX, startY, endX, endY, duration) => Effect7.tryPromise({
2256
2857
  try: async () => {
2257
2858
  await page.evaluate(`
2258
2859
  (function() {
@@ -2289,23 +2890,23 @@ function makePlaywrightDriver(config) {
2289
2890
  },
2290
2891
  catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
2291
2892
  }),
2292
- inputText: (text) => Effect6.tryPromise({
2893
+ inputText: (text) => Effect7.tryPromise({
2293
2894
  try: () => page.keyboard.insertText(text),
2294
2895
  catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
2295
2896
  }),
2296
- pressKey: (key) => Effect6.tryPromise({
2897
+ pressKey: (key) => Effect7.tryPromise({
2297
2898
  try: () => page.keyboard.press(key),
2298
2899
  catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
2299
2900
  }),
2300
- hideKeyboard: () => Effect6.void,
2301
- takeScreenshot: () => Effect6.tryPromise({
2901
+ hideKeyboard: () => Effect7.void,
2902
+ takeScreenshot: () => Effect7.tryPromise({
2302
2903
  try: async () => {
2303
2904
  const buffer = await page.screenshot();
2304
2905
  return new Uint8Array(buffer);
2305
2906
  },
2306
2907
  catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
2307
2908
  }),
2308
- getDeviceInfo: () => Effect6.tryPromise({
2909
+ getDeviceInfo: () => Effect7.tryPromise({
2309
2910
  try: async () => {
2310
2911
  const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
2311
2912
  return {
@@ -2320,7 +2921,7 @@ function makePlaywrightDriver(config) {
2320
2921
  },
2321
2922
  catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
2322
2923
  }),
2323
- launchApp: (url, opts) => Effect6.tryPromise({
2924
+ launchApp: (url, opts) => Effect7.tryPromise({
2324
2925
  try: async () => {
2325
2926
  const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
2326
2927
  if (opts?.clearState) {
@@ -2336,11 +2937,12 @@ function makePlaywrightDriver(config) {
2336
2937
  config.waitUntil ? { waitUntil: config.waitUntil } : void 0
2337
2938
  );
2338
2939
  updateHarPage(page);
2940
+ schedulePrefetchNextContext();
2339
2941
  debugLog("launchApp", targetUrl);
2340
2942
  },
2341
2943
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
2342
2944
  }),
2343
- stopApp: (_id) => Effect6.tryPromise({
2945
+ stopApp: (_id) => Effect7.tryPromise({
2344
2946
  try: async () => {
2345
2947
  await page.goto("about:blank");
2346
2948
  updateHarPage(page);
@@ -2348,32 +2950,46 @@ function makePlaywrightDriver(config) {
2348
2950
  },
2349
2951
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
2350
2952
  }),
2351
- killApp: (_id) => Effect6.tryPromise({
2953
+ killApp: (_id) => Effect7.tryPromise({
2352
2954
  try: async () => {
2353
- await Promise.allSettled([
2955
+ const prefetched = prefetchedSlotPromise;
2956
+ prefetchedSlotPromise = void 0;
2957
+ if (ownsBrowser) {
2958
+ await Promise.race([
2959
+ Promise.allSettled([page.close(), context.close(), browser.close()]),
2960
+ new Promise((r) => setTimeout(r, 5e3))
2961
+ ]);
2962
+ return;
2963
+ }
2964
+ const prefetchedClose = prefetched ? prefetched.then((slot) => slot.context.close()).catch(() => {
2965
+ }) : Promise.resolve();
2966
+ const drain = Promise.allSettled([
2354
2967
  page.close(),
2355
2968
  context.close(),
2356
- ...ownsBrowser ? [browser.close()] : []
2969
+ prefetchedClose,
2970
+ ...backgroundCloses
2357
2971
  ]);
2972
+ await Promise.race([drain, new Promise((r) => setTimeout(r, 3e3))]);
2358
2973
  },
2359
2974
  catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
2360
2975
  }),
2361
- clearAppState: (_id) => Effect6.tryPromise({
2976
+ clearAppState: (_id) => Effect7.tryPromise({
2362
2977
  try: async () => {
2363
2978
  await clearStorage();
2364
2979
  debugLog("clearAppState");
2365
2980
  },
2366
2981
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
2367
2982
  }),
2368
- openLink: (url) => Effect6.tryPromise({
2983
+ openLink: (url) => Effect7.tryPromise({
2369
2984
  try: async () => {
2370
2985
  await page.goto(url, config.waitUntil ? { waitUntil: config.waitUntil } : void 0);
2371
2986
  updateHarPage(page);
2987
+ schedulePrefetchNextContext();
2372
2988
  debugLog("openLink", url);
2373
2989
  },
2374
2990
  catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
2375
2991
  }),
2376
- back: () => Effect6.tryPromise({
2992
+ back: () => Effect7.tryPromise({
2377
2993
  try: async () => {
2378
2994
  await page.goBack();
2379
2995
  updateHarPage(page);
@@ -2381,11 +2997,54 @@ function makePlaywrightDriver(config) {
2381
2997
  },
2382
2998
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
2383
2999
  }),
2384
- evaluate: (script, ...args) => Effect6.tryPromise({
2385
- try: () => page.evaluate(script, ...args),
3000
+ evaluate: (script, ...args) => Effect7.tryPromise({
3001
+ try: () => evaluateOnPage(page, script, args),
2386
3002
  catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
2387
3003
  }),
2388
- mockNetwork: (matcher, response) => Effect6.tryPromise({
3004
+ getRawPage: () => page,
3005
+ enableVirtualAuthenticator: (opts) => Effect7.tryPromise({
3006
+ try: async () => {
3007
+ const attached = await attachVirtualAuthenticatorOn(context, page, opts);
3008
+ activeAuthenticatorId = attached.authenticatorId;
3009
+ debugLog("enableVirtualAuthenticator", attached.authenticatorId);
3010
+ return attached.authenticatorId;
3011
+ },
3012
+ catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to enable virtual authenticator: ${e}` })
3013
+ }),
3014
+ removeVirtualAuthenticator: (authenticatorId) => Effect7.tryPromise({
3015
+ try: async () => {
3016
+ const id = authenticatorId ?? activeAuthenticatorId;
3017
+ if (!id) return;
3018
+ const session = await ensureCdpSession();
3019
+ await session.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId: id });
3020
+ if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
3021
+ debugLog("removeVirtualAuthenticator", id);
3022
+ },
3023
+ catch: (e) => new DriverError({ message: `Failed to remove virtual authenticator: ${e}` })
3024
+ }),
3025
+ getVirtualCredentials: (authenticatorId) => Effect7.tryPromise({
3026
+ try: async () => {
3027
+ const id = authenticatorId ?? activeAuthenticatorId;
3028
+ if (!id) return [];
3029
+ const session = await ensureCdpSession();
3030
+ const res = await session.send("WebAuthn.getCredentials", {
3031
+ authenticatorId: id
3032
+ });
3033
+ return Array.isArray(res?.credentials) ? res.credentials : [];
3034
+ },
3035
+ catch: (e) => new DriverError({ message: `Failed to read virtual credentials: ${e}` })
3036
+ }),
3037
+ clearVirtualCredentials: (authenticatorId) => Effect7.tryPromise({
3038
+ try: async () => {
3039
+ const id = authenticatorId ?? activeAuthenticatorId;
3040
+ if (!id) return;
3041
+ const session = await ensureCdpSession();
3042
+ await session.send("WebAuthn.clearCredentials", { authenticatorId: id });
3043
+ debugLog("clearVirtualCredentials", id);
3044
+ },
3045
+ catch: (e) => new DriverError({ message: `Failed to clear virtual credentials: ${e}` })
3046
+ }),
3047
+ mockNetwork: (matcher, response) => Effect7.tryPromise({
2389
3048
  try: async () => {
2390
3049
  buildMockResponse(response);
2391
3050
  const definition = { kind: "mock", matcher, response };
@@ -2395,7 +3054,7 @@ function makePlaywrightDriver(config) {
2395
3054
  },
2396
3055
  catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
2397
3056
  }),
2398
- blockNetwork: (matcher) => Effect6.tryPromise({
3057
+ blockNetwork: (matcher) => Effect7.tryPromise({
2399
3058
  try: async () => {
2400
3059
  const definition = { kind: "block", matcher };
2401
3060
  routeDefinitions.push(definition);
@@ -2404,7 +3063,7 @@ function makePlaywrightDriver(config) {
2404
3063
  },
2405
3064
  catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
2406
3065
  }),
2407
- clearNetworkMocks: () => Effect6.tryPromise({
3066
+ clearNetworkMocks: () => Effect7.tryPromise({
2408
3067
  try: async () => {
2409
3068
  for (const appliedRoute of appliedRoutes) {
2410
3069
  await context.unroute(appliedRoute.matcher, appliedRoute.handler);
@@ -2415,7 +3074,7 @@ function makePlaywrightDriver(config) {
2415
3074
  },
2416
3075
  catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
2417
3076
  }),
2418
- setNetworkConditions: (conditions) => Effect6.tryPromise({
3077
+ setNetworkConditions: (conditions) => Effect7.tryPromise({
2419
3078
  try: async () => {
2420
3079
  currentNetworkConditions = { ...conditions };
2421
3080
  await applyNetworkConditions();
@@ -2423,7 +3082,7 @@ function makePlaywrightDriver(config) {
2423
3082
  },
2424
3083
  catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
2425
3084
  }),
2426
- saveCookies: (path) => Effect6.tryPromise({
3085
+ saveCookies: (path) => Effect7.tryPromise({
2427
3086
  try: async () => {
2428
3087
  const cookies = await context.cookies();
2429
3088
  await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
@@ -2431,7 +3090,7 @@ function makePlaywrightDriver(config) {
2431
3090
  },
2432
3091
  catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
2433
3092
  }),
2434
- loadCookies: (path) => Effect6.tryPromise({
3093
+ loadCookies: (path) => Effect7.tryPromise({
2435
3094
  try: async () => {
2436
3095
  const contents = await readFile(path, "utf8");
2437
3096
  const cookies = JSON.parse(contents);
@@ -2443,14 +3102,14 @@ function makePlaywrightDriver(config) {
2443
3102
  },
2444
3103
  catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
2445
3104
  }),
2446
- saveAuthState: (path) => Effect6.tryPromise({
3105
+ saveAuthState: (path) => Effect7.tryPromise({
2447
3106
  try: async () => {
2448
3107
  await context.storageState({ path });
2449
3108
  debugLog("saveAuthState", path);
2450
3109
  },
2451
3110
  catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
2452
3111
  }),
2453
- loadAuthState: (path) => Effect6.tryPromise({
3112
+ loadAuthState: (path) => Effect7.tryPromise({
2454
3113
  try: async () => {
2455
3114
  await replaceContext(path);
2456
3115
  updateHarPage(page);
@@ -2458,7 +3117,7 @@ function makePlaywrightDriver(config) {
2458
3117
  },
2459
3118
  catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
2460
3119
  }),
2461
- downloadFile: (path) => Effect6.tryPromise({
3120
+ downloadFile: (path) => Effect7.tryPromise({
2462
3121
  try: async () => {
2463
3122
  const download = await nextDownload();
2464
3123
  await download.saveAs(path);
@@ -2466,14 +3125,14 @@ function makePlaywrightDriver(config) {
2466
3125
  },
2467
3126
  catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
2468
3127
  }),
2469
- uploadFile: (selector, path) => Effect6.tryPromise({
3128
+ uploadFile: (selector, path) => Effect7.tryPromise({
2470
3129
  try: async () => {
2471
3130
  await setInputFiles(selector, path);
2472
3131
  debugLog("uploadFile", path);
2473
3132
  },
2474
3133
  catch: (e) => new DriverError({ message: `Failed to upload file ${path}: ${e}` })
2475
3134
  }),
2476
- newTab: (url) => Effect6.tryPromise({
3135
+ newTab: (url) => Effect7.tryPromise({
2477
3136
  try: async () => {
2478
3137
  const nextPage = await context.newPage();
2479
3138
  attachPageDiagnostics(nextPage);
@@ -2488,7 +3147,7 @@ function makePlaywrightDriver(config) {
2488
3147
  },
2489
3148
  catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
2490
3149
  }),
2491
- switchToTab: (index) => Effect6.tryPromise({
3150
+ switchToTab: (index) => Effect7.tryPromise({
2492
3151
  try: async () => {
2493
3152
  const openPages = context.pages();
2494
3153
  const nextPage = openPages[index];
@@ -2504,7 +3163,7 @@ function makePlaywrightDriver(config) {
2504
3163
  },
2505
3164
  catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
2506
3165
  }),
2507
- closeTab: () => Effect6.tryPromise({
3166
+ closeTab: () => Effect7.tryPromise({
2508
3167
  try: async () => {
2509
3168
  const openPages = context.pages();
2510
3169
  if (openPages.length <= 1) {
@@ -2524,14 +3183,14 @@ function makePlaywrightDriver(config) {
2524
3183
  },
2525
3184
  catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
2526
3185
  }),
2527
- getTabIds: () => Effect6.sync(() => {
3186
+ getTabIds: () => Effect7.sync(() => {
2528
3187
  const ids = context.pages().map((openPage) => getTabId(openPage));
2529
3188
  debugLog("getTabIds", ids.join(", "));
2530
3189
  return ids;
2531
3190
  }),
2532
- getConsoleLogs: () => Effect6.succeed([...consoleLogs]),
2533
- getJSErrors: () => Effect6.succeed([...jsErrors]),
2534
- getHAR: () => Effect6.sync(() => ({
3191
+ getConsoleLogs: () => Effect7.succeed([...consoleLogs]),
3192
+ getJSErrors: () => Effect7.succeed([...jsErrors]),
3193
+ getHAR: () => Effect7.sync(() => ({
2535
3194
  log: {
2536
3195
  version: "1.2",
2537
3196
  creator: {
@@ -2551,7 +3210,7 @@ function makePlaywrightDriver(config) {
2551
3210
  }
2552
3211
 
2553
3212
  // src/drivers/uiautomator2/driver.ts
2554
- import { Effect as Effect7 } from "effect";
3213
+ import { Effect as Effect8 } from "effect";
2555
3214
 
2556
3215
  // src/drivers/uiautomator2/client.ts
2557
3216
  var UiAutomator2Client = class {
@@ -2895,7 +3554,7 @@ var UiAutomator2Client = class {
2895
3554
 
2896
3555
  // src/drivers/uiautomator2/driver.ts
2897
3556
  function createUiAutomator2Driver(host, port, serial, packageName, driverOptions) {
2898
- return Effect7.gen(function* () {
3557
+ return Effect8.gen(function* () {
2899
3558
  const client = new UiAutomator2Client(host, port);
2900
3559
  let currentContext = "NATIVE_APP";
2901
3560
  const cdpChannel = driverOptions?.enableWebViewCdp === false ? void 0 : createAndroidWebViewCdpChannel({
@@ -2907,7 +3566,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
2907
3566
  if (driverOptions?.domChannel) channels.push(driverOptions.domChannel);
2908
3567
  if (cdpChannel) channels.push(cdpChannel);
2909
3568
  const domChannel = channels.length === 0 ? void 0 : channels.length === 1 ? channels[0] : createCompositeDomChannel(channels);
2910
- yield* Effect7.tryPromise({
3569
+ yield* Effect8.tryPromise({
2911
3570
  try: () => client.createSession(packageName),
2912
3571
  catch: (e) => new DriverError({
2913
3572
  message: `Failed to create UiAutomator2 session: ${e}`
@@ -2918,70 +3577,70 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
2918
3577
  // -----------------------------------------------------------------------
2919
3578
  // Hierarchy
2920
3579
  // -----------------------------------------------------------------------
2921
- dumpHierarchy: () => Effect7.tryPromise({
3580
+ dumpHierarchy: () => Effect8.tryPromise({
2922
3581
  try: () => client.getSource(),
2923
3582
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
2924
3583
  }),
2925
3584
  // -----------------------------------------------------------------------
2926
3585
  // Coordinate-level actions
2927
3586
  // -----------------------------------------------------------------------
2928
- tapAtCoordinate: (x, y) => Effect7.tryPromise({
3587
+ tapAtCoordinate: (x, y) => Effect8.tryPromise({
2929
3588
  try: () => client.performTap(x, y),
2930
3589
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
2931
3590
  }),
2932
- doubleTapAtCoordinate: (x, y) => Effect7.tryPromise({
3591
+ doubleTapAtCoordinate: (x, y) => Effect8.tryPromise({
2933
3592
  try: async () => {
2934
3593
  await client.performTap(x, y);
2935
3594
  await client.performTap(x, y);
2936
3595
  },
2937
3596
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
2938
3597
  }),
2939
- longPressAtCoordinate: (x, y, duration) => Effect7.tryPromise({
3598
+ longPressAtCoordinate: (x, y, duration) => Effect8.tryPromise({
2940
3599
  try: () => client.performLongPress(x, y, duration),
2941
3600
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
2942
3601
  }),
2943
- swipe: (sx, sy, ex, ey, dur) => Effect7.tryPromise({
3602
+ swipe: (sx, sy, ex, ey, dur) => Effect8.tryPromise({
2944
3603
  try: () => client.performSwipe(sx, sy, ex, ey, dur),
2945
3604
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
2946
3605
  }),
2947
- pinch: (cx, cy, scale, duration) => Effect7.tryPromise({
3606
+ pinch: (cx, cy, scale, duration) => Effect8.tryPromise({
2948
3607
  try: () => client.performPinch(cx, cy, scale, duration),
2949
3608
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
2950
3609
  }),
2951
- zoom: (cx, cy, scale, duration) => Effect7.tryPromise({
3610
+ zoom: (cx, cy, scale, duration) => Effect8.tryPromise({
2952
3611
  try: () => client.performZoom(cx, cy, scale, duration),
2953
3612
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
2954
3613
  }),
2955
- multiTouch: (sequences) => Effect7.tryPromise({
3614
+ multiTouch: (sequences) => Effect8.tryPromise({
2956
3615
  try: () => client.performMultiTouch(sequences),
2957
3616
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
2958
3617
  }),
2959
3618
  // -----------------------------------------------------------------------
2960
3619
  // Text input
2961
3620
  // -----------------------------------------------------------------------
2962
- inputText: (text) => Effect7.tryPromise({
3621
+ inputText: (text) => Effect8.tryPromise({
2963
3622
  try: () => client.sendKeys(text),
2964
3623
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
2965
3624
  }),
2966
- pressKey: (key) => Effect7.tryPromise({
3625
+ pressKey: (key) => Effect8.tryPromise({
2967
3626
  try: () => client.pressKeyCode(parseInt(key, 10) || 0),
2968
3627
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
2969
3628
  }),
2970
- hideKeyboard: () => Effect7.tryPromise({
3629
+ hideKeyboard: () => Effect8.tryPromise({
2971
3630
  try: () => client.hideKeyboard(),
2972
3631
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
2973
3632
  }),
2974
3633
  // -----------------------------------------------------------------------
2975
3634
  // Queries
2976
3635
  // -----------------------------------------------------------------------
2977
- takeScreenshot: () => Effect7.tryPromise({
3636
+ takeScreenshot: () => Effect8.tryPromise({
2978
3637
  try: async () => {
2979
3638
  const base64 = await client.getScreenshot();
2980
3639
  return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
2981
3640
  },
2982
3641
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
2983
3642
  }),
2984
- getDeviceInfo: () => Effect7.tryPromise({
3643
+ getDeviceInfo: () => Effect8.tryPromise({
2985
3644
  try: async () => {
2986
3645
  const size = await client.getWindowSize();
2987
3646
  return {
@@ -2999,7 +3658,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
2999
3658
  // -----------------------------------------------------------------------
3000
3659
  // App lifecycle
3001
3660
  // -----------------------------------------------------------------------
3002
- launchApp: (bundleId, opts) => Effect7.tryPromise({
3661
+ launchApp: (bundleId, opts) => Effect8.tryPromise({
3003
3662
  try: async () => {
3004
3663
  if (opts?.clearState) {
3005
3664
  adbClearApp(serial, bundleId);
@@ -3046,13 +3705,13 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3046
3705
  },
3047
3706
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
3048
3707
  }),
3049
- stopApp: (bundleId) => Effect7.tryPromise({
3708
+ stopApp: (bundleId) => Effect8.tryPromise({
3050
3709
  try: async () => {
3051
3710
  adbForceStop(serial, bundleId);
3052
3711
  },
3053
3712
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
3054
3713
  }),
3055
- killApp: (bundleId) => Effect7.tryPromise({
3714
+ killApp: (bundleId) => Effect8.tryPromise({
3056
3715
  try: async () => {
3057
3716
  await domChannel?.disconnect().catch(() => {
3058
3717
  });
@@ -3061,7 +3720,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3061
3720
  },
3062
3721
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
3063
3722
  }),
3064
- clearAppState: (bundleId) => Effect7.tryPromise({
3723
+ clearAppState: (bundleId) => Effect8.tryPromise({
3065
3724
  try: async () => {
3066
3725
  if (domChannel?.isConnected() && domChannel.clearStorage) {
3067
3726
  await domChannel.clearStorage({
@@ -3081,7 +3740,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3081
3740
  },
3082
3741
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
3083
3742
  }),
3084
- resetFast: () => Effect7.tryPromise({
3743
+ resetFast: () => Effect8.tryPromise({
3085
3744
  try: async () => {
3086
3745
  if (!domChannel) {
3087
3746
  throw new Error("resetFast() requires a connected DOM channel (spana-bridge or CDP)");
@@ -3111,14 +3770,14 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3111
3770
  // -----------------------------------------------------------------------
3112
3771
  // Navigation
3113
3772
  // -----------------------------------------------------------------------
3114
- openLink: (url) => Effect7.tryPromise({
3773
+ openLink: (url) => Effect8.tryPromise({
3115
3774
  try: async () => {
3116
3775
  adbOpenLink(serial, url, packageName);
3117
3776
  await new Promise((resolve2) => setTimeout(resolve2, 1e3));
3118
3777
  },
3119
3778
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
3120
3779
  }),
3121
- back: () => Effect7.tryPromise({
3780
+ back: () => Effect8.tryPromise({
3122
3781
  // KEYCODE_BACK = 4
3123
3782
  try: () => client.pressKeyCode(4),
3124
3783
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
@@ -3127,7 +3786,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3127
3786
  // Direct DOM evaluation via spana-bridge or Android WebView CDP,
3128
3787
  // falling back to UiAutomator2 /execute/sync when no DOM channel attaches.
3129
3788
  // -----------------------------------------------------------------------
3130
- evaluate: (script, ...args) => Effect7.tryPromise({
3789
+ evaluate: (script, ...args) => Effect8.tryPromise({
3131
3790
  try: async () => {
3132
3791
  if (domChannel) {
3133
3792
  try {
@@ -3153,7 +3812,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3153
3812
  },
3154
3813
  catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
3155
3814
  }),
3156
- getContexts: () => Effect7.tryPromise({
3815
+ getContexts: () => Effect8.tryPromise({
3157
3816
  try: async () => {
3158
3817
  const contexts = /* @__PURE__ */ new Set(["NATIVE_APP"]);
3159
3818
  if (domChannel?.listTargets) {
@@ -3176,7 +3835,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3176
3835
  },
3177
3836
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
3178
3837
  }),
3179
- getCurrentContext: () => Effect7.tryPromise({
3838
+ getCurrentContext: () => Effect8.tryPromise({
3180
3839
  try: async () => {
3181
3840
  if (currentContext !== "NATIVE_APP") return currentContext;
3182
3841
  if (typeof client.getCurrentContext === "function") {
@@ -3190,7 +3849,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3190
3849
  },
3191
3850
  catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
3192
3851
  }),
3193
- setContext: (contextId) => Effect7.tryPromise({
3852
+ setContext: (contextId) => Effect8.tryPromise({
3194
3853
  try: async () => {
3195
3854
  if (contextId === "NATIVE_APP") {
3196
3855
  currentContext = "NATIVE_APP";
@@ -3216,7 +3875,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3216
3875
  },
3217
3876
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
3218
3877
  }),
3219
- mockNetwork: (matcher, response) => Effect7.tryPromise({
3878
+ mockNetwork: (matcher, response) => Effect8.tryPromise({
3220
3879
  try: async () => {
3221
3880
  if (!domChannel?.mockNetwork) {
3222
3881
  throw new Error("mockNetwork() on Android requires spana-bridge");
@@ -3225,7 +3884,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3225
3884
  },
3226
3885
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
3227
3886
  }),
3228
- blockNetwork: (matcher) => Effect7.tryPromise({
3887
+ blockNetwork: (matcher) => Effect8.tryPromise({
3229
3888
  try: async () => {
3230
3889
  if (!domChannel?.blockNetwork) {
3231
3890
  throw new Error("blockNetwork() on Android requires spana-bridge");
@@ -3234,7 +3893,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3234
3893
  },
3235
3894
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
3236
3895
  }),
3237
- clearNetworkMocks: () => Effect7.tryPromise({
3896
+ clearNetworkMocks: () => Effect8.tryPromise({
3238
3897
  try: async () => {
3239
3898
  if (domChannel?.clearNetworkMocks) {
3240
3899
  await domChannel.clearNetworkMocks();
@@ -3242,18 +3901,18 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3242
3901
  },
3243
3902
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
3244
3903
  }),
3245
- getConsoleLogs: () => Effect7.tryPromise({
3904
+ getConsoleLogs: () => Effect8.tryPromise({
3246
3905
  try: async () => domChannel?.getConsoleLogs ? domChannel.getConsoleLogs() : [],
3247
3906
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
3248
3907
  }),
3249
- getJSErrors: () => Effect7.tryPromise({
3908
+ getJSErrors: () => Effect8.tryPromise({
3250
3909
  try: async () => domChannel?.getJSErrors ? domChannel.getJSErrors() : [],
3251
3910
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
3252
3911
  }),
3253
3912
  // -----------------------------------------------------------------------
3254
3913
  // Network conditions
3255
3914
  // -----------------------------------------------------------------------
3256
- setNetworkConditions: (conditions) => Effect7.tryPromise({
3915
+ setNetworkConditions: (conditions) => Effect8.tryPromise({
3257
3916
  try: async () => {
3258
3917
  const isEmulator = serial.startsWith("emulator-");
3259
3918
  const resolved = resolveNetworkConditions(conditions);
@@ -3500,7 +4159,7 @@ function parseAndroidHierarchy(xml) {
3500
4159
  }
3501
4160
 
3502
4161
  // src/drivers/wda/driver.ts
3503
- import { Effect as Effect8 } from "effect";
4162
+ import { Effect as Effect9 } from "effect";
3504
4163
 
3505
4164
  // src/drivers/wda/client.ts
3506
4165
  var WDAClient = class {
@@ -3935,7 +4594,7 @@ function isSessionError(error) {
3935
4594
  return msg.includes("session does not exist") || msg.includes("unable to connect") || msg.includes("no active session") || msg.includes("invalid session") || /status[:\s]*404/.test(msg);
3936
4595
  }
3937
4596
  function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth = 100, driverOptions) {
3938
- return Effect8.gen(function* () {
4597
+ return Effect9.gen(function* () {
3939
4598
  const client = new WDAClient(host, port);
3940
4599
  let currentContext = "NATIVE_APP";
3941
4600
  const inspectorChannel = createWebKitInspectorChannel({
@@ -4044,23 +4703,23 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4044
4703
  let reusedWarmSession = false;
4045
4704
  if (driverOptions?.warmSessionId && typeof client.attachSession === "function") {
4046
4705
  client.attachSession(driverOptions.warmSessionId);
4047
- const alive = yield* Effect8.tryPromise({
4706
+ const alive = yield* Effect9.tryPromise({
4048
4707
  try: () => client.isSessionAlive(),
4049
4708
  catch: () => false
4050
- }).pipe(Effect8.catchAll(() => Effect8.succeed(false)));
4709
+ }).pipe(Effect9.catchAll(() => Effect9.succeed(false)));
4051
4710
  reusedWarmSession = alive;
4052
4711
  }
4053
4712
  if (!reusedWarmSession) {
4054
- const createdId = yield* Effect8.tryPromise({
4713
+ const createdId = yield* Effect9.tryPromise({
4055
4714
  try: () => createSessionWithRetry(bundleId || void 0),
4056
4715
  catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
4057
4716
  });
4058
4717
  driverOptions?.onSessionCreated?.(createdId);
4059
- yield* Effect8.tryPromise({
4718
+ yield* Effect9.tryPromise({
4060
4719
  try: () => client.disableQuiescence(),
4061
4720
  catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
4062
4721
  });
4063
- yield* Effect8.tryPromise({
4722
+ yield* Effect9.tryPromise({
4064
4723
  try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
4065
4724
  catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
4066
4725
  });
@@ -4070,27 +4729,27 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4070
4729
  // -----------------------------------------------------------------------
4071
4730
  // Hierarchy
4072
4731
  // -----------------------------------------------------------------------
4073
- dumpHierarchy: () => Effect8.tryPromise({
4732
+ dumpHierarchy: () => Effect9.tryPromise({
4074
4733
  try: () => withSessionRecovery(() => client.getSource()),
4075
4734
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
4076
4735
  }),
4077
4736
  // -----------------------------------------------------------------------
4078
4737
  // Coordinate-level actions
4079
4738
  // -----------------------------------------------------------------------
4080
- tapAtCoordinate: (x, y) => Effect8.tryPromise({
4739
+ tapAtCoordinate: (x, y) => Effect9.tryPromise({
4081
4740
  try: () => withSessionRecovery(() => client.tap(x, y)),
4082
4741
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
4083
4742
  }),
4084
- doubleTapAtCoordinate: (x, y) => Effect8.tryPromise({
4743
+ doubleTapAtCoordinate: (x, y) => Effect9.tryPromise({
4085
4744
  try: () => withSessionRecovery(() => client.doubleTap(x, y)),
4086
4745
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
4087
4746
  }),
4088
- longPressAtCoordinate: (x, y, duration) => Effect8.tryPromise({
4747
+ longPressAtCoordinate: (x, y, duration) => Effect9.tryPromise({
4089
4748
  // duration arrives in ms (spana convention) → convert to seconds for WDA
4090
4749
  try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
4091
4750
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
4092
4751
  }),
4093
- swipe: (sx, sy, ex, ey, dur) => Effect8.tryPromise({
4752
+ swipe: (sx, sy, ex, ey, dur) => Effect9.tryPromise({
4094
4753
  // dur arrives in ms → convert to seconds for WDA.
4095
4754
  // Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
4096
4755
  try: async () => {
@@ -4108,26 +4767,26 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4108
4767
  },
4109
4768
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
4110
4769
  }),
4111
- pinch: (cx, cy, scale, duration) => Effect8.tryPromise({
4770
+ pinch: (cx, cy, scale, duration) => Effect9.tryPromise({
4112
4771
  try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
4113
4772
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
4114
4773
  }),
4115
- zoom: (cx, cy, scale, duration) => Effect8.tryPromise({
4774
+ zoom: (cx, cy, scale, duration) => Effect9.tryPromise({
4116
4775
  try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
4117
4776
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
4118
4777
  }),
4119
- multiTouch: (sequences) => Effect8.tryPromise({
4778
+ multiTouch: (sequences) => Effect9.tryPromise({
4120
4779
  try: () => withSessionRecovery(() => client.multiTouch(sequences)),
4121
4780
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
4122
4781
  }),
4123
4782
  // -----------------------------------------------------------------------
4124
4783
  // Text input
4125
4784
  // -----------------------------------------------------------------------
4126
- inputText: (text) => Effect8.tryPromise({
4785
+ inputText: (text) => Effect9.tryPromise({
4127
4786
  try: () => withSessionRecovery(() => client.sendKeys(text)),
4128
4787
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
4129
4788
  }),
4130
- pressKey: (key) => Effect8.tryPromise({
4789
+ pressKey: (key) => Effect9.tryPromise({
4131
4790
  // WDA uses named hardware buttons; map common names, fall back to home
4132
4791
  try: async () => {
4133
4792
  const buttonMap = {
@@ -4142,7 +4801,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4142
4801
  },
4143
4802
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
4144
4803
  }),
4145
- hideKeyboard: () => Effect8.tryPromise({
4804
+ hideKeyboard: () => Effect9.tryPromise({
4146
4805
  // Dismiss keyboard by tapping above the keyboard area.
4147
4806
  // The previous approach (pressHome) backgrounds the app on iOS.
4148
4807
  try: async () => {
@@ -4155,11 +4814,11 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4155
4814
  // -----------------------------------------------------------------------
4156
4815
  // Queries
4157
4816
  // -----------------------------------------------------------------------
4158
- takeScreenshot: () => Effect8.tryPromise({
4817
+ takeScreenshot: () => Effect9.tryPromise({
4159
4818
  try: () => withSessionRecovery(() => client.getScreenshot()),
4160
4819
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
4161
4820
  }),
4162
- getDeviceInfo: () => Effect8.tryPromise({
4821
+ getDeviceInfo: () => Effect9.tryPromise({
4163
4822
  try: async () => {
4164
4823
  const size = await withSessionRecovery(() => client.getWindowSize());
4165
4824
  return {
@@ -4177,7 +4836,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4177
4836
  // -----------------------------------------------------------------------
4178
4837
  // App lifecycle
4179
4838
  // -----------------------------------------------------------------------
4180
- launchApp: (appBundleId, opts) => Effect8.tryPromise({
4839
+ launchApp: (appBundleId, opts) => Effect9.tryPromise({
4181
4840
  try: async () => {
4182
4841
  if (opts?.clearState && simulatorUdid) {
4183
4842
  terminateOnSimulator(simulatorUdid, appBundleId);
@@ -4235,7 +4894,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4235
4894
  },
4236
4895
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
4237
4896
  }),
4238
- stopApp: (appBundleId) => Effect8.tryPromise({
4897
+ stopApp: (appBundleId) => Effect9.tryPromise({
4239
4898
  try: () => {
4240
4899
  if (simulatorUdid) {
4241
4900
  terminateOnSimulator(simulatorUdid, appBundleId);
@@ -4245,7 +4904,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4245
4904
  },
4246
4905
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
4247
4906
  }),
4248
- killApp: (appBundleId) => Effect8.tryPromise({
4907
+ killApp: (appBundleId) => Effect9.tryPromise({
4249
4908
  try: async () => {
4250
4909
  await domChannel.disconnect().catch(() => {
4251
4910
  });
@@ -4258,7 +4917,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4258
4917
  },
4259
4918
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
4260
4919
  }),
4261
- clearAppState: (appBundleId) => Effect8.tryPromise({
4920
+ clearAppState: (appBundleId) => Effect9.tryPromise({
4262
4921
  try: async () => {
4263
4922
  if (domChannel.isConnected() && domChannel.clearStorage) {
4264
4923
  await domChannel.clearStorage({
@@ -4281,7 +4940,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4281
4940
  },
4282
4941
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
4283
4942
  }),
4284
- resetFast: () => Effect8.tryPromise({
4943
+ resetFast: () => Effect9.tryPromise({
4285
4944
  try: async () => {
4286
4945
  if (domChannel.clearStorage) {
4287
4946
  await domChannel.clearStorage({
@@ -4308,7 +4967,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4308
4967
  // -----------------------------------------------------------------------
4309
4968
  // Navigation
4310
4969
  // -----------------------------------------------------------------------
4311
- openLink: (url) => Effect8.tryPromise({
4970
+ openLink: (url) => Effect9.tryPromise({
4312
4971
  try: async () => {
4313
4972
  if (simulatorUdid) {
4314
4973
  await openSimulatorUrl(url);
@@ -4318,7 +4977,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4318
4977
  },
4319
4978
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
4320
4979
  }),
4321
- back: () => Effect8.tryPromise({
4980
+ back: () => Effect9.tryPromise({
4322
4981
  // iOS has no hardware back button; pressing home is the closest
4323
4982
  // equivalent for dismissing the current context.
4324
4983
  try: () => client.pressHome(),
@@ -4328,13 +4987,13 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4328
4987
  // Direct DOM evaluation via spana-bridge or WebKit Remote Inspector
4329
4988
  // (no Appium required)
4330
4989
  // -----------------------------------------------------------------------
4331
- evaluate: (script, ...args) => Effect8.tryPromise({
4990
+ evaluate: (script, ...args) => Effect9.tryPromise({
4332
4991
  try: () => domChannel.evaluate(script, ...args),
4333
4992
  catch: (e) => new DriverError({
4334
4993
  message: `iOS direct WDA evaluate() failed via ${domChannel.kind}: ${e instanceof Error ? e.message : e}. Ensure WKWebView.isInspectable = true (iOS 16.4+) with ios_webkit_debug_proxy running, or include spana-bridge in test builds.`
4335
4994
  })
4336
4995
  }),
4337
- getContexts: () => Effect8.tryPromise({
4996
+ getContexts: () => Effect9.tryPromise({
4338
4997
  try: async () => {
4339
4998
  const contexts = ["NATIVE_APP"];
4340
4999
  if (domChannel.listTargets) {
@@ -4353,8 +5012,8 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4353
5012
  },
4354
5013
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
4355
5014
  }),
4356
- getCurrentContext: () => Effect8.succeed(currentContext),
4357
- setContext: (contextId) => Effect8.tryPromise({
5015
+ getCurrentContext: () => Effect9.succeed(currentContext),
5016
+ setContext: (contextId) => Effect9.tryPromise({
4358
5017
  try: async () => {
4359
5018
  if (contextId === "NATIVE_APP") {
4360
5019
  currentContext = "NATIVE_APP";
@@ -4374,7 +5033,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4374
5033
  },
4375
5034
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
4376
5035
  }),
4377
- mockNetwork: (matcher, response) => Effect8.tryPromise({
5036
+ mockNetwork: (matcher, response) => Effect9.tryPromise({
4378
5037
  try: async () => {
4379
5038
  if (!domChannel.mockNetwork) {
4380
5039
  throw new Error("mockNetwork() on iOS requires spana-bridge");
@@ -4383,7 +5042,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4383
5042
  },
4384
5043
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
4385
5044
  }),
4386
- blockNetwork: (matcher) => Effect8.tryPromise({
5045
+ blockNetwork: (matcher) => Effect9.tryPromise({
4387
5046
  try: async () => {
4388
5047
  if (!domChannel.blockNetwork) {
4389
5048
  throw new Error("blockNetwork() on iOS requires spana-bridge");
@@ -4392,7 +5051,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4392
5051
  },
4393
5052
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
4394
5053
  }),
4395
- clearNetworkMocks: () => Effect8.tryPromise({
5054
+ clearNetworkMocks: () => Effect9.tryPromise({
4396
5055
  try: async () => {
4397
5056
  if (domChannel.clearNetworkMocks) {
4398
5057
  await domChannel.clearNetworkMocks();
@@ -4400,18 +5059,18 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4400
5059
  },
4401
5060
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
4402
5061
  }),
4403
- getConsoleLogs: () => Effect8.tryPromise({
5062
+ getConsoleLogs: () => Effect9.tryPromise({
4404
5063
  try: async () => domChannel.getConsoleLogs ? domChannel.getConsoleLogs() : [],
4405
5064
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
4406
5065
  }),
4407
- getJSErrors: () => Effect8.tryPromise({
5066
+ getJSErrors: () => Effect9.tryPromise({
4408
5067
  try: async () => domChannel.getJSErrors ? domChannel.getJSErrors() : [],
4409
5068
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
4410
5069
  }),
4411
5070
  // -----------------------------------------------------------------------
4412
5071
  // Network simulation
4413
5072
  // -----------------------------------------------------------------------
4414
- setNetworkConditions: (conditions) => Effect8.tryPromise({
5073
+ setNetworkConditions: (conditions) => Effect9.tryPromise({
4415
5074
  try: async () => {
4416
5075
  if (!simulatorUdid) {
4417
5076
  throw new DriverError({
@@ -4534,7 +5193,7 @@ function parseIOSHierarchy(xml) {
4534
5193
  }
4535
5194
 
4536
5195
  // src/drivers/electron.ts
4537
- import { Effect as Effect9 } from "effect";
5196
+ import { Effect as Effect10 } from "effect";
4538
5197
  import {
4539
5198
  _electron,
4540
5199
  chromium as chromium2
@@ -4578,7 +5237,7 @@ var CLEAR_STORAGE_SCRIPT2 = `
4578
5237
  })();
4579
5238
  `;
4580
5239
  function makeElectronDriver(options) {
4581
- return Effect9.gen(function* () {
5240
+ return Effect10.gen(function* () {
4582
5241
  let electronApp;
4583
5242
  let cdpBrowser;
4584
5243
  let context;
@@ -4602,13 +5261,13 @@ function makeElectronDriver(options) {
4602
5261
  const resolvedCdpUrl = options.cdpUrl ?? (options.cdpPort && !options.entry && !options.executablePath ? `http://127.0.0.1:${options.cdpPort}` : void 0);
4603
5262
  if (resolvedCdpUrl) {
4604
5263
  const connect = options.connectOverCDP ?? chromium2.connectOverCDP.bind(chromium2);
4605
- cdpBrowser = yield* Effect9.tryPromise({
5264
+ cdpBrowser = yield* Effect10.tryPromise({
4606
5265
  try: () => connect(resolvedCdpUrl),
4607
5266
  catch: (e) => new DriverError({
4608
5267
  message: `Failed to connect to Electron over CDP (${resolvedCdpUrl}): ${e}`
4609
5268
  })
4610
5269
  });
4611
- page = yield* Effect9.tryPromise({
5270
+ page = yield* Effect10.tryPromise({
4612
5271
  try: async () => {
4613
5272
  const contexts = cdpBrowser.contexts();
4614
5273
  context = contexts[0];
@@ -4633,7 +5292,7 @@ function makeElectronDriver(options) {
4633
5292
  });
4634
5293
  }
4635
5294
  const launcher = options.launchElectron ?? _electron.launch.bind(_electron);
4636
- electronApp = yield* Effect9.tryPromise({
5295
+ electronApp = yield* Effect10.tryPromise({
4637
5296
  try: () => launcher({
4638
5297
  ...options.executablePath ? { executablePath: options.executablePath } : {},
4639
5298
  ...launchArgs.length > 0 ? { args: launchArgs } : {},
@@ -4642,7 +5301,7 @@ function makeElectronDriver(options) {
4642
5301
  }),
4643
5302
  catch: (e) => new DriverError({ message: `Failed to launch Electron app: ${e}` })
4644
5303
  });
4645
- page = yield* Effect9.tryPromise({
5304
+ page = yield* Effect10.tryPromise({
4646
5305
  try: async () => {
4647
5306
  const win = await electronApp.firstWindow();
4648
5307
  context = electronApp.context();
@@ -4672,26 +5331,26 @@ function makeElectronDriver(options) {
4672
5331
  };
4673
5332
  const service = {
4674
5333
  domChannel,
4675
- beginFlow: () => Effect9.sync(() => {
5334
+ beginFlow: () => Effect10.sync(() => {
4676
5335
  consoleLogs.length = 0;
4677
5336
  jsErrors.length = 0;
4678
5337
  }),
4679
- dumpHierarchy: () => Effect9.tryPromise({
5338
+ dumpHierarchy: () => Effect10.tryPromise({
4680
5339
  try: async () => {
4681
5340
  const tree = await page.evaluate(DOM_HIERARCHY_WALK_SCRIPT);
4682
5341
  return JSON.stringify(tree);
4683
5342
  },
4684
5343
  catch: (e) => new DriverError({ message: `Electron dumpHierarchy failed: ${e}` })
4685
5344
  }),
4686
- tapAtCoordinate: (x, y) => Effect9.tryPromise({
5345
+ tapAtCoordinate: (x, y) => Effect10.tryPromise({
4687
5346
  try: () => page.mouse.click(x, y),
4688
5347
  catch: (e) => new DriverError({ message: `Electron tap failed at (${x}, ${y}): ${e}` })
4689
5348
  }),
4690
- doubleTapAtCoordinate: (x, y) => Effect9.tryPromise({
5349
+ doubleTapAtCoordinate: (x, y) => Effect10.tryPromise({
4691
5350
  try: () => page.mouse.dblclick(x, y),
4692
5351
  catch: (e) => new DriverError({ message: `Electron doubleTap failed at (${x}, ${y}): ${e}` })
4693
5352
  }),
4694
- longPressAtCoordinate: (x, y, duration) => Effect9.tryPromise({
5353
+ longPressAtCoordinate: (x, y, duration) => Effect10.tryPromise({
4695
5354
  try: async () => {
4696
5355
  await page.mouse.move(x, y);
4697
5356
  await page.mouse.down();
@@ -4700,7 +5359,7 @@ function makeElectronDriver(options) {
4700
5359
  },
4701
5360
  catch: (e) => new DriverError({ message: `Electron longPress failed: ${e}` })
4702
5361
  }),
4703
- swipe: (startX, startY, endX, endY, duration) => Effect9.tryPromise({
5362
+ swipe: (startX, startY, endX, endY, duration) => Effect10.tryPromise({
4704
5363
  try: async () => {
4705
5364
  await page.mouse.move(startX, startY);
4706
5365
  await page.mouse.wheel(startX - endX, startY - endY);
@@ -4708,20 +5367,20 @@ function makeElectronDriver(options) {
4708
5367
  },
4709
5368
  catch: (e) => new DriverError({ message: `Electron swipe failed: ${e}` })
4710
5369
  }),
4711
- inputText: (text) => Effect9.tryPromise({
5370
+ inputText: (text) => Effect10.tryPromise({
4712
5371
  try: () => page.keyboard.insertText(text),
4713
5372
  catch: (e) => new DriverError({ message: `Electron inputText failed: ${e}` })
4714
5373
  }),
4715
- pressKey: (key) => Effect9.tryPromise({
5374
+ pressKey: (key) => Effect10.tryPromise({
4716
5375
  try: () => page.keyboard.press(key),
4717
5376
  catch: (e) => new DriverError({ message: `Electron pressKey failed: ${e}` })
4718
5377
  }),
4719
- hideKeyboard: () => Effect9.void,
4720
- takeScreenshot: () => Effect9.tryPromise({
5378
+ hideKeyboard: () => Effect10.void,
5379
+ takeScreenshot: () => Effect10.tryPromise({
4721
5380
  try: async () => new Uint8Array(await page.screenshot()),
4722
5381
  catch: (e) => new DriverError({ message: `Electron screenshot failed: ${e}` })
4723
5382
  }),
4724
- getDeviceInfo: () => Effect9.tryPromise({
5383
+ getDeviceInfo: () => Effect10.tryPromise({
4725
5384
  try: async () => {
4726
5385
  const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
4727
5386
  return {
@@ -4736,7 +5395,7 @@ function makeElectronDriver(options) {
4736
5395
  },
4737
5396
  catch: (e) => new DriverError({ message: `Electron getDeviceInfo failed: ${e}` })
4738
5397
  }),
4739
- launchApp: (appRef, opts) => Effect9.tryPromise({
5398
+ launchApp: (appRef, opts) => Effect10.tryPromise({
4740
5399
  try: async () => {
4741
5400
  if (opts?.clearState) {
4742
5401
  await clearStorageAndCookies();
@@ -4748,8 +5407,8 @@ function makeElectronDriver(options) {
4748
5407
  },
4749
5408
  catch: (e) => new DriverError({ message: `Electron launchApp failed: ${e}` })
4750
5409
  }),
4751
- stopApp: () => Effect9.void,
4752
- killApp: () => Effect9.tryPromise({
5410
+ stopApp: () => Effect10.void,
5411
+ killApp: () => Effect10.tryPromise({
4753
5412
  try: async () => {
4754
5413
  await domChannel?.disconnect().catch(() => {
4755
5414
  });
@@ -4761,32 +5420,32 @@ function makeElectronDriver(options) {
4761
5420
  },
4762
5421
  catch: (e) => new DriverError({ message: `Electron killApp failed: ${e}` })
4763
5422
  }),
4764
- clearAppState: () => Effect9.tryPromise({
5423
+ clearAppState: () => Effect10.tryPromise({
4765
5424
  try: async () => {
4766
5425
  await clearStorageAndCookies();
4767
5426
  },
4768
5427
  catch: (e) => new DriverError({ message: `Electron clearAppState failed: ${e}` })
4769
5428
  }),
4770
- resetFast: () => Effect9.tryPromise({
5429
+ resetFast: () => Effect10.tryPromise({
4771
5430
  try: async () => {
4772
5431
  await clearStorageAndCookies();
4773
5432
  await page.reload();
4774
5433
  },
4775
5434
  catch: (e) => new DriverError({ message: `Electron resetFast failed: ${e}` })
4776
5435
  }),
4777
- openLink: (url) => Effect9.tryPromise({
5436
+ openLink: (url) => Effect10.tryPromise({
4778
5437
  try: async () => {
4779
5438
  await page.goto(url);
4780
5439
  },
4781
5440
  catch: (e) => new DriverError({ message: `Electron openLink failed: ${e}` })
4782
5441
  }),
4783
- back: () => Effect9.tryPromise({
5442
+ back: () => Effect10.tryPromise({
4784
5443
  try: async () => {
4785
5444
  await page.goBack();
4786
5445
  },
4787
5446
  catch: (e) => new DriverError({ message: `Electron back failed: ${e}` })
4788
5447
  }),
4789
- evaluate: (script, ...args) => Effect9.tryPromise({
5448
+ evaluate: (script, ...args) => Effect10.tryPromise({
4790
5449
  try: async () => {
4791
5450
  if (domChannel?.isConnected()) {
4792
5451
  return await domChannel.evaluate(script, ...args);
@@ -4804,7 +5463,7 @@ function makeElectronDriver(options) {
4804
5463
  },
4805
5464
  catch: (e) => new DriverError({ message: `Electron evaluate failed: ${e}` })
4806
5465
  }),
4807
- mockNetwork: (matcher, response) => Effect9.tryPromise({
5466
+ mockNetwork: (matcher, response) => Effect10.tryPromise({
4808
5467
  try: async () => {
4809
5468
  if (!context) throw new Error("No Electron BrowserContext available");
4810
5469
  await context.route(matcher, async (route) => {
@@ -4819,7 +5478,7 @@ function makeElectronDriver(options) {
4819
5478
  },
4820
5479
  catch: (e) => new DriverError({ message: `Electron mockNetwork failed: ${e}` })
4821
5480
  }),
4822
- blockNetwork: (matcher) => Effect9.tryPromise({
5481
+ blockNetwork: (matcher) => Effect10.tryPromise({
4823
5482
  try: async () => {
4824
5483
  if (!context) throw new Error("No Electron BrowserContext available");
4825
5484
  await context.route(matcher, async (route) => {
@@ -4829,7 +5488,7 @@ function makeElectronDriver(options) {
4829
5488
  },
4830
5489
  catch: (e) => new DriverError({ message: `Electron blockNetwork failed: ${e}` })
4831
5490
  }),
4832
- clearNetworkMocks: () => Effect9.tryPromise({
5491
+ clearNetworkMocks: () => Effect10.tryPromise({
4833
5492
  try: async () => {
4834
5493
  if (!context) return;
4835
5494
  for (const entry of appliedRoutes) {
@@ -4840,8 +5499,8 @@ function makeElectronDriver(options) {
4840
5499
  },
4841
5500
  catch: (e) => new DriverError({ message: `Electron clearNetworkMocks failed: ${e}` })
4842
5501
  }),
4843
- getConsoleLogs: () => Effect9.succeed([...consoleLogs]),
4844
- getJSErrors: () => Effect9.succeed([...jsErrors])
5502
+ getConsoleLogs: () => Effect10.succeed([...consoleLogs]),
5503
+ getJSErrors: () => Effect10.succeed([...jsErrors])
4845
5504
  };
4846
5505
  return service;
4847
5506
  });
@@ -4990,23 +5649,24 @@ export {
4990
5649
  hasLaunchDeviceState,
4991
5650
  deviceStateToAppiumCapabilities,
4992
5651
  buildIOSLaunchConfiguration,
4993
- splitGraphemes,
4994
5652
  systemUI,
4995
5653
  isSystemUISelector,
4996
5654
  isTestIDSelector,
5655
+ splitGraphemes,
4997
5656
  flattenElements,
4998
5657
  invalidateWebViewFrameCache,
4999
5658
  findWebViewFrame,
5000
5659
  domRectToScreenBounds,
5001
5660
  isOffscreenInViewport,
5002
5661
  resolveElementAcrossChannels,
5003
- waitForElement,
5004
5662
  createCoordinator,
5005
5663
  buildStorybookUrl,
5664
+ createPromiseApp,
5006
5665
  parseWebHierarchy,
5007
5666
  resolveNetworkConditions,
5008
5667
  ensureWarmBrowserDaemon,
5009
5668
  connectPlaywrightOverCDP,
5669
+ connectPlaywrightOverWS,
5010
5670
  launchPlaywrightBrowser,
5011
5671
  makePlaywrightDriver,
5012
5672
  createUiAutomator2Driver,
@@ -5016,4 +5676,4 @@ export {
5016
5676
  makeElectronDriver,
5017
5677
  setupUiAutomator2
5018
5678
  };
5019
- //# sourceMappingURL=chunk-PJKIXVSO.js.map
5679
+ //# sourceMappingURL=chunk-T5CROOR7.js.map