@sgedda/mockifyer-fetch 1.8.87 → 1.8.96

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.
@@ -19,8 +19,12 @@
19
19
  * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
20
20
  * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
21
21
  * 17. POST /mockifyer-network-events/clear — clear ring buffer
22
- * 18. Metro terminal key `t` — start/stop Atlas capture (stop generates HTML; stream auto-starts; `atlasKey: false` to disable). `a` is reserved for Android.
23
- * 19. Metro terminal key `m` — open Mockifyer dashboard in the browser (`dashboardKey: false` to disable)
22
+ * 18. GET /mockifyer-atlas-live — live hop stream web page (SSE + expand/collapse)
23
+ * 19. GET /mockifyer-atlas-trace?id= — re-call a hop with X-Mockifyer-Include-Trace (`&format=html` opens a result tab)
24
+ * 20. GET /mockifyer-atlas-capture — Atlas `t` capture session (`active` plus `activateMockifyer` for the app)
25
+ * 21. Metro terminal key `t` — start/stop Atlas capture (start opens live stream and signals enableMockifyer; stop ends capture; Render docs on the live page writes HTML; capture does not start until `t`; `atlasKey: false` to disable). `a` is reserved for Android.
26
+ * 22. Optional Metro `dashboardKey` — open the dashboard in the browser (off unless set)
27
+ * 23. On hop ingest / Atlas render — pull nested hops from dashboard `/api/network-events/trace` (remote BFF → dashboard → Atlas)
24
28
  *
25
29
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
26
30
  * Legacy polling-based sync is still available for backward compatibility.
@@ -60,14 +64,29 @@ import {
60
64
  type NetworkEvent,
61
65
  getMetroNetworkEventBuffer,
62
66
  resolveNetworkEventBodyRelPaths,
67
+ networkBodySpillRelPath,
63
68
  analyzeMetroNetworkEvents,
64
69
  createEmptyAtlasDocMap,
65
70
  buildAtlasHarJson,
71
+ buildAtlasLiveStreamHtml,
72
+ buildAtlasTraceReplayHtml,
73
+ buildAtlasTracePendingHtml,
74
+ ATLAS_LIVE_STREAM_PATH,
75
+ ATLAS_TRACE_REPLAY_PATH,
76
+ ATLAS_TRACE_REPLAY_TIMEOUT_MS,
77
+ ATLAS_CAPTURE_SESSION_PATH,
78
+ replayNetworkEventWithIncludeTrace,
79
+ setMetroAtlasCaptureSessionActive,
80
+ isMetroAtlasCaptureSessionActive,
81
+ normalizeDashboardBaseUrl,
82
+ pullDashboardDescendantsForParents,
66
83
  } from "@sgedda/mockifyer-core";
67
84
  import {
68
85
  attachMetroAtlasKeyHandler,
86
+ getMetroAtlasSessionPhase,
69
87
  notifyMetroAtlasStreamClientConnected,
70
88
  notifyMetroAtlasStreamClientDisconnected,
89
+ resolveMetroDashboardUrl,
71
90
  type AtlasKeyOption,
72
91
  } from "./metro-atlas-key-handlers";
73
92
 
