@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.
@@ -20,8 +20,12 @@
20
20
  * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
21
21
  * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
22
22
  * 17. POST /mockifyer-network-events/clear — clear ring buffer
23
- * 18. Metro terminal key `t` — start/stop Atlas capture (stop generates HTML; stream auto-starts; `atlasKey: false` to disable). `a` is reserved for Android.
24
- * 19. Metro terminal key `m` — open Mockifyer dashboard in the browser (`dashboardKey: false` to disable)
23
+ * 18. GET /mockifyer-atlas-live — live hop stream web page (SSE + expand/collapse)
24
+ * 19. GET /mockifyer-atlas-trace?id= — re-call a hop with X-Mockifyer-Include-Trace (`&format=html` opens a result tab)
25
+ * 20. GET /mockifyer-atlas-capture — Atlas `t` capture session (`active` plus `activateMockifyer` for the app)
26
+ * 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.
27
+ * 22. Optional Metro `dashboardKey` — open the dashboard in the browser (off unless set)
28
+ * 23. On hop ingest / Atlas render — pull nested hops from dashboard `/api/network-events/trace` (remote BFF → dashboard → Atlas)
25
29
  *
26
30
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
27
31
  * Legacy polling-based sync is still available for backward compatibility.
@@ -74,7 +78,142 @@ const metro_atlas_key_handlers_1 = require("./metro-atlas-key-handlers");
74
78
  const DEFAULT_SCENARIO = "default";
75
79
  /** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
76
80
  const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
81
+ /**
82
+ * Debounce so a burst of hops triggers one dashboard read, and remote BFF children
83
+ * (logged slightly after the parent) have landed before we ask.
84
+ */
85
+ const DASHBOARD_ENRICH_DEBOUNCE_MS = 1500;
86
+ /** Hard deadline for the enrichment on Atlas stop — `t` must never hang on a slow store. */
87
+ const DASHBOARD_ENRICH_DEADLINE_MS = 4000;
77
88
  let autoSyncInterval = null;
