@sgedda/mockifyer-fetch 1.8.106 → 1.8.108
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 +181 -0
- package/dist/clients/fetch-client.d.ts +7 -2
- package/dist/clients/fetch-client.js +47 -7
- package/dist/core-proxy.browser.d.ts +19 -0
- package/dist/core-proxy.browser.js +57 -0
- package/dist/index.browser.d.ts +53 -0
- package/dist/index.browser.js +111 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +41 -1564
- package/dist/mockifyer-class.d.ts +128 -0
- package/dist/mockifyer-class.js +1417 -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/dist/utils/fetch-response-body.d.ts +18 -1
- package/dist/utils/fetch-response-body.js +18 -4
- package/package.json +13 -2
- package/src/clients/fetch-client.ts +62 -10
- package/src/core-proxy.browser.ts +62 -0
- package/src/index.browser.ts +171 -0
- package/src/index.ts +48 -1917
- package/src/mockifyer-class.ts +1830 -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/src/utils/fetch-response-body.ts +38 -1
|
@@ -0,0 +1,1417 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Core MockifyerClass - browser and Node compatible via dependency injection.
|
|
4
|
+
* Only imports browser-safe utilities from @sgedda/mockifyer-core.
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.MockifyerClass = void 0;
|
|
8
|
+
// Browser-safe imports from core
|
|
9
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
10
|
+
const core_proxy_1 = require("./core-proxy");
|
|
11
|
+
// Local imports
|
|
12
|
+
const fetch_client_1 = require("./clients/fetch-client");
|
|
13
|
+
// Lazy-load Node.js built-ins (static literal requires, bundler-safe)
|
|
14
|
+
function getFs() {
|
|
15
|
+
// Only works in Node.js
|
|
16
|
+
if (typeof process === 'undefined' || !process.versions?.node) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
// Static require with literal path - bundlers can stub this
|
|
21
|
+
return require('fs');
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function getPath() {
|
|
28
|
+
if (typeof process === 'undefined' || !process.versions?.node) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
return require('path');
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
class MockifyerClass {
|
|
39
|
+
/** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
|
|
40
|
+
getRuntimeSessionId() {
|
|
41
|
+
return (0, mockifyer_core_1.resolveActiveMockifyerSessionId)(() => {
|
|
42
|
+
const now = Date.now();
|
|
43
|
+
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
44
|
+
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
45
|
+
this.sessionStartTime = now;
|
|
46
|
+
(0, mockifyer_core_1.setFlightRecorderRuntimeContext)({ sessionId: this.currentSessionId });
|
|
47
|
+
}
|
|
48
|
+
return this.currentSessionId;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
unwrapResponseInlineTrace(response) {
|
|
52
|
+
const correlation = this.readRequestCorrelation(response.config);
|
|
53
|
+
const parentRequestId = correlation?.requestId?.trim();
|
|
54
|
+
if (!parentRequestId) {
|
|
55
|
+
response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const scenario = this.config.proxy?.scenario?.trim() ||
|
|
59
|
+
this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
60
|
+
response.data = (0, mockifyer_core_1.unwrapInlineTraceEnvelopeEmittingNetworkEvents)(response.data, {
|
|
61
|
+
parentRequestId,
|
|
62
|
+
config: this.config,
|
|
63
|
+
scenario,
|
|
64
|
+
clientId: this.config.clientId,
|
|
65
|
+
sessionId: this.getRuntimeSessionId(),
|
|
66
|
+
transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
async applyOutboundCorrelation(config) {
|
|
70
|
+
return (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config, await (0, mockifyer_core_1.resolveNetworkLogIncludeTraceOptionsAsync)(this.config));
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Full outbound URL including `params` — hop logs / Atlas curl / include-trace
|
|
74
|
+
* must not drop the query string (fetch splits search into `config.params`).
|
|
75
|
+
*/
|
|
76
|
+
resolveLoggedRequestUrl(config, fallbackUrl) {
|
|
77
|
+
const raw = (fallbackUrl || config?.url || '').trim();
|
|
78
|
+
if (!raw)
|
|
79
|
+
return '';
|
|
80
|
+
return (0, mockifyer_core_1.appendParamsToUrl)(raw, config?.params);
|
|
81
|
+
}
|
|
82
|
+
/** Best-effort dashboard network log. */
|
|
83
|
+
logNetworkEvent(partial, correlation,
|
|
84
|
+
/** Final outbound header bag (after auth interceptors). */
|
|
85
|
+
requestHeadersSource) {
|
|
86
|
+
const scenario = this.config.proxy?.scenario?.trim() ||
|
|
87
|
+
this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
88
|
+
const { requestBody, responseBody, ...eventPartial } = partial;
|
|
89
|
+
const businessResponseBody = (0, mockifyer_core_1.getInlineTraceEnvelopeBusinessBody)(responseBody);
|
|
90
|
+
const requestHeaders = eventPartial.requestHeaders ?? (0, mockifyer_core_1.outboundHeadersToRecord)(requestHeadersSource);
|
|
91
|
+
if (!this.config.proxy?.baseUrl) {
|
|
92
|
+
(0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
|
|
93
|
+
method: eventPartial.method,
|
|
94
|
+
url: eventPartial.url,
|
|
95
|
+
status: eventPartial.status,
|
|
96
|
+
source: eventPartial.source,
|
|
97
|
+
transport: eventPartial.transport ?? 'fetch',
|
|
98
|
+
requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
|
|
99
|
+
parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
|
|
100
|
+
durationMs: eventPartial.durationMs,
|
|
101
|
+
clientId: this.config.clientId ?? eventPartial.clientId ?? null,
|
|
102
|
+
errorMessage: eventPartial.errorMessage,
|
|
103
|
+
requestHeaders,
|
|
104
|
+
requestBody,
|
|
105
|
+
responseBody,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
(0, mockifyer_core_1.emitMockifyerNetworkEvent)({
|
|
109
|
+
config: this.config,
|
|
110
|
+
scenario,
|
|
111
|
+
clientId: this.config.clientId,
|
|
112
|
+
sessionId: this.getRuntimeSessionId(),
|
|
113
|
+
requestBody,
|
|
114
|
+
responseBody: businessResponseBody,
|
|
115
|
+
event: {
|
|
116
|
+
...eventPartial,
|
|
117
|
+
transport: eventPartial.transport ?? 'fetch',
|
|
118
|
+
requestId: correlation?.requestId ?? eventPartial.requestId,
|
|
119
|
+
parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
|
|
120
|
+
requestHeaders,
|
|
121
|
+
requestBodyPreview: eventPartial.requestBodyPreview,
|
|
122
|
+
responseBodyPreview: eventPartial.responseBodyPreview,
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
stashRequestCorrelation(config, correlation) {
|
|
127
|
+
config.__mockifyer_requestId =
|
|
128
|
+
correlation.requestId;
|
|
129
|
+
config.__mockifyer_parentRequestId =
|
|
130
|
+
correlation.parentRequestId;
|
|
131
|
+
}
|
|
132
|
+
bindStoredHopId(config, mockData, fallback) {
|
|
133
|
+
const adopted = (0, mockifyer_core_1.adoptStoredOutboundRequestId)(config, mockData?.requestId);
|
|
134
|
+
if (adopted) {
|
|
135
|
+
this.stashRequestCorrelation(config, adopted);
|
|
136
|
+
return adopted;
|
|
137
|
+
}
|
|
138
|
+
return fallback;
|
|
139
|
+
}
|
|
140
|
+
readRequestCorrelation(config) {
|
|
141
|
+
const requestId = config.__mockifyer_requestId;
|
|
142
|
+
if (!requestId)
|
|
143
|
+
return undefined;
|
|
144
|
+
const parentRequestId = config.__mockifyer_parentRequestId;
|
|
145
|
+
return parentRequestId ? { requestId, parentRequestId } : { requestId };
|
|
146
|
+
}
|
|
147
|
+
/** Attach dashboard lookup id onto thrown fetch/client errors. */
|
|
148
|
+
throwWithMockifyerRequestId(error) {
|
|
149
|
+
const err = error;
|
|
150
|
+
const hopRequestId = err?.config?.__mockifyer_requestId;
|
|
151
|
+
if (hopRequestId) {
|
|
152
|
+
err.mockifyerRequestId = hopRequestId;
|
|
153
|
+
}
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Serve stored mock body with optional `$pool` resolution from the local fixture pool.
|
|
158
|
+
* Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
|
|
159
|
+
* missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
|
|
160
|
+
*/
|
|
161
|
+
prepareStoredResponseBody(mockData, filename, scenarioPath) {
|
|
162
|
+
const fs = getFs();
|
|
163
|
+
const path = getPath();
|
|
164
|
+
const joinPath = path && typeof path.join === 'function' ? path.join.bind(path) : null;
|
|
165
|
+
return (0, mockifyer_core_1.prepareMockResponseBody)(mockData, (0, mockifyer_core_1.createServeTimeClock)(this.config), {
|
|
166
|
+
loadPoolResponse: (0, mockifyer_core_1.createServeTimePoolResponseLoader)({
|
|
167
|
+
mockDataPath: this.config.mockDataPath,
|
|
168
|
+
nodeFs: (0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs) ? fs : null,
|
|
169
|
+
joinPath,
|
|
170
|
+
cache: this.poolResponseCache,
|
|
171
|
+
}),
|
|
172
|
+
filename,
|
|
173
|
+
scenarioPath,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
|
|
178
|
+
* cannot load them (React Native). Tries database provider, then Metro.
|
|
179
|
+
*/
|
|
180
|
+
async warmPoolResponseCache(mockData) {
|
|
181
|
+
if (!(0, mockifyer_core_1.arePoolRefsEnabled)() || !(0, mockifyer_core_1.containsPoolRefs)(mockData.response?.data)) {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const fs = getFs();
|
|
185
|
+
if ((0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs)) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const ids = (0, mockifyer_core_1.collectPoolRefIds)(mockData.response.data);
|
|
189
|
+
for (const id of ids) {
|
|
190
|
+
if (this.poolResponseCache.has(id)) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const fromProvider = await this.loadPoolResponseFromProvider(id);
|
|
194
|
+
if (fromProvider) {
|
|
195
|
+
this.poolResponseCache.set(id, fromProvider);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const fromMetro = await this.loadPoolResponseFromMetro(id);
|
|
199
|
+
if (fromMetro) {
|
|
200
|
+
this.poolResponseCache.set(id, fromMetro);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async loadPoolResponseFromProvider(id) {
|
|
205
|
+
const provider = this.databaseProvider;
|
|
206
|
+
if (!provider || typeof provider.loadPoolResponseItem !== 'function') {
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
return (await provider.loadPoolResponseItem(id)) ?? undefined;
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from provider:`, error);
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
async loadPoolResponseFromMetro(id) {
|
|
218
|
+
const metroPort = this.config.databaseProvider?.options?.metroPort ?? 8081;
|
|
219
|
+
const originalFetch = global.__mockifyer_original_fetch ||
|
|
220
|
+
(typeof fetch !== 'undefined' ? fetch : undefined);
|
|
221
|
+
if (!originalFetch) {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const url = `http://localhost:${metroPort}/mockifyer-pool-response?id=${encodeURIComponent(id)}`;
|
|
226
|
+
const response = await originalFetch(url);
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
const payload = (await response.json());
|
|
231
|
+
if (payload.success && payload.item?.responseItemId && payload.item.response) {
|
|
232
|
+
return payload.item;
|
|
233
|
+
}
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from Metro:`, error);
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
constructor(config, capabilities) {
|
|
242
|
+
this.processingRequests = new Set();
|
|
243
|
+
this.savingResponses = new Set();
|
|
244
|
+
/** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
|
|
245
|
+
this.databaseProviderInitPromise = Promise.resolve();
|
|
246
|
+
this.currentSessionId = null;
|
|
247
|
+
this.sessionStartTime = 0;
|
|
248
|
+
this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
249
|
+
/**
|
|
250
|
+
* Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
|
|
251
|
+
* unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
|
|
252
|
+
*/
|
|
253
|
+
this.poolResponseCache = new Map();
|
|
254
|
+
/**
|
|
255
|
+
* Runtime override for whether local/proxy recordings include response bodies.
|
|
256
|
+
* `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
|
|
257
|
+
*/
|
|
258
|
+
this.recordResponsesOverride = undefined;
|
|
259
|
+
// Import Node capabilities (static require, bundler handles via package.json exports)
|
|
260
|
+
if (!capabilities) {
|
|
261
|
+
// Static require with literal path - package.json browser field maps to .browser.ts
|
|
262
|
+
if (typeof require !== 'undefined') {
|
|
263
|
+
try {
|
|
264
|
+
const nodeModule = require('./node-capabilities.node');
|
|
265
|
+
this.capabilities = nodeModule.nodeCapabilities;
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
throw new Error('[Mockifyer] Failed to load node capabilities. ' +
|
|
269
|
+
'In browser builds, pass capabilities explicitly or use the browser entry point. ' +
|
|
270
|
+
`Error: ${error}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
throw new Error('[Mockifyer] No capabilities provided and require() not available. ' +
|
|
275
|
+
'In browser builds, pass capabilities explicitly or use the browser entry point.');
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
this.capabilities = capabilities;
|
|
280
|
+
}
|
|
281
|
+
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
282
|
+
if (config.databaseProvider && config.databaseProvider.type) {
|
|
283
|
+
const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
|
|
284
|
+
if (!supportedTypes.includes(config.databaseProvider.type)) {
|
|
285
|
+
throw new Error(`Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
|
|
286
|
+
`Supported types: ${supportedTypes.join(', ')}. ` +
|
|
287
|
+
`Please use one of the supported provider types.`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// Validate and normalize conflicting settings
|
|
291
|
+
if (config.recordMode && config.failOnMissingMock) {
|
|
292
|
+
mockifyer_core_1.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
|
|
293
|
+
'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
|
|
294
|
+
'Setting failOnMissingMock to false.');
|
|
295
|
+
config.failOnMissingMock = false;
|
|
296
|
+
}
|
|
297
|
+
// Validate conflicting similar match settings
|
|
298
|
+
if (config.similarMatchIgnoreAllQueryParams &&
|
|
299
|
+
config.similarMatchRequiredParams &&
|
|
300
|
+
config.similarMatchRequiredParams.length > 0) {
|
|
301
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
|
|
302
|
+
'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
|
|
303
|
+
'similarMatchRequiredParams will be ignored.');
|
|
304
|
+
// Clear similarMatchRequiredParams to avoid confusion
|
|
305
|
+
config.similarMatchRequiredParams = undefined;
|
|
306
|
+
}
|
|
307
|
+
// Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
|
|
308
|
+
if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
|
|
309
|
+
if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
|
|
310
|
+
config.useSimilarMatch = true;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
|
|
314
|
+
if (config.similarMatchIgnoreAllQueryParams) {
|
|
315
|
+
if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
|
|
316
|
+
config.useSimilarMatch = true;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
let launchClientId;
|
|
320
|
+
if (config.useLaunchArgumentsClientId) {
|
|
321
|
+
const key = config.launchArgumentClientIdKey ?? mockifyer_core_1.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
|
|
322
|
+
launchClientId = (0, mockifyer_core_1.tryGetClientIdFromLaunchArguments)(key);
|
|
323
|
+
if (launchClientId) {
|
|
324
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// Store config BEFORE any modifications
|
|
328
|
+
this.config = { ...config }; // Create a copy to avoid mutations
|
|
329
|
+
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
330
|
+
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
331
|
+
if (launchClientId) {
|
|
332
|
+
this.config.clientId = launchClientId;
|
|
333
|
+
}
|
|
334
|
+
else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
|
|
335
|
+
Boolean(this.config.proxy?.baseUrl?.trim())) {
|
|
336
|
+
this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
|
|
340
|
+
}
|
|
341
|
+
this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
|
|
342
|
+
this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
|
|
343
|
+
config: this.config,
|
|
344
|
+
getRecordMode: () => this.config.recordMode === true,
|
|
345
|
+
});
|
|
346
|
+
this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
|
|
347
|
+
if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
|
|
348
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
|
|
349
|
+
'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.');
|
|
350
|
+
}
|
|
351
|
+
this.runtimeEnabled = (0, mockifyer_core_1.resolveInitialRuntimeEnabled)({
|
|
352
|
+
initialRuntimeEnabled: config.initialRuntimeEnabled,
|
|
353
|
+
startDisabled: config.startDisabled,
|
|
354
|
+
runtimeMode: config.runtimeMode,
|
|
355
|
+
launchScenarioPresent: (0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)(),
|
|
356
|
+
});
|
|
357
|
+
if (!this.runtimeEnabled) {
|
|
358
|
+
const reason = typeof config.initialRuntimeEnabled === 'boolean'
|
|
359
|
+
? 'persisted / initialRuntimeEnabled: false'
|
|
360
|
+
: config.runtimeMode === 'manual'
|
|
361
|
+
? 'runtimeMode: "manual"'
|
|
362
|
+
: 'startDisabled: true';
|
|
363
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
|
|
364
|
+
}
|
|
365
|
+
else if ((0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)()) {
|
|
366
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).');
|
|
367
|
+
}
|
|
368
|
+
else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
|
|
369
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).');
|
|
370
|
+
}
|
|
371
|
+
(0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
|
|
372
|
+
(0, mockifyer_core_1.configureAtlas)(this.config, {
|
|
373
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
374
|
+
clientId: this.config.clientId ?? null,
|
|
375
|
+
});
|
|
376
|
+
(0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
|
|
377
|
+
clientId: this.config.clientId,
|
|
378
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
379
|
+
});
|
|
380
|
+
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
381
|
+
const raw = typeof process !== 'undefined'
|
|
382
|
+
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
383
|
+
: '';
|
|
384
|
+
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
|
|
385
|
+
this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// Initialize test generator if test generation is enabled
|
|
389
|
+
if (config.generateTests?.enabled) {
|
|
390
|
+
this.testGenerator = new mockifyer_core_1.TestGenerator();
|
|
391
|
+
}
|
|
392
|
+
// Initialize database provider if specified
|
|
393
|
+
if (config.databaseProvider && config.databaseProvider.type) {
|
|
394
|
+
const providerConfig = {
|
|
395
|
+
...config.databaseProvider,
|
|
396
|
+
options: {
|
|
397
|
+
...config.databaseProvider.options,
|
|
398
|
+
mockDataPath: config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
|
|
399
|
+
clientId: this.config.clientId,
|
|
400
|
+
getClientId: () => this.config.clientId,
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, providerConfig);
|
|
404
|
+
const initResult = this.databaseProvider.initialize();
|
|
405
|
+
// Handle async initialization (expo-filesystem / hybrid providers)
|
|
406
|
+
if (initResult instanceof Promise) {
|
|
407
|
+
this.databaseProviderInitPromise = initResult.catch((error) => {
|
|
408
|
+
mockifyer_core_1.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
// Fallback to Node.js filesystem
|
|
414
|
+
this.ensureMockDataDirectory();
|
|
415
|
+
}
|
|
416
|
+
// Create fetch HTTP client
|
|
417
|
+
this.httpClient = new fetch_client_1.FetchHTTPClient({
|
|
418
|
+
baseUrl: config.baseUrl,
|
|
419
|
+
defaultHeaders: config.defaultHeaders,
|
|
420
|
+
proxy: config.proxy,
|
|
421
|
+
clientId: this.config.clientId,
|
|
422
|
+
getClientId: () => this.config.clientId,
|
|
423
|
+
getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
|
|
424
|
+
getUpstreamTlsInsecure: () => (0, mockifyer_core_1.resolveProxyUpstreamTlsInsecure)(this.config),
|
|
425
|
+
getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
|
|
426
|
+
getShouldRecordStreams: () => this.config.recordMode === true && !this.config.proxy?.baseUrl,
|
|
427
|
+
getStreamRecordCaps: () => ({
|
|
428
|
+
maxBytes: this.config.streamRecordMaxBytes,
|
|
429
|
+
maxDurationMs: this.config.streamRecordMaxDurationMs,
|
|
430
|
+
}),
|
|
431
|
+
deviceId: this.config.deviceId,
|
|
432
|
+
});
|
|
433
|
+
if (!config.recordSameEndpoints) {
|
|
434
|
+
this.loadMockData();
|
|
435
|
+
}
|
|
436
|
+
// Always set up mock response interceptor (to use existing mocks)
|
|
437
|
+
this.setupMockResponses();
|
|
438
|
+
// Set up response interceptor to save responses when recordMode is enabled
|
|
439
|
+
this.setupResponseInterceptor();
|
|
440
|
+
(0, mockifyer_core_1.logMockifyerInitSummary)(this.config, {
|
|
441
|
+
runtimeMode: this.config.runtimeMode,
|
|
442
|
+
headline: this.config.initLog?.headline,
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
ensureMockDataDirectory() {
|
|
446
|
+
const fs = getFs();
|
|
447
|
+
// Only use fs if available (Node.js environment) and no database provider is set
|
|
448
|
+
if (!fs || this.databaseProvider) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (!fs.existsSync(this.config.mockDataPath)) {
|
|
452
|
+
fs.mkdirSync(this.config.mockDataPath, { recursive: true });
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
generateRequestKey(request) {
|
|
456
|
+
return (0, mockifyer_core_1.generateRequestKey)(request);
|
|
457
|
+
}
|
|
458
|
+
/** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
|
|
459
|
+
usesDashboardProxy() {
|
|
460
|
+
const baseUrl = this.config.proxy?.baseUrl;
|
|
461
|
+
return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
|
|
462
|
+
}
|
|
463
|
+
async findBestMatchingMock(request, options) {
|
|
464
|
+
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
465
|
+
const requestUrl = request?.url || '';
|
|
466
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
const requestKey = this.generateRequestKey(request);
|
|
470
|
+
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
471
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
// Use database provider if available, otherwise fallback to filesystem
|
|
475
|
+
if (this.databaseProvider) {
|
|
476
|
+
return await this.findBestMatchingMockFromProvider(request, options);
|
|
477
|
+
}
|
|
478
|
+
// Fallback to Node.js filesystem
|
|
479
|
+
return this.findBestMatchingMockFromFiles(request, options);
|
|
480
|
+
}
|
|
481
|
+
async findBestMatchingMockFromProvider(request, options) {
|
|
482
|
+
if (!this.databaseProvider) {
|
|
483
|
+
return undefined;
|
|
484
|
+
}
|
|
485
|
+
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
486
|
+
const requestUrl = request?.url || '';
|
|
487
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
488
|
+
return undefined;
|
|
489
|
+
}
|
|
490
|
+
const requestKey = this.generateRequestKey(request);
|
|
491
|
+
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
492
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
493
|
+
return undefined;
|
|
494
|
+
}
|
|
495
|
+
// Try exact match first
|
|
496
|
+
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
|
|
497
|
+
if (exactMatch) {
|
|
498
|
+
return exactMatch;
|
|
499
|
+
}
|
|
500
|
+
// Try similar match if enabled
|
|
501
|
+
if (this.config.useSimilarMatch) {
|
|
502
|
+
const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
|
|
503
|
+
if (similarMatches && similarMatches.length > 0) {
|
|
504
|
+
// Return first similar match
|
|
505
|
+
return similarMatches[0];
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return undefined;
|
|
509
|
+
}
|
|
510
|
+
getAllJsonFiles(dir) {
|
|
511
|
+
const fs = getFs();
|
|
512
|
+
const path = getPath();
|
|
513
|
+
if (!fs || !path || !fs.existsSync(dir))
|
|
514
|
+
return [];
|
|
515
|
+
const results = [];
|
|
516
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
517
|
+
const fullPath = path.join(dir, entry.name);
|
|
518
|
+
if (entry.isDirectory()) {
|
|
519
|
+
if ((0, mockifyer_core_1.isMockRecordingSidecarDir)(entry.name)) {
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
results.push(...this.getAllJsonFiles(fullPath));
|
|
523
|
+
}
|
|
524
|
+
else if (entry.name.endsWith('.json')) {
|
|
525
|
+
results.push(fullPath);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return results;
|
|
529
|
+
}
|
|
530
|
+
findBestMatchingMockFromFiles(request, options) {
|
|
531
|
+
const fs = getFs();
|
|
532
|
+
const path = getPath();
|
|
533
|
+
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
534
|
+
// Only use fs if available (Node.js environment)
|
|
535
|
+
// This method should never be called when using a database provider
|
|
536
|
+
if (!fs || !path) {
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
|
|
540
|
+
if (!fs.existsSync(resolvedMockDataPath)) {
|
|
541
|
+
console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
|
|
542
|
+
return undefined;
|
|
543
|
+
}
|
|
544
|
+
const currentScenario = this.capabilities.getCurrentScenario(resolvedMockDataPath, this.config.clientId);
|
|
545
|
+
const scenarioPath = this.capabilities.getScenarioFolderPath(resolvedMockDataPath, currentScenario);
|
|
546
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
|
|
547
|
+
if (!fs.existsSync(scenarioPath)) {
|
|
548
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
549
|
+
return undefined;
|
|
550
|
+
}
|
|
551
|
+
const files = this.getAllJsonFiles(scenarioPath);
|
|
552
|
+
const requestKey = this.generateRequestKey(request);
|
|
553
|
+
let exactMatch;
|
|
554
|
+
let similarMatch;
|
|
555
|
+
for (const filePath of files) {
|
|
556
|
+
try {
|
|
557
|
+
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
558
|
+
const mockData = JSON.parse(fileContent);
|
|
559
|
+
if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
const mockKey = this.generateRequestKey(mockData.request);
|
|
563
|
+
const filename = path.relative(scenarioPath, filePath);
|
|
564
|
+
if (mockKey === requestKey) {
|
|
565
|
+
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
566
|
+
includePassthroughMocks,
|
|
567
|
+
filename,
|
|
568
|
+
scenarioPath,
|
|
569
|
+
})) {
|
|
570
|
+
exactMatch = { mockData, filename, filePath };
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
|
|
576
|
+
// Check if it's a GraphQL request - skip similar matching for GraphQL
|
|
577
|
+
const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
|
|
578
|
+
request.data &&
|
|
579
|
+
(() => {
|
|
580
|
+
try {
|
|
581
|
+
let bodyData = request.data;
|
|
582
|
+
if (typeof request.data === 'string') {
|
|
583
|
+
bodyData = JSON.parse(request.data);
|
|
584
|
+
}
|
|
585
|
+
return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
|
|
586
|
+
}
|
|
587
|
+
catch {
|
|
588
|
+
return false;
|
|
589
|
+
}
|
|
590
|
+
})();
|
|
591
|
+
if (!isGraphQL) {
|
|
592
|
+
try {
|
|
593
|
+
const requestUrl = new URL(request.url);
|
|
594
|
+
const mockUrl = new URL(mockData.request.url);
|
|
595
|
+
// Check if pathnames match (exact or pattern-based)
|
|
596
|
+
const requestPathname = requestUrl.pathname;
|
|
597
|
+
const mockPathname = mockUrl.pathname;
|
|
598
|
+
const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
|
|
599
|
+
// Check for exact pathname match
|
|
600
|
+
const exactPathnameMatch = mockPathname === requestPathname;
|
|
601
|
+
// Check for pattern-based match
|
|
602
|
+
let patternMatch = false;
|
|
603
|
+
if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
|
|
604
|
+
const requestSegments = requestPathname.split('/').filter(s => s);
|
|
605
|
+
const mockSegments = mockPathname.split('/').filter(s => s);
|
|
606
|
+
if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
|
|
607
|
+
const requestBase = requestSegments.slice(0, -1);
|
|
608
|
+
const mockBase = mockSegments.slice(0, -1);
|
|
609
|
+
patternMatch = requestBase.join('/') === mockBase.join('/');
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const pathnameMatch = exactPathnameMatch || patternMatch;
|
|
613
|
+
if (pathnameMatch && methodMatch) {
|
|
614
|
+
// If ignoreAllQueryParams is set, skip query param checking entirely
|
|
615
|
+
if (this.config.similarMatchIgnoreAllQueryParams) {
|
|
616
|
+
// Ignore all query params, match on path and method only
|
|
617
|
+
}
|
|
618
|
+
else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
|
|
619
|
+
// Check if required parameters match (if configured)
|
|
620
|
+
const requestParams = request.queryParams || {};
|
|
621
|
+
const mockParams = mockData.request.queryParams || {};
|
|
622
|
+
const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
|
|
623
|
+
const requestValue = requestParams[paramName];
|
|
624
|
+
const mockValue = mockParams[paramName];
|
|
625
|
+
return requestValue === undefined && mockValue === undefined
|
|
626
|
+
? true
|
|
627
|
+
: String(requestValue || '') === String(mockValue || '');
|
|
628
|
+
});
|
|
629
|
+
if (!allRequiredMatch) {
|
|
630
|
+
continue; // Required parameter differs, skip this mock
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
|
|
634
|
+
includePassthroughMocks,
|
|
635
|
+
filename,
|
|
636
|
+
scenarioPath,
|
|
637
|
+
})) {
|
|
638
|
+
similarMatch = { mockData, filename, filePath };
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
catch (e) {
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
catch (error) {
|
|
649
|
+
mockifyer_core_1.logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return exactMatch || similarMatch;
|
|
653
|
+
}
|
|
654
|
+
loadMockData() {
|
|
655
|
+
const fs = getFs();
|
|
656
|
+
// Skip if using database provider or fs not available
|
|
657
|
+
if (this.databaseProvider || !fs) {
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (fs.existsSync(this.config.mockDataPath)) {
|
|
661
|
+
fs.readdirSync(this.config.mockDataPath)
|
|
662
|
+
.filter(file => file.endsWith('.json'));
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
setupMockResponses() {
|
|
666
|
+
this.httpClient.interceptors.request.use(async (config) => {
|
|
667
|
+
// CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
|
|
668
|
+
if (!this.runtimeEnabled) {
|
|
669
|
+
config.__mockifyer_bypass = true;
|
|
670
|
+
return config;
|
|
671
|
+
}
|
|
672
|
+
// CRITICAL: Completely bypass Mockifyer interception for sync endpoints
|
|
673
|
+
const url = config.url || '';
|
|
674
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
|
|
675
|
+
config.__mockifyer_skip_save = true;
|
|
676
|
+
config.__mockifyer_bypass = true;
|
|
677
|
+
return config;
|
|
678
|
+
}
|
|
679
|
+
if ((0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
|
|
680
|
+
config.__mockifyer_bypass = true;
|
|
681
|
+
return config;
|
|
682
|
+
}
|
|
683
|
+
if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers)) {
|
|
684
|
+
config.__mockifyer_bypass = true;
|
|
685
|
+
return config;
|
|
686
|
+
}
|
|
687
|
+
if (!(0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config)) {
|
|
688
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request');
|
|
689
|
+
config.__mockifyer_bypass = true;
|
|
690
|
+
return config;
|
|
691
|
+
}
|
|
692
|
+
let correlation = await this.applyOutboundCorrelation(config);
|
|
693
|
+
this.stashRequestCorrelation(config, correlation);
|
|
694
|
+
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
695
|
+
const rawParams = config.params || {};
|
|
696
|
+
const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
|
|
697
|
+
const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
698
|
+
? anonymizedQueryParams
|
|
699
|
+
: undefined;
|
|
700
|
+
const request = {
|
|
701
|
+
method: config.method || 'GET',
|
|
702
|
+
url: config.url || '',
|
|
703
|
+
headers: config.headers || {},
|
|
704
|
+
data: config.data,
|
|
705
|
+
queryParams: normalizedParams
|
|
706
|
+
};
|
|
707
|
+
const requestKey = this.generateRequestKey(request);
|
|
708
|
+
// Store request key for response interceptor
|
|
709
|
+
config.__mockifyer_requestKey = requestKey;
|
|
710
|
+
// Store request start time for duration calculation
|
|
711
|
+
config.__mockifyer_startTime = Date.now();
|
|
712
|
+
// Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
|
|
713
|
+
// from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
|
|
714
|
+
if (this.usesDashboardProxy()) {
|
|
715
|
+
return config;
|
|
716
|
+
}
|
|
717
|
+
this.domainPathRules.discover(request.url, this.config.baseUrl);
|
|
718
|
+
const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
|
|
719
|
+
config.__mockifyer_domain_path_may_record = trafficGate.mayRecord;
|
|
720
|
+
if (!trafficGate.mayReplay) {
|
|
721
|
+
mockifyer_core_1.logger.debug(`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
|
|
722
|
+
(trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)'));
|
|
723
|
+
return config;
|
|
724
|
+
}
|
|
725
|
+
const cachedMock = await this.findBestMatchingMock(request);
|
|
726
|
+
// Return cached mock if found
|
|
727
|
+
if (cachedMock) {
|
|
728
|
+
const { mockData, filename, filePath } = cachedMock;
|
|
729
|
+
correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
|
|
730
|
+
if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
|
|
731
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
732
|
+
(filePath ? ` (${filePath})` : ''));
|
|
733
|
+
const path = getPath();
|
|
734
|
+
const hitScenarioPath = path
|
|
735
|
+
? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
736
|
+
: undefined;
|
|
737
|
+
if (hitScenarioPath) {
|
|
738
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
|
|
739
|
+
}
|
|
740
|
+
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
741
|
+
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
742
|
+
}
|
|
743
|
+
const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
|
|
744
|
+
const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
|
|
745
|
+
this.logNetworkEvent({
|
|
746
|
+
method: (request.method || 'GET').toUpperCase(),
|
|
747
|
+
url: this.resolveLoggedRequestUrl(config, request.url),
|
|
748
|
+
source: 'mock-hit',
|
|
749
|
+
status: effectiveStatus,
|
|
750
|
+
requestBody: request.data,
|
|
751
|
+
responseBody: mockResponseBody,
|
|
752
|
+
}, correlation, request.headers ?? config.headers);
|
|
753
|
+
const responseHeaders = {
|
|
754
|
+
...mockData.response.headers,
|
|
755
|
+
'x-mockifyer': 'true',
|
|
756
|
+
'x-mockifyer-timestamp': mockData.timestamp,
|
|
757
|
+
'x-mockifyer-filename': filename,
|
|
758
|
+
'x-mockifyer-filepath': filePath
|
|
759
|
+
};
|
|
760
|
+
await this.warmPoolResponseCache(mockData);
|
|
761
|
+
const mockResponse = {
|
|
762
|
+
data: mockResponseBody,
|
|
763
|
+
status: effectiveStatus,
|
|
764
|
+
statusText: 'OK',
|
|
765
|
+
headers: responseHeaders,
|
|
766
|
+
config: config,
|
|
767
|
+
...(mockData.response.stream
|
|
768
|
+
? { mockifyerStoredStream: mockData.response.stream }
|
|
769
|
+
: {}),
|
|
770
|
+
};
|
|
771
|
+
return {
|
|
772
|
+
...config,
|
|
773
|
+
__mockResponse: Promise.resolve(mockResponse),
|
|
774
|
+
__mockifyer_requestKey: requestKey
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
|
|
778
|
+
(filePath ? ` (${filePath})` : ''));
|
|
779
|
+
config.__mockifyer_matchedMock = cachedMock;
|
|
780
|
+
}
|
|
781
|
+
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
782
|
+
if (this.config.recordMode) {
|
|
783
|
+
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
784
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
785
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
786
|
+
const responseHeaders = {
|
|
787
|
+
'x-mockifyer': 'true',
|
|
788
|
+
'x-mockifyer-limit-reached': 'true',
|
|
789
|
+
'content-type': 'application/json'
|
|
790
|
+
};
|
|
791
|
+
const mockErrorResponse = {
|
|
792
|
+
data: {
|
|
793
|
+
error: limitCheck.error.message,
|
|
794
|
+
message: limitCheck.error.message,
|
|
795
|
+
limitReached: true,
|
|
796
|
+
maxRequests: limitCheck.error.maxRequests,
|
|
797
|
+
currentScenario: limitCheck.error.currentScenario
|
|
798
|
+
},
|
|
799
|
+
status: 429,
|
|
800
|
+
statusText: 'Too Many Requests',
|
|
801
|
+
headers: responseHeaders,
|
|
802
|
+
config: config
|
|
803
|
+
};
|
|
804
|
+
return {
|
|
805
|
+
...config,
|
|
806
|
+
__mockResponse: Promise.resolve(mockErrorResponse),
|
|
807
|
+
__mockifyer_requestKey: requestKey,
|
|
808
|
+
__mockifyer_limit_reached: true
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
if (this.config.failOnMissingMock) {
|
|
813
|
+
const scenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
814
|
+
const requestKey = this.generateRequestKey(request);
|
|
815
|
+
throw new Error(`No mock data found for request: ${requestKey}\n` +
|
|
816
|
+
`\n` +
|
|
817
|
+
`Scenario: ${scenario}\n` +
|
|
818
|
+
`Request key: ${requestKey}\n` +
|
|
819
|
+
`\n` +
|
|
820
|
+
`In replay mode with failOnMissingMock=true, all requests must have recorded mocks.\n` +
|
|
821
|
+
`To fix:\n` +
|
|
822
|
+
` 1. Record this request: set recordMode: true\n` +
|
|
823
|
+
` 2. Or preload fixture: databaseProvider: { type: 'memory', options: { fixtures: [...] } }\n` +
|
|
824
|
+
` 3. Or allow passthrough: set failOnMissingMock: false`);
|
|
825
|
+
}
|
|
826
|
+
return config;
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
setupResponseInterceptor() {
|
|
830
|
+
this.httpClient.interceptors.response.use(async (response) => {
|
|
831
|
+
// CRITICAL: Check for skip flag FIRST
|
|
832
|
+
if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
|
|
833
|
+
return response;
|
|
834
|
+
}
|
|
835
|
+
// Clean up processing requests tracking
|
|
836
|
+
const requestKey = response.config.__mockifyer_requestKey;
|
|
837
|
+
if (requestKey) {
|
|
838
|
+
this.processingRequests.delete(requestKey);
|
|
839
|
+
}
|
|
840
|
+
const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
|
|
841
|
+
const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
|
|
842
|
+
if (isMocked || isLimitReached) {
|
|
843
|
+
const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
|
|
844
|
+
if (shouldLogMockOrLimit) {
|
|
845
|
+
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
846
|
+
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
847
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
848
|
+
const startTime = response.config.__mockifyer_startTime;
|
|
849
|
+
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
850
|
+
this.logNetworkEvent({
|
|
851
|
+
method: reqMethod,
|
|
852
|
+
url: reqUrl,
|
|
853
|
+
source: isLimitReached ? 'error' : 'mock-hit',
|
|
854
|
+
status: response.status,
|
|
855
|
+
durationMs,
|
|
856
|
+
transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
|
|
857
|
+
requestBody: response.config?.data,
|
|
858
|
+
responseBody: response.data,
|
|
859
|
+
...(isLimitReached
|
|
860
|
+
? {
|
|
861
|
+
errorMessage: typeof response.data === 'object' &&
|
|
862
|
+
response.data !== null &&
|
|
863
|
+
'message' in response.data
|
|
864
|
+
? String(response.data.message)
|
|
865
|
+
: 'Request limit reached',
|
|
866
|
+
}
|
|
867
|
+
: {}),
|
|
868
|
+
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
869
|
+
}
|
|
870
|
+
// Mock hits return before the upstream path
|
|
871
|
+
this.unwrapResponseInlineTrace(response);
|
|
872
|
+
return response;
|
|
873
|
+
}
|
|
874
|
+
if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
|
|
875
|
+
await this.maybeMirrorProxyRecordingToClient(response);
|
|
876
|
+
}
|
|
877
|
+
const matchedMock = response.config.__mockifyer_matchedMock;
|
|
878
|
+
if (matchedMock) {
|
|
879
|
+
const startTime = response.config.__mockifyer_startTime;
|
|
880
|
+
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
881
|
+
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
882
|
+
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
883
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
884
|
+
this.logNetworkEvent({
|
|
885
|
+
method: reqMethod,
|
|
886
|
+
url: reqUrl,
|
|
887
|
+
source: 'upstream',
|
|
888
|
+
status: response.status,
|
|
889
|
+
durationMs,
|
|
890
|
+
requestBody: response.config?.data,
|
|
891
|
+
responseBody: response.data,
|
|
892
|
+
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
893
|
+
this.unwrapResponseInlineTrace(response);
|
|
894
|
+
const capturedResponse = {
|
|
895
|
+
status: response.status,
|
|
896
|
+
data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
|
|
897
|
+
headers: response.headers || {},
|
|
898
|
+
};
|
|
899
|
+
if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
|
|
900
|
+
await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
|
|
901
|
+
}
|
|
902
|
+
const path = getPath();
|
|
903
|
+
const liveScenarioPath = path
|
|
904
|
+
? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
905
|
+
: undefined;
|
|
906
|
+
if (liveScenarioPath) {
|
|
907
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
|
|
908
|
+
}
|
|
909
|
+
const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, (0, mockifyer_core_1.createServeTimeClock)(this.config), { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
|
|
910
|
+
response.data = clientResponse.data;
|
|
911
|
+
response.status = clientResponse.status;
|
|
912
|
+
delete response.config.__mockifyer_matchedMock;
|
|
913
|
+
return response;
|
|
914
|
+
}
|
|
915
|
+
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
916
|
+
const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
|
|
917
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
918
|
+
this.logNetworkEvent({
|
|
919
|
+
method: reqMethod,
|
|
920
|
+
url: reqUrl,
|
|
921
|
+
source: 'upstream',
|
|
922
|
+
status: response.status,
|
|
923
|
+
durationMs: typeof response.config?.metadata?.durationMs === 'number'
|
|
924
|
+
? response.config.metadata.durationMs
|
|
925
|
+
: undefined,
|
|
926
|
+
requestBody: response.config?.data,
|
|
927
|
+
responseBody: typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
928
|
+
? '[stream]'
|
|
929
|
+
: response.data,
|
|
930
|
+
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
931
|
+
this.unwrapResponseInlineTrace(response);
|
|
932
|
+
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
933
|
+
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
934
|
+
if (response.mockifyerStreamRecording) {
|
|
935
|
+
// Do not await recording — the caller already has the live stream.
|
|
936
|
+
// Persist once the recording branch finishes (caps / EOF).
|
|
937
|
+
void this.saveStreamRecording(response).catch((err) => {
|
|
938
|
+
mockifyer_core_1.logger.error('[Mockifyer-Fetch] Failed to save stream recording:', err);
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
else {
|
|
942
|
+
await this.saveResponse(response);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return response;
|
|
946
|
+
}, async (error) => {
|
|
947
|
+
const requestKey = error.config?.__mockifyer_requestKey;
|
|
948
|
+
if (requestKey) {
|
|
949
|
+
this.processingRequests.delete(requestKey);
|
|
950
|
+
}
|
|
951
|
+
const reqUrl = this.resolveLoggedRequestUrl(error.config);
|
|
952
|
+
if (reqUrl) {
|
|
953
|
+
this.logNetworkEvent({
|
|
954
|
+
method: (error.config?.method || 'GET').toUpperCase(),
|
|
955
|
+
url: reqUrl,
|
|
956
|
+
source: 'error',
|
|
957
|
+
status: error.response?.status,
|
|
958
|
+
errorMessage: error?.message ?? String(error),
|
|
959
|
+
requestBody: error.config?.data,
|
|
960
|
+
responseBody: error.response?.data,
|
|
961
|
+
}, this.readRequestCorrelation(error.config), error.config?.headers);
|
|
962
|
+
}
|
|
963
|
+
this.throwWithMockifyerRequestId(error);
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
async maybeMirrorProxyRecordingToClient(response) {
|
|
967
|
+
const rec = response.mockifyerProxyRecording;
|
|
968
|
+
if (!rec?.recordedToStore || !rec.storedMock) {
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
const hash = rec.hash?.trim();
|
|
972
|
+
const scenarioName = rec.scenarioName?.trim();
|
|
973
|
+
const mockData = rec.storedMock;
|
|
974
|
+
const providerType = this.config.databaseProvider?.type;
|
|
975
|
+
await (0, core_proxy_1.mirrorProxyRecordingToClient)({
|
|
976
|
+
config: this.config,
|
|
977
|
+
mockDataPath: this.config.mockDataPath,
|
|
978
|
+
recording: rec,
|
|
979
|
+
databaseProvider: this.databaseProvider,
|
|
980
|
+
databaseProviderInitPromise: this.databaseProviderInitPromise,
|
|
981
|
+
logPrefix: 'Mockifyer-Fetch',
|
|
982
|
+
});
|
|
983
|
+
const fs = getFs();
|
|
984
|
+
if (providerType === 'hybrid' && hash && scenarioName && mockData) {
|
|
985
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
986
|
+
}
|
|
987
|
+
else if (!fs && hash && scenarioName && mockData) {
|
|
988
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
|
|
992
|
+
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
993
|
+
const fetchFn = global.__mockifyer_original_fetch || fetch;
|
|
994
|
+
if (!fetchFn) {
|
|
995
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
try {
|
|
999
|
+
const body = JSON.stringify({
|
|
1000
|
+
__mockifyerProxyMirror: true,
|
|
1001
|
+
mockData,
|
|
1002
|
+
scenarioName,
|
|
1003
|
+
relativePath: `redis/${hash}.json`,
|
|
1004
|
+
});
|
|
1005
|
+
const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
|
|
1006
|
+
method: 'POST',
|
|
1007
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1008
|
+
body,
|
|
1009
|
+
});
|
|
1010
|
+
const text = await res.text().catch(() => '');
|
|
1011
|
+
if (!res.ok) {
|
|
1012
|
+
mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
const parsed = JSON.parse(text);
|
|
1017
|
+
if (parsed.success === false) {
|
|
1018
|
+
mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
catch {
|
|
1023
|
+
// non-JSON response
|
|
1024
|
+
}
|
|
1025
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
|
|
1026
|
+
}
|
|
1027
|
+
catch (e) {
|
|
1028
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Await background stream capture, then persist concatenated body + stream timeline.
|
|
1033
|
+
* Called without blocking the caller's live ReadableStream.
|
|
1034
|
+
*/
|
|
1035
|
+
async saveStreamRecording(response) {
|
|
1036
|
+
const recording = response.mockifyerStreamRecording;
|
|
1037
|
+
if (!recording) {
|
|
1038
|
+
await this.saveResponse(response);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
const captured = await recording;
|
|
1042
|
+
const withBody = {
|
|
1043
|
+
...response,
|
|
1044
|
+
data: captured.concatenated,
|
|
1045
|
+
mockifyerStoredStream: captured.stream,
|
|
1046
|
+
mockifyerStreamRecording: undefined,
|
|
1047
|
+
};
|
|
1048
|
+
await this.saveResponse(withBody);
|
|
1049
|
+
}
|
|
1050
|
+
async saveResponse(response) {
|
|
1051
|
+
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
1052
|
+
if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
// If using a proxy for upstream calls, do not save locally.
|
|
1056
|
+
if (this.config.proxy?.baseUrl) {
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
|
|
1060
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
1064
|
+
if (url && (0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
|
|
1068
|
+
if (url &&
|
|
1069
|
+
(0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
const mayRecordFlag = response.config?.__mockifyer_domain_path_may_record;
|
|
1073
|
+
if (mayRecordFlag === false) {
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
if (mayRecordFlag !== true) {
|
|
1077
|
+
this.domainPathRules.discover(url, this.config.baseUrl);
|
|
1078
|
+
const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
|
|
1079
|
+
if (!gate.mayRecord) {
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
1084
|
+
const rawParams = response.config.params || {};
|
|
1085
|
+
const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
|
|
1086
|
+
const saveLookupRequest = {
|
|
1087
|
+
method: response.config.method?.toUpperCase() || 'GET',
|
|
1088
|
+
url: response.config.url || '',
|
|
1089
|
+
headers: {},
|
|
1090
|
+
data: response.config.data,
|
|
1091
|
+
queryParams: normalizedParams,
|
|
1092
|
+
};
|
|
1093
|
+
const requestKey = this.generateRequestKey(saveLookupRequest);
|
|
1094
|
+
if (this.savingResponses.has(requestKey)) {
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
|
|
1098
|
+
includePassthroughMocks: true,
|
|
1099
|
+
});
|
|
1100
|
+
const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
|
|
1101
|
+
if (saveDecision.action === 'skip') {
|
|
1102
|
+
if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
|
|
1103
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
|
|
1104
|
+
}
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
this.savingResponses.add(requestKey);
|
|
1108
|
+
try {
|
|
1109
|
+
const rawParamsForSave = response.config.params || {};
|
|
1110
|
+
const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
|
|
1111
|
+
const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
1112
|
+
? anonymizedQueryParams
|
|
1113
|
+
: undefined;
|
|
1114
|
+
const now = Date.now();
|
|
1115
|
+
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
1116
|
+
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
1117
|
+
this.sessionStartTime = now;
|
|
1118
|
+
}
|
|
1119
|
+
const startTime = response.config.__mockifyer_startTime;
|
|
1120
|
+
const duration = startTime ? Date.now() - startTime : undefined;
|
|
1121
|
+
const correlation = this.readRequestCorrelation(response.config);
|
|
1122
|
+
const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
|
|
1123
|
+
const storedRequest = {
|
|
1124
|
+
method: response.config?.method?.toUpperCase() || 'GET',
|
|
1125
|
+
url: response.config?.url || '',
|
|
1126
|
+
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
1127
|
+
data: response.config?.data,
|
|
1128
|
+
queryParams: normalizedParamsForSave,
|
|
1129
|
+
};
|
|
1130
|
+
// Prefer explicit override / config; else request-only default (same as proxy).
|
|
1131
|
+
// Use URL-aware resolution for selective recording.
|
|
1132
|
+
const configValue = this.recordResponsesOverride ??
|
|
1133
|
+
this.config.proxy?.recordResponses ??
|
|
1134
|
+
this.config.recordResponses;
|
|
1135
|
+
const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponsesForUrl)(storedRequest.url, configValue, this.config.baseUrl);
|
|
1136
|
+
const storedStream = response.mockifyerStoredStream;
|
|
1137
|
+
const responseDataForSave = typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
1138
|
+
? ''
|
|
1139
|
+
: response.data;
|
|
1140
|
+
const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
|
|
1141
|
+
request: storedRequest,
|
|
1142
|
+
response: {
|
|
1143
|
+
status: response.status,
|
|
1144
|
+
data: responseDataForSave,
|
|
1145
|
+
headers: response.headers || {},
|
|
1146
|
+
...(storedStream && recordBodies ? { stream: storedStream } : {}),
|
|
1147
|
+
},
|
|
1148
|
+
recordResponses: recordBodies,
|
|
1149
|
+
meta: {
|
|
1150
|
+
timestamp: new Date().toISOString(),
|
|
1151
|
+
duration,
|
|
1152
|
+
sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1153
|
+
? existingMock.mockData.sessionId
|
|
1154
|
+
: this.currentSessionId,
|
|
1155
|
+
requestId: hopIds.requestId,
|
|
1156
|
+
parentRequestId: hopIds.parentRequestId,
|
|
1157
|
+
parentRequestIds: hopIds.parentRequestIds,
|
|
1158
|
+
// Allowlisted URLs (recordBodies=true) should NOT have alwaysUseRealApi
|
|
1159
|
+
// so they replay immediately. Request-only stubs need alwaysUseRealApi.
|
|
1160
|
+
...(!recordBodies
|
|
1161
|
+
? { alwaysUseRealApi: true }
|
|
1162
|
+
: {}),
|
|
1163
|
+
},
|
|
1164
|
+
});
|
|
1165
|
+
(0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
|
|
1166
|
+
if (this.databaseProvider) {
|
|
1167
|
+
try {
|
|
1168
|
+
await this.databaseProvider.save(mockData);
|
|
1169
|
+
if (this.config.generateTests?.enabled) {
|
|
1170
|
+
await this.generateTestForMock(mockData);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
catch (error) {
|
|
1174
|
+
console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
|
|
1175
|
+
throw error;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
else {
|
|
1179
|
+
const fs = getFs();
|
|
1180
|
+
const path = getPath();
|
|
1181
|
+
if (fs && path) {
|
|
1182
|
+
const currentScenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1183
|
+
const scenarioPath = this.capabilities.getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1184
|
+
this.capabilities.ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
1185
|
+
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
1186
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
1187
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1191
|
+
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1192
|
+
mockifyer_core_1.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
|
|
1193
|
+
}
|
|
1194
|
+
else {
|
|
1195
|
+
const { dir, filename } = (0, mockifyer_core_1.getMockFilePath)(mockData, (0, mockifyer_core_1.formatDateStr)((0, mockifyer_core_1.getCurrentDate)()));
|
|
1196
|
+
const filePath = path.join(scenarioPath, dir, filename);
|
|
1197
|
+
fs.mkdirSync(path.join(scenarioPath, dir), { recursive: true });
|
|
1198
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1199
|
+
mockifyer_core_1.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`);
|
|
1200
|
+
}
|
|
1201
|
+
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
1202
|
+
await this.generateTestForMock(mockData);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
else {
|
|
1206
|
+
console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
// Update domain path rule to allow replay for allowlisted responses
|
|
1210
|
+
if (recordBodies) {
|
|
1211
|
+
this.domainPathRules.enableAutoMockForUrl(storedRequest.url, this.config.baseUrl);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
finally {
|
|
1215
|
+
this.savingResponses.delete(requestKey);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
|
|
1219
|
+
const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
|
|
1220
|
+
(0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
|
|
1221
|
+
if (this.databaseProvider) {
|
|
1222
|
+
await this.databaseProvider.save(updated);
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
const fs = getFs();
|
|
1226
|
+
if (fs && cachedMock.filePath) {
|
|
1227
|
+
fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
|
|
1228
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Generates test file for a mock
|
|
1233
|
+
*/
|
|
1234
|
+
async generateTestForMock(mockData) {
|
|
1235
|
+
if (!this.testGenerator) {
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
// Browser: skip test generation (needs fs)
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
anonymizeHeaders(headers) {
|
|
1242
|
+
const defaultHeadersToAnonymize = [
|
|
1243
|
+
'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
|
|
1244
|
+
'x-auth-token', 'x-access-token', 'bearer'
|
|
1245
|
+
];
|
|
1246
|
+
const headersToAnonymize = this.config.anonymizeHeaders !== undefined
|
|
1247
|
+
? this.config.anonymizeHeaders
|
|
1248
|
+
: defaultHeadersToAnonymize;
|
|
1249
|
+
if (headersToAnonymize.length === 0) {
|
|
1250
|
+
return headers;
|
|
1251
|
+
}
|
|
1252
|
+
const anonymized = { ...headers };
|
|
1253
|
+
const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
|
|
1254
|
+
Object.keys(anonymized).forEach(key => {
|
|
1255
|
+
if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
|
|
1256
|
+
anonymized[key] = '***';
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
return anonymized;
|
|
1260
|
+
}
|
|
1261
|
+
anonymizeQueryParams(params) {
|
|
1262
|
+
const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
|
|
1263
|
+
const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
|
|
1264
|
+
? this.config.anonymizeQueryParams
|
|
1265
|
+
: defaultParamsToAnonymize;
|
|
1266
|
+
if (paramsToAnonymize.length === 0) {
|
|
1267
|
+
return params;
|
|
1268
|
+
}
|
|
1269
|
+
const anonymized = { ...params };
|
|
1270
|
+
const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
|
|
1271
|
+
Object.keys(anonymized).forEach(key => {
|
|
1272
|
+
if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
|
|
1273
|
+
anonymized[key] = '***';
|
|
1274
|
+
}
|
|
1275
|
+
});
|
|
1276
|
+
return anonymized;
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
|
|
1280
|
+
* Does not re-read native launch arguments or environment variables.
|
|
1281
|
+
*/
|
|
1282
|
+
setClientId(lane) {
|
|
1283
|
+
const t = String(lane).trim();
|
|
1284
|
+
if (!t) {
|
|
1285
|
+
throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
|
|
1286
|
+
}
|
|
1287
|
+
this.config.clientId = t;
|
|
1288
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
|
|
1289
|
+
}
|
|
1290
|
+
/** Current logical lane id (same value used for isolation). */
|
|
1291
|
+
getClientId() {
|
|
1292
|
+
return this.config.clientId;
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Turn record mode on/off at runtime (dev menus, tests).
|
|
1296
|
+
*/
|
|
1297
|
+
setRecordMode(enabled) {
|
|
1298
|
+
const next = Boolean(enabled);
|
|
1299
|
+
this.config.recordMode = next;
|
|
1300
|
+
if (next) {
|
|
1301
|
+
this.config.failOnMissingMock = false;
|
|
1302
|
+
this.domainPathRules.enableRecordResponsesForAllRules();
|
|
1303
|
+
}
|
|
1304
|
+
if (this.config.proxy?.baseUrl) {
|
|
1305
|
+
this.config.proxy = {
|
|
1306
|
+
...this.config.proxy,
|
|
1307
|
+
recordOnMiss: next,
|
|
1308
|
+
};
|
|
1309
|
+
const client = this.httpClient;
|
|
1310
|
+
client.setProxyRecordOnMiss?.(next);
|
|
1311
|
+
}
|
|
1312
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
|
|
1313
|
+
}
|
|
1314
|
+
/** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
|
|
1315
|
+
isRecordMode() {
|
|
1316
|
+
return this.config.recordMode === true;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Whether new recordings store full response bodies (true) or request-only stubs (false, default).
|
|
1320
|
+
*/
|
|
1321
|
+
setRecordResponses(enabled) {
|
|
1322
|
+
const next = Boolean(enabled);
|
|
1323
|
+
this.recordResponsesOverride = next;
|
|
1324
|
+
this.config.recordResponses = next;
|
|
1325
|
+
if (this.config.proxy) {
|
|
1326
|
+
this.config.proxy = {
|
|
1327
|
+
...this.config.proxy,
|
|
1328
|
+
recordResponses: next,
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
const client = this.httpClient;
|
|
1332
|
+
client.setProxyRecordResponses?.(next);
|
|
1333
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
|
|
1334
|
+
}
|
|
1335
|
+
/** True when new recordings include response bodies (not request-only stubs). */
|
|
1336
|
+
isRecordResponses() {
|
|
1337
|
+
const configValue = this.recordResponsesOverride ??
|
|
1338
|
+
(this.config.proxy?.baseUrl ? this.config.proxy.recordResponses : this.config.recordResponses);
|
|
1339
|
+
// Check env override first (applies to both boolean and array configs)
|
|
1340
|
+
const { envRecordResponsesOverride } = require('@sgedda/mockifyer-core');
|
|
1341
|
+
const envOverride = envRecordResponsesOverride();
|
|
1342
|
+
if (envOverride !== undefined) {
|
|
1343
|
+
return envOverride;
|
|
1344
|
+
}
|
|
1345
|
+
// If config is an array, return true if non-empty (at least some URLs will record)
|
|
1346
|
+
if (Array.isArray(configValue)) {
|
|
1347
|
+
return configValue.length > 0;
|
|
1348
|
+
}
|
|
1349
|
+
// For boolean configs, use the old resolvers
|
|
1350
|
+
if (this.config.proxy?.baseUrl) {
|
|
1351
|
+
return (0, mockifyer_core_1.resolveRecordResponses)(configValue);
|
|
1352
|
+
}
|
|
1353
|
+
return (0, mockifyer_core_1.resolveLocalRecordResponses)(configValue);
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Enable Mockifyer at runtime.
|
|
1357
|
+
*/
|
|
1358
|
+
enableMockifyer() {
|
|
1359
|
+
this.runtimeEnabled = true;
|
|
1360
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
|
|
1361
|
+
void this.persistRuntimeEnabledState(true);
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Disable Mockifyer at runtime.
|
|
1365
|
+
*/
|
|
1366
|
+
disableMockifyer() {
|
|
1367
|
+
this.runtimeEnabled = false;
|
|
1368
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
|
|
1369
|
+
void this.persistRuntimeEnabledState(false);
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Check if Mockifyer is currently enabled at runtime.
|
|
1373
|
+
*/
|
|
1374
|
+
isMockifyerEnabled() {
|
|
1375
|
+
return this.runtimeEnabled;
|
|
1376
|
+
}
|
|
1377
|
+
async persistRuntimeEnabledState(enabled) {
|
|
1378
|
+
if (!this.runtimeEnabledStorage) {
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
await (0, mockifyer_core_1.savePersistedRuntimeEnabled)(this.runtimeEnabledStorage, enabled);
|
|
1382
|
+
}
|
|
1383
|
+
getHTTPClient() {
|
|
1384
|
+
return this.httpClient;
|
|
1385
|
+
}
|
|
1386
|
+
async reloadMockData(syncFromProject = true) {
|
|
1387
|
+
await this.databaseProviderInitPromise;
|
|
1388
|
+
this.poolResponseCache.clear();
|
|
1389
|
+
if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
|
|
1390
|
+
if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
|
|
1391
|
+
await this.databaseProvider.reload(syncFromProject);
|
|
1392
|
+
}
|
|
1393
|
+
else {
|
|
1394
|
+
await this.databaseProvider.reload();
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
else {
|
|
1398
|
+
if (typeof this.loadMockData === 'function') {
|
|
1399
|
+
this.loadMockData();
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
this.domainPathRules.invalidateCache();
|
|
1403
|
+
await this.domainPathRules.hydrate();
|
|
1404
|
+
}
|
|
1405
|
+
clearStaleCacheEntries() {
|
|
1406
|
+
return 0; // No cache in fetch implementation
|
|
1407
|
+
}
|
|
1408
|
+
async clearAllMocks() {
|
|
1409
|
+
if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
|
|
1410
|
+
await this.databaseProvider.clearAll();
|
|
1411
|
+
}
|
|
1412
|
+
else {
|
|
1413
|
+
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
exports.MockifyerClass = MockifyerClass;
|