@@ -78,13 +97,15 @@ export interface MetroSyncMiddlewareOptions {
78
97
  mockDataPath?: string;
79
98
  /**
80
99
  * Metro terminal key that starts/stops Atlas capture (default `"t"`).
81
- * Start clears the hop buffer; stop generates HTML (same as `POST /mockifyer-network-events/render`).
100
+ * Start clears the hop buffer and signals the app to enable Mockifyer; stop ends
101
+ * capture. Write HTML via live page “Render docs” (`POST /mockifyer-network-events/render`)
102
+ * or the CLI.
82
103
  * Pass `false` to disable. `a` is reserved by Metro for Android.
83
104
  */
84
105
  atlasKey?: AtlasKeyOption;
85
106
  /**
86
- * Metro terminal key that opens the dashboard in the browser (default `"m"`).
87
- * Pass `false` to disable.
107
+ * Metro terminal key that opens the dashboard in the browser.
108
+ * Off unless set (for example `"m"`).
88
109
  */
89
110
  dashboardKey?: AtlasKeyOption;
90
111
  /**
@@ -115,8 +136,193 @@ const DEFAULT_SCENARIO = "default";
115
136
  /** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
116
137
  const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
117
138
 
139
+ /**
140
+ * Debounce so a burst of hops triggers one dashboard read, and remote BFF children
141
+ * (logged slightly after the parent) have landed before we ask.
142
+ */
143
+ const DASHBOARD_ENRICH_DEBOUNCE_MS = 1_500;
144
+
145
+ /** Hard deadline for the enrichment on Atlas stop — `t` must never hang on a slow store. */
146
+ const DASHBOARD_ENRICH_DEADLINE_MS = 4_000;
147
+
118
148
  let autoSyncInterval: NodeJS.Timeout | null = null;
119
149
 
150
+ /** Last dashboard base seen on a hop POST (device proxy URL). */
151
+ let lastHopDashboardBaseUrl: string | undefined;
152
+ let dashboardEnrichTimer: ReturnType<typeof setTimeout> | null = null;
153
+ let dashboardEnrichInFlight: Promise<number> | null = null;
154
+
155
+ function clearDashboardTraceEnrichmentSchedules(): void {
156
+ if (dashboardEnrichTimer) {
157
+ clearTimeout(dashboardEnrichTimer);
158
+ dashboardEnrichTimer = null;
159
+ }
160
+ dashboardEnrichInFlight = null;
161
+ }
162
+
163
+ function resolveAtlasEnrichmentDashboardUrl(
164
+ middlewareDashboardUrl: string | undefined,
165
+ hopHint?: string,
166
+ ): string | undefined {
167
+ const fromHop = normalizeDashboardBaseUrl(hopHint);
168
+ if (fromHop) {
169
+ lastHopDashboardBaseUrl = fromHop;
170
+ return fromHop;
171
+ }
172
+ if (lastHopDashboardBaseUrl) {
173
+ return lastHopDashboardBaseUrl;
174
+ }
175
+ const hasExplicit =
176
+ Boolean(middlewareDashboardUrl?.trim()) ||
177
+ Boolean(
178
+ typeof process !== "undefined" &&
179
+ process.env.MOCKIFYER_DASHBOARD_URL?.trim(),
180
+ );
181
+ if (!hasExplicit) {
182
+ return undefined;
183
+ }
184
+ return normalizeDashboardBaseUrl(
185
+ resolveMetroDashboardUrl(middlewareDashboardUrl),
186
+ );
187
+ }
188
+
189
+ /**
190
+ * Merge remote-service children into the Metro buffer with a single dashboard read.
191
+ * Buffered hop ids are the parents; descendants are linked by `parentRequestId`.
192
+ * Returns how many new hops were appended. Never throws.
193
+ */
194
+ async function enrichMetroBufferFromDashboard(options: {
195
+ dashboardBaseUrl: string;
196
+ mockDataPath: string;
197
+ timeoutMs?: number;
198
+ }): Promise<number> {
199
+ if (!options.dashboardBaseUrl) {
200
+ return 0;
201
+ }
202
+ if (dashboardEnrichInFlight) {
203
+ return dashboardEnrichInFlight;
204
+ }
205
+
206
+ const flight = (async (): Promise<number> => {
207
+ const buffer = getMetroNetworkEventBuffer();
208
+ const existing = buffer.list();
209
+ const parentRequestIds = [
210
+ ...new Set(
211
+ existing
212
+ .map((event) => event.requestId?.trim())
213
+ .filter((id): id is string => Boolean(id)),
214
+ ),
215
+ ];
216
+ if (parentRequestIds.length === 0) {
217
+ return 0;
218
+ }
219
+
220
+ const children = await pullDashboardDescendantsForParents({
221
+ dashboardBaseUrl: options.dashboardBaseUrl,
222
+ parentRequestIds,
223
+ existing,
224
+ timeoutMs: options.timeoutMs,
225
+ });
226
+
227
+ let added = 0;
228
+ for (const child of children) {
229
+ const stored = buffer.append(child);
230
+ appendNetworkEventNdjson(options.mockDataPath, stored);
231
+ added += 1;
232
+ }
233
+ return added;
234
+ })();
235
+
236
+ dashboardEnrichInFlight = flight;
237
+ try {
238
+ return await flight;
239
+ } catch {
240
+ return 0;
241
+ } finally {
242
+ dashboardEnrichInFlight = null;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Render the current Metro hop buffer to Atlas HTML and log the outcome.
248
+ * Returns the same shape as {@link renderNetworkEventsAtlasHtml}. When the
249
+ * buffer is empty, leaves any existing `index.html` alone.
250
+ */
251
+ function renderBufferedAtlasHtml(options: {
252
+ projectRoot: string;
253
+ mockDataPath: string;
254
+ scenario?: string;
255
+ }): {
256
+ success: boolean;
257
+ written: number;
258
+ outputDir: string;
259
+ indexPath: string;
260
+ hopCount: number;
261
+ error?: string;
262
+ } {
263
+ const events = [...getMetroNetworkEventBuffer().list()].reverse();
264
+ const outDir = path.join(options.mockDataPath, "atlas-html");
265
+ const indexPath = path.join(outDir, "index.html");
266
+ const relativeFromRoot = path
267
+ .relative(options.projectRoot, outDir)
268
+ .split(path.sep)
269
+ .join("/");
270
+ if (events.length === 0) {
271
+ console.warn(
272
+ `[Mockifyer] Atlas: 0 hops — keeping the existing ${indexPath}`,
273
+ );
274
+ console.warn(
275
+ "[Mockifyer] Atlas: no hops reached Metro. Check that Mockifyer is enabled in the app " +
276
+ "(runtimeMode 'manual' needs the dev-menu switch), that the app made requests during the " +
277
+ "session, and that hops arrive: curl http://localhost:8081/mockifyer-network-events",
278
+ );
279
+ return {
280
+ success: false,
281
+ written: 0,
282
+ outputDir: relativeFromRoot,
283
+ indexPath,
284
+ hopCount: 0,
285
+ error: "0 hops — existing index.html left unchanged",
286
+ };
287
+ }
288
+ const startedAt = Date.now();
289
+ const result = renderNetworkEventsAtlasHtml(
290
+ options.projectRoot,
291
+ options.mockDataPath,
292
+ events,
293
+ options.scenario,
294
+ );
295
+ if (result.success) {
296
+ const elapsedMs = Date.now() - startedAt;
297
+ console.log(
298
+ `[Mockifyer] Atlas HTML (${result.hopCount} hop(s), ${elapsedMs}ms) → ${result.indexPath}`,
299
+ );
300
+ } else {
301
+ console.error(
302
+ `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
303
+ );
304
+ }
305
+ return result;
306
+ }
307
+
308
+ /** Coalesce hop-ingest bursts into one dashboard read. */
309
+ function scheduleDashboardTraceEnrichment(options: {
310
+ dashboardBaseUrl: string;
311
+ mockDataPath: string;
312
+ }): void {
313
+ if (!options.dashboardBaseUrl) {
314
+ return;
315
+ }
316
+ if (dashboardEnrichTimer) {
317
+ clearTimeout(dashboardEnrichTimer);
318
+ }
319
+ dashboardEnrichTimer = setTimeout(() => {
320
+ dashboardEnrichTimer = null;
321
+ void enrichMetroBufferFromDashboard(options);
322
+ }, DASHBOARD_ENRICH_DEBOUNCE_MS);
323
+ dashboardEnrichTimer.unref?.();
324
+ }
325
+
120
326
  /**
121
327
  * Buffer an incoming request body with `Buffer.concat` (not `body += chunk`).
122
328
  * Large Atlas render payloads hang for minutes with quadratic string concatenation.
@@ -1024,9 +1230,158 @@ function saveAtlasScreenshot(
1024
1230
  }
1025
1231
  }
1026
1232
 
1233
+ /**
1234
+ * Candidate relative body paths for a hop (refs first, then id / requestId variants).
1235
+ * Spills key by requestId when present, but older captures / races can land under event.id.
1236
+ */
1237
+ function candidateBodyRelPaths(
1238
+ event: NetworkEvent,
1239
+ side: "req" | "res",
1240
+ ): string[] {
1241
+ const preferred = resolveNetworkEventBodyRelPaths(event);
1242
+ const out: string[] = [side === "req" ? preferred.req : preferred.res];
1243
+ const push = (rel: string | undefined) => {
1244
+ const trimmed = rel?.trim();
1245
+ if (!trimmed || out.includes(trimmed)) return;
1246
+ out.push(trimmed);
1247
+ };
1248
+ if (side === "req") push(event.requestBodyRef);
1249
+ else push(event.responseBodyRef);
1250
+ push(networkBodySpillRelPath(event.id, event.requestId, side));
1251
+ push(networkBodySpillRelPath(event.id, null, side));
1252
+ if (event.requestId?.trim()) {
1253
+ push(networkBodySpillRelPath(event.requestId, event.requestId, side));
1254
+ }
1255
+ return out;
1256
+ }
1257
+
1027
1258
  const BODY_SPILL_REL_PATTERN =
1028
1259
  /^bodies\/[A-Za-z0-9._-]+-(req|res)\.(json|txt)$/;
1029
1260
 
1261
+ /**
1262
+ * Locate a full body on disk or in the Metro spill buffer.
1263
+ * Writes a buffer hit for *this* hop only — never flushes the whole spill map
1264
+ * (that blocked Metro for seconds on every req/res/trace click).
1265
+ */
1266
+ function findExistingBodyFile(options: {
1267
+ projectRoot: string;
1268
+ mockDataPath: string;
1269
+ event: NetworkEvent;
1270
+ side: "req" | "res";
1271
+ }): { abs: string; rel: string; text?: string } | null {
1272
+ const outDir = path.join(options.mockDataPath, "atlas-html");
1273
+ const outDirResolved = path.resolve(outDir);
1274
+ const snapshot = getNetworkBodySpillSnapshot();
1275
+
1276
+ for (const rel of candidateBodyRelPaths(options.event, options.side)) {
1277
+ // Validate path: reject absolute paths, parent traversal, and paths outside atlas-html
1278
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
1279
+ continue;
1280
+ }
1281
+ const abs = path.resolve(outDir, rel);
1282
+ const outDirPrefix = outDirResolved.endsWith(path.sep)
1283
+ ? outDirResolved
1284
+ : outDirResolved + path.sep;
1285
+ if (abs !== outDirResolved && !abs.startsWith(outDirPrefix)) {
1286
+ continue;
1287
+ }
1288
+
1289
+ const fromBuffer = snapshot[rel];
1290
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1291
+ const saved = saveAtlasBodySpill(
1292
+ options.projectRoot,
1293
+ options.mockDataPath,
1294
+ rel,
1295
+ fromBuffer,
1296
+ );
1297
+ if (saved.success && saved.filePath) {
1298
+ return { abs: saved.filePath, rel, text: fromBuffer };
1299
+ }
1300
+ return {
1301
+ abs,
1302
+ rel,
1303
+ text: fromBuffer,
1304
+ };
1305
+ }
1306
+ if (fs.existsSync(abs)) {
1307
+ return { abs, rel };
1308
+ }
1309
+ }
1310
+ return null;
1311
+ }
1312
+
1313
+ /**
1314
+ * Read spilled request body text for a live include-trace re-call (optional).
1315
+ * Prefer in-memory spill; fall back to disk. Does not flush other hops.
1316
+ */
1317
+ function readSpilledRequestBodyText(
1318
+ projectRoot: string,
1319
+ mockDataPath: string,
1320
+ event: NetworkEvent,
1321
+ ): string | undefined {
1322
+ const snapshot = getNetworkBodySpillSnapshot();
1323
+ for (const rel of candidateBodyRelPaths(event, "req")) {
1324
+ const fromBuffer = snapshot[rel];
1325
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1326
+ return fromBuffer;
1327
+ }
1328
+ }
1329
+ const found = findExistingBodyFile({
1330
+ projectRoot,
1331
+ mockDataPath,
1332
+ event,
1333
+ side: "req",
1334
+ });
1335
+ if (!found) return undefined;
1336
+ if (typeof found.text === "string") return found.text;
1337
+ try {
1338
+ return fs.readFileSync(found.abs, "utf8");
1339
+ } catch {
1340
+ return undefined;
1341
+ }
1342
+ }
1343
+
1344
+ /**
1345
+ * Nested hops already in the Metro buffer for this request (shown on the
1346
+ * include-trace HTML result page before the live re-call payload).
1347
+ */
1348
+ function formatCapturedTraceLines(
1349
+ events: readonly NetworkEvent[],
1350
+ root: NetworkEvent,
1351
+ ): string[] {
1352
+ const byParent = new Map<string, NetworkEvent[]>();
1353
+ for (const ev of events) {
1354
+ const parent =
1355
+ typeof ev.parentRequestId === "string" ? ev.parentRequestId.trim() : "";
1356
+ if (!parent) continue;
1357
+ const list = byParent.get(parent) ?? [];
1358
+ list.push(ev);
1359
+ byParent.set(parent, list);
1360
+ }
1361
+
1362
+ const lines: string[] = [];
1363
+ const guard = new Set<string>();
1364
+ const walk = (ev: NetworkEvent, depth: number): void => {
1365
+ const id =
1366
+ (typeof ev.requestId === "string" && ev.requestId.trim()) ||
1367
+ (typeof ev.id === "string" ? ev.id.trim() : "");
1368
+ if (id && guard.has(id)) return;
1369
+ if (id) guard.add(id);
1370
+ const indent = depth > 0 ? `${" ".repeat(depth)}` : "";
1371
+ const status = ev.status != null ? String(ev.status) : "—";
1372
+ const ms = ev.durationMs != null ? `${ev.durationMs}ms` : "";
1373
+ lines.push(
1374
+ `${indent}${(ev.method || "?").toUpperCase()} ${status} ${ms} ${ev.url || ev.path || ""}`.trimEnd(),
1375
+ );
1376
+ if (!id) return;
1377
+ for (const kid of byParent.get(id) || []) {
1378
+ walk(kid, depth + 1);
1379
+ }
1380
+ };
1381
+ walk(root, 0);
1382
+ return lines;
1383
+ }
1384
+
1030
1385
  /**
1031
1386
  * Persist a full hop body spill from the device (RN) under atlas-html/bodies/.
1032
1387
  */
@@ -1281,26 +1636,22 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1281
1636
  atlasKey: options?.atlasKey,
1282
1637
  dashboardKey: options?.dashboardKey,
1283
1638
  dashboardUrl: options?.dashboardUrl,
1284
- onSessionStart: () => {
1285
- getMetroNetworkEventBuffer().clear();
1639
+ onSessionStart: (reason) => {
1640
+ clearDashboardTraceEnrichmentSchedules();
1641
+ // Explicit `t` starts a clean session. Live-stream connect must NOT wipe hops
1642
+ // already in the buffer (that made the live page look empty and empty HTML on stop).
1643
+ if (reason === "key") {
1644
+ lastHopDashboardBaseUrl = undefined;
1645
+ getMetroNetworkEventBuffer().clear();
1646
+ }
1647
+ setMetroAtlasCaptureSessionActive(true);
1286
1648
  },
1287
- onSessionStop: () => {
1288
- const buffer = getMetroNetworkEventBuffer();
1289
- const events = [...buffer.list()].reverse();
1290
- const result = renderNetworkEventsAtlasHtml(
1291
- projectRoot,
1292
- mockDataPath,
1293
- events,
1649
+ onSessionStop: async () => {
1650
+ setMetroAtlasCaptureSessionActive(false);
1651
+ const hopCount = getMetroNetworkEventBuffer().list().length;
1652
+ console.log(
1653
+ `[Mockifyer] Atlas: capture ended with ${hopCount} hop(s) in buffer — use live page “Render docs” (or POST /mockifyer-network-events/render) to write HTML.`,
1294
1654
  );
1295
- if (result.success) {
1296
- console.log(
1297
- `[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`,
1298
- );
1299
- } else {
1300
- console.error(
1301
- `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
1302
- );
1303
- }
1304
1655
  },
1305
1656
  });
1306
1657
 
@@ -1315,6 +1666,185 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1315
1666
  return;
1316
1667
  }
1317
1668
 
1669
+ // Atlas `t` capture session — device polls this for include-trace and enableMockifyer().
1670
+ if (
1671
+ (url === ATLAS_CAPTURE_SESSION_PATH ||
1672
+ url === `${ATLAS_CAPTURE_SESSION_PATH}/`) &&
1673
+ req.method === "GET"
1674
+ ) {
1675
+ const phase = getMetroAtlasSessionPhase();
1676
+ const capturing = phase === "capturing";
1677
+ res.setHeader("Content-Type", "application/json");
1678
+ res.setHeader("Cache-Control", "no-store");
1679
+ res.end(
1680
+ JSON.stringify({
1681
+ success: true,
1682
+ active: isMetroAtlasCaptureSessionActive(),
1683
+ phase,
1684
+ capturing,
1685
+ /** App should call enableMockifyer() while capturing (runtimeMode: manual). */
1686
+ activateMockifyer: capturing,
1687
+ }),
1688
+ );
1689
+ return;
1690
+ }
1691
+
1692
+ // Live Atlas hop stream page (browser EventSource → same SSE as mockifyer-atlas CLI)
1693
+ if (
1694
+ (url === ATLAS_LIVE_STREAM_PATH || url === `${ATLAS_LIVE_STREAM_PATH}/`) &&
1695
+ req.method === "GET"
1696
+ ) {
1697
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1698
+ res.setHeader("Cache-Control", "no-store");
1699
+ res.end(
1700
+ buildAtlasLiveStreamHtml({
1701
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1702
+ }),
1703
+ );
1704
+ return;
1705
+ }
1706
+
1707
+ // Re-call a buffered hop with X-Mockifyer-Include-Trace (live page "trace" link).
1708
+ // Live HTTP only — nested hops come back on the response; no disk/Redis store required.
1709
+ // `format=html` returns a result page (new browser tab); default remains JSON.
1710
+ if (req.method === "GET" && url === ATLAS_TRACE_REPLAY_PATH) {
1711
+ const fullUrl = String(req.url || "");
1712
+ const q = fullUrl.includes("?")
1713
+ ? fullUrl.slice(fullUrl.indexOf("?") + 1)
1714
+ : "";
1715
+ const params = new URLSearchParams(q);
1716
+ const hopId = (params.get("id") || "").trim();
1717
+ const includeBodies = params.get("bodies") !== "0";
1718
+ const wantHtml =
1719
+ params.get("format") === "html" ||
1720
+ String(req.headers?.accept || "").includes("text/html");
1721
+ if (!hopId) {
1722
+ res.statusCode = 400;
1723
+ if (wantHtml) {
1724
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1725
+ res.end(
1726
+ buildAtlasTraceReplayHtml(
1727
+ {
1728
+ success: false,
1729
+ hopId: "",
1730
+ method: "",
1731
+ url: "",
1732
+ error: "id query param required",
1733
+ requestHeaders: {},
1734
+ },
1735
+ {
1736
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1737
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1738
+ },
1739
+ ),
1740
+ );
1741
+ } else {
1742
+ res.setHeader("Content-Type", "application/json");
1743
+ res.end(
1744
+ JSON.stringify({ success: false, error: "id query param required" }),
1745
+ );
1746
+ }
1747
+ return;
1748
+ }
1749
+ const buffer = getMetroNetworkEventBuffer();
1750
+ const events = buffer.list();
1751
+ const event =
1752
+ events.find((e) => e && (e.id === hopId || e.requestId === hopId)) ??
1753
+ undefined;
1754
+
1755
+ // format=html without wait=1: return a shell immediately so the tab is not
1756
+ // blank while the include-trace re-call runs (can be many seconds).
1757
+ if (wantHtml && params.get("wait") !== "1") {
1758
+ const waitParams = new URLSearchParams(params);
1759
+ waitParams.set("format", "html");
1760
+ waitParams.set("wait", "1");
1761
+ res.statusCode = 200;
1762
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1763
+ res.setHeader("Cache-Control", "no-store");
1764
+ res.end(
1765
+ buildAtlasTracePendingHtml({
1766
+ hopId,
1767
+ method: event?.method,
1768
+ url: event?.url,
1769
+ resultUrl: `${ATLAS_TRACE_REPLAY_PATH}?${waitParams.toString()}`,
1770
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1771
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1772
+ timeoutMs: ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1773
+ }),
1774
+ );
1775
+ return;
1776
+ }
1777
+
1778
+ const spilledRequestBody = event
1779
+ ? readSpilledRequestBodyText(projectRoot, mockDataPath, event)
1780
+ : undefined;
1781
+ const capturedLines = event
1782
+ ? formatCapturedTraceLines(events, event)
1783
+ : undefined;
1784
+ void replayNetworkEventWithIncludeTrace(events, hopId, {
1785
+ includeBodies,
1786
+ requestBody: spilledRequestBody,
1787
+ timeoutMs: ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1788
+ })
1789
+ .then((result) => {
1790
+ if (res.writableEnded) return;
1791
+ res.statusCode = result.success
1792
+ ? 200
1793
+ : result.error === "hop not found"
1794
+ ? 404
1795
+ : 502;
1796
+ res.setHeader("Cache-Control", "no-store");
1797
+ if (wantHtml) {
1798
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1799
+ res.end(
1800
+ buildAtlasTraceReplayHtml(result, {
1801
+ capturedLines,
1802
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1803
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1804
+ requestBody:
1805
+ spilledRequestBody ||
1806
+ (typeof event?.requestBodyPreview === "string"
1807
+ ? event.requestBodyPreview
1808
+ : undefined),
1809
+ }),
1810
+ );
1811
+ } else {
1812
+ res.setHeader("Content-Type", "application/json");
1813
+ res.end(JSON.stringify(result));
1814
+ }
1815
+ })
1816
+ .catch((error: unknown) => {
1817
+ if (res.writableEnded) return;
1818
+ const message =
1819
+ error instanceof Error ? error.message : String(error);
1820
+ res.statusCode = 500;
1821
+ res.setHeader("Cache-Control", "no-store");
1822
+ if (wantHtml) {
1823
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1824
+ res.end(
1825
+ buildAtlasTraceReplayHtml(
1826
+ {
1827
+ success: false,
1828
+ hopId,
1829
+ method: event?.method || "",
1830
+ url: event?.url || "",
1831
+ error: message,
1832
+ requestHeaders: {},
1833
+ },
1834
+ {
1835
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1836
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1837
+ },
1838
+ ),
1839
+ );
1840
+ } else {
1841
+ res.setHeader("Content-Type", "application/json");
1842
+ res.end(JSON.stringify({ success: false, hopId, error: message }));
1843
+ }
1844
+ });
1845
+ return;
1846
+ }
1847
+
1318
1848
  // Live hop ring buffer for `mockifyer-atlas` interactive CLI
1319
1849
  if (url === "/mockifyer-network-events" && req.method === "POST") {
1320
1850
  collectRequestBodyUtf8(req, (err, body) => {
@@ -1328,6 +1858,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1328
1858
  const parsed = JSON.parse(body) as {
1329
1859
  event?: NetworkEvent;
1330
1860
  events?: NetworkEvent[];
1861
+ dashboardBaseUrl?: string;
1331
1862
  };
1332
1863
  const incoming: NetworkEvent[] = [];
1333
1864
  if (parsed.event && typeof parsed.event === "object") {
@@ -1355,6 +1886,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1355
1886
  appendNetworkEventNdjson(mockDataPath, stored);
1356
1887
  return stored;
1357
1888
  });
1889
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
1890
+ options?.dashboardUrl,
1891
+ parsed.dashboardBaseUrl,
1892
+ );
1893
+ if (dashboardBaseUrl) {
1894
+ scheduleDashboardTraceEnrichment({ dashboardBaseUrl, mockDataPath });
1895
+ }
1358
1896
  res.statusCode = 201;
1359
1897
  res.setHeader("Content-Type", "application/json");
1360
1898
  res.end(
@@ -1362,6 +1900,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1362
1900
  success: true,
1363
1901
  count: saved.length,
1364
1902
  size: buffer.size,
1903
+ atlasCaptureActive: isMetroAtlasCaptureSessionActive(),
1365
1904
  }),
1366
1905
  );
