@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/clients/fetch-client.d.ts +9 -3
- package/dist/clients/fetch-client.js +71 -17
- package/dist/index.d.ts +59 -1
- package/dist/index.js +480 -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 +19 -0
- package/dist/utils/dashboard-redis-health.js +49 -0
- package/package.json +14 -2
- package/src/clients/fetch-client.ts +139 -28
- package/src/index.ts +682 -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 +58 -0
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,11 +56,47 @@ import {
|
|
|
46
56
|
resolveActivationMode,
|
|
47
57
|
shouldApplyMockifyer,
|
|
48
58
|
isExplicitProxyScenarioContext,
|
|
59
|
+
parseProxyRecordOnMissEnv,
|
|
60
|
+
newRecordingUsesAlwaysUseRealApi,
|
|
61
|
+
shouldBlockLocalMockRecording,
|
|
62
|
+
resolveStrictScenarioResolution,
|
|
49
63
|
type MockifyerActivationMode,
|
|
64
|
+
emitMockifyerNetworkEvent,
|
|
65
|
+
networkEventHashFromRequestKey,
|
|
66
|
+
resolveRecordResponses,
|
|
67
|
+
applyOutboundRequestCorrelation,
|
|
68
|
+
type RequestCorrelationContext,
|
|
69
|
+
installNodeInboundRequestCorrelationCapture,
|
|
50
70
|
} from '@sgedda/mockifyer-core';
|
|
51
71
|
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
52
72
|
|
|
53
73
|
import { FetchHTTPClient } from './clients/fetch-client';
|
|
74
|
+
import { canUseDashboardRedisProxy } from './utils/dashboard-redis-health';
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* When `proxy.baseUrl` is set and `proxy.recordOnMiss` is omitted, apply `MOCKIFYER_PROXY_RECORD_ON_MISS` if set.
|
|
78
|
+
*/
|
|
79
|
+
function applyProxyRecordOnMissEnv(config: MockifyerConfig): MockifyerConfig {
|
|
80
|
+
const proxy = config.proxy;
|
|
81
|
+
const baseUrl = proxy?.baseUrl?.trim();
|
|
82
|
+
if (!proxy || !baseUrl || proxy.recordOnMiss !== undefined) {
|
|
83
|
+
return config;
|
|
84
|
+
}
|
|
85
|
+
const parsed = parseProxyRecordOnMissEnv();
|
|
86
|
+
if (parsed === undefined) {
|
|
87
|
+
return config;
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
...config,
|
|
91
|
+
proxy: {
|
|
92
|
+
baseUrl: proxy.baseUrl,
|
|
93
|
+
scenario: proxy.scenario,
|
|
94
|
+
recordOnMiss: parsed,
|
|
95
|
+
strictLaneScenario: proxy.strictLaneScenario,
|
|
96
|
+
mirrorRecordedMocksToClient: proxy.mirrorRecordedMocksToClient,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
54
100
|
|
|
55
101
|
class MockifyerClass {
|
|
56
102
|
private config: MockifyerConfig;
|
|
@@ -66,6 +112,42 @@ class MockifyerClass {
|
|
|
66
112
|
private testGenerator?: TestGenerator;
|
|
67
113
|
private readonly activationMode: MockifyerActivationMode;
|
|
68
114
|
|
|
115
|
+
/** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
|
|
116
|
+
private logNetworkEvent(
|
|
117
|
+
partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & { transport?: 'fetch' },
|
|
118
|
+
correlation?: RequestCorrelationContext
|
|
119
|
+
): void {
|
|
120
|
+
if (this.config.proxy?.baseUrl) return;
|
|
121
|
+
const scenario =
|
|
122
|
+
this.config.proxy?.scenario?.trim() ||
|
|
123
|
+
getCurrentScenario(this.config.mockDataPath);
|
|
124
|
+
emitMockifyerNetworkEvent({
|
|
125
|
+
config: this.config,
|
|
126
|
+
scenario,
|
|
127
|
+
clientId: this.config.clientId,
|
|
128
|
+
event: {
|
|
129
|
+
...partial,
|
|
130
|
+
transport: partial.transport ?? 'fetch',
|
|
131
|
+
requestId: correlation?.requestId ?? partial.requestId,
|
|
132
|
+
parentRequestId: correlation?.parentRequestId ?? partial.parentRequestId,
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private stashRequestCorrelation(config: unknown, correlation: RequestCorrelationContext): void {
|
|
138
|
+
(config as { __mockifyer_requestId?: string; __mockifyer_parentRequestId?: string }).__mockifyer_requestId =
|
|
139
|
+
correlation.requestId;
|
|
140
|
+
(config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId =
|
|
141
|
+
correlation.parentRequestId;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
|
|
145
|
+
const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
|
|
146
|
+
if (!requestId) return undefined;
|
|
147
|
+
const parentRequestId = (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId;
|
|
148
|
+
return parentRequestId ? { requestId, parentRequestId } : { requestId };
|
|
149
|
+
}
|
|
150
|
+
|
|
69
151
|
constructor(config: MockifyerConfig) {
|
|
70
152
|
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
71
153
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
@@ -131,11 +213,27 @@ class MockifyerClass {
|
|
|
131
213
|
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
132
214
|
if (launchClientId) {
|
|
133
215
|
this.config.clientId = launchClientId;
|
|
216
|
+
} else if (
|
|
217
|
+
resolveStrictScenarioResolution(this.config) &&
|
|
218
|
+
Boolean(this.config.proxy?.baseUrl?.trim())
|
|
219
|
+
) {
|
|
220
|
+
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
221
|
+
this.config.clientId = resolveExplicitClientIdOnly(this.config);
|
|
134
222
|
} else {
|
|
135
223
|
this.config.clientId = resolveClientId(this.config);
|
|
136
224
|
}
|
|
137
225
|
this.activationMode = resolveActivationMode(this.config);
|
|
138
226
|
|
|
227
|
+
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
228
|
+
const raw =
|
|
229
|
+
typeof process !== 'undefined'
|
|
230
|
+
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
231
|
+
: '';
|
|
232
|
+
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
|
|
233
|
+
this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
139
237
|
// Initialize test generator if test generation is enabled
|
|
140
238
|
if (config.generateTests?.enabled) {
|
|
141
239
|
this.testGenerator = new TestGenerator();
|
|
@@ -174,6 +272,7 @@ class MockifyerClass {
|
|
|
174
272
|
clientId: this.config.clientId,
|
|
175
273
|
getClientId: () => this.config.clientId,
|
|
176
274
|
getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
|
|
275
|
+
getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
|
|
177
276
|
deviceId: (this.config as any).deviceId,
|
|
178
277
|
});
|
|
179
278
|
|
|
@@ -206,7 +305,16 @@ class MockifyerClass {
|
|
|
206
305
|
return generateRequestKeyUtil(request);
|
|
207
306
|
}
|
|
208
307
|
|
|
209
|
-
|
|
308
|
+
/** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
|
|
309
|
+
private usesDashboardProxy(): boolean {
|
|
310
|
+
const baseUrl = this.config.proxy?.baseUrl;
|
|
311
|
+
return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private async findBestMatchingMock(
|
|
315
|
+
request: StoredRequest,
|
|
316
|
+
options?: { includePassthroughMocks?: boolean }
|
|
317
|
+
): Promise<CachedMockData | undefined> {
|
|
210
318
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
211
319
|
const requestUrl = request?.url || '';
|
|
212
320
|
if (requestUrl.includes('/mockifyer-save') ||
|
|
@@ -226,13 +334,16 @@ class MockifyerClass {
|
|
|
226
334
|
|
|
227
335
|
// Use database provider if available, otherwise fallback to filesystem
|
|
228
336
|
if (this.databaseProvider) {
|
|
229
|
-
return await this.findBestMatchingMockFromProvider(request);
|
|
337
|
+
return await this.findBestMatchingMockFromProvider(request, options);
|
|
230
338
|
}
|
|
231
339
|
// Fallback to Node.js filesystem
|
|
232
|
-
return this.findBestMatchingMockFromFiles(request);
|
|
340
|
+
return this.findBestMatchingMockFromFiles(request, options);
|
|
233
341
|
}
|
|
234
342
|
|
|
235
|
-
private async findBestMatchingMockFromProvider(
|
|
343
|
+
private async findBestMatchingMockFromProvider(
|
|
344
|
+
request: StoredRequest,
|
|
345
|
+
options?: { includePassthroughMocks?: boolean }
|
|
346
|
+
): Promise<CachedMockData | undefined> {
|
|
236
347
|
if (!this.databaseProvider) {
|
|
237
348
|
return undefined;
|
|
238
349
|
}
|
|
@@ -255,7 +366,7 @@ class MockifyerClass {
|
|
|
255
366
|
}
|
|
256
367
|
|
|
257
368
|
// Try exact match first
|
|
258
|
-
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
|
|
369
|
+
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
|
|
259
370
|
if (exactMatch) {
|
|
260
371
|
return exactMatch;
|
|
261
372
|
}
|
|
@@ -272,7 +383,11 @@ class MockifyerClass {
|
|
|
272
383
|
return undefined;
|
|
273
384
|
}
|
|
274
385
|
|
|
275
|
-
private findBestMatchingMockFromFiles(
|
|
386
|
+
private findBestMatchingMockFromFiles(
|
|
387
|
+
request: StoredRequest,
|
|
388
|
+
options?: { includePassthroughMocks?: boolean }
|
|
389
|
+
): CachedMockData | undefined {
|
|
390
|
+
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
276
391
|
// Only use fs if available (Node.js environment)
|
|
277
392
|
// This method should never be called when using a database provider
|
|
278
393
|
if (!fs || !path) {
|
|
@@ -313,7 +428,7 @@ class MockifyerClass {
|
|
|
313
428
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
314
429
|
|
|
315
430
|
if (mockKey === requestKey) {
|
|
316
|
-
if (
|
|
431
|
+
if (mockShouldBeIncludedInRequestMatch(mockData, { includePassthroughMocks })) {
|
|
317
432
|
exactMatch = { mockData, filename: file, filePath };
|
|
318
433
|
break;
|
|
319
434
|
}
|
|
@@ -438,6 +553,7 @@ class MockifyerClass {
|
|
|
438
553
|
useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
|
|
439
554
|
})
|
|
440
555
|
) {
|
|
556
|
+
applyOutboundRequestCorrelation(config);
|
|
441
557
|
(config as any).__mockifyer_bypass = true;
|
|
442
558
|
return config;
|
|
443
559
|
}
|
|
@@ -450,6 +566,9 @@ class MockifyerClass {
|
|
|
450
566
|
return config;
|
|
451
567
|
}
|
|
452
568
|
|
|
569
|
+
const correlation = applyOutboundRequestCorrelation(config);
|
|
570
|
+
this.stashRequestCorrelation(config, correlation);
|
|
571
|
+
|
|
453
572
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
454
573
|
const rawParams = config.params || {};
|
|
455
574
|
const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
|
|
@@ -471,6 +590,12 @@ class MockifyerClass {
|
|
|
471
590
|
(config as any).__mockifyer_requestKey = requestKey;
|
|
472
591
|
// Store request start time for duration calculation
|
|
473
592
|
(config as any).__mockifyer_startTime = Date.now();
|
|
593
|
+
|
|
594
|
+
// Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
|
|
595
|
+
// from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
|
|
596
|
+
if (this.usesDashboardProxy()) {
|
|
597
|
+
return config;
|
|
598
|
+
}
|
|
474
599
|
|
|
475
600
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
476
601
|
|
|
@@ -478,31 +603,49 @@ class MockifyerClass {
|
|
|
478
603
|
|
|
479
604
|
if (cachedMock) {
|
|
480
605
|
const { mockData, filename, filePath } = cachedMock;
|
|
606
|
+
if (mockShouldServeStoredBody(mockData)) {
|
|
607
|
+
logger.info(
|
|
608
|
+
`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
609
|
+
(filePath ? ` (${filePath})` : '')
|
|
610
|
+
);
|
|
611
|
+
this.logNetworkEvent(
|
|
612
|
+
{
|
|
613
|
+
method: (request.method || 'GET').toUpperCase(),
|
|
614
|
+
url: request.url,
|
|
615
|
+
source: 'mock-hit',
|
|
616
|
+
status: mockData.response.status,
|
|
617
|
+
requestHash: networkEventHashFromRequestKey(requestKey),
|
|
618
|
+
},
|
|
619
|
+
correlation
|
|
620
|
+
);
|
|
621
|
+
const responseHeaders = {
|
|
622
|
+
...mockData.response.headers,
|
|
623
|
+
'x-mockifyer': 'true',
|
|
624
|
+
'x-mockifyer-timestamp': mockData.timestamp,
|
|
625
|
+
'x-mockifyer-filename': filename,
|
|
626
|
+
'x-mockifyer-filepath': filePath
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
const mockResponse = {
|
|
630
|
+
data: prepareMockResponseBody(mockData, getCurrentDate),
|
|
631
|
+
status: mockData.response.status,
|
|
632
|
+
statusText: 'OK',
|
|
633
|
+
headers: responseHeaders,
|
|
634
|
+
config: config as any
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
return {
|
|
638
|
+
...config,
|
|
639
|
+
__mockResponse: Promise.resolve(mockResponse),
|
|
640
|
+
__mockifyer_requestKey: requestKey
|
|
641
|
+
} as any;
|
|
642
|
+
}
|
|
643
|
+
|
|
481
644
|
logger.info(
|
|
482
|
-
`[Mockifyer-Fetch]
|
|
645
|
+
`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
|
|
483
646
|
(filePath ? ` (${filePath})` : '')
|
|
484
647
|
);
|
|
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;
|
|
648
|
+
(config as any).__mockifyer_matchedMock = cachedMock;
|
|
506
649
|
}
|
|
507
650
|
|
|
508
651
|
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
@@ -633,12 +776,71 @@ class MockifyerClass {
|
|
|
633
776
|
if (isMocked || isLimitReached) {
|
|
634
777
|
return response;
|
|
635
778
|
}
|
|
636
|
-
|
|
779
|
+
|
|
780
|
+
if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
|
|
781
|
+
await this.maybeMirrorProxyRecordingToClient(response);
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const matchedMock = (response.config as any).__mockifyer_matchedMock as CachedMockData | undefined;
|
|
785
|
+
if (matchedMock) {
|
|
786
|
+
const capturedResponse: StoredResponse = {
|
|
787
|
+
status: response.status,
|
|
788
|
+
data: response.data,
|
|
789
|
+
headers: (response.headers as Record<string, string>) || {},
|
|
790
|
+
};
|
|
791
|
+
const startTime = (response.config as any).__mockifyer_startTime;
|
|
792
|
+
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
793
|
+
|
|
794
|
+
if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
|
|
795
|
+
await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const clientResponse = buildClientResponseFromLiveCapture(
|
|
799
|
+
matchedMock.mockData,
|
|
800
|
+
capturedResponse,
|
|
801
|
+
getCurrentDate
|
|
802
|
+
);
|
|
803
|
+
response.data = clientResponse.data;
|
|
804
|
+
response.status = clientResponse.status;
|
|
805
|
+
delete (response.config as any).__mockifyer_matchedMock;
|
|
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
|
+
},
|
|
817
|
+
this.readRequestCorrelation(response.config)
|
|
818
|
+
);
|
|
819
|
+
return response;
|
|
820
|
+
}
|
|
821
|
+
|
|
637
822
|
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
638
823
|
// When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
|
|
639
824
|
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
640
825
|
await this.saveResponse(response);
|
|
641
826
|
}
|
|
827
|
+
|
|
828
|
+
const reqUrl = response.config?.url || url;
|
|
829
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
830
|
+
this.logNetworkEvent(
|
|
831
|
+
{
|
|
832
|
+
method: reqMethod,
|
|
833
|
+
url: reqUrl,
|
|
834
|
+
source: 'upstream',
|
|
835
|
+
status: response.status,
|
|
836
|
+
durationMs:
|
|
837
|
+
typeof response.config?.metadata?.durationMs === 'number'
|
|
838
|
+
? response.config.metadata.durationMs
|
|
839
|
+
: undefined,
|
|
840
|
+
},
|
|
841
|
+
this.readRequestCorrelation(response.config)
|
|
842
|
+
);
|
|
843
|
+
|
|
642
844
|
return response;
|
|
643
845
|
},
|
|
644
846
|
async (error: any) => {
|
|
@@ -646,11 +848,131 @@ class MockifyerClass {
|
|
|
646
848
|
if (requestKey) {
|
|
647
849
|
this.processingRequests.delete(requestKey);
|
|
648
850
|
}
|
|
851
|
+
const reqUrl = error.config?.url || '';
|
|
852
|
+
if (reqUrl) {
|
|
853
|
+
this.logNetworkEvent(
|
|
854
|
+
{
|
|
855
|
+
method: (error.config?.method || 'GET').toUpperCase(),
|
|
856
|
+
url: reqUrl,
|
|
857
|
+
source: 'error',
|
|
858
|
+
status: error.response?.status,
|
|
859
|
+
errorMessage: error?.message ?? String(error),
|
|
860
|
+
},
|
|
861
|
+
this.readRequestCorrelation(error.config)
|
|
862
|
+
);
|
|
863
|
+
}
|
|
649
864
|
throw error;
|
|
650
865
|
}
|
|
651
866
|
);
|
|
652
867
|
}
|
|
653
868
|
|
|
869
|
+
/**
|
|
870
|
+
* When dashboard proxy records to Redis, optionally persist the same payload next to the client
|
|
871
|
+
* (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
|
|
872
|
+
*/
|
|
873
|
+
private async maybeMirrorProxyRecordingToClient(response: HTTPResponse): Promise<void> {
|
|
874
|
+
const rec = response.mockifyerProxyRecording;
|
|
875
|
+
if (!rec?.recordedToStore || !rec.storedMock) {
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
const hash = rec.hash?.trim();
|
|
879
|
+
const scenarioName = rec.scenarioName?.trim();
|
|
880
|
+
if (!hash || !scenarioName) {
|
|
881
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror skipped: missing hash or scenario from proxy');
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const mockData = rec.storedMock as MockData;
|
|
885
|
+
const url = mockData?.request?.url || '';
|
|
886
|
+
if (shouldExcludeUrl(url, this.config.excludedUrls)) {
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
const recExclusions = resolveRecordingExclusions(this.config);
|
|
890
|
+
if (shouldExcludeRecording(url, recExclusions, this.config.baseUrl)) {
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
await this.databaseProviderInitPromise;
|
|
895
|
+
|
|
896
|
+
const providerType = this.config.databaseProvider?.type;
|
|
897
|
+
if (this.databaseProvider && providerType !== 'memory') {
|
|
898
|
+
try {
|
|
899
|
+
const out = this.databaseProvider.save(mockData, {
|
|
900
|
+
relativePath: `redis/${hash}.json`,
|
|
901
|
+
scenario: scenarioName,
|
|
902
|
+
});
|
|
903
|
+
if (out instanceof Promise) {
|
|
904
|
+
await out;
|
|
905
|
+
}
|
|
906
|
+
logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (${providerType}): ${scenarioName}/redis/${hash}.json`);
|
|
907
|
+
if (providerType === 'hybrid') {
|
|
908
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
909
|
+
}
|
|
910
|
+
} catch (e) {
|
|
911
|
+
logger.error('[Mockifyer-Fetch] Proxy client mirror (provider) failed:', e);
|
|
912
|
+
}
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
if (fs && path) {
|
|
917
|
+
try {
|
|
918
|
+
ensureScenarioFolder(this.config.mockDataPath, scenarioName);
|
|
919
|
+
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, scenarioName);
|
|
920
|
+
const filePath = path.join(scenarioPath, 'redis', `${hash}.json`);
|
|
921
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
922
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
923
|
+
logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (filesystem): ${scenarioName}/redis/${hash}.json`);
|
|
924
|
+
} catch (e) {
|
|
925
|
+
logger.error('[Mockifyer-Fetch] Proxy client mirror (Node fs) failed:', e);
|
|
926
|
+
}
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
private async tryMirrorProxyRecordingViaMetro(
|
|
934
|
+
mockData: MockData,
|
|
935
|
+
scenarioName: string,
|
|
936
|
+
hash: string
|
|
937
|
+
): Promise<void> {
|
|
938
|
+
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
939
|
+
const fetchFn = (global as any).__mockifyer_original_fetch || fetch;
|
|
940
|
+
if (!fetchFn) {
|
|
941
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
const body = JSON.stringify({
|
|
946
|
+
__mockifyerProxyMirror: true,
|
|
947
|
+
mockData,
|
|
948
|
+
scenarioName,
|
|
949
|
+
relativePath: `redis/${hash}.json`,
|
|
950
|
+
});
|
|
951
|
+
const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
|
|
952
|
+
method: 'POST',
|
|
953
|
+
headers: { 'Content-Type': 'application/json' },
|
|
954
|
+
body,
|
|
955
|
+
});
|
|
956
|
+
const text = await res.text().catch(() => '');
|
|
957
|
+
if (!res.ok) {
|
|
958
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
try {
|
|
962
|
+
const parsed = JSON.parse(text) as { success?: boolean; error?: string };
|
|
963
|
+
if (parsed.success === false) {
|
|
964
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
} catch {
|
|
968
|
+
// non-JSON response
|
|
969
|
+
}
|
|
970
|
+
logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
|
|
971
|
+
} catch (e) {
|
|
972
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
654
976
|
private async saveResponse(response: HTTPResponse): Promise<void> {
|
|
655
977
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
656
978
|
if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
|
|
@@ -662,11 +984,25 @@ class MockifyerClass {
|
|
|
662
984
|
if (this.config.proxy?.baseUrl) {
|
|
663
985
|
return;
|
|
664
986
|
}
|
|
987
|
+
|
|
988
|
+
if (shouldBlockLocalMockRecording(this.config)) {
|
|
989
|
+
logger.info(
|
|
990
|
+
'[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).'
|
|
991
|
+
);
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
665
994
|
|
|
666
995
|
const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
|
|
996
|
+
const recordingExclusions = resolveRecordingExclusions(this.config);
|
|
667
997
|
if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
|
|
668
998
|
return;
|
|
669
999
|
}
|
|
1000
|
+
if (
|
|
1001
|
+
url &&
|
|
1002
|
+
shouldExcludeRecording(url, recordingExclusions, this.config.baseUrl)
|
|
1003
|
+
) {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
670
1006
|
|
|
671
1007
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
672
1008
|
// This is a defense-in-depth measure
|
|
@@ -703,97 +1039,126 @@ class MockifyerClass {
|
|
|
703
1039
|
const rawParams = response.config.params || {};
|
|
704
1040
|
const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
|
|
705
1041
|
|
|
706
|
-
const
|
|
1042
|
+
const saveLookupRequest: StoredRequest = {
|
|
707
1043
|
method: response.config.method?.toUpperCase() || 'GET',
|
|
708
1044
|
url: response.config.url || '',
|
|
709
1045
|
headers: {},
|
|
710
1046
|
data: response.config.data,
|
|
711
|
-
queryParams: normalizedParams
|
|
712
|
-
}
|
|
713
|
-
|
|
1047
|
+
queryParams: normalizedParams,
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
const requestKey = this.generateRequestKey(saveLookupRequest);
|
|
1051
|
+
|
|
714
1052
|
if (this.savingResponses.has(requestKey)) {
|
|
715
1053
|
return;
|
|
716
1054
|
}
|
|
717
|
-
|
|
1055
|
+
|
|
1056
|
+
const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
|
|
1057
|
+
includePassthroughMocks: true,
|
|
1058
|
+
});
|
|
1059
|
+
|
|
1060
|
+
const saveDecision = resolveMockRecordingSaveDecision(
|
|
1061
|
+
this.config,
|
|
1062
|
+
existingMock?.mockData
|
|
1063
|
+
);
|
|
1064
|
+
|
|
1065
|
+
if (saveDecision.action === 'skip') {
|
|
1066
|
+
if (existingMock && mockPassesThroughToRealApi(existingMock.mockData)) {
|
|
1067
|
+
logger.info(
|
|
1068
|
+
`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`
|
|
1069
|
+
);
|
|
1070
|
+
}
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
718
1074
|
this.savingResponses.add(requestKey);
|
|
719
|
-
|
|
1075
|
+
|
|
720
1076
|
try {
|
|
721
|
-
|
|
722
|
-
const
|
|
723
|
-
const
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
// Generate or reuse sessionId
|
|
1077
|
+
const rawParamsForSave = response.config.params || {};
|
|
1078
|
+
const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
|
|
1079
|
+
const normalizedParamsForSave =
|
|
1080
|
+
anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
1081
|
+
? anonymizedQueryParams
|
|
1082
|
+
: undefined;
|
|
1083
|
+
|
|
729
1084
|
const now = Date.now();
|
|
730
|
-
if (!this.currentSessionId ||
|
|
731
|
-
// Generate new session ID
|
|
1085
|
+
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
732
1086
|
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
733
1087
|
this.sessionStartTime = now;
|
|
734
1088
|
}
|
|
735
1089
|
|
|
736
|
-
// Calculate request duration if start time is available
|
|
737
1090
|
const startTime = (response.config as any).__mockifyer_startTime;
|
|
738
1091
|
const duration = startTime ? Date.now() - startTime : undefined;
|
|
739
1092
|
|
|
1093
|
+
const correlation = this.readRequestCorrelation(response.config);
|
|
1094
|
+
|
|
740
1095
|
const mockData: MockData = {
|
|
741
1096
|
request: {
|
|
742
1097
|
method: response.config?.method?.toUpperCase() || 'GET',
|
|
743
1098
|
url: response.config?.url || '',
|
|
744
1099
|
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
745
1100
|
data: response.config?.data,
|
|
746
|
-
queryParams:
|
|
1101
|
+
queryParams: normalizedParamsForSave,
|
|
747
1102
|
},
|
|
748
1103
|
response: {
|
|
749
1104
|
status: response.status,
|
|
750
1105
|
data: response.data,
|
|
751
|
-
headers: response.headers || {}
|
|
1106
|
+
headers: response.headers || {},
|
|
752
1107
|
},
|
|
753
1108
|
timestamp: new Date().toISOString(),
|
|
754
1109
|
duration,
|
|
755
|
-
sessionId:
|
|
1110
|
+
sessionId:
|
|
1111
|
+
saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1112
|
+
? existingMock.mockData.sessionId
|
|
1113
|
+
: this.currentSessionId,
|
|
1114
|
+
requestId: correlation?.requestId,
|
|
1115
|
+
parentRequestId: correlation?.parentRequestId,
|
|
1116
|
+
...(newRecordingUsesAlwaysUseRealApi() ? { alwaysUseRealApi: true as const } : {}),
|
|
756
1117
|
};
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
1118
|
+
|
|
1119
|
+
applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
|
|
1120
|
+
|
|
760
1121
|
if (this.databaseProvider) {
|
|
761
1122
|
try {
|
|
762
1123
|
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
|
|
1124
|
+
|
|
766
1125
|
if (this.config.generateTests?.enabled) {
|
|
767
1126
|
await this.generateTestForMock(mockData);
|
|
768
1127
|
}
|
|
769
1128
|
} catch (error) {
|
|
770
|
-
console.error(
|
|
1129
|
+
console.error(
|
|
1130
|
+
`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`,
|
|
1131
|
+
error
|
|
1132
|
+
);
|
|
771
1133
|
throw error;
|
|
772
1134
|
}
|
|
773
1135
|
} 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
1136
|
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
781
1137
|
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
782
1138
|
ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
783
|
-
|
|
784
|
-
// Check request limit before saving (only if limit is set via env var)
|
|
1139
|
+
|
|
785
1140
|
const limitCheck = checkRequestLimit(this.config.mockDataPath);
|
|
786
1141
|
if (limitCheck.limitReached && limitCheck.error) {
|
|
787
1142
|
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
788
|
-
// Don't throw - just log and return to prevent app crash
|
|
789
1143
|
return;
|
|
790
1144
|
}
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
1145
|
+
|
|
1146
|
+
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1147
|
+
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1148
|
+
logger.info(
|
|
1149
|
+
`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
|
|
1150
|
+
);
|
|
1151
|
+
} else {
|
|
1152
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1153
|
+
const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
|
|
1154
|
+
const domain = urlParts[0].replace(/\./g, '_');
|
|
1155
|
+
const urlPathPart = urlParts.slice(1).join('_') || 'root';
|
|
1156
|
+
const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
|
|
1157
|
+
const filePath = path.join(scenarioPath, filename);
|
|
1158
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1159
|
+
logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
797
1162
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
798
1163
|
await this.generateTestForMock(mockData);
|
|
799
1164
|
}
|
|
@@ -805,6 +1170,24 @@ class MockifyerClass {
|
|
|
805
1170
|
}
|
|
806
1171
|
}
|
|
807
1172
|
|
|
1173
|
+
private async persistMatchedMockAfterLiveCapture(
|
|
1174
|
+
cachedMock: CachedMockData,
|
|
1175
|
+
capturedResponse: StoredResponse,
|
|
1176
|
+
durationMs?: number
|
|
1177
|
+
): Promise<void> {
|
|
1178
|
+
const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
|
|
1179
|
+
|
|
1180
|
+
if (this.databaseProvider) {
|
|
1181
|
+
await this.databaseProvider.save(updated);
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
if (fs && cachedMock.filePath) {
|
|
1186
|
+
fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
|
|
1187
|
+
logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
808
1191
|
/**
|
|
809
1192
|
* Simple path resolution fallback for React Native (when path module is stubbed)
|
|
810
1193
|
*/
|
|
@@ -1058,8 +1441,13 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
1058
1441
|
}
|
|
1059
1442
|
|
|
1060
1443
|
export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
1444
|
+
// Node-only inbound capture; safe on RN (no-op when not on Node).
|
|
1445
|
+
if (typeof installNodeInboundRequestCorrelationCapture === 'function') {
|
|
1446
|
+
installNodeInboundRequestCorrelationCapture();
|
|
1447
|
+
}
|
|
1448
|
+
const resolvedConfig = applyProxyRecordOnMissEnv(config);
|
|
1061
1449
|
// Initialize logger with config level (default to 'info' if not specified)
|
|
1062
|
-
setLogLevel(
|
|
1450
|
+
setLogLevel(resolvedConfig.logging || 'info');
|
|
1063
1451
|
|
|
1064
1452
|
// Set environment variables for Metro middleware to read test generation config
|
|
1065
1453
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
@@ -1086,11 +1474,11 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1086
1474
|
}
|
|
1087
1475
|
}
|
|
1088
1476
|
|
|
1089
|
-
initializeDateManipulation(
|
|
1090
|
-
initializeScenario(
|
|
1091
|
-
|
|
1477
|
+
initializeDateManipulation(resolvedConfig);
|
|
1478
|
+
initializeScenario(resolvedConfig);
|
|
1479
|
+
|
|
1092
1480
|
|
|
1093
|
-
const mockifyer = new MockifyerClass(
|
|
1481
|
+
const mockifyer = new MockifyerClass(resolvedConfig);
|
|
1094
1482
|
const httpClient = mockifyer.getHTTPClient();
|
|
1095
1483
|
|
|
1096
1484
|
// Always store original fetch (even if not patching global)
|
|
@@ -1108,7 +1496,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1108
1496
|
}
|
|
1109
1497
|
|
|
1110
1498
|
// Patch global fetch if useGlobalFetch is true
|
|
1111
|
-
if (
|
|
1499
|
+
if (resolvedConfig.useGlobalFetch) {
|
|
1112
1500
|
const mockifyerInstance = mockifyer;
|
|
1113
1501
|
const originalFetchForPatched = (global as any).__mockifyer_original_fetch || originalFetch;
|
|
1114
1502
|
|
|
@@ -1221,9 +1609,223 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1221
1609
|
return extendedClient;
|
|
1222
1610
|
}
|
|
1223
1611
|
|
|
1612
|
+
/** Drops `proxy` when merging partial config so filesystem fallback cannot accidentally keep proxy. */
|
|
1613
|
+
function omitProxyFromPartialConfig(config: Partial<MockifyerConfig>): Partial<MockifyerConfig> {
|
|
1614
|
+
const { proxy: _drop, ...rest } = config;
|
|
1615
|
+
void _drop;
|
|
1616
|
+
return rest;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
/** Options for {@link initMockifyerForDashboardProxy} — dashboard + `/api/proxy` (run `mockifyer-dashboard --provider redis`). */
|
|
1620
|
+
export interface InitMockifyerForDashboardProxyOptions {
|
|
1621
|
+
/** mockifyer-dashboard origin (e.g. `http://localhost:3002`). Not the Redis URL. */
|
|
1622
|
+
dashboardBaseUrl: string;
|
|
1623
|
+
/** Mock root for scenario file fallbacks etc. Defaults `MOCKIFYER_PATH` env or `./mock-data`. */
|
|
1624
|
+
mockDataPath?: string;
|
|
1625
|
+
/** Client lane id (`X-Mockifyer-Client-Id` / proxy envelope). Defaults `MOCKIFYER_CLIENT_ID` env. */
|
|
1626
|
+
clientId?: string;
|
|
1627
|
+
deviceId?: string;
|
|
1628
|
+
scenario?: string;
|
|
1629
|
+
/**
|
|
1630
|
+
* When **`true`**, each `/api/proxy` request sends **`"record": true`**. When **`false`**, sends **`"record": false`**.
|
|
1631
|
+
* When **omitted**, the **`record`** field is omitted so the **dashboard per-scenario** toggle applies; **`MOCKIFYER_PROXY_RECORD_ON_MISS`**
|
|
1632
|
+
* and **`MOCKIFYER_RECORD=true`** (last) still set an explicit client flag when you want env-driven recording without code.
|
|
1633
|
+
*/
|
|
1634
|
+
recordOnMiss?: boolean;
|
|
1635
|
+
/**
|
|
1636
|
+
* When false, dashboard proxy stores request-only stubs on cache miss.
|
|
1637
|
+
* Defaults via {@link resolveRecordResponses} (`MOCKIFYER_RECORD_RESPONSES` env, else `false`).
|
|
1638
|
+
*/
|
|
1639
|
+
recordResponses?: boolean;
|
|
1640
|
+
strictLaneScenario?: boolean;
|
|
1641
|
+
useGlobalFetch?: boolean;
|
|
1642
|
+
/** Use a local provider for mock hits before the proxy (default in-memory only) when **`/api/proxy`** is active. */
|
|
1643
|
+
databaseProvider?: MockifyerConfig['databaseProvider'];
|
|
1644
|
+
/** Additional `MockifyerConfig` fields — applied first, then preset fields win on `mockDataPath`, `proxy`, etc. */
|
|
1645
|
+
config?: Partial<MockifyerConfig>;
|
|
1646
|
+
/**
|
|
1647
|
+
* When **`true`**, skips **`GET …/api/health`** and always sets **`proxy`**.
|
|
1648
|
+
* Default **`false`**: if Redis is not healthy (or unreachable), omit **`proxy`** and use filesystem mocks + **`recordMode`** disk saves — aligns with **`setupMockifyerForReactNative`** dev fallback.
|
|
1649
|
+
*/
|
|
1650
|
+
skipDashboardRedisHealthCheck?: boolean;
|
|
1651
|
+
/**
|
|
1652
|
+
* When the proxy records a response to Redis, also write the same mock under `mockDataPath` on this machine
|
|
1653
|
+
* (or via Metro when using strict RN + in-memory). Env: `MOCKIFYER_PROXY_MIRROR_TO_CLIENT`.
|
|
1654
|
+
*/
|
|
1655
|
+
mirrorRecordedMocksToClient?: boolean;
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
|
|
1660
|
+
* Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
|
|
1661
|
+
*
|
|
1662
|
+
* For full control, use {@link setupMockifyer} directly.
|
|
1663
|
+
*/
|
|
1664
|
+
export async function initMockifyerForDashboardProxy(
|
|
1665
|
+
options: InitMockifyerForDashboardProxyOptions
|
|
1666
|
+
): Promise<MockifyerInstance> {
|
|
1667
|
+
const extra = options.config ?? {};
|
|
1668
|
+
const dashboardBaseUrl = String(options.dashboardBaseUrl).trim();
|
|
1669
|
+
if (!dashboardBaseUrl) {
|
|
1670
|
+
throw new Error('initMockifyerForDashboardProxy: dashboardBaseUrl is required');
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
const mockDataPath =
|
|
1674
|
+
options.mockDataPath ??
|
|
1675
|
+
extra.mockDataPath ??
|
|
1676
|
+
(typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
|
|
1677
|
+
? process.env.MOCKIFYER_PATH
|
|
1678
|
+
: './mock-data');
|
|
1679
|
+
|
|
1680
|
+
const envRecord =
|
|
1681
|
+
typeof process !== 'undefined' && process.env?.MOCKIFYER_RECORD === 'true';
|
|
1682
|
+
|
|
1683
|
+
const recordOnMiss =
|
|
1684
|
+
options.recordOnMiss ??
|
|
1685
|
+
extra.proxy?.recordOnMiss ??
|
|
1686
|
+
parseProxyRecordOnMissEnv() ??
|
|
1687
|
+
(envRecord ? true : undefined);
|
|
1688
|
+
|
|
1689
|
+
const recordResponses = resolveRecordResponses(
|
|
1690
|
+
options.recordResponses ?? extra.proxy?.recordResponses
|
|
1691
|
+
);
|
|
1692
|
+
|
|
1693
|
+
const useRedisProxy =
|
|
1694
|
+
options.skipDashboardRedisHealthCheck === true ||
|
|
1695
|
+
(await canUseDashboardRedisProxy(dashboardBaseUrl));
|
|
1696
|
+
|
|
1697
|
+
if (!useRedisProxy) {
|
|
1698
|
+
const strictProxyOnly = resolveStrictScenarioResolution({
|
|
1699
|
+
strictScenarioResolution:
|
|
1700
|
+
options.config?.strictScenarioResolution ?? extra.strictScenarioResolution,
|
|
1701
|
+
});
|
|
1702
|
+
logger.warn(
|
|
1703
|
+
`[Mockifyer] initMockifyerForDashboardProxy: "${dashboardBaseUrl}" did not report healthy Redis ` +
|
|
1704
|
+
(strictProxyOnly
|
|
1705
|
+
? '(strict proxy-only — local recording disabled). '
|
|
1706
|
+
: '(unreachable or non-Redis provider). Falling back to filesystem mocks without proxy. ') +
|
|
1707
|
+
'Set skipDashboardRedisHealthCheck: true to force proxy anyway.'
|
|
1708
|
+
);
|
|
1709
|
+
const stripped = omitProxyFromPartialConfig(extra);
|
|
1710
|
+
const fallbackDb = options.databaseProvider ?? extra.databaseProvider;
|
|
1711
|
+
const mergedInitLogFs: MockifyerConfig['initLog'] = {
|
|
1712
|
+
...stripped.initLog,
|
|
1713
|
+
headline:
|
|
1714
|
+
stripped.initLog?.headline ??
|
|
1715
|
+
(strictProxyOnly
|
|
1716
|
+
? '[Mockifyer preset] Node · strict proxy-only (dashboard Redis health check failed)'
|
|
1717
|
+
: '[Mockifyer preset] Node · filesystem (dashboard Redis health check failed)'),
|
|
1718
|
+
};
|
|
1719
|
+
return setupMockifyer({
|
|
1720
|
+
...stripped,
|
|
1721
|
+
mockDataPath,
|
|
1722
|
+
...(fallbackDb !== undefined ? { databaseProvider: fallbackDb } : {}),
|
|
1723
|
+
...(strictProxyOnly ? { intendedProxyBaseUrl: dashboardBaseUrl.trim() } : {}),
|
|
1724
|
+
useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
|
|
1725
|
+
clientId: options.clientId ?? extra.clientId,
|
|
1726
|
+
deviceId: options.deviceId ?? extra.deviceId,
|
|
1727
|
+
initLog: mergedInitLogFs,
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
const upstreamProxy = extra.proxy as MockifyerConfig['proxy'] | undefined;
|
|
1732
|
+
const mergedProxy = {
|
|
1733
|
+
...upstreamProxy,
|
|
1734
|
+
baseUrl: upstreamProxy?.baseUrl ?? dashboardBaseUrl,
|
|
1735
|
+
scenario:
|
|
1736
|
+
options.scenario ??
|
|
1737
|
+
upstreamProxy?.scenario ??
|
|
1738
|
+
(typeof process !== 'undefined' && process.env?.MOCKIFYER_SCENARIO?.trim()
|
|
1739
|
+
? process.env.MOCKIFYER_SCENARIO.trim()
|
|
1740
|
+
: undefined),
|
|
1741
|
+
...(typeof recordOnMiss === 'boolean' ? { recordOnMiss } : {}),
|
|
1742
|
+
recordResponses,
|
|
1743
|
+
} as NonNullable<MockifyerConfig['proxy']>;
|
|
1744
|
+
if (
|
|
1745
|
+
options.strictLaneScenario !== undefined ||
|
|
1746
|
+
upstreamProxy?.strictLaneScenario !== undefined
|
|
1747
|
+
) {
|
|
1748
|
+
mergedProxy.strictLaneScenario =
|
|
1749
|
+
options.strictLaneScenario ?? upstreamProxy?.strictLaneScenario;
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
const envMirrorRaw =
|
|
1753
|
+
typeof process !== 'undefined'
|
|
1754
|
+
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
1755
|
+
: '';
|
|
1756
|
+
const envMirror =
|
|
1757
|
+
envMirrorRaw === '1' || envMirrorRaw === 'true' || envMirrorRaw === 'yes' || envMirrorRaw === 'on';
|
|
1758
|
+
const mirrorRecordedMocksToClient =
|
|
1759
|
+
options.mirrorRecordedMocksToClient ??
|
|
1760
|
+
extra.proxy?.mirrorRecordedMocksToClient ??
|
|
1761
|
+
(envMirror ? true : undefined);
|
|
1762
|
+
if (mirrorRecordedMocksToClient !== undefined) {
|
|
1763
|
+
mergedProxy.mirrorRecordedMocksToClient = mirrorRecordedMocksToClient;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
const mergedInitLogProxy: MockifyerConfig['initLog'] = {
|
|
1767
|
+
...extra.initLog,
|
|
1768
|
+
headline: extra.initLog?.headline ?? '[Mockifyer preset] Node · dashboard Redis proxy',
|
|
1769
|
+
};
|
|
1770
|
+
|
|
1771
|
+
const strictScenarioResolution =
|
|
1772
|
+
extra.strictScenarioResolution ??
|
|
1773
|
+
options.config?.strictScenarioResolution ??
|
|
1774
|
+
true;
|
|
1775
|
+
|
|
1776
|
+
return setupMockifyer({
|
|
1777
|
+
...extra,
|
|
1778
|
+
mockDataPath,
|
|
1779
|
+
strictScenarioResolution,
|
|
1780
|
+
databaseProvider: options.databaseProvider ?? extra.databaseProvider ?? { type: 'memory' },
|
|
1781
|
+
useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
|
|
1782
|
+
clientId: options.clientId ?? extra.clientId,
|
|
1783
|
+
deviceId: options.deviceId ?? extra.deviceId,
|
|
1784
|
+
proxy: mergedProxy,
|
|
1785
|
+
initLog: mergedInitLogProxy,
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
export interface InitMockifyerForLocalFilesystemOptions {
|
|
1790
|
+
mockDataPath?: string;
|
|
1791
|
+
useGlobalFetch?: boolean;
|
|
1792
|
+
recordMode?: boolean;
|
|
1793
|
+
/** Applied first; preset fills `mockDataPath` / `useGlobalFetch` when omitted. */
|
|
1794
|
+
config?: Partial<MockifyerConfig>;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
/**
|
|
1798
|
+
* Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
|
|
1799
|
+
* (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
|
|
1800
|
+
*/
|
|
1801
|
+
export function initMockifyerForLocalFilesystem(
|
|
1802
|
+
options: InitMockifyerForLocalFilesystemOptions = {}
|
|
1803
|
+
): MockifyerInstance {
|
|
1804
|
+
const extra = options.config ?? {};
|
|
1805
|
+
const mockDataPath =
|
|
1806
|
+
options.mockDataPath ??
|
|
1807
|
+
extra.mockDataPath ??
|
|
1808
|
+
(typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
|
|
1809
|
+
? process.env.MOCKIFYER_PATH
|
|
1810
|
+
: './mock-data');
|
|
1811
|
+
|
|
1812
|
+
return setupMockifyer({
|
|
1813
|
+
...extra,
|
|
1814
|
+
mockDataPath,
|
|
1815
|
+
useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
|
|
1816
|
+
recordMode: options.recordMode ?? extra.recordMode ?? false,
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
|
|
1821
|
+
export {
|
|
1822
|
+
canUseDashboardRedisProxy,
|
|
1823
|
+
canUseDashboardCentralProxy,
|
|
1824
|
+
} from './utils/dashboard-redis-health';
|
|
1825
|
+
|
|
1224
1826
|
// Re-export types from core
|
|
1225
1827
|
export * from '@sgedda/mockifyer-core';
|
|
1226
1828
|
|
|
1227
|
-
//
|
|
1228
|
-
|
|
1829
|
+
// React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
|
|
1830
|
+
// pulling optional `react-native-launch-arguments` into Node/Next webpack bundles).
|
|
1229
1831
|
|