@sgedda/mockifyer-fetch 1.8.72 → 1.8.86

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.
@@ -0,0 +1,448 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DEFAULT_METRO_DASHBOARD_URL = exports.DEFAULT_METRO_DASHBOARD_KEY = exports.DEFAULT_METRO_ATLAS_KEY = void 0;
37
+ exports.resolveKeyOption = resolveKeyOption;
38
+ exports.resolveAtlasKeyOption = resolveAtlasKeyOption;
39
+ exports.resolveDashboardKeyOption = resolveDashboardKeyOption;
40
+ exports.resolveMetroDashboardUrl = resolveMetroDashboardUrl;
41
+ exports.openMetroBrowseUrl = openMetroBrowseUrl;
42
+ exports.matchesAtlasKey = matchesAtlasKey;
43
+ exports.getMetroAtlasSessionPhase = getMetroAtlasSessionPhase;
44
+ exports.getMetroAtlasStreamSubscriberCount = getMetroAtlasStreamSubscriberCount;
45
+ exports.startMetroAtlasSession = startMetroAtlasSession;
46
+ exports.stopMetroAtlasSession = stopMetroAtlasSession;
47
+ exports.openMetroDashboard = openMetroDashboard;
48
+ exports.notifyMetroAtlasStreamClientConnected = notifyMetroAtlasStreamClientConnected;
49
+ exports.notifyMetroAtlasStreamClientDisconnected = notifyMetroAtlasStreamClientDisconnected;
50
+ exports.detachMetroAtlasKeyHandler = detachMetroAtlasKeyHandler;
51
+ exports.attachMetroAtlasKeyHandler = attachMetroAtlasKeyHandler;
52
+ /**
53
+ * Metro terminal keys for Mockifyer:
54
+ * - `t` (default): start/stop Atlas capture (stop generates HTML)
55
+ * - `m` (default): open the Mockifyer dashboard in the browser
56
+ *
57
+ * Opening `mockifyer-atlas` (SSE `/mockifyer-network-events/stream`) auto-starts
58
+ * capture when idle — then press `t` once to stop & generate.
59
+ *
60
+ * `a` is reserved by Metro for Android (`i` iOS, `r` reload, `d` Dev Menu, `j` DevTools).
61
+ * Disable Atlas with `atlasKey: false`, dashboard with `dashboardKey: false`.
62
+ */
63
+ const readline = __importStar(require("readline"));
64
+ const child_process_1 = require("child_process");
65
+ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
66
+ /**
67
+ * Keys already used by @react-native/community-cli-plugin (avoid stealing).
68
+ * Value is the short reason shown when a binding collides.
69
+ */
70
+ const RESERVED_METRO_KEYS = new Map([
71
+ ["a", "Android"],
72
+ ["d", "the Dev Menu"],
73
+ ["i", "iOS"],
74
+ ["j", "DevTools"],
75
+ ["r", "reload"],
76
+ ]);
77
+ /** `t` — `a` launches Android in the Metro / RN CLI. */
78
+ exports.DEFAULT_METRO_ATLAS_KEY = "t";
79
+ exports.DEFAULT_METRO_DASHBOARD_KEY = "m";
80
+ exports.DEFAULT_METRO_DASHBOARD_URL = "http://localhost:3002";
81
+ /** Delay so RN/Expo CLI can own raw-mode stdin first. */
82
+ const ATTACH_DEFER_MS = 1000;
83
+ let attached = false;
84
+ let weSetRawMode = false;
85
+ let activeHandler = null;
86
+ let activeStdin = null;
87
+ let pendingTimer = null;
88
+ let sessionPhase = "idle";
89
+ let sessionStartedAt = null;
90
+ let sessionCallbacks = null;
91
+ let streamSubscriberCount = 0;
92
+ /**
93
+ * Normalize a single-char key option: default when undefined, `false` → disabled.
94
+ */
95
+ function resolveKeyOption(value, defaultKey) {
96
+ if (value === false)
97
+ return null;
98
+ const raw = value === undefined || value === null ? defaultKey : String(value).trim();
99
+ if (!raw)
100
+ return null;
101
+ const key = raw.length === 1 ? raw.toLowerCase() : raw.toLowerCase().charAt(0);
102
+ return key || null;
103
+ }
104
+ /**
105
+ * Normalize `atlasKey` option: default `"t"`, `false` → disabled, else single char.
106
+ */
107
+ function resolveAtlasKeyOption(atlasKey) {
108
+ return resolveKeyOption(atlasKey, exports.DEFAULT_METRO_ATLAS_KEY);
109
+ }
110
+ /**
111
+ * Normalize `dashboardKey` option: default `"m"`, `false` → disabled.
112
+ */
113
+ function resolveDashboardKeyOption(dashboardKey) {
114
+ return resolveKeyOption(dashboardKey, exports.DEFAULT_METRO_DASHBOARD_KEY);
115
+ }
116
+ /**
117
+ * Resolve dashboard browse URL for Metro `m`.
118
+ * Precedence: explicit → `MOCKIFYER_DASHBOARD_URL` → `http://localhost:3002`,
119
+ * then append `MOCKIFYER_DASHBOARD_BASE` when set.
120
+ */
121
+ function resolveMetroDashboardUrl(explicit) {
122
+ const fromExplicit = explicit?.trim();
123
+ const fromEnv = typeof process !== "undefined"
124
+ ? process.env.MOCKIFYER_DASHBOARD_URL?.trim()
125
+ : undefined;
126
+ const base = (fromExplicit || fromEnv || exports.DEFAULT_METRO_DASHBOARD_URL).replace(/\/+$/, "");
127
+ const mountRaw = typeof process !== "undefined"
128
+ ? process.env.MOCKIFYER_DASHBOARD_BASE?.trim()
129
+ : undefined;
130
+ if (!mountRaw)
131
+ return base;
132
+ const mount = mountRaw.replace(/\/+$/, "");
133
+ if (!mount || mount === "/")
134
+ return base;
135
+ return `${base}${mount.startsWith("/") ? mount : `/${mount}`}`;
136
+ }
137
+ /**
138
+ * Open a URL with the OS default handler (browser / file).
139
+ */
140
+ function openMetroBrowseUrl(target) {
141
+ const platform = process.platform;
142
+ const child = platform === "darwin"
143
+ ? (0, child_process_1.spawn)("open", [target], { detached: true, stdio: "ignore" })
144
+ : platform === "win32"
145
+ ? (0, child_process_1.spawn)("cmd", ["/c", "start", "", target], {
146
+ detached: true,
147
+ stdio: "ignore",
148
+ windowsVerbatimArguments: true,
149
+ })
150
+ : (0, child_process_1.spawn)("xdg-open", [target], { detached: true, stdio: "ignore" });
151
+ child.once("error", (err) => {
152
+ console.error(`[Mockifyer] could not open: ${err.message}`);
153
+ console.log(`[Mockifyer] open manually: ${target}`);
154
+ });
155
+ child.unref();
156
+ }
157
+ /**
158
+ * Whether a keypress matches a bound key (no ctrl/meta).
159
+ */
160
+ function matchesAtlasKey(str, key, atlasKey) {
161
+ if (!atlasKey)
162
+ return false;
163
+ if (key?.ctrl || key?.meta)
164
+ return false;
165
+ if (key?.name === atlasKey)
166
+ return true;
167
+ if (typeof str === "string" && str.toLowerCase() === atlasKey)
168
+ return true;
169
+ return false;
170
+ }
171
+ /** Current session phase (idle / capturing / rendering). Exported for tests. */
172
+ function getMetroAtlasSessionPhase() {
173
+ return sessionPhase;
174
+ }
175
+ /** Active SSE stream subscriber count (tests / diagnostics). */
176
+ function getMetroAtlasStreamSubscriberCount() {
177
+ return streamSubscriberCount;
178
+ }
179
+ function formatSessionDuration(startedAt) {
180
+ const ms = Date.now() - startedAt;
181
+ if (ms < 1000)
182
+ return `${ms}ms`;
183
+ const sec = Math.round(ms / 1000);
184
+ if (sec < 60)
185
+ return `${sec}s`;
186
+ const min = Math.floor(sec / 60);
187
+ const rem = sec % 60;
188
+ return `${min}m ${rem}s`;
189
+ }
190
+ /**
191
+ * Start capture when idle. No-op if already capturing/rendering or Atlas key off.
192
+ * @returns true if a new session was started
193
+ */
194
+ function startMetroAtlasSession(reason = "key") {
195
+ if (!sessionCallbacks?.key || !sessionCallbacks.onSessionStart)
196
+ return false;
197
+ if (sessionPhase !== "idle")
198
+ return false;
199
+ const { key, onSessionStart } = sessionCallbacks;
200
+ sessionPhase = "capturing";
201
+ sessionStartedAt = Date.now();
202
+ try {
203
+ onSessionStart();
204
+ }
205
+ catch (err) {
206
+ sessionPhase = "idle";
207
+ sessionStartedAt = null;
208
+ const message = err instanceof Error ? err.message : String(err);
209
+ console.error(`[Mockifyer] Atlas session start failed: ${message}`);
210
+ return false;
211
+ }
212
+ if (reason === "stream") {
213
+ console.log(`[Mockifyer] Atlas capture started (stream connected) — press ${key} to stop & generate HTML.`);
214
+ }
215
+ else {
216
+ console.log(`[Mockifyer] Atlas capture started — press ${key} again to stop & generate HTML.`);
217
+ }
218
+ return true;
219
+ }
220
+ /**
221
+ * Stop capture and generate Atlas HTML when capturing.
222
+ * @returns true if stop/render was kicked off
223
+ */
224
+ function stopMetroAtlasSession() {
225
+ if (!sessionCallbacks?.onSessionStop)
226
+ return false;
227
+ if (sessionPhase !== "capturing")
228
+ return false;
229
+ const { onSessionStop } = sessionCallbacks;
230
+ const startedAt = sessionStartedAt ?? Date.now();
231
+ const duration = formatSessionDuration(startedAt);
232
+ sessionPhase = "rendering";
233
+ console.log(`[Mockifyer] Atlas capture stopped (${duration}) — generating HTML…`);
234
+ Promise.resolve()
235
+ .then(() => onSessionStop())
236
+ .catch((err) => {
237
+ const message = err instanceof Error ? err.message : String(err);
238
+ console.error(`[Mockifyer] Atlas render failed: ${message}`);
239
+ })
240
+ .finally(() => {
241
+ sessionPhase = "idle";
242
+ sessionStartedAt = null;
243
+ });
244
+ return true;
245
+ }
246
+ /** Open the dashboard URL when the dashboard key is enabled. */
247
+ function openMetroDashboard() {
248
+ if (!sessionCallbacks?.dashboardKey || !sessionCallbacks.dashboardUrl) {
249
+ return false;
250
+ }
251
+ const url = sessionCallbacks.dashboardUrl;
252
+ console.log(`[Mockifyer] Opening dashboard → ${url}`);
253
+ try {
254
+ sessionCallbacks.openUrl(url);
255
+ }
256
+ catch (err) {
257
+ const message = err instanceof Error ? err.message : String(err);
258
+ console.error(`[Mockifyer] Could not open dashboard: ${message}`);
259
+ return false;
260
+ }
261
+ return true;
262
+ }
263
+ /**
264
+ * First SSE client for `/mockifyer-network-events/stream` auto-starts capture.
265
+ */
266
+ function notifyMetroAtlasStreamClientConnected() {
267
+ streamSubscriberCount += 1;
268
+ if (streamSubscriberCount === 1) {
269
+ startMetroAtlasSession("stream");
270
+ }
271
+ }
272
+ /**
273
+ * SSE client disconnected — capture stays open until Metro `a` (or explicit stop).
274
+ */
275
+ function notifyMetroAtlasStreamClientDisconnected() {
276
+ streamSubscriberCount = Math.max(0, streamSubscriberCount - 1);
277
+ }
278
+ function clearPendingTimer() {
279
+ if (pendingTimer != null) {
280
+ clearTimeout(pendingTimer);
281
+ pendingTimer = null;
282
+ }
283
+ }
284
+ /**
285
+ * Detach a previously attached handler (idempotent). Exported for tests.
286
+ */
287
+ function detachMetroAtlasKeyHandler() {
288
+ clearPendingTimer();
289
+ if (activeHandler && activeStdin) {
290
+ activeStdin.removeListener("keypress", activeHandler);
291
+ }
292
+ if (weSetRawMode && activeStdin?.isTTY && typeof activeStdin.setRawMode === "function") {
293
+ try {
294
+ activeStdin.setRawMode(false);
295
+ }
296
+ catch {
297
+ // ignore
298
+ }
299
+ }
300
+ activeHandler = null;
301
+ activeStdin = null;
302
+ weSetRawMode = false;
303
+ attached = false;
304
+ sessionPhase = "idle";
305
+ sessionStartedAt = null;
306
+ sessionCallbacks = null;
307
+ streamSubscriberCount = 0;
308
+ }
309
+ function warnIfReserved(key, label) {
310
+ const reason = RESERVED_METRO_KEYS.get(key);
311
+ if (reason) {
312
+ mockifyer_core_1.logger.warn(`[Mockifyer] ${label} "${key}" is reserved for ${reason} — pick another letter`);
313
+ }
314
+ }
315
+ /**
316
+ * Listen for Metro terminal keys (Atlas capture + open dashboard).
317
+ * Safe to call once per process; subsequent calls are no-ops until detach.
318
+ */
319
+ function attachMetroAtlasKeyHandler(options) {
320
+ const atlasKey = resolveAtlasKeyOption(options.atlasKey);
321
+ const dashboardKey = resolveDashboardKeyOption(options.dashboardKey);
322
+ const dashboardUrl = dashboardKey != null
323
+ ? resolveMetroDashboardUrl(options.dashboardUrl)
324
+ : null;
325
+ if (atlasKey == null && dashboardKey == null) {
326
+ return {
327
+ key: null,
328
+ dashboardKey: null,
329
+ dashboardUrl: null,
330
+ detach: () => undefined,
331
+ };
332
+ }
333
+ if (atlasKey != null)
334
+ warnIfReserved(atlasKey, "atlasKey");
335
+ if (dashboardKey != null)
336
+ warnIfReserved(dashboardKey, "dashboardKey");
337
+ if (atlasKey != null &&
338
+ dashboardKey != null &&
339
+ atlasKey === dashboardKey) {
340
+ mockifyer_core_1.logger.warn(`[Mockifyer] atlasKey and dashboardKey are both "${atlasKey}" — dashboard key ignored`);
341
+ }
342
+ const effectiveDashboardKey = atlasKey != null && dashboardKey === atlasKey ? null : dashboardKey;
343
+ sessionCallbacks = {
344
+ key: atlasKey,
345
+ dashboardKey: effectiveDashboardKey,
346
+ dashboardUrl: effectiveDashboardKey != null ? dashboardUrl : null,
347
+ onSessionStart: options.onSessionStart,
348
+ onSessionStop: options.onSessionStop,
349
+ openUrl: options.openUrl ?? openMetroBrowseUrl,
350
+ };
351
+ if (attached) {
352
+ return {
353
+ key: atlasKey,
354
+ dashboardKey: effectiveDashboardKey,
355
+ dashboardUrl: sessionCallbacks.dashboardUrl,
356
+ detach: detachMetroAtlasKeyHandler,
357
+ };
358
+ }
359
+ const stdin = options.stdin ?? process.stdin;
360
+ const deferMs = options.deferMs ?? ATTACH_DEFER_MS;
361
+ const onKeypress = (str, keyObj) => {
362
+ if (keyObj?.ctrl && keyObj.name === "c") {
363
+ if (weSetRawMode) {
364
+ try {
365
+ if (typeof stdin.setRawMode === "function")
366
+ stdin.setRawMode(false);
367
+ }
368
+ catch {
369
+ // ignore
370
+ }
371
+ process.exit(0);
372
+ }
373
+ return;
374
+ }
375
+ if (effectiveDashboardKey &&
376
+ matchesAtlasKey(str, keyObj, effectiveDashboardKey)) {
377
+ openMetroDashboard();
378
+ return;
379
+ }
380
+ if (!atlasKey || !matchesAtlasKey(str, keyObj, atlasKey))
381
+ return;
382
+ if (sessionPhase === "rendering") {
383
+ console.log("[Mockifyer] Atlas render already in progress…");
384
+ return;
385
+ }
386
+ if (sessionPhase === "idle") {
387
+ startMetroAtlasSession("key");
388
+ return;
389
+ }
390
+ stopMetroAtlasSession();
391
+ };
392
+ const doAttach = () => {
393
+ if (attached)
394
+ return;
395
+ if (!stdin.isTTY) {
396
+ mockifyer_core_1.logger.info("[Mockifyer] Metro keys skipped (stdin is not a TTY — use mockifyer-atlas or Dev Menu)");
397
+ return;
398
+ }
399
+ readline.emitKeypressEvents(stdin);
400
+ if (typeof stdin.setRawMode === "function" && stdin.isRaw !== true) {
401
+ try {
402
+ stdin.setRawMode(true);
403
+ weSetRawMode = true;
404
+ }
405
+ catch (err) {
406
+ mockifyer_core_1.logger.warn("[Mockifyer] Could not enable raw stdin for Metro keys:", err);
407
+ return;
408
+ }
409
+ }
410
+ if (typeof stdin.resume === "function") {
411
+ stdin.resume();
412
+ }
413
+ activeHandler = onKeypress;
414
+ activeStdin = stdin;
415
+ stdin.on("keypress", onKeypress);
416
+ attached = true;
417
+ const parts = [];
418
+ if (atlasKey) {
419
+ parts.push(`Press ${atlasKey} to start/stop Atlas capture (stop generates HTML; stream auto-starts)`);
420
+ }
421
+ if (effectiveDashboardKey && dashboardUrl) {
422
+ parts.push(`Press ${effectiveDashboardKey} to open dashboard (${dashboardUrl})`);
423
+ }
424
+ if (parts.length > 0) {
425
+ console.log(`[Mockifyer] info ${parts.join(". ")}.`);
426
+ }
427
+ };
428
+ clearPendingTimer();
429
+ if (deferMs <= 0) {
430
+ doAttach();
431
+ }
432
+ else {
433
+ pendingTimer = setTimeout(() => {
434
+ pendingTimer = null;
435
+ doAttach();
436
+ }, deferMs);
437
+ // Don't keep the process alive solely for the defer timer.
438
+ if (typeof pendingTimer === "object" && pendingTimer && "unref" in pendingTimer) {
439
+ pendingTimer.unref();
440
+ }
441
+ }
442
+ return {
443
+ key: atlasKey,
444
+ dashboardKey: effectiveDashboardKey,
445
+ dashboardUrl: sessionCallbacks.dashboardUrl,
446
+ detach: detachMetroAtlasKeyHandler,
447
+ };
448
+ }
@@ -108,6 +108,9 @@ export interface ConfigureMetroOptions {
108
108
  * syncMiddleware: {
109
109
  * projectRoot: __dirname,
110
110
  * mockDataPath: './mock-data',
111
+ * // atlasKey: 't' (default) — Metro terminal: start/stop Atlas capture (stop → HTML). `a` is Android.
112
+ * // dashboardKey: 'm' (default) — open dashboard in browser
113
+ * // dashboardUrl: 'http://localhost:3002' — or MOCKIFYER_DASHBOARD_URL
111
114
  * },
112
115
  * });
