@sgedda/mockifyer-fetch 1.7.2 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/METRO_CONFIG.md CHANGED
@@ -6,8 +6,6 @@ Mockifyer requires Metro bundler configuration to stub Node.js built-in modules
6
6
 
7
7
  Use the provided helper function to configure Metro automatically:
8
8
 
9
- ### Basic Setup (FS Stubbing Only)
10
-
11
9
  ```javascript
12
10
  // metro.config.js
13
11
  const { getDefaultConfig } = require('expo/metro-config');
@@ -17,32 +15,6 @@ const config = getDefaultConfig(__dirname);
17
15
  module.exports = configureMetroForMockifyer(config);
18
16
  ```
19
17
 
20
- ### With Sync Middleware (For Hybrid Provider)
21
-
22
- If you're using the Hybrid Provider to save files to both device and project folder:
23
-
24
- ```javascript
25
- // metro.config.js
26
- const { getDefaultConfig } = require('expo/metro-config');
27
- const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
28
-
29
- const config = getDefaultConfig(__dirname);
30
-
31
- // One function call handles BOTH:
32
- // 1. FS/path stubbing (for bundling)
33
- // 2. Sync middleware (for Hybrid Provider to save files to project folder)
34
- module.exports = configureMetroForMockifyer(config, {
35
- syncMiddleware: {
36
- projectRoot: __dirname,
37
- mockDataPath: './mock-data',
38
- },
39
- });
40
- ```
41
-
42
- This automatically sets up:
43
- - ✅ Node.js module stubbing (`fs`, `path`, `assert`, `util`)
44
- - ✅ Sync middleware for Hybrid Provider (saves files to project folder)
45
-
46
18
  ## Manual Setup
47
19
 
48
20
  If you prefer manual configuration or need more control:
@@ -80,20 +52,8 @@ module.exports = config;
80
52
 
81
53
  ## Why This Is Needed
82
54
 
83
- ### FS/Path Stubbing
84
-
85
55
  Mockifyer packages use Node.js built-in modules (`fs`, `path`) for filesystem operations. These modules aren't available in React Native, so Metro needs to stub them during bundling. The stubs are empty modules that allow bundling to succeed while the code gracefully handles their absence at runtime.
86
56
 
87
- **Note:** With conditional imports (added in recent versions), FS stubbing is optional - the code handles missing modules gracefully. However, Metro config is still recommended to prevent bundling errors.
88
-
89
- ### Sync Middleware (Optional)
90
-
91
- If you're using the **Hybrid Provider**, you need sync middleware to save files to your project folder. The Hybrid Provider saves mocks to both:
92
- 1. Device filesystem (via Expo FileSystem)
93
- 2. Project folder (via Metro HTTP endpoint)
94
-
95
- The sync middleware handles the Metro endpoint (`/mockifyer-save`) that writes files to your project folder.
96
-
97
57
  ## Modules Stubbed
98
58
 
99
59
  - `fs` - Used by FilesystemProvider (not used in React Native - use ExpoFileSystemProvider instead)
@@ -135,23 +95,3 @@ config.resolver.extraNodeModules = { /* ... */ };
135
95
  module.exports = configureMetroForMockifyer(config);
