spana-test 0.9.0 → 0.11.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 (94) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +11 -8
  3. package/dist/agent-fixture-5C4MCWRD.js +20 -0
  4. package/dist/{allure-RAEK4SIH.js → allure-FGVR5LND.js} +5 -1
  5. package/dist/allure-FGVR5LND.js.map +1 -0
  6. package/dist/app-RSDPDTKT.js +10 -0
  7. package/dist/cache-command-PANUAEMZ.js +12 -0
  8. package/dist/{chunk-Y2RZNOKU.js → chunk-26NJXP55.js} +2 -2
  9. package/dist/{chunk-ALPQES3J.js → chunk-3IZMPNE7.js} +549 -2002
  10. package/dist/chunk-3IZMPNE7.js.map +1 -0
  11. package/dist/chunk-4KK4E3N3.js +3587 -0
  12. package/dist/chunk-4KK4E3N3.js.map +1 -0
  13. package/dist/{chunk-IGTK5MHB.js → chunk-4SA7JK5D.js} +23 -15
  14. package/dist/chunk-4SA7JK5D.js.map +1 -0
  15. package/dist/{chunk-PLE7RFQE.js → chunk-64UZQP7Z.js} +52 -3
  16. package/dist/chunk-64UZQP7Z.js.map +1 -0
  17. package/dist/chunk-6PTUVG6A.js +127 -0
  18. package/dist/chunk-6PTUVG6A.js.map +1 -0
  19. package/dist/chunk-FPQAJNE3.js +2874 -0
  20. package/dist/chunk-FPQAJNE3.js.map +1 -0
  21. package/dist/{chunk-3UVSUVHW.js → chunk-FXBWACUT.js} +530 -3360
  22. package/dist/chunk-FXBWACUT.js.map +1 -0
  23. package/dist/chunk-OPTNFLBL.js +556 -0
  24. package/dist/chunk-OPTNFLBL.js.map +1 -0
  25. package/dist/chunk-S7MSBZ3F.js +72 -0
  26. package/dist/chunk-S7MSBZ3F.js.map +1 -0
  27. package/dist/chunk-SGZMO456.js +2125 -0
  28. package/dist/chunk-SGZMO456.js.map +1 -0
  29. package/dist/{chunk-2KRVN4WN.js → chunk-SIJJVN2D.js} +358 -3
  30. package/dist/chunk-SIJJVN2D.js.map +1 -0
  31. package/dist/{chunk-SF7UYW4I.js → chunk-VUNH4AJD.js} +4 -4
  32. package/dist/{chunk-UEWZ2EXL.js → chunk-WS2TVNMY.js} +107 -1976
  33. package/dist/chunk-WS2TVNMY.js.map +1 -0
  34. package/dist/{chunk-FP6PVHHR.js → chunk-WZAQANN6.js} +2 -2
  35. package/dist/{chunk-JZZ2W2XH.js → chunk-XA6LWLZQ.js} +65 -3
  36. package/dist/chunk-XA6LWLZQ.js.map +1 -0
  37. package/dist/cli.js +195 -17
  38. package/dist/cli.js.map +1 -1
  39. package/dist/config-loader-CNGIW2XK.js +9 -0
  40. package/dist/{console-BGAK7Z2L.js → console-DIYEJSSP.js} +9 -2
  41. package/dist/console-DIYEJSSP.js.map +1 -0
  42. package/dist/{discover-RLSKEBAX.js → discover-NKDMB4UI.js} +3 -3
  43. package/dist/{doctor-command-YTCQ2SC7.js → doctor-command-6ZVJWCW7.js} +5 -4
  44. package/dist/{doctor-command-YTCQ2SC7.js.map → doctor-command-6ZVJWCW7.js.map} +1 -1
  45. package/dist/{app-DSh1ejLh.d.ts → flow-DddAj1xv.d.ts} +1002 -355
  46. package/dist/gherkin/steps.d.ts +1 -2
  47. package/dist/{html-JO2YNRWX.js → html-FLMWPFQD.js} +2 -1
  48. package/dist/html-FLMWPFQD.js.map +1 -0
  49. package/dist/index.d.ts +498 -131
  50. package/dist/index.js +491 -278
  51. package/dist/index.js.map +1 -1
  52. package/dist/{junit-HLC62MK6.js → junit-CGB3LKHD.js} +3 -2
  53. package/dist/junit-CGB3LKHD.js.map +1 -0
  54. package/dist/local-DM3YBSV5.js +31 -0
  55. package/dist/{runner-TF4OKPYP.js → runner-WOVZWUQR.js} +6 -2
  56. package/dist/runner-WOVZWUQR.js.map +1 -0
  57. package/dist/{server-IS4K5FCT.js → server-ING5D5ZJ.js} +2 -2
  58. package/dist/server-ING5D5ZJ.js.map +1 -0
  59. package/dist/{server-4YLBAZEM.js → server-JNQ2PLCC.js} +17 -14
  60. package/dist/{server-4YLBAZEM.js.map → server-JNQ2PLCC.js.map} +1 -1
  61. package/dist/session-5TNWVGQQ.js +21 -0
  62. package/dist/session-5TNWVGQQ.js.map +1 -0
  63. package/dist/{session-CgvT-Oso.d.ts → session-uT8xL03K.d.ts} +5 -1
  64. package/dist/{studio-command-RFPV2DS7.js → studio-command-KK7A3KN6.js} +2 -2
  65. package/dist/{test-command-UEJG5AI6.js → test-command-QGIJBRH7.js} +278 -41
  66. package/dist/test-command-QGIJBRH7.js.map +1 -0
  67. package/dist/{validator-BLOLIHUY.js → validator-WO5IL7IY.js} +3 -3
  68. package/dist/validator-WO5IL7IY.js.map +1 -0
  69. package/package.json +10 -10
  70. package/dist/allure-RAEK4SIH.js.map +0 -1
  71. package/dist/chunk-2KRVN4WN.js.map +0 -1
  72. package/dist/chunk-3UVSUVHW.js.map +0 -1
  73. package/dist/chunk-ALPQES3J.js.map +0 -1
  74. package/dist/chunk-IGTK5MHB.js.map +0 -1
  75. package/dist/chunk-JZZ2W2XH.js.map +0 -1
  76. package/dist/chunk-PLE7RFQE.js.map +0 -1
  77. package/dist/chunk-UEWZ2EXL.js.map +0 -1
  78. package/dist/config-loader-F5YAY7RP.js +0 -9
  79. package/dist/console-BGAK7Z2L.js.map +0 -1
  80. package/dist/flow-CSMwD9Fh.d.ts +0 -69
  81. package/dist/html-JO2YNRWX.js.map +0 -1
  82. package/dist/junit-HLC62MK6.js.map +0 -1
  83. package/dist/session-K7FCRKOC.js +0 -18
  84. package/dist/test-command-UEJG5AI6.js.map +0 -1
  85. /package/dist/{config-loader-F5YAY7RP.js.map → agent-fixture-5C4MCWRD.js.map} +0 -0
  86. /package/dist/{discover-RLSKEBAX.js.map → app-RSDPDTKT.js.map} +0 -0
  87. /package/dist/{runner-TF4OKPYP.js.map → cache-command-PANUAEMZ.js.map} +0 -0
  88. /package/dist/{chunk-Y2RZNOKU.js.map → chunk-26NJXP55.js.map} +0 -0
  89. /package/dist/{chunk-SF7UYW4I.js.map → chunk-VUNH4AJD.js.map} +0 -0
  90. /package/dist/{chunk-FP6PVHHR.js.map → chunk-WZAQANN6.js.map} +0 -0
  91. /package/dist/{server-IS4K5FCT.js.map → config-loader-CNGIW2XK.js.map} +0 -0
  92. /package/dist/{session-K7FCRKOC.js.map → discover-NKDMB4UI.js.map} +0 -0
  93. /package/dist/{validator-BLOLIHUY.js.map → local-DM3YBSV5.js.map} +0 -0
  94. /package/dist/{studio-command-RFPV2DS7.js.map → studio-command-KK7A3KN6.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,34 +1,49 @@
1
1
  import {
2
2
  DEFAULT_MAX_WORKERS_PER_PROCESS,
3
- UPLOAD_ATTACH_TIMEOUT_MS,
4
3
  buildPlaybackTraceFromSteps,
4
+ buildRichFlowTrace,
5
+ captureAndroidLogcat,
6
+ captureIosSimulatorCrashLogs,
7
+ checkServerReady,
5
8
  createRemoteFlowClaimer,
6
9
  exportFramesToMp4,
7
10
  extractCodeFrame,
11
+ filterFlowsForProject,
8
12
  formatCodeFrame,
9
- launchDirectCdpBrowser,
10
- makeLightweightCdpDriver,
13
+ isHttpUrlReady,
14
+ isTcpPortOpen,
11
15
  orderFlowsLongestFirst,
12
16
  partitionFlowsAcrossProcesses,
13
17
  planProcessPool,
14
- resolveWebEngine,
18
+ renderTraceViewerHtml,
19
+ resolveProjectExecutionPlan,
15
20
  runMultiProcessPool,
16
- speculativelyPrelaunchWebBrowser,
17
21
  startAndroidVideoRecorder,
18
22
  startCdpScreencastRecorder,
19
23
  startIosSimulatorVideoRecorder,
20
24
  startSharedFlowQueueServer,
25
+ startWebServer,
26
+ startWebServers,
27
+ step,
28
+ suite,
29
+ withActiveStepRecorder,
30
+ writeRichTraceBundle,
21
31
  writeWorkerProcessReport
22
- } from "./chunk-ALPQES3J.js";
32
+ } from "./chunk-FPQAJNE3.js";
23
33
  import {
34
+ NetworkEventBuffer,
24
35
  SPANA_MCP_TOOLS,
25
36
  SpanaMcpServer,
37
+ buildComponentTreeScript,
26
38
  buildFlowFileFromLines,
39
+ buildPerformanceProfileScript,
27
40
  formatSelectorCode
28
- } from "./chunk-2KRVN4WN.js";
41
+ } from "./chunk-SIJJVN2D.js";
29
42
  import {
30
- defineConfig
31
- } from "./chunk-JZZ2W2XH.js";
43
+ clearReplayCache,
44
+ formatCacheInspectTable,
45
+ inspectReplayCache
46
+ } from "./chunk-S7MSBZ3F.js";
32
47
  import "./chunk-X2TJP7LB.js";