1367
1906
  } catch (error) {
@@ -1402,8 +1941,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1402
1941
  qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "",
1403
1942
  );
1404
1943
  const backlog = params.get("backlog") !== "0";
1405
- // First SSE client (e.g. mockifyer-atlas) auto-starts Metro Atlas capture.
1406
- // Must run before reading the buffer — start clears hops for a clean session.
1944
+ // Track the SSE client. Capture starts only when Metro `t` is pressed.
1407
1945
  notifyMetroAtlasStreamClientConnected();
1408
1946
  const buffer = getMetroNetworkEventBuffer();
1409
1947
  res.writeHead(200, {
@@ -1513,22 +2051,37 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1513
2051
  // empty / ignore
1514
2052
  }
1515
2053
  }
1516
- const buffer = getMetroNetworkEventBuffer();
1517
- const events = [...buffer.list()].reverse();
1518
- const result = renderNetworkEventsAtlasHtml(
1519
- projectRoot,
1520
- mockDataPath,
1521
- events,
1522
- scenario,
2054
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
2055
+ options?.dashboardUrl,
1523
2056
  );
1524
- res.statusCode = result.success ? 201 : 500;
1525
- res.setHeader("Content-Type", "application/json");
1526
- res.end(JSON.stringify(result));
2057
+ const finishRender = () => {
2058
+ const result = renderBufferedAtlasHtml({
2059
+ projectRoot,
2060
+ mockDataPath,
2061
+ scenario,
2062
+ });
2063
+ res.statusCode = result.success ? 201 : 500;
2064
+ res.setHeader("Content-Type", "application/json");
2065
+ res.end(JSON.stringify(result));
2066
+ };
2067
+ if (!dashboardBaseUrl) {
2068
+ finishRender();
2069
+ return;
2070
+ }
2071
+ void enrichMetroBufferFromDashboard({
2072
+ dashboardBaseUrl,
2073
+ mockDataPath,
2074
+ timeoutMs: DASHBOARD_ENRICH_DEADLINE_MS,
2075
+ }).then(() => {
2076
+ finishRender();
2077
+ });
1527
2078
  });
