@sgedda/mockifyer-fetch 1.8.106 → 1.8.107
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/README.md +155 -0
- package/dist/clients/fetch-client.d.ts +1 -1
- package/dist/clients/fetch-client.js +4 -2
- package/dist/core-proxy.browser.d.ts +19 -0
- package/dist/core-proxy.browser.js +57 -0
- package/dist/index.browser.d.ts +52 -0
- package/dist/index.browser.js +107 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +32 -1562
- package/dist/mockifyer-class.d.ts +123 -0
- package/dist/mockifyer-class.js +1306 -0
- package/dist/node-capabilities.browser.d.ts +6 -0
- package/dist/node-capabilities.browser.js +110 -0
- package/dist/node-capabilities.d.ts +51 -0
- package/dist/node-capabilities.js +6 -0
- package/dist/node-capabilities.node.d.ts +6 -0
- package/dist/node-capabilities.node.js +31 -0
- package/dist/react-native.js +2 -1
- package/package.json +13 -2
- package/src/clients/fetch-client.ts +6 -3
- package/src/core-proxy.browser.ts +62 -0
- package/src/index.browser.ts +166 -0
- package/src/index.ts +32 -1911
- package/src/mockifyer-class.ts +1700 -0
- package/src/node-capabilities.browser.ts +123 -0
- package/src/node-capabilities.node.ts +40 -0
- package/src/node-capabilities.ts +60 -0
- package/src/react-native.ts +2 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
// Fetch-only Mockifyer implementation
|
|
3
|
+
// fs and path are lazy-loaded via dynamic require to avoid breaking browser bundles
|
|
4
|
+
//
|
|
5
|
+
// DO NOT change this to static require() or import - bundlers will fail on browser builds.
|
|
6
|
+
// The dynamic require is hidden inside functions to prevent bundle-time resolution.
|
|
2
7
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
8
|
if (k2 === undefined) k2 = k;
|
|
4
9
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -14,1578 +19,43 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
19
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
20
|
};
|
|
16
21
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
|
|
22
|
+
exports.MockifyerClass = exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
|
|
18
23
|
exports.setupMockifyer = setupMockifyer;
|
|
19
24
|
exports.initMockifyerForDashboardProxy = initMockifyerForDashboardProxy;
|
|
20
25
|
exports.initMockifyerForLocalFilesystem = initMockifyerForLocalFilesystem;
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
// Lazy-load Node.js built-ins (static literal requires, bundler-safe)
|
|
27
|
+
function getFs() {
|
|
28
|
+
// Only works in Node.js
|
|
29
|
+
if (typeof process === 'undefined' || !process.versions?.node) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
// Static require with literal path - bundlers can stub this
|
|
34
|
+
return require('fs');
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
29
39
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
40
|
+
function getPath() {
|
|
41
|
+
if (typeof process === 'undefined' || !process.versions?.node) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
return require('path');
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
34
50
|
}
|
|
35
51
|
// Import from core package
|
|
36
52
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
37
53
|
const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
38
54
|
const core_proxy_1 = require("./core-proxy");
|
|
39
|
-
const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
|
|
40
|
-
const fetch_client_1 = require("./clients/fetch-client");
|
|
41
55
|
const fetch_response_body_1 = require("./utils/fetch-response-body");
|
|
42
56
|
const resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
getRuntimeSessionId() {
|
|
46
|
-
return (0, mockifyer_core_1.resolveActiveMockifyerSessionId)(() => {
|
|
47
|
-
const now = Date.now();
|
|
48
|
-
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
49
|
-
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
50
|
-
this.sessionStartTime = now;
|
|
51
|
-
(0, mockifyer_core_1.setFlightRecorderRuntimeContext)({ sessionId: this.currentSessionId });
|
|
52
|
-
}
|
|
53
|
-
return this.currentSessionId;
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
unwrapResponseInlineTrace(response) {
|
|
57
|
-
const correlation = this.readRequestCorrelation(response.config);
|
|
58
|
-
const parentRequestId = correlation?.requestId?.trim();
|
|
59
|
-
if (!parentRequestId) {
|
|
60
|
-
response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const scenario = this.config.proxy?.scenario?.trim() ||
|
|
64
|
-
(0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
|
|
65
|
-
response.data = (0, mockifyer_core_1.unwrapInlineTraceEnvelopeEmittingNetworkEvents)(response.data, {
|
|
66
|
-
parentRequestId,
|
|
67
|
-
config: this.config,
|
|
68
|
-
scenario,
|
|
69
|
-
clientId: this.config.clientId,
|
|
70
|
-
sessionId: this.getRuntimeSessionId(),
|
|
71
|
-
transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
async applyOutboundCorrelation(config) {
|
|
75
|
-
return (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config, await (0, mockifyer_core_1.resolveNetworkLogIncludeTraceOptionsAsync)(this.config));
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Full outbound URL including `params` — hop logs / Atlas curl / include-trace
|
|
79
|
-
* must not drop the query string (fetch splits search into `config.params`).
|
|
80
|
-
*/
|
|
81
|
-
resolveLoggedRequestUrl(config, fallbackUrl) {
|
|
82
|
-
const raw = (fallbackUrl || config?.url || '').trim();
|
|
83
|
-
if (!raw)
|
|
84
|
-
return '';
|
|
85
|
-
return (0, mockifyer_core_1.appendParamsToUrl)(raw, config?.params);
|
|
86
|
-
}
|
|
87
|
-
/** Best-effort dashboard network log. */
|
|
88
|
-
logNetworkEvent(partial, correlation,
|
|
89
|
-
/** Final outbound header bag (after auth interceptors). */
|
|
90
|
-
requestHeadersSource) {
|
|
91
|
-
const scenario = this.config.proxy?.scenario?.trim() ||
|
|
92
|
-
(0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
|
|
93
|
-
const { requestBody, responseBody, ...eventPartial } = partial;
|
|
94
|
-
const businessResponseBody = (0, mockifyer_core_1.getInlineTraceEnvelopeBusinessBody)(responseBody);
|
|
95
|
-
const requestHeaders = eventPartial.requestHeaders ?? (0, mockifyer_core_1.outboundHeadersToRecord)(requestHeadersSource);
|
|
96
|
-
if (!this.config.proxy?.baseUrl) {
|
|
97
|
-
(0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
|
|
98
|
-
method: eventPartial.method,
|
|
99
|
-
url: eventPartial.url,
|
|
100
|
-
status: eventPartial.status,
|
|
101
|
-
source: eventPartial.source,
|
|
102
|
-
transport: eventPartial.transport ?? 'fetch',
|
|
103
|
-
requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
|
|
104
|
-
parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
|
|
105
|
-
durationMs: eventPartial.durationMs,
|
|
106
|
-
clientId: this.config.clientId ?? eventPartial.clientId ?? null,
|
|
107
|
-
errorMessage: eventPartial.errorMessage,
|
|
108
|
-
requestHeaders,
|
|
109
|
-
requestBody,
|
|
110
|
-
responseBody,
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
(0, mockifyer_core_1.emitMockifyerNetworkEvent)({
|
|
114
|
-
config: this.config,
|
|
115
|
-
scenario,
|
|
116
|
-
clientId: this.config.clientId,
|
|
117
|
-
sessionId: this.getRuntimeSessionId(),
|
|
118
|
-
requestBody,
|
|
119
|
-
responseBody: businessResponseBody,
|
|
120
|
-
event: {
|
|
121
|
-
...eventPartial,
|
|
122
|
-
transport: eventPartial.transport ?? 'fetch',
|
|
123
|
-
requestId: correlation?.requestId ?? eventPartial.requestId,
|
|
124
|
-
parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
|
|
125
|
-
requestHeaders,
|
|
126
|
-
requestBodyPreview: eventPartial.requestBodyPreview,
|
|
127
|
-
responseBodyPreview: eventPartial.responseBodyPreview,
|
|
128
|
-
},
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
stashRequestCorrelation(config, correlation) {
|
|
132
|
-
config.__mockifyer_requestId =
|
|
133
|
-
correlation.requestId;
|
|
134
|
-
config.__mockifyer_parentRequestId =
|
|
135
|
-
correlation.parentRequestId;
|
|
136
|
-
}
|
|
137
|
-
bindStoredHopId(config, mockData, fallback) {
|
|
138
|
-
const adopted = (0, mockifyer_core_1.adoptStoredOutboundRequestId)(config, mockData?.requestId);
|
|
139
|
-
if (adopted) {
|
|
140
|
-
this.stashRequestCorrelation(config, adopted);
|
|
141
|
-
return adopted;
|
|
142
|
-
}
|
|
143
|
-
return fallback;
|
|
144
|
-
}
|
|
145
|
-
readRequestCorrelation(config) {
|
|
146
|
-
const requestId = config.__mockifyer_requestId;
|
|
147
|
-
if (!requestId)
|
|
148
|
-
return undefined;
|
|
149
|
-
const parentRequestId = config.__mockifyer_parentRequestId;
|
|
150
|
-
return parentRequestId ? { requestId, parentRequestId } : { requestId };
|
|
151
|
-
}
|
|
152
|
-
/** Attach dashboard lookup id onto thrown fetch/client errors. */
|
|
153
|
-
throwWithMockifyerRequestId(error) {
|
|
154
|
-
const err = error;
|
|
155
|
-
const hopRequestId = err?.config?.__mockifyer_requestId;
|
|
156
|
-
const requestId = (0, mockifyer_core_1.resolveMockifyerRequestIdForError)({
|
|
157
|
-
hopRequestId,
|
|
158
|
-
responseHeaders: err?.response?.headers,
|
|
159
|
-
});
|
|
160
|
-
throw (0, mockifyer_core_1.attachMockifyerRequestIdToError)(error, requestId);
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Serve stored mock body with optional `$pool` resolution from the local fixture pool.
|
|
164
|
-
* Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
|
|
165
|
-
* missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
|
|
166
|
-
*/
|
|
167
|
-
prepareStoredResponseBody(mockData, filename, scenarioPath) {
|
|
168
|
-
const joinPath = path && typeof path.join === 'function' ? path.join.bind(path) : null;
|
|
169
|
-
return (0, mockifyer_core_1.prepareMockResponseBody)(mockData, (0, mockifyer_core_1.createServeTimeClock)(this.config), {
|
|
170
|
-
loadPoolResponse: (0, mockifyer_core_1.createServeTimePoolResponseLoader)({
|
|
171
|
-
mockDataPath: this.config.mockDataPath,
|
|
172
|
-
nodeFs: (0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs) ? fs : null,
|
|
173
|
-
joinPath,
|
|
174
|
-
cache: this.poolResponseCache,
|
|
175
|
-
}),
|
|
176
|
-
filename,
|
|
177
|
-
scenarioPath,
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
|
|
182
|
-
* cannot load them (React Native). Tries database provider, then Metro.
|
|
183
|
-
*/
|
|
184
|
-
async warmPoolResponseCache(mockData) {
|
|
185
|
-
if (!(0, mockifyer_core_1.arePoolRefsEnabled)() || !(0, mockifyer_core_1.containsPoolRefs)(mockData.response?.data)) {
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
if ((0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs)) {
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
const ids = (0, mockifyer_core_1.collectPoolRefIds)(mockData.response.data);
|
|
192
|
-
for (const id of ids) {
|
|
193
|
-
if (this.poolResponseCache.has(id)) {
|
|
194
|
-
continue;
|
|
195
|
-
}
|
|
196
|
-
const fromProvider = await this.loadPoolResponseFromProvider(id);
|
|
197
|
-
if (fromProvider) {
|
|
198
|
-
this.poolResponseCache.set(id, fromProvider);
|
|
199
|
-
continue;
|
|
200
|
-
}
|
|
201
|
-
const fromMetro = await this.loadPoolResponseFromMetro(id);
|
|
202
|
-
if (fromMetro) {
|
|
203
|
-
this.poolResponseCache.set(id, fromMetro);
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
async loadPoolResponseFromProvider(id) {
|
|
208
|
-
const provider = this.databaseProvider;
|
|
209
|
-
if (!provider || typeof provider.loadPoolResponseItem !== 'function') {
|
|
210
|
-
return undefined;
|
|
211
|
-
}
|
|
212
|
-
try {
|
|
213
|
-
return (await provider.loadPoolResponseItem(id)) ?? undefined;
|
|
214
|
-
}
|
|
215
|
-
catch (error) {
|
|
216
|
-
mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from provider:`, error);
|
|
217
|
-
return undefined;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
async loadPoolResponseFromMetro(id) {
|
|
221
|
-
const metroPort = this.config.databaseProvider?.options?.metroPort ?? 8081;
|
|
222
|
-
const originalFetch = global.__mockifyer_original_fetch ||
|
|
223
|
-
(typeof fetch !== 'undefined' ? fetch : undefined);
|
|
224
|
-
if (!originalFetch) {
|
|
225
|
-
return undefined;
|
|
226
|
-
}
|
|
227
|
-
try {
|
|
228
|
-
const url = `http://localhost:${metroPort}/mockifyer-pool-response?id=${encodeURIComponent(id)}`;
|
|
229
|
-
const response = await originalFetch(url);
|
|
230
|
-
if (!response.ok) {
|
|
231
|
-
return undefined;
|
|
232
|
-
}
|
|
233
|
-
const payload = (await response.json());
|
|
234
|
-
if (payload.success && payload.item?.responseItemId && payload.item.response) {
|
|
235
|
-
return payload.item;
|
|
236
|
-
}
|
|
237
|
-
return undefined;
|
|
238
|
-
}
|
|
239
|
-
catch (error) {
|
|
240
|
-
mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from Metro:`, error);
|
|
241
|
-
return undefined;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
constructor(config) {
|
|
245
|
-
this.processingRequests = new Set();
|
|
246
|
-
this.savingResponses = new Set();
|
|
247
|
-
/** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
|
|
248
|
-
this.databaseProviderInitPromise = Promise.resolve();
|
|
249
|
-
this.currentSessionId = null;
|
|
250
|
-
this.sessionStartTime = 0;
|
|
251
|
-
this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
252
|
-
/**
|
|
253
|
-
* Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
|
|
254
|
-
* unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
|
|
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;
|
|
262
|
-
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
263
|
-
if (config.databaseProvider && config.databaseProvider.type) {
|
|
264
|
-
const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
|
|
265
|
-
if (!supportedTypes.includes(config.databaseProvider.type)) {
|
|
266
|
-
throw new Error(`Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
|
|
267
|
-
`Supported types: ${supportedTypes.join(', ')}. ` +
|
|
268
|
-
`Please use one of the supported provider types.`);
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
// Validate and normalize conflicting settings
|
|
272
|
-
if (config.recordMode && config.failOnMissingMock) {
|
|
273
|
-
mockifyer_core_2.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
|
|
274
|
-
'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
|
|
275
|
-
'Setting failOnMissingMock to false.');
|
|
276
|
-
config.failOnMissingMock = false;
|
|
277
|
-
}
|
|
278
|
-
// Validate conflicting similar match settings
|
|
279
|
-
if (config.similarMatchIgnoreAllQueryParams &&
|
|
280
|
-
config.similarMatchRequiredParams &&
|
|
281
|
-
config.similarMatchRequiredParams.length > 0) {
|
|
282
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
|
|
283
|
-
'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
|
|
284
|
-
'similarMatchRequiredParams will be ignored.');
|
|
285
|
-
// Clear similarMatchRequiredParams to avoid confusion
|
|
286
|
-
config.similarMatchRequiredParams = undefined;
|
|
287
|
-
}
|
|
288
|
-
// Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
|
|
289
|
-
if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
|
|
290
|
-
if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
|
|
291
|
-
config.useSimilarMatch = true;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
// Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
|
|
295
|
-
if (config.similarMatchIgnoreAllQueryParams) {
|
|
296
|
-
if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
|
|
297
|
-
config.useSimilarMatch = true;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
let launchClientId;
|
|
301
|
-
if (config.useLaunchArgumentsClientId) {
|
|
302
|
-
const key = config.launchArgumentClientIdKey ?? mockifyer_core_1.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
|
|
303
|
-
launchClientId = (0, mockifyer_core_1.tryGetClientIdFromLaunchArguments)(key);
|
|
304
|
-
if (launchClientId) {
|
|
305
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
// Store config BEFORE any modifications
|
|
309
|
-
this.config = { ...config }; // Create a copy to avoid mutations
|
|
310
|
-
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
311
|
-
if (launchClientId) {
|
|
312
|
-
this.config.clientId = launchClientId;
|
|
313
|
-
}
|
|
314
|
-
else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
|
|
315
|
-
Boolean(this.config.proxy?.baseUrl?.trim())) {
|
|
316
|
-
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
317
|
-
this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
|
|
318
|
-
}
|
|
319
|
-
else {
|
|
320
|
-
this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
|
|
321
|
-
}
|
|
322
|
-
this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
|
|
323
|
-
this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
|
|
324
|
-
config: this.config,
|
|
325
|
-
getRecordMode: () => this.config.recordMode === true,
|
|
326
|
-
});
|
|
327
|
-
this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
|
|
328
|
-
if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
|
|
329
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
|
|
330
|
-
'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.');
|
|
331
|
-
}
|
|
332
|
-
this.runtimeEnabled = (0, mockifyer_core_1.resolveInitialRuntimeEnabled)({
|
|
333
|
-
initialRuntimeEnabled: config.initialRuntimeEnabled,
|
|
334
|
-
startDisabled: config.startDisabled,
|
|
335
|
-
runtimeMode: config.runtimeMode,
|
|
336
|
-
launchScenarioPresent: (0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)(),
|
|
337
|
-
});
|
|
338
|
-
if (!this.runtimeEnabled) {
|
|
339
|
-
const reason = typeof config.initialRuntimeEnabled === 'boolean'
|
|
340
|
-
? 'persisted / initialRuntimeEnabled: false'
|
|
341
|
-
: config.runtimeMode === 'manual'
|
|
342
|
-
? 'runtimeMode: "manual"'
|
|
343
|
-
: 'startDisabled: true';
|
|
344
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
|
|
345
|
-
}
|
|
346
|
-
else if ((0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)()) {
|
|
347
|
-
mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).');
|
|
348
|
-
}
|
|
349
|
-
else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
|
|
350
|
-
mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).');
|
|
351
|
-
}
|
|
352
|
-
(0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
|
|
353
|
-
(0, mockifyer_core_1.configureAtlas)(this.config, {
|
|
354
|
-
scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
|
|
355
|
-
clientId: this.config.clientId ?? null,
|
|
356
|
-
});
|
|
357
|
-
(0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
|
|
358
|
-
clientId: this.config.clientId,
|
|
359
|
-
scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
|
|
360
|
-
});
|
|
361
|
-
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
362
|
-
const raw = typeof process !== 'undefined'
|
|
363
|
-
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
364
|
-
: '';
|
|
365
|
-
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
|
|
366
|
-
this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
// Initialize test generator if test generation is enabled
|
|
370
|
-
if (config.generateTests?.enabled) {
|
|
371
|
-
this.testGenerator = new mockifyer_core_1.TestGenerator();
|
|
372
|
-
}
|
|
373
|
-
// Initialize database provider if specified
|
|
374
|
-
if (config.databaseProvider && config.databaseProvider.type) {
|
|
375
|
-
const providerConfig = {
|
|
376
|
-
...config.databaseProvider,
|
|
377
|
-
options: {
|
|
378
|
-
...config.databaseProvider.options,
|
|
379
|
-
mockDataPath: config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
|
|
380
|
-
clientId: this.config.clientId,
|
|
381
|
-
getClientId: () => this.config.clientId,
|
|
382
|
-
},
|
|
383
|
-
};
|
|
384
|
-
this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, providerConfig);
|
|
385
|
-
const initResult = this.databaseProvider.initialize();
|
|
386
|
-
// Handle async initialization (expo-filesystem / hybrid providers)
|
|
387
|
-
if (initResult instanceof Promise) {
|
|
388
|
-
this.databaseProviderInitPromise = initResult.catch((error) => {
|
|
389
|
-
mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
|
|
390
|
-
});
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
else {
|
|
394
|
-
// Fallback to Node.js filesystem
|
|
395
|
-
this.ensureMockDataDirectory();
|
|
396
|
-
}
|
|
397
|
-
// Create fetch HTTP client
|
|
398
|
-
this.httpClient = new fetch_client_1.FetchHTTPClient({
|
|
399
|
-
baseUrl: config.baseUrl,
|
|
400
|
-
defaultHeaders: config.defaultHeaders,
|
|
401
|
-
proxy: config.proxy,
|
|
402
|
-
clientId: this.config.clientId,
|
|
403
|
-
getClientId: () => this.config.clientId,
|
|
404
|
-
getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
|
|
405
|
-
getUpstreamTlsInsecure: () => (0, proxy_upstream_tls_insecure_1.resolveProxyUpstreamTlsInsecure)(this.config),
|
|
406
|
-
getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
|
|
407
|
-
deviceId: this.config.deviceId,
|
|
408
|
-
});
|
|
409
|
-
if (!config.recordSameEndpoints) {
|
|
410
|
-
this.loadMockData();
|
|
411
|
-
}
|
|
412
|
-
// Always set up mock response interceptor (to use existing mocks)
|
|
413
|
-
this.setupMockResponses();
|
|
414
|
-
// Set up response interceptor to save responses when recordMode is enabled
|
|
415
|
-
this.setupResponseInterceptor();
|
|
416
|
-
(0, mockifyer_core_1.logMockifyerInitSummary)(this.config, {
|
|
417
|
-
runtimeMode: this.config.runtimeMode,
|
|
418
|
-
headline: this.config.initLog?.headline,
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
ensureMockDataDirectory() {
|
|
422
|
-
// Only use fs if available (Node.js environment) and no database provider is set
|
|
423
|
-
if (!fs || this.databaseProvider) {
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
if (!fs.existsSync(this.config.mockDataPath)) {
|
|
427
|
-
fs.mkdirSync(this.config.mockDataPath, { recursive: true });
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
generateRequestKey(request) {
|
|
431
|
-
return (0, mockifyer_core_1.generateRequestKey)(request);
|
|
432
|
-
}
|
|
433
|
-
/** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
|
|
434
|
-
usesDashboardProxy() {
|
|
435
|
-
const baseUrl = this.config.proxy?.baseUrl;
|
|
436
|
-
return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
|
|
437
|
-
}
|
|
438
|
-
async findBestMatchingMock(request, options) {
|
|
439
|
-
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
440
|
-
const requestUrl = request?.url || '';
|
|
441
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
442
|
-
return undefined;
|
|
443
|
-
}
|
|
444
|
-
const requestKey = this.generateRequestKey(request);
|
|
445
|
-
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
446
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
447
|
-
return undefined;
|
|
448
|
-
}
|
|
449
|
-
// Use database provider if available, otherwise fallback to filesystem
|
|
450
|
-
if (this.databaseProvider) {
|
|
451
|
-
return await this.findBestMatchingMockFromProvider(request, options);
|
|
452
|
-
}
|
|
453
|
-
// Fallback to Node.js filesystem
|
|
454
|
-
return this.findBestMatchingMockFromFiles(request, options);
|
|
455
|
-
}
|
|
456
|
-
async findBestMatchingMockFromProvider(request, options) {
|
|
457
|
-
if (!this.databaseProvider) {
|
|
458
|
-
return undefined;
|
|
459
|
-
}
|
|
460
|
-
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
461
|
-
const requestUrl = request?.url || '';
|
|
462
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
463
|
-
return undefined;
|
|
464
|
-
}
|
|
465
|
-
const requestKey = this.generateRequestKey(request);
|
|
466
|
-
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
467
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
468
|
-
return undefined;
|
|
469
|
-
}
|
|
470
|
-
// Try exact match first
|
|
471
|
-
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
|
|
472
|
-
if (exactMatch) {
|
|
473
|
-
return exactMatch;
|
|
474
|
-
}
|
|
475
|
-
// Try similar match if enabled
|
|
476
|
-
if (this.config.useSimilarMatch) {
|
|
477
|
-
const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
|
|
478
|
-
if (similarMatches && similarMatches.length > 0) {
|
|
479
|
-
// Return first similar match
|
|
480
|
-
return similarMatches[0];
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
return undefined;
|
|
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
|
-
}
|
|
503
|
-
findBestMatchingMockFromFiles(request, options) {
|
|
504
|
-
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
505
|
-
// Only use fs if available (Node.js environment)
|
|
506
|
-
// This method should never be called when using a database provider
|
|
507
|
-
if (!fs || !path) {
|
|
508
|
-
return undefined;
|
|
509
|
-
}
|
|
510
|
-
const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
|
|
511
|
-
if (!fs.existsSync(resolvedMockDataPath)) {
|
|
512
|
-
console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
|
|
513
|
-
return undefined;
|
|
514
|
-
}
|
|
515
|
-
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath, this.config.clientId);
|
|
516
|
-
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
|
|
517
|
-
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
|
|
518
|
-
if (!fs.existsSync(scenarioPath)) {
|
|
519
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
520
|
-
return undefined;
|
|
521
|
-
}
|
|
522
|
-
const files = this.getAllJsonFiles(scenarioPath);
|
|
523
|
-
const requestKey = this.generateRequestKey(request);
|
|
524
|
-
let exactMatch;
|
|
525
|
-
let similarMatch;
|
|
526
|
-
for (const filePath of files) {
|
|
527
|
-
try {
|
|
528
|
-
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
529
|
-
const mockData = JSON.parse(fileContent);
|
|
530
|
-
if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
|
|
531
|
-
continue;
|
|
532
|
-
}
|
|
533
|
-
const mockKey = this.generateRequestKey(mockData.request);
|
|
534
|
-
const filename = path.relative(scenarioPath, filePath);
|
|
535
|
-
if (mockKey === requestKey) {
|
|
536
|
-
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
537
|
-
includePassthroughMocks,
|
|
538
|
-
filename,
|
|
539
|
-
scenarioPath,
|
|
540
|
-
})) {
|
|
541
|
-
exactMatch = { mockData, filename, filePath };
|
|
542
|
-
break;
|
|
543
|
-
}
|
|
544
|
-
continue;
|
|
545
|
-
}
|
|
546
|
-
if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
|
|
547
|
-
// Check if it's a GraphQL request - skip similar matching for GraphQL
|
|
548
|
-
const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
|
|
549
|
-
request.data &&
|
|
550
|
-
(() => {
|
|
551
|
-
try {
|
|
552
|
-
let bodyData = request.data;
|
|
553
|
-
if (typeof request.data === 'string') {
|
|
554
|
-
bodyData = JSON.parse(request.data);
|
|
555
|
-
}
|
|
556
|
-
return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
|
|
557
|
-
}
|
|
558
|
-
catch {
|
|
559
|
-
return false;
|
|
560
|
-
}
|
|
561
|
-
})();
|
|
562
|
-
if (!isGraphQL) {
|
|
563
|
-
try {
|
|
564
|
-
const requestUrl = new URL(request.url);
|
|
565
|
-
const mockUrl = new URL(mockData.request.url);
|
|
566
|
-
// Check if pathnames match (exact or pattern-based)
|
|
567
|
-
const requestPathname = requestUrl.pathname;
|
|
568
|
-
const mockPathname = mockUrl.pathname;
|
|
569
|
-
const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
|
|
570
|
-
// Check for exact pathname match
|
|
571
|
-
const exactPathnameMatch = mockPathname === requestPathname;
|
|
572
|
-
// Check for pattern-based match (e.g., /posts/71 matches /posts/17 when similarMatchIgnoreAllQueryParams is true)
|
|
573
|
-
// This allows matching paths with different IDs when we're ignoring query params
|
|
574
|
-
let patternMatch = false;
|
|
575
|
-
if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
|
|
576
|
-
// Extract base path by removing the last segment (ID)
|
|
577
|
-
// /posts/71 -> /posts, /users/2/todos -> /users/2
|
|
578
|
-
const requestSegments = requestPathname.split('/').filter(s => s);
|
|
579
|
-
const mockSegments = mockPathname.split('/').filter(s => s);
|
|
580
|
-
// Match if base paths are the same (same number of segments, all but last match)
|
|
581
|
-
if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
|
|
582
|
-
const requestBase = requestSegments.slice(0, -1);
|
|
583
|
-
const mockBase = mockSegments.slice(0, -1);
|
|
584
|
-
patternMatch = requestBase.join('/') === mockBase.join('/');
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
const pathnameMatch = exactPathnameMatch || patternMatch;
|
|
588
|
-
// Check similar match
|
|
589
|
-
if (pathnameMatch && methodMatch) {
|
|
590
|
-
// If ignoreAllQueryParams is set, skip query param checking entirely
|
|
591
|
-
if (this.config.similarMatchIgnoreAllQueryParams) {
|
|
592
|
-
// Ignore all query params, match on path and method only
|
|
593
|
-
}
|
|
594
|
-
else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
|
|
595
|
-
// Check if required parameters match (if configured)
|
|
596
|
-
const requestParams = request.queryParams || {};
|
|
597
|
-
const mockParams = mockData.request.queryParams || {};
|
|
598
|
-
const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
|
|
599
|
-
const requestValue = requestParams[paramName];
|
|
600
|
-
const mockValue = mockParams[paramName];
|
|
601
|
-
return requestValue === undefined && mockValue === undefined
|
|
602
|
-
? true
|
|
603
|
-
: String(requestValue || '') === String(mockValue || '');
|
|
604
|
-
});
|
|
605
|
-
if (!allRequiredMatch) {
|
|
606
|
-
continue; // Required parameter differs, skip this mock
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
610
|
-
includePassthroughMocks,
|
|
611
|
-
filename,
|
|
612
|
-
scenarioPath,
|
|
613
|
-
})) {
|
|
614
|
-
similarMatch = { mockData, filename, filePath };
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
catch (e) {
|
|
619
|
-
continue;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
catch (error) {
|
|
625
|
-
mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
return exactMatch || similarMatch;
|
|
629
|
-
}
|
|
630
|
-
loadMockData() {
|
|
631
|
-
// Skip if using database provider or fs not available
|
|
632
|
-
if (this.databaseProvider || !fs) {
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
if (fs.existsSync(this.config.mockDataPath)) {
|
|
636
|
-
fs.readdirSync(this.config.mockDataPath)
|
|
637
|
-
.filter(file => file.endsWith('.json'));
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
setupMockResponses() {
|
|
641
|
-
this.httpClient.interceptors.request.use(async (config) => {
|
|
642
|
-
// CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
|
|
643
|
-
if (!this.runtimeEnabled) {
|
|
644
|
-
config.__mockifyer_bypass = true;
|
|
645
|
-
return config;
|
|
646
|
-
}
|
|
647
|
-
// CRITICAL: Completely bypass Mockifyer interception for sync endpoints
|
|
648
|
-
// This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
|
|
649
|
-
const url = config.url || '';
|
|
650
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
|
|
651
|
-
// Mark this request to completely skip Mockifyer processing
|
|
652
|
-
config.__mockifyer_skip_save = true;
|
|
653
|
-
config.__mockifyer_bypass = true;
|
|
654
|
-
return config;
|
|
655
|
-
}
|
|
656
|
-
if ((0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
|
|
657
|
-
config.__mockifyer_bypass = true;
|
|
658
|
-
return config;
|
|
659
|
-
}
|
|
660
|
-
if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers)) {
|
|
661
|
-
config.__mockifyer_bypass = true;
|
|
662
|
-
return config;
|
|
663
|
-
}
|
|
664
|
-
if (!(0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config)) {
|
|
665
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request');
|
|
666
|
-
config.__mockifyer_bypass = true;
|
|
667
|
-
return config;
|
|
668
|
-
}
|
|
669
|
-
let correlation = await this.applyOutboundCorrelation(config);
|
|
670
|
-
this.stashRequestCorrelation(config, correlation);
|
|
671
|
-
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
672
|
-
const rawParams = config.params || {};
|
|
673
|
-
const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
|
|
674
|
-
const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
675
|
-
? anonymizedQueryParams
|
|
676
|
-
: undefined;
|
|
677
|
-
const request = {
|
|
678
|
-
method: config.method || 'GET',
|
|
679
|
-
url: config.url || '',
|
|
680
|
-
headers: config.headers || {},
|
|
681
|
-
data: config.data,
|
|
682
|
-
queryParams: normalizedParams
|
|
683
|
-
};
|
|
684
|
-
const requestKey = this.generateRequestKey(request);
|
|
685
|
-
// Store request key for response interceptor
|
|
686
|
-
config.__mockifyer_requestKey = requestKey;
|
|
687
|
-
// Store request start time for duration calculation
|
|
688
|
-
config.__mockifyer_startTime = Date.now();
|
|
689
|
-
// Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
|
|
690
|
-
// from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
|
|
691
|
-
if (this.usesDashboardProxy()) {
|
|
692
|
-
return config;
|
|
693
|
-
}
|
|
694
|
-
this.domainPathRules.discover(request.url, this.config.baseUrl);
|
|
695
|
-
const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
|
|
696
|
-
config.__mockifyer_domain_path_may_record = trafficGate.mayRecord;
|
|
697
|
-
if (!trafficGate.mayReplay) {
|
|
698
|
-
mockifyer_core_2.logger.debug(`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
|
|
699
|
-
(trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)'));
|
|
700
|
-
return config;
|
|
701
|
-
}
|
|
702
|
-
const cachedMock = await this.findBestMatchingMock(request);
|
|
703
|
-
// Return cached mock if found
|
|
704
|
-
if (cachedMock) {
|
|
705
|
-
const { mockData, filename, filePath } = cachedMock;
|
|
706
|
-
correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
|
|
707
|
-
if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
|
|
708
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
709
|
-
(filePath ? ` (${filePath})` : ''));
|
|
710
|
-
const hitScenarioPath = path
|
|
711
|
-
? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
712
|
-
: undefined;
|
|
713
|
-
if (hitScenarioPath) {
|
|
714
|
-
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
|
|
715
|
-
}
|
|
716
|
-
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
717
|
-
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
718
|
-
}
|
|
719
|
-
const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
|
|
720
|
-
const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
|
|
721
|
-
this.logNetworkEvent({
|
|
722
|
-
method: (request.method || 'GET').toUpperCase(),
|
|
723
|
-
url: this.resolveLoggedRequestUrl(config, request.url),
|
|
724
|
-
source: 'mock-hit',
|
|
725
|
-
status: effectiveStatus,
|
|
726
|
-
requestHash: (0, mockifyer_core_1.networkEventHashFromRequestKey)(requestKey),
|
|
727
|
-
requestBody: request.data,
|
|
728
|
-
responseBody: mockResponseBody,
|
|
729
|
-
}, correlation, request.headers ?? config.headers);
|
|
730
|
-
const responseHeaders = {
|
|
731
|
-
...mockData.response.headers,
|
|
732
|
-
'x-mockifyer': 'true',
|
|
733
|
-
'x-mockifyer-timestamp': mockData.timestamp,
|
|
734
|
-
'x-mockifyer-filename': filename,
|
|
735
|
-
'x-mockifyer-filepath': filePath
|
|
736
|
-
};
|
|
737
|
-
await this.warmPoolResponseCache(mockData);
|
|
738
|
-
const mockResponse = {
|
|
739
|
-
data: mockResponseBody,
|
|
740
|
-
status: effectiveStatus,
|
|
741
|
-
statusText: 'OK',
|
|
742
|
-
headers: responseHeaders,
|
|
743
|
-
config: config
|
|
744
|
-
};
|
|
745
|
-
return {
|
|
746
|
-
...config,
|
|
747
|
-
__mockResponse: Promise.resolve(mockResponse),
|
|
748
|
-
__mockifyer_requestKey: requestKey
|
|
749
|
-
};
|
|
750
|
-
}
|
|
751
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
|
|
752
|
-
(filePath ? ` (${filePath})` : ''));
|
|
753
|
-
config.__mockifyer_matchedMock = cachedMock;
|
|
754
|
-
}
|
|
755
|
-
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
756
|
-
if (this.config.recordMode) {
|
|
757
|
-
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
758
|
-
if (limitCheck.limitReached && limitCheck.error) {
|
|
759
|
-
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
760
|
-
// Return a mock error response instead of making a real API call
|
|
761
|
-
const responseHeaders = {
|
|
762
|
-
'x-mockifyer': 'true',
|
|
763
|
-
'x-mockifyer-limit-reached': 'true',
|
|
764
|
-
'content-type': 'application/json'
|
|
765
|
-
};
|
|
766
|
-
const mockErrorResponse = {
|
|
767
|
-
data: {
|
|
768
|
-
error: limitCheck.error.message,
|
|
769
|
-
message: limitCheck.error.message,
|
|
770
|
-
limitReached: true,
|
|
771
|
-
maxRequests: limitCheck.error.maxRequests,
|
|
772
|
-
currentScenario: limitCheck.error.currentScenario
|
|
773
|
-
},
|
|
774
|
-
status: 429, // Too Many Requests
|
|
775
|
-
statusText: 'Too Many Requests',
|
|
776
|
-
headers: responseHeaders,
|
|
777
|
-
config: config
|
|
778
|
-
};
|
|
779
|
-
return {
|
|
780
|
-
...config,
|
|
781
|
-
__mockResponse: Promise.resolve(mockErrorResponse),
|
|
782
|
-
__mockifyer_requestKey: requestKey,
|
|
783
|
-
__mockifyer_limit_reached: true
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
if (this.config.failOnMissingMock) {
|
|
788
|
-
throw new Error(`No mock data found for request: ${this.generateRequestKey(request)}`);
|
|
789
|
-
}
|
|
790
|
-
return config;
|
|
791
|
-
});
|
|
792
|
-
}
|
|
793
|
-
setupResponseInterceptor() {
|
|
794
|
-
this.httpClient.interceptors.response.use(async (response) => {
|
|
795
|
-
// CRITICAL: Check for skip flag FIRST (set by request interceptor for sync endpoints)
|
|
796
|
-
// This completely bypasses Mockifyer interception for sync endpoints
|
|
797
|
-
if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
|
|
798
|
-
return response;
|
|
799
|
-
}
|
|
800
|
-
// CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
|
|
801
|
-
// Check multiple ways to get the URL in case response.config is undefined
|
|
802
|
-
const url = response.config?.url || response.request?.responseURL || response.url || response.config?.url || '';
|
|
803
|
-
// CRITICAL: Check URL FIRST before any other processing
|
|
804
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
|
|
805
|
-
// Mark as bypassed to prevent any further processing
|
|
806
|
-
response.config.__mockifyer_skip_save = true;
|
|
807
|
-
response.config.__mockifyer_bypass = true;
|
|
808
|
-
return response;
|
|
809
|
-
}
|
|
810
|
-
// Clean up processing requests tracking
|
|
811
|
-
const requestKey = response.config.__mockifyer_requestKey;
|
|
812
|
-
if (requestKey) {
|
|
813
|
-
this.processingRequests.delete(requestKey);
|
|
814
|
-
}
|
|
815
|
-
// CRITICAL: Check response data for Metro rejection messages (defense in depth)
|
|
816
|
-
// This catches any responses that might have gotten through
|
|
817
|
-
try {
|
|
818
|
-
let responseDataStr = '';
|
|
819
|
-
let responseDataObj = null;
|
|
820
|
-
if (typeof response.data === 'string') {
|
|
821
|
-
responseDataStr = response.data;
|
|
822
|
-
try {
|
|
823
|
-
responseDataObj = JSON.parse(response.data);
|
|
824
|
-
}
|
|
825
|
-
catch (e) {
|
|
826
|
-
// Not JSON, that's fine
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
else if (response.data) {
|
|
830
|
-
// Try to stringify, but handle circular references
|
|
831
|
-
try {
|
|
832
|
-
responseDataStr = JSON.stringify(response.data);
|
|
833
|
-
responseDataObj = response.data;
|
|
834
|
-
}
|
|
835
|
-
catch (stringifyError) {
|
|
836
|
-
// If stringify fails, try to get a string representation
|
|
837
|
-
responseDataStr = String(response.data);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
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));
|
|
848
|
-
if (hasRejectionMessage || hasRejectionInObject) {
|
|
849
|
-
return response;
|
|
850
|
-
}
|
|
851
|
-
// CRITICAL: Check for sync endpoint URLs in response data
|
|
852
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
|
|
853
|
-
return response;
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
catch (e) {
|
|
857
|
-
// Ignore errors - continue processing
|
|
858
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
|
|
859
|
-
}
|
|
860
|
-
const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
|
|
861
|
-
const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
|
|
862
|
-
if (isMocked || isLimitReached) {
|
|
863
|
-
// Local mock hits are logged in the request interceptor; proxy mock hits must
|
|
864
|
-
// be recorded here before early return (otherwise flight recorder stays empty).
|
|
865
|
-
const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
|
|
866
|
-
if (shouldLogMockOrLimit) {
|
|
867
|
-
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
868
|
-
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
869
|
-
const startTime = response.config.__mockifyer_startTime;
|
|
870
|
-
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
871
|
-
this.logNetworkEvent({
|
|
872
|
-
method: reqMethod,
|
|
873
|
-
url: reqUrl,
|
|
874
|
-
source: isLimitReached ? 'error' : 'mock-hit',
|
|
875
|
-
status: response.status,
|
|
876
|
-
durationMs,
|
|
877
|
-
transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
|
|
878
|
-
requestBody: response.config?.data,
|
|
879
|
-
responseBody: response.data,
|
|
880
|
-
...(isLimitReached
|
|
881
|
-
? {
|
|
882
|
-
errorMessage: typeof response.data === 'object' &&
|
|
883
|
-
response.data !== null &&
|
|
884
|
-
'message' in response.data
|
|
885
|
-
? String(response.data.message)
|
|
886
|
-
: 'Request limit reached',
|
|
887
|
-
}
|
|
888
|
-
: {}),
|
|
889
|
-
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
890
|
-
}
|
|
891
|
-
// Mock hits return before the upstream path. Still emit nested service
|
|
892
|
-
// hops and strip mockifyerTrace so the caller sees the business body.
|
|
893
|
-
this.unwrapResponseInlineTrace(response);
|
|
894
|
-
return response;
|
|
895
|
-
}
|
|
896
|
-
if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
|
|
897
|
-
await this.maybeMirrorProxyRecordingToClient(response);
|
|
898
|
-
}
|
|
899
|
-
const matchedMock = response.config.__mockifyer_matchedMock;
|
|
900
|
-
if (matchedMock) {
|
|
901
|
-
const startTime = response.config.__mockifyer_startTime;
|
|
902
|
-
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
903
|
-
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
904
|
-
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
905
|
-
// Parent hop first, then unwrap nested service hops from downstream services.
|
|
906
|
-
this.logNetworkEvent({
|
|
907
|
-
method: reqMethod,
|
|
908
|
-
url: reqUrl,
|
|
909
|
-
source: 'upstream',
|
|
910
|
-
status: response.status,
|
|
911
|
-
durationMs,
|
|
912
|
-
requestBody: response.config?.data,
|
|
913
|
-
responseBody: response.data,
|
|
914
|
-
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
915
|
-
this.unwrapResponseInlineTrace(response);
|
|
916
|
-
const capturedResponse = {
|
|
917
|
-
status: response.status,
|
|
918
|
-
data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
|
|
919
|
-
headers: response.headers || {},
|
|
920
|
-
};
|
|
921
|
-
if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
|
|
922
|
-
await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
|
|
923
|
-
}
|
|
924
|
-
const liveScenarioPath = path
|
|
925
|
-
? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
926
|
-
: undefined;
|
|
927
|
-
if (liveScenarioPath) {
|
|
928
|
-
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
|
|
929
|
-
}
|
|
930
|
-
const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, (0, mockifyer_core_1.createServeTimeClock)(this.config), { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
|
|
931
|
-
response.data = clientResponse.data;
|
|
932
|
-
response.status = clientResponse.status;
|
|
933
|
-
delete response.config.__mockifyer_matchedMock;
|
|
934
|
-
return response;
|
|
935
|
-
}
|
|
936
|
-
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
937
|
-
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
938
|
-
this.logNetworkEvent({
|
|
939
|
-
method: reqMethod,
|
|
940
|
-
url: reqUrl,
|
|
941
|
-
source: 'upstream',
|
|
942
|
-
status: response.status,
|
|
943
|
-
durationMs: typeof response.config?.metadata?.durationMs === 'number'
|
|
944
|
-
? response.config.metadata.durationMs
|
|
945
|
-
: undefined,
|
|
946
|
-
requestBody: response.config?.data,
|
|
947
|
-
responseBody: response.data,
|
|
948
|
-
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
949
|
-
this.unwrapResponseInlineTrace(response);
|
|
950
|
-
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
951
|
-
// When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
|
|
952
|
-
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
953
|
-
await this.saveResponse(response);
|
|
954
|
-
}
|
|
955
|
-
return response;
|
|
956
|
-
}, async (error) => {
|
|
957
|
-
const requestKey = error.config?.__mockifyer_requestKey;
|
|
958
|
-
if (requestKey) {
|
|
959
|
-
this.processingRequests.delete(requestKey);
|
|
960
|
-
}
|
|
961
|
-
const reqUrl = this.resolveLoggedRequestUrl(error.config);
|
|
962
|
-
if (reqUrl) {
|
|
963
|
-
this.logNetworkEvent({
|
|
964
|
-
method: (error.config?.method || 'GET').toUpperCase(),
|
|
965
|
-
url: reqUrl,
|
|
966
|
-
source: 'error',
|
|
967
|
-
status: error.response?.status,
|
|
968
|
-
errorMessage: error?.message ?? String(error),
|
|
969
|
-
requestBody: error.config?.data,
|
|
970
|
-
responseBody: error.response?.data,
|
|
971
|
-
}, this.readRequestCorrelation(error.config), error.config?.headers);
|
|
972
|
-
}
|
|
973
|
-
this.throwWithMockifyerRequestId(error);
|
|
974
|
-
});
|
|
975
|
-
}
|
|
976
|
-
/**
|
|
977
|
-
* When dashboard proxy records to Redis, optionally persist the same payload next to the client
|
|
978
|
-
* (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
|
|
979
|
-
*/
|
|
980
|
-
async maybeMirrorProxyRecordingToClient(response) {
|
|
981
|
-
const rec = response.mockifyerProxyRecording;
|
|
982
|
-
if (!rec?.recordedToStore || !rec.storedMock) {
|
|
983
|
-
return;
|
|
984
|
-
}
|
|
985
|
-
const hash = rec.hash?.trim();
|
|
986
|
-
const scenarioName = rec.scenarioName?.trim();
|
|
987
|
-
const mockData = rec.storedMock;
|
|
988
|
-
const providerType = this.config.databaseProvider?.type;
|
|
989
|
-
await (0, core_proxy_1.mirrorProxyRecordingToClient)({
|
|
990
|
-
config: this.config,
|
|
991
|
-
mockDataPath: this.config.mockDataPath,
|
|
992
|
-
recording: rec,
|
|
993
|
-
databaseProvider: this.databaseProvider,
|
|
994
|
-
databaseProviderInitPromise: this.databaseProviderInitPromise,
|
|
995
|
-
logPrefix: 'Mockifyer-Fetch',
|
|
996
|
-
});
|
|
997
|
-
if (providerType === 'hybrid' && hash && scenarioName && mockData) {
|
|
998
|
-
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
999
|
-
}
|
|
1000
|
-
else if (!fs && hash && scenarioName && mockData) {
|
|
1001
|
-
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
|
|
1005
|
-
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
1006
|
-
const fetchFn = global.__mockifyer_original_fetch || fetch;
|
|
1007
|
-
if (!fetchFn) {
|
|
1008
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
|
|
1009
|
-
return;
|
|
1010
|
-
}
|
|
1011
|
-
try {
|
|
1012
|
-
const body = JSON.stringify({
|
|
1013
|
-
__mockifyerProxyMirror: true,
|
|
1014
|
-
mockData,
|
|
1015
|
-
scenarioName,
|
|
1016
|
-
relativePath: `redis/${hash}.json`,
|
|
1017
|
-
});
|
|
1018
|
-
const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
|
|
1019
|
-
method: 'POST',
|
|
1020
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1021
|
-
body,
|
|
1022
|
-
});
|
|
1023
|
-
const text = await res.text().catch(() => '');
|
|
1024
|
-
if (!res.ok) {
|
|
1025
|
-
mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
|
-
try {
|
|
1029
|
-
const parsed = JSON.parse(text);
|
|
1030
|
-
if (parsed.success === false) {
|
|
1031
|
-
mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
|
|
1032
|
-
return;
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1035
|
-
catch {
|
|
1036
|
-
// non-JSON response
|
|
1037
|
-
}
|
|
1038
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
|
|
1039
|
-
}
|
|
1040
|
-
catch (e) {
|
|
1041
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
async saveResponse(response) {
|
|
1045
|
-
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
1046
|
-
if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
|
|
1047
|
-
return;
|
|
1048
|
-
}
|
|
1049
|
-
// If using a proxy for upstream calls, do not save locally.
|
|
1050
|
-
// Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
|
|
1051
|
-
if (this.config.proxy?.baseUrl) {
|
|
1052
|
-
return;
|
|
1053
|
-
}
|
|
1054
|
-
if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
|
|
1055
|
-
mockifyer_core_2.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
|
|
1056
|
-
return;
|
|
1057
|
-
}
|
|
1058
|
-
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
1059
|
-
if (url && (0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
|
|
1060
|
-
return;
|
|
1061
|
-
}
|
|
1062
|
-
const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
|
|
1063
|
-
if (url &&
|
|
1064
|
-
(0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
|
|
1065
|
-
return;
|
|
1066
|
-
}
|
|
1067
|
-
const mayRecordFlag = response.config?.__mockifyer_domain_path_may_record;
|
|
1068
|
-
if (mayRecordFlag === false) {
|
|
1069
|
-
return;
|
|
1070
|
-
}
|
|
1071
|
-
if (mayRecordFlag !== true) {
|
|
1072
|
-
this.domainPathRules.discover(url, this.config.baseUrl);
|
|
1073
|
-
const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
|
|
1074
|
-
if (!gate.mayRecord) {
|
|
1075
|
-
return;
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
1079
|
-
// This is a defense-in-depth measure
|
|
1080
|
-
try {
|
|
1081
|
-
let responseDataStr = '';
|
|
1082
|
-
if (typeof response.data === 'string') {
|
|
1083
|
-
responseDataStr = response.data;
|
|
1084
|
-
}
|
|
1085
|
-
else if (response.data) {
|
|
1086
|
-
try {
|
|
1087
|
-
responseDataStr = JSON.stringify(response.data);
|
|
1088
|
-
}
|
|
1089
|
-
catch (stringifyError) {
|
|
1090
|
-
responseDataStr = String(response.data);
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
// CRITICAL: Check for Metro rejection message
|
|
1094
|
-
if (responseDataStr && responseDataStr.includes('Cannot save Mockifyer sync endpoint')) {
|
|
1095
|
-
return;
|
|
1096
|
-
}
|
|
1097
|
-
// CRITICAL: Check for sync endpoint URLs in response data
|
|
1098
|
-
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
|
|
1099
|
-
return;
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
catch (e) {
|
|
1103
|
-
// Ignore JSON stringify errors
|
|
1104
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
|
|
1105
|
-
}
|
|
1106
|
-
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
1107
|
-
const rawParams = response.config.params || {};
|
|
1108
|
-
const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
|
|
1109
|
-
const saveLookupRequest = {
|
|
1110
|
-
method: response.config.method?.toUpperCase() || 'GET',
|
|
1111
|
-
url: response.config.url || '',
|
|
1112
|
-
headers: {},
|
|
1113
|
-
data: response.config.data,
|
|
1114
|
-
queryParams: normalizedParams,
|
|
1115
|
-
};
|
|
1116
|
-
const requestKey = this.generateRequestKey(saveLookupRequest);
|
|
1117
|
-
if (this.savingResponses.has(requestKey)) {
|
|
1118
|
-
return;
|
|
1119
|
-
}
|
|
1120
|
-
const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
|
|
1121
|
-
includePassthroughMocks: true,
|
|
1122
|
-
});
|
|
1123
|
-
const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
|
|
1124
|
-
if (saveDecision.action === 'skip') {
|
|
1125
|
-
if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
|
|
1126
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
|
|
1127
|
-
}
|
|
1128
|
-
return;
|
|
1129
|
-
}
|
|
1130
|
-
this.savingResponses.add(requestKey);
|
|
1131
|
-
try {
|
|
1132
|
-
const rawParamsForSave = response.config.params || {};
|
|
1133
|
-
const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
|
|
1134
|
-
const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
1135
|
-
? anonymizedQueryParams
|
|
1136
|
-
: undefined;
|
|
1137
|
-
const now = Date.now();
|
|
1138
|
-
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
1139
|
-
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
1140
|
-
this.sessionStartTime = now;
|
|
1141
|
-
}
|
|
1142
|
-
const startTime = response.config.__mockifyer_startTime;
|
|
1143
|
-
const duration = startTime ? Date.now() - startTime : undefined;
|
|
1144
|
-
const correlation = this.readRequestCorrelation(response.config);
|
|
1145
|
-
const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
|
|
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,
|
|
1159
|
-
response: {
|
|
1160
|
-
status: response.status,
|
|
1161
|
-
data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
|
|
1162
|
-
headers: response.headers || {},
|
|
1163
|
-
},
|
|
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
|
-
});
|
|
1179
|
-
(0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
|
|
1180
|
-
if (this.databaseProvider) {
|
|
1181
|
-
try {
|
|
1182
|
-
await this.databaseProvider.save(mockData);
|
|
1183
|
-
if (this.config.generateTests?.enabled) {
|
|
1184
|
-
await this.generateTestForMock(mockData);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
catch (error) {
|
|
1188
|
-
console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
|
|
1189
|
-
throw error;
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
else if (fs && path) {
|
|
1193
|
-
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
|
|
1194
|
-
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
|
|
1195
|
-
(0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
|
|
1196
|
-
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
1197
|
-
if (limitCheck.limitReached && limitCheck.error) {
|
|
1198
|
-
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
1199
|
-
return;
|
|
1200
|
-
}
|
|
1201
|
-
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1202
|
-
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1203
|
-
mockifyer_core_2.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
|
|
1204
|
-
}
|
|
1205
|
-
else {
|
|
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 });
|
|
1211
|
-
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1212
|
-
mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`);
|
|
1213
|
-
}
|
|
1214
|
-
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
1215
|
-
await this.generateTestForMock(mockData);
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
else {
|
|
1219
|
-
console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
|
|
1220
|
-
}
|
|
1221
|
-
await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
|
|
1222
|
-
}
|
|
1223
|
-
finally {
|
|
1224
|
-
this.savingResponses.delete(requestKey);
|
|
1225
|
-
}
|
|
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
|
-
}
|
|
1272
|
-
async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
|
|
1273
|
-
const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
|
|
1274
|
-
(0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
|
|
1275
|
-
if (this.databaseProvider) {
|
|
1276
|
-
await this.databaseProvider.save(updated);
|
|
1277
|
-
return;
|
|
1278
|
-
}
|
|
1279
|
-
if (fs && cachedMock.filePath) {
|
|
1280
|
-
fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
|
|
1281
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
/**
|
|
1285
|
-
* Simple path resolution fallback for React Native (when path module is stubbed)
|
|
1286
|
-
*/
|
|
1287
|
-
resolvePath(...parts) {
|
|
1288
|
-
if (path && typeof path.resolve === 'function') {
|
|
1289
|
-
return path.resolve(...parts);
|
|
1290
|
-
}
|
|
1291
|
-
// Fallback: simple string-based path resolution
|
|
1292
|
-
const cwd = typeof process !== 'undefined' && process.cwd ? process.cwd() : '.';
|
|
1293
|
-
const joined = parts
|
|
1294
|
-
.filter(p => p)
|
|
1295
|
-
.join('/')
|
|
1296
|
-
.replace(/\/+/g, '/')
|
|
1297
|
-
.replace(/^\.\//, '');
|
|
1298
|
-
if (joined.startsWith('/')) {
|
|
1299
|
-
return joined;
|
|
1300
|
-
}
|
|
1301
|
-
return `${cwd}/${joined}`.replace(/\/+/g, '/');
|
|
1302
|
-
}
|
|
1303
|
-
/**
|
|
1304
|
-
* Simple dirname fallback for React Native (when path module is stubbed)
|
|
1305
|
-
*/
|
|
1306
|
-
dirname(filePath) {
|
|
1307
|
-
if (path && typeof path.dirname === 'function') {
|
|
1308
|
-
return path.dirname(filePath);
|
|
1309
|
-
}
|
|
1310
|
-
// Fallback: extract directory from path string
|
|
1311
|
-
const lastSlash = filePath.lastIndexOf('/');
|
|
1312
|
-
if (lastSlash <= 0) {
|
|
1313
|
-
return '.';
|
|
1314
|
-
}
|
|
1315
|
-
return filePath.substring(0, lastSlash);
|
|
1316
|
-
}
|
|
1317
|
-
/**
|
|
1318
|
-
* Generates test file for a mock
|
|
1319
|
-
*/
|
|
1320
|
-
async generateTestForMock(mockData) {
|
|
1321
|
-
if (!this.testGenerator) {
|
|
1322
|
-
return;
|
|
1323
|
-
}
|
|
1324
|
-
// Check if fs is available for writing test files
|
|
1325
|
-
// In React Native runtime, fs is not available, but in Metro bundler (Node.js) it should be
|
|
1326
|
-
// Try to require it dynamically if not already available
|
|
1327
|
-
let testFs = fs;
|
|
1328
|
-
if (!testFs) {
|
|
1329
|
-
try {
|
|
1330
|
-
testFs = require('fs');
|
|
1331
|
-
}
|
|
1332
|
-
catch (e) {
|
|
1333
|
-
return;
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
// Use the available fs - ensure it's defined and has required methods
|
|
1337
|
-
if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
const fsToUse = testFs;
|
|
1341
|
-
try {
|
|
1342
|
-
const options = {
|
|
1343
|
-
framework: this.config.generateTests?.framework || 'jest',
|
|
1344
|
-
outputPath: this.config.generateTests?.outputPath || './tests/generated',
|
|
1345
|
-
testPattern: this.config.generateTests?.testPattern || '{endpoint}.test.ts',
|
|
1346
|
-
includeSetup: this.config.generateTests?.includeSetup !== false,
|
|
1347
|
-
groupBy: this.config.generateTests?.groupBy || 'file',
|
|
1348
|
-
httpClientType: 'fetch'
|
|
1349
|
-
};
|
|
1350
|
-
const testCode = this.testGenerator.generateTest(mockData, options);
|
|
1351
|
-
const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
|
|
1352
|
-
// Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
|
|
1353
|
-
// Use our fallback path resolution that works even when path module is stubbed
|
|
1354
|
-
const absoluteTestPath = this.resolvePath(testFilePath);
|
|
1355
|
-
// Ensure test directory exists
|
|
1356
|
-
const testDir = this.dirname(absoluteTestPath);
|
|
1357
|
-
if (!fsToUse.existsSync(testDir)) {
|
|
1358
|
-
fsToUse.mkdirSync(testDir, { recursive: true });
|
|
1359
|
-
}
|
|
1360
|
-
// Check if test file already exists
|
|
1361
|
-
if (fsToUse.existsSync(absoluteTestPath)) {
|
|
1362
|
-
// Extract test info to check if test already exists
|
|
1363
|
-
const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
|
|
1364
|
-
const testName = this.generateTestNameFromInfo(testInfo);
|
|
1365
|
-
// Check if test already exists
|
|
1366
|
-
const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
|
|
1367
|
-
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
1368
|
-
return;
|
|
1369
|
-
}
|
|
1370
|
-
// Extract test code without imports and describe wrapper
|
|
1371
|
-
const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
|
|
1372
|
-
if (testMatch) {
|
|
1373
|
-
// Append test to existing describe block
|
|
1374
|
-
const newTest = testMatch[0];
|
|
1375
|
-
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
1376
|
-
fsToUse.writeFileSync(absoluteTestPath, updatedContent);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
else {
|
|
1380
|
-
// Create new test file
|
|
1381
|
-
fsToUse.writeFileSync(absoluteTestPath, testCode);
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
catch (error) {
|
|
1385
|
-
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error generating test:', error);
|
|
1386
|
-
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
|
|
1387
|
-
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error message:', error?.message);
|
|
1388
|
-
// Don't throw - test generation failure shouldn't break mock saving
|
|
1389
|
-
}
|
|
1390
|
-
}
|
|
1391
|
-
/**
|
|
1392
|
-
* Helper to generate test name from test info
|
|
1393
|
-
*/
|
|
1394
|
-
generateTestNameFromInfo(testInfo) {
|
|
1395
|
-
const method = testInfo.method.toUpperCase();
|
|
1396
|
-
const endpoint = testInfo.endpoint;
|
|
1397
|
-
if (testInfo.isGraphQL && testInfo.graphQLQuery) {
|
|
1398
|
-
const operationMatch = testInfo.graphQLQuery.match(/(?:query|mutation|subscription)\s+(\w+)/);
|
|
1399
|
-
if (operationMatch) {
|
|
1400
|
-
return `should execute ${operationMatch[1]} query`;
|
|
1401
|
-
}
|
|
1402
|
-
return 'should execute GraphQL query';
|
|
1403
|
-
}
|
|
1404
|
-
return `should ${method} ${endpoint}`;
|
|
1405
|
-
}
|
|
1406
|
-
anonymizeHeaders(headers) {
|
|
1407
|
-
const defaultHeadersToAnonymize = [
|
|
1408
|
-
'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
|
|
1409
|
-
'x-auth-token', 'x-access-token', 'bearer'
|
|
1410
|
-
];
|
|
1411
|
-
const headersToAnonymize = this.config.anonymizeHeaders !== undefined
|
|
1412
|
-
? this.config.anonymizeHeaders
|
|
1413
|
-
: defaultHeadersToAnonymize;
|
|
1414
|
-
if (headersToAnonymize.length === 0) {
|
|
1415
|
-
return headers;
|
|
1416
|
-
}
|
|
1417
|
-
const anonymized = { ...headers };
|
|
1418
|
-
const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
|
|
1419
|
-
Object.keys(anonymized).forEach(key => {
|
|
1420
|
-
if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
|
|
1421
|
-
anonymized[key] = '***';
|
|
1422
|
-
}
|
|
1423
|
-
});
|
|
1424
|
-
return anonymized;
|
|
1425
|
-
}
|
|
1426
|
-
anonymizeQueryParams(params) {
|
|
1427
|
-
const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
|
|
1428
|
-
const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
|
|
1429
|
-
? this.config.anonymizeQueryParams
|
|
1430
|
-
: defaultParamsToAnonymize;
|
|
1431
|
-
if (paramsToAnonymize.length === 0) {
|
|
1432
|
-
return params;
|
|
1433
|
-
}
|
|
1434
|
-
const anonymized = { ...params };
|
|
1435
|
-
const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
|
|
1436
|
-
Object.keys(anonymized).forEach(key => {
|
|
1437
|
-
if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
|
|
1438
|
-
anonymized[key] = '***';
|
|
1439
|
-
}
|
|
1440
|
-
});
|
|
1441
|
-
return anonymized;
|
|
1442
|
-
}
|
|
1443
|
-
/**
|
|
1444
|
-
* Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
|
|
1445
|
-
* Does not re-read native launch arguments or environment variables.
|
|
1446
|
-
*/
|
|
1447
|
-
setClientId(lane) {
|
|
1448
|
-
const t = String(lane).trim();
|
|
1449
|
-
if (!t) {
|
|
1450
|
-
throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
|
|
1451
|
-
}
|
|
1452
|
-
this.config.clientId = t;
|
|
1453
|
-
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
|
|
1454
|
-
}
|
|
1455
|
-
/** Current logical lane id (same value used for isolation). */
|
|
1456
|
-
getClientId() {
|
|
1457
|
-
return this.config.clientId;
|
|
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
|
-
}
|
|
1515
|
-
/**
|
|
1516
|
-
* Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
|
|
1517
|
-
* (mock lookup, recording, dashboard/Redis proxy, etc.).
|
|
1518
|
-
* When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
|
|
1519
|
-
*/
|
|
1520
|
-
enableMockifyer() {
|
|
1521
|
-
this.runtimeEnabled = true;
|
|
1522
|
-
mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
|
|
1523
|
-
void this.persistRuntimeEnabledState(true);
|
|
1524
|
-
}
|
|
1525
|
-
/**
|
|
1526
|
-
* Disable Mockifyer at runtime. All subsequent requests will bypass Mockifyer completely
|
|
1527
|
-
* (no dashboard, Redis, proxy, mock lookup, or recording).
|
|
1528
|
-
* When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
|
|
1529
|
-
*/
|
|
1530
|
-
disableMockifyer() {
|
|
1531
|
-
this.runtimeEnabled = false;
|
|
1532
|
-
mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
|
|
1533
|
-
void this.persistRuntimeEnabledState(false);
|
|
1534
|
-
}
|
|
1535
|
-
/**
|
|
1536
|
-
* Check if Mockifyer is currently enabled at runtime.
|
|
1537
|
-
*/
|
|
1538
|
-
isMockifyerEnabled() {
|
|
1539
|
-
return this.runtimeEnabled;
|
|
1540
|
-
}
|
|
1541
|
-
async persistRuntimeEnabledState(enabled) {
|
|
1542
|
-
if (!this.runtimeEnabledStorage) {
|
|
1543
|
-
return;
|
|
1544
|
-
}
|
|
1545
|
-
await (0, mockifyer_core_1.savePersistedRuntimeEnabled)(this.runtimeEnabledStorage, enabled);
|
|
1546
|
-
}
|
|
1547
|
-
getHTTPClient() {
|
|
1548
|
-
return this.httpClient;
|
|
1549
|
-
}
|
|
1550
|
-
async reloadMockData(syncFromProject = true) {
|
|
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();
|
|
1555
|
-
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
1556
|
-
// For HybridProvider, this will also sync files from project folder to device
|
|
1557
|
-
if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
|
|
1558
|
-
if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
|
|
1559
|
-
// Pass syncFromProject flag if provider supports it (HybridProvider)
|
|
1560
|
-
await this.databaseProvider.reload(syncFromProject);
|
|
1561
|
-
}
|
|
1562
|
-
else {
|
|
1563
|
-
await this.databaseProvider.reload();
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
else {
|
|
1567
|
-
// Fallback: try to load mock data if method exists
|
|
1568
|
-
if (typeof this.loadMockData === 'function') {
|
|
1569
|
-
this.loadMockData();
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
// RN Hybrid: pull domain-path-rules.json via Metro before traffic can discover
|
|
1573
|
-
// allowlist defaults that would block already-enabled paths.
|
|
1574
|
-
this.domainPathRules.invalidateCache();
|
|
1575
|
-
await this.domainPathRules.hydrate();
|
|
1576
|
-
}
|
|
1577
|
-
clearStaleCacheEntries() {
|
|
1578
|
-
return 0; // No cache in fetch implementation
|
|
1579
|
-
}
|
|
1580
|
-
async clearAllMocks() {
|
|
1581
|
-
if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
|
|
1582
|
-
await this.databaseProvider.clearAll();
|
|
1583
|
-
}
|
|
1584
|
-
else {
|
|
1585
|
-
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
}
|
|
57
|
+
const mockifyer_class_1 = require("./mockifyer-class");
|
|
58
|
+
Object.defineProperty(exports, "MockifyerClass", { enumerable: true, get: function () { return mockifyer_class_1.MockifyerClass; } });
|
|
1589
59
|
function setupMockifyer(config) {
|
|
1590
60
|
// Node-only inbound capture; safe on RN (no-op when not on Node).
|
|
1591
61
|
if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
|
|
@@ -1621,7 +91,7 @@ function setupMockifyer(config) {
|
|
|
1621
91
|
(0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
|
|
1622
92
|
(0, mockifyer_core_1.initializeScenario)(resolvedConfig);
|
|
1623
93
|
(0, mockifyer_core_1.scheduleRuntimeDateSyncFromConfig)(resolvedConfig);
|
|
1624
|
-
const mockifyer = new MockifyerClass(resolvedConfig);
|
|
94
|
+
const mockifyer = new mockifyer_class_1.MockifyerClass(resolvedConfig);
|
|
1625
95
|
const httpClient = mockifyer.getHTTPClient();
|
|
1626
96
|
// Always store original fetch (even if not patching global)
|
|
1627
97
|
let originalFetch;
|