33
48
  import {
34
49
  createGitHubPrReporter,
@@ -47,44 +62,46 @@ import {
47
62
  probabilityFromTopLogprobs
48
63
  } from "./chunk-3SH5JQF7.js";
49
64
  import {
50
- byCss,
51
- byRole,
65
+ defineConfig
66
+ } from "./chunk-XA6LWLZQ.js";
67
+ import {
68
+ UPLOAD_ATTACH_TIMEOUT_MS,
69
+ applyExtensionChromeArgs,
70
+ getLoadedExtensions,
71
+ launchDirectCdpBrowser,
72
+ makeLightweightCdpDriver,
73
+ resolveBrowserExtensions,
74
+ resolveWebEngine,
75
+ runOAuthPopupFlow,
76
+ speculativelyPrelaunchWebBrowser
77
+ } from "./chunk-3IZMPNE7.js";
78
+ import {
79
+ ReplayCacheStore,
80
+ ReplaySession,
81
+ buildReplayCacheKey,
82
+ createFlowAgent,
83
+ createOpenAICompatibleAgentProvider,
84
+ formatActionsAsFlowCode,
85
+ isSecretValue,
86
+ replayRecordedAction,
87
+ runExploreSession,
88
+ secret,
89
+ unique
90
+ } from "./chunk-OPTNFLBL.js";
91
+ import {
52
92
  connectPlaywrightOverCDP,
53
93
  connectPlaywrightOverWS,
54
- domRectToScreenBounds,
55
94
  ensureWarmBrowserDaemon,
56
- filterSelector,
57
- findWebViewFrame,
58
- first,
59
- inFrame,
60
- invalidateWebViewFrameCache,
61
- isComposableDomSelector,
62
- isOffscreenInViewport,
63
- isSystemUISelector,
64
- isTestIDSelector,
65
- last,
66
95
  launchPlaywrightBrowser,
67
- makeElectronDriver,
68
- nth,
69
- or,
70
- resolveElementAcrossChannels,
71
- systemUI,
72
- within
73
- } from "./chunk-3UVSUVHW.js";
96
+ makeElectronDriver
97
+ } from "./chunk-FXBWACUT.js";
74
98
  import {
75
99
  AndroidWebViewCdpChannel,
76
100
  AppleWebInspectorClient,
77
101
  CdpDomChannel,
78
- SPANA_INJECTED_RUNTIME_SCRIPT,
79
102
  SpanaBridgeChannel,
80
103
  TARGET_CHANNEL_MATRIX,
81
104
  WebKitInspectorChannel,
82
- buildDomActionabilityDiagScript,
83
- buildDomFillScript,
84
- buildDomWaitForHiddenScript,
85
- buildDomWaitForMatchScript,
86
- buildDomWaitForSelectorScript,
87
- buildInjectedCallScript,
88
105
  createAndroidWebViewCdpChannel,
89
106
  createCdpDomChannel,
90
107
  createCompositeDomChannel,
@@ -100,7 +117,12 @@ import {
100
117
  resolveElectrobunEngine,
101
118
  resolveElectrobunLaunchPlan,
102
119
  resolveTargetDescriptor
103
- } from "./chunk-UEWZ2EXL.js";
120
+ } from "./chunk-WS2TVNMY.js";
121
+ import "./chunk-2AFWVHQK.js";
122
+ import {
123
+ cloneIOSSimulator,
124
+ deleteIOSSimulator
125
+ } from "./chunk-WV3ALL3H.js";
104
126
  import "./chunk-VP6V4XEJ.js";