89
+ /** Last dashboard base seen on a hop POST (device proxy URL). */
90
+ let lastHopDashboardBaseUrl;
91
+ let dashboardEnrichTimer = null;
92
+ let dashboardEnrichInFlight = null;
93
+ function clearDashboardTraceEnrichmentSchedules() {
94
+ if (dashboardEnrichTimer) {
95
+ clearTimeout(dashboardEnrichTimer);
96
+ dashboardEnrichTimer = null;
97
+ }
98
+ dashboardEnrichInFlight = null;
99
+ }
100
+ function resolveAtlasEnrichmentDashboardUrl(middlewareDashboardUrl, hopHint) {
101
+ const fromHop = (0, mockifyer_core_2.normalizeDashboardBaseUrl)(hopHint);
102
+ if (fromHop) {
103
+ lastHopDashboardBaseUrl = fromHop;
104
+ return fromHop;
105
+ }
106
+ if (lastHopDashboardBaseUrl) {
107
+ return lastHopDashboardBaseUrl;
108
+ }
109
+ const hasExplicit = Boolean(middlewareDashboardUrl?.trim()) ||
110
+ Boolean(typeof process !== "undefined" &&
111
+ process.env.MOCKIFYER_DASHBOARD_URL?.trim());
112
+ if (!hasExplicit) {
113
+ return undefined;
114
+ }
115
+ return (0, mockifyer_core_2.normalizeDashboardBaseUrl)((0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(middlewareDashboardUrl));
116
+ }
117
+ /**
118
+ * Merge remote-service children into the Metro buffer with a single dashboard read.
119
+ * Buffered hop ids are the parents; descendants are linked by `parentRequestId`.
120
+ * Returns how many new hops were appended. Never throws.
121
+ */
122
+ async function enrichMetroBufferFromDashboard(options) {
123
+ if (!options.dashboardBaseUrl) {
124
+ return 0;
125
+ }
126
+ if (dashboardEnrichInFlight) {
127
+ return dashboardEnrichInFlight;
128
+ }
129
+ const flight = (async () => {
130
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
131
+ const existing = buffer.list();
132
+ const parentRequestIds = [
133
+ ...new Set(existing
134
+ .map((event) => event.requestId?.trim())
135
+ .filter((id) => Boolean(id))),
136
+ ];
137
+ if (parentRequestIds.length === 0) {
138
+ return 0;
139
+ }
140
+ const children = await (0, mockifyer_core_2.pullDashboardDescendantsForParents)({
141
+ dashboardBaseUrl: options.dashboardBaseUrl,
142
+ parentRequestIds,
143
+ existing,
144
+ timeoutMs: options.timeoutMs,
145
+ });
146
+ let added = 0;
147
+ for (const child of children) {
148
+ const stored = buffer.append(child);
149
+ appendNetworkEventNdjson(options.mockDataPath, stored);
150
+ added += 1;
151
+ }
152
+ return added;
153
+ })();
154
+ dashboardEnrichInFlight = flight;
155
+ try {
156
+ return await flight;
157
+ }
158
+ catch {
159
+ return 0;
160
+ }
161
+ finally {
162
+ dashboardEnrichInFlight = null;
163
+ }
164
+ }
165
+ /**
166
+ * Render the current Metro hop buffer to Atlas HTML and log the outcome.
167
+ * Returns the same shape as {@link renderNetworkEventsAtlasHtml}. When the
168
+ * buffer is empty, leaves any existing `index.html` alone.
169
+ */
170
+ function renderBufferedAtlasHtml(options) {
171
+ const events = [...(0, mockifyer_core_2.getMetroNetworkEventBuffer)().list()].reverse();
172
+ const outDir = path.join(options.mockDataPath, "atlas-html");
173
+ const indexPath = path.join(outDir, "index.html");
174
+ const relativeFromRoot = path
175
+ .relative(options.projectRoot, outDir)
176
+ .split(path.sep)
177
+ .join("/");
178
+ if (events.length === 0) {
179
+ console.warn(`[Mockifyer] Atlas: 0 hops — keeping the existing ${indexPath}`);
180
+ console.warn("[Mockifyer] Atlas: no hops reached Metro. Check that Mockifyer is enabled in the app " +
181
+ "(runtimeMode 'manual' needs the dev-menu switch), that the app made requests during the " +
182
+ "session, and that hops arrive: curl http://localhost:8081/mockifyer-network-events");
183
+ return {
184
+ success: false,
185
+ written: 0,
186
+ outputDir: relativeFromRoot,
187
+ indexPath,
188
+ hopCount: 0,
189
+ error: "0 hops — existing index.html left unchanged",
190
+ };
191
+ }
192
+ const startedAt = Date.now();
193
+ const result = renderNetworkEventsAtlasHtml(options.projectRoot, options.mockDataPath, events, options.scenario);
194
+ if (result.success) {
195
+ const elapsedMs = Date.now() - startedAt;
196
+ console.log(`[Mockifyer] Atlas HTML (${result.hopCount} hop(s), ${elapsedMs}ms) → ${result.indexPath}`);
197
+ }
198
+ else {
199
+ console.error(`[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`);
200
+ }
201
+ return result;
202
+ }
203
+ /** Coalesce hop-ingest bursts into one dashboard read. */
204
+ function scheduleDashboardTraceEnrichment(options) {
205
+ if (!options.dashboardBaseUrl) {
206
+ return;
207
+ }
208
+ if (dashboardEnrichTimer) {
209
+ clearTimeout(dashboardEnrichTimer);
210
+ }
211
+ dashboardEnrichTimer = setTimeout(() => {
212
+ dashboardEnrichTimer = null;
213
+ void enrichMetroBufferFromDashboard(options);
214
+ }, DASHBOARD_ENRICH_DEBOUNCE_MS);
215
+ dashboardEnrichTimer.unref?.();
216
+ }
78
217
  /**
79
218
  * Buffer an incoming request body with `Buffer.concat` (not `body += chunk`).
80
219
  * Large Atlas render payloads hang for minutes with quadratic string concatenation.
@@ -783,7 +922,135 @@ function saveAtlasScreenshot(projectRoot, mockDataPath, relativePath, base64, me
783
922
  return { success: false, error: error.message };
784
923
  }
785
924
  }
925
+ /**
926
+ * Candidate relative body paths for a hop (refs first, then id / requestId variants).
927
+ * Spills key by requestId when present, but older captures / races can land under event.id.
928
+ */
929
+ function candidateBodyRelPaths(event, side) {
930
+ const preferred = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
931
+ const out = [side === "req" ? preferred.req : preferred.res];
932
+ const push = (rel) => {
933
+ const trimmed = rel?.trim();
934
+ if (!trimmed || out.includes(trimmed))
935
+ return;
936
+ out.push(trimmed);
937
+ };
938
+ if (side === "req")
939
+ push(event.requestBodyRef);
940
+ else
941
+ push(event.responseBodyRef);
942
+ push((0, mockifyer_core_2.networkBodySpillRelPath)(event.id, event.requestId, side));
943
+ push((0, mockifyer_core_2.networkBodySpillRelPath)(event.id, null, side));
944
+ if (event.requestId?.trim()) {
945
+ push((0, mockifyer_core_2.networkBodySpillRelPath)(event.requestId, event.requestId, side));
946
+ }
947
+ return out;
948
+ }
786
949
  const BODY_SPILL_REL_PATTERN = /^bodies\/[A-Za-z0-9._-]+-(req|res)\.(json|txt)$/;
950
+ /**
951
+ * Locate a full body on disk or in the Metro spill buffer.
952
+ * Writes a buffer hit for *this* hop only — never flushes the whole spill map
953
+ * (that blocked Metro for seconds on every req/res/trace click).
954
+ */
955
+ function findExistingBodyFile(options) {
956
+ const outDir = path.join(options.mockDataPath, "atlas-html");
957
+ const outDirResolved = path.resolve(outDir);
958
+ const snapshot = (0, mockifyer_core_2.getNetworkBodySpillSnapshot)();
959
+ for (const rel of candidateBodyRelPaths(options.event, options.side)) {
960
+ // Validate path: reject absolute paths, parent traversal, and paths outside atlas-html
961
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
962
+ continue;
963
+ }
964
+ const abs = path.resolve(outDir, rel);
965
+ const outDirPrefix = outDirResolved.endsWith(path.sep)
966
+ ? outDirResolved
967
+ : outDirResolved + path.sep;
968
+ if (abs !== outDirResolved && !abs.startsWith(outDirPrefix)) {
969
+ continue;
970
+ }
971
+ const fromBuffer = snapshot[rel];
972
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
973
+ const saved = saveAtlasBodySpill(options.projectRoot, options.mockDataPath, rel, fromBuffer);
974
+ if (saved.success && saved.filePath) {
975
+ return { abs: saved.filePath, rel, text: fromBuffer };
976
+ }
977
+ return {
978
+ abs,
979
+ rel,
980
+ text: fromBuffer,
981
+ };
982
+ }
983
+ if (fs.existsSync(abs)) {
984
+ return { abs, rel };
985
+ }
986
+ }
987
+ return null;
988
+ }
989
+ /**
990
+ * Read spilled request body text for a live include-trace re-call (optional).
991
+ * Prefer in-memory spill; fall back to disk. Does not flush other hops.
992
+ */
993
+ function readSpilledRequestBodyText(projectRoot, mockDataPath, event) {
994
+ const snapshot = (0, mockifyer_core_2.getNetworkBodySpillSnapshot)();
995
+ for (const rel of candidateBodyRelPaths(event, "req")) {
996
+ const fromBuffer = snapshot[rel];
997
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
998
+ return fromBuffer;
999
+ }
1000
+ }
1001
+ const found = findExistingBodyFile({
1002
+ projectRoot,
1003
+ mockDataPath,
1004
+ event,
1005
+ side: "req",
1006
+ });
1007
+ if (!found)
1008
+ return undefined;
1009
+ if (typeof found.text === "string")
1010
+ return found.text;
1011
+ try {
1012
+ return fs.readFileSync(found.abs, "utf8");
1013
+ }
1014
+ catch {
1015
+ return undefined;
1016
+ }
1017
+ }
1018
+ /**
1019
+ * Nested hops already in the Metro buffer for this request (shown on the
1020
+ * include-trace HTML result page before the live re-call payload).
1021
+ */
1022
+ function formatCapturedTraceLines(events, root) {
1023
+ const byParent = new Map();
1024
+ for (const ev of events) {
1025
+ const parent = typeof ev.parentRequestId === "string" ? ev.parentRequestId.trim() : "";
1026
+ if (!parent)
1027
+ continue;
1028
+ const list = byParent.get(parent) ?? [];
1029
+ list.push(ev);
1030
+ byParent.set(parent, list);
1031
+ }
1032
+ const lines = [];
1033
+ const guard = new Set();
1034
+ const walk = (ev, depth) => {
1035
+ const id = (typeof ev.requestId === "string" && ev.requestId.trim()) ||
1036
+ (typeof ev.id === "string" ? ev.id.trim() : "");
1037
+ if (id && guard.has(id))
1038
+ return;
1039
+ if (id)
1040
+ guard.add(id);
1041
+ const indent = depth > 0 ? `${" ".repeat(depth)}` : "";
1042
+ const status = ev.status != null ? String(ev.status) : "—";
1043
+ const ms = ev.durationMs != null ? `${ev.durationMs}ms` : "";
1044
+ lines.push(`${indent}${(ev.method || "?").toUpperCase()} ${status} ${ms} ${ev.url || ev.path || ""}`.trimEnd());
1045
+ if (!id)
1046
+ return;
1047
+ for (const kid of byParent.get(id) || []) {
1048
+ walk(kid, depth + 1);
1049
+ }
1050
+ };
1051
+ walk(root, 0);
1052
+ return lines;
1053
+ }
787
1054
  /**
788
1055
  * Persist a full hop body spill from the device (RN) under atlas-html/bodies/.
789
1056
  */
