@sgedda/mockifyer-fetch 1.8.26 → 1.8.32

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.
package/dist/index.js CHANGED
@@ -14,7 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
17
18
  exports.setupMockifyer = setupMockifyer;
19
+ exports.initMockifyerForDashboardProxy = initMockifyerForDashboardProxy;
20
+ exports.initMockifyerForLocalFilesystem = initMockifyerForLocalFilesystem;
18
21
  // Fetch-only Mockifyer implementation
19
22
  // Conditionally import fs - will be undefined in React Native
20
23
  let fs;
@@ -33,7 +36,63 @@ catch (e) {
33
36
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
34
37
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
35
38
  const fetch_client_1 = require("./clients/fetch-client");
39
+ const dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
40
+ /**
41
+ * When `proxy.baseUrl` is set and `proxy.recordOnMiss` is omitted, apply `MOCKIFYER_PROXY_RECORD_ON_MISS` if set.
42
+ */
43
+ function applyProxyRecordOnMissEnv(config) {
44
+ const proxy = config.proxy;
45
+ const baseUrl = proxy?.baseUrl?.trim();
46
+ if (!proxy || !baseUrl || proxy.recordOnMiss !== undefined) {
47
+ return config;
48
+ }
49
+ const parsed = (0, mockifyer_core_1.parseProxyRecordOnMissEnv)();
50
+ if (parsed === undefined) {
51
+ return config;
52
+ }
53
+ return {
54
+ ...config,
55
+ proxy: {
56
+ baseUrl: proxy.baseUrl,
57
+ scenario: proxy.scenario,
58
+ recordOnMiss: parsed,
59
+ strictLaneScenario: proxy.strictLaneScenario,
60
+ mirrorRecordedMocksToClient: proxy.mirrorRecordedMocksToClient,
61
+ },
62
+ };
63
+ }
36
64
  class MockifyerClass {
65
+ /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
66
+ logNetworkEvent(partial, correlation) {
67
+ if (this.config.proxy?.baseUrl)
68
+ return;
69
+ const scenario = this.config.proxy?.scenario?.trim() ||
70
+ (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
71
+ (0, mockifyer_core_1.emitMockifyerNetworkEvent)({
72
+ config: this.config,
73
+ scenario,
74
+ clientId: this.config.clientId,
75
+ event: {
76
+ ...partial,
77
+ transport: partial.transport ?? 'fetch',
78
+ requestId: correlation?.requestId ?? partial.requestId,
79
+ parentRequestId: correlation?.parentRequestId ?? partial.parentRequestId,
80
+ },
81
+ });
82
+ }
83
+ stashRequestCorrelation(config, correlation) {
84
+ config.__mockifyer_requestId =
85
+ correlation.requestId;
86
+ config.__mockifyer_parentRequestId =
87
+ correlation.parentRequestId;
88
+ }
89
+ readRequestCorrelation(config) {
90
+ const requestId = config.__mockifyer_requestId;
91
+ if (!requestId)
92
+ return undefined;
93
+ const parentRequestId = config.__mockifyer_parentRequestId;
94
+ return parentRequestId ? { requestId, parentRequestId } : { requestId };
95
+ }
37
96
  constructor(config) {
38
97
  this.processingRequests = new Set();
39
98
  this.savingResponses = new Set();
@@ -94,10 +153,23 @@ class MockifyerClass {
94
153
  if (launchClientId) {
95
154
  this.config.clientId = launchClientId;
96
155
  }
156
+ else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
157
+ Boolean(this.config.proxy?.baseUrl?.trim())) {
158
+ // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
159
+ this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
160
+ }
97
161
  else {
98
162
  this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
99
163
  }
100
164
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
165
+ if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
166
+ const raw = typeof process !== 'undefined'
167
+ ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
168
+ : '';
169
+ if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
170
+ this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
171
+ }
172
+ }
101
173
  // Initialize test generator if test generation is enabled
102
174
  if (config.generateTests?.enabled) {
103
175
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -134,6 +206,7 @@ class MockifyerClass {
134
206
  clientId: this.config.clientId,
135
207
  getClientId: () => this.config.clientId,
136
208
  getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
209
+ getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
137
210
  deviceId: this.config.deviceId,
138
211
  });
139
212
  if (!config.recordSameEndpoints) {
@@ -160,7 +233,12 @@ class MockifyerClass {
160
233
  generateRequestKey(request) {
161
234
  return (0, mockifyer_core_1.generateRequestKey)(request);
162
235
  }
163
- async findBestMatchingMock(request) {
236
+ /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
237
+ usesDashboardProxy() {
238
+ const baseUrl = this.config.proxy?.baseUrl;
239
+ return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
240
+ }
241
+ async findBestMatchingMock(request, options) {
164
242
  // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
165
243
  const requestUrl = request?.url || '';
166
244
  if (requestUrl.includes('/mockifyer-save') ||
@@ -177,12 +255,12 @@ class MockifyerClass {
177
255
  }
178
256
  // Use database provider if available, otherwise fallback to filesystem
179
257
  if (this.databaseProvider) {
180
- return await this.findBestMatchingMockFromProvider(request);
258
+ return await this.findBestMatchingMockFromProvider(request, options);
181
259
  }
182
260
  // Fallback to Node.js filesystem
183
- return this.findBestMatchingMockFromFiles(request);
261
+ return this.findBestMatchingMockFromFiles(request, options);
184
262
  }
185
- async findBestMatchingMockFromProvider(request) {
263
+ async findBestMatchingMockFromProvider(request, options) {
186
264
  if (!this.databaseProvider) {
187
265
  return undefined;
188
266
  }
@@ -201,7 +279,7 @@ class MockifyerClass {
201
279
  return undefined;
202
280
  }
203
281
  // Try exact match first
204
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
282
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
205
283
  if (exactMatch) {
206
284
  return exactMatch;
207
285
  }
@@ -215,7 +293,8 @@ class MockifyerClass {
215
293
  }
216
294
  return undefined;
217
295
  }
218
- findBestMatchingMockFromFiles(request) {
296
+ findBestMatchingMockFromFiles(request, options) {
297
+ const includePassthroughMocks = options?.includePassthroughMocks === true;
219
298
  // Only use fs if available (Node.js environment)
220
299
  // This method should never be called when using a database provider
221
300
  if (!fs || !path) {
@@ -247,7 +326,7 @@ class MockifyerClass {
247
326
  }
248
327
  const mockKey = this.generateRequestKey(mockData.request);
249
328
  if (mockKey === requestKey) {
250
- if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
329
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, { includePassthroughMocks })) {
251
330
  exactMatch = { mockData, filename: file, filePath };
252
331
  break;
253
332
  }
@@ -357,6 +436,7 @@ class MockifyerClass {
357
436
  if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
358
437
  useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
359
438
  })) {
439
+ (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
360
440
  config.__mockifyer_bypass = true;
361
441
  return config;
362
442
  }
@@ -365,6 +445,8 @@ class MockifyerClass {
365
445
  config.__mockifyer_bypass = true;
366
446
  return config;
367
447
  }
448
+ const correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
449
+ this.stashRequestCorrelation(config, correlation);
368
450
  // Normalize empty params: treat {} the same as undefined for consistent matching
369
451
  const rawParams = config.params || {};
370
452
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -383,31 +465,48 @@ class MockifyerClass {
383
465
  config.__mockifyer_requestKey = requestKey;
384
466
  // Store request start time for duration calculation
385
467
  config.__mockifyer_startTime = Date.now();
468
+ // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
469
+ // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
470
+ if (this.usesDashboardProxy()) {
471
+ return config;
472
+ }
386
473
  const cachedMock = await this.findBestMatchingMock(request);
387
474
  // Return cached mock if found
388
475
  if (cachedMock) {
389
476
  const { mockData, filename, filePath } = cachedMock;
390
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
477
+ if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
478
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
479
+ (filePath ? ` (${filePath})` : ''));
480
+ this.logNetworkEvent({
481
+ method: (request.method || 'GET').toUpperCase(),
482
+ url: request.url,
483
+ source: 'mock-hit',
484
+ status: mockData.response.status,
485
+ requestHash: (0, mockifyer_core_1.networkEventHashFromRequestKey)(requestKey),
486
+ }, correlation);
487
+ const responseHeaders = {
488
+ ...mockData.response.headers,
489
+ 'x-mockifyer': 'true',
490
+ 'x-mockifyer-timestamp': mockData.timestamp,
491
+ 'x-mockifyer-filename': filename,
492
+ 'x-mockifyer-filepath': filePath
493
+ };
494
+ const mockResponse = {
495
+ data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
496
+ status: mockData.response.status,
497
+ statusText: 'OK',
498
+ headers: responseHeaders,
499
+ config: config
500
+ };
501
+ return {
502
+ ...config,
503
+ __mockResponse: Promise.resolve(mockResponse),
504
+ __mockifyer_requestKey: requestKey
505
+ };
506
+ }
507
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
391
508
  (filePath ? ` (${filePath})` : ''));
392
- const responseHeaders = {
393
- ...mockData.response.headers,
394
- 'x-mockifyer': 'true',
395
- 'x-mockifyer-timestamp': mockData.timestamp,
396
- 'x-mockifyer-filename': filename,
397
- 'x-mockifyer-filepath': filePath
398
- };
399
- const mockResponse = {
400
- data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
401
- status: mockData.response.status,
402
- statusText: 'OK',
403
- headers: responseHeaders,
404
- config: config
405
- };
406
- return {
407
- ...config,
408
- __mockResponse: Promise.resolve(mockResponse),
409
- __mockifyer_requestKey: requestKey
410
- };
509
+ config.__mockifyer_matchedMock = cachedMock;
411
510
  }
412
511
  // Check request limit BEFORE making real API call (only if no mock found and in record mode)
413
512
  if (this.config.recordMode) {
@@ -519,20 +618,172 @@ class MockifyerClass {
519
618
  if (isMocked || isLimitReached) {
520
619
  return response;
521
620
  }
621
+ if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
622
+ await this.maybeMirrorProxyRecordingToClient(response);
623
+ }
624
+ const matchedMock = response.config.__mockifyer_matchedMock;
625
+ if (matchedMock) {
626
+ const capturedResponse = {
627
+ status: response.status,
628
+ data: response.data,
629
+ headers: response.headers || {},
630
+ };
631
+ const startTime = response.config.__mockifyer_startTime;
632
+ const durationMs = startTime ? Date.now() - startTime : undefined;
633
+ if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
634
+ await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
635
+ }
636
+ const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate);
637
+ response.data = clientResponse.data;
638
+ response.status = clientResponse.status;
639
+ delete response.config.__mockifyer_matchedMock;
640
+ const reqUrl = response.config?.url || url;
641
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
642
+ this.logNetworkEvent({
643
+ method: reqMethod,
644
+ url: reqUrl,
645
+ source: 'upstream',
646
+ status: response.status,
647
+ durationMs,
648
+ }, this.readRequestCorrelation(response.config));
649
+ return response;
650
+ }
522
651
  // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
523
652
  // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
524
653
  if (this.config.recordMode && !this.config.proxy?.baseUrl) {
525
654
  await this.saveResponse(response);
526
655
  }
656
+ const reqUrl = response.config?.url || url;
657
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
658
+ this.logNetworkEvent({
659
+ method: reqMethod,
660
+ url: reqUrl,
661
+ source: 'upstream',
662
+ status: response.status,
663
+ durationMs: typeof response.config?.metadata?.durationMs === 'number'
664
+ ? response.config.metadata.durationMs
665
+ : undefined,
666
+ }, this.readRequestCorrelation(response.config));
527
667
  return response;
528
668
  }, async (error) => {
529
669
  const requestKey = error.config?.__mockifyer_requestKey;
530
670
  if (requestKey) {
531
671
  this.processingRequests.delete(requestKey);
532
672
  }
673
+ const reqUrl = error.config?.url || '';
674
+ if (reqUrl) {
675
+ this.logNetworkEvent({
676
+ method: (error.config?.method || 'GET').toUpperCase(),
677
+ url: reqUrl,
678
+ source: 'error',
679
+ status: error.response?.status,
680
+ errorMessage: error?.message ?? String(error),
681
+ }, this.readRequestCorrelation(error.config));
682
+ }
533
683
  throw error;
534
684
  });
535
685
  }
686
+ /**
687
+ * When dashboard proxy records to Redis, optionally persist the same payload next to the client
688
+ * (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
689
+ */
690
+ async maybeMirrorProxyRecordingToClient(response) {
691
+ const rec = response.mockifyerProxyRecording;
692
+ if (!rec?.recordedToStore || !rec.storedMock) {
693
+ return;
694
+ }
695
+ const hash = rec.hash?.trim();
696
+ const scenarioName = rec.scenarioName?.trim();
697
+ if (!hash || !scenarioName) {
698
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror skipped: missing hash or scenario from proxy');
699
+ return;
700
+ }
701
+ const mockData = rec.storedMock;
702
+ const url = mockData?.request?.url || '';
703
+ if ((0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
704
+ return;
705
+ }
706
+ const recExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
707
+ if ((0, mockifyer_core_1.shouldExcludeRecording)(url, recExclusions, this.config.baseUrl)) {
708
+ return;
709
+ }
710
+ await this.databaseProviderInitPromise;
711
+ const providerType = this.config.databaseProvider?.type;
712
+ if (this.databaseProvider && providerType !== 'memory') {
713
+ try {
714
+ const out = this.databaseProvider.save(mockData, {
715
+ relativePath: `redis/${hash}.json`,
716
+ scenario: scenarioName,
717
+ });
718
+ if (out instanceof Promise) {
719
+ await out;
720
+ }
721
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (${providerType}): ${scenarioName}/redis/${hash}.json`);
722
+ if (providerType === 'hybrid') {
723
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
724
+ }
725
+ }
726
+ catch (e) {
727
+ mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (provider) failed:', e);
728
+ }
729
+ return;
730
+ }
731
+ if (fs && path) {
732
+ try {
733
+ (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, scenarioName);
734
+ const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, scenarioName);
735
+ const filePath = path.join(scenarioPath, 'redis', `${hash}.json`);
736
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
737
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
738
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (filesystem): ${scenarioName}/redis/${hash}.json`);
739
+ }
740
+ catch (e) {
741
+ mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (Node fs) failed:', e);
742
+ }
743
+ return;
744
+ }
745
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
746
+ }
747
+ async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
748
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
749
+ const fetchFn = global.__mockifyer_original_fetch || fetch;
750
+ if (!fetchFn) {
751
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
752
+ return;
753
+ }
754
+ try {
755
+ const body = JSON.stringify({
756
+ __mockifyerProxyMirror: true,
757
+ mockData,
758
+ scenarioName,
759
+ relativePath: `redis/${hash}.json`,
760
+ });
761
+ const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
762
+ method: 'POST',
763
+ headers: { 'Content-Type': 'application/json' },
764
+ body,
765
+ });
766
+ const text = await res.text().catch(() => '');
767
+ if (!res.ok) {
768
+ mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
769
+ return;
770
+ }
771
+ try {
772
+ const parsed = JSON.parse(text);
773
+ if (parsed.success === false) {
774
+ mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
775
+ return;
776
+ }
777
+ }
778
+ catch {
779
+ // non-JSON response
780
+ }
781
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
782
+ }
783
+ catch (e) {
784
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
785
+ }
786
+ }
536
787
  async saveResponse(response) {
537
788
  // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
538
789
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
@@ -543,10 +794,19 @@ class MockifyerClass {
543
794
  if (this.config.proxy?.baseUrl) {
544
795
  return;
545
796
  }
797
+ if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
798
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
799
+ return;
800
+ }
546
801
  const url = response.config?.url || response.request?.responseURL || response.url || '';
802
+ const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
547
803
  if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
548
804
  return;
549
805
  }