105
127
  import {
106
128
  DEFAULT_WARM_DAEMON_IDLE_TTL_MS,
@@ -113,22 +135,53 @@ import {
113
135
  sweepOrphanedSpanaBrowsers,
114
136
  updateWarmDaemonSession
115
137
  } from "./chunk-Z6K4QQAR.js";
116
- import {
117
- cloneIOSSimulator,
118
- deleteIOSSimulator
119
- } from "./chunk-WV3ALL3H.js";
120
138
  import {
121
139
  allocateFreePort,
122
140
  assertPortAvailable,
123
141
  isPortAvailable
124
142
  } from "./chunk-JPZCZHL4.js";
143
+ import "./chunk-64UZQP7Z.js";
125
144
  import {
126
145
  comparePngNative,
127
146
  getNativeAcceleratorPath,
128
147
  isNativeAcceleratorActive,
129
148
  tokenizeXmlNative
130
149
  } from "./chunk-54ASKII6.js";
131
- import "./chunk-2AFWVHQK.js";
150
+ import {
151
+ assertDataSnapshot,
152
+ byCss,
153
+ byRole,
154
+ domRectToScreenBounds,
155
+ filterSelector,
156
+ findWebViewFrame,
157
+ first,
158
+ inFrame,
159
+ invalidateWebViewFrameCache,
160
+ isComposableDomSelector,
161
+ isOffscreenInViewport,
162
+ isSystemUISelector,
163
+ isTestIDSelector,
164
+ last,
165
+ matchDataSnapshot,
166
+ nth,
167
+ or,
168
+ resolveElementAcrossChannels,
169
+ systemUI,
170
+ within
171
+ } from "./chunk-4KK4E3N3.js";
172
+ import "./chunk-6PTUVG6A.js";
173
+ import {
174
+ SPANA_INJECTED_RUNTIME_SCRIPT,
175
+ buildDomActionabilityDiagScript,
176
+ buildDomFillScript,
177
+ buildDomQueryScript,
178
+ buildDomScrollIntoViewScript,
179
+ buildDomTapScript,
180
+ buildDomWaitForHiddenScript,
181
+ buildDomWaitForMatchScript,
182
+ buildDomWaitForSelectorScript,
183
+ buildInjectedCallScript
184
+ } from "./chunk-SGZMO456.js";
132
185
  import "./chunk-DGUM43GV.js";
133
186
 
134
187
  // src/api/flow.ts
@@ -138,6 +191,19 @@ function flow(name, configOrFn, maybeFn) {
138
191
  }
139
192
  return { name, fn: maybeFn, config: configOrFn };
140
193
  }
194
+ function modifyFlow(modifier) {
195
+ function modified(name, configOrFn, maybeFn) {
196
+ const config = typeof configOrFn === "function" ? {} : configOrFn;
197
+ const fn = typeof configOrFn === "function" ? configOrFn : maybeFn;
198
+ return flow(name, { ...config, [modifier]: config[modifier] ?? true }, fn);
199
+ }
200
+ return modified;
201
+ }
202
+ ((flow2) => {
203
+ flow2.skip = modifyFlow("skip");
204
+ flow2.fixme = modifyFlow("fixme");
205
+ flow2.only = modifyFlow("only");
206
+ })(flow || (flow = {}));
141
207
 
142
208
  // src/schemas/element.ts
143
209
  import { Schema } from "effect";