113
116
  * ```
@@ -70,7 +70,12 @@ const NODE_BUILTINS = [
70
70
  * Optional React Native peer dependencies — stubbed when not installed so
71
71
  * `tryGetClientIdFromLaunchArguments` and similar helpers no-op instead of crashing Metro.
72
72
  */
73
- const OPTIONAL_RN_PEER_MODULES = ['react-native-launch-arguments'];
73
+ const OPTIONAL_RN_PEER_MODULES = [
74
+ 'react-native-launch-arguments',
75
+ '@react-native-async-storage/async-storage',
76
+ '@sgedda/mockifyer-axios',
77
+ '@sgedda/mockifyer-fetch',
78
+ ];
74
79
  function isMockifyerStubbedModule(moduleName) {
75
80
  return (NODE_BUILTINS.includes(moduleName) ||
76
81
  OPTIONAL_RN_PEER_MODULES.includes(moduleName));
@@ -122,6 +127,9 @@ function resolveMockifyerCoreReactNativeEntry(moduleName, platform) {
122
127
  * syncMiddleware: {
123
128
  * projectRoot: __dirname,
124
129
  * mockDataPath: './mock-data',
130
+ * // atlasKey: 't' (default) — Metro terminal: start/stop Atlas capture (stop → HTML). `a` is Android.
131
+ * // dashboardKey: 'm' (default) — open dashboard in browser
132
+ * // dashboardUrl: 'http://localhost:3002' — or MOCKIFYER_DASHBOARD_URL
125
133
  * },
126
134
  * });
127
135
  * ```
