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