@@ -161,6 +227,10 @@ var Element = Schema.Struct({
161
227
  visible: Schema.optional(Schema.Boolean),
162
228
  clickable: Schema.optional(Schema.Boolean),
163
229
  focused: Schema.optional(Schema.Boolean),
230
+ checked: Schema.optional(Schema.Boolean),
231
+ editable: Schema.optional(Schema.Boolean),
232
+ empty: Schema.optional(Schema.Boolean),
233
+ className: Schema.optional(Schema.String),
164
234
  attributes: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),
165
235
  children: Schema.optional(
166
236
  Schema.Array(Schema.suspend(() => Element))
@@ -595,256 +665,30 @@ var PersonaAuthCache = class {
595
665
  }
596
666
  };
597
667
 
598
- // src/core/replay-cache.ts
599
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
600
- import { dirname, join } from "path";
601
- import { createHash } from "crypto";
602
- function buildReplayCacheKey(flowName, platform, goal) {
603
- const hash = createHash("sha256").update(`${flowName}\0${platform}\0${goal.trim()}`).digest("hex").slice(0, 16);
604
- const slug = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "").slice(0, 40);
605
- return `${slug || "flow"}-${platform}-${hash}`;
606
- }
607
- var ReplayCacheStore = class {
608
- cacheDir;
609
- constructor(cacheDir = ".spana/cache") {
610
- this.cacheDir = cacheDir;
611
- }
612
- filePath(key) {
613
- return join(this.cacheDir, `${key}.json`);
614
- }
615
- get(key) {
616
- const p = this.filePath(key);
617
- if (!existsSync(p)) return null;
618
- try {
619
- const raw = readFileSync(p, "utf-8");
620
- const parsed = JSON.parse(raw);
621
- if (parsed.schemaVersion !== 1 || !Array.isArray(parsed.actions)) return null;
622
- return parsed;
623
- } catch {
624
- return null;
625
- }
626
- }
627
- set(entry) {
628
- const p = this.filePath(entry.key);
629
- mkdirSync(dirname(p), { recursive: true });
630
- writeFileSync(p, JSON.stringify(entry, null, 2), "utf-8");
631
- }
632
- delete(key) {
633
- const p = this.filePath(key);
634
- if (!existsSync(p)) return false;
635
- rmSync(p, { force: true });
636
- return true;
637
- }
638
- };
639
- async function replayRecordedAction(app, action) {
640
- switch (action.kind) {
641
- case "tap":
642
- await app.tap(action.selector);
643
- break;
644
- case "doubleTap":
645
- await app.doubleTap(action.selector);
646
- break;
647
- case "longPress":
648
- await app.longPress(action.selector);
649
- break;
650
- case "inputText":
651
- await app.inputText(action.text);
652
- break;
653
- case "pressKey":
654
- await app.pressKey(action.key);
655
- break;
656
- case "scroll":
657
- await app.scroll(action.direction);
658
- break;
659
- case "scrollUntilVisible":
660
- await app.scrollUntilVisible(action.selector);
661
- break;
662
- case "openLink":
663
- await app.openLink(action.url);
664
- break;
665
- }
666
- }
667
- var ReplaySession = class {
668
- flowName;
669
- platform;
670
- app;
671
- store;
672
- mode;
673
- executor;
674
- pendingWrites = [];
675
- replayedKeys = [];
676
- outcomes = [];
677
- constructor(options) {
678
- this.flowName = options.flowName;
679
- this.platform = options.platform;
680
- this.app = options.app;
681
- this.store = options.store ?? new ReplayCacheStore();
682
- this.mode = options.mode ?? "read-write";
683
- this.executor = options.executor;
684
- }
685
- /** Execute a natural-language goal using replay cache first, falling back to `executor`. */
686
- async act(goal) {
687
- const key = buildReplayCacheKey(this.flowName, this.platform, goal);
688
- const cached = this.mode === "off" ? null : this.store.get(key);
689
- if (cached && cached.actions.length > 0) {
690
- try {
691
- for (const action of cached.actions) {
692
- await replayRecordedAction(this.app, action);
693
- }
694
- const outcome = {
695
- goal,
696
- key,
697
- status: "replayed",
698
- writeStatus: "kept",
699
- actionCount: cached.actions.length
700
- };
701
- const idx = this.outcomes.push(outcome) - 1;
702
- this.replayedKeys.push({ key, outcomeIndex: idx });
703
- return outcome;
704
- } catch (err) {
705
- const errMsg = err instanceof Error ? err.message : String(err);
706
- if (this.mode === "strict") {
707
- throw new Error(
708
- `Strict replay cache mismatch for "${goal}" (${key}): ${errMsg}. Re-run locally without --strict-cache to self-heal and update .spana/cache/.`,
709
- { cause: err }
710
- );
711
- }
712
- return this.runLiveAndQueue(goal, key, true, errMsg);
713
- }
714
- }
715
- if (this.mode === "strict") {
716
- throw new Error(
717
- `Strict replay cache miss for "${goal}" (${key}). No verified recording found in ${this.store.cacheDir}.`
718
- );
719
- }
720
- return this.runLiveAndQueue(goal, key, false);
721
- }
722
- async runLiveAndQueue(goal, key, wasExisting, handoffReason) {
723
- if (!this.executor) {
724
- throw new Error(
725
- `No agent executor configured for goal "${goal}" and no cached replay exists.`
726
- );
727
- }
728
- const result = await this.executor.act({
729
- goal,
730
- app: this.app,
731
- handoffReason
732
- });
733
- const outcome = {
734
- goal,
735
- key,
736
- status: wasExisting ? "handed-off" : this.mode === "off" ? "live" : "missed",
737
- writeStatus: this.mode === "off" ? "skipped" : "unconfirmed",
738
- actionCount: result.actions.length
739
- };
740
- const idx = this.outcomes.push(outcome) - 1;
741
- if (this.mode === "read-write" && result.actions.length > 0) {
742
- this.pendingWrites.push({
743
- wasExisting,
744
- outcomeIndex: idx,
745
- entry: {
746
- schemaVersion: 1,
747
- key,
748
- goal,
749
- flowName: this.flowName,
750
- platform: this.platform,
751
- actions: result.actions,
752
- recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
753
- verifiedBy: ""
754
- }
755
- });
756
- }
757
- return outcome;
758
- }
759
- /**
760
- * Call when a real post-action assertion (`expect(...).toBeVisible()`, `toHaveText()`, etc.)
761
- * succeeds. Flushes all preceding pending recordings to disk in `read-write` mode.
762
- */
763
- markVerified(verifierName) {
764
- if (this.mode !== "read-write") return 0;
765
- let saved = 0;
766
- for (const pending of this.pendingWrites) {
767
- pending.entry.verifiedBy = verifierName;
768
- this.store.set(pending.entry);
769
- this.outcomes[pending.outcomeIndex].writeStatus = "saved";
770
- saved += 1;
771
- }
772
- this.pendingWrites = [];
773
- return saved;
774
- }
775
- /**
776
- * Call when the flow attempt fails: evicts any replayed recordings involved in the
777
- * failure (in `read-write` mode) and discards unconfirmed recordings so broken paths
778
- * are never persisted.
779
- */
780
- markFailed() {
781
- let evicted = 0;
782
- if (this.mode === "read-write") {
783
- for (const replayed of this.replayedKeys) {
784
- if (this.store.delete(replayed.key)) {
785
- this.outcomes[replayed.outcomeIndex].writeStatus = "evicted";
786
- evicted += 1;
787
- }
788
- }
789
- for (const pending of this.pendingWrites) {
790
- if (pending.wasExisting && this.store.delete(pending.entry.key)) {
791
- this.outcomes[pending.outcomeIndex].writeStatus = "evicted";
792
- evicted += 1;
793
- }
794
- }
795
- }
796
- this.pendingWrites = [];
797
- this.replayedKeys = [];
798
- return evicted;
799
- }
800
- getOutcomes() {
801
- return [...this.outcomes];
802
- }
803
- getSummary() {
804
- const summary = {
805
- replayed: 0,
806
- handedOff: 0,
807
- missed: 0,
808
- saved: 0,
809
- evicted: 0,
810
- unconfirmed: 0
811
- };
812
- for (const o of this.outcomes) {
813
- if (o.status === "replayed") summary.replayed++;
814
- else if (o.status === "handed-off") summary.handedOff++;
815
- else if (o.status === "missed") summary.missed++;
816
- if (o.writeStatus === "saved") summary.saved++;
817
- else if (o.writeStatus === "evicted") summary.evicted++;
818
- else if (o.writeStatus === "unconfirmed") summary.unconfirmed++;
819
- }
820
- return summary;
821
- }
822
- };
823
-
824
668
  // src/core/network-cache.ts