@@ -160,13 +168,30 @@ function configureMetroForMockifyer(config, options) {
160
168
  const existingResolveRequest = existingResolver.resolveRequest;
161
169
  // Create new resolveRequest function that handles Node.js built-ins
162
170
  const newResolveRequest = (context, moduleName, platform) => {
163
- // Handle Node built-ins and optional RN peers - return empty module stub
164
- if (isMockifyerStubbedModule(moduleName)) {
171
+ // Always stub Node built-ins
172
+ if (NODE_BUILTINS.includes(moduleName)) {
165
173
  return {
166
174
  filePath: emptyModulePath,
167
175
  type: 'sourceFile',
168
176
  };
169
177
  }
178
+ // Stub optional RN peers only when not installed
179
+ if (OPTIONAL_RN_PEER_MODULES.includes(moduleName)) {
180
+ // Try to resolve the module - if it exists, let Metro handle it normally
181
+ try {
182
+ const resolved = context.resolveRequest(context, moduleName, platform);
183
+ if (resolved) {
184
+ return resolved;
185
+ }
186
+ }
187
+ catch {
188
+ // Module not installed - stub it
189
+ return {
190
+ filePath: emptyModulePath,
191
+ type: 'sourceFile',
192
+ };
193
+ }
194
+ }
170
195
  const mockifyerCoreRn = resolveMockifyerCoreReactNativeEntry(moduleName, platform);
171
196
  if (mockifyerCoreRn) {
172
197
  return mockifyerCoreRn;
@@ -189,6 +214,9 @@ function configureMetroForMockifyer(config, options) {
189
214
  projectRoot: options.syncMiddleware.projectRoot || process.cwd(),
190
215
  mockDataPath: options.syncMiddleware.mockDataPath || 'mock-data',
191
216
  testGeneration: options.syncMiddleware.testGeneration,
217
+ atlasKey: options.syncMiddleware.atlasKey,
218
+ dashboardKey: options.syncMiddleware.dashboardKey,
219
+ dashboardUrl: options.syncMiddleware.dashboardUrl,
192
220
  });
193
221
  // Add middleware to server config
194
222
  // Expo Metro uses enhanceMiddleware, but also supports middleware array
@@ -19,17 +19,36 @@
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
24
  *
23
25
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
24
26
  * Legacy polling-based sync is still available for backward compatibility.
25
27
  *
26
28
  * Usage: Add to metro.config.js middleware array
27
29
  */
30
+ import { type AtlasKeyOption } from "./metro-atlas-key-handlers";
28
31
  export interface MetroSyncMiddlewareOptions {
29
32
  /** Project root directory (default: process.cwd()) */
30
33
  projectRoot?: string;
31
34
  /** Path to mock data directory relative to project root (default: 'mock-data') */
32
35
  mockDataPath?: string;
36
+ /**
37
+ * Metro terminal key that starts/stops Atlas capture (default `"t"`).
38
+ * Start clears the hop buffer; stop generates HTML (same as `POST /mockifyer-network-events/render`).
39
+ * Pass `false` to disable. `a` is reserved by Metro for Android.
40
+ */
41
+ atlasKey?: AtlasKeyOption;
42
+ /**
43
+ * Metro terminal key that opens the dashboard in the browser (default `"m"`).
44
+ * Pass `false` to disable.
45
+ */
46
+ dashboardKey?: AtlasKeyOption;
47
+ /**
48
+ * Dashboard URL for Metro `m` (default: `MOCKIFYER_DASHBOARD_URL` or `http://localhost:3002`).
49
+ * `MOCKIFYER_DASHBOARD_BASE` is appended when set.
50
+ */
51
+ dashboardUrl?: string;
33
52
  /** Test generation configuration - tests are generated when mocks are saved to project folder */
34
53
  testGeneration?: {
35
54
  /** Enable automatic test generation when mocks are saved */
@@ -20,6 +20,8 @@
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
25
  *
24
26
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
25
27
  * Legacy polling-based sync is still available for backward compatibility.
@@ -68,6 +70,7 @@ const fs = __importStar(require("fs"));
68
70
  const path = __importStar(require("path"));
69
71
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
70
72
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
73
+ const metro_atlas_key_handlers_1 = require("./metro-atlas-key-handlers");
71
74
  const DEFAULT_SCENARIO = "default";
72
75
  /** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
73
76
  const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
@@ -958,6 +961,25 @@ function createMockSyncMiddleware(options) {
958
961
  const testConfig = getTestGenerationConfig(options);
959
962
  // Log the resolved paths for debugging
960
963
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
964
+ (0, metro_atlas_key_handlers_1.attachMetroAtlasKeyHandler)({
965
+ atlasKey: options?.atlasKey,
966
+ dashboardKey: options?.dashboardKey,
967
+ 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"}`);
980
+ }
981
+ },
982
+ });
961
983
  return function mockSyncMiddleware(req, res, next) {
962
984
  const url = normalizeMiddlewarePathname(req.url || "");
963
985
  // Handle POST endpoint for clearing mocks
@@ -1039,6 +1061,9 @@ function createMockSyncMiddleware(options) {
1039
1061
  const qIndex = fullUrl.indexOf("?");
1040
1062
  const params = new URLSearchParams(qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "");
1041
1063
  const backlog = params.get("backlog") !== "0";
1064
+ // First SSE client (e.g. mockifyer-atlas) auto-starts Metro Atlas capture.
1065
+ // Must run before reading the buffer — start clears hops for a clean session.
1066
+ (0, metro_atlas_key_handlers_1.notifyMetroAtlasStreamClientConnected)();
1042
1067
  const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1043
1068
  res.writeHead(200, {
1044
1069
  "Content-Type": "text/event-stream",
@@ -1076,6 +1101,7 @@ function createMockSyncMiddleware(options) {
1076
1101
  const onClose = () => {
1077
1102
  clearInterval(keepAlive);
1078
1103
  unsubscribe();
1104
+ (0, metro_atlas_key_handlers_1.notifyMetroAtlasStreamClientDisconnected)();
1079
1105
  };
1080
1106
  req.on("close", onClose);
1081
1107
  req.on("aborted", onClose);
@@ -1250,17 +1276,34 @@ function createMockSyncMiddleware(options) {
1250
1276
  const rels = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1251
1277
  const rel = side === "req" ? rels.req : rels.res;
1252
1278
  const abs = path.join(mockDataPath, "atlas-html", rel);
1253
- if (!fs.existsSync(abs)) {
1254
- fs.mkdirSync(path.dirname(abs), { recursive: true });
1255
- const preview = side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
1256
- const text = preview != null && String(preview).trim() !== ""
1257
- ? String(preview)
1258
- : JSON.stringify({
1259
- note: "No body captured for this hop yet",
1260
- id: event.id,
1261
- side,
1262
- }, null, 2);
1263
- fs.writeFileSync(abs, text.endsWith("\n") ? text : `${text}\n`, "utf8");
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
+ }));
1293
+ return;
1294
+ }
1295
+ }
1296
+ else if (!fs.existsSync(abs)) {
1297
+ res.statusCode = 404;
1298
+ res.setHeader("Content-Type", "application/json");
1299
+ 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.",
1302
+ hopId: event.id,
1303
+ side,
1304
+ relativePath: rel,
1305
+ }));
1306
+ return;
1264
1307
  }
1265
1308
  res.statusCode = 302;
1266
1309
  res.setHeader("Location", `/atlas-html/${rel.split(path.sep).join("/")}`);