1528
2079
  return;
1529
2080
  }
1530
2081
 
1531
2082
  if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
2083
+ clearDashboardTraceEnrichmentSchedules();
2084
+ lastHopDashboardBaseUrl = undefined;
1532
2085
  const buffer = getMetroNetworkEventBuffer();
1533
2086
  buffer.clear();
1534
2087
  res.setHeader("Content-Type", "application/json");
@@ -1606,6 +2159,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1606
2159
 
1607
2160
  // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1608
2161
  // GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
2162
+ //
2163
+ // req/res must stay fast: look up the hop + flush/serve the body spill only.
2164
+ // Never rebuild the full Atlas HTML site here — that used to hang for seconds
2165
+ // when the buffer was large (writeAtlasDocHtml for every hop).
1609
2166
  if (
1610
2167
  req.method === "GET" &&
1611
2168
  (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))
@@ -1619,22 +2176,27 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1619
2176
  sideParam === "req" || sideParam === "res" ? sideParam : "html";
1620
2177
 
1621
2178
  const buffer = getMetroNetworkEventBuffer();
1622
- // Buffer is newest-first; render expects chronological / display order.
1623
- const events = [...buffer.list()].reverse();
1624
- const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1625
- if (!rendered.success) {
1626
- res.statusCode = 500;
1627
- res.setHeader("Content-Type", "application/json");
1628
- res.end(
1629
- JSON.stringify({
1630
- success: false,
1631
- error: rendered.error || "atlas render failed",
1632
- }),
1633
- );
1634
- return;
1635
- }
2179
+ const listed = buffer.list();
1636
2180
 