806
+ if (url &&
807
+ (0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
808
+ return;
809
+ }
550
810
  // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
551
811
  // This is a defense-in-depth measure
552
812
  try {
@@ -580,57 +840,68 @@ class MockifyerClass {
580
840
  // Normalize empty params: treat {} the same as undefined for consistent matching
581
841
  const rawParams = response.config.params || {};
582
842
  const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
583
- const requestKey = this.generateRequestKey({
843
+ const saveLookupRequest = {
584
844
  method: response.config.method?.toUpperCase() || 'GET',
585
845
  url: response.config.url || '',
586
846
  headers: {},
587
847
  data: response.config.data,
588
- queryParams: normalizedParams
589
- });
848
+ queryParams: normalizedParams,
849
+ };
850
+ const requestKey = this.generateRequestKey(saveLookupRequest);
590
851
  if (this.savingResponses.has(requestKey)) {
591
852
  return;
592
853
  }
854
+ const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
855
+ includePassthroughMocks: true,
856
+ });
857
+ const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
858
+ if (saveDecision.action === 'skip') {
859
+ if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
860
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
861
+ }
862
+ return;
863
+ }
593
864
  this.savingResponses.add(requestKey);
594
865
  try {
595
- // Normalize empty params: treat {} the same as undefined for consistent matching
596
- const rawParams = response.config.params || {};
597
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
598
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
866
+ const rawParamsForSave = response.config.params || {};
867
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
868
+ const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
599
869
  ? anonymizedQueryParams
600
870
  : undefined;
601
- // Generate or reuse sessionId
602
871
  const now = Date.now();
603
- if (!this.currentSessionId || (now - this.sessionStartTime) > this.SESSION_TIMEOUT_MS) {
604
- // Generate new session ID
872
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
605
873
  this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
606
874
  this.sessionStartTime = now;
607
875
  }
608
- // Calculate request duration if start time is available
609
876
  const startTime = response.config.__mockifyer_startTime;
610
877
  const duration = startTime ? Date.now() - startTime : undefined;
878
+ const correlation = this.readRequestCorrelation(response.config);
611
879
  const mockData = {
612
880
  request: {
613
881
  method: response.config?.method?.toUpperCase() || 'GET',
614
882
  url: response.config?.url || '',
615
883
  headers: this.anonymizeHeaders(response.config?.headers || {}),
616
884
  data: response.config?.data,
617
- queryParams: normalizedParams
885
+ queryParams: normalizedParamsForSave,
618
886
  },
619
887
  response: {
620
888
  status: response.status,
621
889
  data: response.data,
622
- headers: response.headers || {}
890
+ headers: response.headers || {},
623
891
  },
624
892
  timestamp: new Date().toISOString(),
625
893
  duration,
626
- sessionId: this.currentSessionId
894
+ sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
895
+ ? existingMock.mockData.sessionId
896
+ : this.currentSessionId,
897
+ requestId: correlation?.requestId,
898
+ parentRequestId: correlation?.parentRequestId,
899
+ ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() ? { alwaysUseRealApi: true } : {}),
627
900
  };
