@sgedda/mockifyer-fetch 1.8.86 → 1.8.92

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 flag
26
+ * 21. Metro terminal key `t` — start/stop Atlas capture (start opens live stream; stop ends capture; Render docs on the live page writes HTML; stream auto-starts; `atlasKey: false` to disable). `a` is reserved for Android.
27
+ * 22. Metro terminal key `m` — open Mockifyer dashboard in the browser (`dashboardKey: false` to disable)
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
  */
@@ -961,23 +1228,26 @@ function createMockSyncMiddleware(options) {
961
1228
  const testConfig = getTestGenerationConfig(options);
962
1229
  // Log the resolved paths for debugging
963
1230
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
1231
+ /** Last scenario announced at info. Polls of an unchanged scenario stay quiet. */
1232
+ let announcedScenario;
964
1233
  (0, metro_atlas_key_handlers_1.attachMetroAtlasKeyHandler)({
965
1234
  atlasKey: options?.atlasKey,
966
1235
  dashboardKey: options?.dashboardKey,
967
1236
  dashboardUrl: options?.dashboardUrl,
968
- onSessionStart: () => {
969
- (0, mockifyer_core_2.getMetroNetworkEventBuffer)().clear();
970
- },
971
- onSessionStop: () => {
972
- const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
973
- const events = [...buffer.list()].reverse();
974
- const result = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
975
- if (result.success) {
976
- console.log(`[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`);
977
- }
978
- else {
979
- 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();
980
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.`);
981
1251
  },
982
1252
  });
983
1253
  return function mockSyncMiddleware(req, res, next) {
@@ -989,6 +1259,151 @@ function createMockSyncMiddleware(options) {
989
1259
  res.end(JSON.stringify(result));
990
1260
  return;
991
1261
  }
1262
+ // Atlas `t` capture session flag — device / live page poll this for session UI.
1263
+ if ((url === mockifyer_core_2.ATLAS_CAPTURE_SESSION_PATH ||
1264
+ url === `${mockifyer_core_2.ATLAS_CAPTURE_SESSION_PATH}/`) &&
1265
+ req.method === "GET") {
1266
+ res.setHeader("Content-Type", "application/json");
1267
+ res.setHeader("Cache-Control", "no-store");
1268
+ res.end(JSON.stringify({
1269
+ success: true,
1270
+ active: (0, mockifyer_core_2.isMetroAtlasCaptureSessionActive)(),
1271
+ }));
1272
+ return;
1273
+ }
1274
+ // Live Atlas hop stream page (browser EventSource → same SSE as mockifyer-atlas CLI)
1275
+ if ((url === mockifyer_core_2.ATLAS_LIVE_STREAM_PATH || url === `${mockifyer_core_2.ATLAS_LIVE_STREAM_PATH}/`) &&
1276
+ req.method === "GET") {
1277
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1278
+ res.setHeader("Cache-Control", "no-store");
1279
+ res.end((0, mockifyer_core_2.buildAtlasLiveStreamHtml)({
1280
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1281
+ }));
1282
+ return;
1283
+ }
1284
+ // Re-call a buffered hop with X-Mockifyer-Include-Trace (live page "trace" link).
1285
+ // Live HTTP only — nested hops come back on the response; no disk/Redis store required.
1286
+ // `format=html` returns a result page (new browser tab); default remains JSON.
1287
+ if (req.method === "GET" && url === mockifyer_core_2.ATLAS_TRACE_REPLAY_PATH) {
1288
+ const fullUrl = String(req.url || "");
1289
+ const q = fullUrl.includes("?")
1290
+ ? fullUrl.slice(fullUrl.indexOf("?") + 1)
1291
+ : "";
1292
+ const params = new URLSearchParams(q);
1293
+ const hopId = (params.get("id") || "").trim();
1294
+ const includeBodies = params.get("bodies") !== "0";
1295
+ const wantHtml = params.get("format") === "html" ||
1296
+ String(req.headers?.accept || "").includes("text/html");
1297
+ if (!hopId) {
1298
+ res.statusCode = 400;
1299
+ if (wantHtml) {
1300
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1301
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)({
1302
+ success: false,
1303
+ hopId: "",
1304
+ method: "",
1305
+ url: "",
1306
+ error: "id query param required",
1307
+ requestHeaders: {},
1308
+ }, {
1309
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1310
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1311
+ }));
1312
+ }
1313
+ else {
1314
+ res.setHeader("Content-Type", "application/json");
1315
+ res.end(JSON.stringify({ success: false, error: "id query param required" }));
1316
+ }
1317
+ return;
1318
+ }
1319
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1320
+ const events = buffer.list();
1321
+ const event = events.find((e) => e && (e.id === hopId || e.requestId === hopId)) ??
1322
+ undefined;
1323
+ // format=html without wait=1: return a shell immediately so the tab is not
1324
+ // blank while the include-trace re-call runs (can be many seconds).
1325
+ if (wantHtml && params.get("wait") !== "1") {
1326
+ const waitParams = new URLSearchParams(params);
1327
+ waitParams.set("format", "html");
1328
+ waitParams.set("wait", "1");
1329
+ res.statusCode = 200;
1330
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1331
+ res.setHeader("Cache-Control", "no-store");
1332
+ res.end((0, mockifyer_core_2.buildAtlasTracePendingHtml)({
1333
+ hopId,
1334
+ method: event?.method,
1335
+ url: event?.url,
1336
+ resultUrl: `${mockifyer_core_2.ATLAS_TRACE_REPLAY_PATH}?${waitParams.toString()}`,
1337
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1338
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1339
+ timeoutMs: mockifyer_core_2.ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1340
+ }));
1341
+ return;
1342
+ }
1343
+ const spilledRequestBody = event
1344
+ ? readSpilledRequestBodyText(projectRoot, mockDataPath, event)
1345
+ : undefined;
1346
+ const capturedLines = event
1347
+ ? formatCapturedTraceLines(events, event)
1348
+ : undefined;
1349
+ void (0, mockifyer_core_2.replayNetworkEventWithIncludeTrace)(events, hopId, {
1350
+ includeBodies,
1351
+ requestBody: spilledRequestBody,
1352
+ timeoutMs: mockifyer_core_2.ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1353
+ })
1354
+ .then((result) => {
1355
+ if (res.writableEnded)
1356
+ return;
1357
+ res.statusCode = result.success
1358
+ ? 200
1359
+ : result.error === "hop not found"
1360
+ ? 404
1361
+ : 502;
1362
+ res.setHeader("Cache-Control", "no-store");
1363
+ if (wantHtml) {
1364
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1365
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)(result, {
1366
+ capturedLines,
1367
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1368
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1369
+ requestBody: spilledRequestBody ||
1370
+ (typeof event?.requestBodyPreview === "string"
1371
+ ? event.requestBodyPreview
1372
+ : undefined),
1373
+ }));
1374
+ }
1375
+ else {
1376
+ res.setHeader("Content-Type", "application/json");
1377
+ res.end(JSON.stringify(result));
1378
+ }
1379
+ })
1380
+ .catch((error) => {
1381
+ if (res.writableEnded)
1382
+ return;
1383
+ const message = error instanceof Error ? error.message : String(error);
1384
+ res.statusCode = 500;
1385
+ res.setHeader("Cache-Control", "no-store");
1386
+ if (wantHtml) {
1387
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1388
+ res.end((0, mockifyer_core_2.buildAtlasTraceReplayHtml)({
1389
+ success: false,
1390
+ hopId,
1391
+ method: event?.method || "",
1392
+ url: event?.url || "",
1393
+ error: message,
1394
+ requestHeaders: {},
1395
+ }, {
1396
+ atlasLiveUrl: mockifyer_core_2.ATLAS_LIVE_STREAM_PATH,
1397
+ dashboardUrl: (0, metro_atlas_key_handlers_1.resolveMetroDashboardUrl)(options?.dashboardUrl),
1398
+ }));
1399
+ }
1400
+ else {
1401
+ res.setHeader("Content-Type", "application/json");
1402
+ res.end(JSON.stringify({ success: false, hopId, error: message }));
1403
+ }
1404
+ });
1405
+ return;
1406
+ }
992
1407
  // Live hop ring buffer for `mockifyer-atlas` interactive CLI
993
1408
  if (url === "/mockifyer-network-events" && req.method === "POST") {
994
1409
  collectRequestBodyUtf8(req, (err, body) => {
@@ -1025,12 +1440,17 @@ function createMockSyncMiddleware(options) {
1025
1440
  appendNetworkEventNdjson(mockDataPath, stored);
1026
1441
  return stored;
1027
1442
  });
1443
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(options?.dashboardUrl, parsed.dashboardBaseUrl);
1444
+ if (dashboardBaseUrl) {
1445
+ scheduleDashboardTraceEnrichment({ dashboardBaseUrl, mockDataPath });
1446
+ }
1028
1447
  res.statusCode = 201;
1029
1448
  res.setHeader("Content-Type", "application/json");
1030
1449
  res.end(JSON.stringify({
1031
1450
  success: true,
1032
1451
  count: saved.length,
1033
1452
  size: buffer.size,
1453
+ atlasCaptureActive: (0, mockifyer_core_2.isMetroAtlasCaptureSessionActive)(),
1034
1454
  }));
1035
1455
  }
1036
1456
  catch (error) {
@@ -1167,16 +1587,34 @@ function createMockSyncMiddleware(options) {
1167
1587
  // empty / ignore
1168
1588
  }
1169
1589
  }
1170
- const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1171
- const events = [...buffer.list()].reverse();
1172
- const result = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events, scenario);
1173
- res.statusCode = result.success ? 201 : 500;
1174
- res.setHeader("Content-Type", "application/json");
1175
- res.end(JSON.stringify(result));
1590
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(options?.dashboardUrl);
1591
+ const finishRender = () => {
1592
+ const result = renderBufferedAtlasHtml({
1593
+ projectRoot,
1594
+ mockDataPath,
1595
+ scenario,
1596
+ });
1597
+ res.statusCode = result.success ? 201 : 500;
1598
+ res.setHeader("Content-Type", "application/json");
1599
+ res.end(JSON.stringify(result));
1600
+ };
1601
+ if (!dashboardBaseUrl) {
1602
+ finishRender();
1603
+ return;
1604
+ }
1605
+ void enrichMetroBufferFromDashboard({
1606
+ dashboardBaseUrl,
1607
+ mockDataPath,
1608
+ timeoutMs: DASHBOARD_ENRICH_DEADLINE_MS,
1609
+ }).then(() => {
1610
+ finishRender();
1611
+ });
1176
1612
  });
1177
1613
  return;
1178
1614
  }
1179
1615
  if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
1616
+ clearDashboardTraceEnrichmentSchedules();
1617
+ lastHopDashboardBaseUrl = undefined;
1180
1618
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1181
1619
  buffer.clear();
1182
1620
  res.setHeader("Content-Type", "application/json");
@@ -1237,6 +1675,10 @@ function createMockSyncMiddleware(options) {
1237
1675
  }
1238
1676
  // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1239
1677
  // GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
1678
+ //
1679
+ // req/res must stay fast: look up the hop + flush/serve the body spill only.
1680
+ // Never rebuild the full Atlas HTML site here — that used to hang for seconds
1681
+ // when the buffer was large (writeAtlasDocHtml for every hop).
1240
1682
  if (req.method === "GET" &&
1241
1683
  (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))) {
1242
1684
  const fullUrl = String(req.url || "");
@@ -1246,68 +1688,99 @@ function createMockSyncMiddleware(options) {
1246
1688
  const sideParam = (params.get("side") || "html").trim().toLowerCase();
1247
1689
  const side = sideParam === "req" || sideParam === "res" ? sideParam : "html";
1248
1690
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1249
- // Buffer is newest-first; render expects chronological / display order.
1250
- const events = [...buffer.list()].reverse();
1251
- const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1252
- if (!rendered.success) {
1253
- res.statusCode = 500;
1254
- res.setHeader("Content-Type", "application/json");
1255
- res.end(JSON.stringify({
1256
- success: false,
1257
- error: rendered.error || "atlas render failed",
1258
- }));
1259
- return;
1260
- }
1691
+ const listed = buffer.list();
1261
1692
  if (side === "html") {
1693
+ // Full site rebuild only when opening the Atlas index (terminal / html link).
1694
+ const events = [...listed].reverse();
1695
+ const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1696
+ if (!rendered.success) {
1697
+ res.statusCode = 500;
1698
+ res.setHeader("Content-Type", "application/json");
1699
+ res.end(JSON.stringify({
1700
+ success: false,
1701
+ error: rendered.error || "atlas render failed",
1702
+ }));
1703
+ return;
1704
+ }
1262
1705
  res.statusCode = 302;
1263
1706
  res.setHeader("Location", "/atlas-html/index.html");
1264
1707
  res.end();
1265
1708
  return;
1266
1709
  }
1267
1710
  const event = (hopId
1268
- ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1269
- : undefined) || events[0];
1711
+ ? listed.find((e) => e && (e.id === hopId || e.requestId === hopId))
1712
+ : undefined) || listed[0];
1270
1713
  if (!event) {
1271
1714
  res.statusCode = 404;
1272
1715
  res.setHeader("Content-Type", "application/json");
1273
1716
  res.end(JSON.stringify({ success: false, error: "hop not found" }));
1274
1717
  return;
1275
1718
  }
1276
- const rels = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1277
- const rel = side === "req" ? rels.req : rels.res;
1278
- const abs = path.join(mockDataPath, "atlas-html", rel);
1279
- const outDir = path.join(mockDataPath, "atlas-html");
1280
- // Prefer real spill buffer / disk — never materialize the truncated Metro
1281
- // hop preview (often ~512 bytes) as the "full body" JSON page.
1282
- (0, mockifyer_core_2.flushNetworkBodySpillsToDir)(outDir);
1283
- const fromBuffer = (0, mockifyer_core_2.getNetworkBodySpillSnapshot)()[rel];
1284
- if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1285
- const saved = saveAtlasBodySpill(projectRoot, mockDataPath, rel, fromBuffer);
1286
- if (!saved.success) {
1287
- res.statusCode = 500;
1288
- res.setHeader("Content-Type", "application/json");
1289
- res.end(JSON.stringify({
1290
- success: false,
1291
- error: saved.error || "Failed to write full body spill",
1292
- }));
1719
+ const found = findExistingBodyFile({
1720
+ projectRoot,
1721
+ mockDataPath,
1722
+ event,
1723
+ side,
1724
+ });
1725
+ if (found) {
1726
+ // Serve the body directly — a 302 to /atlas-html/... is a second hop and
1727
+ // used to queue behind other sync Atlas work in Metro.
1728
+ let text = found.text;
1729
+ if (typeof text !== "string") {
1730
+ try {
1731
+ text = fs.readFileSync(found.abs, "utf8");
1732
+ }
1733
+ catch {
1734
+ text = undefined;
1735
+ }
1736
+ }
1737
+ if (typeof text === "string") {
1738
+ const ext = path.extname(found.rel).toLowerCase();
1739
+ res.statusCode = 200;
1740
+ res.setHeader("Content-Type", ext === ".json"
1741
+ ? "application/json; charset=utf-8"
1742
+ : "text/plain; charset=utf-8");
1743
+ res.setHeader("Cache-Control", "no-store");
1744
+ res.setHeader("X-Mockifyer-Body-Source", "spill");
1745
+ res.setHeader("X-Mockifyer-Body-Rel", found.rel.split(path.sep).join("/"));
1746
+ res.end(text);
1293
1747
  return;
1294
1748
  }
1749
+ res.statusCode = 302;
1750
+ res.setHeader("Location", `/atlas-html/${found.rel.split(path.sep).join("/")}`);
1751
+ res.end();
1752
+ return;
1295
1753
  }
1296
- else if (!fs.existsSync(abs)) {
1297
- res.statusCode = 404;
1298
- res.setHeader("Content-Type", "application/json");
1754
+ // Spill not on disk yet (race) or never uploaded — still return the captured
1755
+ // preview so open/trace UX is usable. Do not write preview as the spill file.
1756
+ const preview = side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
1757
+ if (typeof preview === "string" && preview.length > 0) {
1758
+ const preferred = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1759
+ res.statusCode = 200;
1760
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1761
+ res.setHeader("Cache-Control", "no-store");
1762
+ res.setHeader("X-Mockifyer-Body-Source", "preview");
1763
+ res.setHeader("X-Mockifyer-Body-Note", "Full spill file missing; showing hop preview");
1299
1764
  res.end(JSON.stringify({
1300
- success: false,
1301
- 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.",
1765
+ success: true,
1766
+ source: "preview",
1302
1767
  hopId: event.id,
1303
1768
  side,
1304
- relativePath: rel,
1305
- }));
1769
+ relativePath: side === "req" ? preferred.req : preferred.res,
1770
+ preview,
1771
+ }, null, 2));
1306
1772
  return;
1307
1773
  }
1308
- res.statusCode = 302;
1309
- res.setHeader("Location", `/atlas-html/${rel.split(path.sep).join("/")}`);
1310
- res.end();
1774
+ const preferred = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1775
+ res.statusCode = 404;
1776
+ res.setHeader("Content-Type", "application/json");
1777
+ res.end(JSON.stringify({
1778
+ success: false,
1779
+ error: "No full body spill on disk and no hop preview. Re-hit the endpoint during Atlas capture, then open again.",
1780
+ hopId: event.id,
1781
+ side,
1782
+ relativePath: side === "req" ? preferred.req : preferred.res,
1783
+ }));
1311
1784
  return;
1312
1785
  }
1313
1786
  // Atlas HTML static files (index, pages, incidents, screenshots) — must not fall through to Expo web shell.
@@ -1603,41 +2076,39 @@ function createMockSyncMiddleware(options) {
1603
2076
  }
1604
2077
  // Handle GET endpoint for scenario config
1605
2078
  if (url === "/mockifyer-scenario-config" && req.method === "GET") {
2079
+ const writeScenarioResponse = (scenario) => {
2080
+ if (announcedScenario !== scenario) {
2081
+ mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Active scenario: ${scenario}`);
2082
+ announcedScenario = scenario;
2083
+ }
2084
+ res.setHeader("Content-Type", "application/json");
2085
+ res.end(JSON.stringify({
2086
+ success: true,
2087
+ currentScenario: scenario,
2088
+ }));
2089
+ };
1606
2090
  try {
1607
2091
  // Check environment variable first (highest priority)
1608
2092
  if (process.env.MOCKIFYER_SCENARIO) {
1609
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
1610
- res.setHeader("Content-Type", "application/json");
1611
- res.end(JSON.stringify({
1612
- success: true,
1613
- currentScenario: process.env.MOCKIFYER_SCENARIO,
1614
- }));
2093
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
2094
+ writeScenarioResponse(process.env.MOCKIFYER_SCENARIO);
1615
2095
  return;
1616
2096
  }
1617
2097
  const configPath = path.join(mockDataPath, "scenario-config.json");
1618
2098
  const resolvedPath = path.resolve(configPath);
1619
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
1620
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
2099
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
2100
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
1621
2101
  if (fs.existsSync(configPath)) {
1622
2102
  const fileContent = fs.readFileSync(configPath, "utf-8");
1623
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
2103
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
1624
2104
  const config = JSON.parse(fileContent);
1625
2105
  const scenario = config.currentScenario || DEFAULT_SCENARIO;
1626
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
1627
- res.setHeader("Content-Type", "application/json");
1628
- // Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
1629
- res.end(JSON.stringify({
1630
- success: true,
1631
- currentScenario: scenario,
1632
- }));
2106
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
2107
+ writeScenarioResponse(scenario);
1633
2108
  }
1634
2109
  else {
1635
- mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
1636
- res.setHeader("Content-Type", "application/json");
1637
- res.end(JSON.stringify({
1638
- success: true,
1639
- currentScenario: DEFAULT_SCENARIO,
1640
- }));
2110
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
2111
+ writeScenarioResponse(DEFAULT_SCENARIO);
1641
2112
  }
1642
2113
  }
1643
2114
  catch (error) {