@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/metro-config.js
CHANGED
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
*
|
|
5
5
|
* This helper configures Metro to stub Node.js built-in modules that aren't
|
|
6
6
|
* available in React Native, allowing Mockifyer to bundle successfully.
|
|
7
|
+
* Optionally sets up sync middleware for Hybrid Provider.
|
|
7
8
|
*
|
|
8
|
-
* @example
|
|
9
|
+
* @example Basic usage (fs stubbing only):
|
|
9
10
|
* ```javascript
|
|
10
11
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
11
12
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -13,9 +14,40 @@
|
|
|
13
14
|
* const config = getDefaultConfig(__dirname);
|
|
14
15
|
* module.exports = configureMetroForMockifyer(config);
|
|
15
16
|
* ```
|
|
17
|
+
*
|
|
18
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
19
|
+
* ```javascript
|
|
20
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
21
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
22
|
+
*
|
|
23
|
+
* const config = getDefaultConfig(__dirname);
|
|
24
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
25
|
+
* syncMiddleware: {
|
|
26
|
+
* projectRoot: __dirname,
|
|
27
|
+
* mockDataPath: './mock-data',
|
|
28
|
+
* },
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
33
|
+
* ```javascript
|
|
34
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
35
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
36
|
+
*
|
|
37
|
+
* const config = getDefaultConfig(__dirname);
|
|
38
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
39
|
+
* autoSync: {
|
|
40
|
+
* enabled: true,
|
|
41
|
+
* intervalMs: 5000,
|
|
42
|
+
* projectRoot: __dirname,
|
|
43
|
+
* mockDataPath: './mock-data',
|
|
44
|
+
* },
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
16
47
|
*/
|
|
17
48
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
49
|
exports.configureMetroForMockifyer = configureMetroForMockifyer;
|
|
50
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
19
51
|
/**
|
|
20
52
|
* Node.js built-in modules that need to be stubbed for React Native
|
|
21
53
|
* Includes modules used by Mockifyer packages and their dependencies:
|
|
@@ -27,15 +59,16 @@ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
|
|
|
27
59
|
/**
|
|
28
60
|
* Configure Metro bundler for Mockifyer
|
|
29
61
|
*
|
|
30
|
-
* This function
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
62
|
+
* This function:
|
|
63
|
+
* 1. Adds resolver configuration to stub Node.js built-in modules (fs, path, assert, util)
|
|
64
|
+
* 2. Optionally sets up sync middleware for Hybrid Provider (if syncMiddleware options provided)
|
|
65
|
+
* 3. Optionally sets up auto-sync polling (if autoSync options provided - needed for ExpoFileSystem Provider, not needed with Hybrid Provider)
|
|
34
66
|
*
|
|
35
67
|
* @param config - Existing Metro config (e.g., from getDefaultConfig)
|
|
36
|
-
* @
|
|
68
|
+
* @param options - Optional configuration including sync middleware setup
|
|
69
|
+
* @returns Metro config with Mockifyer configuration merged in
|
|
37
70
|
*
|
|
38
|
-
* @example
|
|
71
|
+
* @example Basic usage (fs stubbing only):
|
|
39
72
|
* ```javascript
|
|
40
73
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
41
74
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -43,8 +76,38 @@ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
|
|
|
43
76
|
* const config = getDefaultConfig(__dirname);
|
|
44
77
|
* module.exports = configureMetroForMockifyer(config);
|
|
45
78
|
* ```
|
|
79
|
+
*
|
|
80
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
81
|
+
* ```javascript
|
|
82
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
83
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
84
|
+
*
|
|
85
|
+
* const config = getDefaultConfig(__dirname);
|
|
86
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
87
|
+
* syncMiddleware: {
|
|
88
|
+
* projectRoot: __dirname,
|
|
89
|
+
* mockDataPath: './mock-data',
|
|
90
|
+
* },
|
|
91
|
+
* });
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
95
|
+
* ```javascript
|
|
96
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
97
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
98
|
+
*
|
|
99
|
+
* const config = getDefaultConfig(__dirname);
|
|
100
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
101
|
+
* autoSync: {
|
|
102
|
+
* enabled: true,
|
|
103
|
+
* intervalMs: 5000,
|
|
104
|
+
* projectRoot: __dirname,
|
|
105
|
+
* mockDataPath: './mock-data',
|
|
106
|
+
* },
|
|
107
|
+
* });
|
|
108
|
+
* ```
|
|
46
109
|
*/
|
|
47
|
-
function configureMetroForMockifyer(config) {
|
|
110
|
+
function configureMetroForMockifyer(config, options) {
|
|
48
111
|
// Get path to empty module stub
|
|
49
112
|
// Resolve using the package export path, which points to metro-polyfills/empty-module.js
|
|
50
113
|
let emptyModulePath;
|
|
@@ -79,6 +142,61 @@ function configureMetroForMockifyer(config) {
|
|
|
79
142
|
// Fallback to default Metro resolution
|
|
80
143
|
return context.resolveRequest(context, moduleName, platform);
|
|
81
144
|
};
|
|
145
|
+
// Set up sync middleware if options provided
|
|
146
|
+
if (options?.syncMiddleware) {
|
|
147
|
+
try {
|
|
148
|
+
const { createMockSyncMiddleware } = require('./metro-sync-middleware');
|
|
149
|
+
const syncMiddleware = createMockSyncMiddleware({
|
|
150
|
+
projectRoot: options.syncMiddleware.projectRoot || process.cwd(),
|
|
151
|
+
mockDataPath: options.syncMiddleware.mockDataPath || 'mock-data',
|
|
152
|
+
testGeneration: options.syncMiddleware.testGeneration,
|
|
153
|
+
});
|
|
154
|
+
// Add middleware to server config
|
|
155
|
+
// Expo Metro uses enhanceMiddleware, but also supports middleware array
|
|
156
|
+
config.server = config.server || {};
|
|
157
|
+
// Use enhanceMiddleware if available (Expo Metro standard)
|
|
158
|
+
// enhanceMiddleware receives existing middleware and returns new middleware
|
|
159
|
+
const existingEnhance = config.server.enhanceMiddleware;
|
|
160
|
+
config.server.enhanceMiddleware = (middleware) => {
|
|
161
|
+
// Return a middleware function that runs our syncMiddleware first,
|
|
162
|
+
// then calls the existing enhanced middleware
|
|
163
|
+
return (req, res, next) => {
|
|
164
|
+
// Try our middleware first (it calls next() if not handling the request)
|
|
165
|
+
syncMiddleware(req, res, (err) => {
|
|
166
|
+
if (err) {
|
|
167
|
+
return next(err);
|
|
168
|
+
}
|
|
169
|
+
// If our middleware didn't handle it, call the existing middleware
|
|
170
|
+
if (!res.headersSent) {
|
|
171
|
+
return middleware(req, res, next);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
mockifyer_core_1.logger.warn('[Metro] Could not set up Mockifyer sync middleware:', e);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// Set up auto-sync (polling-based sync from iOS Simulator to project folder) if options provided
|
|
182
|
+
// Required when using ExpoFileSystem Provider to sync files from device to project folder for code search
|
|
183
|
+
// Not needed with Hybrid Provider (uses instant HTTP sync via syncMiddleware)
|
|
184
|
+
if (options?.autoSync?.enabled) {
|
|
185
|
+
try {
|
|
186
|
+
const { startAutoSync } = require('./metro-sync-middleware');
|
|
187
|
+
const intervalMs = options.autoSync.intervalMs || 5000;
|
|
188
|
+
const projectRoot = options.autoSync.projectRoot || process.cwd();
|
|
189
|
+
const mockDataPath = options.autoSync.mockDataPath || 'mock-data';
|
|
190
|
+
startAutoSync(intervalMs, {
|
|
191
|
+
projectRoot,
|
|
192
|
+
mockDataPath,
|
|
193
|
+
});
|
|
194
|
+
console.log(`[Metro] ✅ Auto-sync enabled: polling every ${intervalMs}ms`);
|
|
195
|
+
}
|
|
196
|
+
catch (e) {
|
|
197
|
+
mockifyer_core_1.logger.warn('[Metro] Could not set up Mockifyer auto-sync:', e);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
82
200
|
// Merge config with new resolver
|
|
83
201
|
return {
|
|
84
202
|
...config,
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Metro middleware for mock file synchronization
|
|
3
3
|
*
|
|
4
|
-
* Provides
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
@@ -51,8 +53,58 @@ exports.stopAutoSync = stopAutoSync;
|
|
|
51
53
|
exports.syncFromIOSSimulator = syncFromIOSSimulator;
|
|
52
54
|
const fs = __importStar(require("fs"));
|
|
53
55
|
const path = __importStar(require("path"));
|
|
56
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
54
57
|
const DEFAULT_SCENARIO = 'default';
|
|
55
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
|
+
}
|
|
56
108
|
/**
|
|
57
109
|
* Get current scenario from scenario-config.json
|
|
58
110
|
*/
|
|
@@ -139,11 +191,9 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
139
191
|
}
|
|
140
192
|
}
|
|
141
193
|
catch (e) {
|
|
142
|
-
console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${e.message}`);
|
|
143
194
|
return false;
|
|
144
195
|
}
|
|
145
196
|
if (!TestGeneratorClass) {
|
|
146
|
-
console.log('[MockSync] ⚠️ TestGenerator not available');
|
|
147
197
|
return false;
|
|
148
198
|
}
|
|
149
199
|
const generator = new TestGeneratorClass();
|
|
@@ -162,7 +212,6 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
162
212
|
const testDir = path.dirname(absoluteTestPath);
|
|
163
213
|
// If uniqueTestsPerEndpoint is enabled, check if a test file already exists
|
|
164
214
|
if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
|
|
165
|
-
console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
|
|
166
215
|
return true;
|
|
167
216
|
}
|
|
168
217
|
// Ensure test directory exists
|
|
@@ -175,7 +224,6 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
175
224
|
const testName = `${testInfo.method} ${testInfo.endpoint}`;
|
|
176
225
|
const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
|
|
177
226
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
178
|
-
console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
179
227
|
return true;
|
|
180
228
|
}
|
|
181
229
|
// Append test to existing file
|
|
@@ -184,19 +232,17 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
184
232
|
const newTest = testMatch[0];
|
|
185
233
|
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
186
234
|
fs.writeFileSync(absoluteTestPath, updatedContent);
|
|
187
|
-
console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
188
235
|
return true;
|
|
189
236
|
}
|
|
190
237
|
}
|
|
191
238
|
else {
|
|
192
239
|
// Create new test file
|
|
193
240
|
fs.writeFileSync(absoluteTestPath, testCode);
|
|
194
|
-
console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
|
|
195
241
|
}
|
|
196
242
|
return true;
|
|
197
243
|
}
|
|
198
244
|
catch (error) {
|
|
199
|
-
|
|
245
|
+
mockifyer_core_1.logger.error(`[MockSync] ❌ Error generating test:`, error);
|
|
200
246
|
return false;
|
|
201
247
|
}
|
|
202
248
|
}
|
|
@@ -215,38 +261,29 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
215
261
|
// Also check if the mockData string contains nested sync requests
|
|
216
262
|
const mockDataStr = JSON.stringify(mockData);
|
|
217
263
|
if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
|
|
218
|
-
|
|
264
|
+
mockifyer_core_1.logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
|
|
219
265
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
220
266
|
}
|
|
221
267
|
// Get current scenario and ensure scenario folder exists
|
|
222
268
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
223
269
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
224
270
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
.replace(/\..+/, '')
|
|
230
|
-
.replace(/:/g, '-');
|
|
231
|
-
// Create a safe filename from the URL
|
|
232
|
-
const urlSafe = mockData.request.url
|
|
233
|
-
.replace(/^https?:\/\//, '')
|
|
234
|
-
.replace(/[^a-zA-Z0-9]/g, '_');
|
|
235
|
-
const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
|
|
236
|
-
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);
|
|
237
275
|
// Check if file already exists - skip saving if it does
|
|
238
276
|
if (fs.existsSync(filePath)) {
|
|
239
|
-
|
|
240
|
-
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' };
|
|
241
278
|
}
|
|
279
|
+
fs.mkdirSync(fullDir, { recursive: true });
|
|
242
280
|
// Write to file
|
|
243
281
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
244
|
-
console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
|
|
245
282
|
// Generate test file if enabled
|
|
246
283
|
if (testConfig) {
|
|
247
284
|
generateTestForMock(mockData, testConfig, projectRoot);
|
|
248
285
|
}
|
|
249
|
-
return { success: true, filename, scenario: currentScenario };
|
|
286
|
+
return { success: true, filename: path.join(dir, filename), scenario: currentScenario };
|
|
250
287
|
}
|
|
251
288
|
catch (error) {
|
|
252
289
|
console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
|
|
@@ -272,11 +309,10 @@ function clearMockFiles(mockDataPath) {
|
|
|
272
309
|
deleted++;
|
|
273
310
|
}
|
|
274
311
|
});
|
|
275
|
-
console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
|
|
276
312
|
return { success: true, filesDeleted: deleted };
|
|
277
313
|
}
|
|
278
314
|
catch (error) {
|
|
279
|
-
|
|
315
|
+
mockifyer_core_1.logger.error(`[MockSync] ❌ Error clearing mock files:`, error);
|
|
280
316
|
return { success: false, error: error.message };
|
|
281
317
|
}
|
|
282
318
|
}
|
|
@@ -333,7 +369,6 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
|
|
|
333
369
|
syncedFiles.push(file);
|
|
334
370
|
}
|
|
335
371
|
});
|
|
336
|
-
console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
|
|
337
372
|
break;
|
|
338
373
|
}
|
|
339
374
|
}
|
|
@@ -346,6 +381,164 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
|
|
|
346
381
|
return { success: false, filesSynced: 0, error: error.message };
|
|
347
382
|
}
|
|
348
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
|
+
}
|
|
349
542
|
/**
|
|
350
543
|
* Metro middleware function
|
|
351
544
|
*/
|
|
@@ -353,8 +546,10 @@ function createMockSyncMiddleware(options) {
|
|
|
353
546
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
354
547
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
355
548
|
const testConfig = getTestGenerationConfig(options);
|
|
549
|
+
// Log the resolved paths for debugging
|
|
550
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
|
|
356
551
|
return function mockSyncMiddleware(req, res, next) {
|
|
357
|
-
const url = req.url
|
|
552
|
+
const url = normalizeMiddlewarePathname(req.url || '');
|
|
358
553
|
// Handle POST endpoint for clearing mocks
|
|
359
554
|
if (url === '/mockifyer-clear' && req.method === 'POST') {
|
|
360
555
|
const result = clearMockFiles(mockDataPath);
|
|
@@ -386,6 +581,43 @@ function createMockSyncMiddleware(options) {
|
|
|
386
581
|
});
|
|
387
582
|
return;
|
|
388
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
|
+
}
|
|
389
621
|
// Handle GET endpoint for sync status
|
|
390
622
|
if (url === '/mockifyer-sync/status' && req.method === 'GET') {
|
|
391
623
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
@@ -412,18 +644,44 @@ function createMockSyncMiddleware(options) {
|
|
|
412
644
|
// Handle GET endpoint for scenario config
|
|
413
645
|
if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
|
|
414
646
|
try {
|
|
647
|
+
// Check environment variable first (highest priority)
|
|
648
|
+
if (process.env.MOCKIFYER_SCENARIO) {
|
|
649
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
|
|
650
|
+
res.setHeader('Content-Type', 'application/json');
|
|
651
|
+
res.end(JSON.stringify({
|
|
652
|
+
success: true,
|
|
653
|
+
currentScenario: process.env.MOCKIFYER_SCENARIO
|
|
654
|
+
}));
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
415
657
|
const configPath = path.join(mockDataPath, 'scenario-config.json');
|
|
658
|
+
const resolvedPath = path.resolve(configPath);
|
|
659
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
|
|
660
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
|
|
416
661
|
if (fs.existsSync(configPath)) {
|
|
417
|
-
const
|
|
662
|
+
const fileContent = fs.readFileSync(configPath, 'utf-8');
|
|
663
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
664
|
+
const config = JSON.parse(fileContent);
|
|
665
|
+
const scenario = config.currentScenario || DEFAULT_SCENARIO;
|
|
666
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
|
|
418
667
|
res.setHeader('Content-Type', 'application/json');
|
|
419
|
-
|
|
668
|
+
// Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
|
|
669
|
+
res.end(JSON.stringify({
|
|
670
|
+
success: true,
|
|
671
|
+
currentScenario: scenario
|
|
672
|
+
}));
|
|
420
673
|
}
|
|
421
674
|
else {
|
|
675
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
|
|
422
676
|
res.setHeader('Content-Type', 'application/json');
|
|
423
|
-
res.end(JSON.stringify({
|
|
677
|
+
res.end(JSON.stringify({
|
|
678
|
+
success: true,
|
|
679
|
+
currentScenario: DEFAULT_SCENARIO
|
|
680
|
+
}));
|
|
424
681
|
}
|
|
425
682
|
}
|
|
426
683
|
catch (error) {
|
|
684
|
+
mockifyer_core_1.logger.error(`[MetroSyncMiddleware] Error reading scenario config:`, error);
|
|
427
685
|
res.statusCode = 500;
|
|
428
686
|
res.setHeader('Content-Type', 'application/json');
|
|
429
687
|
res.end(JSON.stringify({ success: false, error: error.message }));
|
|
@@ -461,12 +719,11 @@ function createMockSyncMiddleware(options) {
|
|
|
461
719
|
*/
|
|
462
720
|
function startAutoSync(intervalMs = 5000, options) {
|
|
463
721
|
if (autoSyncInterval) {
|
|
464
|
-
console.log('[MockSync] Auto-sync already running');
|
|
465
722
|
return;
|
|
466
723
|
}
|
|
467
724
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
468
725
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
469
|
-
|
|
726
|
+
mockifyer_core_1.logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
|
|
470
727
|
autoSyncInterval = setInterval(() => {
|
|
471
728
|
syncFromIOSSimulator(projectRoot, mockDataPath);
|
|
472
729
|
}, intervalMs);
|
|
@@ -478,6 +735,5 @@ function stopAutoSync() {
|
|
|
478
735
|
if (autoSyncInterval) {
|
|
479
736
|
clearInterval(autoSyncInterval);
|
|
480
737
|
autoSyncInterval = null;
|
|
481
|
-
console.log('[MockSync] Auto-sync disabled');
|
|
482
738
|
}
|
|
483
739
|
}
|
package/dist/react-native.d.ts
CHANGED
|
@@ -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
|
}
|