@sgedda/mockifyer-fetch 1.7.0 → 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/dist/index.d.ts +1 -1
- package/dist/index.js +27 -174
- package/dist/metro-config.d.ts +89 -8
- package/dist/metro-config.js +126 -8
- package/dist/metro-sync-middleware.d.ts +4 -2
- package/dist/metro-sync-middleware.js +292 -36
- package/dist/react-native.d.ts +1 -1
- package/dist/react-native.js +16 -7
- package/package.json +8 -3
- package/src/index.ts +33 -179
- package/src/metro-config.ts +153 -9
- package/src/metro-sync-middleware.ts +319 -41
- package/src/react-native.ts +19 -8
package/dist/react-native.js
CHANGED
|
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
9
9
|
exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
|
|
10
10
|
const index_1 = require("./index");
|
|
11
11
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
12
|
+
const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
12
13
|
// Lazy load bundled data (only used in production builds)
|
|
13
14
|
let bundledMockData = null;
|
|
14
15
|
/**
|
|
@@ -40,7 +41,7 @@ async function loadBundledMockData(bundledDataPath) {
|
|
|
40
41
|
return data;
|
|
41
42
|
}
|
|
42
43
|
catch (error) {
|
|
43
|
-
|
|
44
|
+
mockifyer_core_2.logger.warn('[Mockifyer] Could not load bundled mock data:', error);
|
|
44
45
|
return [];
|
|
45
46
|
}
|
|
46
47
|
}
|
|
@@ -67,7 +68,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
67
68
|
// Check if Mockifyer is enabled
|
|
68
69
|
const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
|
|
69
70
|
if (!isEnabled) {
|
|
70
|
-
|
|
71
|
+
mockifyer_core_2.logger.info('[Mockifyer] Disabled');
|
|
71
72
|
return null;
|
|
72
73
|
}
|
|
73
74
|
if (isDev === true) {
|
|
@@ -103,10 +104,18 @@ async function setupMockifyerForReactNative(options) {
|
|
|
103
104
|
useGlobalFetch: true,
|
|
104
105
|
...config,
|
|
105
106
|
});
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
108
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
|
|
109
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Project→device sync: /mockifyer-sync-to-device-manifest + per-file fetch (on reloadMockData); Metro port ${metroPort}`);
|
|
108
110
|
if (recordMode) {
|
|
109
|
-
|
|
111
|
+
mockifyer_core_2.logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
112
|
+
}
|
|
113
|
+
// Pull repo mock-data onto device once Metro + provider are ready (HybridProvider.reload)
|
|
114
|
+
try {
|
|
115
|
+
await instance.reloadMockData(true);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
mockifyer_core_2.logger.warn('[Mockifyer] Initial project→device sync failed (Metro running with built mockifyer-fetch?):', error);
|
|
110
119
|
}
|
|
111
120
|
return instance;
|
|
112
121
|
}
|
|
@@ -118,7 +127,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
118
127
|
// Load bundled mock data
|
|
119
128
|
const mockDataArray = await loadBundledMockData(bundledDataPath);
|
|
120
129
|
if (mockDataArray.length === 0) {
|
|
121
|
-
|
|
130
|
+
mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
|
|
122
131
|
return null;
|
|
123
132
|
}
|
|
124
133
|
// Pre-load all mocks into memory
|
|
@@ -134,7 +143,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
134
143
|
useGlobalFetch: true,
|
|
135
144
|
...config,
|
|
136
145
|
});
|
|
137
|
-
|
|
146
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
|
|
138
147
|
return instance;
|
|
139
148
|
}
|
|
140
149
|
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.1",
|
|
4
4
|
"description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"react-native": "dist/react-native.js",
|
|
7
8
|
"exports": {
|
|
8
9
|
".": {
|
|
10
|
+
"react-native": "./dist/react-native.js",
|
|
9
11
|
"types": "./dist/index.d.ts",
|
|
10
12
|
"default": "./dist/index.js"
|
|
11
13
|
},
|
|
@@ -44,7 +46,11 @@
|
|
|
44
46
|
"author": "sgedda",
|
|
45
47
|
"license": "MIT",
|
|
46
48
|
"dependencies": {
|
|
47
|
-
"@sgedda/mockifyer-core": "^1.
|
|
49
|
+
"@sgedda/mockifyer-core": "^1.8.1"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^20.11.24",
|
|
53
|
+
"typescript": "^5.3.3"
|
|
48
54
|
},
|
|
49
55
|
"publishConfig": {
|
|
50
56
|
"access": "public"
|
|
@@ -54,4 +60,3 @@
|
|
|
54
60
|
"url": "git+https://github.com/sgedda/mockifyer.git"
|
|
55
61
|
}
|
|
56
62
|
}
|
|
57
|
-
|
package/src/index.ts
CHANGED
|
@@ -32,8 +32,10 @@ import {
|
|
|
32
32
|
initializeScenario,
|
|
33
33
|
TestGenerator,
|
|
34
34
|
TestGenerationOptions,
|
|
35
|
-
checkRequestLimit
|
|
35
|
+
checkRequestLimit,
|
|
36
|
+
shouldExcludeUrl
|
|
36
37
|
} from '@sgedda/mockifyer-core';
|
|
38
|
+
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
37
39
|
|
|
38
40
|
import { FetchHTTPClient } from './clients/fetch-client';
|
|
39
41
|
|
|
@@ -43,6 +45,8 @@ class MockifyerClass {
|
|
|
43
45
|
private processingRequests: Set<string> = new Set();
|
|
44
46
|
private savingResponses: Set<string> = new Set();
|
|
45
47
|
private databaseProvider?: DatabaseProvider;
|
|
48
|
+
/** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
|
|
49
|
+
private databaseProviderInitPromise: Promise<void> = Promise.resolve();
|
|
46
50
|
private currentSessionId: string | null = null;
|
|
47
51
|
private sessionStartTime: number = 0;
|
|
48
52
|
private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
@@ -63,7 +67,7 @@ class MockifyerClass {
|
|
|
63
67
|
|
|
64
68
|
// Validate and normalize conflicting settings
|
|
65
69
|
if (config.recordMode && config.failOnMissingMock) {
|
|
66
|
-
|
|
70
|
+
logger.warn(
|
|
67
71
|
'[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
|
|
68
72
|
'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
|
|
69
73
|
'Setting failOnMissingMock to false.'
|
|
@@ -75,7 +79,7 @@ class MockifyerClass {
|
|
|
75
79
|
if (config.similarMatchIgnoreAllQueryParams &&
|
|
76
80
|
config.similarMatchRequiredParams &&
|
|
77
81
|
config.similarMatchRequiredParams.length > 0) {
|
|
78
|
-
|
|
82
|
+
logger.warn(
|
|
79
83
|
'[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
|
|
80
84
|
'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
|
|
81
85
|
'similarMatchRequiredParams will be ignored.'
|
|
@@ -102,34 +106,18 @@ class MockifyerClass {
|
|
|
102
106
|
this.config = { ...config }; // Create a copy to avoid mutations
|
|
103
107
|
|
|
104
108
|
// Initialize test generator if test generation is enabled
|
|
105
|
-
console.log('[Mockifyer-Fetch] HÖHÖHÖ 🔧 Constructor - Full config received:', JSON.stringify({
|
|
106
|
-
generateTests: config.generateTests,
|
|
107
|
-
recordMode: config.recordMode,
|
|
108
|
-
mockDataPath: config.mockDataPath,
|
|
109
|
-
databaseProvider: config.databaseProvider?.type
|
|
110
|
-
}, null, 2));
|
|
111
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - generateTests config:', JSON.stringify(config.generateTests, null, 2));
|
|
112
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - config.generateTests?.enabled:', config.generateTests?.enabled);
|
|
113
|
-
|
|
114
109
|
if (config.generateTests?.enabled) {
|
|
115
|
-
console.log('[Mockifyer-Fetch] ✅ Initializing test generator...');
|
|
116
110
|
this.testGenerator = new TestGenerator();
|
|
117
|
-
console.log('[Mockifyer-Fetch] ✅ Test generator initialized:', !!this.testGenerator);
|
|
118
|
-
} else {
|
|
119
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled in config');
|
|
120
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config.generateTests:', config.generateTests);
|
|
121
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - typeof config.generateTests:', typeof config.generateTests);
|
|
122
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config keys:', Object.keys(config));
|
|
123
111
|
}
|
|
124
112
|
|
|
125
113
|
// Initialize database provider if specified
|
|
126
114
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
127
115
|
this.databaseProvider = createProvider(config.databaseProvider.type, config.databaseProvider);
|
|
128
116
|
const initResult = this.databaseProvider.initialize();
|
|
129
|
-
// Handle async initialization (expo-filesystem
|
|
117
|
+
// Handle async initialization (expo-filesystem / hybrid providers)
|
|
130
118
|
if (initResult instanceof Promise) {
|
|
131
|
-
initResult.catch((error) => {
|
|
132
|
-
|
|
119
|
+
this.databaseProviderInitPromise = initResult.catch((error) => {
|
|
120
|
+
logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
|
|
133
121
|
});
|
|
134
122
|
}
|
|
135
123
|
} else {
|
|
@@ -240,11 +228,6 @@ class MockifyerClass {
|
|
|
240
228
|
return undefined;
|
|
241
229
|
}
|
|
242
230
|
const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
|
|
243
|
-
console.log('[Mockifyer-Fetch] 📁 Mock data path:', {
|
|
244
|
-
original: this.config.mockDataPath,
|
|
245
|
-
resolved: resolvedMockDataPath,
|
|
246
|
-
exists: fs.existsSync(resolvedMockDataPath)
|
|
247
|
-
});
|
|
248
231
|
|
|
249
232
|
if (!fs.existsSync(resolvedMockDataPath)) {
|
|
250
233
|
console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
|
|
@@ -254,14 +237,8 @@ class MockifyerClass {
|
|
|
254
237
|
const currentScenario = getCurrentScenario(resolvedMockDataPath);
|
|
255
238
|
const scenarioPath = getScenarioFolderPath(resolvedMockDataPath, currentScenario);
|
|
256
239
|
|
|
257
|
-
console.log('[Mockifyer-Fetch] 📁 Scenario path:', {
|
|
258
|
-
scenario: currentScenario,
|
|
259
|
-
path: scenarioPath,
|
|
260
|
-
exists: fs.existsSync(scenarioPath)
|
|
261
|
-
});
|
|
262
|
-
|
|
263
240
|
if (!fs.existsSync(scenarioPath)) {
|
|
264
|
-
|
|
241
|
+
logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
265
242
|
return undefined;
|
|
266
243
|
}
|
|
267
244
|
|
|
@@ -272,14 +249,6 @@ class MockifyerClass {
|
|
|
272
249
|
let exactMatch: CachedMockData | undefined;
|
|
273
250
|
let similarMatch: CachedMockData | undefined;
|
|
274
251
|
|
|
275
|
-
console.log('[Mockifyer-Fetch] 🔍 Searching for mock:', {
|
|
276
|
-
requestKey,
|
|
277
|
-
useSimilarMatch: this.config.useSimilarMatch,
|
|
278
|
-
similarMatchIgnoreAllQueryParams: this.config.similarMatchIgnoreAllQueryParams,
|
|
279
|
-
filesCount: files.length,
|
|
280
|
-
files: files.slice(0, 5) // Show first 5 files for debugging
|
|
281
|
-
});
|
|
282
|
-
|
|
283
252
|
for (const file of files) {
|
|
284
253
|
try {
|
|
285
254
|
const filePath = path!.join(scenarioPath, file);
|
|
@@ -293,7 +262,6 @@ class MockifyerClass {
|
|
|
293
262
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
294
263
|
|
|
295
264
|
if (mockKey === requestKey) {
|
|
296
|
-
console.log('[Mockifyer-Fetch] ✅ Exact match found:', file);
|
|
297
265
|
exactMatch = { mockData, filename: file, filePath };
|
|
298
266
|
break;
|
|
299
267
|
}
|
|
@@ -346,24 +314,13 @@ class MockifyerClass {
|
|
|
346
314
|
|
|
347
315
|
const pathnameMatch = exactPathnameMatch || patternMatch;
|
|
348
316
|
|
|
349
|
-
|
|
350
|
-
file,
|
|
351
|
-
requestPathname,
|
|
352
|
-
mockPathname,
|
|
353
|
-
requestMethod: (request.method || 'GET').toUpperCase(),
|
|
354
|
-
mockMethod: (mockData.request.method || 'GET').toUpperCase(),
|
|
355
|
-
exactPathnameMatch,
|
|
356
|
-
patternMatch,
|
|
357
|
-
pathnameMatch,
|
|
358
|
-
methodMatch
|
|
359
|
-
});
|
|
317
|
+
// Check similar match
|
|
360
318
|
|
|
361
319
|
if (pathnameMatch && methodMatch) {
|
|
362
320
|
|
|
363
321
|
// If ignoreAllQueryParams is set, skip query param checking entirely
|
|
364
322
|
if (this.config.similarMatchIgnoreAllQueryParams) {
|
|
365
323
|
// Ignore all query params, match on path and method only
|
|
366
|
-
console.log('[Mockifyer-Fetch] ✅ Similar match found (ignoring query params):', file);
|
|
367
324
|
} else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
|
|
368
325
|
// Check if required parameters match (if configured)
|
|
369
326
|
const requestParams = request.queryParams || {};
|
|
@@ -390,7 +347,7 @@ class MockifyerClass {
|
|
|
390
347
|
}
|
|
391
348
|
}
|
|
392
349
|
} catch (error) {
|
|
393
|
-
|
|
350
|
+
logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
|
|
394
351
|
}
|
|
395
352
|
}
|
|
396
353
|
|
|
@@ -444,24 +401,14 @@ class MockifyerClass {
|
|
|
444
401
|
|
|
445
402
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
446
403
|
|
|
447
|
-
if
|
|
448
|
-
console.log('[Mockifyer-Fetch] ⚠️ No mock found for request:', {
|
|
449
|
-
method: request.method,
|
|
450
|
-
url: request.url,
|
|
451
|
-
queryParams: request.queryParams,
|
|
452
|
-
requestKey: requestKey,
|
|
453
|
-
mockDataPath: this.config.mockDataPath,
|
|
454
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
455
|
-
});
|
|
456
|
-
} else {
|
|
457
|
-
console.log('[Mockifyer-Fetch] ✅ Mock found:', {
|
|
458
|
-
filename: cachedMock.filename,
|
|
459
|
-
url: request.url
|
|
460
|
-
});
|
|
461
|
-
}
|
|
404
|
+
// Return cached mock if found
|
|
462
405
|
|
|
463
406
|
if (cachedMock) {
|
|
464
407
|
const { mockData, filename, filePath } = cachedMock;
|
|
408
|
+
logger.info(
|
|
409
|
+
`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
410
|
+
(filePath ? ` (${filePath})` : '')
|
|
411
|
+
);
|
|
465
412
|
const responseHeaders = {
|
|
466
413
|
...mockData.response.headers,
|
|
467
414
|
'x-mockifyer': 'true',
|
|
@@ -601,33 +548,22 @@ class MockifyerClass {
|
|
|
601
548
|
responseDataStr.includes('/mockifyer-save') ||
|
|
602
549
|
responseDataStr.includes('/mockifyer-clear') ||
|
|
603
550
|
responseDataStr.includes('/mockifyer-sync'))) {
|
|
604
|
-
console.log('[Mockifyer-Fetch] ⚠️ Bypassing Mockifyer - sync endpoint in response data');
|
|
605
551
|
return response;
|
|
606
552
|
}
|
|
607
553
|
} catch (e) {
|
|
608
554
|
// Ignore errors - continue processing
|
|
609
|
-
|
|
555
|
+
logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
|
|
610
556
|
}
|
|
611
557
|
|
|
612
558
|
const isMocked = response.headers && (response.headers as any)['x-mockifyer'] === 'true';
|
|
613
559
|
const isLimitReached = response.headers && (response.headers as any)['x-mockifyer-limit-reached'] === 'true';
|
|
614
560
|
if (isMocked || isLimitReached) {
|
|
615
|
-
console.log('[Mockifyer-Fetch] Response is mocked, skipping save' + (isLimitReached ? ' (limit reached)' : ''));
|
|
616
561
|
return response;
|
|
617
562
|
}
|
|
618
563
|
|
|
619
564
|
// Only save if recordMode is enabled
|
|
620
565
|
if (this.config.recordMode) {
|
|
621
|
-
console.log('[Mockifyer-Fetch] ✅ recordMode enabled, saving response');
|
|
622
|
-
console.log('[Mockifyer-Fetch] Response URL:', response.config?.url);
|
|
623
|
-
console.log('[Mockifyer-Fetch] Response method:', response.config?.method);
|
|
624
|
-
console.log('[Mockifyer-Fetch] Response status:', response.status);
|
|
625
|
-
console.log('[Mockifyer-Fetch] Response config.data:', response.config?.data);
|
|
626
|
-
console.log('[Mockifyer-Fetch] Response config exists:', !!response.config);
|
|
627
566
|
await this.saveResponse(response);
|
|
628
|
-
} else {
|
|
629
|
-
console.log('[Mockifyer-Fetch] ⚠️ recordMode disabled, not saving response');
|
|
630
|
-
console.log('[Mockifyer-Fetch] Current config.recordMode:', this.config.recordMode);
|
|
631
567
|
}
|
|
632
568
|
return response;
|
|
633
569
|
},
|
|
@@ -642,36 +578,13 @@ class MockifyerClass {
|
|
|
642
578
|
}
|
|
643
579
|
|
|
644
580
|
private async saveResponse(response: HTTPResponse): Promise<void> {
|
|
645
|
-
console.log('[Mockifyer-Fetch] 💾 saveResponse called');
|
|
646
|
-
console.log('[Mockifyer-Fetch] 💾 Config at saveResponse:', {
|
|
647
|
-
generateTestsEnabled: this.config.generateTests?.enabled,
|
|
648
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
649
|
-
recordMode: this.config.recordMode,
|
|
650
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
651
|
-
});
|
|
652
|
-
console.log('[Mockifyer-Fetch] saveResponse - response.config:', response.config ? {
|
|
653
|
-
url: response.config.url,
|
|
654
|
-
method: response.config.method,
|
|
655
|
-
hasData: !!response.config.data,
|
|
656
|
-
dataType: typeof response.config.data
|
|
657
|
-
} : 'NO CONFIG');
|
|
658
|
-
|
|
659
581
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
660
582
|
if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
|
|
661
|
-
console.log('[Mockifyer-Fetch] ⚠️ saveResponse: BLOCKING - bypass flag set');
|
|
662
583
|
return;
|
|
663
584
|
}
|
|
664
585
|
|
|
665
|
-
// CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
|
|
666
|
-
// Check multiple ways to get the URL in case response.config is undefined
|
|
667
586
|
const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
|
|
668
|
-
if (url && (
|
|
669
|
-
url.includes('/mockifyer-save') ||
|
|
670
|
-
url.includes('/mockifyer-clear') ||
|
|
671
|
-
url.includes('/mockifyer-sync') ||
|
|
672
|
-
url.includes('api.resend.com')
|
|
673
|
-
)) {
|
|
674
|
-
console.log('[Mockifyer-Fetch] ⚠️ Skipping save - Resend API request:', url);
|
|
587
|
+
if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
|
|
675
588
|
return;
|
|
676
589
|
}
|
|
677
590
|
|
|
@@ -703,7 +616,7 @@ class MockifyerClass {
|
|
|
703
616
|
}
|
|
704
617
|
} catch (e) {
|
|
705
618
|
// Ignore JSON stringify errors
|
|
706
|
-
|
|
619
|
+
logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
|
|
707
620
|
}
|
|
708
621
|
|
|
709
622
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
@@ -762,40 +675,16 @@ class MockifyerClass {
|
|
|
762
675
|
sessionId: this.currentSessionId
|
|
763
676
|
};
|
|
764
677
|
|
|
765
|
-
console.log('[Mockifyer-Fetch] Saving mock data:', {
|
|
766
|
-
method: mockData.request.method,
|
|
767
|
-
url: mockData.request.url,
|
|
768
|
-
hasRequestData: !!mockData.request.data,
|
|
769
|
-
responseStatus: mockData.response.status,
|
|
770
|
-
provider: this.config.databaseProvider?.type || 'filesystem'
|
|
771
|
-
});
|
|
772
678
|
|
|
773
679
|
// Use database provider if available, otherwise fallback to filesystem
|
|
774
680
|
if (this.databaseProvider) {
|
|
775
681
|
try {
|
|
776
|
-
console.log('[Mockifyer-Fetch] 💾 Saving mock via database provider...');
|
|
777
682
|
await this.databaseProvider.save(mockData);
|
|
778
|
-
console.log('[Mockifyer-Fetch] ✅ Successfully saved mock using provider');
|
|
779
683
|
|
|
780
684
|
// Generate test if enabled (try to write test files even with database provider)
|
|
781
|
-
//
|
|
782
|
-
console.log('[Mockifyer-Fetch] 🔍 Checking test generation config...');
|
|
783
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests:', JSON.stringify(this.config.generateTests, null, 2));
|
|
784
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests?.enabled:', this.config.generateTests?.enabled);
|
|
785
|
-
|
|
685
|
+
// Generate test if enabled
|
|
786
686
|
if (this.config.generateTests?.enabled) {
|
|
787
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generation enabled, attempting to generate test...');
|
|
788
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generator available:', !!this.testGenerator);
|
|
789
|
-
console.log('[Mockifyer-Fetch] 🔧 fs available:', !!fs);
|
|
790
|
-
console.log('[Mockifyer-Fetch] 🔧 path available:', !!path);
|
|
791
687
|
await this.generateTestForMock(mockData);
|
|
792
|
-
} else {
|
|
793
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled - skipping');
|
|
794
|
-
console.log('[Mockifyer-Fetch] ⚠️ Config check:', {
|
|
795
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
796
|
-
enabled: this.config.generateTests?.enabled,
|
|
797
|
-
fullConfig: JSON.stringify(this.config.generateTests)
|
|
798
|
-
});
|
|
799
688
|
}
|
|
800
689
|
} catch (error) {
|
|
801
690
|
console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
|
|
@@ -822,7 +711,7 @@ class MockifyerClass {
|
|
|
822
711
|
|
|
823
712
|
const filePath = path.join(scenarioPath, filename);
|
|
824
713
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
825
|
-
|
|
714
|
+
logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
826
715
|
|
|
827
716
|
// Generate test if enabled
|
|
828
717
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
@@ -888,20 +777,13 @@ class MockifyerClass {
|
|
|
888
777
|
if (!testFs) {
|
|
889
778
|
try {
|
|
890
779
|
testFs = require('fs');
|
|
891
|
-
console.log('[Mockifyer] ✅ Found fs module for test generation');
|
|
892
780
|
} catch (e) {
|
|
893
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs not available');
|
|
894
|
-
console.log('[Mockifyer] 💡 Tip: Test generation requires Node.js fs module.');
|
|
895
|
-
console.log('[Mockifyer] 💡 In React Native, tests are generated in Metro bundler (Node.js environment).');
|
|
896
781
|
return;
|
|
897
782
|
}
|
|
898
783
|
}
|
|
899
784
|
|
|
900
785
|
// Use the available fs - ensure it's defined and has required methods
|
|
901
786
|
if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
|
|
902
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs module missing required methods');
|
|
903
|
-
console.log('[Mockifyer] 💡 fs.writeFileSync:', typeof testFs?.writeFileSync);
|
|
904
|
-
console.log('[Mockifyer] 💡 fs.mkdirSync:', typeof testFs?.mkdirSync);
|
|
905
787
|
return;
|
|
906
788
|
}
|
|
907
789
|
|
|
@@ -917,30 +799,22 @@ class MockifyerClass {
|
|
|
917
799
|
httpClientType: 'fetch'
|
|
918
800
|
};
|
|
919
801
|
|
|
920
|
-
console.log('[Mockifyer] 📝 Test generation options:', JSON.stringify(options, null, 2));
|
|
921
|
-
|
|
922
802
|
const testCode = this.testGenerator.generateTest(mockData, options);
|
|
923
803
|
const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
|
|
924
804
|
|
|
925
|
-
console.log('[Mockifyer] 📝 Generated test file path:', testFilePath);
|
|
926
|
-
|
|
927
805
|
// Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
|
|
928
806
|
// Use our fallback path resolution that works even when path module is stubbed
|
|
929
807
|
const absoluteTestPath = this.resolvePath(testFilePath);
|
|
930
|
-
console.log('[Mockifyer] 📝 Final absolute test path:', absoluteTestPath);
|
|
931
808
|
|
|
932
809
|
// Ensure test directory exists
|
|
933
810
|
const testDir = this.dirname(absoluteTestPath);
|
|
934
|
-
console.log('[Mockifyer] 📝 Test directory:', testDir);
|
|
935
811
|
|
|
936
812
|
if (!fsToUse.existsSync(testDir)) {
|
|
937
|
-
console.log('[Mockifyer] 📝 Creating test directory:', testDir);
|
|
938
813
|
fsToUse.mkdirSync(testDir, { recursive: true });
|
|
939
814
|
}
|
|
940
815
|
|
|
941
816
|
// Check if test file already exists
|
|
942
817
|
if (fsToUse.existsSync(absoluteTestPath)) {
|
|
943
|
-
console.log('[Mockifyer] 📝 Test file already exists, checking if test needs to be appended...');
|
|
944
818
|
// Extract test info to check if test already exists
|
|
945
819
|
const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
|
|
946
820
|
const testName = this.generateTestNameFromInfo(testInfo);
|
|
@@ -948,7 +822,6 @@ class MockifyerClass {
|
|
|
948
822
|
// Check if test already exists
|
|
949
823
|
const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
|
|
950
824
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
951
|
-
console.log(`[Mockifyer] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
952
825
|
return;
|
|
953
826
|
}
|
|
954
827
|
|
|
@@ -962,19 +835,15 @@ class MockifyerClass {
|
|
|
962
835
|
`$1${newTest}\n$1$2`
|
|
963
836
|
);
|
|
964
837
|
fsToUse.writeFileSync(absoluteTestPath, updatedContent);
|
|
965
|
-
console.log(`[Mockifyer] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
966
838
|
}
|
|
967
839
|
} else {
|
|
968
840
|
// Create new test file
|
|
969
|
-
console.log('[Mockifyer] 📝 Creating new test file...');
|
|
970
841
|
fsToUse.writeFileSync(absoluteTestPath, testCode);
|
|
971
|
-
console.log(`[Mockifyer] ✅ Generated test: ${absoluteTestPath}`);
|
|
972
|
-
console.log(`[Mockifyer] ✅ Test file size: ${fsToUse.statSync(absoluteTestPath).size} bytes`);
|
|
973
842
|
}
|
|
974
843
|
} catch (error: any) {
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
844
|
+
logger.error('[Mockifyer] ❌ Error generating test:', error);
|
|
845
|
+
logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
|
|
846
|
+
logger.error('[Mockifyer] ❌ Error message:', error?.message);
|
|
978
847
|
// Don't throw - test generation failure shouldn't break mock saving
|
|
979
848
|
}
|
|
980
849
|
}
|
|
@@ -1051,6 +920,7 @@ class MockifyerClass {
|
|
|
1051
920
|
}
|
|
1052
921
|
|
|
1053
922
|
async reloadMockData(syncFromProject: boolean = true): Promise<void> {
|
|
923
|
+
await this.databaseProviderInitPromise;
|
|
1054
924
|
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
1055
925
|
// For HybridProvider, this will also sync files from project folder to device
|
|
1056
926
|
if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
|
|
@@ -1076,24 +946,20 @@ class MockifyerClass {
|
|
|
1076
946
|
if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
|
|
1077
947
|
await this.databaseProvider.clearAll();
|
|
1078
948
|
} else {
|
|
1079
|
-
|
|
949
|
+
logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
|
|
1080
950
|
}
|
|
1081
951
|
}
|
|
1082
952
|
}
|
|
1083
953
|
|
|
1084
954
|
export interface MockifyerInstance extends HTTPClient {
|
|
1085
|
-
reloadMockData: () => Promise<void>;
|
|
955
|
+
reloadMockData: (syncFromProject?: boolean) => Promise<void>;
|
|
1086
956
|
clearStaleCacheEntries: () => number;
|
|
1087
957
|
clearAllMocks: () => Promise<void>;
|
|
1088
958
|
}
|
|
1089
959
|
|
|
1090
960
|
export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
recordMode: config.recordMode,
|
|
1094
|
-
mockDataPath: config.mockDataPath,
|
|
1095
|
-
databaseProvider: config.databaseProvider?.type
|
|
1096
|
-
}, null, 2));
|
|
961
|
+
// Initialize logger with config level (default to 'info' if not specified)
|
|
962
|
+
setLogLevel(config.logging || 'info');
|
|
1097
963
|
|
|
1098
964
|
// Set environment variables for Metro middleware to read test generation config
|
|
1099
965
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
@@ -1123,10 +989,6 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1123
989
|
initializeDateManipulation(config);
|
|
1124
990
|
initializeScenario(config);
|
|
1125
991
|
|
|
1126
|
-
console.log('[Mockifyer-Fetch] 🚀 After initializeScenario - config:', JSON.stringify({
|
|
1127
|
-
generateTests: config.generateTests,
|
|
1128
|
-
recordMode: config.recordMode
|
|
1129
|
-
}, null, 2));
|
|
1130
992
|
|
|
1131
993
|
const mockifyer = new MockifyerClass(config);
|
|
1132
994
|
const httpClient = mockifyer.getHTTPClient();
|
|
@@ -1215,15 +1077,6 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1215
1077
|
responseHeaders.set(key, String(value));
|
|
1216
1078
|
}
|
|
1217
1079
|
});
|
|
1218
|
-
// Debug: Verify x-mockifyer header is present
|
|
1219
|
-
if (response.headers['x-mockifyer']) {
|
|
1220
|
-
console.log('[Mockifyer-Fetch] ✅ x-mockifyer header found in response:', response.headers['x-mockifyer']);
|
|
1221
|
-
} else {
|
|
1222
|
-
console.warn('[Mockifyer-Fetch] ⚠️ x-mockifyer header NOT found in response.headers');
|
|
1223
|
-
console.warn('[Mockifyer-Fetch] Available headers:', Object.keys(response.headers));
|
|
1224
|
-
}
|
|
1225
|
-
} else {
|
|
1226
|
-
console.warn('[Mockifyer-Fetch] ⚠️ response.headers is undefined/null');
|
|
1227
1080
|
}
|
|
1228
1081
|
|
|
1229
1082
|
const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
|
|
@@ -1256,7 +1109,8 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1256
1109
|
}
|
|
1257
1110
|
|
|
1258
1111
|
const extendedClient = httpClient as MockifyerInstance;
|
|
1259
|
-
extendedClient.reloadMockData = async () =>
|
|
1112
|
+
extendedClient.reloadMockData = async (syncFromProject?: boolean) =>
|
|
1113
|
+
await mockifyer.reloadMockData(syncFromProject);
|
|
1260
1114
|
extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
|
|
1261
1115
|
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
1262
1116
|
|