628
- // Use database provider if available, otherwise fallback to filesystem
901
+ (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
629
902
  if (this.databaseProvider) {
630
903
  try {
631
904
  await this.databaseProvider.save(mockData);
632
- // Generate test if enabled (try to write test files even with database provider)
633
- // Generate test if enabled
634
905
  if (this.config.generateTests?.enabled) {
635
906
  await this.generateTestForMock(mockData);
636
907
  }
@@ -641,26 +912,28 @@ class MockifyerClass {
641
912
  }
642
913
  }
643
914
  else if (fs && path) {
644
- // Fallback to Node.js filesystem (only if fs/path are available)
645
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
646
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
647
- const domain = urlParts[0].replace(/\./g, '_');
648
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
649
- const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
650
915
  const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
651
916
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
652
917
  (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
653
- // Check request limit before saving (only if limit is set via env var)
654
918
  const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
655
919
  if (limitCheck.limitReached && limitCheck.error) {
656
920
  console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
657
- // Don't throw - just log and return to prevent app crash
658
921
  return;
659
922
  }
660
- const filePath = path.join(scenarioPath, filename);
661
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
662
- mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
663
- // Generate test if enabled
923
+ if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
924
+ fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
925
+ mockifyer_core_2.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
926
+ }
927
+ else {
928
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
929
+ const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
930
+ const domain = urlParts[0].replace(/\./g, '_');
931
+ const urlPathPart = urlParts.slice(1).join('_') || 'root';
932
+ const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
933
+ const filePath = path.join(scenarioPath, filename);
934
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
935
+ mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
936
+ }
664
937
  if (this.config.generateTests?.enabled && this.testGenerator) {
665
938
  await this.generateTestForMock(mockData);
666
939
  }
@@ -673,6 +946,17 @@ class MockifyerClass {
673
946
  this.savingResponses.delete(requestKey);
674
947
  }
675
948
  }
949
+ async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs) {
950
+ const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
951
+ if (this.databaseProvider) {
952
+ await this.databaseProvider.save(updated);
953
+ return;
954
+ }
955
+ if (fs && cachedMock.filePath) {
956
+ fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
957
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
958
+ }
959
+ }
676
960
  /**
677
961
  * Simple path resolution fallback for React Native (when path module is stubbed)
678
962
  */
@@ -884,8 +1168,13 @@ class MockifyerClass {
884
1168
  }
885
1169
  }
