@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.
package/src/index.ts CHANGED
@@ -1,16 +1,32 @@
1
1
  // Fetch-only Mockifyer implementation
2
- // Conditionally import fs - will be undefined in React Native
3
- let fs: typeof import('fs') | undefined;
4
- let path: typeof import('path') | undefined;
2
+ // fs and path are lazy-loaded via dynamic require to avoid breaking browser bundles
3
+ //
4
+ // DO NOT change this to static require() or import - bundlers will fail on browser builds.
5
+ // The dynamic require is hidden inside functions to prevent bundle-time resolution.
6
+
7
+ // Lazy-load Node.js built-ins (static literal requires, bundler-safe)
8
+ function getFs(): typeof import('fs') | null {
9
+ // Only works in Node.js
10
+ if (typeof process === 'undefined' || !process.versions?.node) {
11
+ return null;
12
+ }
13
+ try {
14
+ // Static require with literal path - bundlers can stub this
15
+ return require('fs');
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
5
20
 
6
- try {
7
- // Try to require fs and path - will fail in React Native where they're stubbed
8
- fs = require('fs');
9
- path = require('path');
10
- } catch (e) {
11
- // fs/path not available (React Native environment)
12
- fs = undefined;
13
- path = undefined;
21
+ function getPath(): typeof import('path') | null {
22
+ if (typeof process === 'undefined' || !process.versions?.node) {
23
+ return null;
24
+ }
25
+ try {
26
+ return require('path');
27
+ } catch {
28
+ return null;
29
+ }
14
30
  }
15
31
 
16
32
  // Import from core package
@@ -27,9 +43,6 @@ import {
27
43
  scheduleRuntimeDateSyncFromConfig,
28
44
  DatabaseProvider,
29
45
  createProvider,
30
- getCurrentScenario,
31
- getScenarioFolderPath,
32
- ensureScenarioFolder,
33
46
  initializeScenario,
34
47
  isScenarioLaunchFromNativeArguments,
35
48
  TestGenerator,
@@ -107,6 +120,10 @@ import {
107
120
  type MockifyerRuntimeEnabledStorage,
108
121
  outboundHeadersToRecord,
109
122
  appendParamsToUrl,
123
+ getMockFilePath,
124
+ formatDateStr,
125
+ getCurrentDate,
126
+ isMockRecordingSidecarDir,
110
127
  } from '@sgedda/mockifyer-core';
111
128
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
112
129
  import {
@@ -128,1879 +145,8 @@ import { resolveProxyUpstreamTlsInsecure } from '@sgedda/mockifyer-core/utils/pr
128
145
  import { FetchHTTPClient } from './clients/fetch-client';
129
146
  import { bodyInitForFetchResponse } from './utils/fetch-response-body';
130
147
  import { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
131
-
132
- class MockifyerClass {
133
- private config: MockifyerConfig;
134
- private httpClient: HTTPClient;
135
- private processingRequests: Set<string> = new Set();
136
- private savingResponses: Set<string> = new Set();
137
- private databaseProvider?: DatabaseProvider;
138
- /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
139
- private databaseProviderInitPromise: Promise<void> = Promise.resolve();
140
- private currentSessionId: string | null = null;
141
- private sessionStartTime: number = 0;
142
- private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
143
- private testGenerator?: TestGenerator;
144
- private readonly activationMode: MockifyerActivationMode;
145
- /**
146
- * Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
147
- * unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
148
- */
149
- private readonly poolResponseCache = new Map<string, PoolResponseItem>();
150
- private readonly domainPathRules: DomainPathRulesSession;
151
- /** Runtime toggle: when false, all Mockifyer logic is bypassed (no dashboard, Redis, proxy, or mock lookup). */
152
- private runtimeEnabled: boolean;
153
- /** Optional storage for persisting enable/disable across restarts. */
154
- private readonly runtimeEnabledStorage?: MockifyerRuntimeEnabledStorage;
155
- /**
156
- * Runtime override for whether local/proxy recordings include response bodies.
157
- * `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
158
- */
159
- private recordResponsesOverride: boolean | undefined = undefined;
160
-
161
- /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
162
- private getRuntimeSessionId(): string {
163
- return resolveActiveMockifyerSessionId(() => {
164
- const now = Date.now();
165
- if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
166
- this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
167
- this.sessionStartTime = now;
168
- setFlightRecorderRuntimeContext({ sessionId: this.currentSessionId });
169
- }
170
- return this.currentSessionId;
171
- });
172
- }
173
-
174
- private unwrapResponseInlineTrace(response: {
175
- data?: unknown;
176
- config?: unknown;
177
- }): void {
178
- const correlation = this.readRequestCorrelation(response.config);
179
- const parentRequestId = correlation?.requestId?.trim();
180
- if (!parentRequestId) {
181
- response.data = unwrapAndMergeInlineTraceEnvelope(response.data);
182
- return;
183
- }
184
- const scenario =
185
- this.config.proxy?.scenario?.trim() ||
186
- getCurrentScenario(this.config.mockDataPath);
187
- response.data = unwrapInlineTraceEnvelopeEmittingNetworkEvents(response.data, {
188
- parentRequestId,
189
- config: this.config,
190
- scenario,
191
- clientId: this.config.clientId,
192
- sessionId: this.getRuntimeSessionId(),
193
- transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
194
- });
195
- }
196
-
197
- private async applyOutboundCorrelation(config: unknown): Promise<RequestCorrelationContext> {
198
- return applyOutboundRequestCorrelation(
199
- config as { headers?: unknown; url?: unknown; method?: unknown },
200
- await resolveNetworkLogIncludeTraceOptionsAsync(this.config)
201
- );
202
- }
203
-
204
- /**
205
- * Full outbound URL including `params` — hop logs / Atlas curl / include-trace
206
- * must not drop the query string (fetch splits search into `config.params`).
207
- */
208
- private resolveLoggedRequestUrl(
209
- config?: { url?: string; params?: Record<string, unknown> } | null,
210
- fallbackUrl?: string,
211
- ): string {
212
- const raw = (fallbackUrl || config?.url || '').trim();
213
- if (!raw) return '';
214
- return appendParamsToUrl(raw, config?.params);
215
- }
216
-
217
- /** Best-effort dashboard network log. */
218
- private logNetworkEvent(
219
- partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & {
220
- transport?: 'fetch' | 'proxy';
221
- /** Raw bodies for inline-trace / network-log previews (stripped before emit). */
222
- requestBody?: unknown;
223
- responseBody?: unknown;
224
- },
225
- correlation?: RequestCorrelationContext,
226
- /** Final outbound header bag (after auth interceptors). */
227
- requestHeadersSource?: unknown
228
- ): void {
229
- const scenario =
230
- this.config.proxy?.scenario?.trim() ||
231
- getCurrentScenario(this.config.mockDataPath);
232
-
233
- const { requestBody, responseBody, ...eventPartial } = partial;
234
- const businessResponseBody = getInlineTraceEnvelopeBusinessBody(responseBody);
235
- const requestHeaders =
236
- eventPartial.requestHeaders ?? outboundHeadersToRecord(requestHeadersSource);
237
-
238
- if (!this.config.proxy?.baseUrl) {
239
- recordInlineTraceHopFromExchange({
240
- method: eventPartial.method,
241
- url: eventPartial.url,
242
- status: eventPartial.status,
243
- source: eventPartial.source,
244
- transport: eventPartial.transport ?? 'fetch',
245
- requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
246
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
247
- durationMs: eventPartial.durationMs,
248
- clientId: this.config.clientId ?? eventPartial.clientId ?? null,
249
- errorMessage: eventPartial.errorMessage,
250
- requestHeaders,
251
- requestBody,
252
- responseBody,
253
- });
254
- }
255
-
256
- emitMockifyerNetworkEvent({
257
- config: this.config,
258
- scenario,
259
- clientId: this.config.clientId,
260
- sessionId: this.getRuntimeSessionId(),
261
- requestBody,
262
- responseBody: businessResponseBody,
263
- event: {
264
- ...eventPartial,
265
- transport: eventPartial.transport ?? 'fetch',
266
- requestId: correlation?.requestId ?? eventPartial.requestId,
267
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
268
- requestHeaders,
269
- requestBodyPreview: eventPartial.requestBodyPreview,
270
- responseBodyPreview: eventPartial.responseBodyPreview,
271
- },
272
- });
273
- }
274
-
275
- private stashRequestCorrelation(config: unknown, correlation: RequestCorrelationContext): void {
276
- (config as { __mockifyer_requestId?: string; __mockifyer_parentRequestId?: string }).__mockifyer_requestId =
277
- correlation.requestId;
278
- (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId =
279
- correlation.parentRequestId;
280
- }
281
-
282
- private bindStoredHopId(
283
- config: unknown,
284
- mockData: { requestId?: string } | undefined,
285
- fallback?: RequestCorrelationContext
286
- ): RequestCorrelationContext | undefined {
287
- const adopted = adoptStoredOutboundRequestId(
288
- config as { headers?: unknown },
289
- mockData?.requestId
290
- );
291
- if (adopted) {
292
- this.stashRequestCorrelation(config, adopted);
293
- return adopted;
294
- }
295
- return fallback;
296
- }
297
-
298
- private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
299
- const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
300
- if (!requestId) return undefined;
301
- const parentRequestId = (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId;
302
- return parentRequestId ? { requestId, parentRequestId } : { requestId };
303
- }
304
-
305
- /** Attach dashboard lookup id onto thrown fetch/client errors. */
306
- private throwWithMockifyerRequestId(error: unknown): never {
307
- const err = error as { config?: unknown; response?: { headers?: unknown } };
308
- const hopRequestId = (err?.config as { __mockifyer_requestId?: string } | undefined)?.__mockifyer_requestId;
309
- const requestId = resolveMockifyerRequestIdForError({
310
- hopRequestId,
311
- responseHeaders: err?.response?.headers,
312
- });
313
- throw attachMockifyerRequestIdToError(error, requestId);
314
- }
315
-
316
- /**
317
- * Serve stored mock body with optional `$pool` resolution from the local fixture pool.
318
- * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
319
- * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
320
- */
321
- private prepareStoredResponseBody(mockData: MockData, filename?: string, scenarioPath?: string): unknown {
322
- const joinPath =
323
- path && typeof path.join === 'function' ? path.join.bind(path) : null;
324
- return prepareMockResponseBody(mockData, createServeTimeClock(this.config), {
325
- loadPoolResponse: createServeTimePoolResponseLoader({
326
- mockDataPath: this.config.mockDataPath,
327
- nodeFs: isUsableNodeLikePoolFs(fs) ? fs : null,
328
- joinPath,
329
- cache: this.poolResponseCache,
330
- }),
331
- filename,
332
- scenarioPath,
333
- });
334
- }
335
-
336
- /**
337
- * Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
338
- * cannot load them (React Native). Tries database provider, then Metro.
339
- */
340
- private async warmPoolResponseCache(mockData: MockData): Promise<void> {
341
- if (!arePoolRefsEnabled() || !containsPoolRefs(mockData.response?.data)) {
342
- return;
343
- }
344
- if (isUsableNodeLikePoolFs(fs)) {
345
- return;
346
- }
347
-
348
- const ids = collectPoolRefIds(mockData.response.data);
349
- for (const id of ids) {
350
- if (this.poolResponseCache.has(id)) {
351
- continue;
352
- }
353
- const fromProvider = await this.loadPoolResponseFromProvider(id);
354
- if (fromProvider) {
355
- this.poolResponseCache.set(id, fromProvider);
356
- continue;
357
- }
358
- const fromMetro = await this.loadPoolResponseFromMetro(id);
359
- if (fromMetro) {
360
- this.poolResponseCache.set(id, fromMetro);
361
- }
362
- }
363
- }
364
-
365
- private async loadPoolResponseFromProvider(
366
- id: string
367
- ): Promise<PoolResponseItem | undefined> {
368
- const provider = this.databaseProvider as
369
- | { loadPoolResponseItem?: (poolId: string) => Promise<PoolResponseItem | undefined> | PoolResponseItem | undefined }
370
- | undefined;
371
- if (!provider || typeof provider.loadPoolResponseItem !== 'function') {
372
- return undefined;
373
- }
374
- try {
375
- return (await provider.loadPoolResponseItem(id)) ?? undefined;
376
- } catch (error) {
377
- logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from provider:`, error);
378
- return undefined;
379
- }
380
- }
381
-
382
- private async loadPoolResponseFromMetro(
383
- id: string
384
- ): Promise<PoolResponseItem | undefined> {
385
- const metroPort = this.config.databaseProvider?.options?.metroPort ?? 8081;
386
- const originalFetch =
387
- (global as { __mockifyer_original_fetch?: typeof fetch }).__mockifyer_original_fetch ||
388
- (typeof fetch !== 'undefined' ? fetch : undefined);
389
- if (!originalFetch) {
390
- return undefined;
391
- }
392
- try {
393
- const url = `http://localhost:${metroPort}/mockifyer-pool-response?id=${encodeURIComponent(id)}`;
394
- const response = await originalFetch(url);
395
- if (!response.ok) {
396
- return undefined;
397
- }
398
- const payload = (await response.json()) as {
399
- success?: boolean;
400
- item?: PoolResponseItem;
401
- };
402
- if (payload.success && payload.item?.responseItemId && payload.item.response) {
403
- return payload.item;
404
- }
405
- return undefined;
406
- } catch (error) {
407
- logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from Metro:`, error);
408
- return undefined;
409
- }
410
- }
411
-
412
- constructor(config: MockifyerConfig) {
413
- // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
414
- if (config.databaseProvider && config.databaseProvider.type) {
415
- const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
416
- if (!supportedTypes.includes(config.databaseProvider.type)) {
417
- throw new Error(
418
- `Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
419
- `Supported types: ${supportedTypes.join(', ')}. ` +
420
- `Please use one of the supported provider types.`
421
- );
422
- }
423
- }
424
-
425
- // Validate and normalize conflicting settings
426
- if (config.recordMode && config.failOnMissingMock) {
427
- logger.warn(
428
- '[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
429
- 'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
430
- 'Setting failOnMissingMock to false.'
431
- );
432
- config.failOnMissingMock = false;
433
- }
434
-
435
- // Validate conflicting similar match settings
436
- if (config.similarMatchIgnoreAllQueryParams &&
437
- config.similarMatchRequiredParams &&
438
- config.similarMatchRequiredParams.length > 0) {
439
- logger.warn(
440
- '[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
441
- 'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
442
- 'similarMatchRequiredParams will be ignored.'
443
- );
444
- // Clear similarMatchRequiredParams to avoid confusion
445
- config.similarMatchRequiredParams = undefined;
446
- }
447
-
448
- // Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
449
- if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
450
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
451
- config.useSimilarMatch = true;
452
- }
453
- }
454
-
455
- // Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
456
- if (config.similarMatchIgnoreAllQueryParams) {
457
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
458
- config.useSimilarMatch = true;
459
- }
460
- }
461
-
462
- let launchClientId: string | undefined;
463
- if (config.useLaunchArgumentsClientId) {
464
- const key = config.launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
465
- launchClientId = tryGetClientIdFromLaunchArguments(key);
466
- if (launchClientId) {
467
- logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
468
- }
469
- }
470
-
471
- // Store config BEFORE any modifications
472
- this.config = { ...config }; // Create a copy to avoid mutations
473
-
474
- // Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
475
- if (launchClientId) {
476
- this.config.clientId = launchClientId;
477
- } else if (
478
- resolveStrictScenarioResolution(this.config) &&
479
- Boolean(this.config.proxy?.baseUrl?.trim())
480
- ) {
481
- // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
482
- this.config.clientId = resolveExplicitClientIdOnly(this.config);
483
- } else {
484
- this.config.clientId = resolveClientId(this.config);
485
- }
486
- this.activationMode = resolveActivationMode(this.config);
487
- this.domainPathRules = new DomainPathRulesSession({
488
- config: this.config,
489
- getRecordMode: () => this.config.recordMode === true,
490
- });
491
-
492
- this.runtimeEnabledStorage = resolveRuntimeEnabledStorage(config.persistRuntimeEnabled);
493
- if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
494
- logger.warn(
495
- '[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
496
- 'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.'
497
- );
498
- }
499
- this.runtimeEnabled = resolveInitialRuntimeEnabled({
500
- initialRuntimeEnabled: config.initialRuntimeEnabled,
501
- startDisabled: config.startDisabled,
502
- runtimeMode: config.runtimeMode,
503
- launchScenarioPresent: isScenarioLaunchFromNativeArguments(),
504
- });
505
-
506
- if (!this.runtimeEnabled) {
507
- const reason =
508
- typeof config.initialRuntimeEnabled === 'boolean'
509
- ? 'persisted / initialRuntimeEnabled: false'
510
- : config.runtimeMode === 'manual'
511
- ? 'runtimeMode: "manual"'
512
- : 'startDisabled: true';
513
- logger.info(
514
- `[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`
515
- );
516
- } else if (isScenarioLaunchFromNativeArguments()) {
517
- logger.info(
518
- '[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).'
519
- );
520
- } else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
521
- logger.info(
522
- '[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).'
523
- );
524
- }
525
-
526
- configureFlightRecorder(resolveFlightRecorderConfig(this.config));
527
- configureAtlas(this.config, {
528
- scenario: getCurrentScenario(this.config.mockDataPath, this.config.clientId),
529
- clientId: this.config.clientId ?? null,
530
- });
531
- setFlightRecorderRuntimeContext({
532
- clientId: this.config.clientId,
533
- scenario: getCurrentScenario(this.config.mockDataPath, this.config.clientId),
534
- });
535
-
536
- if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
537
- const raw =
538
- typeof process !== 'undefined'
539
- ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
540
- : '';
541
- if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
542
- this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
543
- }
544
- }
545
-
546
- // Initialize test generator if test generation is enabled
547
- if (config.generateTests?.enabled) {
548
- this.testGenerator = new TestGenerator();
549
- }
550
-
551
- // Initialize database provider if specified
552
- if (config.databaseProvider && config.databaseProvider.type) {
553
- const providerConfig = {
554
- ...config.databaseProvider,
555
- options: {
556
- ...config.databaseProvider.options,
557
- mockDataPath:
558
- config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
559
- clientId: this.config.clientId,
560
- getClientId: () => this.config.clientId,
561
- },
562
- };
563
- this.databaseProvider = createProvider(config.databaseProvider.type, providerConfig);
564
- const initResult = this.databaseProvider.initialize();
565
- // Handle async initialization (expo-filesystem / hybrid providers)
566
- if (initResult instanceof Promise) {
567
- this.databaseProviderInitPromise = initResult.catch((error) => {
568
- logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
569
- });
570
- }
571
- } else {
572
- // Fallback to Node.js filesystem
573
- this.ensureMockDataDirectory();
574
- }
575
-
576
- // Create fetch HTTP client
577
- this.httpClient = new FetchHTTPClient({
578
- baseUrl: config.baseUrl,
579
- defaultHeaders: config.defaultHeaders,
580
- proxy: config.proxy,
581
- clientId: this.config.clientId,
582
- getClientId: () => this.config.clientId,
583
- getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
584
- getUpstreamTlsInsecure: () => resolveProxyUpstreamTlsInsecure(this.config),
585
- getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
586
- deviceId: (this.config as any).deviceId,
587
- });
588
-
589
- if(!config.recordSameEndpoints) {
590
- this.loadMockData();
591
- }
592
- // Always set up mock response interceptor (to use existing mocks)
593
- this.setupMockResponses();
594
-
595
- // Set up response interceptor to save responses when recordMode is enabled
596
- this.setupResponseInterceptor();
597
-
598
- logMockifyerInitSummary(this.config, {
599
- runtimeMode: this.config.runtimeMode,
600
- headline: this.config.initLog?.headline,
601
- });
602
- }
603
-
604
- private ensureMockDataDirectory(): void {
605
- // Only use fs if available (Node.js environment) and no database provider is set
606
- if (!fs || this.databaseProvider) {
607
- return;
608
- }
609
- if (!fs.existsSync(this.config.mockDataPath)) {
610
- fs.mkdirSync(this.config.mockDataPath, { recursive: true });
611
- }
612
- }
613
-
614
- private generateRequestKey(request: StoredRequest): string {
615
- return generateRequestKeyUtil(request);
616
- }
617
-
618
- /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
619
- private usesDashboardProxy(): boolean {
620
- const baseUrl = this.config.proxy?.baseUrl;
621
- return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
622
- }
623
-
624
- private async findBestMatchingMock(
625
- request: StoredRequest,
626
- options?: { includePassthroughMocks?: boolean }
627
- ): Promise<CachedMockData | undefined> {
628
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
629
- const requestUrl = request?.url || '';
630
- if (containsMockifyerSyncEndpointMarker(requestUrl)) {
631
- return undefined;
632
- }
633
-
634
- const requestKey = this.generateRequestKey(request);
635
-
636
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
637
- if (containsMockifyerSyncEndpointMarker(requestKey)) {
638
- return undefined;
639
- }
640
-
641
- // Use database provider if available, otherwise fallback to filesystem
642
- if (this.databaseProvider) {
643
- return await this.findBestMatchingMockFromProvider(request, options);
644
- }
645
- // Fallback to Node.js filesystem
646
- return this.findBestMatchingMockFromFiles(request, options);
647
- }
648
-
649
- private async findBestMatchingMockFromProvider(
650
- request: StoredRequest,
651
- options?: { includePassthroughMocks?: boolean }
652
- ): Promise<CachedMockData | undefined> {
653
- if (!this.databaseProvider) {
654
- return undefined;
655
- }
656
-
657
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
658
- const requestUrl = request?.url || '';
659
- if (containsMockifyerSyncEndpointMarker(requestUrl)) {
660
- return undefined;
661
- }
662
-
663
- const requestKey = this.generateRequestKey(request);
664
-
665
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
666
- if (containsMockifyerSyncEndpointMarker(requestKey)) {
667
- return undefined;
668
- }
669
-
670
- // Try exact match first
671
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
672
- if (exactMatch) {
673
- return exactMatch;
674
- }
675
-
676
- // Try similar match if enabled
677
- if (this.config.useSimilarMatch) {
678
- const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
679
- if (similarMatches && similarMatches.length > 0) {
680
- // Return first similar match
681
- return similarMatches[0];
682
- }
683
- }
684
-
685
- return undefined;
686
- }
687
-
688
- private findBestMatchingMockFromFiles(
689
- request: StoredRequest,
690
- options?: { includePassthroughMocks?: boolean }
691
- ): CachedMockData | undefined {
692
- const includePassthroughMocks = options?.includePassthroughMocks === true;
693
- // Only use fs if available (Node.js environment)
694
- // This method should never be called when using a database provider
695
- if (!fs || !path) {
696
- return undefined;
697
- }
698
- const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
699
-
700
- if (!fs.existsSync(resolvedMockDataPath)) {
701
- console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
702
- return undefined;
703
- }
704
-
705
- const currentScenario = getCurrentScenario(resolvedMockDataPath, this.config.clientId);
706
- const scenarioPath = getScenarioFolderPath(resolvedMockDataPath, currentScenario);
707
- ensureOverrideGroupRuntimeForScenarioPath(scenarioPath, { clientId: this.config.clientId });
708
-
709
- if (!fs.existsSync(scenarioPath)) {
710
- logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
711
- return undefined;
712
- }
713
-
714
- const files = fs.readdirSync(scenarioPath)
715
- .filter(file => file.endsWith('.json'));
716
-
717
- const requestKey = this.generateRequestKey(request);
718
- let exactMatch: CachedMockData | undefined;
719
- let similarMatch: CachedMockData | undefined;
720
-
721
- for (const file of files) {
722
- try {
723
- const filePath = path!.join(scenarioPath, file);
724
- const fileContent = fs.readFileSync(filePath, 'utf-8');
725
- const mockData: MockData = JSON.parse(fileContent);
726
-
727
- if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
728
- continue;
729
- }
730
-
731
- const mockKey = this.generateRequestKey(mockData.request);
732
-
733
- if (mockKey === requestKey) {
734
- if (
735
- mockShouldBeIncludedInRequestMatch(mockData, {
736
- includePassthroughMocks,
737
- filename: file,
738
- scenarioPath,
739
- })
740
- ) {
741
- exactMatch = { mockData, filename: file, filePath };
742
- break;
743
- }
744
- continue;
745
- }
746
-
747
- if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
748
- // Check if it's a GraphQL request - skip similar matching for GraphQL
749
- const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
750
- request.data &&
751
- (() => {
752
- try {
753
- let bodyData = request.data;
754
- if (typeof request.data === 'string') {
755
- bodyData = JSON.parse(request.data);
756
- }
757
- return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
758
- } catch {
759
- return false;
760
- }
761
- })();
762
-
763
- if (!isGraphQL) {
764
- try {
765
- const requestUrl = new URL(request.url);
766
- const mockUrl = new URL(mockData.request.url);
767
-
768
- // Check if pathnames match (exact or pattern-based)
769
- const requestPathname = requestUrl.pathname;
770
- const mockPathname = mockUrl.pathname;
771
- const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
772
-
773
- // Check for exact pathname match
774
- const exactPathnameMatch = mockPathname === requestPathname;
775
-
776
- // Check for pattern-based match (e.g., /posts/71 matches /posts/17 when similarMatchIgnoreAllQueryParams is true)
777
- // This allows matching paths with different IDs when we're ignoring query params
778
- let patternMatch = false;
779
- if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
780
- // Extract base path by removing the last segment (ID)
781
- // /posts/71 -> /posts, /users/2/todos -> /users/2
782
- const requestSegments = requestPathname.split('/').filter(s => s);
783
- const mockSegments = mockPathname.split('/').filter(s => s);
784
-
785
- // Match if base paths are the same (same number of segments, all but last match)
786
- if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
787
- const requestBase = requestSegments.slice(0, -1);
788
- const mockBase = mockSegments.slice(0, -1);
789
- patternMatch = requestBase.join('/') === mockBase.join('/');
790
- }
791
- }
792
-
793
- const pathnameMatch = exactPathnameMatch || patternMatch;
794
-
795
- // Check similar match
796
-
797
- if (pathnameMatch && methodMatch) {
798
-
799
- // If ignoreAllQueryParams is set, skip query param checking entirely
800
- if (this.config.similarMatchIgnoreAllQueryParams) {
801
- // Ignore all query params, match on path and method only
802
- } else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
803
- // Check if required parameters match (if configured)
804
- const requestParams = request.queryParams || {};
805
- const mockParams = mockData.request.queryParams || {};
806
-
807
- const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName: string) => {
808
- const requestValue = requestParams[paramName];
809
- const mockValue = mockParams[paramName];
810
- return requestValue === undefined && mockValue === undefined
811
- ? true
812
- : String(requestValue || '') === String(mockValue || '');
813
- });
814
-
815
- if (!allRequiredMatch) {
816
- continue; // Required parameter differs, skip this mock
817
- }
818
- }
819
-
820
- if (
821
- mockShouldBeIncludedInRequestMatch(mockData, {
822
- includePassthroughMocks,
823
- filename: file,
824
- scenarioPath,
825
- })
826
- ) {
827
- similarMatch = { mockData, filename: file, filePath };
828
- }
829
- }
830
- } catch (e) {
831
- continue;
832
- }
833
- }
834
- }
835
- } catch (error) {
836
- logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
837
- }
838
- }
839
-
840
- return exactMatch || similarMatch;
841
- }
842
-
843
- private loadMockData(): void {
844
- // Skip if using database provider or fs not available
845
- if (this.databaseProvider || !fs) {
846
- return;
847
- }
848
- if (fs.existsSync(this.config.mockDataPath)) {
849
- fs.readdirSync(this.config.mockDataPath)
850
- .filter(file => file.endsWith('.json'));
851
- }
852
- }
853
-
854
- private setupMockResponses(): void {
855
- this.httpClient.interceptors.request.use(async (config: any) => {
856
- // CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
857
- if (!this.runtimeEnabled) {
858
- (config as any).__mockifyer_bypass = true;
859
- return config;
860
- }
861
-
862
- // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
863
- // This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
864
- const url = config.url || '';
865
- if (containsMockifyerSyncEndpointMarker(url)) {
866
- // Mark this request to completely skip Mockifyer processing
867
- (config as any).__mockifyer_skip_save = true;
868
- (config as any).__mockifyer_bypass = true;
869
- return config;
870
- }
871
-
872
- if (shouldBypassMockifyerForUrl(url, this.config.excludedUrls, this.config.baseUrl)) {
873
- (config as any).__mockifyer_bypass = true;
874
- return config;
875
- }
876
-
877
- if (!shouldApplyMockifyer(this.activationMode, config.headers)) {
878
- (config as any).__mockifyer_bypass = true;
879
- return config;
880
- }
881
-
882
- if (!isExplicitProxyScenarioContext(this.config)) {
883
- logger.warn(
884
- '[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request'
885
- );
886
- (config as any).__mockifyer_bypass = true;
887
- return config;
888
- }
889
-
890
- let correlation = await this.applyOutboundCorrelation(config);
891
- this.stashRequestCorrelation(config, correlation);
892
-
893
- // Normalize empty params: treat {} the same as undefined for consistent matching
894
- const rawParams = config.params || {};
895
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
896
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
897
- ? anonymizedQueryParams
898
- : undefined;
899
-
900
- const request: StoredRequest = {
901
- method: config.method || 'GET',
902
- url: config.url || '',
903
- headers: config.headers || {},
904
- data: config.data,
905
- queryParams: normalizedParams
906
- };
907
-
908
- const requestKey = this.generateRequestKey(request);
909
-
910
- // Store request key for response interceptor
911
- (config as any).__mockifyer_requestKey = requestKey;
912
- // Store request start time for duration calculation
913
- (config as any).__mockifyer_startTime = Date.now();
914
-
915
- // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
916
- // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
917
- if (this.usesDashboardProxy()) {
918
- return config;
919
- }
920
-
921
- this.domainPathRules.discover(request.url, this.config.baseUrl);
922
- const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
923
- (config as any).__mockifyer_domain_path_may_record = trafficGate.mayRecord;
924
- if (!trafficGate.mayReplay) {
925
- logger.debug(
926
- `[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
927
- (trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)')
928
- );
929
- return config;
930
- }
931
-
932
- const cachedMock = await this.findBestMatchingMock(request);
933
-
934
- // Return cached mock if found
935
-
936
- if (cachedMock) {
937
- const { mockData, filename, filePath } = cachedMock;
938
- correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
939
- if (mockShouldServeStoredBody(mockData)) {
940
- logger.info(
941
- `[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
942
- (filePath ? ` (${filePath})` : '')
943
- );
944
- const hitScenarioPath = path
945
- ? getScenarioFolderPath(
946
- path.resolve(this.config.mockDataPath),
947
- getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
948
- )
949
- : undefined;
950
- if (hitScenarioPath) {
951
- ensureOverrideGroupRuntimeForScenarioPath(hitScenarioPath, { clientId: this.config.clientId });
952
- }
953
- const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
954
- this.logNetworkEvent(
955
- {
956
- method: (request.method || 'GET').toUpperCase(),
957
- url: this.resolveLoggedRequestUrl(config, request.url),
958
- source: 'mock-hit',
959
- status: mockData.response.status,
960
- requestHash: networkEventHashFromRequestKey(requestKey),
961
- requestBody: request.data,
962
- responseBody: mockResponseBody,
963
- },
964
- correlation,
965
- request.headers ?? config.headers
966
- );
967
- const responseHeaders = {
968
- ...mockData.response.headers,
969
- 'x-mockifyer': 'true',
970
- 'x-mockifyer-timestamp': mockData.timestamp,
971
- 'x-mockifyer-filename': filename,
972
- 'x-mockifyer-filepath': filePath
973
- };
974
-
975
- await this.warmPoolResponseCache(mockData);
976
-
977
- const mockResponse = {
978
- data: mockResponseBody,
979
- status: mockData.response.status,
980
- statusText: 'OK',
981
- headers: responseHeaders,
982
- config: config as any
983
- };
984
-
985
- return {
986
- ...config,
987
- __mockResponse: Promise.resolve(mockResponse),
988
- __mockifyer_requestKey: requestKey
989
- } as any;
990
- }
991
-
992
- logger.info(
993
- `[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
994
- (filePath ? ` (${filePath})` : '')
995
- );
996
- (config as any).__mockifyer_matchedMock = cachedMock;
997
- }
998
-
999
- // Check request limit BEFORE making real API call (only if no mock found and in record mode)
1000
- if (this.config.recordMode) {
1001
- const limitCheck = checkRequestLimit(this.config.mockDataPath);
1002
- if (limitCheck.limitReached && limitCheck.error) {
1003
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
1004
-
1005
- // Return a mock error response instead of making a real API call
1006
- const responseHeaders = {
1007
- 'x-mockifyer': 'true',
1008
- 'x-mockifyer-limit-reached': 'true',
1009
- 'content-type': 'application/json'
1010
- };
1011
-
1012
- const mockErrorResponse = {
1013
- data: {
1014
- error: limitCheck.error.message,
1015
- message: limitCheck.error.message,
1016
- limitReached: true,
1017
- maxRequests: limitCheck.error.maxRequests,
1018
- currentScenario: limitCheck.error.currentScenario
1019
- },
1020
- status: 429, // Too Many Requests
1021
- statusText: 'Too Many Requests',
1022
- headers: responseHeaders,
1023
- config: config as any
1024
- };
1025
-
1026
- return {
1027
- ...config,
1028
- __mockResponse: Promise.resolve(mockErrorResponse),
1029
- __mockifyer_requestKey: requestKey,
1030
- __mockifyer_limit_reached: true
1031
- } as any;
1032
- }
1033
- }
1034
-
1035
- if (this.config.failOnMissingMock) {
1036
- throw new Error(`No mock data found for request: ${this.generateRequestKey(request)}`);
1037
- }
1038
-
1039
- return config;
1040
- });
1041
- }
1042
-
1043
- private setupResponseInterceptor(): void {
1044
- this.httpClient.interceptors.response.use(
1045
- async (response: any) => {
1046
- // CRITICAL: Check for skip flag FIRST (set by request interceptor for sync endpoints)
1047
- // This completely bypasses Mockifyer interception for sync endpoints
1048
- if ((response.config as any).__mockifyer_skip_save || (response.config as any).__mockifyer_bypass) {
1049
- return response;
1050
- }
1051
-
1052
- // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
1053
- // Check multiple ways to get the URL in case response.config is undefined
1054
- const url = response.config?.url || response.request?.responseURL || response.url || (response as any).config?.url || '';
1055
-
1056
- // CRITICAL: Check URL FIRST before any other processing
1057
- if (containsMockifyerSyncEndpointMarker(url)) {
1058
- // Mark as bypassed to prevent any further processing
1059
- (response.config as any).__mockifyer_skip_save = true;
1060
- (response.config as any).__mockifyer_bypass = true;
1061
- return response;
1062
- }
1063
-
1064
- // Clean up processing requests tracking
1065
- const requestKey = (response.config as any).__mockifyer_requestKey;
1066
- if (requestKey) {
1067
- this.processingRequests.delete(requestKey);
1068
- }
1069
-
1070
- // CRITICAL: Check response data for Metro rejection messages (defense in depth)
1071
- // This catches any responses that might have gotten through
1072
- try {
1073
- let responseDataStr = '';
1074
- let responseDataObj: any = null;
1075
-
1076
- if (typeof response.data === 'string') {
1077
- responseDataStr = response.data;
1078
- try {
1079
- responseDataObj = JSON.parse(response.data);
1080
- } catch (e) {
1081
- // Not JSON, that's fine
1082
- }
1083
- } else if (response.data) {
1084
- // Try to stringify, but handle circular references
1085
- try {
1086
- responseDataStr = JSON.stringify(response.data);
1087
- responseDataObj = response.data;
1088
- } catch (stringifyError) {
1089
- // If stringify fails, try to get a string representation
1090
- responseDataStr = String(response.data);
1091
- }
1092
- }
1093
-
1094
- // CRITICAL: Check for Metro rejection message
1095
- const hasRejectionMessage = responseDataStr && (
1096
- responseDataStr.includes('Cannot save Mockifyer sync endpoint') ||
1097
- responseDataStr.includes('Cannot save Mockifyer sync endpoint requests')
1098
- );
1099
-
1100
- const hasRejectionInObject = responseDataObj && (
1101
- (responseDataObj.error && typeof responseDataObj.error === 'string' &&
1102
- responseDataObj.error.includes('Cannot save Mockifyer sync endpoint')) ||
1103
- (responseDataObj.success === false && responseDataObj.error)
1104
- );
1105
-
1106
- if (hasRejectionMessage || hasRejectionInObject) {
1107
- return response;
1108
- }
1109
-
1110
- // CRITICAL: Check for sync endpoint URLs in response data
1111
- if (containsMockifyerSyncEndpointMarker(responseDataStr)) {
1112
- return response;
1113
- }
1114
- } catch (e) {
1115
- // Ignore errors - continue processing
1116
- logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
1117
- }
1118
-
1119
- const isMocked = response.headers && (response.headers as any)['x-mockifyer'] === 'true';
1120
- const isLimitReached = response.headers && (response.headers as any)['x-mockifyer-limit-reached'] === 'true';
1121
- if (isMocked || isLimitReached) {
1122
- // Local mock hits are logged in the request interceptor; proxy mock hits must
1123
- // be recorded here before early return (otherwise flight recorder stays empty).
1124
- const shouldLogMockOrLimit =
1125
- isLimitReached || (isMocked && this.usesDashboardProxy());
1126
- if (shouldLogMockOrLimit) {
1127
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1128
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
1129
- const startTime = (response.config as any).__mockifyer_startTime;
1130
- const durationMs = startTime ? Date.now() - startTime : undefined;
1131
- this.logNetworkEvent(
1132
- {
1133
- method: reqMethod,
1134
- url: reqUrl,
1135
- source: isLimitReached ? 'error' : 'mock-hit',
1136
- status: response.status,
1137
- durationMs,
1138
- transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
1139
- requestBody: response.config?.data,
1140
- responseBody: response.data,
1141
- ...(isLimitReached
1142
- ? {
1143
- errorMessage:
1144
- typeof response.data === 'object' &&
1145
- response.data !== null &&
1146
- 'message' in response.data
1147
- ? String((response.data as { message?: unknown }).message)
1148
- : 'Request limit reached',
1149
- }
1150
- : {}),
1151
- },
1152
- this.readRequestCorrelation(response.config),
1153
- response.config?.headers
1154
- );
1155
- }
1156
- // Mock hits return before the upstream path. Still emit nested service
1157
- // hops and strip mockifyerTrace so the caller sees the business body.
1158
- this.unwrapResponseInlineTrace(response);
1159
- return response;
1160
- }
1161
-
1162
- if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
1163
- await this.maybeMirrorProxyRecordingToClient(response);
1164
- }
1165
-
1166
- const matchedMock = (response.config as any).__mockifyer_matchedMock as CachedMockData | undefined;
1167
- if (matchedMock) {
1168
- const startTime = (response.config as any).__mockifyer_startTime;
1169
- const durationMs = startTime ? Date.now() - startTime : undefined;
1170
-
1171
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1172
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
1173
- // Parent hop first, then unwrap nested service hops from downstream services.
1174
- this.logNetworkEvent(
1175
- {
1176
- method: reqMethod,
1177
- url: reqUrl,
1178
- source: 'upstream',
1179
- status: response.status,
1180
- durationMs,
1181
- requestBody: response.config?.data,
1182
- responseBody: response.data,
1183
- },
1184
- this.readRequestCorrelation(response.config),
1185
- response.config?.headers
1186
- );
1187
- this.unwrapResponseInlineTrace(response);
1188
-
1189
- const capturedResponse: StoredResponse = {
1190
- status: response.status,
1191
- data: stripMockifyerTraceFromBody(response.data),
1192
- headers: (response.headers as Record<string, string>) || {},
1193
- };
1194
-
1195
- if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
1196
- await this.persistMatchedMockAfterLiveCapture(
1197
- matchedMock,
1198
- capturedResponse,
1199
- durationMs,
1200
- this.readRequestCorrelation(response.config)
1201
- );
1202
- }
1203
-
1204
- const liveScenarioPath = path
1205
- ? getScenarioFolderPath(
1206
- path.resolve(this.config.mockDataPath),
1207
- getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
1208
- )
1209
- : undefined;
1210
- if (liveScenarioPath) {
1211
- ensureOverrideGroupRuntimeForScenarioPath(liveScenarioPath, { clientId: this.config.clientId });
1212
- }
1213
- const clientResponse = buildClientResponseFromLiveCapture(
1214
- matchedMock.mockData,
1215
- capturedResponse,
1216
- createServeTimeClock(this.config),
1217
- { filename: matchedMock.filename, scenarioPath: liveScenarioPath }
1218
- );
1219
- response.data = clientResponse.data;
1220
- response.status = clientResponse.status;
1221
- delete (response.config as any).__mockifyer_matchedMock;
1222
-
1223
- return response;
1224
- }
1225
-
1226
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1227
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
1228
- this.logNetworkEvent(
1229
- {
1230
- method: reqMethod,
1231
- url: reqUrl,
1232
- source: 'upstream',
1233
- status: response.status,
1234
- durationMs:
1235
- typeof response.config?.metadata?.durationMs === 'number'
1236
- ? response.config.metadata.durationMs
1237
- : undefined,
1238
- requestBody: response.config?.data,
1239
- responseBody: response.data,
1240
- },
1241
- this.readRequestCorrelation(response.config),
1242
- response.config?.headers
1243
- );
1244
- this.unwrapResponseInlineTrace(response);
1245
-
1246
- // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
1247
- // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
1248
- if (this.config.recordMode && !this.config.proxy?.baseUrl) {
1249
- await this.saveResponse(response);
1250
- }
1251
-
1252
- return response;
1253
- },
1254
- async (error: any) => {
1255
- const requestKey = (error.config as any)?.__mockifyer_requestKey;
1256
- if (requestKey) {
1257
- this.processingRequests.delete(requestKey);
1258
- }
1259
- const reqUrl = this.resolveLoggedRequestUrl(error.config);
1260
- if (reqUrl) {
1261
- this.logNetworkEvent(
1262
- {
1263
- method: (error.config?.method || 'GET').toUpperCase(),
1264
- url: reqUrl,
1265
- source: 'error',
1266
- status: error.response?.status,
1267
- errorMessage: error?.message ?? String(error),
1268
- requestBody: error.config?.data,
1269
- responseBody: error.response?.data,
1270
- },
1271
- this.readRequestCorrelation(error.config),
1272
- error.config?.headers
1273
- );
1274
- }
1275
- this.throwWithMockifyerRequestId(error);
1276
- }
1277
- );
1278
- }
1279
-
1280
- /**
1281
- * When dashboard proxy records to Redis, optionally persist the same payload next to the client
1282
- * (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
1283
- */
1284
- private async maybeMirrorProxyRecordingToClient(response: HTTPResponse): Promise<void> {
1285
- const rec = response.mockifyerProxyRecording;
1286
- if (!rec?.recordedToStore || !rec.storedMock) {
1287
- return;
1288
- }
1289
- const hash = rec.hash?.trim();
1290
- const scenarioName = rec.scenarioName?.trim();
1291
- const mockData = rec.storedMock as MockData;
1292
- const providerType = this.config.databaseProvider?.type;
1293
-
1294
- await mirrorProxyRecordingToClient({
1295
- config: this.config,
1296
- mockDataPath: this.config.mockDataPath,
1297
- recording: rec,
1298
- databaseProvider: this.databaseProvider,
1299
- databaseProviderInitPromise: this.databaseProviderInitPromise,
1300
- logPrefix: 'Mockifyer-Fetch',
1301
- });
1302
-
1303
- if (providerType === 'hybrid' && hash && scenarioName && mockData) {
1304
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
1305
- } else if (!fs && hash && scenarioName && mockData) {
1306
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
1307
- }
1308
- }
1309
-
1310
- private async tryMirrorProxyRecordingViaMetro(
1311
- mockData: MockData,
1312
- scenarioName: string,
1313
- hash: string
1314
- ): Promise<void> {
1315
- const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
1316
- const fetchFn = (global as any).__mockifyer_original_fetch || fetch;
1317
- if (!fetchFn) {
1318
- logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
1319
- return;
1320
- }
1321
- try {
1322
- const body = JSON.stringify({
1323
- __mockifyerProxyMirror: true,
1324
- mockData,
1325
- scenarioName,
1326
- relativePath: `redis/${hash}.json`,
1327
- });
1328
- const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
1329
- method: 'POST',
1330
- headers: { 'Content-Type': 'application/json' },
1331
- body,
1332
- });
1333
- const text = await res.text().catch(() => '');
1334
- if (!res.ok) {
1335
- logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
1336
- return;
1337
- }
1338
- try {
1339
- const parsed = JSON.parse(text) as { success?: boolean; error?: string };
1340
- if (parsed.success === false) {
1341
- logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
1342
- return;
1343
- }
1344
- } catch {
1345
- // non-JSON response
1346
- }
1347
- logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
1348
- } catch (e) {
1349
- logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
1350
- }
1351
- }
1352
-
1353
- private async saveResponse(response: HTTPResponse): Promise<void> {
1354
- // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
1355
- if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
1356
- return;
1357
- }
1358
-
1359
- // If using a proxy for upstream calls, do not save locally.
1360
- // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
1361
- if (this.config.proxy?.baseUrl) {
1362
- return;
1363
- }
1364
-
1365
- if (shouldBlockLocalMockRecording(this.config)) {
1366
- logger.info(
1367
- '[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).'
1368
- );
1369
- return;
1370
- }
1371
-
1372
- const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
1373
- if (url && shouldBypassMockifyerForUrl(url, this.config.excludedUrls, this.config.baseUrl)) {
1374
- return;
1375
- }
1376
- const recordingExclusions = resolveRecordingExclusions(this.config);
1377
- if (
1378
- url &&
1379
- shouldExcludeRecording(url, recordingExclusions, this.config.baseUrl)
1380
- ) {
1381
- return;
1382
- }
1383
-
1384
- const mayRecordFlag = (response.config as any)?.__mockifyer_domain_path_may_record;
1385
- if (mayRecordFlag === false) {
1386
- return;
1387
- }
1388
- if (mayRecordFlag !== true) {
1389
- this.domainPathRules.discover(url, this.config.baseUrl);
1390
- const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
1391
- if (!gate.mayRecord) {
1392
- return;
1393
- }
1394
- }
1395
-
1396
- // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
1397
- // This is a defense-in-depth measure
1398
- try {
1399
- let responseDataStr = '';
1400
- if (typeof response.data === 'string') {
1401
- responseDataStr = response.data;
1402
- } else if (response.data) {
1403
- try {
1404
- responseDataStr = JSON.stringify(response.data);
1405
- } catch (stringifyError) {
1406
- responseDataStr = String(response.data);
1407
- }
1408
- }
1409
-
1410
- // CRITICAL: Check for Metro rejection message
1411
- if (responseDataStr && responseDataStr.includes('Cannot save Mockifyer sync endpoint')) {
1412
- return;
1413
- }
1414
-
1415
- // CRITICAL: Check for sync endpoint URLs in response data
1416
- if (containsMockifyerSyncEndpointMarker(responseDataStr)) {
1417
- return;
1418
- }
1419
- } catch (e) {
1420
- // Ignore JSON stringify errors
1421
- logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
1422
- }
1423
-
1424
- // Normalize empty params: treat {} the same as undefined for consistent matching
1425
- const rawParams = response.config.params || {};
1426
- const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
1427
-
1428
- const saveLookupRequest: StoredRequest = {
1429
- method: response.config.method?.toUpperCase() || 'GET',
1430
- url: response.config.url || '',
1431
- headers: {},
1432
- data: response.config.data,
1433
- queryParams: normalizedParams,
1434
- };
1435
-
1436
- const requestKey = this.generateRequestKey(saveLookupRequest);
1437
-
1438
- if (this.savingResponses.has(requestKey)) {
1439
- return;
1440
- }
1441
-
1442
- const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
1443
- includePassthroughMocks: true,
1444
- });
1445
-
1446
- const saveDecision = resolveMockRecordingSaveDecision(
1447
- this.config,
1448
- existingMock?.mockData
1449
- );
1450
-
1451
- if (saveDecision.action === 'skip') {
1452
- if (existingMock && mockPassesThroughToRealApi(existingMock.mockData)) {
1453
- logger.info(
1454
- `[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`
1455
- );
1456
- }
1457
- return;
1458
- }
1459
-
1460
- this.savingResponses.add(requestKey);
1461
-
1462
- try {
1463
- const rawParamsForSave = response.config.params || {};
1464
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
1465
- const normalizedParamsForSave =
1466
- anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
1467
- ? anonymizedQueryParams
1468
- : undefined;
1469
-
1470
- const now = Date.now();
1471
- if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
1472
- this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
1473
- this.sessionStartTime = now;
1474
- }
1475
-
1476
- const startTime = (response.config as any).__mockifyer_startTime;
1477
- const duration = startTime ? Date.now() - startTime : undefined;
1478
-
1479
- const correlation = this.readRequestCorrelation(response.config);
1480
- const hopIds = resolvePersistedHopIds(
1481
- saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined,
1482
- correlation
1483
- );
1484
-
1485
- const storedRequest: StoredRequest = {
1486
- method: response.config?.method?.toUpperCase() || 'GET',
1487
- url: response.config?.url || '',
1488
- headers: this.anonymizeHeaders(response.config?.headers || {}),
1489
- data: response.config?.data,
1490
- queryParams: normalizedParamsForSave,
1491
- };
1492
- // Prefer explicit override / config; else request-only default (same as proxy).
1493
- const recordBodies = resolveLocalRecordResponses(
1494
- this.recordResponsesOverride ??
1495
- this.config.proxy?.recordResponses ??
1496
- this.config.recordResponses
1497
- );
1498
- const mockData = buildLocalRecordingMockData({
1499
- request: storedRequest,
1500
- response: {
1501
- status: response.status,
1502
- data: stripMockifyerTraceFromBody(response.data),
1503
- headers: response.headers || {},
1504
- },
1505
- recordResponses: recordBodies,
1506
- meta: {
1507
- timestamp: new Date().toISOString(),
1508
- duration,
1509
- sessionId:
1510
- saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1511
- ? existingMock.mockData.sessionId
1512
- : this.currentSessionId,
1513
- requestId: hopIds.requestId,
1514
- parentRequestId: hopIds.parentRequestId,
1515
- parentRequestIds: hopIds.parentRequestIds,
1516
- ...(newRecordingUsesAlwaysUseRealApi() || !recordBodies
1517
- ? { alwaysUseRealApi: true as const }
1518
- : {}),
1519
- },
1520
- });
1521
-
1522
- applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
1523
-
1524
- if (this.databaseProvider) {
1525
- try {
1526
- await this.databaseProvider.save(mockData);
1527
-
1528
- if (this.config.generateTests?.enabled) {
1529
- await this.generateTestForMock(mockData);
1530
- }
1531
- } catch (error) {
1532
- console.error(
1533
- `[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`,
1534
- error
1535
- );
1536
- throw error;
1537
- }
1538
- } else if (fs && path) {
1539
- const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1540
- const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
1541
- ensureScenarioFolder(this.config.mockDataPath, currentScenario);
1542
-
1543
- const limitCheck = checkRequestLimit(this.config.mockDataPath);
1544
- if (limitCheck.limitReached && limitCheck.error) {
1545
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
1546
- return;
1547
- }
1548
-
1549
- if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
1550
- fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
1551
- logger.info(
1552
- `[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
1553
- );
1554
- } else {
1555
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
1556
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
1557
- const domain = urlParts[0].replace(/\./g, '_');
1558
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
1559
- const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
1560
- const filePath = path.join(scenarioPath, filename);
1561
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
1562
- logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
1563
- }
1564
-
1565
- if (this.config.generateTests?.enabled && this.testGenerator) {
1566
- await this.generateTestForMock(mockData);
1567
- }
1568
- } else {
1569
- console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
1570
- }
1571
-
1572
- await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
1573
- } finally {
1574
- this.savingResponses.delete(requestKey);
1575
- }
1576
- }
1577
-
1578
- /**
1579
- * When a child hop is recorded locally, persist a synthetic inbound-parent stub so
1580
- * Hops does not show "Missing entry hop" for the ALS gateway id.
1581
- */
1582
- private async ensureInboundParentStubForChild(
1583
- parentRequestId: string | null | undefined,
1584
- config: unknown
1585
- ): Promise<void> {
1586
- const activeInbound = getActiveInboundRequest();
1587
- const hop =
1588
- readOutboundParentHopFromConfig(config) ??
1589
- (activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
1590
-
1591
- try {
1592
- await ensureLocalInboundParentStubSaved({
1593
- parentRequestId,
1594
- hop,
1595
- parentExists: (id) => {
1596
- if (!fs || !path || this.databaseProvider) {
1597
- return false;
1598
- }
1599
- const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1600
- const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
1601
- return fs.existsSync(path.join(scenarioPath, inboundParentStubFilename(id)));
1602
- },
1603
- save: async (row) => {
1604
- if (this.databaseProvider) {
1605
- await this.databaseProvider.save(row.mock);
1606
- return;
1607
- }
1608
- if (!fs || !path) {
1609
- return;
1610
- }
1611
- const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1612
- const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
1613
- ensureScenarioFolder(this.config.mockDataPath, currentScenario);
1614
- const filePath = path.join(scenarioPath, row.filename);
1615
- if (fs.existsSync(filePath)) {
1616
- return;
1617
- }
1618
- fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
1619
- logger.info(
1620
- `[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`
1621
- );
1622
- },
1623
- });
1624
- } catch (error) {
1625
- const message = error instanceof Error ? error.message : String(error);
1626
- logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
1627
- }
1628
- }
1629
-
1630
- private async persistMatchedMockAfterLiveCapture(
1631
- cachedMock: CachedMockData,
1632
- capturedResponse: StoredResponse,
1633
- durationMs?: number,
1634
- liveCorrelation?: RequestCorrelationContext
1635
- ): Promise<void> {
1636
- const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
1637
- applyPersistedHopIds(updated, resolvePersistedHopIds(cachedMock.mockData, liveCorrelation));
1638
-
1639
- if (this.databaseProvider) {
1640
- await this.databaseProvider.save(updated);
1641
- return;
1642
- }
1643
-
1644
- if (fs && cachedMock.filePath) {
1645
- fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
1646
- logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
1647
- }
1648
- }
1649
-
1650
- /**
1651
- * Simple path resolution fallback for React Native (when path module is stubbed)
1652
- */
1653
- private resolvePath(...parts: string[]): string {
1654
- if (path && typeof path.resolve === 'function') {
1655
- return path.resolve(...parts);
1656
- }
1657
- // Fallback: simple string-based path resolution
1658
- const cwd = typeof process !== 'undefined' && process.cwd ? process.cwd() : '.';
1659
- const joined = parts
1660
- .filter(p => p)
1661
- .join('/')
1662
- .replace(/\/+/g, '/')
1663
- .replace(/^\.\//, '');
1664
-
1665
- if (joined.startsWith('/')) {
1666
- return joined;
1667
- }
1668
- return `${cwd}/${joined}`.replace(/\/+/g, '/');
1669
- }
1670
-
1671
- /**
1672
- * Simple dirname fallback for React Native (when path module is stubbed)
1673
- */
1674
- private dirname(filePath: string): string {
1675
- if (path && typeof path.dirname === 'function') {
1676
- return path.dirname(filePath);
1677
- }
1678
- // Fallback: extract directory from path string
1679
- const lastSlash = filePath.lastIndexOf('/');
1680
- if (lastSlash <= 0) {
1681
- return '.';
1682
- }
1683
- return filePath.substring(0, lastSlash);
1684
- }
1685
-
1686
- /**
1687
- * Generates test file for a mock
1688
- */
1689
- private async generateTestForMock(mockData: MockData): Promise<void> {
1690
- if (!this.testGenerator) {
1691
- return;
1692
- }
1693
-
1694
- // Check if fs is available for writing test files
1695
- // In React Native runtime, fs is not available, but in Metro bundler (Node.js) it should be
1696
- // Try to require it dynamically if not already available
1697
- let testFs = fs;
1698
-
1699
- if (!testFs) {
1700
- try {
1701
- testFs = require('fs');
1702
- } catch (e) {
1703
- return;
1704
- }
1705
- }
1706
-
1707
- // Use the available fs - ensure it's defined and has required methods
1708
- if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
1709
- return;
1710
- }
1711
-
1712
- const fsToUse = testFs;
1713
-
1714
- try {
1715
- const options: TestGenerationOptions = {
1716
- framework: this.config.generateTests?.framework || 'jest',
1717
- outputPath: this.config.generateTests?.outputPath || './tests/generated',
1718
- testPattern: this.config.generateTests?.testPattern || '{endpoint}.test.ts',
1719
- includeSetup: this.config.generateTests?.includeSetup !== false,
1720
- groupBy: this.config.generateTests?.groupBy || 'file',
1721
- httpClientType: 'fetch'
1722
- };
1723
-
1724
- const testCode = this.testGenerator.generateTest(mockData, options);
1725
- const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
1726
-
1727
- // Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
1728
- // Use our fallback path resolution that works even when path module is stubbed
1729
- const absoluteTestPath = this.resolvePath(testFilePath);
1730
-
1731
- // Ensure test directory exists
1732
- const testDir = this.dirname(absoluteTestPath);
1733
-
1734
- if (!fsToUse.existsSync(testDir)) {
1735
- fsToUse.mkdirSync(testDir, { recursive: true });
1736
- }
1737
-
1738
- // Check if test file already exists
1739
- if (fsToUse.existsSync(absoluteTestPath)) {
1740
- // Extract test info to check if test already exists
1741
- const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
1742
- const testName = this.generateTestNameFromInfo(testInfo);
1743
-
1744
- // Check if test already exists
1745
- const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
1746
- if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
1747
- return;
1748
- }
1749
-
1750
- // Extract test code without imports and describe wrapper
1751
- const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
1752
- if (testMatch) {
1753
- // Append test to existing describe block
1754
- const newTest = testMatch[0];
1755
- const updatedContent = existingContent.replace(
1756
- /(\s+)(\}\);?\s*)$/,
1757
- `$1${newTest}\n$1$2`
1758
- );
1759
- fsToUse.writeFileSync(absoluteTestPath, updatedContent);
1760
- }
1761
- } else {
1762
- // Create new test file
1763
- fsToUse.writeFileSync(absoluteTestPath, testCode);
1764
- }
1765
- } catch (error: any) {
1766
- logger.error('[Mockifyer] ❌ Error generating test:', error);
1767
- logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
1768
- logger.error('[Mockifyer] ❌ Error message:', error?.message);
1769
- // Don't throw - test generation failure shouldn't break mock saving
1770
- }
1771
- }
1772
-
1773
- /**
1774
- * Helper to generate test name from test info
1775
- */
1776
- private generateTestNameFromInfo(testInfo: any): string {
1777
- const method = testInfo.method.toUpperCase();
1778
- const endpoint = testInfo.endpoint;
1779
-
1780
- if (testInfo.isGraphQL && testInfo.graphQLQuery) {
1781
- const operationMatch = testInfo.graphQLQuery.match(/(?:query|mutation|subscription)\s+(\w+)/);
1782
- if (operationMatch) {
1783
- return `should execute ${operationMatch[1]} query`;
1784
- }
1785
- return 'should execute GraphQL query';
1786
- }
1787
-
1788
- return `should ${method} ${endpoint}`;
1789
- }
1790
-
1791
- private anonymizeHeaders(headers: Record<string, any>): Record<string, any> {
1792
- const defaultHeadersToAnonymize = [
1793
- 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
1794
- 'x-auth-token', 'x-access-token', 'bearer'
1795
- ];
1796
-
1797
- const headersToAnonymize = this.config.anonymizeHeaders !== undefined
1798
- ? this.config.anonymizeHeaders
1799
- : defaultHeadersToAnonymize;
1800
-
1801
- if (headersToAnonymize.length === 0) {
1802
- return headers;
1803
- }
1804
-
1805
- const anonymized = { ...headers };
1806
- const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h: string) => h.toLowerCase());
1807
-
1808
- Object.keys(anonymized).forEach(key => {
1809
- if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
1810
- anonymized[key] = '***';
1811
- }
1812
- });
1813
-
1814
- return anonymized;
1815
- }
1816
-
1817
- private anonymizeQueryParams(params: Record<string, any>): Record<string, any> {
1818
- const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
1819
-
1820
- const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
1821
- ? this.config.anonymizeQueryParams
1822
- : defaultParamsToAnonymize;
1823
-
1824
- if (paramsToAnonymize.length === 0) {
1825
- return params;
1826
- }
1827
-
1828
- const anonymized = { ...params };
1829
- const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p: string) => p.toLowerCase());
1830
-
1831
- Object.keys(anonymized).forEach(key => {
1832
- if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
1833
- anonymized[key] = '***';
1834
- }
1835
- });
1836
-
1837
- return anonymized;
1838
- }
1839
-
1840
- /**
1841
- * Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
1842
- * Does not re-read native launch arguments or environment variables.
1843
- */
1844
- setClientId(lane: string): void {
1845
- const t = String(lane).trim();
1846
- if (!t) {
1847
- throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
1848
- }
1849
- this.config.clientId = t;
1850
- logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
1851
- }
1852
-
1853
- /** Current logical lane id (same value used for isolation). */
1854
- getClientId(): string | undefined {
1855
- return this.config.clientId;
1856
- }
1857
-
1858
- /**
1859
- * Turn record mode on/off at runtime (dev menus, tests).
1860
- * Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
1861
- * Redis/proxy recording follows the same switch as local hybrid saves.
1862
- *
1863
- * When enabling: flips existing allowlist `recordResponses` to true and new
1864
- * discoveries enable recording. When disabled, allowlist discovery stops
1865
- * persisting new keys (so browsing does not poison the rules file).
1866
- */
1867
- setRecordMode(enabled: boolean): void {
1868
- const next = Boolean(enabled);
1869
- this.config.recordMode = next;
1870
- if (next) {
1871
- // Recording needs live upstream calls; fail-on-miss conflicts with that.
1872
- this.config.failOnMissingMock = false;
1873
- this.domainPathRules.enableRecordResponsesForAllRules();
1874
- }
1875
- if (this.config.proxy?.baseUrl) {
1876
- this.config.proxy = {
1877
- ...this.config.proxy,
1878
- recordOnMiss: next,
1879
- };
1880
- const client = this.httpClient as FetchHTTPClient & {
1881
- setProxyRecordOnMiss?: (value: boolean | undefined) => void;
1882
- };
1883
- client.setProxyRecordOnMiss?.(next);
1884
- }
1885
- logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
1886
- }
1887
-
1888
- /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
1889
- isRecordMode(): boolean {
1890
- return this.config.recordMode === true;
1891
- }
1892
-
1893
- /**
1894
- * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
1895
- * Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
1896
- */
1897
- setRecordResponses(enabled: boolean): void {
1898
- const next = Boolean(enabled);
1899
- this.recordResponsesOverride = next;
1900
- this.config.recordResponses = next;
1901
- if (this.config.proxy) {
1902
- this.config.proxy = {
1903
- ...this.config.proxy,
1904
- recordResponses: next,
1905
- };
1906
- }
1907
- const client = this.httpClient as FetchHTTPClient & {
1908
- setProxyRecordResponses?: (value: boolean) => void;
1909
- };
1910
- client.setProxyRecordResponses?.(next);
1911
- logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
1912
- }
1913
-
1914
- /** True when new recordings include response bodies (not request-only stubs). */
1915
- isRecordResponses(): boolean {
1916
- if (this.config.proxy?.baseUrl) {
1917
- return resolveRecordResponses(
1918
- this.recordResponsesOverride ?? this.config.proxy.recordResponses
1919
- );
1920
- }
1921
- return resolveLocalRecordResponses(
1922
- this.recordResponsesOverride ?? this.config.recordResponses
1923
- );
1924
- }
1925
-
1926
- /**
1927
- * Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
1928
- * (mock lookup, recording, dashboard/Redis proxy, etc.).
1929
- * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1930
- */
1931
- enableMockifyer(): void {
1932
- this.runtimeEnabled = true;
1933
- logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
1934
- void this.persistRuntimeEnabledState(true);
1935
- }
1936
-
1937
- /**
1938
- * Disable Mockifyer at runtime. All subsequent requests will bypass Mockifyer completely
1939
- * (no dashboard, Redis, proxy, mock lookup, or recording).
1940
- * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1941
- */
1942
- disableMockifyer(): void {
1943
- this.runtimeEnabled = false;
1944
- logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
1945
- void this.persistRuntimeEnabledState(false);
1946
- }
1947
-
1948
- /**
1949
- * Check if Mockifyer is currently enabled at runtime.
1950
- */
1951
- isMockifyerEnabled(): boolean {
1952
- return this.runtimeEnabled;
1953
- }
1954
-
1955
- private async persistRuntimeEnabledState(enabled: boolean): Promise<void> {
1956
- if (!this.runtimeEnabledStorage) {
1957
- return;
1958
- }
1959
- await savePersistedRuntimeEnabled(this.runtimeEnabledStorage, enabled);
1960
- }
1961
-
1962
- getHTTPClient(): HTTPClient {
1963
- return this.httpClient;
1964
- }
1965
-
1966
- async reloadMockData(syncFromProject: boolean = true): Promise<void> {
1967
- await this.databaseProviderInitPromise;
1968
- // `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
1969
- // picks up updated pool response bodies from the provider / Metro sync.
1970
- this.poolResponseCache.clear();
1971
- // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
1972
- // For HybridProvider, this will also sync files from project folder to device
1973
- if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
1974
- if (syncFromProject && typeof (this.databaseProvider as any).reload === 'function') {
1975
- // Pass syncFromProject flag if provider supports it (HybridProvider)
1976
- await (this.databaseProvider as any).reload(syncFromProject);
1977
- } else {
1978
- await (this.databaseProvider as any).reload();
1979
- }
1980
- } else {
1981
- // Fallback: try to load mock data if method exists
1982
- if (typeof (this as any).loadMockData === 'function') {
1983
- (this as any).loadMockData();
1984
- }
1985
- }
1986
- // RN Hybrid: pull domain-path-rules.json via Metro before traffic can discover
1987
- // allowlist defaults that would block already-enabled paths.
1988
- this.domainPathRules.invalidateCache();
1989
- await this.domainPathRules.hydrate();
1990
- }
1991
-
1992
- clearStaleCacheEntries(): number {
1993
- return 0; // No cache in fetch implementation
1994
- }
1995
-
1996
- async clearAllMocks(): Promise<void> {
1997
- if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
1998
- await this.databaseProvider.clearAll();
1999
- } else {
2000
- logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
2001
- }
2002
- }
2003
- }
148
+ import { NodeCapabilities } from './node-capabilities';
149
+ import { MockifyerClass } from './mockifyer-class';
2004
150
 
2005
151
  export interface MockifyerInstance extends HTTPClient {
2006
152
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
@@ -2273,6 +419,9 @@ export {
2273
419
  canUseDashboardCentralProxy,
2274
420
  } from './utils/dashboard-redis-health';
2275
421
 
422
+ // Export MockifyerClass for browser/RN entries to use with capabilities
423
+ export { MockifyerClass };
424
+
2276
425
  // Re-export types from core
2277
426
  export * from '@sgedda/mockifyer-core';
2278
427