@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/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
|
|
2
2
|
export interface MockifyerInstance extends HTTPClient {
|
|
3
|
-
reloadMockData: () => Promise<void>;
|
|
3
|
+
reloadMockData: (syncFromProject?: boolean) => Promise<void>;
|
|
4
4
|
clearStaleCacheEntries: () => number;
|
|
5
5
|
clearAllMocks: () => Promise<void>;
|
|
6
6
|
}
|
package/dist/index.js
CHANGED
|
@@ -31,11 +31,14 @@ catch (e) {
|
|
|
31
31
|
}
|
|
32
32
|
// Import from core package
|
|
33
33
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
34
|
+
const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
34
35
|
const fetch_client_1 = require("./clients/fetch-client");
|
|
35
36
|
class MockifyerClass {
|
|
36
37
|
constructor(config) {
|
|
37
38
|
this.processingRequests = new Set();
|
|
38
39
|
this.savingResponses = new Set();
|
|
40
|
+
/** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
|
|
41
|
+
this.databaseProviderInitPromise = Promise.resolve();
|
|
39
42
|
this.currentSessionId = null;
|
|
40
43
|
this.sessionStartTime = 0;
|
|
41
44
|
this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
@@ -50,7 +53,7 @@ class MockifyerClass {
|
|
|
50
53
|
}
|
|
51
54
|
// Validate and normalize conflicting settings
|
|
52
55
|
if (config.recordMode && config.failOnMissingMock) {
|
|
53
|
-
|
|
56
|
+
mockifyer_core_2.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
|
|
54
57
|
'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
|
|
55
58
|
'Setting failOnMissingMock to false.');
|
|
56
59
|
config.failOnMissingMock = false;
|
|
@@ -59,7 +62,7 @@ class MockifyerClass {
|
|
|
59
62
|
if (config.similarMatchIgnoreAllQueryParams &&
|
|
60
63
|
config.similarMatchRequiredParams &&
|
|
61
64
|
config.similarMatchRequiredParams.length > 0) {
|
|
62
|
-
|
|
65
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
|
|
63
66
|
'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
|
|
64
67
|
'similarMatchRequiredParams will be ignored.');
|
|
65
68
|
// Clear similarMatchRequiredParams to avoid confusion
|
|
@@ -80,33 +83,17 @@ class MockifyerClass {
|
|
|
80
83
|
// Store config BEFORE any modifications
|
|
81
84
|
this.config = { ...config }; // Create a copy to avoid mutations
|
|
82
85
|
// Initialize test generator if test generation is enabled
|
|
83
|
-
console.log('[Mockifyer-Fetch] HÖHÖHÖ 🔧 Constructor - Full config received:', JSON.stringify({
|
|
84
|
-
generateTests: config.generateTests,
|
|
85
|
-
recordMode: config.recordMode,
|
|
86
|
-
mockDataPath: config.mockDataPath,
|
|
87
|
-
databaseProvider: config.databaseProvider?.type
|
|
88
|
-
}, null, 2));
|
|
89
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - generateTests config:', JSON.stringify(config.generateTests, null, 2));
|
|
90
|
-
console.log('[Mockifyer-Fetch] 🔧 Constructor - config.generateTests?.enabled:', config.generateTests?.enabled);
|
|
91
86
|
if (config.generateTests?.enabled) {
|
|
92
|
-
console.log('[Mockifyer-Fetch] ✅ Initializing test generator...');
|
|
93
87
|
this.testGenerator = new mockifyer_core_1.TestGenerator();
|
|
94
|
-
console.log('[Mockifyer-Fetch] ✅ Test generator initialized:', !!this.testGenerator);
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled in config');
|
|
98
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config.generateTests:', config.generateTests);
|
|
99
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - typeof config.generateTests:', typeof config.generateTests);
|
|
100
|
-
console.log('[Mockifyer-Fetch] ⚠️ Debug - config keys:', Object.keys(config));
|
|
101
88
|
}
|
|
102
89
|
// Initialize database provider if specified
|
|
103
90
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
104
91
|
this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, config.databaseProvider);
|
|
105
92
|
const initResult = this.databaseProvider.initialize();
|
|
106
|
-
// Handle async initialization (expo-filesystem
|
|
93
|
+
// Handle async initialization (expo-filesystem / hybrid providers)
|
|
107
94
|
if (initResult instanceof Promise) {
|
|
108
|
-
initResult.catch((error) => {
|
|
109
|
-
|
|
95
|
+
this.databaseProviderInitPromise = initResult.catch((error) => {
|
|
96
|
+
mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
|
|
110
97
|
});
|
|
111
98
|
}
|
|
112
99
|
}
|
|
@@ -201,24 +188,14 @@ class MockifyerClass {
|
|
|
201
188
|
return undefined;
|
|
202
189
|
}
|
|
203
190
|
const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
|
|
204
|
-
console.log('[Mockifyer-Fetch] 📁 Mock data path:', {
|
|
205
|
-
original: this.config.mockDataPath,
|
|
206
|
-
resolved: resolvedMockDataPath,
|
|
207
|
-
exists: fs.existsSync(resolvedMockDataPath)
|
|
208
|
-
});
|
|
209
191
|
if (!fs.existsSync(resolvedMockDataPath)) {
|
|
210
192
|
console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
|
|
211
193
|
return undefined;
|
|
212
194
|
}
|
|
213
195
|
const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath);
|
|
214
196
|
const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
|
|
215
|
-
console.log('[Mockifyer-Fetch] 📁 Scenario path:', {
|
|
216
|
-
scenario: currentScenario,
|
|
217
|
-
path: scenarioPath,
|
|
218
|
-
exists: fs.existsSync(scenarioPath)
|
|
219
|
-
});
|
|
220
197
|
if (!fs.existsSync(scenarioPath)) {
|
|
221
|
-
|
|
198
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
222
199
|
return undefined;
|
|
223
200
|
}
|
|
224
201
|
const files = fs.readdirSync(scenarioPath)
|
|
@@ -226,13 +203,6 @@ class MockifyerClass {
|
|
|
226
203
|
const requestKey = this.generateRequestKey(request);
|
|
227
204
|
let exactMatch;
|
|
228
205
|
let similarMatch;
|
|
229
|
-
console.log('[Mockifyer-Fetch] 🔍 Searching for mock:', {
|
|
230
|
-
requestKey,
|
|
231
|
-
useSimilarMatch: this.config.useSimilarMatch,
|
|
232
|
-
similarMatchIgnoreAllQueryParams: this.config.similarMatchIgnoreAllQueryParams,
|
|
233
|
-
filesCount: files.length,
|
|
234
|
-
files: files.slice(0, 5) // Show first 5 files for debugging
|
|
235
|
-
});
|
|
236
206
|
for (const file of files) {
|
|
237
207
|
try {
|
|
238
208
|
const filePath = path.join(scenarioPath, file);
|
|
@@ -243,7 +213,6 @@ class MockifyerClass {
|
|
|
243
213
|
}
|
|
244
214
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
245
215
|
if (mockKey === requestKey) {
|
|
246
|
-
console.log('[Mockifyer-Fetch] ✅ Exact match found:', file);
|
|
247
216
|
exactMatch = { mockData, filename: file, filePath };
|
|
248
217
|
break;
|
|
249
218
|
}
|
|
@@ -289,22 +258,11 @@ class MockifyerClass {
|
|
|
289
258
|
}
|
|
290
259
|
}
|
|
291
260
|
const pathnameMatch = exactPathnameMatch || patternMatch;
|
|
292
|
-
|
|
293
|
-
file,
|
|
294
|
-
requestPathname,
|
|
295
|
-
mockPathname,
|
|
296
|
-
requestMethod: (request.method || 'GET').toUpperCase(),
|
|
297
|
-
mockMethod: (mockData.request.method || 'GET').toUpperCase(),
|
|
298
|
-
exactPathnameMatch,
|
|
299
|
-
patternMatch,
|
|
300
|
-
pathnameMatch,
|
|
301
|
-
methodMatch
|
|
302
|
-
});
|
|
261
|
+
// Check similar match
|
|
303
262
|
if (pathnameMatch && methodMatch) {
|
|
304
263
|
// If ignoreAllQueryParams is set, skip query param checking entirely
|
|
305
264
|
if (this.config.similarMatchIgnoreAllQueryParams) {
|
|
306
265
|
// Ignore all query params, match on path and method only
|
|
307
|
-
console.log('[Mockifyer-Fetch] ✅ Similar match found (ignoring query params):', file);
|
|
308
266
|
}
|
|
309
267
|
else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
|
|
310
268
|
// Check if required parameters match (if configured)
|
|
@@ -331,7 +289,7 @@ class MockifyerClass {
|
|
|
331
289
|
}
|
|
332
290
|
}
|
|
333
291
|
catch (error) {
|
|
334
|
-
|
|
292
|
+
mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
|
|
335
293
|
}
|
|
336
294
|
}
|
|
337
295
|
return exactMatch || similarMatch;
|
|
@@ -376,24 +334,11 @@ class MockifyerClass {
|
|
|
376
334
|
// Store request start time for duration calculation
|
|
377
335
|
config.__mockifyer_startTime = Date.now();
|
|
378
336
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
379
|
-
if
|
|
380
|
-
console.log('[Mockifyer-Fetch] ⚠️ No mock found for request:', {
|
|
381
|
-
method: request.method,
|
|
382
|
-
url: request.url,
|
|
383
|
-
queryParams: request.queryParams,
|
|
384
|
-
requestKey: requestKey,
|
|
385
|
-
mockDataPath: this.config.mockDataPath,
|
|
386
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
else {
|
|
390
|
-
console.log('[Mockifyer-Fetch] ✅ Mock found:', {
|
|
391
|
-
filename: cachedMock.filename,
|
|
392
|
-
url: request.url
|
|
393
|
-
});
|
|
394
|
-
}
|
|
337
|
+
// Return cached mock if found
|
|
395
338
|
if (cachedMock) {
|
|
396
339
|
const { mockData, filename, filePath } = cachedMock;
|
|
340
|
+
mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
341
|
+
(filePath ? ` (${filePath})` : ''));
|
|
397
342
|
const responseHeaders = {
|
|
398
343
|
...mockData.response.headers,
|
|
399
344
|
'x-mockifyer': 'true',
|
|
@@ -512,34 +457,22 @@ class MockifyerClass {
|
|
|
512
457
|
if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
|
|
513
458
|
responseDataStr.includes('/mockifyer-clear') ||
|
|
514
459
|
responseDataStr.includes('/mockifyer-sync'))) {
|
|
515
|
-
console.log('[Mockifyer-Fetch] ⚠️ Bypassing Mockifyer - sync endpoint in response data');
|
|
516
460
|
return response;
|
|
517
461
|
}
|
|
518
462
|
}
|
|
519
463
|
catch (e) {
|
|
520
464
|
// Ignore errors - continue processing
|
|
521
|
-
|
|
465
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
|
|
522
466
|
}
|
|
523
467
|
const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
|
|
524
468
|
const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
|
|
525
469
|
if (isMocked || isLimitReached) {
|
|
526
|
-
console.log('[Mockifyer-Fetch] Response is mocked, skipping save' + (isLimitReached ? ' (limit reached)' : ''));
|
|
527
470
|
return response;
|
|
528
471
|
}
|
|
529
472
|
// Only save if recordMode is enabled
|
|
530
473
|
if (this.config.recordMode) {
|
|
531
|
-
console.log('[Mockifyer-Fetch] ✅ recordMode enabled, saving response');
|
|
532
|
-
console.log('[Mockifyer-Fetch] Response URL:', response.config?.url);
|
|
533
|
-
console.log('[Mockifyer-Fetch] Response method:', response.config?.method);
|
|
534
|
-
console.log('[Mockifyer-Fetch] Response status:', response.status);
|
|
535
|
-
console.log('[Mockifyer-Fetch] Response config.data:', response.config?.data);
|
|
536
|
-
console.log('[Mockifyer-Fetch] Response config exists:', !!response.config);
|
|
537
474
|
await this.saveResponse(response);
|
|
538
475
|
}
|
|
539
|
-
else {
|
|
540
|
-
console.log('[Mockifyer-Fetch] ⚠️ recordMode disabled, not saving response');
|
|
541
|
-
console.log('[Mockifyer-Fetch] Current config.recordMode:', this.config.recordMode);
|
|
542
|
-
}
|
|
543
476
|
return response;
|
|
544
477
|
}, async (error) => {
|
|
545
478
|
const requestKey = error.config?.__mockifyer_requestKey;
|
|
@@ -550,32 +483,12 @@ class MockifyerClass {
|
|
|
550
483
|
});
|
|
551
484
|
}
|
|
552
485
|
async saveResponse(response) {
|
|
553
|
-
console.log('[Mockifyer-Fetch] 💾 saveResponse called');
|
|
554
|
-
console.log('[Mockifyer-Fetch] 💾 Config at saveResponse:', {
|
|
555
|
-
generateTestsEnabled: this.config.generateTests?.enabled,
|
|
556
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
557
|
-
recordMode: this.config.recordMode,
|
|
558
|
-
hasDatabaseProvider: !!this.databaseProvider
|
|
559
|
-
});
|
|
560
|
-
console.log('[Mockifyer-Fetch] saveResponse - response.config:', response.config ? {
|
|
561
|
-
url: response.config.url,
|
|
562
|
-
method: response.config.method,
|
|
563
|
-
hasData: !!response.config.data,
|
|
564
|
-
dataType: typeof response.config.data
|
|
565
|
-
} : 'NO CONFIG');
|
|
566
486
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
567
487
|
if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
|
|
568
|
-
console.log('[Mockifyer-Fetch] ⚠️ saveResponse: BLOCKING - bypass flag set');
|
|
569
488
|
return;
|
|
570
489
|
}
|
|
571
|
-
// CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
|
|
572
|
-
// Check multiple ways to get the URL in case response.config is undefined
|
|
573
490
|
const url = response.config?.url || response.request?.responseURL || response.url || '';
|
|
574
|
-
if (url && (url.
|
|
575
|
-
url.includes('/mockifyer-clear') ||
|
|
576
|
-
url.includes('/mockifyer-sync') ||
|
|
577
|
-
url.includes('api.resend.com'))) {
|
|
578
|
-
console.log('[Mockifyer-Fetch] ⚠️ Skipping save - Resend API request:', url);
|
|
491
|
+
if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
|
|
579
492
|
return;
|
|
580
493
|
}
|
|
581
494
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
@@ -606,7 +519,7 @@ class MockifyerClass {
|
|
|
606
519
|
}
|
|
607
520
|
catch (e) {
|
|
608
521
|
// Ignore JSON stringify errors
|
|
609
|
-
|
|
522
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
|
|
610
523
|
}
|
|
611
524
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
612
525
|
const rawParams = response.config.params || {};
|
|
@@ -656,39 +569,15 @@ class MockifyerClass {
|
|
|
656
569
|
duration,
|
|
657
570
|
sessionId: this.currentSessionId
|
|
658
571
|
};
|
|
659
|
-
console.log('[Mockifyer-Fetch] Saving mock data:', {
|
|
660
|
-
method: mockData.request.method,
|
|
661
|
-
url: mockData.request.url,
|
|
662
|
-
hasRequestData: !!mockData.request.data,
|
|
663
|
-
responseStatus: mockData.response.status,
|
|
664
|
-
provider: this.config.databaseProvider?.type || 'filesystem'
|
|
665
|
-
});
|
|
666
572
|
// Use database provider if available, otherwise fallback to filesystem
|
|
667
573
|
if (this.databaseProvider) {
|
|
668
574
|
try {
|
|
669
|
-
console.log('[Mockifyer-Fetch] 💾 Saving mock via database provider...');
|
|
670
575
|
await this.databaseProvider.save(mockData);
|
|
671
|
-
console.log('[Mockifyer-Fetch] ✅ Successfully saved mock using provider');
|
|
672
576
|
// Generate test if enabled (try to write test files even with database provider)
|
|
673
|
-
//
|
|
674
|
-
console.log('[Mockifyer-Fetch] 🔍 Checking test generation config...');
|
|
675
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests:', JSON.stringify(this.config.generateTests, null, 2));
|
|
676
|
-
console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests?.enabled:', this.config.generateTests?.enabled);
|
|
577
|
+
// Generate test if enabled
|
|
677
578
|
if (this.config.generateTests?.enabled) {
|
|
678
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generation enabled, attempting to generate test...');
|
|
679
|
-
console.log('[Mockifyer-Fetch] 🔧 Test generator available:', !!this.testGenerator);
|
|
680
|
-
console.log('[Mockifyer-Fetch] 🔧 fs available:', !!fs);
|
|
681
|
-
console.log('[Mockifyer-Fetch] 🔧 path available:', !!path);
|
|
682
579
|
await this.generateTestForMock(mockData);
|
|
683
580
|
}
|
|
684
|
-
else {
|
|
685
|
-
console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled - skipping');
|
|
686
|
-
console.log('[Mockifyer-Fetch] ⚠️ Config check:', {
|
|
687
|
-
hasGenerateTests: !!this.config.generateTests,
|
|
688
|
-
enabled: this.config.generateTests?.enabled,
|
|
689
|
-
fullConfig: JSON.stringify(this.config.generateTests)
|
|
690
|
-
});
|
|
691
|
-
}
|
|
692
581
|
}
|
|
693
582
|
catch (error) {
|
|
694
583
|
console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
|
|
@@ -714,7 +603,7 @@ class MockifyerClass {
|
|
|
714
603
|
}
|
|
715
604
|
const filePath = path.join(scenarioPath, filename);
|
|
716
605
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
717
|
-
|
|
606
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
718
607
|
// Generate test if enabled
|
|
719
608
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
720
609
|
await this.generateTestForMock(mockData);
|
|
@@ -775,20 +664,13 @@ class MockifyerClass {
|
|
|
775
664
|
if (!testFs) {
|
|
776
665
|
try {
|
|
777
666
|
testFs = require('fs');
|
|
778
|
-
console.log('[Mockifyer] ✅ Found fs module for test generation');
|
|
779
667
|
}
|
|
780
668
|
catch (e) {
|
|
781
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs not available');
|
|
782
|
-
console.log('[Mockifyer] 💡 Tip: Test generation requires Node.js fs module.');
|
|
783
|
-
console.log('[Mockifyer] 💡 In React Native, tests are generated in Metro bundler (Node.js environment).');
|
|
784
669
|
return;
|
|
785
670
|
}
|
|
786
671
|
}
|
|
787
672
|
// Use the available fs - ensure it's defined and has required methods
|
|
788
673
|
if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
|
|
789
|
-
console.log('[Mockifyer] ⚠️ Test generation skipped: fs module missing required methods');
|
|
790
|
-
console.log('[Mockifyer] 💡 fs.writeFileSync:', typeof testFs?.writeFileSync);
|
|
791
|
-
console.log('[Mockifyer] 💡 fs.mkdirSync:', typeof testFs?.mkdirSync);
|
|
792
674
|
return;
|
|
793
675
|
}
|
|
794
676
|
const fsToUse = testFs;
|
|
@@ -801,31 +683,24 @@ class MockifyerClass {
|
|
|
801
683
|
groupBy: this.config.generateTests?.groupBy || 'file',
|
|
802
684
|
httpClientType: 'fetch'
|
|
803
685
|
};
|
|
804
|
-
console.log('[Mockifyer] 📝 Test generation options:', JSON.stringify(options, null, 2));
|
|
805
686
|
const testCode = this.testGenerator.generateTest(mockData, options);
|
|
806
687
|
const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
|
|
807
|
-
console.log('[Mockifyer] 📝 Generated test file path:', testFilePath);
|
|
808
688
|
// Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
|
|
809
689
|
// Use our fallback path resolution that works even when path module is stubbed
|
|
810
690
|
const absoluteTestPath = this.resolvePath(testFilePath);
|
|
811
|
-
console.log('[Mockifyer] 📝 Final absolute test path:', absoluteTestPath);
|
|
812
691
|
// Ensure test directory exists
|
|
813
692
|
const testDir = this.dirname(absoluteTestPath);
|
|
814
|
-
console.log('[Mockifyer] 📝 Test directory:', testDir);
|
|
815
693
|
if (!fsToUse.existsSync(testDir)) {
|
|
816
|
-
console.log('[Mockifyer] 📝 Creating test directory:', testDir);
|
|
817
694
|
fsToUse.mkdirSync(testDir, { recursive: true });
|
|
818
695
|
}
|
|
819
696
|
// Check if test file already exists
|
|
820
697
|
if (fsToUse.existsSync(absoluteTestPath)) {
|
|
821
|
-
console.log('[Mockifyer] 📝 Test file already exists, checking if test needs to be appended...');
|
|
822
698
|
// Extract test info to check if test already exists
|
|
823
699
|
const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
|
|
824
700
|
const testName = this.generateTestNameFromInfo(testInfo);
|
|
825
701
|
// Check if test already exists
|
|
826
702
|
const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
|
|
827
703
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
828
|
-
console.log(`[Mockifyer] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
829
704
|
return;
|
|
830
705
|
}
|
|
831
706
|
// Extract test code without imports and describe wrapper
|
|
@@ -835,21 +710,17 @@ class MockifyerClass {
|
|
|
835
710
|
const newTest = testMatch[0];
|
|
836
711
|
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
837
712
|
fsToUse.writeFileSync(absoluteTestPath, updatedContent);
|
|
838
|
-
console.log(`[Mockifyer] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
839
713
|
}
|
|
840
714
|
}
|
|
841
715
|
else {
|
|
842
716
|
// Create new test file
|
|
843
|
-
console.log('[Mockifyer] 📝 Creating new test file...');
|
|
844
717
|
fsToUse.writeFileSync(absoluteTestPath, testCode);
|
|
845
|
-
console.log(`[Mockifyer] ✅ Generated test: ${absoluteTestPath}`);
|
|
846
|
-
console.log(`[Mockifyer] ✅ Test file size: ${fsToUse.statSync(absoluteTestPath).size} bytes`);
|
|
847
718
|
}
|
|
848
719
|
}
|
|
849
720
|
catch (error) {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
721
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error generating test:', error);
|
|
722
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
|
|
723
|
+
mockifyer_core_2.logger.error('[Mockifyer] ❌ Error message:', error?.message);
|
|
853
724
|
// Don't throw - test generation failure shouldn't break mock saving
|
|
854
725
|
}
|
|
855
726
|
}
|
|
@@ -909,6 +780,7 @@ class MockifyerClass {
|
|
|
909
780
|
return this.httpClient;
|
|
910
781
|
}
|
|
911
782
|
async reloadMockData(syncFromProject = true) {
|
|
783
|
+
await this.databaseProviderInitPromise;
|
|
912
784
|
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
913
785
|
// For HybridProvider, this will also sync files from project folder to device
|
|
914
786
|
if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
|
|
@@ -935,17 +807,13 @@ class MockifyerClass {
|
|
|
935
807
|
await this.databaseProvider.clearAll();
|
|
936
808
|
}
|
|
937
809
|
else {
|
|
938
|
-
|
|
810
|
+
mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
|
|
939
811
|
}
|
|
940
812
|
}
|
|
941
813
|
}
|
|
942
814
|
function setupMockifyer(config) {
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
recordMode: config.recordMode,
|
|
946
|
-
mockDataPath: config.mockDataPath,
|
|
947
|
-
databaseProvider: config.databaseProvider?.type
|
|
948
|
-
}, null, 2));
|
|
815
|
+
// Initialize logger with config level (default to 'info' if not specified)
|
|
816
|
+
(0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
|
|
949
817
|
// Set environment variables for Metro middleware to read test generation config
|
|
950
818
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
951
819
|
// when Hybrid Provider saves mocks via Metro endpoint
|
|
@@ -972,10 +840,6 @@ function setupMockifyer(config) {
|
|
|
972
840
|
}
|
|
973
841
|
(0, mockifyer_core_1.initializeDateManipulation)(config);
|
|
974
842
|
(0, mockifyer_core_1.initializeScenario)(config);
|
|
975
|
-
console.log('[Mockifyer-Fetch] 🚀 After initializeScenario - config:', JSON.stringify({
|
|
976
|
-
generateTests: config.generateTests,
|
|
977
|
-
recordMode: config.recordMode
|
|
978
|
-
}, null, 2));
|
|
979
843
|
const mockifyer = new MockifyerClass(config);
|
|
980
844
|
const httpClient = mockifyer.getHTTPClient();
|
|
981
845
|
// Always store original fetch (even if not patching global)
|
|
@@ -1056,17 +920,6 @@ function setupMockifyer(config) {
|
|
|
1056
920
|
responseHeaders.set(key, String(value));
|
|
1057
921
|
}
|
|
1058
922
|
});
|
|
1059
|
-
// Debug: Verify x-mockifyer header is present
|
|
1060
|
-
if (response.headers['x-mockifyer']) {
|
|
1061
|
-
console.log('[Mockifyer-Fetch] ✅ x-mockifyer header found in response:', response.headers['x-mockifyer']);
|
|
1062
|
-
}
|
|
1063
|
-
else {
|
|
1064
|
-
console.warn('[Mockifyer-Fetch] ⚠️ x-mockifyer header NOT found in response.headers');
|
|
1065
|
-
console.warn('[Mockifyer-Fetch] Available headers:', Object.keys(response.headers));
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
else {
|
|
1069
|
-
console.warn('[Mockifyer-Fetch] ⚠️ response.headers is undefined/null');
|
|
1070
923
|
}
|
|
1071
924
|
const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
|
|
1072
925
|
return new Response(responseBody, {
|
|
@@ -1095,7 +948,7 @@ function setupMockifyer(config) {
|
|
|
1095
948
|
};
|
|
1096
949
|
}
|
|
1097
950
|
const extendedClient = httpClient;
|
|
1098
|
-
extendedClient.reloadMockData = async () => await mockifyer.reloadMockData();
|
|
951
|
+
extendedClient.reloadMockData = async (syncFromProject) => await mockifyer.reloadMockData(syncFromProject);
|
|
1099
952
|
extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
|
|
1100
953
|
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
1101
954
|
return extendedClient;
|
package/dist/metro-config.d.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* This helper configures Metro to stub Node.js built-in modules that aren't
|
|
5
5
|
* available in React Native, allowing Mockifyer to bundle successfully.
|
|
6
|
+
* Optionally sets up sync middleware for Hybrid Provider.
|
|
6
7
|
*
|
|
7
|
-
* @example
|
|
8
|
+
* @example Basic usage (fs stubbing only):
|
|
8
9
|
* ```javascript
|
|
9
10
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
10
11
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -12,7 +13,38 @@
|
|
|
12
13
|
* const config = getDefaultConfig(__dirname);
|
|
13
14
|
* module.exports = configureMetroForMockifyer(config);
|
|
14
15
|
* ```
|
|
16
|
+
*
|
|
17
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
18
|
+
* ```javascript
|
|
19
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
20
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
21
|
+
*
|
|
22
|
+
* const config = getDefaultConfig(__dirname);
|
|
23
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
24
|
+
* syncMiddleware: {
|
|
25
|
+
* projectRoot: __dirname,
|
|
26
|
+
* mockDataPath: './mock-data',
|
|
27
|
+
* },
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
32
|
+
* ```javascript
|
|
33
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
34
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
35
|
+
*
|
|
36
|
+
* const config = getDefaultConfig(__dirname);
|
|
37
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
38
|
+
* autoSync: {
|
|
39
|
+
* enabled: true,
|
|
40
|
+
* intervalMs: 5000,
|
|
41
|
+
* projectRoot: __dirname,
|
|
42
|
+
* mockDataPath: './mock-data',
|
|
43
|
+
* },
|
|
44
|
+
* });
|
|
45
|
+
* ```
|
|
15
46
|
*/
|
|
47
|
+
import type { MetroSyncMiddlewareOptions } from './metro-sync-middleware';
|
|
16
48
|
export interface MetroConfig {
|
|
17
49
|
resolver?: {
|
|
18
50
|
resolveRequest?: (context: any, moduleName: string, platform: string | null) => {
|
|
@@ -27,18 +59,37 @@ export interface MetroConfig {
|
|
|
27
59
|
server?: any;
|
|
28
60
|
[key: string]: any;
|
|
29
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Options for configuring Metro for Mockifyer
|
|
64
|
+
*/
|
|
65
|
+
export interface ConfigureMetroOptions {
|
|
66
|
+
/** Sync middleware options - if provided, sets up Hybrid Provider sync */
|
|
67
|
+
syncMiddleware?: MetroSyncMiddlewareOptions;
|
|
68
|
+
/** Auto-sync options - Required when using ExpoFileSystem Provider to sync files from device to project folder for code search. Not needed with Hybrid Provider (uses instant HTTP sync). */
|
|
69
|
+
autoSync?: {
|
|
70
|
+
/** Enable auto-sync (default: false). Set to true if using ExpoFileSystem Provider and want files in project folder for code search */
|
|
71
|
+
enabled?: boolean;
|
|
72
|
+
/** Sync interval in milliseconds (default: 5000) */
|
|
73
|
+
intervalMs?: number;
|
|
74
|
+
/** Project root directory (default: process.cwd()) */
|
|
75
|
+
projectRoot?: string;
|
|
76
|
+
/** Mock data path (default: 'mock-data') */
|
|
77
|
+
mockDataPath?: string;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
30
80
|
/**
|
|
31
81
|
* Configure Metro bundler for Mockifyer
|
|
32
82
|
*
|
|
33
|
-
* This function
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
83
|
+
* This function:
|
|
84
|
+
* 1. Adds resolver configuration to stub Node.js built-in modules (fs, path, assert, util)
|
|
85
|
+
* 2. Optionally sets up sync middleware for Hybrid Provider (if syncMiddleware options provided)
|
|
86
|
+
* 3. Optionally sets up auto-sync polling (if autoSync options provided - needed for ExpoFileSystem Provider, not needed with Hybrid Provider)
|
|
37
87
|
*
|
|
38
88
|
* @param config - Existing Metro config (e.g., from getDefaultConfig)
|
|
39
|
-
* @
|
|
89
|
+
* @param options - Optional configuration including sync middleware setup
|
|
90
|
+
* @returns Metro config with Mockifyer configuration merged in
|
|
40
91
|
*
|
|
41
|
-
* @example
|
|
92
|
+
* @example Basic usage (fs stubbing only):
|
|
42
93
|
* ```javascript
|
|
43
94
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
44
95
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -46,5 +97,35 @@ export interface MetroConfig {
|
|
|
46
97
|
* const config = getDefaultConfig(__dirname);
|
|
47
98
|
* module.exports = configureMetroForMockifyer(config);
|
|
48
99
|
* ```
|
|
100
|
+
*
|
|
101
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
102
|
+
* ```javascript
|
|
103
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
104
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
105
|
+
*
|
|
106
|
+
* const config = getDefaultConfig(__dirname);
|
|
107
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
108
|
+
* syncMiddleware: {
|
|
109
|
+
* projectRoot: __dirname,
|
|
110
|
+
* mockDataPath: './mock-data',
|
|
111
|
+
* },
|
|
112
|
+
* });
|
|
113
|
+
* ```
|
|
114
|
+
*
|
|
115
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
116
|
+
* ```javascript
|
|
117
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
118
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
119
|
+
*
|
|
120
|
+
* const config = getDefaultConfig(__dirname);
|
|
121
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
122
|
+
* autoSync: {
|
|
123
|
+
* enabled: true,
|
|
124
|
+
* intervalMs: 5000,
|
|
125
|
+
* projectRoot: __dirname,
|
|
126
|
+
* mockDataPath: './mock-data',
|
|
127
|
+
* },
|
|
128
|
+
* });
|
|
129
|
+
* ```
|
|
49
130
|
*/
|
|
50
|
-
export declare function configureMetroForMockifyer(config: MetroConfig): MetroConfig;
|
|
131
|
+
export declare function configureMetroForMockifyer(config: MetroConfig, options?: ConfigureMetroOptions): MetroConfig;
|