@@ -967,19 +1234,20 @@ function createMockSyncMiddleware(options) {
967
1234
  atlasKey: options?.atlasKey,
968
1235
  dashboardKey: options?.dashboardKey,
969
1236
  dashboardUrl: options?.dashboardUrl,
970
- onSessionStart: () => {
971
- (0, mockifyer_core_2.getMetroNetworkEventBuffer)().clear();
972
- },
973
- onSessionStop: () => {
974
- const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
975
- const events = [...buffer.list()].reverse();
976
- const result = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
977
- if (result.success) {
978
- console.log(`[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`);
979
- }
980
- else {
981
- console.error(`[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`);
1237
+ onSessionStart: (reason) => {
1238
+ clearDashboardTraceEnrichmentSchedules();
1239
+ // Explicit `t` starts a clean session. Live-stream connect must NOT wipe hops
1240
+ // already in the buffer (that made the live page look empty and empty HTML on stop).
1241
+ if (reason === "key") {
1242
+ lastHopDashboardBaseUrl = undefined;
1243
+ (0, mockifyer_core_2.getMetroNetworkEventBuffer)().clear();
982
1244
  }
1245
+ (0, mockifyer_core_2.setMetroAtlasCaptureSessionActive)(true);
1246
+ },
1247
+ onSessionStop: async () => {
1248
+ (0, mockifyer_core_2.setMetroAtlasCaptureSessionActive)(false);
1249
+ const hopCount = (0, mockifyer_core_2.getMetroNetworkEventBuffer)().list().length;
1250
+ console.log(`[Mockifyer] Atlas: capture ended with ${hopCount} hop(s) in buffer — use live page “Render docs” (or POST /mockifyer-network-events/render) to write HTML.`);
983
1251
  },
984
1252
  });
985
1253
  return function mockSyncMiddleware(req, res, next) {
@@ -991,6 +1259,157 @@ function createMockSyncMiddleware(options) {
991
1259
  res.end(JSON.stringify(result));
992
1260
  return;
993
1261
  }
1262
+ // Atlas `t` capture session — device polls this for include-trace and enableMockifyer().
1263
+ if ((url === mockifyer_core_2.ATLAS_CAPTURE_SESSION_PATH ||
1264
+ url === `${mockifyer_core_2.ATLAS_CAPTURE_SESSION_PATH}/`) &&
1265
+ req.method === "GET") {
1266
+ const phase = (0, metro_atlas_key_handlers_1.getMetroAtlasSessionPhase)();
1267
+ const capturing = phase === "capturing";
1268
+ res.setHeader("Content-Type", "application/json");
1269
+ res.setHeader("Cache-Control", "no-store");
1270
+ res.end(JSON.stringify({
1271
+ success: true,
1272
+ active: (0, mockifyer_core_2.isMetroAtlasCaptureSessionActive)(),
1273
+ phase,
1274
+ capturing,
1275
+ /** App should call enableMockifyer() while capturing (runtimeMode: manual). */
1276
+ activateMockifyer: capturing,
1277
+ }));
1278
+ return;
1279
+ }
1280
+ // Live Atlas hop stream page (browser EventSource → same SSE as mockifyer-atlas CLI)
1281
+ if ((url === mockifyer_core_2.ATLAS_LIVE_STREAM_PATH || url === `${mockifyer_core_2.ATLAS_LIVE_STREAM_PATH}/`) &&
1282
+ req.method === "GET") {
1283
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1284
+ res.setHeader("Cache-Control", "no-store");
1285
+ res.end((0, mockifyer_core_2.buildAtlasLiveStreamHtml)({
1286
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1287
+ }));
1288
+ return;
1289
+ }
1290
+ // Re-call a buffered hop with X-Mockifyer-Include-Trace (live page "trace" link).
1291
+ // Live HTTP only — nested hops come back on the response; no disk/Redis store required.
1292
+ // `format=html` returns a result page (new browser tab); default remains JSON.
1293
+ if (req.method === "GET" && url === mockifyer_core_2.ATLAS_TRACE_REPLAY_PATH) {
1294
+ const fullUrl = String(req.url || "");
1295
+ const q = fullUrl.includes("?")
1296
+ ? fullUrl.slice(fullUrl.indexOf("?") + 1)
1297
+ : "";
1298
+ const params = new URLSearchParams(q);
1299
+ const hopId = (params.get("id") || "").trim();
1300
+ const includeBodies = params.get("bodies") !== "0";
1301
+ const wantHtml = params.get("format") === "html" ||
1302
+ String(req.headers?.accept || "").includes("text/html");
1303
+ if (!hopId) {
1304
+ res.statusCode = 400;
1305
+ if (wantHtml) {
1306
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1307
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)({
1308
+ success: false,
1309
+ hopId: "",
1310
+ method: "",
1311
+ url: "",
1312
+ error: "id query param required",
1313
+ requestHeaders: {},
1314
+ }, {
1315
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1316
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1317
+ }));
1318
+ }
1319
+ else {
1320
+ res.setHeader("Content-Type", "application/json");
1321
+ res.end(JSON.stringify({ success: false, error: "id query param required" }));
1322
+ }
1323
+ return;
1324
+ }
1325
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1326
+ const events = buffer.list();
1327
+ const event = events.find((e) => e && (e.id === hopId || e.requestId === hopId)) ??
1328
+ undefined;
1329
+ // format=html without wait=1: return a shell immediately so the tab is not
1330
+ // blank while the include-trace re-call runs (can be many seconds).
1331
+ if (wantHtml && params.get("wait") !== "1") {
1332
+ const waitParams = new URLSearchParams(params);
1333
+ waitParams.set("format", "html");
1334
+ waitParams.set("wait", "1");
1335
+ res.statusCode = 200;
1336
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1337
+ res.setHeader("Cache-Control", "no-store");
1338
+ res.end((0, mockifyer_core_2.buildAtlasTracePendingHtml)({
1339
+ hopId,
1340
+ method: event?.method,
1341
+ url: event?.url,
1342
+ resultUrl: `${mockifyer_core_2.ATLAS_TRACE_REPLAY_PATH}?${waitParams.toString()}`,
1343
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1344
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1345
+ timeoutMs: mockifyer_core_2.ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1346
+ }));
1347
+ return;
1348
+ }
1349
+ const spilledRequestBody = event
1350
+ ? readSpilledRequestBodyText(projectRoot, mockDataPath, event)
1351
+ : undefined;
1352
+ const capturedLines = event
1353
+ ? formatCapturedTraceLines(events, event)
1354
+ : undefined;
1355
+ void (0, mockifyer_core_2.replayNetworkEventWithIncludeTrace)(events, hopId, {
1356
+ includeBodies,
1357
+ requestBody: spilledRequestBody,
1358
+ timeoutMs: mockifyer_core_2.ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1359
+ })
1360
+ .then((result) => {
1361
+ if (res.writableEnded)
1362
+ return;
1363
+ res.statusCode = result.success
1364
+ ? 200
1365
+ : result.error === "hop not found"
1366
+ ? 404
1367
+ : 502;
1368
+ res.setHeader("Cache-Control", "no-store");
1369
+ if (wantHtml) {
1370
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1371
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)(result, {
1372
+ capturedLines,
1373
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1374
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1375
+ requestBody: spilledRequestBody ||
1376
+ (typeof event?.requestBodyPreview === "string"
1377
+ ? event.requestBodyPreview
1378
+ : undefined),
1379
+ }));
1380
+ }
1381
+ else {
1382
+ res.setHeader("Content-Type", "application/json");
1383
+ res.end(JSON.stringify(result));
1384
+ }
1385
+ })
1386
+ .catch((error) => {
1387
+ if (res.writableEnded)
1388
+ return;
1389
+ const message = error instanceof Error ? error.message : String(error);
1390
+ res.statusCode = 500;
1391
+ res.setHeader("Cache-Control", "no-store");
1392
+ if (wantHtml) {
1393
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1394
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)({
1395
+ success: false,
1396
+ hopId,
1397
+ method: event?.method || "",
1398
+ url: event?.url || "",
1399
+ error: message,
1400
+ requestHeaders: {},
1401
+ }, {
1402
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1403
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1404
+ }));
1405
+ }
1406
+ else {
1407
+ res.setHeader("Content-Type", "application/json");
1408
+ res.end(JSON.stringify({ success: false, hopId, error: message }));
1409
+ }
1410
+ });
1411
+ return;
1412
+ }
994
1413
  // Live hop ring buffer for `mockifyer-atlas` interactive CLI