136
96
  ```
137
97
 
138
- ### Files Not Appearing in Project Folder (Hybrid Provider)
139
-
140
- If you're using Hybrid Provider but files aren't appearing in your project folder:
141
-
142
- 1. **Check Metro is running**: Hybrid Provider requires Metro to be running
143
- 2. **Check sync middleware is configured**: Make sure you passed `syncMiddleware` options to `configureMetroForMockifyer`
144
- 3. **Check Metro port**: Ensure Metro port matches (default: 8081)
145
- 4. **Check logs**: Look for `[HybridProvider]` messages in your app logs
146
-
147
- Example with sync middleware:
148
-
149
- ```javascript
150
- module.exports = configureMetroForMockifyer(config, {
151
- syncMiddleware: {
152
- projectRoot: __dirname,
153
- mockDataPath: './mock-data',
154
- },
155
- });
156
- ```
157
-
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
@@ -37,6 +37,8 @@ class MockifyerClass {
37
37
  constructor(config) {
38
38
  this.processingRequests = new Set();
39
39
  this.savingResponses = new Set();
40
+ /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
41
+ this.databaseProviderInitPromise = Promise.resolve();
40
42
  this.currentSessionId = null;
41
43
  this.sessionStartTime = 0;
42
44
  this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
@@ -88,9 +90,9 @@ class MockifyerClass {
88
90
  if (config.databaseProvider && config.databaseProvider.type) {
89
91
  this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, config.databaseProvider);
90
92
  const initResult = this.databaseProvider.initialize();
91
- // Handle async initialization (expo-filesystem provider has async initialize)
93
+ // Handle async initialization (expo-filesystem / hybrid providers)
92
94
  if (initResult instanceof Promise) {
93
- initResult.catch((error) => {
95
+ this.databaseProviderInitPromise = initResult.catch((error) => {
94
96
  mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
95
97
  });
96
98
  }
@@ -335,6 +337,8 @@ class MockifyerClass {
335
337
  // Return cached mock if found
336
338
  if (cachedMock) {
337
339
  const { mockData, filename, filePath } = cachedMock;
340
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
341
+ (filePath ? ` (${filePath})` : ''));
338
342
  const responseHeaders = {
339
343
  ...mockData.response.headers,
340
344
  'x-mockifyer': 'true',
@@ -483,13 +487,8 @@ class MockifyerClass {
483
487
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
484
488
  return;
485
489
  }
486
- // CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
487
- // Check multiple ways to get the URL in case response.config is undefined
488
490
  const url = response.config?.url || response.request?.responseURL || response.url || '';
489
- if (url && (url.includes('/mockifyer-save') ||
490
- url.includes('/mockifyer-clear') ||
491
- url.includes('/mockifyer-sync') ||
492
- url.includes('api.resend.com'))) {
491
+ if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
493
492
  return;
494
493
  }
495
494
  // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
@@ -781,6 +780,7 @@ class MockifyerClass {
781
780
  return this.httpClient;
782
781
  }
783
782
  async reloadMockData(syncFromProject = true) {
783
+ await this.databaseProviderInitPromise;
784
784
  // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
785
785
  // For HybridProvider, this will also sync files from project folder to device
786
786
  if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
@@ -948,7 +948,7 @@ function setupMockifyer(config) {
948
948
  };
949
949
  }
950
950
  const extendedClient = httpClient;
951
- extendedClient.reloadMockData = async () => await mockifyer.reloadMockData();
951
+ extendedClient.reloadMockData = async (syncFromProject) => await mockifyer.reloadMockData(syncFromProject);
952
952
  extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
953
953
  extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
954
954
  return extendedClient;
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Metro middleware for mock file synchronization
3
3
  *
4
- * Provides two sync mechanisms:
4
+ * Provides sync mechanisms:
5
5
  * 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
6
- * 2. GET /mockifyer-sync - Legacy polling-based sync endpoint (for manual sync)
6
+ * 2. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
7
+ * 3. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
8
+ * 4. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
7
9
  *
8
10
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
9
11
  * Legacy polling-based sync is still available for backward compatibility.
@@ -2,9 +2,11 @@
2
2
  /**
3
3
  * Metro middleware for mock file synchronization
4
4
  *
5
- * Provides two sync mechanisms:
5
+ * Provides sync mechanisms:
6
6
  * 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
7
- * 2. GET /mockifyer-sync - Legacy polling-based sync endpoint (for manual sync)
7
+ * 2. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
8
+ * 3. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
9
+ * 4. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
8
10
  *
9
11
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
10
12
  * Legacy polling-based sync is still available for backward compatibility.
@@ -54,6 +56,55 @@ const path = __importStar(require("path"));
54
56
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
55
57
  const DEFAULT_SCENARIO = 'default';
56
58
  let autoSyncInterval = null;
59
+ function getMockFilePathLocal(mockData, dateStr) {
60
+ const url = mockData.request.url || '';
61
+ const method = (mockData.request.method || 'GET').toUpperCase();
62
+ let host = 'unknown';
63
+ let pathSegments = [];
64
+ try {
65
+ const parsed = new URL(url);
66
+ host = parsed.hostname;
67
+ pathSegments = parsed.pathname.split('/').filter(Boolean);
68
+ }
69
+ catch {
70
+ return { dir: 'unknown', filename: `${method}_${dateStr}.json` };
71
+ }
72
+ const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, '_');
73
+ const graphqlIdx = pathSegments.lastIndexOf('graphql');
74
+ const restIdx = pathSegments.indexOf('rest');
75
+ let type;
76
+ let remainingSegments;
77
+ if (graphqlIdx >= 0) {
78
+ type = 'graphql';
79
+ remainingSegments = pathSegments.slice(graphqlIdx + 1);
80
+ }
81
+ else if (restIdx >= 0) {
82
+ type = 'rest';
83
+ remainingSegments = pathSegments.slice(restIdx + 1);
84
+ }
85
+ else {
86
+ type = '';
87
+ remainingSegments = pathSegments;
88
+ }
89
+ let identifier = '';
90
+ if (mockData.request.data) {
91
+ try {
92
+ const body = typeof mockData.request.data === 'string'
93
+ ? JSON.parse(mockData.request.data) : mockData.request.data;
94
+ if (body.operationName)
95
+ identifier = body.operationName;
96
+ else if (body.path)
97
+ identifier = body.path;
98
+ else if (body.webAppName)
99
+ identifier = body.webAppName;
100
+ }
101
+ catch { /* ignore */ }
102
+ }
103
+ identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, '_').substring(0, 60);
104
+ const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join('/');
105
+ const filename = identifier ? `${method}_${identifier}_${dateStr}.json` : `${method}_${dateStr}.json`;
106
+ return { dir, filename };
107
+ }
57
108
  /**
58
109
  * Get current scenario from scenario-config.json
59
110
  */
@@ -217,29 +268,22 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
217
268
  const currentScenario = getCurrentScenario(mockDataPath);
218
269
  const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
219
270
  fs.mkdirSync(scenarioPath, { recursive: true });
220
- // Format the datetime to be readable
221
- const now = new Date();
222
- const dateStr = now.toISOString()
223
- .replace(/T/, '_')
224
- .replace(/\..+/, '')
225
- .replace(/:/g, '-');
226
- // Create a safe filename from the URL
227
- const urlSafe = mockData.request.url
228
- .replace(/^https?:\/\//, '')
229
- .replace(/[^a-zA-Z0-9]/g, '_');
230
- const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
231
- const filePath = path.join(scenarioPath, filename);
271
+ const dateStr = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
272
+ const { dir, filename } = getMockFilePathLocal(mockData, dateStr);
273
+ const fullDir = path.join(scenarioPath, dir);
274
+ const filePath = path.join(fullDir, filename);
232
275
  // Check if file already exists - skip saving if it does
233
276
  if (fs.existsSync(filePath)) {
234
- return { success: true, filename, skipped: true, reason: 'File already exists' };
277
+ return { success: true, filename: path.join(dir, filename), skipped: true, reason: 'File already exists' };
235
278
  }
279
+ fs.mkdirSync(fullDir, { recursive: true });
236
280
  // Write to file
237
281
  fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
238
282
  // Generate test file if enabled
239
283
  if (testConfig) {
240
284
  generateTestForMock(mockData, testConfig, projectRoot);
241
285
  }
242
- return { success: true, filename, scenario: currentScenario };
286
+ return { success: true, filename: path.join(dir, filename), scenario: currentScenario };
243
287
  }
244
288
  catch (error) {
245
289
  console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
@@ -337,6 +381,164 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
337
381
  return { success: false, filesSynced: 0, error: error.message };
338
382
  }
339
383
  }
384
+ /**
385
+ * Recursive mock JSON files under scenario root (paths relative to scenario, POSIX slashes).
386
+ */
387
+ function listScenarioMockJsonFiles(scenarioAbsPath) {
388
+ const out = [];
389
+ if (!fs.existsSync(scenarioAbsPath)) {
390
+ return out;
391
+ }
392
+ const walk = (dir) => {
393
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
394
+ const full = path.join(dir, entry.name);
395
+ if (entry.isDirectory()) {
396
+ walk(full);
397
+ }
398
+ else if (entry.name.endsWith('.json')) {
399
+ const rel = path.relative(scenarioAbsPath, full);
400
+ const relativePath = rel.split(path.sep).join('/');
401
+ if (relativePath === 'scenario-config.json' ||
402
+ relativePath === 'date-config.json') {
403
+ continue;
404
+ }
405
+ out.push({ relativePath, fullPath: full });
406
+ }
407
+ }
408
+ };
409
+ walk(scenarioAbsPath);
410
+ return out;
411
+ }
412
+ /**
413
+ * Resolve a client-supplied path to a mock file under the scenario folder (blocks path traversal).
414
+ */
415
+ function resolveScenarioRelativeMockPath(rawQueryPath, scenarioAbsPath) {
416
+ let decoded;
417
+ try {
418
+ decoded = decodeURIComponent(rawQueryPath);
419
+ }
420
+ catch {
421
+ return null;
422
+ }
423
+ const normalized = decoded.replace(/\\/g, '/').replace(/^\//, '');
424
+ if (!normalized.endsWith('.json') || normalized.includes('..')) {
425
+ return null;
426
+ }
427
+ const fullPath = path.normalize(path.join(scenarioAbsPath, normalized));
428
+ const scenarioResolved = path.resolve(scenarioAbsPath);
429
+ const relativeToScenario = path.relative(scenarioResolved, fullPath);
430
+ if (relativeToScenario.startsWith('..') || path.isAbsolute(relativeToScenario)) {
431
+ return null;
432
+ }
433
+ const relativePath = relativeToScenario.split(path.sep).join('/');
434
+ return { relativePath, fullPath };
435
+ }
436
+ /**
437
+ * Small manifest only (paths + mtimes) for GET /mockifyer-sync-to-device-manifest.
438
+ */
439
+ function buildSyncToDeviceManifest(mockDataPath) {
440
+ try {
441
+ const currentScenario = getCurrentScenario(mockDataPath);
442
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
443
+ const entries = listScenarioMockJsonFiles(scenarioPath);
444
+ const files = [];
445
+ for (const { relativePath, fullPath } of entries) {
446
+ try {
447
+ const stat = fs.statSync(fullPath);
448
+ files.push({ filename: relativePath, modificationTime: stat.mtimeMs });
449
+ }
450
+ catch (e) {
451
+ mockifyer_core_1.logger.warn(`[MetroSyncMiddleware] Manifest: could not stat ${fullPath}:`, e);
452
+ }
453
+ }
454
+ mockifyer_core_1.logger.info(`[MetroSyncMiddleware] /mockifyer-sync-to-device-manifest: ${files.length} file(s), scenario "${currentScenario}"`);
455
+ return { success: true, files, count: files.length };
456
+ }
457
+ catch (error) {
458
+ return { success: false, error: error.message };
459
+ }
460
+ }
461
+ /**
462
+ * One mock file for GET /mockifyer-sync-to-device-file?path=
463
+ */
464
+ function buildSyncToDeviceSingleFilePayload(mockDataPath, rawPathParam) {
465
+ try {
466
+ const currentScenario = getCurrentScenario(mockDataPath);
467
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
468
+ const resolved = resolveScenarioRelativeMockPath(rawPathParam, scenarioPath);
469
+ if (!resolved) {
470
+ return { success: false, error: 'Invalid or unsafe path' };
471
+ }
472
+ const { fullPath, relativePath } = resolved;
473
+ if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
474
+ return { success: false, error: 'Not found' };
475
+ }
476
+ const raw = fs.readFileSync(fullPath, 'utf-8');
477
+ const content = JSON.parse(raw);
478
+ if (!content?.request || !content?.response) {
479
+ return { success: false, error: 'Invalid mock JSON (missing request/response)' };
480
+ }
481
+ const stat = fs.statSync(fullPath);
482
+ return {
483
+ success: true,
484
+ filename: relativePath,
485
+ content,
486
+ modificationTime: stat.mtimeMs,
487
+ };
488
+ }
489
+ catch (error) {
490
+ return { success: false, error: error.message };
491
+ }
492
+ }
493
+ /**
494
+ * Build payload for GET /mockifyer-sync-to-device (project mock-data → native app via HybridProvider).
495
+ */
496
+ function buildSyncToDevicePayload(mockDataPath) {
497
+ try {
498
+ const currentScenario = getCurrentScenario(mockDataPath);
499
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
500
+ const entries = listScenarioMockJsonFiles(scenarioPath);
501
+ const files = [];
502
+ for (const { relativePath, fullPath } of entries) {
503
+ try {
504
+ const raw = fs.readFileSync(fullPath, 'utf-8');
505
+ const content = JSON.parse(raw);
506
+ if (!content?.request || !content?.response) {
507
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Skipping JSON without request/response: ${relativePath}`);
508
+ continue;
509
+ }
510
+ const stat = fs.statSync(fullPath);
511
+ files.push({
512
+ filename: relativePath,
513
+ content,
514
+ modificationTime: stat.mtimeMs,
515
+ });
516
+ }
517
+ catch (e) {
518
+ mockifyer_core_1.logger.warn(`[MetroSyncMiddleware] Could not read ${fullPath}:`, e);
519
+ }
520
+ }
521
+ mockifyer_core_1.logger.info(`[MetroSyncMiddleware] /mockifyer-sync-to-device: ${files.length} mock file(s) from scenario "${getCurrentScenario(mockDataPath)}"`);
522
+ return { success: true, files, count: files.length };
523
+ }
524
+ catch (error) {
525
+ return { success: false, error: error.message };
526
+ }
527
+ }
528
+ /**
529
+ * Normalize URL pathname from Node/Metro `req.url` so `/mockifyer-sync-to-device/` matches `/mockifyer-sync-to-device`.
530
+ * Without this, trailing slashes fall through to Expo Web's SPA and Expo Router treats them as AppDun routes.
531
+ */
532
+ function normalizeMiddlewarePathname(reqUrl) {
533
+ if (!reqUrl || typeof reqUrl !== 'string') {
534
+ return '/';
535
+ }
536
+ let pathname = reqUrl.split('?')[0];
537
+ if (pathname.length > 1 && pathname.endsWith('/')) {
538
+ pathname = pathname.slice(0, -1);
539
+ }
540
+ return pathname;
541
+ }
340
542
  /**
341
543
  * Metro middleware function
342
544
  */
