@sgedda/mockifyer-fetch 1.7.2 → 1.8.1

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.js DELETED
@@ -1,966 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.setupMockifyer = setupMockifyer;
18
- // Fetch-only Mockifyer implementation
19
- // Conditionally import fs - will be undefined in React Native
20
- let fs;
21
- let path;
22
- try {
23
- // Try to require fs and path - will fail in React Native where they're stubbed
24
- fs = require('fs');
25
- path = require('path');
26
- }
27
- catch (e) {
28
- // fs/path not available (React Native environment)
29
- fs = undefined;
30
- path = undefined;
31
- }
32
- // Import from core package
33
- const mockifyer_core_1 = require("@sgedda/mockifyer-core");
34
- const mockifyer_core_2 = require("@sgedda/mockifyer-core");
35
- const fetch_client_1 = require("./clients/fetch-client");
36
- class MockifyerClass {
37
- constructor(config) {
38
- var _a;
39
- this.processingRequests = new Set();
40
- this.savingResponses = new Set();
41
- this.currentSessionId = null;
42
- this.sessionStartTime = 0;
43
- this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
44
- // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
45
- if (config.databaseProvider && config.databaseProvider.type) {
46
- const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory'];
47
- if (!supportedTypes.includes(config.databaseProvider.type)) {
48
- throw new Error(`Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
49
- `Supported types: ${supportedTypes.join(', ')}. ` +
50
- `Please use one of the supported provider types.`);
51
- }
52
- }
53
- // Validate and normalize conflicting settings
54
- if (config.recordMode && config.failOnMissingMock) {
55
- mockifyer_core_2.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
56
- 'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
57
- 'Setting failOnMissingMock to false.');
58
- config.failOnMissingMock = false;
59
- }
60
- // Validate conflicting similar match settings
61
- if (config.similarMatchIgnoreAllQueryParams &&
62
- config.similarMatchRequiredParams &&
63
- config.similarMatchRequiredParams.length > 0) {
64
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
65
- 'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
66
- 'similarMatchRequiredParams will be ignored.');
67
- // Clear similarMatchRequiredParams to avoid confusion
68
- config.similarMatchRequiredParams = undefined;
69
- }
70
- // Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
71
- if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
72
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
73
- config.useSimilarMatch = true;
74
- }
75
- }
76
- // Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
77
- if (config.similarMatchIgnoreAllQueryParams) {
78
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
79
- config.useSimilarMatch = true;
80
- }
81
- }
82
- // Store config BEFORE any modifications
83
- this.config = { ...config }; // Create a copy to avoid mutations
84
- // Initialize test generator if test generation is enabled
85
- if ((_a = config.generateTests) === null || _a === void 0 ? void 0 : _a.enabled) {
86
- this.testGenerator = new mockifyer_core_1.TestGenerator();
87
- }
88
- // Initialize database provider if specified
89
- if (config.databaseProvider && config.databaseProvider.type) {
90
- this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, config.databaseProvider);
91
- const initResult = this.databaseProvider.initialize();
92
- // Handle async initialization (expo-filesystem provider has async initialize)
93
- if (initResult instanceof Promise) {
94
- initResult.catch((error) => {
95
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
96
- });
97
- }
98
- }
99
- else {
100
- // Fallback to Node.js filesystem
101
- this.ensureMockDataDirectory();
102
- }
103
- // Create fetch HTTP client
104
- this.httpClient = new fetch_client_1.FetchHTTPClient({
105
- baseUrl: config.baseUrl,
106
- defaultHeaders: config.defaultHeaders
107
- });
108
- if (!config.recordSameEndpoints) {
109
- this.loadMockData();
110
- }
111
- // Always set up mock response interceptor (to use existing mocks)
112
- this.setupMockResponses();
113
- // Set up response interceptor to save responses when recordMode is enabled
114
- this.setupResponseInterceptor();
115
- }
116
- ensureMockDataDirectory() {
117
- // Only use fs if available (Node.js environment) and no database provider is set
118
- if (!fs || this.databaseProvider) {
119
- return;
120
- }
121
- if (!fs.existsSync(this.config.mockDataPath)) {
122
- fs.mkdirSync(this.config.mockDataPath, { recursive: true });
123
- }
124
- }
125
- generateRequestKey(request) {
126
- return (0, mockifyer_core_1.generateRequestKey)(request);
127
- }
128
- async findBestMatchingMock(request) {
129
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
130
- const requestUrl = (request === null || request === void 0 ? void 0 : request.url) || '';
131
- if (requestUrl.includes('/mockifyer-save') ||
132
- requestUrl.includes('/mockifyer-clear') ||
133
- requestUrl.includes('/mockifyer-sync')) {
134
- return undefined;
135
- }
136
- const requestKey = this.generateRequestKey(request);
137
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
138
- if (requestKey.includes('/mockifyer-save') ||
139
- requestKey.includes('/mockifyer-clear') ||
140
- requestKey.includes('/mockifyer-sync')) {
141
- return undefined;
142
- }
143
- // Use database provider if available, otherwise fallback to filesystem
144
- if (this.databaseProvider) {
145
- return await this.findBestMatchingMockFromProvider(request);
146
- }
147
- // Fallback to Node.js filesystem
148
- return this.findBestMatchingMockFromFiles(request);
149
- }
150
- async findBestMatchingMockFromProvider(request) {
151
- if (!this.databaseProvider) {
152
- return undefined;
153
- }
154
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
155
- const requestUrl = (request === null || request === void 0 ? void 0 : request.url) || '';
156
- if (requestUrl.includes('/mockifyer-save') ||
157
- requestUrl.includes('/mockifyer-clear') ||
158
- requestUrl.includes('/mockifyer-sync')) {
159
- return undefined;
160
- }
161
- const requestKey = this.generateRequestKey(request);
162
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
163
- if (requestKey.includes('/mockifyer-save') ||
164
- requestKey.includes('/mockifyer-clear') ||
165
- requestKey.includes('/mockifyer-sync')) {
166
- return undefined;
167
- }
168
- // Try exact match first
169
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
170
- if (exactMatch) {
171
- return exactMatch;
172
- }
173
- // Try similar match if enabled
174
- if (this.config.useSimilarMatch) {
175
- const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
176
- if (similarMatches && similarMatches.length > 0) {
177
- // Return first similar match
178
- return similarMatches[0];
179
- }
180
- }
181
- return undefined;
182
- }
183
- findBestMatchingMockFromFiles(request) {
184
- // Only use fs if available (Node.js environment)
185
- // This method should never be called when using a database provider
186
- if (!fs || !path) {
187
- return undefined;
188
- }
189
- const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
190
- if (!fs.existsSync(resolvedMockDataPath)) {
191
- console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
192
- return undefined;
193
- }
194
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath);
195
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
196
- if (!fs.existsSync(scenarioPath)) {
197
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
198
- return undefined;
199
- }
200
- const files = fs.readdirSync(scenarioPath)
201
- .filter(file => file.endsWith('.json'));
202
- const requestKey = this.generateRequestKey(request);
203
- let exactMatch;
204
- let similarMatch;
205
- for (const file of files) {
206
- try {
207
- const filePath = path.join(scenarioPath, file);
208
- const fileContent = fs.readFileSync(filePath, 'utf-8');
209
- const mockData = JSON.parse(fileContent);
210
- if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
211
- continue;
212
- }
213
- const mockKey = this.generateRequestKey(mockData.request);
214
- if (mockKey === requestKey) {
215
- exactMatch = { mockData, filename: file, filePath };
216
- break;
217
- }
218
- if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
219
- // Check if it's a GraphQL request - skip similar matching for GraphQL
220
- const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
221
- request.data &&
222
- (() => {
223
- try {
224
- let bodyData = request.data;
225
- if (typeof request.data === 'string') {
226
- bodyData = JSON.parse(request.data);
227
- }
228
- return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
229
- }
230
- catch {
231
- return false;
232
- }
233
- })();
234
- if (!isGraphQL) {
235
- try {
236
- const requestUrl = new URL(request.url);
237
- const mockUrl = new URL(mockData.request.url);
238
- // Check if pathnames match (exact or pattern-based)
239
- const requestPathname = requestUrl.pathname;
240
- const mockPathname = mockUrl.pathname;
241
- const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
242
- // Check for exact pathname match
243
- const exactPathnameMatch = mockPathname === requestPathname;
244
- // Check for pattern-based match (e.g., /posts/71 matches /posts/17 when similarMatchIgnoreAllQueryParams is true)
245
- // This allows matching paths with different IDs when we're ignoring query params
246
- let patternMatch = false;
247
- if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
248
- // Extract base path by removing the last segment (ID)
249
- // /posts/71 -> /posts, /users/2/todos -> /users/2
250
- const requestSegments = requestPathname.split('/').filter(s => s);
251
- const mockSegments = mockPathname.split('/').filter(s => s);
252
- // Match if base paths are the same (same number of segments, all but last match)
253
- if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
254
- const requestBase = requestSegments.slice(0, -1);
255
- const mockBase = mockSegments.slice(0, -1);
256
- patternMatch = requestBase.join('/') === mockBase.join('/');
257
- }
258
- }
259
- const pathnameMatch = exactPathnameMatch || patternMatch;
260
- // Check similar match
261
- if (pathnameMatch && methodMatch) {
262
- // If ignoreAllQueryParams is set, skip query param checking entirely
263
- if (this.config.similarMatchIgnoreAllQueryParams) {
264
- // Ignore all query params, match on path and method only
265
- }
266
- else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
267
- // Check if required parameters match (if configured)
268
- const requestParams = request.queryParams || {};
269
- const mockParams = mockData.request.queryParams || {};
270
- const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
271
- const requestValue = requestParams[paramName];
272
- const mockValue = mockParams[paramName];
273
- return requestValue === undefined && mockValue === undefined
274
- ? true
275
- : String(requestValue || '') === String(mockValue || '');
276
- });
277
- if (!allRequiredMatch) {
278
- continue; // Required parameter differs, skip this mock
279
- }
280
- }
281
- similarMatch = { mockData, filename: file, filePath };
282
- }
283
- }
284
- catch (e) {
285
- continue;
286
- }
287
- }
288
- }
289
- }
290
- catch (error) {
291
- mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
292
- }
293
- }
294
- return exactMatch || similarMatch;
295
- }
296
- loadMockData() {
297
- // Skip if using database provider or fs not available
298
- if (this.databaseProvider || !fs) {
299
- return;
300
- }
301
- if (fs.existsSync(this.config.mockDataPath)) {
302
- fs.readdirSync(this.config.mockDataPath)
303
- .filter(file => file.endsWith('.json'));
304
- }
305
- }
306
- setupMockResponses() {
307
- this.httpClient.interceptors.request.use(async (config) => {
308
- // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
309
- // This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
310
- const url = config.url || '';
311
- if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
312
- // Mark this request to completely skip Mockifyer processing
313
- config.__mockifyer_skip_save = true;
314
- config.__mockifyer_bypass = true;
315
- return config;
316
- }
317
- // Normalize empty params: treat {} the same as undefined for consistent matching
318
- const rawParams = config.params || {};
319
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
320
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
321
- ? anonymizedQueryParams
322
- : undefined;
323
- const request = {
324
- method: config.method || 'GET',
325
- url: config.url || '',
326
- headers: config.headers || {},
327
- data: config.data,
328
- queryParams: normalizedParams
329
- };
330
- const requestKey = this.generateRequestKey(request);
331
- // Store request key for response interceptor
332
- config.__mockifyer_requestKey = requestKey;
333
- // Store request start time for duration calculation
334
- config.__mockifyer_startTime = Date.now();
335
- const cachedMock = await this.findBestMatchingMock(request);
336
- // Return cached mock if found
337
- if (cachedMock) {
338
- const { mockData, filename, filePath } = cachedMock;
339
- const responseHeaders = {
340
- ...mockData.response.headers,
341
- 'x-mockifyer': 'true',
342
- 'x-mockifyer-timestamp': mockData.timestamp,
343
- 'x-mockifyer-filename': filename,
344
- 'x-mockifyer-filepath': filePath
345
- };
346
- const mockResponse = {
347
- data: mockData.response.data,
348
- status: mockData.response.status,
349
- statusText: 'OK',
350
- headers: responseHeaders,
351
- config: config
352
- };
353
- return {
354
- ...config,
355
- __mockResponse: Promise.resolve(mockResponse),
356
- __mockifyer_requestKey: requestKey
357
- };
358
- }
359
- // Check request limit BEFORE making real API call (only if no mock found and in record mode)
360
- if (this.config.recordMode) {
361
- const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
362
- if (limitCheck.limitReached && limitCheck.error) {
363
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
364
- // Return a mock error response instead of making a real API call
365
- const responseHeaders = {
366
- 'x-mockifyer': 'true',
367
- 'x-mockifyer-limit-reached': 'true',
368
- 'content-type': 'application/json'
369
- };
370
- const mockErrorResponse = {
371
- data: {
372
- error: limitCheck.error.message,
373
- message: limitCheck.error.message,
374
- limitReached: true,
375
- maxRequests: limitCheck.error.maxRequests,
376
- currentScenario: limitCheck.error.currentScenario
377
- },
378
- status: 429, // Too Many Requests
379
- statusText: 'Too Many Requests',
380
- headers: responseHeaders,
381
- config: config
382
- };
383
- return {
384
- ...config,
385
- __mockResponse: Promise.resolve(mockErrorResponse),
386
- __mockifyer_requestKey: requestKey,
387
- __mockifyer_limit_reached: true
388
- };
389
- }
390
- }
391
- if (this.config.failOnMissingMock) {
392
- throw new Error(`No mock data found for request: ${this.generateRequestKey(request)}`);
393
- }
394
- return config;
395
- });
396
- }
397
- setupResponseInterceptor() {
398
- this.httpClient.interceptors.response.use(async (response) => {
399
- var _a, _b, _c;
400
- // CRITICAL: Check for skip flag FIRST (set by request interceptor for sync endpoints)
401
- // This completely bypasses Mockifyer interception for sync endpoints
402
- if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
403
- return response;
404
- }
405
- // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
406
- // Check multiple ways to get the URL in case response.config is undefined
407
- const url = ((_a = response.config) === null || _a === void 0 ? void 0 : _a.url) || ((_b = response.request) === null || _b === void 0 ? void 0 : _b.responseURL) || response.url || ((_c = response.config) === null || _c === void 0 ? void 0 : _c.url) || '';
408
- // CRITICAL: Check URL FIRST before any other processing
409
- if (url && (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync'))) {
410
- // Mark as bypassed to prevent any further processing
411
- response.config.__mockifyer_skip_save = true;
412
- response.config.__mockifyer_bypass = true;
413
- return response;
414
- }
415
- // Clean up processing requests tracking
416
- const requestKey = response.config.__mockifyer_requestKey;
417
- if (requestKey) {
418
- this.processingRequests.delete(requestKey);
419
- }
420
- // CRITICAL: Check response data for Metro rejection messages (defense in depth)
421
- // This catches any responses that might have gotten through
422
- try {
423
- let responseDataStr = '';
424
- let responseDataObj = null;
425
- if (typeof response.data === 'string') {
426
- responseDataStr = response.data;
427
- try {
428
- responseDataObj = JSON.parse(response.data);
429
- }
430
- catch (e) {
431
- // Not JSON, that's fine
432
- }
433
- }
434
- else if (response.data) {
435
- // Try to stringify, but handle circular references
436
- try {
437
- responseDataStr = JSON.stringify(response.data);
438
- responseDataObj = response.data;
439
- }
440
- catch (stringifyError) {
441
- // If stringify fails, try to get a string representation
442
- responseDataStr = String(response.data);
443
- }
444
- }
445
- // CRITICAL: Check for Metro rejection message
446
- const hasRejectionMessage = responseDataStr && (responseDataStr.includes('Cannot save Mockifyer sync endpoint') ||
447
- responseDataStr.includes('Cannot save Mockifyer sync endpoint requests'));
448
- const hasRejectionInObject = responseDataObj && ((responseDataObj.error && typeof responseDataObj.error === 'string' &&
449
- responseDataObj.error.includes('Cannot save Mockifyer sync endpoint')) ||
450
- (responseDataObj.success === false && responseDataObj.error));
451
- if (hasRejectionMessage || hasRejectionInObject) {
452
- return response;
453
- }
454
- // CRITICAL: Check for sync endpoint URLs in response data
455
- if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
456
- responseDataStr.includes('/mockifyer-clear') ||
457
- responseDataStr.includes('/mockifyer-sync'))) {
458
- return response;
459
- }
460
- }
461
- catch (e) {
462
- // Ignore errors - continue processing
463
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
464
- }
465
- const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
466
- const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
467
- if (isMocked || isLimitReached) {
468
- return response;
469
- }
470
- // Only save if recordMode is enabled
471
- if (this.config.recordMode) {
472
- await this.saveResponse(response);
473
- }
474
- return response;
475
- }, async (error) => {
476
- var _a;
477
- const requestKey = (_a = error.config) === null || _a === void 0 ? void 0 : _a.__mockifyer_requestKey;
478
- if (requestKey) {
479
- this.processingRequests.delete(requestKey);
480
- }
481
- throw error;
482
- });
483
- }
484
- async saveResponse(response) {
485
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
486
- // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
487
- if (((_a = response.config) === null || _a === void 0 ? void 0 : _a.__mockifyer_skip_save) || ((_b = response.config) === null || _b === void 0 ? void 0 : _b.__mockifyer_bypass)) {
488
- return;
489
- }
490
- // CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
491
- // Check multiple ways to get the URL in case response.config is undefined
492
- const url = ((_c = response.config) === null || _c === void 0 ? void 0 : _c.url) || ((_d = response.request) === null || _d === void 0 ? void 0 : _d.responseURL) || response.url || '';
493
- if (url && (url.includes('/mockifyer-save') ||
494
- url.includes('/mockifyer-clear') ||
495
- url.includes('/mockifyer-sync') ||
496
- url.includes('api.resend.com'))) {
497
- return;
498
- }
499
- // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
500
- // This is a defense-in-depth measure
501
- try {
502
- let responseDataStr = '';
503
- if (typeof response.data === 'string') {
504
- responseDataStr = response.data;
505
- }
506
- else if (response.data) {
507
- try {
508
- responseDataStr = JSON.stringify(response.data);
509
- }
510
- catch (stringifyError) {
511
- responseDataStr = String(response.data);
512
- }
513
- }
514
- // CRITICAL: Check for Metro rejection message
515
- if (responseDataStr && responseDataStr.includes('Cannot save Mockifyer sync endpoint')) {
516
- return;
517
- }
518
- // CRITICAL: Check for sync endpoint URLs in response data
519
- if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
520
- responseDataStr.includes('/mockifyer-clear') ||
521
- responseDataStr.includes('/mockifyer-sync'))) {
522
- return;
523
- }
524
- }
525
- catch (e) {
526
- // Ignore JSON stringify errors
527
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
528
- }
529
- // Normalize empty params: treat {} the same as undefined for consistent matching
530
- const rawParams = response.config.params || {};
531
- const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
532
- const requestKey = this.generateRequestKey({
533
- method: ((_e = response.config.method) === null || _e === void 0 ? void 0 : _e.toUpperCase()) || 'GET',
534
- url: response.config.url || '',
535
- headers: {},
536
- data: response.config.data,
537
- queryParams: normalizedParams
538
- });
539
- if (this.savingResponses.has(requestKey)) {
540
- return;
541
- }
542
- this.savingResponses.add(requestKey);
543
- try {
544
- // Normalize empty params: treat {} the same as undefined for consistent matching
545
- const rawParams = response.config.params || {};
546
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
547
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
548
- ? anonymizedQueryParams
549
- : undefined;
550
- // Generate or reuse sessionId
551
- const now = Date.now();
552
- if (!this.currentSessionId || (now - this.sessionStartTime) > this.SESSION_TIMEOUT_MS) {
553
- // Generate new session ID
554
- this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
555
- this.sessionStartTime = now;
556
- }
557
- // Calculate request duration if start time is available
558
- const startTime = response.config.__mockifyer_startTime;
559
- const duration = startTime ? Date.now() - startTime : undefined;
560
- const mockData = {
561
- request: {
562
- method: ((_g = (_f = response.config) === null || _f === void 0 ? void 0 : _f.method) === null || _g === void 0 ? void 0 : _g.toUpperCase()) || 'GET',
563
- url: ((_h = response.config) === null || _h === void 0 ? void 0 : _h.url) || '',
564
- headers: this.anonymizeHeaders(((_j = response.config) === null || _j === void 0 ? void 0 : _j.headers) || {}),
565
- data: (_k = response.config) === null || _k === void 0 ? void 0 : _k.data,
566
- queryParams: normalizedParams
567
- },
568
- response: {
569
- status: response.status,
570
- data: response.data,
571
- headers: response.headers || {}
572
- },
573
- timestamp: new Date().toISOString(),
574
- duration,
575
- sessionId: this.currentSessionId
576
- };
577
- // Use database provider if available, otherwise fallback to filesystem
578
- if (this.databaseProvider) {
579
- try {
580
- await this.databaseProvider.save(mockData);
581
- // Generate test if enabled (try to write test files even with database provider)
582
- // Generate test if enabled
583
- if ((_l = this.config.generateTests) === null || _l === void 0 ? void 0 : _l.enabled) {
584
- await this.generateTestForMock(mockData);
585
- }
586
- }
587
- catch (error) {
588
- console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${(_m = this.config.databaseProvider) === null || _m === void 0 ? void 0 : _m.type} provider:`, error);
589
- throw error;
590
- }
591
- }
592
- else if (fs && path) {
593
- // Fallback to Node.js filesystem (only if fs/path are available)
594
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
595
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
596
- const domain = urlParts[0].replace(/\./g, '_');
597
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
598
- const filename = `${timestamp}_${((_o = response.config.method) === null || _o === void 0 ? void 0 : _o.toUpperCase()) || 'GET'}_${domain}_${urlPathPart}.json`;
599
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
600
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
601
- (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
602
- // Check request limit before saving (only if limit is set via env var)
603
- const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
604
- if (limitCheck.limitReached && limitCheck.error) {
605
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
606
- // Don't throw - just log and return to prevent app crash
607
- return;
608
- }
609
- const filePath = path.join(scenarioPath, filename);
610
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
611
- mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
612
- // Generate test if enabled
613
- if (((_p = this.config.generateTests) === null || _p === void 0 ? void 0 : _p.enabled) && this.testGenerator) {
614
- await this.generateTestForMock(mockData);
615
- }
616
- }
617
- else {
618
- console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
619
- }
620
- }
621
- finally {
622
- this.savingResponses.delete(requestKey);
623
- }
624
- }
625
- /**
626
- * Simple path resolution fallback for React Native (when path module is stubbed)
627
- */
628
- resolvePath(...parts) {
629
- if (path && typeof path.resolve === 'function') {
630
- return path.resolve(...parts);
631
- }
632
- // Fallback: simple string-based path resolution
633
- const cwd = typeof process !== 'undefined' && process.cwd ? process.cwd() : '.';
634
- const joined = parts
635
- .filter(p => p)
636
- .join('/')
637
- .replace(/\/+/g, '/')
638
- .replace(/^\.\//, '');
639
- if (joined.startsWith('/')) {
640
- return joined;
641
- }
642
- return `${cwd}/${joined}`.replace(/\/+/g, '/');
643
- }
644
- /**
645
- * Simple dirname fallback for React Native (when path module is stubbed)
646
- */
647
- dirname(filePath) {
648
- if (path && typeof path.dirname === 'function') {
649
- return path.dirname(filePath);
650
- }
651
- // Fallback: extract directory from path string
652
- const lastSlash = filePath.lastIndexOf('/');
653
- if (lastSlash <= 0) {
654
- return '.';
655
- }
656
- return filePath.substring(0, lastSlash);
657
- }
658
- /**
659
- * Generates test file for a mock
660
- */
661
- async generateTestForMock(mockData) {
662
- var _a, _b, _c, _d, _e;
663
- if (!this.testGenerator) {
664
- return;
665
- }
666
- // Check if fs is available for writing test files
667
- // In React Native runtime, fs is not available, but in Metro bundler (Node.js) it should be
668
- // Try to require it dynamically if not already available
669
- let testFs = fs;
670
- if (!testFs) {
671
- try {
672
- testFs = require('fs');
673
- }
674
- catch (e) {
675
- return;
676
- }
677
- }
678
- // Use the available fs - ensure it's defined and has required methods
679
- if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
680
- return;
681
- }
682
- const fsToUse = testFs;
683
- try {
684
- const options = {
685
- framework: ((_a = this.config.generateTests) === null || _a === void 0 ? void 0 : _a.framework) || 'jest',
686
- outputPath: ((_b = this.config.generateTests) === null || _b === void 0 ? void 0 : _b.outputPath) || './tests/generated',
687
- testPattern: ((_c = this.config.generateTests) === null || _c === void 0 ? void 0 : _c.testPattern) || '{endpoint}.test.ts',
688
- includeSetup: ((_d = this.config.generateTests) === null || _d === void 0 ? void 0 : _d.includeSetup) !== false,
689
- groupBy: ((_e = this.config.generateTests) === null || _e === void 0 ? void 0 : _e.groupBy) || 'file',
690
- httpClientType: 'fetch'
691
- };
692
- const testCode = this.testGenerator.generateTest(mockData, options);
693
- const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
694
- // Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
695
- // Use our fallback path resolution that works even when path module is stubbed
696
- const absoluteTestPath = this.resolvePath(testFilePath);
697
- // Ensure test directory exists
698
- const testDir = this.dirname(absoluteTestPath);
699
- if (!fsToUse.existsSync(testDir)) {
700
- fsToUse.mkdirSync(testDir, { recursive: true });
701
- }
702
- // Check if test file already exists
703
- if (fsToUse.existsSync(absoluteTestPath)) {
704
- // Extract test info to check if test already exists
705
- const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
706
- const testName = this.generateTestNameFromInfo(testInfo);
707
- // Check if test already exists
708
- const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
709
- if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
710
- return;
711
- }
712
- // Extract test code without imports and describe wrapper
713
- const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
714
- if (testMatch) {
715
- // Append test to existing describe block
716
- const newTest = testMatch[0];
717
- const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
718
- fsToUse.writeFileSync(absoluteTestPath, updatedContent);
719
- }
720
- }
721
- else {
722
- // Create new test file
723
- fsToUse.writeFileSync(absoluteTestPath, testCode);
724
- }
725
- }
726
- catch (error) {
727
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error generating test:', error);
728
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error stack:', error === null || error === void 0 ? void 0 : error.stack);
729
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error message:', error === null || error === void 0 ? void 0 : error.message);
730
- // Don't throw - test generation failure shouldn't break mock saving
731
- }
732
- }
733
- /**
734
- * Helper to generate test name from test info
735
- */
736
- generateTestNameFromInfo(testInfo) {
737
- const method = testInfo.method.toUpperCase();
738
- const endpoint = testInfo.endpoint;
739
- if (testInfo.isGraphQL && testInfo.graphQLQuery) {
740
- const operationMatch = testInfo.graphQLQuery.match(/(?:query|mutation|subscription)\s+(\w+)/);
741
- if (operationMatch) {
742
- return `should execute ${operationMatch[1]} query`;
743
- }
744
- return 'should execute GraphQL query';
745
- }
746
- return `should ${method} ${endpoint}`;
747
- }
748
- anonymizeHeaders(headers) {
749
- const defaultHeadersToAnonymize = [
750
- 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
751
- 'x-auth-token', 'x-access-token', 'bearer'
752
- ];
753
- const headersToAnonymize = this.config.anonymizeHeaders !== undefined
754
- ? this.config.anonymizeHeaders
755
- : defaultHeadersToAnonymize;
756
- if (headersToAnonymize.length === 0) {
757
- return headers;
758
- }
759
- const anonymized = { ...headers };
760
- const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
761
- Object.keys(anonymized).forEach(key => {
762
- if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
763
- anonymized[key] = '***';
764
- }
765
- });
766
- return anonymized;
767
- }
768
- anonymizeQueryParams(params) {
769
- const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
770
- const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
771
- ? this.config.anonymizeQueryParams
772
- : defaultParamsToAnonymize;
773
- if (paramsToAnonymize.length === 0) {
774
- return params;
775
- }
776
- const anonymized = { ...params };
777
- const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
778
- Object.keys(anonymized).forEach(key => {
779
- if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
780
- anonymized[key] = '***';
781
- }
782
- });
783
- return anonymized;
784
- }
785
- getHTTPClient() {
786
- return this.httpClient;
787
- }
788
- async reloadMockData(syncFromProject = true) {
789
- // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
790
- // For HybridProvider, this will also sync files from project folder to device
791
- if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
792
- if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
793
- // Pass syncFromProject flag if provider supports it (HybridProvider)
794
- await this.databaseProvider.reload(syncFromProject);
795
- }
796
- else {
797
- await this.databaseProvider.reload();
798
- }
799
- }
800
- else {
801
- // Fallback: try to load mock data if method exists
802
- if (typeof this.loadMockData === 'function') {
803
- this.loadMockData();
804
- }
805
- }
806
- }
807
- clearStaleCacheEntries() {
808
- return 0; // No cache in fetch implementation
809
- }
810
- async clearAllMocks() {
811
- if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
812
- await this.databaseProvider.clearAll();
813
- }
814
- else {
815
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
816
- }
817
- }
818
- }
819
- function setupMockifyer(config) {
820
- var _a;
821
- // Initialize logger with config level (default to 'info' if not specified)
822
- (0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
823
- // Set environment variables for Metro middleware to read test generation config
824
- // This allows Metro middleware (which runs in Node.js) to generate tests
825
- // when Hybrid Provider saves mocks via Metro endpoint
826
- if ((_a = config.generateTests) === null || _a === void 0 ? void 0 : _a.enabled) {
827
- process.env.MOCKIFYER_GENERATE_TESTS = 'true';
828
- if (config.generateTests.framework) {
829
- process.env.MOCKIFYER_TEST_FRAMEWORK = config.generateTests.framework;
830
- }
831
- if (config.generateTests.outputPath) {
832
- process.env.MOCKIFYER_TEST_OUTPUT_PATH = config.generateTests.outputPath;
833
- }
834
- if (config.generateTests.testPattern) {
835
- process.env.MOCKIFYER_TEST_PATTERN = config.generateTests.testPattern;
836
- }
837
- if (config.generateTests.includeSetup === false) {
838
- process.env.MOCKIFYER_TEST_INCLUDE_SETUP = 'false';
839
- }
840
- if (config.generateTests.groupBy) {
841
- process.env.MOCKIFYER_TEST_GROUP_BY = config.generateTests.groupBy;
842
- }
843
- if (config.generateTests.uniqueTestsPerEndpoint) {
844
- process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT = 'true';
845
- }
846
- }
847
- (0, mockifyer_core_1.initializeDateManipulation)(config);
848
- (0, mockifyer_core_1.initializeScenario)(config);
849
- const mockifyer = new MockifyerClass(config);
850
- const httpClient = mockifyer.getHTTPClient();
851
- // Always store original fetch (even if not patching global)
852
- let originalFetch;
853
- if (global.__mockifyer_original_fetch) {
854
- originalFetch = global.__mockifyer_original_fetch;
855
- }
856
- else {
857
- originalFetch = global.fetch;
858
- global.__mockifyer_original_fetch = originalFetch;
859
- }
860
- const fetchClient = httpClient;
861
- if (fetchClient && typeof fetchClient.performRequest === 'function') {
862
- fetchClient._originalFetch = originalFetch;
863
- }
864
- // Patch global fetch if useGlobalFetch is true
865
- if (config.useGlobalFetch) {
866
- const mockifyerInstance = mockifyer;
867
- const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
868
- global.fetch = async function (input, init) {
869
- var _a;
870
- const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
871
- const method = (init === null || init === void 0 ? void 0 : init.method) || 'GET';
872
- const headers = (init === null || init === void 0 ? void 0 : init.headers) || {};
873
- const body = init === null || init === void 0 ? void 0 : init.body;
874
- // Skip Mockifyer sync endpoints and Resend API to prevent infinite loops
875
- if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync') || url.includes('api.resend.com')) {
876
- return await originalFetchForPatched(input, init);
877
- }
878
- const simpleRequestKey = `${method}:${url}`;
879
- const isProcessing = (_a = mockifyerInstance.processingRequests) === null || _a === void 0 ? void 0 : _a.has(simpleRequestKey);
880
- if (isProcessing) {
881
- return await originalFetchForPatched(input, init);
882
- }
883
- let params = undefined;
884
- let baseUrl = url;
885
- try {
886
- const urlObj = new URL(url);
887
- if (urlObj.search) {
888
- params = {};
889
- urlObj.searchParams.forEach((value, key) => {
890
- params[key] = value;
891
- });
892
- urlObj.search = '';
893
- baseUrl = urlObj.toString();
894
- }
895
- }
896
- catch (error) {
897
- // URL parsing failed, use URL as-is
898
- }
899
- let headersObj = {};
900
- if (headers instanceof Headers) {
901
- headers.forEach((value, key) => {
902
- headersObj[key] = value;
903
- });
904
- }
905
- else if (Array.isArray(headers)) {
906
- headers.forEach(([key, value]) => {
907
- headersObj[key] = value;
908
- });
909
- }
910
- else {
911
- headersObj = headers;
912
- }
913
- try {
914
- const requestConfig = {
915
- url: baseUrl,
916
- method: method,
917
- headers: headersObj,
918
- params: params,
919
- data: body ? (typeof body === 'string' ? (body.startsWith('{') || body.startsWith('[') ? JSON.parse(body) : body) : body) : undefined
920
- };
921
- const response = await httpClient.request(requestConfig);
922
- const responseHeaders = new Headers();
923
- // Copy all headers from response, ensuring x-mockifyer header is included if present
924
- if (response.headers) {
925
- Object.entries(response.headers).forEach(([key, value]) => {
926
- if (value !== undefined && value !== null) {
927
- responseHeaders.set(key, String(value));
928
- }
929
- });
930
- }
931
- const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
932
- return new Response(responseBody, {
933
- status: response.status,
934
- statusText: response.statusText || '',
935
- headers: responseHeaders
936
- });
937
- }
938
- catch (error) {
939
- if (error.response) {
940
- const responseHeaders = new Headers();
941
- Object.entries(error.response.headers || {}).forEach(([key, value]) => {
942
- responseHeaders.set(key, String(value));
943
- });
944
- const errorBody = typeof error.response.data === 'string'
945
- ? error.response.data
946
- : JSON.stringify(error.response.data);
947
- return new Response(errorBody, {
948
- status: error.response.status,
949
- statusText: error.response.statusText || '',
950
- headers: responseHeaders
951
- });
952
- }
953
- throw error;
954
- }
955
- };
956
- }
957
- const extendedClient = httpClient;
958
- extendedClient.reloadMockData = async () => await mockifyer.reloadMockData();
959
- extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
960
- extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
961
- return extendedClient;
962
- }
963
- // Re-export types from core
964
- __exportStar(require("@sgedda/mockifyer-core"), exports);
965
- // Export React Native helpers
966
- __exportStar(require("./react-native"), exports);