995
1414
  if (url === "/mockifyer-network-events" && req.method === "POST") {
996
1415
  collectRequestBodyUtf8(req, (err, body) => {
@@ -1027,12 +1446,17 @@ function createMockSyncMiddleware(options) {
1027
1446
  appendNetworkEventNdjson(mockDataPath, stored);
1028
1447
  return stored;
1029
1448
  });
1449
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(options?.dashboardUrl, parsed.dashboardBaseUrl);
1450
+ if (dashboardBaseUrl) {
1451
+ scheduleDashboardTraceEnrichment({ dashboardBaseUrl, mockDataPath });
1452
+ }
1030
1453
  res.statusCode = 201;
1031
1454
  res.setHeader("Content-Type", "application/json");
1032
1455
  res.end(JSON.stringify({
1033
1456
  success: true,
1034
1457
  count: saved.length,
1035
1458
  size: buffer.size,
1459
+ atlasCaptureActive: (0, mockifyer_core_2.isMetroAtlasCaptureSessionActive)(),
1036
1460
  }));
1037
1461
  }
1038
1462
  catch (error) {
@@ -1063,8 +1487,7 @@ function createMockSyncMiddleware(options) {
1063
1487
  const qIndex = fullUrl.indexOf("?");
1064
1488
  const params = new URLSearchParams(qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "");
1065
1489
  const backlog = params.get("backlog") !== "0";
1066
- // First SSE client (e.g. mockifyer-atlas) auto-starts Metro Atlas capture.
1067
- // Must run before reading the buffer — start clears hops for a clean session.
1490
+ // Track the SSE client. Capture starts only when Metro `t` is pressed.
1068
1491
  (0, metro_atlas_key_handlers_1.notifyMetroAtlasStreamClientConnected)();
1069
1492
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1070
1493
  res.writeHead(200, {
@@ -1169,16 +1592,34 @@ function createMockSyncMiddleware(options) {
1169
1592
  // empty / ignore
1170
1593
  }
1171
1594
  }
1172
- const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1173
- const events = [...buffer.list()].reverse();
1174
- const result = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events, scenario);
1175
- res.statusCode = result.success ? 201 : 500;
1176
- res.setHeader("Content-Type", "application/json");
1177
- res.end(JSON.stringify(result));
1595
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(options?.dashboardUrl);
1596
+ const finishRender = () => {
1597
+ const result = renderBufferedAtlasHtml({
1598
+ projectRoot,
1599
+ mockDataPath,
1600
+ scenario,
1601
+ });
1602
+ res.statusCode = result.success ? 201 : 500;
1603
+ res.setHeader("Content-Type", "application/json");
1604
+ res.end(JSON.stringify(result));
1605
+ };
1606
+ if (!dashboardBaseUrl) {
1607
+ finishRender();
1608
+ return;
1609
+ }
1610
+ void enrichMetroBufferFromDashboard({
1611
+ dashboardBaseUrl,
1612
+ mockDataPath,
1613
+ timeoutMs: DASHBOARD_ENRICH_DEADLINE_MS,
1614
+ }).then(() => {
1615
+ finishRender();
1616
+ });
1178
1617
  });
1179
1618
  return;
1180
1619
  }
