@sgedda/mockifyer-fetch 1.8.104 → 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.
@@ -0,0 +1,1306 @@
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
+ // Store config BEFORE any modifications
320
+ this.config = { ...config }; // Create a copy to avoid mutations
321
+ // Resolve client ID
322
+ // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
323
+ if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
324
+ Boolean(this.config.proxy?.baseUrl?.trim())) {
325
+ this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
326
+ }
327
+ else {
328
+ this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
329
+ }
330
+ this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
331
+ this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
332
+ config: this.config,
333
+ getRecordMode: () => this.config.recordMode === true,
334
+ });
335
+ this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
336
+ if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
337
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
338
+ 'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.');
339
+ }
340
+ this.runtimeEnabled = (0, mockifyer_core_1.resolveInitialRuntimeEnabled)({
341
+ initialRuntimeEnabled: config.initialRuntimeEnabled,
342
+ startDisabled: config.startDisabled,
343
+ runtimeMode: config.runtimeMode,
344
+ launchScenarioPresent: (0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)(),
345
+ });
346
+ if (!this.runtimeEnabled) {
347
+ const reason = typeof config.initialRuntimeEnabled === 'boolean'
348
+ ? 'persisted / initialRuntimeEnabled: false'
349
+ : config.runtimeMode === 'manual'
350
+ ? 'runtimeMode: "manual"'
351
+ : 'startDisabled: true';
352
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
353
+ }
354
+ if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
355
+ const raw = typeof process !== 'undefined'
356
+ ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
357
+ : '';
358
+ if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
359
+ this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
360
+ }
361
+ }
362
+ // Initialize test generator if test generation is enabled
363
+ if (config.generateTests?.enabled) {
364
+ this.testGenerator = new mockifyer_core_1.TestGenerator();
365
+ }
366
+ // Initialize database provider if specified
367
+ if (config.databaseProvider && config.databaseProvider.type) {
368
+ const providerConfig = {
369
+ ...config.databaseProvider,
370
+ options: {
371
+ ...config.databaseProvider.options,
372
+ mockDataPath: config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
373
+ clientId: this.config.clientId,
374
+ getClientId: () => this.config.clientId,
375
+ },
376
+ };
377
+ this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, providerConfig);
378
+ const initResult = this.databaseProvider.initialize();
379
+ // Handle async initialization (expo-filesystem / hybrid providers)
380
+ if (initResult instanceof Promise) {
381
+ this.databaseProviderInitPromise = initResult.catch((error) => {
382
+ mockifyer_core_1.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
383
+ });
384
+ }
385
+ }
386
+ else {
387
+ // Fallback to Node.js filesystem
388
+ this.ensureMockDataDirectory();
389
+ }
390
+ // Create fetch HTTP client
391
+ this.httpClient = new fetch_client_1.FetchHTTPClient({
392
+ baseUrl: config.baseUrl,
393
+ defaultHeaders: config.defaultHeaders,
394
+ proxy: config.proxy,
395
+ clientId: this.config.clientId,
396
+ getClientId: () => this.config.clientId,
397
+ getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
398
+ getUpstreamTlsInsecure: () => false, // Browser-safe: no TLS insecure
399
+ getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
400
+ deviceId: this.config.deviceId,
401
+ });
402
+ if (!config.recordSameEndpoints) {
403
+ this.loadMockData();
404
+ }
405
+ // Always set up mock response interceptor (to use existing mocks)
406
+ this.setupMockResponses();
407
+ // Set up response interceptor to save responses when recordMode is enabled
408
+ this.setupResponseInterceptor();
409
+ mockifyer_core_1.logger.info('[Mockifyer] Initialized');
410
+ }
411
+ ensureMockDataDirectory() {
412
+ const fs = getFs();
413
+ // Only use fs if available (Node.js environment) and no database provider is set
414
+ if (!fs || this.databaseProvider) {
415
+ return;
416
+ }
417
+ if (!fs.existsSync(this.config.mockDataPath)) {
418
+ fs.mkdirSync(this.config.mockDataPath, { recursive: true });
419
+ }
420
+ }
421
+ generateRequestKey(request) {
422
+ return (0, mockifyer_core_1.generateRequestKey)(request);
423
+ }
424
+ /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
425
+ usesDashboardProxy() {
426
+ const baseUrl = this.config.proxy?.baseUrl;
427
+ return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
428
+ }
429
+ async findBestMatchingMock(request, options) {
430
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
431
+ const requestUrl = request?.url || '';
432
+ if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
433
+ return undefined;
434
+ }
435
+ const requestKey = this.generateRequestKey(request);
436
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
437
+ if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
438
+ return undefined;
439
+ }
440
+ // Use database provider if available, otherwise fallback to filesystem
441
+ if (this.databaseProvider) {
442
+ return await this.findBestMatchingMockFromProvider(request, options);
443
+ }
444
+ // Fallback to Node.js filesystem
445
+ return this.findBestMatchingMockFromFiles(request, options);
446
+ }
447
+ async findBestMatchingMockFromProvider(request, options) {
448
+ if (!this.databaseProvider) {
449
+ return undefined;
450
+ }
451
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
452
+ const requestUrl = request?.url || '';
453
+ if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
454
+ return undefined;
455
+ }
456
+ const requestKey = this.generateRequestKey(request);
457
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
458
+ if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
459
+ return undefined;
460
+ }
461
+ // Try exact match first
462
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
463
+ if (exactMatch) {
464
+ return exactMatch;
465
+ }
466
+ // Try similar match if enabled
467
+ if (this.config.useSimilarMatch) {
468
+ const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
469
+ if (similarMatches && similarMatches.length > 0) {
470
+ // Return first similar match
471
+ return similarMatches[0];
472
+ }
473
+ }
474
+ return undefined;
475
+ }
476
+ getAllJsonFiles(dir) {
477
+ const fs = getFs();
478
+ const path = getPath();
479
+ if (!fs || !path || !fs.existsSync(dir))
480
+ return [];
481
+ const results = [];
482
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
483
+ const fullPath = path.join(dir, entry.name);
484
+ if (entry.isDirectory()) {
485
+ if ((0, mockifyer_core_1.isMockRecordingSidecarDir)(entry.name)) {
486
+ continue;
487
+ }
488
+ results.push(...this.getAllJsonFiles(fullPath));
489
+ }
490
+ else if (entry.name.endsWith('.json')) {
491
+ results.push(fullPath);
492
+ }
493
+ }
494
+ return results;
495
+ }
496
+ findBestMatchingMockFromFiles(request, options) {
497
+ const fs = getFs();
498
+ const path = getPath();
499
+ const includePassthroughMocks = options?.includePassthroughMocks === true;
500
+ // Only use fs if available (Node.js environment)
501
+ // This method should never be called when using a database provider
502
+ if (!fs || !path) {
503
+ return undefined;
504
+ }
505
+ const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
506
+ if (!fs.existsSync(resolvedMockDataPath)) {
507
+ console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
508
+ return undefined;
509
+ }
510
+ const currentScenario = this.capabilities.getCurrentScenario(resolvedMockDataPath, this.config.clientId);
511
+ const scenarioPath = this.capabilities.getScenarioFolderPath(resolvedMockDataPath, currentScenario);
512
+ if (!fs.existsSync(scenarioPath)) {
513
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
514
+ return undefined;
515
+ }
516
+ const files = this.getAllJsonFiles(scenarioPath);
517
+ const requestKey = this.generateRequestKey(request);
518
+ let exactMatch;
519
+ let similarMatch;
520
+ for (const filePath of files) {
521
+ try {
522
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
523
+ const mockData = JSON.parse(fileContent);
524
+ if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
525
+ continue;
526
+ }
527
+ const mockKey = this.generateRequestKey(mockData.request);
528
+ const filename = path.relative(scenarioPath, filePath);
529
+ if (mockKey === requestKey) {
530
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
531
+ includePassthroughMocks,
532
+ filename,
533
+ scenarioPath,
534
+ })) {
535
+ exactMatch = { mockData, filename, filePath };
536
+ break;
537
+ }
538
+ continue;
539
+ }
540
+ if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
541
+ // Check if it's a GraphQL request - skip similar matching for GraphQL
542
+ const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
543
+ request.data &&
544
+ (() => {
545
+ try {
546
+ let bodyData = request.data;
547
+ if (typeof request.data === 'string') {
548
+ bodyData = JSON.parse(request.data);
549
+ }
550
+ return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
551
+ }
552
+ catch {
553
+ return false;
554
+ }
555
+ })();
556
+ if (!isGraphQL) {
557
+ try {
558
+ const requestUrl = new URL(request.url);
559
+ const mockUrl = new URL(mockData.request.url);
560
+ // Check if pathnames match (exact or pattern-based)
561
+ const requestPathname = requestUrl.pathname;
562
+ const mockPathname = mockUrl.pathname;
563
+ const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
564
+ // Check for exact pathname match
565
+ const exactPathnameMatch = mockPathname === requestPathname;
566
+ // Check for pattern-based match
567
+ let patternMatch = false;
568
+ if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
569
+ const requestSegments = requestPathname.split('/').filter(s => s);
570
+ const mockSegments = mockPathname.split('/').filter(s => s);
571
+ if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
572
+ const requestBase = requestSegments.slice(0, -1);
573
+ const mockBase = mockSegments.slice(0, -1);
574
+ patternMatch = requestBase.join('/') === mockBase.join('/');
575
+ }
576
+ }
577
+ const pathnameMatch = exactPathnameMatch || patternMatch;
578
+ if (pathnameMatch && methodMatch) {
579
+ // If ignoreAllQueryParams is set, skip query param checking entirely
580
+ if (this.config.similarMatchIgnoreAllQueryParams) {
581
+ // Ignore all query params, match on path and method only
582
+ }
583
+ else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
584
+ // Check if required parameters match (if configured)
585
+ const requestParams = request.queryParams || {};
586
+ const mockParams = mockData.request.queryParams || {};
587
+ const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
588
+ const requestValue = requestParams[paramName];
589
+ const mockValue = mockParams[paramName];
590
+ return requestValue === undefined && mockValue === undefined
591
+ ? true
592
+ : String(requestValue || '') === String(mockValue || '');
593
+ });
594
+ if (!allRequiredMatch) {
595
+ continue; // Required parameter differs, skip this mock
596
+ }
597
+ }
598
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
599
+ includePassthroughMocks,
600
+ filename,
601
+ scenarioPath,
602
+ })) {
603
+ similarMatch = { mockData, filename, filePath };
604
+ }
605
+ }
606
+ }
607
+ catch (e) {
608
+ continue;
609
+ }
610
+ }
611
+ }
612
+ }
613
+ catch (error) {
614
+ mockifyer_core_1.logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
615
+ }
616
+ }
617
+ return exactMatch || similarMatch;
618
+ }
619
+ loadMockData() {
620
+ const fs = getFs();
621
+ // Skip if using database provider or fs not available
622
+ if (this.databaseProvider || !fs) {
623
+ return;
624
+ }
625
+ if (fs.existsSync(this.config.mockDataPath)) {
626
+ fs.readdirSync(this.config.mockDataPath)
627
+ .filter(file => file.endsWith('.json'));
628
+ }
629
+ }
630
+ setupMockResponses() {
631
+ this.httpClient.interceptors.request.use(async (config) => {
632
+ // CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
633
+ if (!this.runtimeEnabled) {
634
+ config.__mockifyer_bypass = true;
635
+ return config;
636
+ }
637
+ // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
638
+ const url = config.url || '';
639
+ if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
640
+ config.__mockifyer_skip_save = true;
641
+ config.__mockifyer_bypass = true;
642
+ return config;
643
+ }
644
+ if ((0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
645
+ config.__mockifyer_bypass = true;
646
+ return config;
647
+ }
648
+ if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers)) {
649
+ config.__mockifyer_bypass = true;
650
+ return config;
651
+ }
652
+ if (!(0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config)) {
653
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request');
654
+ config.__mockifyer_bypass = true;
655
+ return config;
656
+ }
657
+ let correlation = await this.applyOutboundCorrelation(config);
658
+ this.stashRequestCorrelation(config, correlation);
659
+ // Normalize empty params: treat {} the same as undefined for consistent matching
660
+ const rawParams = config.params || {};
661
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
662
+ const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
663
+ ? anonymizedQueryParams
664
+ : undefined;
665
+ const request = {
666
+ method: config.method || 'GET',
667
+ url: config.url || '',
668
+ headers: config.headers || {},
669
+ data: config.data,
670
+ queryParams: normalizedParams
671
+ };
672
+ const requestKey = this.generateRequestKey(request);
673
+ // Store request key for response interceptor
674
+ config.__mockifyer_requestKey = requestKey;
675
+ // Store request start time for duration calculation
676
+ config.__mockifyer_startTime = Date.now();
677
+ // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
678
+ // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
679
+ if (this.usesDashboardProxy()) {
680
+ return config;
681
+ }
682
+ this.domainPathRules.discover(request.url, this.config.baseUrl);
683
+ const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
684
+ config.__mockifyer_domain_path_may_record = trafficGate.mayRecord;
685
+ if (!trafficGate.mayReplay) {
686
+ mockifyer_core_1.logger.debug(`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
687
+ (trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)'));
688
+ return config;
689
+ }
690
+ const cachedMock = await this.findBestMatchingMock(request);
691
+ // Return cached mock if found
692
+ if (cachedMock) {
693
+ const { mockData, filename, filePath } = cachedMock;
694
+ correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
695
+ if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
696
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
697
+ (filePath ? ` (${filePath})` : ''));
698
+ const path = getPath();
699
+ const hitScenarioPath = path
700
+ ? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
701
+ : undefined;
702
+ if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
703
+ await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
704
+ }
705
+ const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
706
+ const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
707
+ this.logNetworkEvent({
708
+ method: (request.method || 'GET').toUpperCase(),
709
+ url: this.resolveLoggedRequestUrl(config, request.url),
710
+ source: 'mock-hit',
711
+ status: effectiveStatus,
712
+ requestBody: request.data,
713
+ responseBody: mockResponseBody,
714
+ }, correlation, request.headers ?? config.headers);
715
+ const responseHeaders = {
716
+ ...mockData.response.headers,
717
+ 'x-mockifyer': 'true',
718
+ 'x-mockifyer-timestamp': mockData.timestamp,
719
+ 'x-mockifyer-filename': filename,
720
+ 'x-mockifyer-filepath': filePath
721
+ };
722
+ await this.warmPoolResponseCache(mockData);
723
+ const mockResponse = {
724
+ data: mockResponseBody,
725
+ status: effectiveStatus,
726
+ statusText: 'OK',
727
+ headers: responseHeaders,
728
+ config: config
729
+ };
730
+ return {
731
+ ...config,
732
+ __mockResponse: Promise.resolve(mockResponse),
733
+ __mockifyer_requestKey: requestKey
734
+ };
735
+ }
736
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
737
+ (filePath ? ` (${filePath})` : ''));
738
+ config.__mockifyer_matchedMock = cachedMock;
739
+ }
740
+ // Check request limit BEFORE making real API call (only if no mock found and in record mode)
741
+ if (this.config.recordMode) {
742
+ // Browser: skip request limit check (needs fs)
743
+ }
744
+ if (this.config.failOnMissingMock) {
745
+ const scenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
746
+ const requestKey = this.generateRequestKey(request);
747
+ throw new Error(`No mock data found for request: ${requestKey}\n` +
748
+ `\n` +
749
+ `Scenario: ${scenario}\n` +
750
+ `Request key: ${requestKey}\n` +
751
+ `\n` +
752
+ `In replay mode with failOnMissingMock=true, all requests must have recorded mocks.\n` +
753
+ `To fix:\n` +
754
+ ` 1. Record this request: set recordMode: true\n` +
755
+ ` 2. Or preload fixture: databaseProvider: { type: 'memory', options: { fixtures: [...] } }\n` +
756
+ ` 3. Or allow passthrough: set failOnMissingMock: false`);
757
+ }
758
+ return config;
759
+ });
760
+ }
761
+ setupResponseInterceptor() {
762
+ this.httpClient.interceptors.response.use(async (response) => {
763
+ // CRITICAL: Check for skip flag FIRST
764
+ if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
765
+ return response;
766
+ }
767
+ // Clean up processing requests tracking
768
+ const requestKey = response.config.__mockifyer_requestKey;
769
+ if (requestKey) {
770
+ this.processingRequests.delete(requestKey);
771
+ }
772
+ const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
773
+ const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
774
+ if (isMocked || isLimitReached) {
775
+ const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
776
+ if (shouldLogMockOrLimit) {
777
+ const url = response.config?.url || response.request?.responseURL || response.url || '';
778
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
779
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
780
+ const startTime = response.config.__mockifyer_startTime;
781
+ const durationMs = startTime ? Date.now() - startTime : undefined;
782
+ this.logNetworkEvent({
783
+ method: reqMethod,
784
+ url: reqUrl,
785
+ source: isLimitReached ? 'error' : 'mock-hit',
786
+ status: response.status,
787
+ durationMs,
788
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
789
+ requestBody: response.config?.data,
790
+ responseBody: response.data,
791
+ ...(isLimitReached
792
+ ? {
793
+ errorMessage: typeof response.data === 'object' &&
794
+ response.data !== null &&
795
+ 'message' in response.data
796
+ ? String(response.data.message)
797
+ : 'Request limit reached',
798
+ }
799
+ : {}),
800
+ }, this.readRequestCorrelation(response.config), response.config?.headers);
801
+ }
802
+ // Mock hits return before the upstream path
803
+ this.unwrapResponseInlineTrace(response);
804
+ return response;
805
+ }
806
+ if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
807
+ await this.maybeMirrorProxyRecordingToClient(response);
808
+ }
809
+ const matchedMock = response.config.__mockifyer_matchedMock;
810
+ if (matchedMock) {
811
+ const startTime = response.config.__mockifyer_startTime;
812
+ const durationMs = startTime ? Date.now() - startTime : undefined;
813
+ const url = response.config?.url || response.request?.responseURL || response.url || '';
814
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
815
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
816
+ this.logNetworkEvent({
817
+ method: reqMethod,
818
+ url: reqUrl,
819
+ source: 'upstream',
820
+ status: response.status,
821
+ durationMs,
822
+ requestBody: response.config?.data,
823
+ responseBody: response.data,
824
+ }, this.readRequestCorrelation(response.config), response.config?.headers);
825
+ this.unwrapResponseInlineTrace(response);
826
+ const capturedResponse = {
827
+ status: response.status,
828
+ data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
829
+ headers: response.headers || {},
830
+ };
831
+ if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
832
+ await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
833
+ }
834
+ const path = getPath();
835
+ const liveScenarioPath = path
836
+ ? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
837
+ : undefined;
838
+ const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, (0, mockifyer_core_1.createServeTimeClock)(this.config), { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
839
+ response.data = clientResponse.data;
840
+ response.status = clientResponse.status;
841
+ delete response.config.__mockifyer_matchedMock;
842
+ return response;
843
+ }
844
+ const url = response.config?.url || response.request?.responseURL || response.url || '';
845
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
846
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
847
+ this.logNetworkEvent({
848
+ method: reqMethod,
849
+ url: reqUrl,
850
+ source: 'upstream',
851
+ status: response.status,
852
+ durationMs: typeof response.config?.metadata?.durationMs === 'number'
853
+ ? response.config.metadata.durationMs
854
+ : undefined,
855
+ requestBody: response.config?.data,
856
+ responseBody: response.data,
857
+ }, this.readRequestCorrelation(response.config), response.config?.headers);
858
+ this.unwrapResponseInlineTrace(response);
859
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
860
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
861
+ await this.saveResponse(response);
862
+ }
863
+ return response;
864
+ }, async (error) => {
865
+ const requestKey = error.config?.__mockifyer_requestKey;
866
+ if (requestKey) {
867
+ this.processingRequests.delete(requestKey);
868
+ }
869
+ const reqUrl = this.resolveLoggedRequestUrl(error.config);
870
+ if (reqUrl) {
871
+ this.logNetworkEvent({
872
+ method: (error.config?.method || 'GET').toUpperCase(),
873
+ url: reqUrl,
874
+ source: 'error',
875
+ status: error.response?.status,
876
+ errorMessage: error?.message ?? String(error),
877
+ requestBody: error.config?.data,
878
+ responseBody: error.response?.data,
879
+ }, this.readRequestCorrelation(error.config), error.config?.headers);
880
+ }
881
+ this.throwWithMockifyerRequestId(error);
882
+ });
883
+ }
884
+ async maybeMirrorProxyRecordingToClient(response) {
885
+ const rec = response.mockifyerProxyRecording;
886
+ if (!rec?.recordedToStore || !rec.storedMock) {
887
+ return;
888
+ }
889
+ const hash = rec.hash?.trim();
890
+ const scenarioName = rec.scenarioName?.trim();
891
+ const mockData = rec.storedMock;
892
+ const providerType = this.config.databaseProvider?.type;
893
+ await (0, core_proxy_1.mirrorProxyRecordingToClient)({
894
+ config: this.config,
895
+ mockDataPath: this.config.mockDataPath,
896
+ recording: rec,
897
+ databaseProvider: this.databaseProvider,
898
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
899
+ logPrefix: 'Mockifyer-Fetch',
900
+ });
901
+ const fs = getFs();
902
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
903
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
904
+ }
905
+ else if (!fs && hash && scenarioName && mockData) {
906
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
907
+ }
908
+ }
909
+ async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
910
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
911
+ const fetchFn = global.__mockifyer_original_fetch || fetch;
912
+ if (!fetchFn) {
913
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
914
+ return;
915
+ }
916
+ try {
917
+ const body = JSON.stringify({
918
+ __mockifyerProxyMirror: true,
919
+ mockData,
920
+ scenarioName,
921
+ relativePath: `redis/${hash}.json`,
922
+ });
923
+ const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
924
+ method: 'POST',
925
+ headers: { 'Content-Type': 'application/json' },
926
+ body,
927
+ });
928
+ const text = await res.text().catch(() => '');
929
+ if (!res.ok) {
930
+ mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
931
+ return;
932
+ }
933
+ try {
934
+ const parsed = JSON.parse(text);
935
+ if (parsed.success === false) {
936
+ mockifyer_core_1.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
937
+ return;
938
+ }
939
+ }
940
+ catch {
941
+ // non-JSON response
942
+ }
943
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
944
+ }
945
+ catch (e) {
946
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
947
+ }
948
+ }
949
+ async saveResponse(response) {
950
+ // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
951
+ if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
952
+ return;
953
+ }
954
+ // If using a proxy for upstream calls, do not save locally.
955
+ if (this.config.proxy?.baseUrl) {
956
+ return;
957
+ }
958
+ if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
959
+ mockifyer_core_1.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
960
+ return;
961
+ }
962
+ const url = response.config?.url || response.request?.responseURL || response.url || '';
963
+ if (url && (0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
964
+ return;
965
+ }
966
+ const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
967
+ if (url &&
968
+ (0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
969
+ return;
970
+ }
971
+ const mayRecordFlag = response.config?.__mockifyer_domain_path_may_record;
972
+ if (mayRecordFlag === false) {
973
+ return;
974
+ }
975
+ if (mayRecordFlag !== true) {
976
+ this.domainPathRules.discover(url, this.config.baseUrl);
977
+ const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
978
+ if (!gate.mayRecord) {
979
+ return;
980
+ }
981
+ }
982
+ // Normalize empty params: treat {} the same as undefined for consistent matching
983
+ const rawParams = response.config.params || {};
984
+ const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
985
+ const saveLookupRequest = {
986
+ method: response.config.method?.toUpperCase() || 'GET',
987
+ url: response.config.url || '',
988
+ headers: {},
989
+ data: response.config.data,
990
+ queryParams: normalizedParams,
991
+ };
992
+ const requestKey = this.generateRequestKey(saveLookupRequest);
993
+ if (this.savingResponses.has(requestKey)) {
994
+ return;
995
+ }
996
+ const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
997
+ includePassthroughMocks: true,
998
+ });
999
+ const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
1000
+ if (saveDecision.action === 'skip') {
1001
+ if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
1002
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
1003
+ }
1004
+ return;
1005
+ }
1006
+ this.savingResponses.add(requestKey);
1007
+ try {
1008
+ const rawParamsForSave = response.config.params || {};
1009
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
1010
+ const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
1011
+ ? anonymizedQueryParams
1012
+ : undefined;
1013
+ const now = Date.now();
1014
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
1015
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
1016
+ this.sessionStartTime = now;
1017
+ }
1018
+ const startTime = response.config.__mockifyer_startTime;
1019
+ const duration = startTime ? Date.now() - startTime : undefined;
1020
+ const correlation = this.readRequestCorrelation(response.config);
1021
+ const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
1022
+ const storedRequest = {
1023
+ method: response.config?.method?.toUpperCase() || 'GET',
1024
+ url: response.config?.url || '',
1025
+ headers: this.anonymizeHeaders(response.config?.headers || {}),
1026
+ data: response.config?.data,
1027
+ queryParams: normalizedParamsForSave,
1028
+ };
1029
+ // Prefer explicit override / config; else request-only default (same as proxy).
1030
+ // Use URL-aware resolution for selective recording.
1031
+ const configValue = this.recordResponsesOverride ??
1032
+ this.config.proxy?.recordResponses ??
1033
+ this.config.recordResponses;
1034
+ const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponsesForUrl)(storedRequest.url, configValue, this.config.baseUrl);
1035
+ const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
1036
+ request: storedRequest,
1037
+ response: {
1038
+ status: response.status,
1039
+ data: response.data,
1040
+ headers: response.headers || {},
1041
+ },
1042
+ recordResponses: recordBodies,
1043
+ meta: {
1044
+ timestamp: new Date().toISOString(),
1045
+ duration,
1046
+ sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1047
+ ? existingMock.mockData.sessionId
1048
+ : this.currentSessionId,
1049
+ requestId: hopIds.requestId,
1050
+ parentRequestId: hopIds.parentRequestId,
1051
+ parentRequestIds: hopIds.parentRequestIds,
1052
+ // Allowlisted URLs (recordBodies=true) should NOT have alwaysUseRealApi
1053
+ // so they replay immediately. Request-only stubs need alwaysUseRealApi.
1054
+ ...(!recordBodies
1055
+ ? { alwaysUseRealApi: true }
1056
+ : {}),
1057
+ },
1058
+ });
1059
+ (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
1060
+ if (this.databaseProvider) {
1061
+ try {
1062
+ await this.databaseProvider.save(mockData);
1063
+ if (this.config.generateTests?.enabled) {
1064
+ await this.generateTestForMock(mockData);
1065
+ }
1066
+ }
1067
+ catch (error) {
1068
+ console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ else {
1073
+ const fs = getFs();
1074
+ const path = getPath();
1075
+ if (fs && path) {
1076
+ const currentScenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1077
+ const scenarioPath = this.capabilities.getScenarioFolderPath(this.config.mockDataPath, currentScenario);
1078
+ this.capabilities.ensureScenarioFolder(this.config.mockDataPath, currentScenario);
1079
+ if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
1080
+ fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
1081
+ mockifyer_core_1.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
1082
+ }
1083
+ else {
1084
+ const { dir, filename } = (0, mockifyer_core_1.getMockFilePath)(mockData, (0, mockifyer_core_1.formatDateStr)((0, mockifyer_core_1.getCurrentDate)()));
1085
+ const filePath = path.join(scenarioPath, dir, filename);
1086
+ fs.mkdirSync(path.join(scenarioPath, dir), { recursive: true });
1087
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
1088
+ mockifyer_core_1.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`);
1089
+ }
1090
+ if (this.config.generateTests?.enabled && this.testGenerator) {
1091
+ await this.generateTestForMock(mockData);
1092
+ }
1093
+ }
1094
+ else {
1095
+ console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
1096
+ }
1097
+ }
1098
+ // Update domain path rule to allow replay for allowlisted responses
1099
+ if (recordBodies) {
1100
+ this.domainPathRules.enableAutoMockForUrl(storedRequest.url, this.config.baseUrl);
1101
+ }
1102
+ }
1103
+ finally {
1104
+ this.savingResponses.delete(requestKey);
1105
+ }
1106
+ }
1107
+ async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
1108
+ const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
1109
+ (0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
1110
+ if (this.databaseProvider) {
1111
+ await this.databaseProvider.save(updated);
1112
+ return;
1113
+ }
1114
+ const fs = getFs();
1115
+ if (fs && cachedMock.filePath) {
1116
+ fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
1117
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
1118
+ }
1119
+ }
1120
+ /**
1121
+ * Generates test file for a mock
1122
+ */
1123
+ async generateTestForMock(mockData) {
1124
+ if (!this.testGenerator) {
1125
+ return;
1126
+ }
1127
+ // Browser: skip test generation (needs fs)
1128
+ return;
1129
+ }
1130
+ anonymizeHeaders(headers) {
1131
+ const defaultHeadersToAnonymize = [
1132
+ 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
1133
+ 'x-auth-token', 'x-access-token', 'bearer'
1134
+ ];
1135
+ const headersToAnonymize = this.config.anonymizeHeaders !== undefined
1136
+ ? this.config.anonymizeHeaders
1137
+ : defaultHeadersToAnonymize;
1138
+ if (headersToAnonymize.length === 0) {
1139
+ return headers;
1140
+ }
1141
+ const anonymized = { ...headers };
1142
+ const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
1143
+ Object.keys(anonymized).forEach(key => {
1144
+ if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
1145
+ anonymized[key] = '***';
1146
+ }
1147
+ });
1148
+ return anonymized;
1149
+ }
1150
+ anonymizeQueryParams(params) {
1151
+ const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
1152
+ const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
1153
+ ? this.config.anonymizeQueryParams
1154
+ : defaultParamsToAnonymize;
1155
+ if (paramsToAnonymize.length === 0) {
1156
+ return params;
1157
+ }
1158
+ const anonymized = { ...params };
1159
+ const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
1160
+ Object.keys(anonymized).forEach(key => {
1161
+ if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
1162
+ anonymized[key] = '***';
1163
+ }
1164
+ });
1165
+ return anonymized;
1166
+ }
1167
+ /**
1168
+ * Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
1169
+ * Does not re-read native launch arguments or environment variables.
1170
+ */
1171
+ setClientId(lane) {
1172
+ const t = String(lane).trim();
1173
+ if (!t) {
1174
+ throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
1175
+ }
1176
+ this.config.clientId = t;
1177
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
1178
+ }
1179
+ /** Current logical lane id (same value used for isolation). */
1180
+ getClientId() {
1181
+ return this.config.clientId;
1182
+ }
1183
+ /**
1184
+ * Turn record mode on/off at runtime (dev menus, tests).
1185
+ */
1186
+ setRecordMode(enabled) {
1187
+ const next = Boolean(enabled);
1188
+ this.config.recordMode = next;
1189
+ if (next) {
1190
+ this.config.failOnMissingMock = false;
1191
+ this.domainPathRules.enableRecordResponsesForAllRules();
1192
+ }
1193
+ if (this.config.proxy?.baseUrl) {
1194
+ this.config.proxy = {
1195
+ ...this.config.proxy,
1196
+ recordOnMiss: next,
1197
+ };
1198
+ const client = this.httpClient;
1199
+ client.setProxyRecordOnMiss?.(next);
1200
+ }
1201
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
1202
+ }
1203
+ /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
1204
+ isRecordMode() {
1205
+ return this.config.recordMode === true;
1206
+ }
1207
+ /**
1208
+ * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
1209
+ */
1210
+ setRecordResponses(enabled) {
1211
+ const next = Boolean(enabled);
1212
+ this.recordResponsesOverride = next;
1213
+ this.config.recordResponses = next;
1214
+ if (this.config.proxy) {
1215
+ this.config.proxy = {
1216
+ ...this.config.proxy,
1217
+ recordResponses: next,
1218
+ };
1219
+ }
1220
+ const client = this.httpClient;
1221
+ client.setProxyRecordResponses?.(next);
1222
+ mockifyer_core_1.logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
1223
+ }
1224
+ /** True when new recordings include response bodies (not request-only stubs). */
1225
+ isRecordResponses() {
1226
+ const configValue = this.recordResponsesOverride ??
1227
+ (this.config.proxy?.baseUrl ? this.config.proxy.recordResponses : this.config.recordResponses);
1228
+ // Check env override first (applies to both boolean and array configs)
1229
+ const { envRecordResponsesOverride } = require('@sgedda/mockifyer-core');
1230
+ const envOverride = envRecordResponsesOverride();
1231
+ if (envOverride !== undefined) {
1232
+ return envOverride;
1233
+ }
1234
+ // If config is an array, return true if non-empty (at least some URLs will record)
1235
+ if (Array.isArray(configValue)) {
1236
+ return configValue.length > 0;
1237
+ }
1238
+ // For boolean configs, use the old resolvers
1239
+ if (this.config.proxy?.baseUrl) {
1240
+ return (0, mockifyer_core_1.resolveRecordResponses)(configValue);
1241
+ }
1242
+ return (0, mockifyer_core_1.resolveLocalRecordResponses)(configValue);
1243
+ }
1244
+ /**
1245
+ * Enable Mockifyer at runtime.
1246
+ */
1247
+ enableMockifyer() {
1248
+ this.runtimeEnabled = true;
1249
+ mockifyer_core_1.logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
1250
+ void this.persistRuntimeEnabledState(true);
1251
+ }
1252
+ /**
1253
+ * Disable Mockifyer at runtime.
1254
+ */
1255
+ disableMockifyer() {
1256
+ this.runtimeEnabled = false;
1257
+ mockifyer_core_1.logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
1258
+ void this.persistRuntimeEnabledState(false);
1259
+ }
1260
+ /**
1261
+ * Check if Mockifyer is currently enabled at runtime.
1262
+ */
1263
+ isMockifyerEnabled() {
1264
+ return this.runtimeEnabled;
1265
+ }
1266
+ async persistRuntimeEnabledState(enabled) {
1267
+ if (!this.runtimeEnabledStorage) {
1268
+ return;
1269
+ }
1270
+ await (0, mockifyer_core_1.savePersistedRuntimeEnabled)(this.runtimeEnabledStorage, enabled);
1271
+ }
1272
+ getHTTPClient() {
1273
+ return this.httpClient;
1274
+ }
1275
+ async reloadMockData(syncFromProject = true) {
1276
+ await this.databaseProviderInitPromise;
1277
+ this.poolResponseCache.clear();
1278
+ if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
1279
+ if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
1280
+ await this.databaseProvider.reload(syncFromProject);
1281
+ }
1282
+ else {
1283
+ await this.databaseProvider.reload();
1284
+ }
1285
+ }
1286
+ else {
1287
+ if (typeof this.loadMockData === 'function') {
1288
+ this.loadMockData();
1289
+ }
1290
+ }
1291
+ this.domainPathRules.invalidateCache();
1292
+ await this.domainPathRules.hydrate();
1293
+ }
1294
+ clearStaleCacheEntries() {
1295
+ return 0; // No cache in fetch implementation
1296
+ }
1297
+ async clearAllMocks() {
1298
+ if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
1299
+ await this.databaseProvider.clearAll();
1300
+ }
1301
+ else {
1302
+ mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
1303
+ }
1304
+ }
1305
+ }
1306
+ exports.MockifyerClass = MockifyerClass;