@sgedda/mockifyer-fetch 1.8.100 → 1.8.106
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 +4 -0
- package/dist/clients/fetch-client.js +50 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +207 -65
- package/dist/metro-sync-middleware.d.ts +10 -0
- package/dist/metro-sync-middleware.js +159 -73
- package/dist/react-native.d.ts +4 -0
- package/dist/utils/resolve-patched-fetch-request.d.ts +24 -0
- package/dist/utils/resolve-patched-fetch-request.js +91 -0
- package/package.json +3 -3
- package/src/clients/fetch-client.ts +66 -1
- package/src/index.ts +251 -68
- package/src/metro-sync-middleware.ts +201 -76
- package/src/react-native.ts +4 -0
- package/src/utils/resolve-patched-fetch-request.ts +105 -0
|
@@ -34,6 +34,10 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
|
|
|
34
34
|
});
|
|
35
35
|
private resolvedClientLane;
|
|
36
36
|
protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
|
|
37
|
+
/** Update whether `/api/proxy` sends `record` (record-on-miss). */
|
|
38
|
+
setProxyRecordOnMiss(recordOnMiss: boolean | undefined): void;
|
|
39
|
+
/** Update whether `/api/proxy` asks the dashboard to store response bodies. */
|
|
40
|
+
setProxyRecordResponses(recordResponses: boolean): void;
|
|
37
41
|
protected getDefaultHeaders(): Record<string, string>;
|
|
38
42
|
protected getDefaultConfig(): Record<string, any>;
|
|
39
43
|
}
|
|
@@ -3,6 +3,47 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.FetchHTTPClient = void 0;
|
|
4
4
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
5
5
|
const core_proxy_1 = require("../core-proxy");
|
|
6
|
+
function headerContentType(headers) {
|
|
7
|
+
const contentType = headers.get('content-type');
|
|
8
|
+
return contentType ? contentType.toLowerCase() : undefined;
|
|
9
|
+
}
|
|
10
|
+
/** Native Fetch body types that must not be JSON.stringified (bypass / direct upstream). */
|
|
11
|
+
function isNativeFetchBody(value) {
|
|
12
|
+
return (typeof value === 'string' ||
|
|
13
|
+
(typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) ||
|
|
14
|
+
(typeof FormData !== 'undefined' && value instanceof FormData) ||
|
|
15
|
+
(typeof Blob !== 'undefined' && value instanceof Blob) ||
|
|
16
|
+
(typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||
|
|
17
|
+
(typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value)));
|
|
18
|
+
}
|
|
19
|
+
function plainObjectToUrlEncoded(body) {
|
|
20
|
+
const params = new URLSearchParams();
|
|
21
|
+
for (const [key, value] of Object.entries(body)) {
|
|
22
|
+
if (value === undefined || value === null)
|
|
23
|
+
continue;
|
|
24
|
+
params.append(key, String(value));
|
|
25
|
+
}
|
|
26
|
+
return params;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Build a RequestInit body for direct (non-proxy) fetch.
|
|
30
|
+
* JSON.stringify on URLSearchParams/FormData yields "{}" and corrupts OAuth/uploads on bypass paths.
|
|
31
|
+
*/
|
|
32
|
+
function buildDirectFetchBody(data, method, headers) {
|
|
33
|
+
const upperMethod = method.toUpperCase();
|
|
34
|
+
if (upperMethod === 'GET' || upperMethod === 'HEAD' || data === undefined || data === null) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (isNativeFetchBody(data)) {
|
|
38
|
+
return data;
|
|
39
|
+
}
|
|
40
|
+
if (typeof data === 'object' &&
|
|
41
|
+
!Array.isArray(data) &&
|
|
42
|
+
headerContentType(headers)?.includes('application/x-www-form-urlencoded')) {
|
|
43
|
+
return plainObjectToUrlEncoded(data);
|
|
44
|
+
}
|
|
45
|
+
return JSON.stringify(data);
|
|
46
|
+
}
|
|
6
47
|
class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
7
48
|
constructor(config) {
|
|
8
49
|
super();
|
|
@@ -71,7 +112,7 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
71
112
|
const requestConfig = {
|
|
72
113
|
method: config.method || 'GET',
|
|
73
114
|
headers,
|
|
74
|
-
body: config.data
|
|
115
|
+
body: buildDirectFetchBody(config.data, config.method || 'GET', headers),
|
|
75
116
|
};
|
|
76
117
|
// Use original fetch if available (when global fetch is patched), otherwise use global fetch
|
|
77
118
|
const fetchFn = this._originalFetch || fetch;
|
|
@@ -143,6 +184,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
143
184
|
...(mockifyerTrace ? { mockifyerTrace } : {}),
|
|
144
185
|
};
|
|
145
186
|
}
|
|
187
|
+
/** Update whether `/api/proxy` sends `record` (record-on-miss). */
|
|
188
|
+
setProxyRecordOnMiss(recordOnMiss) {
|
|
189
|
+
this.proxyRecordOnMiss = recordOnMiss;
|
|
190
|
+
}
|
|
191
|
+
/** Update whether `/api/proxy` asks the dashboard to store response bodies. */
|
|
192
|
+
setProxyRecordResponses(recordResponses) {
|
|
193
|
+
this.proxyRecordResponses = recordResponses;
|
|
194
|
+
}
|
|
146
195
|
getDefaultHeaders() {
|
|
147
196
|
return this.defaultHeaders;
|
|
148
197
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
6
6
|
clearAllMocks: () => Promise<void>;
|
|
7
7
|
setClientId: (lane: string) => void;
|
|
8
8
|
getClientId: () => string | undefined;
|
|
9
|
+
setRecordMode: (enabled: boolean) => void;
|
|
10
|
+
isRecordMode: () => boolean;
|
|
11
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
12
|
+
isRecordResponses: () => boolean;
|
|
9
13
|
enableMockifyer: () => void;
|
|
10
14
|
disableMockifyer: () => void;
|
|
11
15
|
isMockifyerEnabled: () => boolean;
|
package/dist/index.js
CHANGED
|
@@ -39,6 +39,7 @@ const core_proxy_1 = require("./core-proxy");
|
|
|
39
39
|
const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
|
|
40
40
|
const fetch_client_1 = require("./clients/fetch-client");
|
|
41
41
|
const fetch_response_body_1 = require("./utils/fetch-response-body");
|
|
42
|
+
const resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
|
|
42
43
|
class MockifyerClass {
|
|
43
44
|
/** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
|
|
44
45
|
getRuntimeSessionId() {
|
|
@@ -253,6 +254,11 @@ class MockifyerClass {
|
|
|
253
254
|
* unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
|
|
254
255
|
*/
|
|
255
256
|
this.poolResponseCache = new Map();
|
|
257
|
+
/**
|
|
258
|
+
* Runtime override for whether local/proxy recordings include response bodies.
|
|
259
|
+
* `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
|
|
260
|
+
*/
|
|
261
|
+
this.recordResponsesOverride = undefined;
|
|
256
262
|
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
257
263
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
258
264
|
const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
|
|
@@ -314,7 +320,10 @@ class MockifyerClass {
|
|
|
314
320
|
this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
|
|
315
321
|
}
|
|
316
322
|
this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
|
|
317
|
-
this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
|
|
323
|
+
this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
|
|
324
|
+
config: this.config,
|
|
325
|
+
getRecordMode: () => this.config.recordMode === true,
|
|
326
|
+
});
|
|
318
327
|
this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
|
|
319
328
|
if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
|
|
320
329
|
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
|
|
@@ -473,6 +482,24 @@ class MockifyerClass {
|
|
|
473
482
|
}
|
|
474
483
|
return undefined;
|
|
475
484
|
}
|
|
485
|
+
getAllJsonFiles(dir) {
|
|
486
|
+
if (!fs || !path || !fs.existsSync(dir))
|
|
487
|
+
return [];
|
|
488
|
+
const results = [];
|
|
489
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
490
|
+
const fullPath = path.join(dir, entry.name);
|
|
491
|
+
if (entry.isDirectory()) {
|
|
492
|
+
if ((0, mockifyer_core_1.isMockRecordingSidecarDir)(entry.name)) {
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
results.push(...this.getAllJsonFiles(fullPath));
|
|
496
|
+
}
|
|
497
|
+
else if (entry.name.endsWith('.json')) {
|
|
498
|
+
results.push(fullPath);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return results;
|
|
502
|
+
}
|
|
476
503
|
findBestMatchingMockFromFiles(request, options) {
|
|
477
504
|
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
478
505
|
// Only use fs if available (Node.js environment)
|
|
@@ -492,27 +519,26 @@ class MockifyerClass {
|
|
|
492
519
|
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
493
520
|
return undefined;
|
|
494
521
|
}
|
|
495
|
-
const files =
|
|
496
|
-
.filter(file => file.endsWith('.json'));
|
|
522
|
+
const files = this.getAllJsonFiles(scenarioPath);
|
|
497
523
|
const requestKey = this.generateRequestKey(request);
|
|
498
524
|
let exactMatch;
|
|
499
525
|
let similarMatch;
|
|
500
|
-
for (const
|
|
526
|
+
for (const filePath of files) {
|
|
501
527
|
try {
|
|
502
|
-
const filePath = path.join(scenarioPath, file);
|
|
503
528
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
504
529
|
const mockData = JSON.parse(fileContent);
|
|
505
530
|
if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
|
|
506
531
|
continue;
|
|
507
532
|
}
|
|
508
533
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
534
|
+
const filename = path.relative(scenarioPath, filePath);
|
|
509
535
|
if (mockKey === requestKey) {
|
|
510
536
|
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
511
537
|
includePassthroughMocks,
|
|
512
|
-
filename
|
|
538
|
+
filename,
|
|
513
539
|
scenarioPath,
|
|
514
540
|
})) {
|
|
515
|
-
exactMatch = { mockData, filename
|
|
541
|
+
exactMatch = { mockData, filename, filePath };
|
|
516
542
|
break;
|
|
517
543
|
}
|
|
518
544
|
continue;
|
|
@@ -582,10 +608,10 @@ class MockifyerClass {
|
|
|
582
608
|
}
|
|
583
609
|
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
584
610
|
includePassthroughMocks,
|
|
585
|
-
filename
|
|
611
|
+
filename,
|
|
586
612
|
scenarioPath,
|
|
587
613
|
})) {
|
|
588
|
-
similarMatch = { mockData, filename
|
|
614
|
+
similarMatch = { mockData, filename, filePath };
|
|
589
615
|
}
|
|
590
616
|
}
|
|
591
617
|
}
|
|
@@ -596,7 +622,7 @@ class MockifyerClass {
|
|
|
596
622
|
}
|
|
597
623
|
}
|
|
598
624
|
catch (error) {
|
|
599
|
-
mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${
|
|
625
|
+
mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
|
|
600
626
|
}
|
|
601
627
|
}
|
|
602
628
|
return exactMatch || similarMatch;
|
|
@@ -687,12 +713,16 @@ class MockifyerClass {
|
|
|
687
713
|
if (hitScenarioPath) {
|
|
688
714
|
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
|
|
689
715
|
}
|
|
716
|
+
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
717
|
+
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
718
|
+
}
|
|
690
719
|
const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
|
|
720
|
+
const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
|
|
691
721
|
this.logNetworkEvent({
|
|
692
722
|
method: (request.method || 'GET').toUpperCase(),
|
|
693
723
|
url: this.resolveLoggedRequestUrl(config, request.url),
|
|
694
724
|
source: 'mock-hit',
|
|
695
|
-
status:
|
|
725
|
+
status: effectiveStatus,
|
|
696
726
|
requestHash: (0, mockifyer_core_1.networkEventHashFromRequestKey)(requestKey),
|
|
697
727
|
requestBody: request.data,
|
|
698
728
|
responseBody: mockResponseBody,
|
|
@@ -707,7 +737,7 @@ class MockifyerClass {
|
|
|
707
737
|
await this.warmPoolResponseCache(mockData);
|
|
708
738
|
const mockResponse = {
|
|
709
739
|
data: mockResponseBody,
|
|
710
|
-
status:
|
|
740
|
+
status: effectiveStatus,
|
|
711
741
|
statusText: 'OK',
|
|
712
742
|
headers: responseHeaders,
|
|
713
743
|
config: config
|
|
@@ -807,12 +837,14 @@ class MockifyerClass {
|
|
|
807
837
|
responseDataStr = String(response.data);
|
|
808
838
|
}
|
|
809
839
|
}
|
|
810
|
-
//
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const
|
|
814
|
-
|
|
815
|
-
|
|
840
|
+
// Only Metro's own save rejection should skip recording. A business
|
|
841
|
+
// payload such as `{ success: false, error: "username taken" }` must
|
|
842
|
+
// still be logged, unwrapped, and saved.
|
|
843
|
+
const METRO_SAVE_REJECTION = 'Cannot save Mockifyer sync endpoint';
|
|
844
|
+
const hasRejectionMessage = Boolean(responseDataStr && responseDataStr.includes(METRO_SAVE_REJECTION));
|
|
845
|
+
const hasRejectionInObject = Boolean(responseDataObj &&
|
|
846
|
+
typeof responseDataObj.error === 'string' &&
|
|
847
|
+
responseDataObj.error.includes(METRO_SAVE_REJECTION));
|
|
816
848
|
if (hasRejectionMessage || hasRejectionInObject) {
|
|
817
849
|
return response;
|
|
818
850
|
}
|
|
@@ -1111,29 +1143,39 @@ class MockifyerClass {
|
|
|
1111
1143
|
const duration = startTime ? Date.now() - startTime : undefined;
|
|
1112
1144
|
const correlation = this.readRequestCorrelation(response.config);
|
|
1113
1145
|
const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
|
|
1114
|
-
const
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1146
|
+
const storedRequest = {
|
|
1147
|
+
method: response.config?.method?.toUpperCase() || 'GET',
|
|
1148
|
+
url: response.config?.url || '',
|
|
1149
|
+
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
1150
|
+
data: response.config?.data,
|
|
1151
|
+
queryParams: normalizedParamsForSave,
|
|
1152
|
+
};
|
|
1153
|
+
// Prefer explicit override / config; else request-only default (same as proxy).
|
|
1154
|
+
const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ??
|
|
1155
|
+
this.config.proxy?.recordResponses ??
|
|
1156
|
+
this.config.recordResponses);
|
|
1157
|
+
const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
|
|
1158
|
+
request: storedRequest,
|
|
1122
1159
|
response: {
|
|
1123
1160
|
status: response.status,
|
|
1124
1161
|
data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
|
|
1125
1162
|
headers: response.headers || {},
|
|
1126
1163
|
},
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
:
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1164
|
+
recordResponses: recordBodies,
|
|
1165
|
+
meta: {
|
|
1166
|
+
timestamp: new Date().toISOString(),
|
|
1167
|
+
duration,
|
|
1168
|
+
sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1169
|
+
? existingMock.mockData.sessionId
|
|
1170
|
+
: this.currentSessionId,
|
|
1171
|
+
requestId: hopIds.requestId,
|
|
1172
|
+
parentRequestId: hopIds.parentRequestId,
|
|
1173
|
+
parentRequestIds: hopIds.parentRequestIds,
|
|
1174
|
+
...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() || !recordBodies
|
|
1175
|
+
? { alwaysUseRealApi: true }
|
|
1176
|
+
: {}),
|
|
1177
|
+
},
|
|
1178
|
+
});
|
|
1137
1179
|
(0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
|
|
1138
1180
|
if (this.databaseProvider) {
|
|
1139
1181
|
try {
|
|
@@ -1161,14 +1203,13 @@ class MockifyerClass {
|
|
|
1161
1203
|
mockifyer_core_2.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
|
|
1162
1204
|
}
|
|
1163
1205
|
else {
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
const
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
const filePath = path.join(scenarioPath, filename);
|
|
1206
|
+
// Same nested host/path layout as FilesystemProvider / Expo (Folders view).
|
|
1207
|
+
// getMockFilePath clamps over-long path segments to stay within NAME_MAX.
|
|
1208
|
+
const { dir, filename } = (0, mockifyer_core_1.getMockFilePath)(mockData, (0, mockifyer_core_1.formatDateStr)((0, mockifyer_core_1.getCurrentDate)()));
|
|
1209
|
+
const filePath = path.join(scenarioPath, dir, filename);
|
|
1210
|
+
fs.mkdirSync(path.join(scenarioPath, dir), { recursive: true });
|
|
1170
1211
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1171
|
-
mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
1212
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`);
|
|
1172
1213
|
}
|
|
1173
1214
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
1174
1215
|
await this.generateTestForMock(mockData);
|
|
@@ -1177,11 +1218,57 @@ class MockifyerClass {
|
|
|
1177
1218
|
else {
|
|
1178
1219
|
console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
|
|
1179
1220
|
}
|
|
1221
|
+
await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
|
|
1180
1222
|
}
|
|
1181
1223
|
finally {
|
|
1182
1224
|
this.savingResponses.delete(requestKey);
|
|
1183
1225
|
}
|
|
1184
1226
|
}
|
|
1227
|
+
/**
|
|
1228
|
+
* When a child hop is recorded locally, persist a synthetic inbound-parent stub so
|
|
1229
|
+
* Hops does not show "Missing entry hop" for the ALS gateway id.
|
|
1230
|
+
*/
|
|
1231
|
+
async ensureInboundParentStubForChild(parentRequestId, config) {
|
|
1232
|
+
const activeInbound = (0, mockifyer_core_1.getActiveInboundRequest)();
|
|
1233
|
+
const hop = (0, mockifyer_core_1.readOutboundParentHopFromConfig)(config) ??
|
|
1234
|
+
(activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
|
|
1235
|
+
try {
|
|
1236
|
+
await (0, mockifyer_core_1.ensureLocalInboundParentStubSaved)({
|
|
1237
|
+
parentRequestId,
|
|
1238
|
+
hop,
|
|
1239
|
+
parentExists: (id) => {
|
|
1240
|
+
if (!fs || !path || this.databaseProvider) {
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
|
|
1244
|
+
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
|
|
1245
|
+
return fs.existsSync(path.join(scenarioPath, (0, mockifyer_core_1.inboundParentStubFilename)(id)));
|
|
1246
|
+
},
|
|
1247
|
+
save: async (row) => {
|
|
1248
|
+
if (this.databaseProvider) {
|
|
1249
|
+
await this.databaseProvider.save(row.mock);
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
if (!fs || !path) {
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
|
|
1256
|
+
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
|
|
1257
|
+
(0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
|
|
1258
|
+
const filePath = path.join(scenarioPath, row.filename);
|
|
1259
|
+
if (fs.existsSync(filePath)) {
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
|
|
1263
|
+
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`);
|
|
1264
|
+
},
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
catch (error) {
|
|
1268
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1269
|
+
mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1185
1272
|
async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
|
|
1186
1273
|
const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
|
|
1187
1274
|
(0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
|
|
@@ -1369,6 +1456,62 @@ class MockifyerClass {
|
|
|
1369
1456
|
getClientId() {
|
|
1370
1457
|
return this.config.clientId;
|
|
1371
1458
|
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Turn record mode on/off at runtime (dev menus, tests).
|
|
1461
|
+
* Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
|
|
1462
|
+
* Redis/proxy recording follows the same switch as local hybrid saves.
|
|
1463
|
+
*
|
|
1464
|
+
* When enabling: flips existing allowlist `recordResponses` to true and new
|
|
1465
|
+
* discoveries enable recording. When disabled, allowlist discovery stops
|
|
1466
|
+
* persisting new keys (so browsing does not poison the rules file).
|
|
1467
|
+
*/
|
|
1468
|
+
setRecordMode(enabled) {
|
|
1469
|
+
const next = Boolean(enabled);
|
|
1470
|
+
this.config.recordMode = next;
|
|
1471
|
+
if (next) {
|
|
1472
|
+
// Recording needs live upstream calls; fail-on-miss conflicts with that.
|
|
1473
|
+
this.config.failOnMissingMock = false;
|
|
1474
|
+
this.domainPathRules.enableRecordResponsesForAllRules();
|
|
1475
|
+
}
|
|
1476
|
+
if (this.config.proxy?.baseUrl) {
|
|
1477
|
+
this.config.proxy = {
|
|
1478
|
+
...this.config.proxy,
|
|
1479
|
+
recordOnMiss: next,
|
|
1480
|
+
};
|
|
1481
|
+
const client = this.httpClient;
|
|
1482
|
+
client.setProxyRecordOnMiss?.(next);
|
|
1483
|
+
}
|
|
1484
|
+
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
|
|
1485
|
+
}
|
|
1486
|
+
/** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
|
|
1487
|
+
isRecordMode() {
|
|
1488
|
+
return this.config.recordMode === true;
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Whether new recordings store full response bodies (true) or request-only stubs (false, default).
|
|
1492
|
+
* Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
|
|
1493
|
+
*/
|
|
1494
|
+
setRecordResponses(enabled) {
|
|
1495
|
+
const next = Boolean(enabled);
|
|
1496
|
+
this.recordResponsesOverride = next;
|
|
1497
|
+
this.config.recordResponses = next;
|
|
1498
|
+
if (this.config.proxy) {
|
|
1499
|
+
this.config.proxy = {
|
|
1500
|
+
...this.config.proxy,
|
|
1501
|
+
recordResponses: next,
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
const client = this.httpClient;
|
|
1505
|
+
client.setProxyRecordResponses?.(next);
|
|
1506
|
+
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
|
|
1507
|
+
}
|
|
1508
|
+
/** True when new recordings include response bodies (not request-only stubs). */
|
|
1509
|
+
isRecordResponses() {
|
|
1510
|
+
if (this.config.proxy?.baseUrl) {
|
|
1511
|
+
return (0, mockifyer_core_1.resolveRecordResponses)(this.recordResponsesOverride ?? this.config.proxy.recordResponses);
|
|
1512
|
+
}
|
|
1513
|
+
return (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ?? this.config.recordResponses);
|
|
1514
|
+
}
|
|
1372
1515
|
/**
|
|
1373
1516
|
* Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
|
|
1374
1517
|
* (mock lookup, recording, dashboard/Redis proxy, etc.).
|
|
@@ -1406,6 +1549,9 @@ class MockifyerClass {
|
|
|
1406
1549
|
}
|
|
1407
1550
|
async reloadMockData(syncFromProject = true) {
|
|
1408
1551
|
await this.databaseProviderInitPromise;
|
|
1552
|
+
// `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
|
|
1553
|
+
// picks up updated pool response bodies from the provider / Metro sync.
|
|
1554
|
+
this.poolResponseCache.clear();
|
|
1409
1555
|
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
1410
1556
|
// For HybridProvider, this will also sync files from project folder to device
|
|
1411
1557
|
if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
|
|
@@ -1495,25 +1641,31 @@ function setupMockifyer(config) {
|
|
|
1495
1641
|
const mockifyerInstance = mockifyer;
|
|
1496
1642
|
const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
|
|
1497
1643
|
global.fetch = async function (input, init) {
|
|
1644
|
+
// Disabled means the real network: do not rebuild the call. The interceptor
|
|
1645
|
+
// bypass flag still runs FetchHTTPClient, which JSON.parses `{`/`[` bodies
|
|
1646
|
+
// (throwing on invalid JSON), JSON.stringifies FormData/Blob/URLSearchParams,
|
|
1647
|
+
// and drops credentials, abort signals, and Request-only method/headers/body.
|
|
1648
|
+
if (!mockifyerInstance.isMockifyerEnabled()) {
|
|
1649
|
+
return await originalFetchForPatched(input, init);
|
|
1650
|
+
}
|
|
1498
1651
|
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
1499
|
-
const method = init?.method || 'GET';
|
|
1500
|
-
const headers = init?.headers || {};
|
|
1501
|
-
const body = init?.body;
|
|
1502
1652
|
// Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
|
|
1503
1653
|
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url) ||
|
|
1504
1654
|
url.includes('api.resend.com') ||
|
|
1505
1655
|
(0, mockifyer_core_1.isMockifyerDashboardPlumbingApiUrl)(url)) {
|
|
1506
1656
|
return await originalFetchForPatched(input, init);
|
|
1507
1657
|
}
|
|
1508
|
-
const
|
|
1658
|
+
const resolved = await (0, resolve_patched_fetch_request_1.resolvePatchedFetchRequest)(input, init);
|
|
1659
|
+
const method = resolved.method;
|
|
1660
|
+
const simpleRequestKey = `${method}:${resolved.url}`;
|
|
1509
1661
|
const isProcessing = mockifyerInstance.processingRequests?.has(simpleRequestKey);
|
|
1510
1662
|
if (isProcessing) {
|
|
1511
1663
|
return await originalFetchForPatched(input, init);
|
|
1512
1664
|
}
|
|
1513
1665
|
let params = undefined;
|
|
1514
|
-
let baseUrl = url;
|
|
1666
|
+
let baseUrl = resolved.url;
|
|
1515
1667
|
try {
|
|
1516
|
-
const urlObj = new URL(url);
|
|
1668
|
+
const urlObj = new URL(resolved.url);
|
|
1517
1669
|
if (urlObj.search) {
|
|
1518
1670
|
params = {};
|
|
1519
1671
|
urlObj.searchParams.forEach((value, key) => {
|
|
@@ -1526,27 +1678,13 @@ function setupMockifyer(config) {
|
|
|
1526
1678
|
catch (error) {
|
|
1527
1679
|
// URL parsing failed, use URL as-is
|
|
1528
1680
|
}
|
|
1529
|
-
let headersObj = {};
|
|
1530
|
-
if (headers instanceof Headers) {
|
|
1531
|
-
headers.forEach((value, key) => {
|
|
1532
|
-
headersObj[key] = value;
|
|
1533
|
-
});
|
|
1534
|
-
}
|
|
1535
|
-
else if (Array.isArray(headers)) {
|
|
1536
|
-
headers.forEach(([key, value]) => {
|
|
1537
|
-
headersObj[key] = value;
|
|
1538
|
-
});
|
|
1539
|
-
}
|
|
1540
|
-
else {
|
|
1541
|
-
headersObj = { ...headers };
|
|
1542
|
-
}
|
|
1543
1681
|
try {
|
|
1544
1682
|
const requestConfig = {
|
|
1545
1683
|
url: baseUrl,
|
|
1546
1684
|
method: method,
|
|
1547
|
-
headers:
|
|
1685
|
+
headers: resolved.headers,
|
|
1548
1686
|
params: params,
|
|
1549
|
-
data:
|
|
1687
|
+
data: resolved.body
|
|
1550
1688
|
};
|
|
1551
1689
|
const response = await httpClient.request(requestConfig);
|
|
1552
1690
|
const responseHeaders = new Headers();
|
|
@@ -1592,6 +1730,10 @@ function setupMockifyer(config) {
|
|
|
1592
1730
|
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
1593
1731
|
extendedClient.setClientId = (lane) => mockifyer.setClientId(lane);
|
|
1594
1732
|
extendedClient.getClientId = () => mockifyer.getClientId();
|
|
1733
|
+
extendedClient.setRecordMode = (enabled) => mockifyer.setRecordMode(enabled);
|
|
1734
|
+
extendedClient.isRecordMode = () => mockifyer.isRecordMode();
|
|
1735
|
+
extendedClient.setRecordResponses = (enabled) => mockifyer.setRecordResponses(enabled);
|
|
1736
|
+
extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
|
|
1595
1737
|
extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
|
|
1596
1738
|
extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
|
|
1597
1739
|
extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
|
|
@@ -91,6 +91,16 @@ export declare function bufferAtlasBodySpill(relativePath: string, text: string)
|
|
|
91
91
|
relativePath?: string;
|
|
92
92
|
error?: string;
|
|
93
93
|
};
|
|
94
|
+
/**
|
|
95
|
+
* Write hop bodies for an Atlas HTML render.
|
|
96
|
+
*
|
|
97
|
+
* Device uploads sit in the Metro spill buffer and are often omitted from the
|
|
98
|
+
* render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
|
|
99
|
+
* Flush that buffer before writing the payload. Buffering the payload first
|
|
100
|
+
* evicts older spills once the in-memory cap is hit, and those files are then
|
|
101
|
+
* missing from disk.
|
|
102
|
+
*/
|
|
103
|
+
export declare function persistAtlasRenderBodySpills(outDir: string, bodySpills: Record<string, string> | undefined): number;
|
|
94
104
|
/**
|
|
95
105
|
* Metro middleware function
|
|
96
106
|
*/
|