1181
1620
  if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
1621
+ clearDashboardTraceEnrichmentSchedules();
1622
+ lastHopDashboardBaseUrl = undefined;
1182
1623
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1183
1624
  buffer.clear();
1184
1625
  res.setHeader("Content-Type", "application/json");
@@ -1239,6 +1680,10 @@ function createMockSyncMiddleware(options) {
1239
1680
  }
1240
1681
  // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1241
1682
  // GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
1683
+ //
1684
+ // req/res must stay fast: look up the hop + flush/serve the body spill only.
1685
+ // Never rebuild the full Atlas HTML site here — that used to hang for seconds
1686
+ // when the buffer was large (writeAtlasDocHtml for every hop).
1242
1687
  if (req.method === "GET" &&
1243
1688
  (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))) {
1244
1689
  const fullUrl = String(req.url || "");
@@ -1248,68 +1693,99 @@ function createMockSyncMiddleware(options) {
1248
1693
  const sideParam = (params.get("side") || "html").trim().toLowerCase();
1249
1694
  const side = sideParam === "req" || sideParam === "res" ? sideParam : "html";
1250
1695
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1251
- // Buffer is newest-first; render expects chronological / display order.
1252
- const events = [...buffer.list()].reverse();
1253
- const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1254
- if (!rendered.success) {
1255
- res.statusCode = 500;
1256
- res.setHeader("Content-Type", "application/json");
1257
- res.end(JSON.stringify({
1258
- success: false,
1259
- error: rendered.error || "atlas render failed",
1260
- }));
1261
- return;
1262
- }
1696
+ const listed = buffer.list();
1263
1697
  if (side === "html") {
1698
+ // Full site rebuild only when opening the Atlas index (terminal / html link).
1699
+ const events = [...listed].reverse();
1700
+ const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1701
+ if (!rendered.success) {
1702
+ res.statusCode = 500;
1703
+ res.setHeader("Content-Type", "application/json");
1704
+ res.end(JSON.stringify({
1705
+ success: false,
1706
+ error: rendered.error || "atlas render failed",
1707
+ }));
1708
+ return;
1709
+ }
1264
1710
  res.statusCode = 302;
1265
1711
  res.setHeader("Location", "/atlas-html/index.html");
1266
1712
  res.end();
1267
1713
  return;
1268
1714
  }
1269
1715
  const event = (hopId
1270
- ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1271
- : undefined) || events[0];
1716
+ ? listed.find((e) => e && (e.id === hopId || e.requestId === hopId))
1717
+ : undefined) || listed[0];
1272
1718
  if (!event) {
1273
1719
  res.statusCode = 404;
1274
1720
  res.setHeader("Content-Type", "application/json");
1275
1721
  res.end(JSON.stringify({ success: false, error: "hop not found" }));
1276
1722
  return;
1277
1723
  }
1278
- const rels = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1279
- const rel = side === "req" ? rels.req : rels.res;
1280
- const abs = path.join(mockDataPath, "atlas-html", rel);
1281
- const outDir = path.join(mockDataPath, "atlas-html");
1282
- // Prefer real spill buffer / disk — never materialize the truncated Metro
1283
- // hop preview (often ~512 bytes) as the "full body" JSON page.
1284
- (0, mockifyer_core_2.flushNetworkBodySpillsToDir)(outDir);
1285
- const fromBuffer = (0, mockifyer_core_2.getNetworkBodySpillSnapshot)()[rel];
1286
- if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1287
- const saved = saveAtlasBodySpill(projectRoot, mockDataPath, rel, fromBuffer);
1288
- if (!saved.success) {
1289
- res.statusCode = 500;
1290
- res.setHeader("Content-Type", "application/json");
1291
- res.end(JSON.stringify({
1292
- success: false,
1293
- error: saved.error || "Failed to write full body spill",
1294
- }));
1724
+ const found = findExistingBodyFile({
1725
+ projectRoot,
1726
+ mockDataPath,
1727
+ event,
1728
+ side,
1729
+ });
1730
+ if (found) {
1731
+ // Serve the body directly — a 302 to /atlas-html/... is a second hop and
1732
+ // used to queue behind other sync Atlas work in Metro.
1733
+ let text = found.text;
1734
+ if (typeof text !== "string") {
1735
+ try {
1736
+ text = fs.readFileSync(found.abs, "utf8");
1737
+ }
1738
+ catch {
1739
+ text = undefined;
1740
+ }
1741
+ }
1742
+ if (typeof text === "string") {
1743
+ const ext = path.extname(found.rel).toLowerCase();
1744
+ res.statusCode = 200;
1745
+ res.setHeader("Content-Type", ext === ".json"
1746
+ ? "application/json; charset=utf-8"
1747
+ : "text/plain; charset=utf-8");
1748
+ res.setHeader("Cache-Control", "no-store");
1749
+ res.setHeader("X-Mockifyer-Body-Source", "spill");
1750
+ res.setHeader("X-Mockifyer-Body-Rel", found.rel.split(path.sep).join("/"));
1751
+ res.end(text);
1295
1752
  return;
1296
1753
  }
1754
+ res.statusCode = 302;
1755
+ res.setHeader("Location", `/atlas-html/${found.rel.split(path.sep).join("/")}`);
1756
+ res.end();
1757
+ return;
1297
1758
  }
1298
- else if (!fs.existsSync(abs)) {
1299
- res.statusCode = 404;
1300
- res.setHeader("Content-Type", "application/json");
1759
+ // Spill not on disk yet (race) or never uploaded — still return the captured
1760
+ // preview so open/trace UX is usable. Do not write preview as the spill file.
1761
+ const preview = side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
1762
+ if (typeof preview === "string" && preview.length > 0) {
1763
+ const preferred = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1764
+ res.statusCode = 200;
1765
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1766
+ res.setHeader("Cache-Control", "no-store");
1767
+ res.setHeader("X-Mockifyer-Body-Source", "preview");
1768
+ res.setHeader("X-Mockifyer-Body-Note", "Full spill file missing; showing hop preview");
1301
1769
  res.end(JSON.stringify({
1302
- success: false,
1303
- error: "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.",
1770
+ success: true,
1771
+ source: "preview",
1304
1772
  hopId: event.id,
1305
1773
  side,
1306
- relativePath: rel,
1307
- }));
1774
+ relativePath: side === "req" ? preferred.req : preferred.res,
1775
+ preview,
1776
+ }, null, 2));
1308
1777
  return;
1309
1778
  }
1310
- res.statusCode = 302;
1311
- res.setHeader("Location", `/atlas-html/${rel.split(path.sep).join("/")}`);
1312
- res.end();
1779
+ const preferred = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1780
+ res.statusCode = 404;
1781
+ res.setHeader("Content-Type", "application/json");
1782
+ res.end(JSON.stringify({
1783
+ success: false,
1784
+ error: "No full body spill on disk and no hop preview. Re-hit the endpoint during Atlas capture, then open again.",
1785
+ hopId: event.id,
1786
+ side,
1787
+ relativePath: side === "req" ? preferred.req : preferred.res,
1788
+ }));
1313
1789
  return;
1314
1790
  }
1315
1791
  // Atlas HTML static files (index, pages, incidents, screenshots) — must not fall through to Expo web shell.