@sgedda/mockifyer-fetch 1.7.0

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.
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Metro bundler configuration helper for Mockifyer
3
+ *
4
+ * This helper configures Metro to stub Node.js built-in modules that aren't
5
+ * available in React Native, allowing Mockifyer to bundle successfully.
6
+ *
7
+ * @example
8
+ * ```javascript
9
+ * const { getDefaultConfig } = require('expo/metro-config');
10
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
11
+ *
12
+ * const config = getDefaultConfig(__dirname);
13
+ * module.exports = configureMetroForMockifyer(config);
14
+ * ```
15
+ */
16
+
17
+ // Metro config types (simplified - Metro doesn't export types)
18
+ export interface MetroConfig {
19
+ resolver?: {
20
+ resolveRequest?: (
21
+ context: any,
22
+ moduleName: string,
23
+ platform: string | null
24
+ ) => { filePath: string; type: string } | null | undefined;
25
+ extraNodeModules?: Record<string, string>;
26
+ nodeModulesPaths?: string[];
27
+ };
28
+ watchFolders?: string[];
29
+ transformer?: any;
30
+ server?: any;
31
+ [key: string]: any;
32
+ }
33
+
34
+ /**
35
+ * Node.js built-in modules that need to be stubbed for React Native
36
+ * Includes modules used by Mockifyer packages and their dependencies:
37
+ * - fs, path: Used by FilesystemProvider
38
+ * - assert: Used by @sinonjs/fake-timers
39
+ * - util: Used by @sinonjs/fake-timers
40
+ */
41
+ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'] as const;
42
+
43
+ /**
44
+ * Configure Metro bundler for Mockifyer
45
+ *
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.
50
+ *
51
+ * @param config - Existing Metro config (e.g., from getDefaultConfig)
52
+ * @returns Metro config with Mockifyer resolver configuration merged in
53
+ *
54
+ * @example
55
+ * ```javascript
56
+ * const { getDefaultConfig } = require('expo/metro-config');
57
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
58
+ *
59
+ * const config = getDefaultConfig(__dirname);
60
+ * module.exports = configureMetroForMockifyer(config);
61
+ * ```
62
+ */
63
+ export function configureMetroForMockifyer(config: MetroConfig): MetroConfig {
64
+ // Get path to empty module stub
65
+ // Resolve using the package export path, which points to metro-polyfills/empty-module.js
66
+ let emptyModulePath: string;
67
+ try {
68
+ // Try to resolve via package exports (works when installed)
69
+ emptyModulePath = require.resolve('@sgedda/mockifyer-fetch/metro-polyfills/empty-module');
70
+ } catch (e) {
71
+ // Fallback: resolve relative to this file (works in monorepo/development)
72
+ const path = require('path');
73
+ emptyModulePath = path.join(__dirname, '..', 'metro-polyfills', 'empty-module.js');
74
+ }
75
+
76
+ // Get existing resolver or create new one
77
+ const existingResolver = config.resolver || {};
78
+ const existingResolveRequest = existingResolver.resolveRequest;
79
+
80
+ // Create new resolveRequest function that handles Node.js built-ins
81
+ const newResolveRequest = (
82
+ context: any,
83
+ moduleName: string,
84
+ platform: string | null
85
+ ): { filePath: string; type: string } | null | undefined => {
86
+ // Handle Node.js built-in modules - return empty module stub
87
+ if (NODE_BUILTINS.includes(moduleName as any)) {
88
+ return {
89
+ filePath: emptyModulePath,
90
+ type: 'sourceFile',
91
+ };
92
+ }
93
+
94
+ // Call existing resolver if present
95
+ if (existingResolveRequest) {
96
+ const result = existingResolveRequest(context, moduleName, platform);
97
+ if (result) {
98
+ return result;
99
+ }
100
+ }
101
+
102
+ // Fallback to default Metro resolution
103
+ return context.resolveRequest(context, moduleName, platform);
104
+ };
105
+
106
+ // Merge config with new resolver
107
+ return {
108
+ ...config,
109
+ resolver: {
110
+ ...existingResolver,
111
+ resolveRequest: newResolveRequest,
112
+ },
113
+ };
114
+ }
115
+
@@ -0,0 +1,560 @@
1
+ /**
2
+ * Metro middleware for mock file synchronization
3
+ *
4
+ * Provides two sync mechanisms:
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)
7
+ *
8
+ * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
9
+ * Legacy polling-based sync is still available for backward compatibility.
10
+ *
11
+ * Usage: Add to metro.config.js middleware array
12
+ */
13
+
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ import { execSync } from 'child_process';
17
+ import { MockData, TestGenerator, TestGenerationOptions } from '@sgedda/mockifyer-core';
18
+
19
+ export interface MetroSyncMiddlewareOptions {
20
+ /** Project root directory (default: process.cwd()) */
21
+ projectRoot?: string;
22
+ /** Path to mock data directory relative to project root (default: 'mock-data') */
23
+ mockDataPath?: string;
24
+ /** Test generation configuration - tests are generated when mocks are saved to project folder */
25
+ testGeneration?: {
26
+ /** Enable automatic test generation when mocks are saved */
27
+ enabled?: boolean;
28
+ /** Test framework to use: 'jest' (default), 'vitest', or 'mocha' */
29
+ framework?: 'jest' | 'vitest' | 'mocha';
30
+ /** Output path for generated tests (default: './tests/generated') */
31
+ outputPath?: string;
32
+ /** Test file naming pattern with placeholders: {endpoint}, {method}, {scenario} (default: '{endpoint}.test.ts') */
33
+ testPattern?: string;
34
+ /** Include setup code in generated tests (default: true) */
35
+ includeSetup?: boolean;
36
+ /** Group tests by: 'endpoint', 'scenario', or 'file' (default: 'endpoint') */
37
+ groupBy?: 'endpoint' | 'scenario' | 'file';
38
+ /** If true, only generate one test per endpoint (method + pathname), ignoring query parameters (default: false) */
39
+ uniqueTestsPerEndpoint?: boolean;
40
+ };
41
+ }
42
+
43
+ const DEFAULT_SCENARIO = 'default';
44
+
45
+ let autoSyncInterval: NodeJS.Timeout | null = null;
46
+
47
+ /**
48
+ * Get current scenario from scenario-config.json
49
+ */
50
+ function getCurrentScenario(mockDataPath: string): string {
51
+ // Check environment variable first
52
+ if (process.env.MOCKIFYER_SCENARIO) {
53
+ return process.env.MOCKIFYER_SCENARIO;
54
+ }
55
+
56
+ // Try to load from scenario-config.json
57
+ try {
58
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
59
+ if (fs.existsSync(configPath)) {
60
+ const fileContent = fs.readFileSync(configPath, 'utf-8');
61
+ const config = JSON.parse(fileContent);
62
+ if (config.currentScenario) {
63
+ return config.currentScenario;
64
+ }
65
+ }
66
+ } catch (error) {
67
+ // Silently fail - file might not exist or be invalid
68
+ }
69
+
70
+ return DEFAULT_SCENARIO;
71
+ }
72
+
73
+ /**
74
+ * Get scenario folder path
75
+ */
76
+ function getScenarioPath(scenario: string, mockDataPath: string): string {
77
+ // Always create scenario subfolder, even for 'default'
78
+ return path.join(mockDataPath, scenario);
79
+ }
80
+
81
+
82
+ /**
83
+ * Get test generation config from options or environment variables
84
+ * Options take precedence, then fall back to environment variables (for backward compatibility)
85
+ */
86
+ function getTestGenerationConfig(options?: MetroSyncMiddlewareOptions): TestGenerationOptions | null {
87
+ // Check if enabled via options or environment variables
88
+ const enabled =
89
+ options?.testGeneration?.enabled === true ||
90
+ process.env.MOCKIFYER_GENERATE_TESTS === 'true' ||
91
+ process.env.MOCKIFYER_GENERATE_TESTS === '1';
92
+
93
+ if (!enabled) {
94
+ return null;
95
+ }
96
+
97
+ // Use options if provided, otherwise fall back to environment variables
98
+ return {
99
+ framework: options?.testGeneration?.framework || (process.env.MOCKIFYER_TEST_FRAMEWORK as any) || 'jest',
100
+ outputPath: options?.testGeneration?.outputPath || process.env.MOCKIFYER_TEST_OUTPUT_PATH || './tests/generated',
101
+ testPattern: options?.testGeneration?.testPattern || process.env.MOCKIFYER_TEST_PATTERN || '{endpoint}.test.ts',
102
+ includeSetup: options?.testGeneration?.includeSetup !== false && process.env.MOCKIFYER_TEST_INCLUDE_SETUP !== 'false',
103
+ groupBy: options?.testGeneration?.groupBy || (process.env.MOCKIFYER_TEST_GROUP_BY as any) || 'endpoint',
104
+ httpClientType: 'fetch',
105
+ uniqueTestsPerEndpoint: options?.testGeneration?.uniqueTestsPerEndpoint || process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT === 'true',
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Generate test file for a mock (runs in Metro/Node.js where fs is available)
111
+ */
112
+ function generateTestForMock(
113
+ mockData: MockData,
114
+ testConfig: TestGenerationOptions,
115
+ projectRoot: string
116
+ ): boolean {
117
+ try {
118
+ // Try to require TestGenerator from mockifyer-core
119
+ let TestGeneratorClass: typeof TestGenerator;
120
+ try {
121
+ let mockifyerCore;
122
+ try {
123
+ mockifyerCore = require('@sgedda/mockifyer-core');
124
+ } catch (e) {
125
+ // Fallback: try relative path (for local file: dependencies)
126
+ const corePath = path.join(projectRoot, '../../packages/mockifyer-core/dist/index.js');
127
+ if (fs.existsSync(corePath)) {
128
+ mockifyerCore = require(corePath);
129
+ } else {
130
+ throw new Error(`Could not find mockifyer-core at ${corePath}`);
131
+ }
132
+ }
133
+
134
+ TestGeneratorClass = mockifyerCore?.TestGenerator;
135
+
136
+ if (!TestGeneratorClass) {
137
+ const testGeneratorPath = path.join(projectRoot, '../../packages/mockifyer-core/dist/utils/test-generator.js');
138
+ if (fs.existsSync(testGeneratorPath)) {
139
+ const testGeneratorModule = require(testGeneratorPath);
140
+ TestGeneratorClass = testGeneratorModule.TestGenerator;
141
+ }
142
+ }
143
+ } catch (e) {
144
+ console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${(e as Error).message}`);
145
+ return false;
146
+ }
147
+
148
+ if (!TestGeneratorClass) {
149
+ console.log('[MockSync] ⚠️ TestGenerator not available');
150
+ return false;
151
+ }
152
+
153
+ const generator = new TestGeneratorClass();
154
+
155
+ const options: TestGenerationOptions = {
156
+ framework: testConfig.framework,
157
+ outputPath: testConfig.outputPath,
158
+ testPattern: testConfig.testPattern,
159
+ includeSetup: testConfig.includeSetup,
160
+ groupBy: testConfig.groupBy,
161
+ httpClientType: testConfig.httpClientType,
162
+ uniqueTestsPerEndpoint: testConfig.uniqueTestsPerEndpoint,
163
+ };
164
+
165
+ const testInfo = generator.analyzeMock(mockData, options.httpClientType || 'fetch');
166
+ const testFilePath = generator.determineTestFilePath(mockData, options);
167
+
168
+ const absoluteTestPath = path.resolve(projectRoot, testFilePath);
169
+ const testDir = path.dirname(absoluteTestPath);
170
+
171
+ // If uniqueTestsPerEndpoint is enabled, check if a test file already exists
172
+ if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
173
+ console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
174
+ return true;
175
+ }
176
+
177
+ // Ensure test directory exists
178
+ if (!fs.existsSync(testDir)) {
179
+ fs.mkdirSync(testDir, { recursive: true });
180
+ }
181
+
182
+ const testCode = generator.generateTest(mockData, options);
183
+
184
+ // Check if test file already exists
185
+ if (fs.existsSync(absoluteTestPath)) {
186
+ const testName = `${testInfo.method} ${testInfo.endpoint}`;
187
+
188
+ const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
189
+ if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
190
+ console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
191
+ return true;
192
+ }
193
+
194
+ // Append test to existing file
195
+ const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
196
+ if (testMatch) {
197
+ const newTest = testMatch[0];
198
+ const updatedContent = existingContent.replace(
199
+ /(\s+)(\}\);?\s*)$/,
200
+ `$1${newTest}\n$1$2`
201
+ );
202
+ fs.writeFileSync(absoluteTestPath, updatedContent);
203
+ console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
204
+ return true;
205
+ }
206
+ } else {
207
+ // Create new test file
208
+ fs.writeFileSync(absoluteTestPath, testCode);
209
+ console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
210
+ }
211
+
212
+ return true;
213
+ } catch (error) {
214
+ console.error(`[MockSync] ❌ Error generating test:`, error);
215
+ return false;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Save mock data directly to project folder
221
+ * Called by HybridProvider when saving mocks
222
+ */
223
+ function saveMockToProjectFolder(
224
+ mockData: MockData,
225
+ projectRoot: string,
226
+ mockDataPath: string,
227
+ testConfig: TestGenerationOptions | null
228
+ ): { success: boolean; filename?: string; scenario?: string; error?: string; skipped?: boolean; reason?: string } {
229
+ try {
230
+ // CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
231
+ const url = mockData?.request?.url || '';
232
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
233
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
234
+ return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
235
+ }
236
+
237
+ // Also check if the mockData string contains nested sync requests
238
+ const mockDataStr = JSON.stringify(mockData);
239
+ if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
240
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
241
+ return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
242
+ }
243
+
244
+ // Get current scenario and ensure scenario folder exists
245
+ const currentScenario = getCurrentScenario(mockDataPath);
246
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
247
+ fs.mkdirSync(scenarioPath, { recursive: true });
248
+
249
+ // Format the datetime to be readable
250
+ const now = new Date();
251
+ const dateStr = now.toISOString()
252
+ .replace(/T/, '_')
253
+ .replace(/\..+/, '')
254
+ .replace(/:/g, '-');
255
+
256
+ // Create a safe filename from the URL
257
+ const urlSafe = mockData.request.url
258
+ .replace(/^https?:\/\//, '')
259
+ .replace(/[^a-zA-Z0-9]/g, '_');
260
+
261
+ const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
262
+ const filePath = path.join(scenarioPath, filename);
263
+
264
+ // Check if file already exists - skip saving if it does
265
+ if (fs.existsSync(filePath)) {
266
+ console.log(`[MockSync] ⚠️ File already exists, skipping save: ${filename}`);
267
+ return { success: true, filename, skipped: true, reason: 'File already exists' };
268
+ }
269
+
270
+ // Write to file
271
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
272
+
273
+ console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
274
+
275
+ // Generate test file if enabled
276
+ if (testConfig) {
277
+ generateTestForMock(mockData, testConfig, projectRoot);
278
+ }
279
+
280
+ return { success: true, filename, scenario: currentScenario };
281
+ } catch (error) {
282
+ console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
283
+ return { success: false, error: (error as Error).message };
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Clear all mock files from project folder (current scenario)
289
+ */
290
+ function clearMockFiles(mockDataPath: string): { success: boolean; filesDeleted?: number; error?: string } {
291
+ try {
292
+ const currentScenario = getCurrentScenario(mockDataPath);
293
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
294
+
295
+ if (!fs.existsSync(scenarioPath)) {
296
+ return { success: true, filesDeleted: 0 };
297
+ }
298
+
299
+ const files = fs.readdirSync(scenarioPath);
300
+ let deleted = 0;
301
+
302
+ files.forEach(file => {
303
+ if (file.endsWith('.json')) {
304
+ const filePath = path.join(scenarioPath, file);
305
+ fs.unlinkSync(filePath);
306
+ deleted++;
307
+ }
308
+ });
309
+
310
+ console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
311
+ return { success: true, filesDeleted: deleted };
312
+ } catch (error) {
313
+ console.error(`[MockSync] ❌ Error clearing mock files:`, error);
314
+ return { success: false, error: (error as Error).message };
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Sync mock files from iOS simulator to project folder
320
+ */
321
+ function syncFromIOSSimulator(
322
+ projectRoot: string,
323
+ mockDataPath: string
324
+ ): { success: boolean; filesSynced?: number; syncedFiles?: string[]; error?: string } {
325
+ try {
326
+ // Get iOS simulator path
327
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
328
+ const simulatorPath = path.join(
329
+ homeDir,
330
+ 'Library/Developer/CoreSimulator/Devices'
331
+ );
332
+
333
+ if (!fs.existsSync(simulatorPath)) {
334
+ return { success: false, error: 'iOS Simulator path not found' };
335
+ }
336
+
337
+ // Find the most recent simulator device
338
+ const devices = fs.readdirSync(simulatorPath);
339
+ let latestDevice = '';
340
+ let latestTime = 0;
341
+
342
+ devices.forEach(device => {
343
+ const devicePath = path.join(simulatorPath, device);
344
+ const stat = fs.statSync(devicePath);
345
+ if (stat.mtimeMs > latestTime) {
346
+ latestTime = stat.mtimeMs;
347
+ latestDevice = device;
348
+ }
349
+ });
350
+
351
+ if (!latestDevice) {
352
+ return { success: false, error: 'No iOS Simulator device found' };
353
+ }
354
+
355
+ // Look for mock-data directory in the simulator
356
+ const appDataPath = path.join(
357
+ simulatorPath,
358
+ latestDevice,
359
+ 'data/Containers/Data/Application'
360
+ );
361
+
362
+ if (!fs.existsSync(appDataPath)) {
363
+ return { success: false, error: 'iOS Simulator app data path not found' };
364
+ }
365
+
366
+ const apps = fs.readdirSync(appDataPath);
367
+ let found = false;
368
+ let filesSynced = 0;
369
+ const syncedFiles: string[] = [];
370
+
371
+ for (const app of apps) {
372
+ const appPath = path.join(appDataPath, app);
373
+ const mockDataSimPath = path.join(appPath, 'Documents/mock-data');
374
+
375
+ if (fs.existsSync(mockDataSimPath)) {
376
+ found = true;
377
+ const currentScenario = getCurrentScenario(mockDataPath);
378
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
379
+ fs.mkdirSync(scenarioPath, { recursive: true });
380
+
381
+ const files = fs.readdirSync(mockDataSimPath);
382
+ files.forEach(file => {
383
+ if (file.endsWith('.json')) {
384
+ const sourcePath = path.join(mockDataSimPath, file);
385
+ const destPath = path.join(scenarioPath, file);
386
+ fs.copyFileSync(sourcePath, destPath);
387
+ filesSynced++;
388
+ syncedFiles.push(file);
389
+ }
390
+ });
391
+
392
+ console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
393
+ break;
394
+ }
395
+ }
396
+
397
+ if (!found) {
398
+ return { success: false, filesSynced: 0, error: 'mock-data directory not found in simulator' };
399
+ }
400
+
401
+ return { success: true, filesSynced, syncedFiles };
402
+ } catch (error) {
403
+ return { success: false, filesSynced: 0, error: (error as Error).message };
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Metro middleware function
409
+ */
410
+ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
411
+ const projectRoot = options?.projectRoot || process.cwd();
412
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
413
+ const testConfig = getTestGenerationConfig(options);
414
+
415
+ return function mockSyncMiddleware(req: any, res: any, next: any) {
416
+ const url = req.url.split('?')[0]; // Remove query params
417
+
418
+ // Handle POST endpoint for clearing mocks
419
+ if (url === '/mockifyer-clear' && req.method === 'POST') {
420
+ const result = clearMockFiles(mockDataPath);
421
+ res.setHeader('Content-Type', 'application/json');
422
+ res.end(JSON.stringify(result));
423
+ return;
424
+ }
425
+
426
+ // Handle POST endpoint for direct save (HybridProvider)
427
+ if (url === '/mockifyer-save' && req.method === 'POST') {
428
+ let body = '';
429
+
430
+ req.on('data', (chunk: Buffer) => {
431
+ body += chunk.toString();
432
+ });
433
+
434
+ req.on('end', () => {
435
+ try {
436
+ const mockData = JSON.parse(body);
437
+ const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
438
+
439
+ res.setHeader('Content-Type', 'application/json');
440
+ res.end(JSON.stringify(result));
441
+ } catch (error) {
442
+ res.statusCode = 400;
443
+ res.setHeader('Content-Type', 'application/json');
444
+ res.end(JSON.stringify({
445
+ success: false,
446
+ error: `Invalid JSON: ${(error as Error).message}`,
447
+ }));
448
+ }
449
+ });
450
+ return;
451
+ }
452
+
453
+ // Handle GET endpoint for sync status
454
+ if (url === '/mockifyer-sync/status' && req.method === 'GET') {
455
+ const currentScenario = getCurrentScenario(mockDataPath);
456
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
457
+ const files = fs.existsSync(scenarioPath)
458
+ ? fs.readdirSync(scenarioPath).filter((f: string) => f.endsWith('.json'))
459
+ : [];
460
+
461
+ res.setHeader('Content-Type', 'application/json');
462
+ res.end(JSON.stringify({
463
+ success: true,
464
+ scenario: currentScenario,
465
+ fileCount: files.length,
466
+ files: files.slice(0, 10), // Return first 10 files
467
+ }));
468
+ return;
469
+ }
470
+
471
+ // Handle GET endpoint for sync (legacy polling-based sync)
472
+ if (url === '/mockifyer-sync' && req.method === 'GET') {
473
+ const result = syncFromIOSSimulator(projectRoot, mockDataPath);
474
+ res.setHeader('Content-Type', 'application/json');
475
+ res.end(JSON.stringify(result));
476
+ return;
477
+ }
478
+
479
+ // Handle GET endpoint for scenario config
480
+ if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
481
+ try {
482
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
483
+ if (fs.existsSync(configPath)) {
484
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
485
+ res.setHeader('Content-Type', 'application/json');
486
+ res.end(JSON.stringify(config));
487
+ } else {
488
+ res.setHeader('Content-Type', 'application/json');
489
+ res.end(JSON.stringify({ currentScenario: DEFAULT_SCENARIO }));
490
+ }
491
+ } catch (error) {
492
+ res.statusCode = 500;
493
+ res.setHeader('Content-Type', 'application/json');
494
+ res.end(JSON.stringify({ success: false, error: (error as Error).message }));
495
+ }
496
+ return;
497
+ }
498
+
499
+ // Handle POST endpoint for scenario config sync
500
+ if (url === '/mockifyer-scenario-config' && req.method === 'POST') {
501
+ let body = '';
502
+ req.on('data', (chunk: Buffer) => {
503
+ body += chunk.toString();
504
+ });
505
+ req.on('end', () => {
506
+ try {
507
+ const config = JSON.parse(body);
508
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
509
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
510
+ res.setHeader('Content-Type', 'application/json');
511
+ res.end(JSON.stringify({ success: true }));
512
+ } catch (error) {
513
+ res.statusCode = 400;
514
+ res.setHeader('Content-Type', 'application/json');
515
+ res.end(JSON.stringify({ success: false, error: (error as Error).message }));
516
+ }
517
+ });
518
+ return;
519
+ }
520
+
521
+ // Continue to next middleware if not handled
522
+ next();
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Start auto-sync from iOS Simulator
528
+ */
529
+ export function startAutoSync(
530
+ intervalMs: number = 5000,
531
+ options?: MetroSyncMiddlewareOptions
532
+ ): void {
533
+ if (autoSyncInterval) {
534
+ console.log('[MockSync] Auto-sync already running');
535
+ return;
536
+ }
537
+
538
+ const projectRoot = options?.projectRoot || process.cwd();
539
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
540
+
541
+ console.log(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
542
+ autoSyncInterval = setInterval(() => {
543
+ syncFromIOSSimulator(projectRoot, mockDataPath);
544
+ }, intervalMs);
545
+ }
546
+
547
+ /**
548
+ * Stop auto-sync
549
+ */
550
+ export function stopAutoSync(): void {
551
+ if (autoSyncInterval) {
552
+ clearInterval(autoSyncInterval);
553
+ autoSyncInterval = null;
554
+ console.log('[MockSync] Auto-sync disabled');
555
+ }
556
+ }
557
+
558
+ // Export sync function for manual use
559
+ export { syncFromIOSSimulator };
560
+