1637
2181
  if (side === "html") {
2182
+ // Full site rebuild only when opening the Atlas index (terminal / html link).
2183
+ const events = [...listed].reverse();
2184
+ const rendered = renderNetworkEventsAtlasHtml(
2185
+ projectRoot,
2186
+ mockDataPath,
2187
+ events,
2188
+ );
2189
+ if (!rendered.success) {
2190
+ res.statusCode = 500;
2191
+ res.setHeader("Content-Type", "application/json");
2192
+ res.end(
2193
+ JSON.stringify({
2194
+ success: false,
2195
+ error: rendered.error || "atlas render failed",
2196
+ }),
2197
+ );
2198
+ return;
2199
+ }
1638
2200
  res.statusCode = 302;
1639
2201
  res.setHeader("Location", "/atlas-html/index.html");
1640
2202
  res.end();
@@ -1643,8 +2205,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1643
2205
 
1644
2206
  const event =
1645
2207
  (hopId
1646
- ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1647
- : undefined) || events[0];
2208
+ ? listed.find((e) => e && (e.id === hopId || e.requestId === hopId))
2209
+ : undefined) || listed[0];
1648
2210
  if (!event) {
1649
2211
  res.statusCode = 404;
1650
2212
  res.setHeader("Content-Type", "application/json");
@@ -1652,53 +2214,94 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1652
2214
  return;
1653
2215
  }