825
- import { createHash as createHash2 } from "crypto";
826
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
827
- import { join as join2 } from "path";
669
+ import { createHash } from "crypto";
670
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
671
+ import { join } from "path";
828
672
  function buildNetworkCacheKey(method, url) {
829
673
  const normalizedMethod = method.toUpperCase();
830
- const hash = createHash2("sha256").update(`${normalizedMethod} ${url}`).digest("hex").slice(0, 16);
674
+ const hash = createHash("sha256").update(`${normalizedMethod} ${url}`).digest("hex").slice(0, 16);
831
675
  const slug = url.replace(/^https?:\/\//, "").replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 48);
832
676
  return `${normalizedMethod.toLowerCase()}-${slug}-${hash}`;
833
677
  }
834
678
  var NetworkReplayCache = class {
835
679
  cacheDir;
836
680
  constructor(options = {}) {
837
- this.cacheDir = options.cacheDir ?? join2(process.cwd(), ".spana", "network-cache");
681
+ this.cacheDir = options.cacheDir ?? join(process.cwd(), ".spana", "network-cache");
838
682
  }
839
683
  entryPath(key) {
840
- return join2(this.cacheDir, `${key}.json`);
684
+ return join(this.cacheDir, `${key}.json`);
841
685
  }
842
686
  get(method, url) {
843
687
  const key = buildNetworkCacheKey(method, url);
844
688
  const filePath = this.entryPath(key);
845
- if (!existsSync2(filePath)) return null;
689
+ if (!existsSync(filePath)) return null;
846
690
  try {
847
- const parsed = JSON.parse(readFileSync2(filePath, "utf8"));
691
+ const parsed = JSON.parse(readFileSync(filePath, "utf8"));
848
692
  if (parsed && parsed.version === 1 && typeof parsed.body === "string") {
849
693
  return parsed;
850
694
  }
@@ -853,7 +697,7 @@ var NetworkReplayCache = class {
853
697
  return null;
854
698
  }
855
699
  set(entry) {
856
- mkdirSync2(this.cacheDir, { recursive: true });
700
+ mkdirSync(this.cacheDir, { recursive: true });
857
701
  const key = buildNetworkCacheKey(entry.method, entry.url);
858
702
  const record = {
859
703
  version: 1,
@@ -866,7 +710,7 @@ var NetworkReplayCache = class {
866
710
  body: entry.body,
867
711
  recordedAt: (/* @__PURE__ */ new Date()).toISOString()
868
712
  };
869
- writeFileSync2(this.entryPath(key), JSON.stringify(record, null, 2), "utf8");
713
+ writeFileSync(this.entryPath(key), JSON.stringify(record, null, 2), "utf8");
870
714
  return record;
871
715
  }
872
716
  /**
@@ -923,12 +767,345 @@ async function attachNetworkReplayCache(app, options) {
923
767
  totalRoutes: options.routes.length
924
768
  };
925
769
  }
770
+
771
+ // src/channels/bidi-client.ts
772
+ function deserializeBidiRemoteValue(remote) {
773
+ if (!remote || typeof remote !== "object") return remote;
774
+ const obj = remote;
775
+ const type = obj["type"];
776
+ switch (type) {
777
+ case "undefined":
778
+ return void 0;
779
+ case "null":
780
+ return null;
781
+ case "string":
782
+ case "boolean":
783
+ case "number":
784
+ return obj["value"];
785
+ case "bigint":
786
+ return BigInt(String(obj["value"] ?? "0"));
787
+ case "array":
788
+ case "set":
789
+ return Array.isArray(obj["value"]) ? obj["value"].map(deserializeBidiRemoteValue) : [];
790
+ case "object": {
791
+ const out = {};
792
+ if (Array.isArray(obj["value"])) {
793
+ for (const pair of obj["value"]) {
794
+ if (!Array.isArray(pair) || pair.length < 2) continue;
795
+ const k = typeof pair[0] === "string" ? pair[0] : String(deserializeBidiRemoteValue(pair[0]));
796
+ out[k] = deserializeBidiRemoteValue(pair[1]);
797
+ }
798
+ }
799
+ return out;
800
+ }
801
+ default:
802
+ return "value" in obj ? obj["value"] : obj;
803
+ }
804
+ }
805
+ var WebDriverBidiClient = class {
806
+ webSocketUrl;
807
+ commandTimeoutMs;
808
+ createWebSocket;
809
+ ws = null;
810
+ nextId = 1;
811
+ pending = /* @__PURE__ */ new Map();
812
+ eventListeners = /* @__PURE__ */ new Map();
813
+ activeContextId;
814
+ constructor(options) {
815
+ this.webSocketUrl = options.webSocketUrl;
816
+ this.activeContextId = options.contextId;
817
+ this.commandTimeoutMs = options.commandTimeoutMs ?? 15e3;
818
+ this.createWebSocket = options.createWebSocket ?? ((url) => new WebSocket(url));
819
+ }
820
+ get contextId() {
821
+ return this.activeContextId;
822
+ }
823
+ isConnected() {
824
+ return this.ws !== null && this.ws.readyState === 1;
825
+ }
826
+ async connect() {
827
+ if (this.isConnected()) return;
828
+ await new Promise((resolve, reject) => {
829
+ const ws = this.createWebSocket(this.webSocketUrl);
830
+ this.ws = ws;
831
+ let settled = false;
832
+ const done = (err) => {
833
+ if (settled) return;
834
+ settled = true;
835
+ if (err) reject(err);
836
+ else resolve();
837
+ };
838
+ ws.addEventListener("open", () => done());
839
+ ws.addEventListener(
840
+ "error",
841
+ (ev) => done(new Error(`BiDi WebSocket error: ${String(ev?.message ?? ev)}`))
842
+ );
843
+ ws.addEventListener("close", () => {
844
+ for (const [, p] of this.pending) {
845
+ clearTimeout(p.timer);
846
+ p.reject(new Error("WebDriver BiDi WebSocket closed"));
847
+ }
848
+ this.pending.clear();
849
+ this.ws = null;
850
+ });
851
+ ws.addEventListener("message", (ev) => {
852
+ this.handleMessage(typeof ev?.data === "string" ? ev.data : String(ev?.data ?? ""));
853
+ });
854
+ if (ws.readyState === 1) done();
855
+ });
856
+ if (!this.activeContextId) {
857
+ const tree = await this.send("browsingContext.getTree", {}).catch(() => null);
858
+ const contexts = tree?.["contexts"] ?? [];
859
+ if (contexts[0]?.context) {
860
+ this.activeContextId = contexts[0].context;
861
+ }
862
+ }
863
+ }
864
+ async disconnect() {
865
+ const ws = this.ws;
866
+ this.ws = null;
867
+ for (const [, p] of this.pending) {
868
+ clearTimeout(p.timer);
869
+ p.reject(new Error("WebDriver BiDi client disconnected"));
870
+ }
871
+ this.pending.clear();
872
+ if (ws) {
873
+ try {
874
+ ws.close();
875
+ } catch {
876
+ }
877
+ }
878
+ }
879
+ async send(method, params = {}) {
880
+ if (!this.ws) {
881
+ throw new Error(`WebDriver BiDi client is not connected (attempted ${method})`);
882
+ }
883
+ const id = this.nextId++;
884
+ return new Promise((resolve, reject) => {
885
+ const timer = setTimeout(() => {
886
+ this.pending.delete(id);
887
+ reject(
888
+ new Error(
889
+ `WebDriver BiDi command timed out (${method}) after ${this.commandTimeoutMs}ms`
890
+ )
891
+ );
892
+ }, this.commandTimeoutMs);
893
+ this.pending.set(id, { resolve, reject, timer });
894
+ this.ws.send(JSON.stringify({ id, method, params }));
895
+ });
896
+ }
897
+ onEvent(method, listener) {
898
+ let set = this.eventListeners.get(method);
899
+ if (!set) {
900
+ set = /* @__PURE__ */ new Set();
901
+ this.eventListeners.set(method, set);
902
+ }
903
+ set.add(listener);
904
+ return () => {
905
+ set?.delete(listener);
906
+ };
907
+ }
908
+ async subscribe(events, contexts) {
909
+ await this.send("session.subscribe", {
910
+ events,
911
+ ...contexts ? { contexts } : {}
912
+ });
913
+ }
914
+ async navigate(url, wait = "interactive") {
915
+ const context = this.requireContextId();
916
+ await this.send("browsingContext.navigate", { context, url, wait });
917
+ }
918
+ async reload(wait = "interactive") {
919
+ const context = this.requireContextId();
920
+ await this.send("browsingContext.reload", { context, wait });
921
+ }
922
+ async evaluate(expression, awaitPromise = true) {
923
+ const context = this.requireContextId();
924
+ const res = await this.send("script.evaluate", {
925
+ expression,
926
+ target: { context },
927
+ awaitPromise,
928
+ resultOwnership: "none"
929
+ });
930
+ if (res["type"] === "exception") {
931
+ const details = res["exceptionDetails"];
932
+ throw new Error(`BiDi script exception: ${details?.text ?? JSON.stringify(details)}`);
933
+ }
934
+ return deserializeBidiRemoteValue(res["result"]);
935
+ }
936
+ async captureScreenshot() {
937
+ const context = this.requireContextId();
938
+ const res = await this.send("browsingContext.captureScreenshot", { context });
939
+ return new Uint8Array(Buffer.from(String(res["data"] ?? ""), "base64"));
940
+ }
941
+ requireContextId() {
942
+ if (!this.activeContextId) {
943
+ throw new Error("No active WebDriver BiDi browsing context.");
944
+ }
945
+ return this.activeContextId;
946
+ }
947
+ handleMessage(raw) {
948
+ let msg;
949
+ try {
950
+ msg = JSON.parse(raw);
951
+ } catch {
952
+ return;
953
+ }
954
+ if (typeof msg["id"] === "number") {
955
+ const pending = this.pending.get(msg["id"]);
956
+ if (!pending) return;
957
+ this.pending.delete(msg["id"]);
958
+ clearTimeout(pending.timer);
959
+ if (msg["type"] === "error") {
960
+ pending.reject(
961
+ new Error(
962
+ `WebDriver BiDi error (${String(msg["error"] ?? "unknown")}): ${String(msg["message"] ?? "")}`
963
+ )
964
+ );
965
+ } else {
966
+ pending.resolve(msg["result"] ?? {});
967
+ }
968
+ return;
969
+ }
970
+ if (msg["type"] === "event" && typeof msg["method"] === "string") {
971
+ const listeners = this.eventListeners.get(msg["method"]);
972
+ if (listeners) {
973
+ const params = msg["params"] ?? {};
974
+ for (const fn of listeners) {
975
+ try {
976
+ fn(params);
977
+ } catch {
978
+ }
979
+ }
980
+ }
981
+ }
982
+ }
983
+ };
984
+ var BidiDomChannel = class {
985
+ kind = "bidi";
986
+ client;
987
+ constructor(options) {
988
+ this.client = new WebDriverBidiClient(options);
989
+ }
990
+ isConnected() {
991
+ return this.client.isConnected();
992
+ }
993
+ async connect() {
994
+ await this.client.connect();
995
+ }
996
+ async disconnect() {
997
+ await this.client.disconnect();
998
+ }
999
+ async getTargetInfo() {
1000
+ const info = await this.client.evaluate(
1001
+ "({ url: window.location.href, title: document.title })",
1002
+ false
1003
+ );
1004
+ return {
1005
+ id: this.client.contextId ?? "bidi-context",
1006
+ url: info?.url,
1007
+ title: info?.title,
1008
+ type: "page"
1009
+ };
1010
+ }
1011
+ async query(selector) {
1012
+ const res = await this.client.evaluate(buildDomQueryScript(selector), false);
1013
+ return Array.isArray(res) ? res : [];
1014
+ }
1015
+ async evaluate(script, ...args) {
1016
+ if (typeof script === "string") {
1017
+ return this.client.evaluate(script, true);
1018
+ }
1019
+ const serializedArgs = args.map((a) => JSON.stringify(a)).join(", ");
1020
+ return this.client.evaluate(`(${script.toString()})(${serializedArgs})`, true);
1021
+ }
1022
+ async waitForIdle(options) {
1023
+ const quietMs = 150;
1024
+ const timeoutMs = Math.max(50, options?.timeout ?? 5e3);
1025
+ await this.client.evaluate(
1026
+ `new Promise((resolve) => {
1027
+ const deadline = setTimeout(resolve, ${timeoutMs});
1028
+ requestAnimationFrame(() => setTimeout(() => { clearTimeout(deadline); resolve(undefined); }, ${quietMs}));
1029
+ })`,
1030
+ true
1031
+ );
1032
+ }
1033
+ async scrollIntoView(selector) {
1034
+ return this.client.evaluate(
1035
+ buildDomScrollIntoViewScript(selector),
1036
+ false
1037
+ );
1038
+ }
1039
+ async tapDom(selector) {
1040
+ return Boolean(await this.client.evaluate(buildDomTapScript(selector), false));
1041
+ }
1042
+ async fillDom(selector, value, options) {
1043
+ return Boolean(
1044
+ await this.client.evaluate(buildDomFillScript(selector, value, options), true)
1045
+ );
1046
+ }
1047
+ async waitForSelector(selector, options) {
1048
+ const res = await this.client.evaluate(
1049
+ buildDomWaitForSelectorScript(selector, options),
1050
+ true
1051
+ );
1052
+ return Array.isArray(res) ? res : [];
1053
+ }
1054
+ async waitForHidden(selector, options) {
1055
+ return Boolean(
1056
+ await this.client.evaluate(buildDomWaitForHiddenScript(selector, options), true)
1057
+ );
1058
+ }
1059
+ async waitForMatch(selector, options) {
1060
+ return this.client.evaluate(
1061
+ buildDomWaitForMatchScript(selector, options),
1062
+ true
1063
+ );
1064
+ }
1065
+ async setStorage(entries) {
1066
+ const serialized = JSON.stringify(entries);
1067
+ await this.client.evaluate(
1068
+ `((payload) => {
1069
+ if (payload.localStorage) {
1070
+ for (const [k, v] of Object.entries(payload.localStorage)) window.localStorage.setItem(k, String(v));
1071
+ }
1072
+ if (payload.sessionStorage) {
1073
+ for (const [k, v] of Object.entries(payload.sessionStorage)) window.sessionStorage.setItem(k, String(v));
1074
+ }
1075
+ if (payload.cookies) {
1076
+ for (const c of payload.cookies) {
1077
+ document.cookie = encodeURIComponent(c.name) + "=" + encodeURIComponent(c.value) + "; path=" + (c.path || "/");
1078
+ }
1079
+ }
1080
+ })(${serialized})`,
1081
+ false
1082
+ );
1083
+ }
1084
+ async clearStorage(options) {
1085
+ const serialized = JSON.stringify(options ?? {});
1086
+ await this.client.evaluate(
1087
+ `((opts) => {
1088
+ if (opts.localStorage !== false) { try { window.localStorage.clear(); } catch {} }
1089
+ if (opts.sessionStorage !== false) { try { window.sessionStorage.clear(); } catch {} }
1090
+ })(${serialized})`,
1091
+ false
1092
+ );
1093
+ }
1094
+ async reload() {
1095
+ await this.client.reload("interactive");
1096
+ }
1097
+ };
1098
+ function createBidiDomChannel(options) {
1099
+ return new BidiDomChannel(options);
1100
+ }
926
1101
  export {
927
1102
  AndroidWebViewCdpChannel,
928
1103
  AppleWebInspectorClient,
1104
+ BidiDomChannel,
929
1105
  CdpDomChannel,
930
1106
  DEFAULT_MAX_WORKERS_PER_PROCESS,
931
1107
  DEFAULT_WARM_DAEMON_IDLE_TTL_MS,
1108
+ NetworkEventBuffer,
932
1109
  NetworkReplayCache,
933
1110
  PersonaAuthCache,
934
1111
  ReplayCacheStore,
@@ -940,12 +1117,16 @@ export {
940
1117
  TARGET_CHANNEL_MATRIX,
941
1118
  UPLOAD_ATTACH_TIMEOUT_MS,
942
1119
  VirtualCredentialStore,
1120
+ WebDriverBidiClient,
943
1121
  WebKitInspectorChannel,
944
1122
  allocateFreePort,
1123
+ applyExtensionChromeArgs,
945
1124
  applyNamedSetup,
946
1125
  applyTestFilters,
1126
+ assertDataSnapshot,
947
1127
  assertPortAvailable,
948
1128
  attachNetworkReplayCache,
1129
+ buildComponentTreeScript,
949
1130
  buildDomActionabilityDiagScript,
950
1131
  buildDomFillScript,
951
1132
  buildDomWaitForHiddenScript,
@@ -955,10 +1136,16 @@ export {
955
1136
  buildFlowFileFromLines,
956
1137
  buildInjectedCallScript,
957
1138
  buildNetworkCacheKey,
1139
+ buildPerformanceProfileScript,
958
1140
  buildPlaybackTraceFromSteps,
959
1141
  buildReplayCacheKey,
1142
+ buildRichFlowTrace,
960
1143
  byCss,
961
1144
  byRole,
1145
+ captureAndroidLogcat,
1146
+ captureIosSimulatorCrashLogs,
1147
+ checkServerReady,
1148
+ clearReplayCache,
962
1149
  cloneIOSSimulator,
963
1150
  collectGitChanges,
964
1151
  comparePngNative,
@@ -967,12 +1154,15 @@ export {
967
1154
  createAndroidWebViewCdpChannel,
968
1155
  createApiClient,
969
1156
  createApiFixture,
1157
+ createBidiDomChannel,
970
1158
  createCdpDomChannel,
971
1159
  createCompositeDomChannel,
1160
+ createFlowAgent,
972
1161
  createFlowWithFixtures,
973
1162
  createGitHubPrReporter,
974
1163
  createLogprobDecisionJudge,
975
1164
  createOllamaDecisionJudge,
1165
+ createOpenAICompatibleAgentProvider,
976
1166
  createRemoteFlowClaimer,
977
1167
  createSpanaBridgeChannel,
978
1168
  createWebKitInspectorChannel,
@@ -983,6 +1173,7 @@ export {
983
1173
  definePersona,
984
1174
  defineSetup,
985
1175
  deleteIOSSimulator,
1176
+ deserializeBidiRemoteValue,
986
1177
  deterministicImpactFilter,
987
1178
  domRectToScreenBounds,
988
1179
  encodeWebInspectorPacket,
@@ -990,25 +1181,33 @@ export {
990
1181
  exportFramesToMp4,
991
1182
  extractCodeFrame,
992
1183
  extractDestructuredParamNames,
1184
+ filterFlowsForProject,
993
1185
  filterSelector,
994
1186
  findSimulatorWebInspectorSocket,
995
1187
  findWebViewFrame,
996
1188
  first,
997
1189
  flow,
1190
+ formatActionsAsFlowCode,
1191
+ formatCacheInspectTable,
998
1192
  formatCodeFrame,
999
1193
  formatFilterSummary,
1000
1194
  formatGitHubPrMarkdown,
1001
1195
  formatSelectorCode,
1002
1196
  formatTargetMatrixTable,
1003
1197
  getHealthyWarmDaemon,
1198
+ getLoadedExtensions,
1004
1199
  getNativeAcceleratorPath,
1005
1200
  inFrame,
1201
+ inspectReplayCache,
1006
1202
  invalidateWebViewFrameCache,
1007
1203
  isComposableDomSelector,
1204
+ isHttpUrlReady,
1008
1205
  isNativeAcceleratorActive,
1009
1206
  isOffscreenInViewport,
1010
1207
  isPortAvailable,
1208
+ isSecretValue,
1011
1209
  isSystemUISelector,
1210
+ isTcpPortOpen,
1012
1211
  isTestIDSelector,
1013
1212
  last,
1014
1213
  launchDirectCdpBrowser,
@@ -1017,6 +1216,7 @@ export {
1017
1216
  makeElectrobunDriver,
1018
1217
  makeElectronDriver,
1019
1218
  makeLightweightCdpDriver,
1219
+ matchDataSnapshot,
1020
1220
  nth,
1021
1221
  or,
1022
1222
  orderFlowsLongestFirst,
@@ -1027,25 +1227,38 @@ export {
1027
1227
  planProcessPool,
1028
1228
  probabilityFromTopLogprobs,
1029
1229
  reapIdleWarmDaemons,
1230
+ renderTraceViewerHtml,
1030
1231
  replayRecordedAction,
1232
+ resolveBrowserExtensions,
1031
1233
  resolveElectrobunEngine,
1032
1234
  resolveElectrobunLaunchPlan,
1033
1235
  resolveElementAcrossChannels,
1236
+ resolveProjectExecutionPlan,
1034
1237
  resolveTargetDescriptor,
1035
1238
  resolveWebEngine,
1239
+ runExploreSession,
1036
1240
  runMultiProcessPool,
1241
+ runOAuthPopupFlow,
1242
+ secret,
1037
1243
  speculativelyPrelaunchWebBrowser,
1038
1244
  startAndroidVideoRecorder,
1039
1245
  startCdpScreencastRecorder,
1040
1246
  startIosSimulatorVideoRecorder,
1041
1247
  startSharedFlowQueueServer,
1248
+ startWebServer,
1249
+ startWebServers,
1250
+ step,
1042
1251
  stopAllWarmDaemons,
1043
1252
  stopWarmDaemon,
1253
+ suite,
1044
1254
  sweepOrphanedSpanaBrowsers,
1045
1255
  systemUI,
1046
1256
  tokenizeXmlNative,
1257
+ unique,
1047
1258
  updateWarmDaemonSession,
1259
+ withActiveStepRecorder,
1048
1260
  within,
1261
+ writeRichTraceBundle,
1049
1262
  writeWorkerProcessReport
1050
1263
  };
1051
1264
  //# sourceMappingURL=index.js.map