@sgedda/mockifyer-fetch 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  TestGenerationOptions,
35
35
  checkRequestLimit
36
36
  } from '@sgedda/mockifyer-core';
37
+ import { logger, setLogLevel } from '@sgedda/mockifyer-core';
37
38
 
38
39
  import { FetchHTTPClient } from './clients/fetch-client';
39
40
 
@@ -63,7 +64,7 @@ class MockifyerClass {
63
64
 
64
65
  // Validate and normalize conflicting settings
65
66
  if (config.recordMode && config.failOnMissingMock) {
66
- console.warn(
67
+ logger.warn(
67
68
  '[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
68
69
  'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
69
70
  'Setting failOnMissingMock to false.'
@@ -75,7 +76,7 @@ class MockifyerClass {
75
76
  if (config.similarMatchIgnoreAllQueryParams &&
76
77
  config.similarMatchRequiredParams &&
77
78
  config.similarMatchRequiredParams.length > 0) {
78
- console.warn(
79
+ logger.warn(
79
80
  '[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
80
81
  'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
81
82
  'similarMatchRequiredParams will be ignored.'
@@ -102,24 +103,8 @@ class MockifyerClass {
102
103
  this.config = { ...config }; // Create a copy to avoid mutations
103
104
 
104
105
  // 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
106
  if (config.generateTests?.enabled) {
115
- console.log('[Mockifyer-Fetch] ✅ Initializing test generator...');
116
107
  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
108
  }
124
109
 
125
110
  // Initialize database provider if specified
@@ -129,7 +114,7 @@ class MockifyerClass {
129
114
  // Handle async initialization (expo-filesystem provider has async initialize)
130
115
  if (initResult instanceof Promise) {
131
116
  initResult.catch((error) => {
132
- console.error('[Mockifyer-Fetch] Error initializing database provider:', error);
117
+ logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
133
118
  });
134
119
  }
135
120
  } else {
@@ -240,11 +225,6 @@ class MockifyerClass {
240
225
  return undefined;
241
226
  }
242
227
  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
228
 
249
229
  if (!fs.existsSync(resolvedMockDataPath)) {
250
230
  console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
@@ -254,14 +234,8 @@ class MockifyerClass {
254
234
  const currentScenario = getCurrentScenario(resolvedMockDataPath);
255
235
  const scenarioPath = getScenarioFolderPath(resolvedMockDataPath, currentScenario);
256
236
 
257
- console.log('[Mockifyer-Fetch] 📁 Scenario path:', {
258
- scenario: currentScenario,
259
- path: scenarioPath,
260
- exists: fs.existsSync(scenarioPath)
261
- });
262
-
263
237
  if (!fs.existsSync(scenarioPath)) {
264
- console.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
238
+ logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
265
239
  return undefined;
266
240
  }
267
241
 
@@ -272,14 +246,6 @@ class MockifyerClass {
272
246
  let exactMatch: CachedMockData | undefined;
273
247
  let similarMatch: CachedMockData | undefined;
274
248
 
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
249
  for (const file of files) {
284
250
  try {
285
251
  const filePath = path!.join(scenarioPath, file);
@@ -293,7 +259,6 @@ class MockifyerClass {
293
259
  const mockKey = this.generateRequestKey(mockData.request);
294
260
 
295
261
  if (mockKey === requestKey) {
296
- console.log('[Mockifyer-Fetch] ✅ Exact match found:', file);
297
262
  exactMatch = { mockData, filename: file, filePath };
298
263
  break;
299
264
  }
@@ -346,24 +311,13 @@ class MockifyerClass {
346
311
 
347
312
  const pathnameMatch = exactPathnameMatch || patternMatch;
348
313
 
349
- console.log('[Mockifyer-Fetch] 🔍 Checking similar match:', {
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
- });
314
+ // Check similar match
360
315
 
361
316
  if (pathnameMatch && methodMatch) {
362
317
 
363
318
  // If ignoreAllQueryParams is set, skip query param checking entirely
364
319
  if (this.config.similarMatchIgnoreAllQueryParams) {
365
320
  // Ignore all query params, match on path and method only
366
- console.log('[Mockifyer-Fetch] ✅ Similar match found (ignoring query params):', file);
367
321
  } else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
368
322
  // Check if required parameters match (if configured)
369
323
  const requestParams = request.queryParams || {};
@@ -390,7 +344,7 @@ class MockifyerClass {
390
344
  }
391
345
  }
392
346
  } catch (error) {
393
- console.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
347
+ logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
394
348
  }
395
349
  }
396
350
 
@@ -444,21 +398,7 @@ class MockifyerClass {
444
398
 
445
399
  const cachedMock = await this.findBestMatchingMock(request);
446
400
 
447
- if (!cachedMock) {
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
- }
401
+ // Return cached mock if found
462
402
 
463
403
  if (cachedMock) {
464
404
  const { mockData, filename, filePath } = cachedMock;
@@ -601,33 +541,22 @@ class MockifyerClass {
601
541
  responseDataStr.includes('/mockifyer-save') ||
602
542
  responseDataStr.includes('/mockifyer-clear') ||
603
543
  responseDataStr.includes('/mockifyer-sync'))) {
604
- console.log('[Mockifyer-Fetch] ⚠️ Bypassing Mockifyer - sync endpoint in response data');
605
544
  return response;
606
545
  }
607
546
  } catch (e) {
608
547
  // Ignore errors - continue processing
609
- console.warn('[Mockifyer-Fetch] Error checking response data:', e);
548
+ logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
610
549
  }
611
550
 
612
551
  const isMocked = response.headers && (response.headers as any)['x-mockifyer'] === 'true';
613
552
  const isLimitReached = response.headers && (response.headers as any)['x-mockifyer-limit-reached'] === 'true';
614
553
  if (isMocked || isLimitReached) {
615
- console.log('[Mockifyer-Fetch] Response is mocked, skipping save' + (isLimitReached ? ' (limit reached)' : ''));
616
554
  return response;
617
555
  }
618
556
 
619
557
  // Only save if recordMode is enabled
620
558
  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
559
  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
560
  }
632
561
  return response;
633
562
  },
@@ -642,23 +571,8 @@ class MockifyerClass {
642
571
  }
643
572
 
644
573
  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
574
  // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
660
575
  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
576
  return;
663
577
  }
664
578
 
@@ -671,7 +585,6 @@ class MockifyerClass {
671
585
  url.includes('/mockifyer-sync') ||
672
586
  url.includes('api.resend.com')
673
587
  )) {
674
- console.log('[Mockifyer-Fetch] ⚠️ Skipping save - Resend API request:', url);
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
- console.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
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
- // In React Native Metro bundler (Node.js), fs/path are available for writing test files
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
- console.log(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
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
- console.error('[Mockifyer] ❌ Error generating test:', error);
976
- console.error('[Mockifyer] ❌ Error stack:', error?.stack);
977
- console.error('[Mockifyer] ❌ Error message:', error?.message);
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
  }
@@ -1076,7 +945,7 @@ class MockifyerClass {
1076
945
  if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
1077
946
  await this.databaseProvider.clearAll();
1078
947
  } else {
1079
- console.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
948
+ logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
1080
949
  }
1081
950
  }
1082
951
  }
@@ -1088,12 +957,8 @@ export interface MockifyerInstance extends HTTPClient {
1088
957
  }
1089
958
 
1090
959
  export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1091
- console.log('[Mockifyer-Fetch] 🚀 setupMockifyer called with config:', JSON.stringify({
1092
- generateTests: config.generateTests,
1093
- recordMode: config.recordMode,
1094
- mockDataPath: config.mockDataPath,
1095
- databaseProvider: config.databaseProvider?.type
1096
- }, null, 2));
960
+ // Initialize logger with config level (default to 'info' if not specified)
961
+ setLogLevel(config.logging || 'info');
1097
962
 
1098
963
  // Set environment variables for Metro middleware to read test generation config
1099
964
  // This allows Metro middleware (which runs in Node.js) to generate tests
@@ -1123,10 +988,6 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1123
988
  initializeDateManipulation(config);
1124
989
  initializeScenario(config);
1125
990
 
1126
- console.log('[Mockifyer-Fetch] 🚀 After initializeScenario - config:', JSON.stringify({
1127
- generateTests: config.generateTests,
1128
- recordMode: config.recordMode
1129
- }, null, 2));
1130
991
 
1131
992
  const mockifyer = new MockifyerClass(config);
1132
993
  const httpClient = mockifyer.getHTTPClient();
@@ -1215,15 +1076,6 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1215
1076
  responseHeaders.set(key, String(value));
1216
1077
  }
1217
1078
  });
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
1079
  }
1228
1080
 
1229
1081
  const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
@@ -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,8 +13,41 @@
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
  */
16
47
 
48
+ import type { MetroSyncMiddlewareOptions } from './metro-sync-middleware';
49
+ import { logger } from '@sgedda/mockifyer-core';
50
+
17
51
  // Metro config types (simplified - Metro doesn't export types)
18
52
  export interface MetroConfig {
19
53
  resolver?: {
@@ -40,18 +74,38 @@ export interface MetroConfig {
40
74
  */
41
75
  const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'] as const;
42
76
 
77
+ /**
78
+ * Options for configuring Metro for Mockifyer
79
+ */
80
+ export interface ConfigureMetroOptions {
81
+ /** Sync middleware options - if provided, sets up Hybrid Provider sync */
82
+ syncMiddleware?: MetroSyncMiddlewareOptions;
83
+ /** 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). */
84
+ autoSync?: {
85
+ /** Enable auto-sync (default: false). Set to true if using ExpoFileSystem Provider and want files in project folder for code search */
86
+ enabled?: boolean;
87
+ /** Sync interval in milliseconds (default: 5000) */
88
+ intervalMs?: number;
89
+ /** Project root directory (default: process.cwd()) */
90
+ projectRoot?: string;
91
+ /** Mock data path (default: 'mock-data') */
92
+ mockDataPath?: string;
93
+ };
94
+ }
95
+
43
96
  /**
44
97
  * Configure Metro bundler for Mockifyer
45
98
  *
46
- * This function adds resolver configuration to stub Node.js built-in modules
47
- * that aren't available in React Native. The stubs are empty modules that
48
- * allow Metro to bundle successfully while the code gracefully handles
49
- * their absence at runtime.
99
+ * This function:
100
+ * 1. Adds resolver configuration to stub Node.js built-in modules (fs, path, assert, util)
101
+ * 2. Optionally sets up sync middleware for Hybrid Provider (if syncMiddleware options provided)
102
+ * 3. Optionally sets up auto-sync polling (if autoSync options provided - needed for ExpoFileSystem Provider, not needed with Hybrid Provider)
50
103
  *
51
104
  * @param config - Existing Metro config (e.g., from getDefaultConfig)
52
- * @returns Metro config with Mockifyer resolver configuration merged in
105
+ * @param options - Optional configuration including sync middleware setup
106
+ * @returns Metro config with Mockifyer configuration merged in
53
107
  *
54
- * @example
108
+ * @example Basic usage (fs stubbing only):
55
109
  * ```javascript
56
110
  * const { getDefaultConfig } = require('expo/metro-config');
57
111
  * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
@@ -59,8 +113,41 @@ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'] as const;
59
113
  * const config = getDefaultConfig(__dirname);
60
114
  * module.exports = configureMetroForMockifyer(config);
61
115
  * ```
116
+ *
117
+ * @example With sync middleware (for Hybrid Provider):
118
+ * ```javascript
119
+ * const { getDefaultConfig } = require('expo/metro-config');
120
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
121
+ *
122
+ * const config = getDefaultConfig(__dirname);
123
+ * module.exports = configureMetroForMockifyer(config, {
124
+ * syncMiddleware: {
125
+ * projectRoot: __dirname,
126
+ * mockDataPath: './mock-data',
127
+ * },
128
+ * });
129
+ * ```
130
+ *
131
+ * @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
132
+ * ```javascript
133
+ * const { getDefaultConfig } = require('expo/metro-config');
134
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
135
+ *
136
+ * const config = getDefaultConfig(__dirname);
137
+ * module.exports = configureMetroForMockifyer(config, {
138
+ * autoSync: {
139
+ * enabled: true,
140
+ * intervalMs: 5000,
141
+ * projectRoot: __dirname,
142
+ * mockDataPath: './mock-data',
143
+ * },
144
+ * });
145
+ * ```
62
146
  */
63
- export function configureMetroForMockifyer(config: MetroConfig): MetroConfig {
147
+ export function configureMetroForMockifyer(
148
+ config: MetroConfig,
149
+ options?: ConfigureMetroOptions
150
+ ): MetroConfig {
64
151
  // Get path to empty module stub
65
152
  // Resolve using the package export path, which points to metro-polyfills/empty-module.js
66
153
  let emptyModulePath: string;
@@ -103,6 +190,64 @@ export function configureMetroForMockifyer(config: MetroConfig): MetroConfig {
103
190
  return context.resolveRequest(context, moduleName, platform);
104
191
  };
105
192
 
193
+ // Set up sync middleware if options provided
194
+ if (options?.syncMiddleware) {
195
+ try {
196
+ const { createMockSyncMiddleware } = require('./metro-sync-middleware');
197
+ const syncMiddleware = createMockSyncMiddleware({
198
+ projectRoot: options.syncMiddleware.projectRoot || process.cwd(),
199
+ mockDataPath: options.syncMiddleware.mockDataPath || 'mock-data',
200
+ testGeneration: options.syncMiddleware.testGeneration,
201
+ });
202
+
203
+ // Add middleware to server config
204
+ // Expo Metro uses enhanceMiddleware, but also supports middleware array
205
+ config.server = config.server || {};
206
+
207
+ // Use enhanceMiddleware if available (Expo Metro standard)
208
+ // enhanceMiddleware receives existing middleware and returns new middleware
209
+ const existingEnhance = config.server.enhanceMiddleware;
210
+ config.server.enhanceMiddleware = (middleware: any) => {
211
+ // Return a middleware function that runs our syncMiddleware first,
212
+ // then calls the existing enhanced middleware
213
+ return (req: any, res: any, next: any) => {
214
+ // Try our middleware first (it calls next() if not handling the request)
215
+ syncMiddleware(req, res, (err?: any) => {
216
+ if (err) {
217
+ return next(err);
218
+ }
219
+ // If our middleware didn't handle it, call the existing middleware
220
+ if (!res.headersSent) {
221
+ return middleware(req, res, next);
222
+ }
223
+ });
224
+ };
225
+ };
226
+ } catch (e) {
227
+ logger.warn('[Metro] Could not set up Mockifyer sync middleware:', e);
228
+ }
229
+ }
230
+
231
+ // Set up auto-sync (polling-based sync from iOS Simulator to project folder) if options provided
232
+ // Required when using ExpoFileSystem Provider to sync files from device to project folder for code search
233
+ // Not needed with Hybrid Provider (uses instant HTTP sync via syncMiddleware)
234
+ if (options?.autoSync?.enabled) {
235
+ try {
236
+ const { startAutoSync } = require('./metro-sync-middleware');
237
+ const intervalMs = options.autoSync.intervalMs || 5000;
238
+ const projectRoot = options.autoSync.projectRoot || process.cwd();
239
+ const mockDataPath = options.autoSync.mockDataPath || 'mock-data';
240
+
241
+ startAutoSync(intervalMs, {
242
+ projectRoot,
243
+ mockDataPath,
244
+ });
245
+ console.log(`[Metro] ✅ Auto-sync enabled: polling every ${intervalMs}ms`);
246
+ } catch (e) {
247
+ logger.warn('[Metro] Could not set up Mockifyer auto-sync:', e);
248
+ }
249
+ }
250
+
106
251
  // Merge config with new resolver
107
252
  return {
108
253
  ...config,
@@ -112,4 +257,3 @@ export function configureMetroForMockifyer(config: MetroConfig): MetroConfig {
112
257
  },
113
258
  };
114
259
  }
115
-