@sgedda/mockifyer-fetch 1.8.71 → 1.8.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,8 @@
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 `a` — start/stop Atlas capture (stop generates HTML; stream auto-starts; `atlasKey: false` to disable)
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.
@@ -51,6 +53,7 @@ import {
51
53
  writeAtlasDocHtml,
52
54
  writeNetworkBodySpillMap,
53
55
  flushNetworkBodySpillsToDir,
56
+ getNetworkBodySpillSnapshot,
54
57
  prettyPrintJsonText,
55
58
  setAtlasDocMap,
56
59
  type AtlasDocMap,
@@ -61,12 +64,34 @@ import {
61
64
  createEmptyAtlasDocMap,
62
65
  buildAtlasHarJson,
63
66
  } from "@sgedda/mockifyer-core";
67
+ import {
68
+ attachMetroAtlasKeyHandler,
69
+ notifyMetroAtlasStreamClientConnected,
70
+ notifyMetroAtlasStreamClientDisconnected,
71
+ type AtlasKeyOption,
72
+ } from "./metro-atlas-key-handlers";
64
73
 
65
74
  export interface MetroSyncMiddlewareOptions {
66
75
  /** Project root directory (default: process.cwd()) */
67
76
  projectRoot?: string;
68
77
  /** Path to mock data directory relative to project root (default: 'mock-data') */
69
78
  mockDataPath?: string;
79
+ /**
80
+ * Metro terminal key that starts/stops Atlas capture (default `"a"`).
81
+ * Start clears the hop buffer; stop generates HTML (same as `POST /mockifyer-network-events/render`).
82
+ * Pass `false` to disable.
83
+ */
84
+ atlasKey?: AtlasKeyOption;
85
+ /**
86
+ * Metro terminal key that opens the dashboard in the browser (default `"m"`).
87
+ * Pass `false` to disable.
88
+ */
89
+ dashboardKey?: AtlasKeyOption;
90
+ /**
91
+ * Dashboard URL for Metro `m` (default: `MOCKIFYER_DASHBOARD_URL` or `http://localhost:3002`).
92
+ * `MOCKIFYER_DASHBOARD_BASE` is appended when set.
93
+ */
94
+ dashboardUrl?: string;
70
95
  /** Test generation configuration - tests are generated when mocks are saved to project folder */
71
96
  testGeneration?: {
72
97
  /** Enable automatic test generation when mocks are saved */
@@ -1249,6 +1274,33 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1249
1274
  `[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`,
1250
1275
  );
1251
1276
 
1277
+ attachMetroAtlasKeyHandler({
1278
+ atlasKey: options?.atlasKey,
1279
+ dashboardKey: options?.dashboardKey,
1280
+ dashboardUrl: options?.dashboardUrl,
1281
+ onSessionStart: () => {
1282
+ getMetroNetworkEventBuffer().clear();
1283
+ },
1284
+ onSessionStop: () => {
1285
+ const buffer = getMetroNetworkEventBuffer();
1286
+ const events = [...buffer.list()].reverse();
1287
+ const result = renderNetworkEventsAtlasHtml(
1288
+ projectRoot,
1289
+ mockDataPath,
1290
+ events,
1291
+ );
1292
+ if (result.success) {
1293
+ console.log(
1294
+ `[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`,
1295
+ );
1296
+ } else {
1297
+ console.error(
1298
+ `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
1299
+ );
1300
+ }
1301
+ },
1302
+ });
1303
+
1252
1304
  return function mockSyncMiddleware(req: any, res: any, next: any) {
1253
1305
  const url = normalizeMiddlewarePathname(req.url || "");
1254
1306
 
@@ -1347,6 +1399,9 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1347
1399
  qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "",
1348
1400
  );
1349
1401
  const backlog = params.get("backlog") !== "0";
1402
+ // First SSE client (e.g. mockifyer-atlas) auto-starts Metro Atlas capture.
1403
+ // Must run before reading the buffer — start clears hops for a clean session.
1404
+ notifyMetroAtlasStreamClientConnected();
1350
1405
  const buffer = getMetroNetworkEventBuffer();
1351
1406
  res.writeHead(200, {
1352
1407
  "Content-Type": "text/event-stream",
@@ -1384,6 +1439,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1384
1439
  const onClose = () => {
1385
1440
  clearInterval(keepAlive);
1386
1441
  unsubscribe();
1442
+ notifyMetroAtlasStreamClientDisconnected();
1387
1443
  };
1388
1444
  req.on("close", onClose);
1389
1445
  req.on("aborted", onClose);
@@ -1596,27 +1652,43 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1596
1652
  const rels = resolveNetworkEventBodyRelPaths(event);
1597
1653
  const rel = side === "req" ? rels.req : rels.res;
1598
1654
  const abs = path.join(mockDataPath, "atlas-html", rel);
1599
- if (!fs.existsSync(abs)) {
1600
- fs.mkdirSync(path.dirname(abs), { recursive: true });
1601
- const preview =
1602
- side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
1603
- const text =
1604
- preview != null && String(preview).trim() !== ""
1605
- ? String(preview)
1606
- : JSON.stringify(
1607
- {
1608
- note: "No body captured for this hop yet",
1609
- id: event.id,
1610
- side,
1611
- },
1612
- null,
1613
- 2,
1614
- );
1615
- fs.writeFileSync(
1616
- abs,
1617
- text.endsWith("\n") ? text : `${text}\n`,
1618
- "utf8",
1655
+ const outDir = path.join(mockDataPath, "atlas-html");
1656
+ // Prefer real spill buffer / disk — never materialize the truncated Metro
1657
+ // hop preview (often ~512 bytes) as the "full body" JSON page.
1658
+ flushNetworkBodySpillsToDir(outDir);
1659
+ const fromBuffer = getNetworkBodySpillSnapshot()[rel];
1660
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1661
+ const saved = saveAtlasBodySpill(
1662
+ projectRoot,
1663
+ mockDataPath,
1664
+ rel,
1665
+ fromBuffer,
1619
1666
  );
1667
+ if (!saved.success) {
1668
+ res.statusCode = 500;
1669
+ res.setHeader("Content-Type", "application/json");
1670
+ res.end(
1671
+ JSON.stringify({
1672
+ success: false,
1673
+ error: saved.error || "Failed to write full body spill",
1674
+ }),
1675
+ );
1676
+ return;
1677
+ }
1678
+ } else if (!fs.existsSync(abs)) {
1679
+ res.statusCode = 404;
1680
+ res.setHeader("Content-Type", "application/json");
1681
+ res.end(
1682
+ JSON.stringify({
1683
+ success: false,
1684
+ error:
1685
+ "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.",
1686
+ hopId: event.id,
1687
+ side,
1688
+ relativePath: rel,
1689
+ }),
1690
+ );
1691
+ return;
1620
1692
  }
1621
1693
  res.statusCode = 302;
1622
1694
  res.setHeader(
@@ -12,11 +12,16 @@ import {
12
12
  logger,
13
13
  MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
14
14
  tryGetClientIdFromLaunchArguments,
15
+ tryGetScenarioFromLaunchArguments,
15
16
  resolveMockifyerRuntimeMode,
16
17
  logMockifyerNotActivated,
17
18
  resolveRecordResponses,
18
19
  resolveStrictScenarioResolution,
20
+ resolveRuntimeEnabledStorage,
21
+ loadPersistedRuntimeEnabled,
22
+ shouldActivateMockifyerForReactNative,
19
23
  type MockifyerRuntimeMode,
24
+ type MockifyerRuntimeEnabledStorage,
20
25
  } from '@sgedda/mockifyer-core';
21
26
 
22
27
  // React Native package-root resolution points at this entry. Keep the root
@@ -31,6 +36,9 @@ export interface MockifyerInstance extends HTTPClient {
31
36
  clearAllMocks: () => Promise<void>;
32
37
  setClientId: (lane: string) => void;
33
38
  getClientId: () => string | undefined;
39
+ enableMockifyer: () => void;
40
+ disableMockifyer: () => void;
41
+ isMockifyerEnabled: () => boolean;
34
42
  }
35
43
 
36
44
  /**
@@ -69,9 +77,27 @@ export interface ReactNativeMockifyerConfig {
69
77
  bundledDataPath?: string;
70
78
  /** Enable recording mode (development only) */
71
79
  recordMode?: boolean;
80
+ /**
81
+ * When true, Mockifyer starts disabled (all requests bypass).
82
+ * Use `instance.enableMockifyer()` to turn it on via GUI.
83
+ *
84
+ * **Prefer `runtimeMode: 'manual'`** for clearer intent.
85
+ *
86
+ * Default: false (starts enabled).
87
+ */
88
+ startDisabled?: boolean;
89
+ /**
90
+ * Persist enable/disable across app restarts (AsyncStorage when `true`).
91
+ * With `runtimeMode: 'manual'`, first launch is off; after the user enables,
92
+ * the next launch stays on.
93
+ */
94
+ persistRuntimeEnabled?: boolean | MockifyerRuntimeEnabledStorage;
72
95
  /**
73
96
  * When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
74
97
  * Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
98
+ * When a launch `scenario` is present, Mockifyer also **starts enabled** (even with `runtimeMode: 'manual'`).
99
+ * Set to `false` to ignore launch scenario args entirely.
100
+ * Default: auto-detect when a non-empty launch `scenario` is present.
75
101
  */
76
102
  useLaunchArgumentsScenario?: boolean;
77
103
  /**
@@ -111,39 +137,39 @@ export interface ReactNativeMockifyerConfig {
111
137
  launchArgumentClientIdKey?: string;
112
138
  /**
113
139
  * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
114
- * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
140
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` | `manual`.
141
+ *
142
+ * Use **`manual`** to patch but start disabled (enable via GUI toggle).
143
+ * Aliases: `e2e`, `maestro` → `launch_client`; `gui`, `toggle` → `manual`.
115
144
  */
116
145
  runtimeMode?: MockifyerRuntimeMode;
117
146
  }
118
147
 
119
148
  /**
120
149
  * Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
150
+ * @returns `true` when a native launch-argument `scenario` was applied (forces runtime toggle on).
121
151
  */
122
- function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): void {
123
- let applied = false;
124
- if (options.useLaunchArgumentsScenario) {
125
- try {
126
- // Optional dependency — install `react-native-launch-arguments` in the app when using this flag
127
- // eslint-disable-next-line @typescript-eslint/no-require-imports
128
- const mod = require(/* webpackIgnore: true */ 'react-native-launch-arguments') as { LaunchArguments?: { value?: () => Record<string, unknown> } };
129
- const LaunchArguments = mod.LaunchArguments;
130
- const raw =
131
- LaunchArguments && typeof LaunchArguments.value === 'function' ? LaunchArguments.value() : undefined;
132
- const scenario = raw?.scenario;
133
- if (scenario !== undefined && scenario !== null && String(scenario).trim() !== '') {
134
- setScenarioLaunchOverride(String(scenario).trim());
135
- applied = true;
136
- }
137
- } catch {
138
- // Package not installed or native module unavailable
152
+ function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): boolean {
153
+ let appliedFromLaunchArgs = false;
154
+
155
+ // Auto-detect launch `scenario` when present (E2E). Opt out with useLaunchArgumentsScenario: false.
156
+ if (options.useLaunchArgumentsScenario !== false) {
157
+ const scenarioFromLaunch = tryGetScenarioFromLaunchArguments();
158
+ if (scenarioFromLaunch) {
159
+ setScenarioLaunchOverride(scenarioFromLaunch, { fromLaunchArguments: true });
160
+ appliedFromLaunchArgs = true;
139
161
  }
140
162
  }
141
- if (!applied && options.defaultScenario !== undefined && options.defaultScenario !== null) {
163
+
164
+ if (!appliedFromLaunchArgs && options.defaultScenario !== undefined && options.defaultScenario !== null) {
142
165
  const t = String(options.defaultScenario).trim();
143
166
  if (t !== '') {
167
+ // App config default — not a native launch arg; do not force runtime toggle on.
144
168
  setScenarioLaunchOverride(t);
145
169
  }
146
170
  }
171
+
172
+ return appliedFromLaunchArgs;
147
173
  }
148
174
 
149
175
  // Lazy load bundled data (only used in production builds)
@@ -214,6 +240,8 @@ export async function setupMockifyerForReactNative(
214
240
  mockDataPath = 'mock-data',
215
241
  bundledDataPath = './assets/mock-data',
216
242
  recordMode = false,
243
+ startDisabled = false,
244
+ persistRuntimeEnabled,
217
245
  config: userConfig = {},
218
246
  proxyBaseUrl,
219
247
  proxyScenario,
@@ -240,9 +268,31 @@ export async function setupMockifyerForReactNative(
240
268
  configMode: runtimeModeOption ?? userConfig.runtimeMode,
241
269
  });
242
270
 
271
+ const persistOption = persistRuntimeEnabled ?? userConfig.persistRuntimeEnabled;
272
+ const runtimeEnabledStorage = resolveRuntimeEnabledStorage(persistOption);
273
+ let initialRuntimeEnabled: boolean | undefined = userConfig.initialRuntimeEnabled;
274
+ if (runtimeEnabledStorage && typeof initialRuntimeEnabled !== 'boolean') {
275
+ const saved = await loadPersistedRuntimeEnabled(runtimeEnabledStorage);
276
+ if (typeof saved === 'boolean') {
277
+ initialRuntimeEnabled = saved;
278
+ }
279
+ }
280
+
281
+ // Apply scenario launch override early so we know if E2E forced a scenario.
282
+ const launchScenarioApplied = applyReactNativeScenarioOptions(options);
283
+ if (launchScenarioApplied) {
284
+ // Launch `scenario` arg → start enabled (wins over persisted off for this session).
285
+ initialRuntimeEnabled = true;
286
+ logger.info(
287
+ '[Mockifyer] Launch argument scenario present — starting with Mockifyer ENABLED'
288
+ );
289
+ }
290
+
243
291
  const mergedConfig: typeof userConfig = {
244
292
  ...userConfig,
245
293
  runtimeMode: resolvedRuntimeMode,
294
+ ...(persistOption !== undefined ? { persistRuntimeEnabled: persistOption } : {}),
295
+ ...(typeof initialRuntimeEnabled === 'boolean' ? { initialRuntimeEnabled } : {}),
246
296
  ...(shouldApplyLaunchClientId
247
297
  ? {
248
298
  useLaunchArgumentsClientId: true as const,
@@ -259,9 +309,13 @@ export async function setupMockifyerForReactNative(
259
309
  return 'React Native dev · hybrid (device + Metro)';
260
310
  };
261
311
 
262
- const isEnabled =
263
- resolvedRuntimeMode === 'on' ||
264
- (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
312
+ // Patch fetch for on / manual; launch_client only when lane id is present.
313
+ // Launch `scenario` forces runtime toggle on after activation — it does not replace client id.
314
+ const isEnabled = shouldActivateMockifyerForReactNative({
315
+ runtimeMode: resolvedRuntimeMode,
316
+ hasLaunchClientId: Boolean(clientIdFromLaunchArgs),
317
+ hasLaunchScenario: launchScenarioApplied,
318
+ });
265
319
  if (!isEnabled) {
266
320
  logMockifyerNotActivated(resolvedRuntimeMode, {
267
321
  launchClientIdKey,
@@ -270,8 +324,6 @@ export async function setupMockifyerForReactNative(
270
324
  return { status: 'not_activated', instance: null } as const;
271
325
  }
272
326
 
273
- applyReactNativeScenarioOptions(options);
274
-
275
327
  if (isDev === true) {
276
328
  const strictProxyEnabled = proxyBaseUrl
277
329
  ? skipDashboardRedisHealthCheck === true ||
@@ -330,6 +382,7 @@ export async function setupMockifyerForReactNative(
330
382
  : databaseProviderConfig,
331
383
  recordMode,
332
384
  useGlobalFetch: true,
385
+ startDisabled,
333
386
  proxy:
334
387
  strictProxyEnabled && proxyBaseUrl
335
388
  ? {
@@ -400,6 +453,7 @@ export async function setupMockifyerForReactNative(
400
453
  },
401
454
  recordMode: false, // Can't record in production builds
402
455
  useGlobalFetch: true,
456
+ startDisabled,
403
457
  proxy: proxyBaseUrl
404
458
  ? {
405
459
  baseUrl: proxyBaseUrl,