@sgedda/mockifyer-fetch 1.8.46 → 1.8.71

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.
@@ -133,12 +133,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
133
133
  response.headers.forEach((value, key) => {
134
134
  responseHeaders[key] = value;
135
135
  });
136
+ const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
136
137
  return {
137
138
  data,
138
139
  status: response.status,
139
140
  statusText: response.statusText,
140
141
  headers: responseHeaders,
141
142
  config,
143
+ ...(mockifyerTrace ? { mockifyerTrace } : {}),
142
144
  };
143
145
  }
144
146
  getDefaultHeaders() {
package/dist/index.js CHANGED
@@ -38,34 +38,49 @@ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
38
38
  const core_proxy_1 = require("./core-proxy");
39
39
  const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
40
40
  const fetch_client_1 = require("./clients/fetch-client");
41
+ const fetch_response_body_1 = require("./utils/fetch-response-body");
41
42
  class MockifyerClass {
42
- /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
43
+ /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
44
+ getRuntimeSessionId() {
45
+ return (0, mockifyer_core_1.resolveActiveMockifyerSessionId)(() => {
46
+ const now = Date.now();
47
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
48
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
49
+ this.sessionStartTime = now;
50
+ (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({ sessionId: this.currentSessionId });
51
+ }
52
+ return this.currentSessionId;
53
+ });
54
+ }
55
+ /** Best-effort dashboard network log. */
43
56
  logNetworkEvent(partial, correlation) {
44
- // Dashboard proxy hops are recorded in performDashboardProxyRequest (shared axios/fetch path).
45
- if (this.config.proxy?.baseUrl)
46
- return;
47
57
  const scenario = this.config.proxy?.scenario?.trim() ||
48
58
  (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
49
59
  const { requestBody, responseBody, ...eventPartial } = partial;
50
60
  const businessResponseBody = (0, mockifyer_core_1.getInlineTraceEnvelopeBusinessBody)(responseBody);
51
- (0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
52
- method: eventPartial.method,
53
- url: eventPartial.url,
54
- status: eventPartial.status,
55
- source: eventPartial.source,
56
- transport: eventPartial.transport ?? 'fetch',
57
- requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
58
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
59
- durationMs: eventPartial.durationMs,
60
- clientId: this.config.clientId ?? eventPartial.clientId ?? null,
61
- errorMessage: eventPartial.errorMessage,
62
- requestBody,
63
- responseBody,
64
- });
61
+ if (!this.config.proxy?.baseUrl) {
62
+ (0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
63
+ method: eventPartial.method,
64
+ url: eventPartial.url,
65
+ status: eventPartial.status,
66
+ source: eventPartial.source,
67
+ transport: eventPartial.transport ?? 'fetch',
68
+ requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
69
+ parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
70
+ durationMs: eventPartial.durationMs,
71
+ clientId: this.config.clientId ?? eventPartial.clientId ?? null,
72
+ errorMessage: eventPartial.errorMessage,
73
+ requestBody,
74
+ responseBody,
75
+ });
76
+ }
65
77
  (0, mockifyer_core_1.emitMockifyerNetworkEvent)({
66
78
  config: this.config,
67
79
  scenario,
68
80
  clientId: this.config.clientId,
81
+ sessionId: this.getRuntimeSessionId(),
82
+ requestBody,
83
+ responseBody: businessResponseBody,
69
84
  event: {
70
85
  ...eventPartial,
71
86
  transport: eventPartial.transport ?? 'fetch',
@@ -84,6 +99,14 @@ class MockifyerClass {
84
99
  config.__mockifyer_parentRequestId =
85
100
  correlation.parentRequestId;
86
101
  }
102
+ bindStoredHopId(config, mockData, fallback) {
103
+ const adopted = (0, mockifyer_core_1.adoptStoredOutboundRequestId)(config, mockData?.requestId);
104
+ if (adopted) {
105
+ this.stashRequestCorrelation(config, adopted);
106
+ return adopted;
107
+ }
108
+ return fallback;
109
+ }
87
110
  readRequestCorrelation(config) {
88
111
  const requestId = config.__mockifyer_requestId;
89
112
  if (!requestId)
@@ -106,7 +129,7 @@ class MockifyerClass {
106
129
  * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
107
130
  * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
108
131
  */
109
- prepareStoredResponseBody(mockData) {
132
+ prepareStoredResponseBody(mockData, filename, scenarioPath) {
110
133
  const joinPath = path && typeof path.join === 'function' ? path.join.bind(path) : null;
111
134
  return (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate, {
112
135
  loadPoolResponse: (0, mockifyer_core_1.createServeTimePoolResponseLoader)({
@@ -115,6 +138,8 @@ class MockifyerClass {
115
138
  joinPath,
116
139
  cache: this.poolResponseCache,
117
140
  }),
141
+ filename,
142
+ scenarioPath,
118
143
  });
119
144
  }
120
145
  /**
@@ -256,6 +281,15 @@ class MockifyerClass {
256
281
  }
257
282
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
258
283
  this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({ config: this.config });
284
+ (0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
285
+ (0, mockifyer_core_1.configureAtlas)(this.config, {
286
+ scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
287
+ clientId: this.config.clientId ?? null,
288
+ });
289
+ (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
290
+ clientId: this.config.clientId,
291
+ scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
292
+ });
259
293
  if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
260
294
  const raw = typeof process !== 'undefined'
261
295
  ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
@@ -394,6 +428,7 @@ class MockifyerClass {
394
428
  }
395
429
  const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath, this.config.clientId);
396
430
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
431
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
397
432
  if (!fs.existsSync(scenarioPath)) {
398
433
  mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
399
434
  return undefined;
@@ -413,7 +448,11 @@ class MockifyerClass {
413
448
  }
414
449
  const mockKey = this.generateRequestKey(mockData.request);
415
450
  if (mockKey === requestKey) {
416
- if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, { includePassthroughMocks })) {
451
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
452
+ includePassthroughMocks,
453
+ filename: file,
454
+ scenarioPath,
455
+ })) {
417
456
  exactMatch = { mockData, filename: file, filePath };
418
457
  break;
419
458
  }
@@ -482,7 +521,11 @@ class MockifyerClass {
482
521
  continue; // Required parameter differs, skip this mock
483
522
  }
484
523
  }
485
- if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
524
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
525
+ includePassthroughMocks,
526
+ filename: file,
527
+ scenarioPath,
528
+ })) {
486
529
  similarMatch = { mockData, filename: file, filePath };
487
530
  }
488
531
  }
@@ -536,7 +579,7 @@ class MockifyerClass {
536
579
  config.__mockifyer_bypass = true;
537
580
  return config;
538
581
  }
539
- const correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
582
+ let correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
540
583
  this.stashRequestCorrelation(config, correlation);
541
584
  // Normalize empty params: treat {} the same as undefined for consistent matching
542
585
  const rawParams = config.params || {};
@@ -573,10 +616,17 @@ class MockifyerClass {
573
616
  // Return cached mock if found
574
617
  if (cachedMock) {
575
618
  const { mockData, filename, filePath } = cachedMock;
619
+ correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
576
620
  if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
577
621
  mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
578
622
  (filePath ? ` (${filePath})` : ''));
579
- const mockResponseBody = this.prepareStoredResponseBody(mockData);
623
+ const hitScenarioPath = path
624
+ ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
625
+ : undefined;
626
+ if (hitScenarioPath) {
627
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
628
+ }
629
+ const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
580
630
  this.logNetworkEvent({
581
631
  method: (request.method || 'GET').toUpperCase(),
582
632
  url: request.url,
@@ -717,6 +767,34 @@ class MockifyerClass {
717
767
  const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
718
768
  const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
719
769
  if (isMocked || isLimitReached) {
770
+ // Local mock hits are logged in the request interceptor; proxy mock hits must
771
+ // be recorded here before early return (otherwise flight recorder stays empty).
772
+ const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
773
+ if (shouldLogMockOrLimit) {
774
+ const reqUrl = response.config?.url || url;
775
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
776
+ const startTime = response.config.__mockifyer_startTime;
777
+ const durationMs = startTime ? Date.now() - startTime : undefined;
778
+ this.logNetworkEvent({
779
+ method: reqMethod,
780
+ url: reqUrl,
781
+ source: isLimitReached ? 'error' : 'mock-hit',
782
+ status: response.status,
783
+ durationMs,
784
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
785
+ requestBody: response.config?.data,
786
+ responseBody: response.data,
787
+ ...(isLimitReached
788
+ ? {
789
+ errorMessage: typeof response.data === 'object' &&
790
+ response.data !== null &&
791
+ 'message' in response.data
792
+ ? String(response.data.message)
793
+ : 'Request limit reached',
794
+ }
795
+ : {}),
796
+ }, this.readRequestCorrelation(response.config));
797
+ }
720
798
  return response;
721
799
  }
722
800
  if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
@@ -741,13 +819,19 @@ class MockifyerClass {
741
819
  response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
742
820
  const capturedResponse = {
743
821
  status: response.status,
744
- data: response.data,
822
+ data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
745
823
  headers: response.headers || {},
746
824
  };
747
825
  if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
748
- await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
826
+ await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
749
827
  }
750
- const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate);
828
+ const liveScenarioPath = path
829
+ ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
830
+ : undefined;
831
+ if (liveScenarioPath) {
832
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
833
+ }
834
+ const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate, { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
751
835
  response.data = clientResponse.data;
752
836
  response.status = clientResponse.status;
753
837
  delete response.config.__mockifyer_matchedMock;
@@ -962,6 +1046,7 @@ class MockifyerClass {
962
1046
  const startTime = response.config.__mockifyer_startTime;
963
1047
  const duration = startTime ? Date.now() - startTime : undefined;
964
1048
  const correlation = this.readRequestCorrelation(response.config);
1049
+ const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
965
1050
  const mockData = {
966
1051
  request: {
967
1052
  method: response.config?.method?.toUpperCase() || 'GET',
@@ -972,7 +1057,7 @@ class MockifyerClass {
972
1057
  },
973
1058
  response: {
974
1059
  status: response.status,
975
- data: response.data,
1060
+ data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
976
1061
  headers: response.headers || {},
977
1062
  },
978
1063
  timestamp: new Date().toISOString(),
@@ -980,8 +1065,8 @@ class MockifyerClass {
980
1065
  sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
981
1066
  ? existingMock.mockData.sessionId
982
1067
  : this.currentSessionId,
983
- requestId: correlation?.requestId,
984
- parentRequestId: correlation?.parentRequestId,
1068
+ requestId: hopIds.requestId,
1069
+ parentRequestId: hopIds.parentRequestId,
985
1070
  ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() ? { alwaysUseRealApi: true } : {}),
986
1071
  };
987
1072
  (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
@@ -1032,8 +1117,18 @@ class MockifyerClass {
1032
1117
  this.savingResponses.delete(requestKey);
1033
1118
  }
1034
1119
  }
1035
- async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs) {
1120
+ async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
1036
1121
  const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
1122
+ const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation);
1123
+ if (hopIds.requestId) {
1124
+ updated.requestId = hopIds.requestId;
1125
+ }
1126
+ if (hopIds.parentRequestId) {
1127
+ updated.parentRequestId = hopIds.parentRequestId;
1128
+ }
1129
+ else {
1130
+ delete updated.parentRequestId;
1131
+ }
1037
1132
  if (this.databaseProvider) {
1038
1133
  await this.databaseProvider.save(updated);
1039
1134
  return;
@@ -1315,10 +1410,10 @@ function setupMockifyer(config) {
1315
1410
  const method = init?.method || 'GET';
1316
1411
  const headers = init?.headers || {};
1317
1412
  const body = init?.body;
1318
- // Skip Mockifyer sync endpoints, dashboard `/api/proxy` plumbing, and Resend API
1413
+ // Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
1319
1414
  if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url) ||
1320
1415
  url.includes('api.resend.com') ||
1321
- (0, mockifyer_core_1.isMockifyerDashboardProxyApiUrl)(url)) {
1416
+ (0, mockifyer_core_1.isMockifyerDashboardPlumbingApiUrl)(url)) {
1322
1417
  return await originalFetchForPatched(input, init);
1323
1418
  }
1324
1419
  const simpleRequestKey = `${method}:${url}`;
@@ -1354,7 +1449,7 @@ function setupMockifyer(config) {
1354
1449
  });
1355
1450
  }
1356
1451
  else {
1357
- headersObj = headers;
1452
+ headersObj = { ...headers };
1358
1453
  }
1359
1454
  try {
1360
1455
  const requestConfig = {
@@ -1374,8 +1469,7 @@ function setupMockifyer(config) {
1374
1469
  }
1375
1470
  });
1376
1471
  }
1377
- const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
1378
- return new Response(responseBody, {
1472
+ return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(response.status, response.data), {
1379
1473
  status: response.status,
1380
1474
  statusText: response.statusText || '',
1381
1475
  headers: responseHeaders
@@ -1387,11 +1481,9 @@ function setupMockifyer(config) {
1387
1481
  Object.entries(error.response.headers || {}).forEach(([key, value]) => {
1388
1482
  responseHeaders.set(key, String(value));
1389
1483
  });
1390
- const errorBody = typeof error.response.data === 'string'
1391
- ? error.response.data
1392
- : JSON.stringify(error.response.data);
1393
- return new Response(errorBody, {
1394
- status: error.response.status,
1484
+ const errorStatus = error.response.status;
1485
+ return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(errorStatus, error.response.data), {
1486
+ status: errorStatus,
1395
1487
  statusText: error.response.statusText || '',
1396
1488
  headers: responseHeaders
1397
1489
  });
@@ -8,6 +8,17 @@
8
8
  * 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
9
9
  * 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
10
10
  * 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
11
+ * 7. POST /mockifyer-atlas-html — write crash-scoped trace HTML to mock-data/atlas-html/incidents/
12
+ * 8. GET /atlas-html[/…] (legacy: /mockifyer-atlas-html[/…]) — serve atlas-html static files (index.html, pages, incidents, screenshots)
13
+ * 9. POST /mockifyer-atlas-screenshot — write screen image (png/jpg/webp) under mock-data/atlas-html/screenshots/
14
+ * 10. POST /mockifyer-atlas-render — write full interactive Atlas HTML under mock-data/atlas-html/
15
+ * 11. POST /mockifyer-atlas-body-spill — write full hop body text under mock-data/atlas-html/bodies/
16
+ * 12. POST/GET /mockifyer-network-events — live hop ring buffer for `mockifyer-atlas` CLI
17
+ * 13. GET /mockifyer-network-events/stream — SSE hop stream
18
+ * 14. GET /mockifyer-network-events/analyze — hop summary JSON
19
+ * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
20
+ * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
21
+ * 17. POST /mockifyer-network-events/clear — clear ring buffer
11
22
  *
12
23
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
13
24
  * Legacy polling-based sync is still available for backward compatibility.
@@ -24,7 +35,7 @@ export interface MetroSyncMiddlewareOptions {
24
35
  /** Enable automatic test generation when mocks are saved */
25
36
  enabled?: boolean;
26
37
  /** Test framework to use: 'jest' (default), 'vitest', or 'mocha' */
27
- framework?: 'jest' | 'vitest' | 'mocha';
38
+ framework?: "jest" | "vitest" | "mocha";
28
39
  /** Output path for generated tests (default: './tests/generated') */
29
40
  outputPath?: string;
30
41
  /** Test file naming pattern with placeholders: {endpoint}, {method}, {scenario} (default: '{endpoint}.test.ts') */
@@ -32,7 +43,7 @@ export interface MetroSyncMiddlewareOptions {
32
43
  /** Include setup code in generated tests (default: true) */
33
44
  includeSetup?: boolean;
34
45
  /** Group tests by: 'endpoint', 'scenario', or 'file' (default: 'endpoint') */
35
- groupBy?: 'endpoint' | 'scenario' | 'file';
46
+ groupBy?: "endpoint" | "scenario" | "file";
36
47
  /** If true, only generate one test per endpoint (method + pathname), ignoring query parameters (default: false) */
37
48
  uniqueTestsPerEndpoint?: boolean;
38
49
  };