@@ -347,7 +549,7 @@ function createMockSyncMiddleware(options) {
347
549
  // Log the resolved paths for debugging
348
550
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
349
551
  return function mockSyncMiddleware(req, res, next) {
350
- const url = req.url.split('?')[0]; // Remove query params
552
+ const url = normalizeMiddlewarePathname(req.url || '');
351
553
  // Handle POST endpoint for clearing mocks
352
554
  if (url === '/mockifyer-clear' && req.method === 'POST') {
353
555
  const result = clearMockFiles(mockDataPath);
@@ -379,6 +581,43 @@ function createMockSyncMiddleware(options) {
379
581
  });
380
582
  return;
381
583
  }
584
+ // Project folder → device/simulator: manifest (small JSON)
585
+ if (url === '/mockifyer-sync-to-device-manifest' && req.method === 'GET') {
586
+ const payload = buildSyncToDeviceManifest(mockDataPath);
587
+ res.setHeader('Content-Type', 'application/json');
588
+ res.statusCode = payload.success ? 200 : 500;
589
+ res.end(JSON.stringify(payload));
590
+ return;
591
+ }
592
+ // Single file for HybridProvider (avoids multi‑MB single response)
593
+ if (url === '/mockifyer-sync-to-device-file' && req.method === 'GET') {
594
+ const fullUrl = req.url || '';
595
+ const qIndex = fullUrl.indexOf('?');
596
+ const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
597
+ const params = new URLSearchParams(query);
598
+ const pathParam = params.get('path') || '';
599
+ const payload = buildSyncToDeviceSingleFilePayload(mockDataPath, pathParam);
600
+ res.setHeader('Content-Type', 'application/json');
601
+ if (payload.success) {
602
+ res.statusCode = 200;
603
+ }
604
+ else if (payload.error === 'Not found') {
605
+ res.statusCode = 404;
606
+ }
607
+ else {
608
+ res.statusCode = 400;
609
+ }
610
+ res.end(JSON.stringify(payload));
611
+ return;
612
+ }
613
+ // Legacy: all files in one response (may OOM / timeout on large scenarios)
614
+ if (url === '/mockifyer-sync-to-device' && req.method === 'GET') {
615
+ const payload = buildSyncToDevicePayload(mockDataPath);
616
+ res.setHeader('Content-Type', 'application/json');
617
+ res.statusCode = payload.success ? 200 : 500;
618
+ res.end(JSON.stringify(payload));
619
+ return;
620
+ }
382
621
  // Handle GET endpoint for sync status
383
622
  if (url === '/mockifyer-sync/status' && req.method === 'GET') {
384
623
  const currentScenario = getCurrentScenario(mockDataPath);
@@ -7,7 +7,7 @@
7
7
  import { setupMockifyer } from './index';
8
8
  import { HTTPClient } from '@sgedda/mockifyer-core';
9
9
  export interface MockifyerInstance extends HTTPClient {
10
- reloadMockData: () => void;
10
+ reloadMockData: (syncFromProject?: boolean) => Promise<void>;
11
11
  clearStaleCacheEntries: () => number;
12
12
  clearAllMocks: () => Promise<void>;
13
13
  }
@@ -106,9 +106,17 @@ async function setupMockifyerForReactNative(options) {
106
106
  });
107
107
  mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
108
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}`);
109
110
  if (recordMode) {
110
111
  mockifyer_core_2.logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
111
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);
119
+ }
112
120
  return instance;
113
121
  }
114
122
  else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.7.2",
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",
@@ -46,7 +46,11 @@
46
46
  "author": "sgedda",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@sgedda/mockifyer-core": "^1.7.1"
49
+ "@sgedda/mockifyer-core": "^1.8.1"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^20.11.24",
53
+ "typescript": "^5.3.3"
50
54
  },
51
55
  "publishConfig": {
52
56
  "access": "public"
package/src/index.ts CHANGED
@@ -32,7 +32,8 @@ import {
32
32
  initializeScenario,
33
33
  TestGenerator,
34
34
  TestGenerationOptions,
35
- checkRequestLimit
35
+ checkRequestLimit,
36
+ shouldExcludeUrl
36
37
  } from '@sgedda/mockifyer-core';
37
38
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
38
39
 
@@ -44,6 +45,8 @@ class MockifyerClass {
44
45
  private processingRequests: Set<string> = new Set();
45
46
  private savingResponses: Set<string> = new Set();
46
47
  private databaseProvider?: DatabaseProvider;
48
+ /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
49
+ private databaseProviderInitPromise: Promise<void> = Promise.resolve();
47
50
  private currentSessionId: string | null = null;
48
51
  private sessionStartTime: number = 0;
49
52
  private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
@@ -111,9 +114,9 @@ class MockifyerClass {
111
114
  if (config.databaseProvider && config.databaseProvider.type) {
112
115
  this.databaseProvider = createProvider(config.databaseProvider.type, config.databaseProvider);
113
116
  const initResult = this.databaseProvider.initialize();
114
- // Handle async initialization (expo-filesystem provider has async initialize)
117
+ // Handle async initialization (expo-filesystem / hybrid providers)
115
118
  if (initResult instanceof Promise) {
116
- initResult.catch((error) => {
119
+ this.databaseProviderInitPromise = initResult.catch((error) => {
117
120
  logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
118
121
  });
119
122
  }
@@ -402,6 +405,10 @@ class MockifyerClass {
402
405
 
403
406
  if (cachedMock) {
404
407
  const { mockData, filename, filePath } = cachedMock;
408
+ logger.info(
409
+ `[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
410
+ (filePath ? ` (${filePath})` : '')
411
+ );
405
412
  const responseHeaders = {
406
413
  ...mockData.response.headers,
407
414
  'x-mockifyer': 'true',
@@ -576,15 +583,8 @@ class MockifyerClass {
576
583
  return;
577
584
  }
578
585
 
579
- // CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
580
- // Check multiple ways to get the URL in case response.config is undefined
581
586
  const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
582
- if (url && (
583
- url.includes('/mockifyer-save') ||
584
- url.includes('/mockifyer-clear') ||
585
- url.includes('/mockifyer-sync') ||
586
- url.includes('api.resend.com')
587
- )) {
587
+ if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
588
588
  return;
589
589
  }
590
590
 
@@ -920,6 +920,7 @@ class MockifyerClass {
920
920
  }
921
921
 
922
922
  async reloadMockData(syncFromProject: boolean = true): Promise<void> {
923
+ await this.databaseProviderInitPromise;
923
924
  // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
924
925
  // For HybridProvider, this will also sync files from project folder to device
925
926
  if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
@@ -951,7 +952,7 @@ class MockifyerClass {
951
952
  }
952
953
 
953
954
  export interface MockifyerInstance extends HTTPClient {
954
- reloadMockData: () => Promise<void>;
955
+ reloadMockData: (syncFromProject?: boolean) => Promise<void>;
955
956
  clearStaleCacheEntries: () => number;
956
957
  clearAllMocks: () => Promise<void>;
957
958
  }
@@ -1108,7 +1109,8 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1108
1109
  }
1109
1110
 
1110
1111
  const extendedClient = httpClient as MockifyerInstance;
1111
- extendedClient.reloadMockData = async () => await mockifyer.reloadMockData();
1112
+ extendedClient.reloadMockData = async (syncFromProject?: boolean) =>
1113
+ await mockifyer.reloadMockData(syncFromProject);
1112
1114
  extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
1113
1115
  extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
1114
1116