1654
2216
 
1655
- const rels = resolveNetworkEventBodyRelPaths(event);
1656
- const rel = side === "req" ? rels.req : rels.res;
1657
- const abs = path.join(mockDataPath, "atlas-html", rel);
1658
- const outDir = path.join(mockDataPath, "atlas-html");
1659
- // Prefer real spill buffer / disk — never materialize the truncated Metro
1660
- // hop preview (often ~512 bytes) as the "full body" JSON page.
1661
- flushNetworkBodySpillsToDir(outDir);
1662
- const fromBuffer = getNetworkBodySpillSnapshot()[rel];
1663
- if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1664
- const saved = saveAtlasBodySpill(
1665
- projectRoot,
1666
- mockDataPath,
1667
- rel,
1668
- fromBuffer,
1669
- );
1670
- if (!saved.success) {
1671
- res.statusCode = 500;
1672
- res.setHeader("Content-Type", "application/json");
1673
- res.end(
1674
- JSON.stringify({
1675
- success: false,
1676
- error: saved.error || "Failed to write full body spill",
1677
- }),
2217
+ const found = findExistingBodyFile({
2218
+ projectRoot,
2219
+ mockDataPath,
2220
+ event,
2221
+ side,
2222
+ });
2223
+ if (found) {
2224
+ // Serve the body directly — a 302 to /atlas-html/... is a second hop and
2225
+ // used to queue behind other sync Atlas work in Metro.
2226
+ let text = found.text;
2227
+ if (typeof text !== "string") {
2228
+ try {
2229
+ text = fs.readFileSync(found.abs, "utf8");
2230
+ } catch {
2231
+ text = undefined;
2232
+ }
2233
+ }
2234
+ if (typeof text === "string") {
2235
+ const ext = path.extname(found.rel).toLowerCase();
2236
+ res.statusCode = 200;
2237
+ res.setHeader(
2238
+ "Content-Type",
2239
+ ext === ".json"
2240
+ ? "application/json; charset=utf-8"
2241
+ : "text/plain; charset=utf-8",
2242
+ );
2243
+ res.setHeader("Cache-Control", "no-store");
2244
+ res.setHeader("X-Mockifyer-Body-Source", "spill");
2245
+ res.setHeader(
2246
+ "X-Mockifyer-Body-Rel",
2247
+ found.rel.split(path.sep).join("/"),
1678
2248
  );
2249
+ res.end(text);
1679
2250
  return;
1680
2251
  }
1681
- } else if (!fs.existsSync(abs)) {
1682
- res.statusCode = 404;
1683
- res.setHeader("Content-Type", "application/json");
2252
+ res.statusCode = 302;
2253
+ res.setHeader(
2254
+ "Location",
2255
+ `/atlas-html/${found.rel.split(path.sep).join("/")}`,
2256
+ );
2257
+ res.end();
2258
+ return;
2259
+ }
2260
+
2261
+ // Spill not on disk yet (race) or never uploaded — still return the captured
2262
+ // preview so open/trace UX is usable. Do not write preview as the spill file.
2263
+ const preview =
2264
+ side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
2265
+ if (typeof preview === "string" && preview.length > 0) {
2266
+ const preferred = resolveNetworkEventBodyRelPaths(event);
2267
+ res.statusCode = 200;
2268
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2269
+ res.setHeader("Cache-Control", "no-store");
2270
+ res.setHeader("X-Mockifyer-Body-Source", "preview");
2271
+ res.setHeader(
2272
+ "X-Mockifyer-Body-Note",
2273
+ "Full spill file missing; showing hop preview",
2274
+ );
1684
2275
  res.end(
1685
- JSON.stringify({
1686
- success: false,
1687
- error:
1688
- "Full body not available on disk yet. Enable captureBodies / body spill, re-hit the endpoint, then open again. Refusing to write the truncated hop preview as the full body file.",
1689
- hopId: event.id,
1690
- side,
1691
- relativePath: rel,
1692
- }),
2276
+ JSON.stringify(
2277
+ {
2278
+ success: true,
2279
+ source: "preview",
2280
+ hopId: event.id,
2281
+ side,
2282
+ relativePath: side === "req" ? preferred.req : preferred.res,
2283
+ preview,
2284
+ },
2285
+ null,
2286
+ 2,
2287
+ ),
1693
2288
  );
1694
2289
  return;
1695
2290
  }
1696
- res.statusCode = 302;
1697
- res.setHeader(
1698
- "Location",
1699
- `/atlas-html/${rel.split(path.sep).join("/")}`,
2291
+
2292
+ const preferred = resolveNetworkEventBodyRelPaths(event);
2293
+ res.statusCode = 404;
2294
+ res.setHeader("Content-Type", "application/json");
2295
+ res.end(
2296
+ JSON.stringify({
2297
+ success: false,
2298
+ error:
2299
+ "No full body spill on disk and no hop preview. Re-hit the endpoint during Atlas capture, then open again.",
2300
+ hopId: event.id,
2301
+ side,
2302
+ relativePath: side === "req" ? preferred.req : preferred.res,
2303
+ }),
1700
2304
  );
1701
- res.end();
1702
2305
  return;
1703
2306
  }
1704
2307