@sgedda/mockifyer-fetch 1.8.25 → 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,13 +153,22 @@ 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
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
101
164
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
102
- if (this.activationMode !== 'always') {
103
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
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
+ }
104
172
  }
105
173
  // Initialize test generator if test generation is enabled
106
174
  if (config.generateTests?.enabled) {
@@ -137,6 +205,8 @@ class MockifyerClass {
137
205
  proxy: config.proxy,
138
206
  clientId: this.config.clientId,
139
207
  getClientId: () => this.config.clientId,
208
+ getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
209
+ getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
140
210
  deviceId: this.config.deviceId,
141
211
  });
142
212
  if (!config.recordSameEndpoints) {
@@ -146,6 +216,10 @@ class MockifyerClass {
146
216
  this.setupMockResponses();
147
217
  // Set up response interceptor to save responses when recordMode is enabled
148
218
  this.setupResponseInterceptor();
219
+ (0, mockifyer_core_1.logMockifyerInitSummary)(this.config, {
220
+ runtimeMode: this.config.runtimeMode,
221
+ headline: this.config.initLog?.headline,
222
+ });
149
223
  }
150
224
  ensureMockDataDirectory() {
151
225
  // Only use fs if available (Node.js environment) and no database provider is set
@@ -159,7 +233,12 @@ class MockifyerClass {
159
233
  generateRequestKey(request) {
160
234
  return (0, mockifyer_core_1.generateRequestKey)(request);
161
235
  }
162
- 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) {
163
242
  // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
164
243
  const requestUrl = request?.url || '';
165
244
  if (requestUrl.includes('/mockifyer-save') ||
@@ -176,12 +255,12 @@ class MockifyerClass {
176
255
  }
177
256
  // Use database provider if available, otherwise fallback to filesystem
178
257
  if (this.databaseProvider) {
179
- return await this.findBestMatchingMockFromProvider(request);
258
+ return await this.findBestMatchingMockFromProvider(request, options);
180
259
  }
181
260
  // Fallback to Node.js filesystem
182
- return this.findBestMatchingMockFromFiles(request);
261
+ return this.findBestMatchingMockFromFiles(request, options);
183
262
  }
184
- async findBestMatchingMockFromProvider(request) {
263
+ async findBestMatchingMockFromProvider(request, options) {
185
264
  if (!this.databaseProvider) {
186
265
  return undefined;
187
266
  }
@@ -200,7 +279,7 @@ class MockifyerClass {
200
279
  return undefined;
201
280
  }
202
281
  // Try exact match first
203
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
282
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
204
283
  if (exactMatch) {
205
284
  return exactMatch;
206
285
  }
@@ -214,7 +293,8 @@ class MockifyerClass {
214
293
  }
215
294
  return undefined;
216
295
  }
217
- findBestMatchingMockFromFiles(request) {
296
+ findBestMatchingMockFromFiles(request, options) {
297
+ const includePassthroughMocks = options?.includePassthroughMocks === true;
218
298
  // Only use fs if available (Node.js environment)
219
299
  // This method should never be called when using a database provider
220
300
  if (!fs || !path) {
@@ -246,7 +326,7 @@ class MockifyerClass {
246
326
  }
247
327
  const mockKey = this.generateRequestKey(mockData.request);
248
328
  if (mockKey === requestKey) {
249
- if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
329
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, { includePassthroughMocks })) {
250
330
  exactMatch = { mockData, filename: file, filePath };
251
331
  break;
252
332
  }
@@ -356,6 +436,7 @@ class MockifyerClass {
356
436
  if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
357
437
  useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
358
438
  })) {
439
+ (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
359
440
  config.__mockifyer_bypass = true;
360
441
  return config;
361
442
  }
@@ -364,6 +445,8 @@ class MockifyerClass {
364
445
  config.__mockifyer_bypass = true;
365
446
  return config;
366
447
  }
448
+ const correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
449
+ this.stashRequestCorrelation(config, correlation);
367
450
  // Normalize empty params: treat {} the same as undefined for consistent matching
368
451
  const rawParams = config.params || {};
369
452
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -382,31 +465,48 @@ class MockifyerClass {
382
465
  config.__mockifyer_requestKey = requestKey;
383
466
  // Store request start time for duration calculation
384
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
+ }
385
473
  const cachedMock = await this.findBestMatchingMock(request);
386
474
  // Return cached mock if found
387
475
  if (cachedMock) {
388
476
  const { mockData, filename, filePath } = cachedMock;
389
- 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}` +
390
508
  (filePath ? ` (${filePath})` : ''));
391
- const responseHeaders = {
392
- ...mockData.response.headers,
393
- 'x-mockifyer': 'true',
394
- 'x-mockifyer-timestamp': mockData.timestamp,
395
- 'x-mockifyer-filename': filename,
396
- 'x-mockifyer-filepath': filePath
397
- };
398
- const mockResponse = {
399
- data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
400
- status: mockData.response.status,
401
- statusText: 'OK',
402
- headers: responseHeaders,
403
- config: config
404
- };
405
- return {
406
- ...config,
407
- __mockResponse: Promise.resolve(mockResponse),
408
- __mockifyer_requestKey: requestKey
409
- };
509
+ config.__mockifyer_matchedMock = cachedMock;
410
510
  }
411
511
  // Check request limit BEFORE making real API call (only if no mock found and in record mode)
412
512
  if (this.config.recordMode) {
@@ -518,20 +618,172 @@ class MockifyerClass {
518
618
  if (isMocked || isLimitReached) {
519
619
  return response;
520
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
+ }
521
651
  // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
522
652
  // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
523
653
  if (this.config.recordMode && !this.config.proxy?.baseUrl) {
524
654
  await this.saveResponse(response);
525
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));
526
667
  return response;
527
668
  }, async (error) => {
528
669
  const requestKey = error.config?.__mockifyer_requestKey;
529
670
  if (requestKey) {
530
671
  this.processingRequests.delete(requestKey);
531
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
+ }
532
683
  throw error;
533
684
  });
534
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
+ }
535
787
  async saveResponse(response) {
536
788
  // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
537
789
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
@@ -542,10 +794,19 @@ class MockifyerClass {
542
794
  if (this.config.proxy?.baseUrl) {
543
795
  return;
544
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
+ }
545
801
  const url = response.config?.url || response.request?.responseURL || response.url || '';
802
+ const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
546
803
  if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
547
804
  return;
548
805
  }
806
+ if (url &&
807
+ (0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
808
+ return;
809
+ }
549
810
  // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
550
811
  // This is a defense-in-depth measure
551
812
  try {
@@ -579,57 +840,68 @@ class MockifyerClass {
579
840
  // Normalize empty params: treat {} the same as undefined for consistent matching
580
841
  const rawParams = response.config.params || {};
581
842
  const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
582
- const requestKey = this.generateRequestKey({
843
+ const saveLookupRequest = {
583
844
  method: response.config.method?.toUpperCase() || 'GET',
584
845
  url: response.config.url || '',
585
846
  headers: {},
586
847
  data: response.config.data,
587
- queryParams: normalizedParams
588
- });
848
+ queryParams: normalizedParams,
849
+ };
850
+ const requestKey = this.generateRequestKey(saveLookupRequest);
589
851
  if (this.savingResponses.has(requestKey)) {
590
852
  return;
591
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
+ }
592
864
  this.savingResponses.add(requestKey);
593
865
  try {
594
- // Normalize empty params: treat {} the same as undefined for consistent matching
595
- const rawParams = response.config.params || {};
596
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
597
- 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
598
869
  ? anonymizedQueryParams
599
870
  : undefined;
600
- // Generate or reuse sessionId
601
871
  const now = Date.now();
602
- if (!this.currentSessionId || (now - this.sessionStartTime) > this.SESSION_TIMEOUT_MS) {
603
- // Generate new session ID
872
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
604
873
  this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
605
874
  this.sessionStartTime = now;
606
875
  }
607
- // Calculate request duration if start time is available
608
876
  const startTime = response.config.__mockifyer_startTime;
609
877
  const duration = startTime ? Date.now() - startTime : undefined;
878
+ const correlation = this.readRequestCorrelation(response.config);
610
879
  const mockData = {
611
880
  request: {
612
881
  method: response.config?.method?.toUpperCase() || 'GET',
613
882
  url: response.config?.url || '',
614
883
  headers: this.anonymizeHeaders(response.config?.headers || {}),
615
884
  data: response.config?.data,
616
- queryParams: normalizedParams
885
+ queryParams: normalizedParamsForSave,
617
886
  },
618
887
  response: {
619
888
  status: response.status,
620
889
  data: response.data,
621
- headers: response.headers || {}
890
+ headers: response.headers || {},
622
891
  },
623
892
  timestamp: new Date().toISOString(),
624
893
  duration,
625
- 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 } : {}),
626
900
  };
627
- // Use database provider if available, otherwise fallback to filesystem
901
+ (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
628
902
  if (this.databaseProvider) {
629
903
  try {
630
904
  await this.databaseProvider.save(mockData);
631
- // Generate test if enabled (try to write test files even with database provider)
632
- // Generate test if enabled
633
905
  if (this.config.generateTests?.enabled) {
634
906
  await this.generateTestForMock(mockData);
635
907
  }
@@ -640,26 +912,28 @@ class MockifyerClass {
640
912
  }
641
913
  }
642
914
  else if (fs && path) {
643
- // Fallback to Node.js filesystem (only if fs/path are available)
644
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
645
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
646
- const domain = urlParts[0].replace(/\./g, '_');
647
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
648
- const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
649
915
  const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
650
916
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
651
917
  (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
652
- // Check request limit before saving (only if limit is set via env var)
653
918
  const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
654
919
  if (limitCheck.limitReached && limitCheck.error) {
655
920
  console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
656
- // Don't throw - just log and return to prevent app crash
657
921
  return;
658
922
  }
659
- const filePath = path.join(scenarioPath, filename);
660
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
661
- mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
662
- // 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
+ }
663
937
  if (this.config.generateTests?.enabled && this.testGenerator) {
664
938
  await this.generateTestForMock(mockData);
665
939
  }
@@ -672,6 +946,17 @@ class MockifyerClass {
672
946
  this.savingResponses.delete(requestKey);
673
947
  }
674
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
+ }
675
960
  /**
676
961
  * Simple path resolution fallback for React Native (when path module is stubbed)
677
962
  */
@@ -883,8 +1168,13 @@ class MockifyerClass {
883
1168
  }
884
1169
  }
885
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);
886
1176
  // Initialize logger with config level (default to 'info' if not specified)
887
- (0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
1177
+ (0, mockifyer_core_2.setLogLevel)(resolvedConfig.logging || 'info');
888
1178
  // Set environment variables for Metro middleware to read test generation config
889
1179
  // This allows Metro middleware (which runs in Node.js) to generate tests
890
1180
  // when Hybrid Provider saves mocks via Metro endpoint
@@ -909,9 +1199,9 @@ function setupMockifyer(config) {
909
1199
  process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT = 'true';
910
1200
  }
911
1201
  }
912
- (0, mockifyer_core_1.initializeDateManipulation)(config);
913
- (0, mockifyer_core_1.initializeScenario)(config);
914
- 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);
915
1205
  const httpClient = mockifyer.getHTTPClient();
916
1206
  // Always store original fetch (even if not patching global)
917
1207
  let originalFetch;
@@ -927,7 +1217,7 @@ function setupMockifyer(config) {
927
1217
  fetchClient._originalFetch = originalFetch;
928
1218
  }
929
1219
  // Patch global fetch if useGlobalFetch is true
930
- if (config.useGlobalFetch) {
1220
+ if (resolvedConfig.useGlobalFetch) {
931
1221
  const mockifyerInstance = mockifyer;
932
1222
  const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
933
1223
  global.fetch = async function (input, init) {
@@ -1027,7 +1317,135 @@ function setupMockifyer(config) {
1027
1317
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1028
1318
  return extendedClient;
1029
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; } });
1030
1448
  // Re-export types from core
1031
1449
  __exportStar(require("@sgedda/mockifyer-core"), exports);
1032
- // Export React Native helpers
1033
- __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).