886
1170
  function setupMockifyer(config) {
1171
+ // Node-only inbound capture; safe on RN (no-op when not on Node).
1172
+ if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
1173
+ (0, mockifyer_core_1.installNodeInboundRequestCorrelationCapture)();
1174
+ }
1175
+ const resolvedConfig = applyProxyRecordOnMissEnv(config);
887
1176
  // Initialize logger with config level (default to 'info' if not specified)
888
- (0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
1177
+ (0, mockifyer_core_2.setLogLevel)(resolvedConfig.logging || 'info');
889
1178
  // Set environment variables for Metro middleware to read test generation config
890
1179
  // This allows Metro middleware (which runs in Node.js) to generate tests
891
1180
  // when Hybrid Provider saves mocks via Metro endpoint
@@ -910,9 +1199,9 @@ function setupMockifyer(config) {
910
1199
  process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT = 'true';
911
1200
  }
912
1201
  }
913
- (0, mockifyer_core_1.initializeDateManipulation)(config);
914
- (0, mockifyer_core_1.initializeScenario)(config);
915
- const mockifyer = new MockifyerClass(config);
1202
+ (0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
1203
+ (0, mockifyer_core_1.initializeScenario)(resolvedConfig);
1204
+ const mockifyer = new MockifyerClass(resolvedConfig);
916
1205
  const httpClient = mockifyer.getHTTPClient();
917
1206
  // Always store original fetch (even if not patching global)
918
1207
  let originalFetch;
@@ -928,7 +1217,7 @@ function setupMockifyer(config) {
928
1217
  fetchClient._originalFetch = originalFetch;
929
1218
  }
930
1219
  // Patch global fetch if useGlobalFetch is true
931
- if (config.useGlobalFetch) {
1220
+ if (resolvedConfig.useGlobalFetch) {
932
1221
  const mockifyerInstance = mockifyer;
933
1222
  const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
934
1223
  global.fetch = async function (input, init) {
@@ -1028,7 +1317,135 @@ function setupMockifyer(config) {
1028
1317
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1029
1318
  return extendedClient;
1030
1319
  }
1320
+ /** Drops `proxy` when merging partial config so filesystem fallback cannot accidentally keep proxy. */
1321
+ function omitProxyFromPartialConfig(config) {
1322
+ const { proxy: _drop, ...rest } = config;
1323
+ void _drop;
1324
+ return rest;
1325
+ }
1326
+ /**
1327
+ * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
1328
+ * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
1329
+ *
1330
+ * For full control, use {@link setupMockifyer} directly.
1331
+ */
1332
+ async function initMockifyerForDashboardProxy(options) {
1333
+ const extra = options.config ?? {};
1334
+ const dashboardBaseUrl = String(options.dashboardBaseUrl).trim();
1335
+ if (!dashboardBaseUrl) {
1336
+ throw new Error('initMockifyerForDashboardProxy: dashboardBaseUrl is required');
1337
+ }
1338
+ const mockDataPath = options.mockDataPath ??
1339
+ extra.mockDataPath ??
1340
+ (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1341
+ ? process.env.MOCKIFYER_PATH
1342
+ : './mock-data');
1343
+ const envRecord = typeof process !== 'undefined' && process.env?.MOCKIFYER_RECORD === 'true';
1344
+ const recordOnMiss = options.recordOnMiss ??
1345
+ extra.proxy?.recordOnMiss ??
1346
+ (0, mockifyer_core_1.parseProxyRecordOnMissEnv)() ??
1347
+ (envRecord ? true : undefined);
1348
+ const recordResponses = (0, mockifyer_core_1.resolveRecordResponses)(options.recordResponses ?? extra.proxy?.recordResponses);
1349
+ const useRedisProxy = options.skipDashboardRedisHealthCheck === true ||
1350
+ (await (0, dashboard_redis_health_1.canUseDashboardRedisProxy)(dashboardBaseUrl));
1351
+ if (!useRedisProxy) {
1352
+ const strictProxyOnly = (0, mockifyer_core_1.resolveStrictScenarioResolution)({
1353
+ strictScenarioResolution: options.config?.strictScenarioResolution ?? extra.strictScenarioResolution,
1354
+ });
1355
+ mockifyer_core_2.logger.warn(`[Mockifyer] initMockifyerForDashboardProxy: "${dashboardBaseUrl}" did not report healthy Redis ` +
1356
+ (strictProxyOnly
1357
+ ? '(strict proxy-only — local recording disabled). '
1358
+ : '(unreachable or non-Redis provider). Falling back to filesystem mocks without proxy. ') +
1359
+ 'Set skipDashboardRedisHealthCheck: true to force proxy anyway.');
1360
+ const stripped = omitProxyFromPartialConfig(extra);
1361
+ const fallbackDb = options.databaseProvider ?? extra.databaseProvider;
1362
+ const mergedInitLogFs = {
1363
+ ...stripped.initLog,
1364
+ headline: stripped.initLog?.headline ??
1365
+ (strictProxyOnly
1366
+ ? '[Mockifyer preset] Node · strict proxy-only (dashboard Redis health check failed)'
1367
+ : '[Mockifyer preset] Node · filesystem (dashboard Redis health check failed)'),
1368
+ };
1369
+ return setupMockifyer({
1370
+ ...stripped,
1371
+ mockDataPath,
1372
+ ...(fallbackDb !== undefined ? { databaseProvider: fallbackDb } : {}),
1373
+ ...(strictProxyOnly ? { intendedProxyBaseUrl: dashboardBaseUrl.trim() } : {}),
1374
+ useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1375
+ clientId: options.clientId ?? extra.clientId,
1376
+ deviceId: options.deviceId ?? extra.deviceId,
1377
+ initLog: mergedInitLogFs,
1378
+ });
1379
+ }
1380
+ const upstreamProxy = extra.proxy;
1381
+ const mergedProxy = {
1382
+ ...upstreamProxy,
1383
+ baseUrl: upstreamProxy?.baseUrl ?? dashboardBaseUrl,
1384
+ scenario: options.scenario ??
1385
+ upstreamProxy?.scenario ??
1386
+ (typeof process !== 'undefined' && process.env?.MOCKIFYER_SCENARIO?.trim()
1387
+ ? process.env.MOCKIFYER_SCENARIO.trim()
1388
+ : undefined),
1389
+ ...(typeof recordOnMiss === 'boolean' ? { recordOnMiss } : {}),
1390
+ recordResponses,
1391
+ };
1392
+ if (options.strictLaneScenario !== undefined ||
1393
+ upstreamProxy?.strictLaneScenario !== undefined) {
1394
+ mergedProxy.strictLaneScenario =
1395
+ options.strictLaneScenario ?? upstreamProxy?.strictLaneScenario;
1396
+ }
1397
+ const envMirrorRaw = typeof process !== 'undefined'
1398
+ ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
1399
+ : '';
1400
+ const envMirror = envMirrorRaw === '1' || envMirrorRaw === 'true' || envMirrorRaw === 'yes' || envMirrorRaw === 'on';
1401
+ const mirrorRecordedMocksToClient = options.mirrorRecordedMocksToClient ??
1402
+ extra.proxy?.mirrorRecordedMocksToClient ??
1403
+ (envMirror ? true : undefined);
1404
+ if (mirrorRecordedMocksToClient !== undefined) {
1405
+ mergedProxy.mirrorRecordedMocksToClient = mirrorRecordedMocksToClient;
1406
+ }
1407
+ const mergedInitLogProxy = {
1408
+ ...extra.initLog,
1409
+ headline: extra.initLog?.headline ?? '[Mockifyer preset] Node · dashboard Redis proxy',
1410
+ };
1411
+ const strictScenarioResolution = extra.strictScenarioResolution ??
1412
+ options.config?.strictScenarioResolution ??
1413
+ true;
1414
+ return setupMockifyer({
1415
+ ...extra,
1416
+ mockDataPath,
1417
+ strictScenarioResolution,
1418
+ databaseProvider: options.databaseProvider ?? extra.databaseProvider ?? { type: 'memory' },
1419
+ useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1420
+ clientId: options.clientId ?? extra.clientId,
1421
+ deviceId: options.deviceId ?? extra.deviceId,
1422
+ proxy: mergedProxy,
1423
+ initLog: mergedInitLogProxy,
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
1428
+ * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
1429
+ */
1430
+ function initMockifyerForLocalFilesystem(options = {}) {
1431
+ const extra = options.config ?? {};
1432
+ const mockDataPath = options.mockDataPath ??
1433
+ extra.mockDataPath ??
1434
+ (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1435
+ ? process.env.MOCKIFYER_PATH
1436
+ : './mock-data');
1437
+ return setupMockifyer({
1438
+ ...extra,
1439
+ mockDataPath,
1440
+ useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1441
+ recordMode: options.recordMode ?? extra.recordMode ?? false,
1442
+ });
1443
+ }
1444
+ /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
1445
+ var dashboard_redis_health_2 = require("./utils/dashboard-redis-health");
1446
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardRedisProxy; } });
1447
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardCentralProxy; } });
1031
1448
  // Re-export types from core
1032
1449
  __exportStar(require("@sgedda/mockifyer-core"), exports);
1033
- // Export React Native helpers
1034
- __exportStar(require("./react-native"), exports);
1450
+ // React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
1451
+ // pulling optional `react-native-launch-arguments` into Node/Next webpack bundles).