@sgedda/mockifyer-fetch 1.8.26 → 1.8.33
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/clients/fetch-client.d.ts +9 -3
- package/dist/clients/fetch-client.js +45 -65
- package/dist/index.d.ts +13 -2
- package/dist/index.js +311 -63
- package/dist/metro-config.js +24 -5
- package/dist/metro-sync-middleware.js +51 -1
- package/dist/react-native.d.ts +35 -0
- package/dist/react-native.js +110 -29
- package/dist/utils/dashboard-redis-health.d.ts +1 -0
- package/dist/utils/dashboard-redis-health.js +6 -0
- package/dist/utils/join-proxy-dashboard-api-url.d.ts +1 -11
- package/dist/utils/join-proxy-dashboard-api-url.js +3 -16
- package/package.json +14 -2
- package/src/clients/fetch-client.ts +68 -72
- package/src/index.ts +446 -80
- package/src/metro-config.ts +28 -5
- package/src/metro-sync-middleware.ts +67 -1
- package/src/react-native.ts +170 -42
- package/src/utils/dashboard-redis-health.ts +5 -0
- package/src/utils/join-proxy-dashboard-api-url.ts +1 -15
package/src/index.ts
CHANGED
|
@@ -36,8 +36,18 @@ import {
|
|
|
36
36
|
prepareMockResponseBody,
|
|
37
37
|
getCurrentDate,
|
|
38
38
|
shouldExcludeUrl,
|
|
39
|
+
resolveRecordingExclusions,
|
|
40
|
+
shouldExcludeRecording,
|
|
39
41
|
mockPassesThroughToRealApi,
|
|
42
|
+
mockShouldServeStoredBody,
|
|
43
|
+
mockShouldBeIncludedInRequestMatch,
|
|
44
|
+
buildClientResponseFromLiveCapture,
|
|
45
|
+
buildMockDataAfterLiveCapture,
|
|
46
|
+
resolveShouldPersistLiveCapture,
|
|
47
|
+
resolveMockRecordingSaveDecision,
|
|
48
|
+
applyRecordingPassthroughFlag,
|
|
40
49
|
resolveClientId,
|
|
50
|
+
resolveExplicitClientIdOnly,
|
|
41
51
|
resolveProxyStrictLaneScenario,
|
|
42
52
|
registerMockifyerInstance,
|
|
43
53
|
logMockifyerInitSummary,
|
|
@@ -46,7 +56,22 @@ import {
|
|
|
46
56
|
resolveActivationMode,
|
|
47
57
|
shouldApplyMockifyer,
|
|
48
58
|
isExplicitProxyScenarioContext,
|
|
59
|
+
applyProxyRecordOnMissEnv,
|
|
60
|
+
mirrorProxyRecordingToClient,
|
|
61
|
+
initMockifyerForDashboardProxy as coreInitMockifyerForDashboardProxy,
|
|
62
|
+
initMockifyerForLocalFilesystem as coreInitMockifyerForLocalFilesystem,
|
|
63
|
+
type InitMockifyerForDashboardProxyOptions,
|
|
64
|
+
type InitMockifyerForLocalFilesystemOptions,
|
|
65
|
+
newRecordingUsesAlwaysUseRealApi,
|
|
66
|
+
shouldBlockLocalMockRecording,
|
|
67
|
+
resolveStrictScenarioResolution,
|
|
49
68
|
type MockifyerActivationMode,
|
|
69
|
+
emitMockifyerNetworkEvent,
|
|
70
|
+
networkEventHashFromRequestKey,
|
|
71
|
+
resolveRecordResponses,
|
|
72
|
+
applyOutboundRequestCorrelation,
|
|
73
|
+
type RequestCorrelationContext,
|
|
74
|
+
installNodeInboundRequestCorrelationCapture,
|
|
50
75
|
} from '@sgedda/mockifyer-core';
|
|
51
76
|
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
52
77
|
|
|
@@ -66,6 +91,42 @@ class MockifyerClass {
|
|
|
66
91
|
private testGenerator?: TestGenerator;
|
|
67
92
|
private readonly activationMode: MockifyerActivationMode;
|
|
68
93
|
|
|
94
|
+
/** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
|
|
95
|
+
private logNetworkEvent(
|
|
96
|
+
partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & { transport?: 'fetch' },
|
|
97
|
+
correlation?: RequestCorrelationContext
|
|
98
|
+
): void {
|
|
99
|
+
if (this.config.proxy?.baseUrl) return;
|
|
100
|
+
const scenario =
|
|
101
|
+
this.config.proxy?.scenario?.trim() ||
|
|
102
|
+
getCurrentScenario(this.config.mockDataPath);
|
|
103
|
+
emitMockifyerNetworkEvent({
|
|
104
|
+
config: this.config,
|
|
105
|
+
scenario,
|
|
106
|
+
clientId: this.config.clientId,
|
|
107
|
+
event: {
|
|
108
|
+
...partial,
|
|
109
|
+
transport: partial.transport ?? 'fetch',
|
|
110
|
+
requestId: correlation?.requestId ?? partial.requestId,
|
|
111
|
+
parentRequestId: correlation?.parentRequestId ?? partial.parentRequestId,
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private stashRequestCorrelation(config: unknown, correlation: RequestCorrelationContext): void {
|
|
117
|
+
(config as { __mockifyer_requestId?: string; __mockifyer_parentRequestId?: string }).__mockifyer_requestId =
|
|
118
|
+
correlation.requestId;
|
|
119
|
+
(config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId =
|
|
120
|
+
correlation.parentRequestId;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
|
|
124
|
+
const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
|
|
125
|
+
if (!requestId) return undefined;
|
|
126
|
+
const parentRequestId = (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId;
|
|
127
|
+
return parentRequestId ? { requestId, parentRequestId } : { requestId };
|
|
128
|
+
}
|
|
129
|
+
|
|
69
130
|
constructor(config: MockifyerConfig) {
|
|
70
131
|
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
71
132
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
@@ -131,11 +192,27 @@ class MockifyerClass {
|
|
|
131
192
|
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
132
193
|
if (launchClientId) {
|
|
133
194
|
this.config.clientId = launchClientId;
|
|
195
|
+
} else if (
|
|
196
|
+
resolveStrictScenarioResolution(this.config) &&
|
|
197
|
+
Boolean(this.config.proxy?.baseUrl?.trim())
|
|
198
|
+
) {
|
|
199
|
+
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
200
|
+
this.config.clientId = resolveExplicitClientIdOnly(this.config);
|
|
134
201
|
} else {
|
|
135
202
|
this.config.clientId = resolveClientId(this.config);
|
|
136
203
|
}
|
|
137
204
|
this.activationMode = resolveActivationMode(this.config);
|
|
138
205
|
|
|
206
|
+
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
207
|
+
const raw =
|
|
208
|
+
typeof process !== 'undefined'
|
|
209
|
+
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
210
|
+
: '';
|
|
211
|
+
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
|
|
212
|
+
this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
139
216
|
// Initialize test generator if test generation is enabled
|
|
140
217
|
if (config.generateTests?.enabled) {
|
|
141
218
|
this.testGenerator = new TestGenerator();
|
|
@@ -174,6 +251,7 @@ class MockifyerClass {
|
|
|
174
251
|
clientId: this.config.clientId,
|
|
175
252
|
getClientId: () => this.config.clientId,
|
|
176
253
|
getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
|
|
254
|
+
getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
|
|
177
255
|
deviceId: (this.config as any).deviceId,
|
|
178
256
|
});
|
|
179
257
|
|
|
@@ -206,7 +284,16 @@ class MockifyerClass {
|
|
|
206
284
|
return generateRequestKeyUtil(request);
|
|
207
285
|
}
|
|
208
286
|
|
|
209
|
-
|
|
287
|
+
/** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
|
|
288
|
+
private usesDashboardProxy(): boolean {
|
|
289
|
+
const baseUrl = this.config.proxy?.baseUrl;
|
|
290
|
+
return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async findBestMatchingMock(
|
|
294
|
+
request: StoredRequest,
|
|
295
|
+
options?: { includePassthroughMocks?: boolean }
|
|
296
|
+
): Promise<CachedMockData | undefined> {
|
|
210
297
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
211
298
|
const requestUrl = request?.url || '';
|
|
212
299
|
if (requestUrl.includes('/mockifyer-save') ||
|
|
@@ -226,13 +313,16 @@ class MockifyerClass {
|
|
|
226
313
|
|
|
227
314
|
// Use database provider if available, otherwise fallback to filesystem
|
|
228
315
|
if (this.databaseProvider) {
|
|
229
|
-
return await this.findBestMatchingMockFromProvider(request);
|
|
316
|
+
return await this.findBestMatchingMockFromProvider(request, options);
|
|
230
317
|
}
|
|
231
318
|
// Fallback to Node.js filesystem
|
|
232
|
-
return this.findBestMatchingMockFromFiles(request);
|
|
319
|
+
return this.findBestMatchingMockFromFiles(request, options);
|
|
233
320
|
}
|
|
234
321
|
|
|
235
|
-
private async findBestMatchingMockFromProvider(
|
|
322
|
+
private async findBestMatchingMockFromProvider(
|
|
323
|
+
request: StoredRequest,
|
|
324
|
+
options?: { includePassthroughMocks?: boolean }
|
|
325
|
+
): Promise<CachedMockData | undefined> {
|
|
236
326
|
if (!this.databaseProvider) {
|
|
237
327
|
return undefined;
|
|
238
328
|
}
|
|
@@ -255,7 +345,7 @@ class MockifyerClass {
|
|
|
255
345
|
}
|
|
256
346
|
|
|
257
347
|
// Try exact match first
|
|
258
|
-
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
|
|
348
|
+
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
|
|
259
349
|
if (exactMatch) {
|
|
260
350
|
return exactMatch;
|
|
261
351
|
}
|
|
@@ -272,7 +362,11 @@ class MockifyerClass {
|
|
|
272
362
|
return undefined;
|
|
273
363
|
}
|
|
274
364
|
|
|
275
|
-
private findBestMatchingMockFromFiles(
|
|
365
|
+
private findBestMatchingMockFromFiles(
|
|
366
|
+
request: StoredRequest,
|
|
367
|
+
options?: { includePassthroughMocks?: boolean }
|
|
368
|
+
): CachedMockData | undefined {
|
|
369
|
+
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
276
370
|
// Only use fs if available (Node.js environment)
|
|
277
371
|
// This method should never be called when using a database provider
|
|
278
372
|
if (!fs || !path) {
|
|
@@ -313,7 +407,7 @@ class MockifyerClass {
|
|
|
313
407
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
314
408
|
|
|
315
409
|
if (mockKey === requestKey) {
|
|
316
|
-
if (
|
|
410
|
+
if (mockShouldBeIncludedInRequestMatch(mockData, { includePassthroughMocks })) {
|
|
317
411
|
exactMatch = { mockData, filename: file, filePath };
|
|
318
412
|
break;
|
|
319
413
|
}
|
|
@@ -438,6 +532,7 @@ class MockifyerClass {
|
|
|
438
532
|
useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
|
|
439
533
|
})
|
|
440
534
|
) {
|
|
535
|
+
applyOutboundRequestCorrelation(config);
|
|
441
536
|
(config as any).__mockifyer_bypass = true;
|
|
442
537
|
return config;
|
|
443
538
|
}
|
|
@@ -450,6 +545,9 @@ class MockifyerClass {
|
|
|
450
545
|
return config;
|
|
451
546
|
}
|
|
452
547
|
|
|
548
|
+
const correlation = applyOutboundRequestCorrelation(config);
|
|
549
|
+
this.stashRequestCorrelation(config, correlation);
|
|
550
|
+
|
|
453
551
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
454
552
|
const rawParams = config.params || {};
|
|
455
553
|
const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
|
|
@@ -471,6 +569,12 @@ class MockifyerClass {
|
|
|
471
569
|
(config as any).__mockifyer_requestKey = requestKey;
|
|
472
570
|
// Store request start time for duration calculation
|
|
473
571
|
(config as any).__mockifyer_startTime = Date.now();
|
|
572
|
+
|
|
573
|
+
// Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
|
|
574
|
+
// from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
|
|
575
|
+
if (this.usesDashboardProxy()) {
|
|
576
|
+
return config;
|
|
577
|
+
}
|
|
474
578
|
|
|
475
579
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
476
580
|
|
|
@@ -478,31 +582,49 @@ class MockifyerClass {
|
|
|
478
582
|
|
|
479
583
|
if (cachedMock) {
|
|
480
584
|
const { mockData, filename, filePath } = cachedMock;
|
|
585
|
+
if (mockShouldServeStoredBody(mockData)) {
|
|
586
|
+
logger.info(
|
|
587
|
+
`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
588
|
+
(filePath ? ` (${filePath})` : '')
|
|
589
|
+
);
|
|
590
|
+
this.logNetworkEvent(
|
|
591
|
+
{
|
|
592
|
+
method: (request.method || 'GET').toUpperCase(),
|
|
593
|
+
url: request.url,
|
|
594
|
+
source: 'mock-hit',
|
|
595
|
+
status: mockData.response.status,
|
|
596
|
+
requestHash: networkEventHashFromRequestKey(requestKey),
|
|
597
|
+
},
|
|
598
|
+
correlation
|
|
599
|
+
);
|
|
600
|
+
const responseHeaders = {
|
|
601
|
+
...mockData.response.headers,
|
|
602
|
+
'x-mockifyer': 'true',
|
|
603
|
+
'x-mockifyer-timestamp': mockData.timestamp,
|
|
604
|
+
'x-mockifyer-filename': filename,
|
|
605
|
+
'x-mockifyer-filepath': filePath
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
const mockResponse = {
|
|
609
|
+
data: prepareMockResponseBody(mockData, getCurrentDate),
|
|
610
|
+
status: mockData.response.status,
|
|
611
|
+
statusText: 'OK',
|
|
612
|
+
headers: responseHeaders,
|
|
613
|
+
config: config as any
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
return {
|
|
617
|
+
...config,
|
|
618
|
+
__mockResponse: Promise.resolve(mockResponse),
|
|
619
|
+
__mockifyer_requestKey: requestKey
|
|
620
|
+
} as any;
|
|
621
|
+
}
|
|
622
|
+
|
|
481
623
|
logger.info(
|
|
482
|
-
`[Mockifyer-Fetch]
|
|
624
|
+
`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
|
|
483
625
|
(filePath ? ` (${filePath})` : '')
|
|
484
626
|
);
|
|
485
|
-
|
|
486
|
-
...mockData.response.headers,
|
|
487
|
-
'x-mockifyer': 'true',
|
|
488
|
-
'x-mockifyer-timestamp': mockData.timestamp,
|
|
489
|
-
'x-mockifyer-filename': filename,
|
|
490
|
-
'x-mockifyer-filepath': filePath
|
|
491
|
-
};
|
|
492
|
-
|
|
493
|
-
const mockResponse = {
|
|
494
|
-
data: prepareMockResponseBody(mockData, getCurrentDate),
|
|
495
|
-
status: mockData.response.status,
|
|
496
|
-
statusText: 'OK',
|
|
497
|
-
headers: responseHeaders,
|
|
498
|
-
config: config as any
|
|
499
|
-
};
|
|
500
|
-
|
|
501
|
-
return {
|
|
502
|
-
...config,
|
|
503
|
-
__mockResponse: Promise.resolve(mockResponse),
|
|
504
|
-
__mockifyer_requestKey: requestKey
|
|
505
|
-
} as any;
|
|
627
|
+
(config as any).__mockifyer_matchedMock = cachedMock;
|
|
506
628
|
}
|
|
507
629
|
|
|
508
630
|
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
@@ -633,12 +755,71 @@ class MockifyerClass {
|
|
|
633
755
|
if (isMocked || isLimitReached) {
|
|
634
756
|
return response;
|
|
635
757
|
}
|
|
636
|
-
|
|
758
|
+
|
|
759
|
+
if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
|
|
760
|
+
await this.maybeMirrorProxyRecordingToClient(response);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
const matchedMock = (response.config as any).__mockifyer_matchedMock as CachedMockData | undefined;
|
|
764
|
+
if (matchedMock) {
|
|
765
|
+
const capturedResponse: StoredResponse = {
|
|
766
|
+
status: response.status,
|
|
767
|
+
data: response.data,
|
|
768
|
+
headers: (response.headers as Record<string, string>) || {},
|
|
769
|
+
};
|
|
770
|
+
const startTime = (response.config as any).__mockifyer_startTime;
|
|
771
|
+
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
772
|
+
|
|
773
|
+
if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
|
|
774
|
+
await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const clientResponse = buildClientResponseFromLiveCapture(
|
|
778
|
+
matchedMock.mockData,
|
|
779
|
+
capturedResponse,
|
|
780
|
+
getCurrentDate
|
|
781
|
+
);
|
|
782
|
+
response.data = clientResponse.data;
|
|
783
|
+
response.status = clientResponse.status;
|
|
784
|
+
delete (response.config as any).__mockifyer_matchedMock;
|
|
785
|
+
|
|
786
|
+
const reqUrl = response.config?.url || url;
|
|
787
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
788
|
+
this.logNetworkEvent(
|
|
789
|
+
{
|
|
790
|
+
method: reqMethod,
|
|
791
|
+
url: reqUrl,
|
|
792
|
+
source: 'upstream',
|
|
793
|
+
status: response.status,
|
|
794
|
+
durationMs,
|
|
795
|
+
},
|
|
796
|
+
this.readRequestCorrelation(response.config)
|
|
797
|
+
);
|
|
798
|
+
return response;
|
|
799
|
+
}
|
|
800
|
+
|
|
637
801
|
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
638
802
|
// When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
|
|
639
803
|
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
640
804
|
await this.saveResponse(response);
|
|
641
805
|
}
|
|
806
|
+
|
|
807
|
+
const reqUrl = response.config?.url || url;
|
|
808
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
809
|
+
this.logNetworkEvent(
|
|
810
|
+
{
|
|
811
|
+
method: reqMethod,
|
|
812
|
+
url: reqUrl,
|
|
813
|
+
source: 'upstream',
|
|
814
|
+
status: response.status,
|
|
815
|
+
durationMs:
|
|
816
|
+
typeof response.config?.metadata?.durationMs === 'number'
|
|
817
|
+
? response.config.metadata.durationMs
|
|
818
|
+
: undefined,
|
|
819
|
+
},
|
|
820
|
+
this.readRequestCorrelation(response.config)
|
|
821
|
+
);
|
|
822
|
+
|
|
642
823
|
return response;
|
|
643
824
|
},
|
|
644
825
|
async (error: any) => {
|
|
@@ -646,11 +827,97 @@ class MockifyerClass {
|
|
|
646
827
|
if (requestKey) {
|
|
647
828
|
this.processingRequests.delete(requestKey);
|
|
648
829
|
}
|
|
830
|
+
const reqUrl = error.config?.url || '';
|
|
831
|
+
if (reqUrl) {
|
|
832
|
+
this.logNetworkEvent(
|
|
833
|
+
{
|
|
834
|
+
method: (error.config?.method || 'GET').toUpperCase(),
|
|
835
|
+
url: reqUrl,
|
|
836
|
+
source: 'error',
|
|
837
|
+
status: error.response?.status,
|
|
838
|
+
errorMessage: error?.message ?? String(error),
|
|
839
|
+
},
|
|
840
|
+
this.readRequestCorrelation(error.config)
|
|
841
|
+
);
|
|
842
|
+
}
|
|
649
843
|
throw error;
|
|
650
844
|
}
|
|
651
845
|
);
|
|
652
846
|
}
|
|
653
847
|
|
|
848
|
+
/**
|
|
849
|
+
* When dashboard proxy records to Redis, optionally persist the same payload next to the client
|
|
850
|
+
* (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
|
|
851
|
+
*/
|
|
852
|
+
private async maybeMirrorProxyRecordingToClient(response: HTTPResponse): Promise<void> {
|
|
853
|
+
const rec = response.mockifyerProxyRecording;
|
|
854
|
+
if (!rec?.recordedToStore || !rec.storedMock) {
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const hash = rec.hash?.trim();
|
|
858
|
+
const scenarioName = rec.scenarioName?.trim();
|
|
859
|
+
const mockData = rec.storedMock as MockData;
|
|
860
|
+
const providerType = this.config.databaseProvider?.type;
|
|
861
|
+
|
|
862
|
+
await mirrorProxyRecordingToClient({
|
|
863
|
+
config: this.config,
|
|
864
|
+
mockDataPath: this.config.mockDataPath,
|
|
865
|
+
recording: rec,
|
|
866
|
+
databaseProvider: this.databaseProvider,
|
|
867
|
+
databaseProviderInitPromise: this.databaseProviderInitPromise,
|
|
868
|
+
logPrefix: 'Mockifyer-Fetch',
|
|
869
|
+
});
|
|
870
|
+
|
|
871
|
+
if (providerType === 'hybrid' && hash && scenarioName && mockData) {
|
|
872
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
873
|
+
} else if (!fs && hash && scenarioName && mockData) {
|
|
874
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
private async tryMirrorProxyRecordingViaMetro(
|
|
879
|
+
mockData: MockData,
|
|
880
|
+
scenarioName: string,
|
|
881
|
+
hash: string
|
|
882
|
+
): Promise<void> {
|
|
883
|
+
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
884
|
+
const fetchFn = (global as any).__mockifyer_original_fetch || fetch;
|
|
885
|
+
if (!fetchFn) {
|
|
886
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
try {
|
|
890
|
+
const body = JSON.stringify({
|
|
891
|
+
__mockifyerProxyMirror: true,
|
|
892
|
+
mockData,
|
|
893
|
+
scenarioName,
|
|
894
|
+
relativePath: `redis/${hash}.json`,
|
|
895
|
+
});
|
|
896
|
+
const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
|
|
897
|
+
method: 'POST',
|
|
898
|
+
headers: { 'Content-Type': 'application/json' },
|
|
899
|
+
body,
|
|
900
|
+
});
|
|
901
|
+
const text = await res.text().catch(() => '');
|
|
902
|
+
if (!res.ok) {
|
|
903
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
try {
|
|
907
|
+
const parsed = JSON.parse(text) as { success?: boolean; error?: string };
|
|
908
|
+
if (parsed.success === false) {
|
|
909
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
} catch {
|
|
913
|
+
// non-JSON response
|
|
914
|
+
}
|
|
915
|
+
logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
|
|
916
|
+
} catch (e) {
|
|
917
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
654
921
|
private async saveResponse(response: HTTPResponse): Promise<void> {
|
|
655
922
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
656
923
|
if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
|
|
@@ -662,11 +929,25 @@ class MockifyerClass {
|
|
|
662
929
|
if (this.config.proxy?.baseUrl) {
|
|
663
930
|
return;
|
|
664
931
|
}
|
|
932
|
+
|
|
933
|
+
if (shouldBlockLocalMockRecording(this.config)) {
|
|
934
|
+
logger.info(
|
|
935
|
+
'[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).'
|
|
936
|
+
);
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
665
939
|
|
|
666
940
|
const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
|
|
941
|
+
const recordingExclusions = resolveRecordingExclusions(this.config);
|
|
667
942
|
if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
|
|
668
943
|
return;
|
|
669
944
|
}
|
|
945
|
+
if (
|
|
946
|
+
url &&
|
|
947
|
+
shouldExcludeRecording(url, recordingExclusions, this.config.baseUrl)
|
|
948
|
+
) {
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
670
951
|
|
|
671
952
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
672
953
|
// This is a defense-in-depth measure
|
|
@@ -703,97 +984,126 @@ class MockifyerClass {
|
|
|
703
984
|
const rawParams = response.config.params || {};
|
|
704
985
|
const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
|
|
705
986
|
|
|
706
|
-
const
|
|
987
|
+
const saveLookupRequest: StoredRequest = {
|
|
707
988
|
method: response.config.method?.toUpperCase() || 'GET',
|
|
708
989
|
url: response.config.url || '',
|
|
709
990
|
headers: {},
|
|
710
991
|
data: response.config.data,
|
|
711
|
-
queryParams: normalizedParams
|
|
712
|
-
}
|
|
713
|
-
|
|
992
|
+
queryParams: normalizedParams,
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
const requestKey = this.generateRequestKey(saveLookupRequest);
|
|
996
|
+
|
|
714
997
|
if (this.savingResponses.has(requestKey)) {
|
|
715
998
|
return;
|
|
716
999
|
}
|
|
717
|
-
|
|
1000
|
+
|
|
1001
|
+
const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
|
|
1002
|
+
includePassthroughMocks: true,
|
|
1003
|
+
});
|
|
1004
|
+
|
|
1005
|
+
const saveDecision = resolveMockRecordingSaveDecision(
|
|
1006
|
+
this.config,
|
|
1007
|
+
existingMock?.mockData
|
|
1008
|
+
);
|
|
1009
|
+
|
|
1010
|
+
if (saveDecision.action === 'skip') {
|
|
1011
|
+
if (existingMock && mockPassesThroughToRealApi(existingMock.mockData)) {
|
|
1012
|
+
logger.info(
|
|
1013
|
+
`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
718
1019
|
this.savingResponses.add(requestKey);
|
|
719
|
-
|
|
1020
|
+
|
|
720
1021
|
try {
|
|
721
|
-
|
|
722
|
-
const
|
|
723
|
-
const
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
// Generate or reuse sessionId
|
|
1022
|
+
const rawParamsForSave = response.config.params || {};
|
|
1023
|
+
const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
|
|
1024
|
+
const normalizedParamsForSave =
|
|
1025
|
+
anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
1026
|
+
? anonymizedQueryParams
|
|
1027
|
+
: undefined;
|
|
1028
|
+
|
|
729
1029
|
const now = Date.now();
|
|
730
|
-
if (!this.currentSessionId ||
|
|
731
|
-
// Generate new session ID
|
|
1030
|
+
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
732
1031
|
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
733
1032
|
this.sessionStartTime = now;
|
|
734
1033
|
}
|
|
735
1034
|
|
|
736
|
-
// Calculate request duration if start time is available
|
|
737
1035
|
const startTime = (response.config as any).__mockifyer_startTime;
|
|
738
1036
|
const duration = startTime ? Date.now() - startTime : undefined;
|
|
739
1037
|
|
|
1038
|
+
const correlation = this.readRequestCorrelation(response.config);
|
|
1039
|
+
|
|
740
1040
|
const mockData: MockData = {
|
|
741
1041
|
request: {
|
|
742
1042
|
method: response.config?.method?.toUpperCase() || 'GET',
|
|
743
1043
|
url: response.config?.url || '',
|
|
744
1044
|
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
745
1045
|
data: response.config?.data,
|
|
746
|
-
queryParams:
|
|
1046
|
+
queryParams: normalizedParamsForSave,
|
|
747
1047
|
},
|
|
748
1048
|
response: {
|
|
749
1049
|
status: response.status,
|
|
750
1050
|
data: response.data,
|
|
751
|
-
headers: response.headers || {}
|
|
1051
|
+
headers: response.headers || {},
|
|
752
1052
|
},
|
|
753
1053
|
timestamp: new Date().toISOString(),
|
|
754
1054
|
duration,
|
|
755
|
-
sessionId:
|
|
1055
|
+
sessionId:
|
|
1056
|
+
saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1057
|
+
? existingMock.mockData.sessionId
|
|
1058
|
+
: this.currentSessionId,
|
|
1059
|
+
requestId: correlation?.requestId,
|
|
1060
|
+
parentRequestId: correlation?.parentRequestId,
|
|
1061
|
+
...(newRecordingUsesAlwaysUseRealApi() ? { alwaysUseRealApi: true as const } : {}),
|
|
756
1062
|
};
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
1063
|
+
|
|
1064
|
+
applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
|
|
1065
|
+
|
|
760
1066
|
if (this.databaseProvider) {
|
|
761
1067
|
try {
|
|
762
1068
|
await this.databaseProvider.save(mockData);
|
|
763
|
-
|
|
764
|
-
// Generate test if enabled (try to write test files even with database provider)
|
|
765
|
-
// Generate test if enabled
|
|
1069
|
+
|
|
766
1070
|
if (this.config.generateTests?.enabled) {
|
|
767
1071
|
await this.generateTestForMock(mockData);
|
|
768
1072
|
}
|
|
769
1073
|
} catch (error) {
|
|
770
|
-
console.error(
|
|
1074
|
+
console.error(
|
|
1075
|
+
`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`,
|
|
1076
|
+
error
|
|
1077
|
+
);
|
|
771
1078
|
throw error;
|
|
772
1079
|
}
|
|
773
1080
|
} else if (fs && path) {
|
|
774
|
-
// Fallback to Node.js filesystem (only if fs/path are available)
|
|
775
|
-
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
776
|
-
const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
|
|
777
|
-
const domain = urlParts[0].replace(/\./g, '_');
|
|
778
|
-
const urlPathPart = urlParts.slice(1).join('_') || 'root';
|
|
779
|
-
const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
|
|
780
1081
|
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
781
1082
|
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
782
1083
|
ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
783
|
-
|
|
784
|
-
// Check request limit before saving (only if limit is set via env var)
|
|
1084
|
+
|
|
785
1085
|
const limitCheck = checkRequestLimit(this.config.mockDataPath);
|
|
786
1086
|
if (limitCheck.limitReached && limitCheck.error) {
|
|
787
1087
|
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
788
|
-
// Don't throw - just log and return to prevent app crash
|
|
789
1088
|
return;
|
|
790
1089
|
}
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
1090
|
+
|
|
1091
|
+
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1092
|
+
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1093
|
+
logger.info(
|
|
1094
|
+
`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
|
|
1095
|
+
);
|
|
1096
|
+
} else {
|
|
1097
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1098
|
+
const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
|
|
1099
|
+
const domain = urlParts[0].replace(/\./g, '_');
|
|
1100
|
+
const urlPathPart = urlParts.slice(1).join('_') || 'root';
|
|
1101
|
+
const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
|
|
1102
|
+
const filePath = path.join(scenarioPath, filename);
|
|
1103
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1104
|
+
logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
1105
|
+
}
|
|
1106
|
+
|
|
797
1107
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
798
1108
|
await this.generateTestForMock(mockData);
|
|
799
1109
|
}
|
|
@@ -805,6 +1115,24 @@ class MockifyerClass {
|
|
|
805
1115
|
}
|
|
806
1116
|
}
|
|
807
1117
|
|
|
1118
|
+
private async persistMatchedMockAfterLiveCapture(
|
|
1119
|
+
cachedMock: CachedMockData,
|
|
1120
|
+
capturedResponse: StoredResponse,
|
|
1121
|
+
durationMs?: number
|
|
1122
|
+
): Promise<void> {
|
|
1123
|
+
const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
|
|
1124
|
+
|
|
1125
|
+
if (this.databaseProvider) {
|
|
1126
|
+
await this.databaseProvider.save(updated);
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
if (fs && cachedMock.filePath) {
|
|
1131
|
+
fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
|
|
1132
|
+
logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
|
|
808
1136
|
/**
|
|
809
1137
|
* Simple path resolution fallback for React Native (when path module is stubbed)
|
|
810
1138
|
*/
|
|
@@ -1058,8 +1386,13 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
1058
1386
|
}
|
|
1059
1387
|
|
|
1060
1388
|
export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
1389
|
+
// Node-only inbound capture; safe on RN (no-op when not on Node).
|
|
1390
|
+
if (typeof installNodeInboundRequestCorrelationCapture === 'function') {
|
|
1391
|
+
installNodeInboundRequestCorrelationCapture();
|
|
1392
|
+
}
|
|
1393
|
+
const resolvedConfig = applyProxyRecordOnMissEnv(config);
|
|
1061
1394
|
// Initialize logger with config level (default to 'info' if not specified)
|
|
1062
|
-
setLogLevel(
|
|
1395
|
+
setLogLevel(resolvedConfig.logging || 'info');
|
|
1063
1396
|
|
|
1064
1397
|
// Set environment variables for Metro middleware to read test generation config
|
|
1065
1398
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
@@ -1086,11 +1419,11 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1086
1419
|
}
|
|
1087
1420
|
}
|
|
1088
1421
|
|
|
1089
|
-
initializeDateManipulation(
|
|
1090
|
-
initializeScenario(
|
|
1091
|
-
|
|
1422
|
+
initializeDateManipulation(resolvedConfig);
|
|
1423
|
+
initializeScenario(resolvedConfig);
|
|
1424
|
+
|
|
1092
1425
|
|
|
1093
|
-
const mockifyer = new MockifyerClass(
|
|
1426
|
+
const mockifyer = new MockifyerClass(resolvedConfig);
|
|
1094
1427
|
const httpClient = mockifyer.getHTTPClient();
|
|
1095
1428
|
|
|
1096
1429
|
// Always store original fetch (even if not patching global)
|
|
@@ -1108,7 +1441,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1108
1441
|
}
|
|
1109
1442
|
|
|
1110
1443
|
// Patch global fetch if useGlobalFetch is true
|
|
1111
|
-
if (
|
|
1444
|
+
if (resolvedConfig.useGlobalFetch) {
|
|
1112
1445
|
const mockifyerInstance = mockifyer;
|
|
1113
1446
|
const originalFetchForPatched = (global as any).__mockifyer_original_fetch || originalFetch;
|
|
1114
1447
|
|
|
@@ -1221,9 +1554,42 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1221
1554
|
return extendedClient;
|
|
1222
1555
|
}
|
|
1223
1556
|
|
|
1557
|
+
export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
|
|
1558
|
+
|
|
1559
|
+
/**
|
|
1560
|
+
* Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
|
|
1561
|
+
* For full control, use {@link setupMockifyer} directly.
|
|
1562
|
+
*/
|
|
1563
|
+
export async function initMockifyerForDashboardProxy(
|
|
1564
|
+
options: InitMockifyerForDashboardProxyOptions
|
|
1565
|
+
): Promise<MockifyerInstance> {
|
|
1566
|
+
return coreInitMockifyerForDashboardProxy(
|
|
1567
|
+
{ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true },
|
|
1568
|
+
setupMockifyer
|
|
1569
|
+
);
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* Preset: local filesystem mocks. No dashboard proxy.
|
|
1574
|
+
*/
|
|
1575
|
+
export function initMockifyerForLocalFilesystem(
|
|
1576
|
+
options: InitMockifyerForLocalFilesystemOptions = {}
|
|
1577
|
+
): MockifyerInstance {
|
|
1578
|
+
return coreInitMockifyerForLocalFilesystem(
|
|
1579
|
+
{ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true },
|
|
1580
|
+
setupMockifyer
|
|
1581
|
+
);
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
|
|
1585
|
+
export {
|
|
1586
|
+
canUseDashboardRedisProxy,
|
|
1587
|
+
canUseDashboardCentralProxy,
|
|
1588
|
+
} from './utils/dashboard-redis-health';
|
|
1589
|
+
|
|
1224
1590
|
// Re-export types from core
|
|
1225
1591
|
export * from '@sgedda/mockifyer-core';
|
|
1226
1592
|
|
|
1227
|
-
//
|
|
1228
|
-
|
|
1593
|
+
// React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
|
|
1594
|
+
// pulling optional `react-native-launch-arguments` into Node/Next webpack bundles).
|
|
1229
1595
|
|