@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,184 @@
1
+ /**
2
+ * React Native/Expo Helper Functions
3
+ *
4
+ * Simplified setup for React Native applications with automatic
5
+ * conditional provider selection (FileSystem in dev, Memory in prod)
6
+ */
7
+
8
+ import { setupMockifyer } from './index';
9
+ import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@sgedda/mockifyer-core';
10
+ import type { MockifyerConfig } from '@sgedda/mockifyer-core';
11
+
12
+ // Re-export MockifyerInstance type to avoid circular dependency
13
+ export interface MockifyerInstance extends HTTPClient {
14
+ reloadMockData: () => void;
15
+ clearStaleCacheEntries: () => number;
16
+ clearAllMocks: () => Promise<void>;
17
+ }
18
+
19
+ export interface ReactNativeMockifyerConfig {
20
+ /** Whether we're in development mode (determines which provider to use) */
21
+ isDev: boolean;
22
+ /** Path to mock data directory (used in development) */
23
+ mockDataPath?: string;
24
+ /** Path to bundled mock data file (used in production) */
25
+ bundledDataPath?: string;
26
+ /** Enable recording mode (development only) */
27
+ recordMode?: boolean;
28
+ /** Additional Mockifyer config options */
29
+ config?: Partial<Parameters<typeof setupMockifyer>[0]>;
30
+ }
31
+
32
+ // Lazy load bundled data (only used in production builds)
33
+ let bundledMockData: MockData[] | null = null;
34
+
35
+ /**
36
+ * Load bundled mock data from a TypeScript/JavaScript module
37
+ *
38
+ * Note: For React Native/Metro, we need to handle dynamic imports differently
39
+ * Metro doesn't support dynamic require() with variables, so we use a workaround
40
+ */
41
+ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]> {
42
+ if (bundledMockData) {
43
+ return bundledMockData;
44
+ }
45
+
46
+ try {
47
+ // Metro bundler doesn't support dynamic require() with variables
48
+ // We use eval with a fully constructed string to avoid Metro's static analysis
49
+ // This bypasses Metro's static analysis completely
50
+ const r = 'r';
51
+ const e = 'e';
52
+ const q = 'q';
53
+ const u = 'u';
54
+ const i = 'i';
55
+ const req = r + e + q + u + i + r + e;
56
+ // eslint-disable-next-line no-eval
57
+ const module = eval(`${req}(${JSON.stringify(bundledDataPath)})`);
58
+
59
+ const data = Array.isArray(module.mockData)
60
+ ? module.mockData
61
+ : [module.mockData];
62
+
63
+ bundledMockData = data;
64
+ return data;
65
+ } catch (error) {
66
+ console.warn('[Mockifyer] Could not load bundled mock data:', error);
67
+ return [];
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
73
+ *
74
+ * - Development (isDev === true): Uses Expo FileSystem provider - can record mocks
75
+ * - Production (isDev === false): Uses Memory provider with bundled TypeScript file
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
80
+ *
81
+ * await setupMockifyerForReactNative({
82
+ * isDev: __DEV__, // Pass React Native's __DEV__ variable
83
+ * mockDataPath: 'mock-data',
84
+ * bundledDataPath: './assets/mock-data',
85
+ * recordMode: process.env.MOCKIFYER_RECORD === 'true',
86
+ * });
87
+ * ```
88
+ */
89
+ export async function setupMockifyerForReactNative(
90
+ options: ReactNativeMockifyerConfig
91
+ ): Promise<MockifyerInstance | null> {
92
+ const {
93
+ isDev,
94
+ mockDataPath = 'mock-data',
95
+ bundledDataPath = './assets/mock-data',
96
+ recordMode = false,
97
+ config = {},
98
+ } = options;
99
+
100
+ // Check if Mockifyer is enabled
101
+ const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
102
+ if (!isEnabled) {
103
+ console.log('[Mockifyer] Disabled');
104
+ return null;
105
+ }
106
+
107
+ if (isDev === true) {
108
+ // DEVELOPMENT MODE (React Native app running in dev)
109
+ // Use Hybrid provider - saves to both device AND project folder simultaneously
110
+ // Files are immediately available in project folder (no polling needed)
111
+ // Note: The provider's initialize() is async and will be handled by the provider methods
112
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
113
+
114
+ // Merge database provider config from options if provided
115
+ const baseDatabaseProvider = {
116
+ type: 'hybrid' as const,
117
+ path: mockDataPath,
118
+ options: {
119
+ metroPort,
120
+ },
121
+ };
122
+
123
+ // Merge with config.databaseProvider if provided
124
+ const databaseProviderConfig = config.databaseProvider
125
+ ? {
126
+ ...baseDatabaseProvider,
127
+ ...config.databaseProvider,
128
+ options: {
129
+ ...baseDatabaseProvider.options,
130
+ ...(config.databaseProvider.options || {}),
131
+ metroPort, // Always ensure metroPort is set
132
+ },
133
+ }
134
+ : baseDatabaseProvider;
135
+
136
+ const instance = setupMockifyer({
137
+ mockDataPath,
138
+ databaseProvider: databaseProviderConfig,
139
+ recordMode,
140
+ useGlobalFetch: true,
141
+ ...config,
142
+ });
143
+
144
+ console.log('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
145
+ console.log(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
146
+ if (recordMode) {
147
+ console.log('[Mockifyer] Recording mode enabled - new API responses will be saved');
148
+ }
149
+
150
+ return instance;
151
+ } else {
152
+ // PRODUCTION BUILD MODE
153
+ // Use Memory provider with bundled TypeScript file
154
+ const provider = new MemoryProvider({});
155
+ provider.initialize();
156
+
157
+ // Load bundled mock data
158
+ const mockDataArray = await loadBundledMockData(bundledDataPath);
159
+
160
+ if (mockDataArray.length === 0) {
161
+ console.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
162
+ return null;
163
+ }
164
+
165
+ // Pre-load all mocks into memory
166
+ for (const mockData of mockDataArray) {
167
+ provider.save(mockData);
168
+ }
169
+
170
+ const instance = setupMockifyer({
171
+ mockDataPath: './mock-data', // Not used with memory provider
172
+ databaseProvider: {
173
+ type: 'memory',
174
+ },
175
+ recordMode: false, // Can't record in production builds
176
+ useGlobalFetch: true,
177
+ ...config,
178
+ });
179
+
180
+ console.log(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
181
+ return instance;
182
+ }
183
+ }
184
+
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Test generation hook for Metro sync middleware
3
+ *
4
+ * This is a separate module that can be used as a callback with the Metro sync middleware
5
+ * to generate tests when mocks are saved. This keeps test generation separate from the
6
+ * core sync functionality.
7
+ */
8
+
9
+ import * as fs from 'fs';
10
+ import * as path from 'path';
11
+ import { TestGenerator, TestGenerationOptions, MockData } from '@sgedda/mockifyer-core';
12
+
13
+ export interface TestGenerationHookOptions {
14
+ /** Project root directory */
15
+ projectRoot: string;
16
+ /** Test framework to use */
17
+ framework?: 'jest' | 'vitest' | 'mocha';
18
+ /** Output path for generated tests */
19
+ outputPath?: string;
20
+ /** Test file naming pattern */
21
+ testPattern?: string;
22
+ /** Include setup code in generated tests */
23
+ includeSetup?: boolean;
24
+ /** Group tests by: 'endpoint', 'scenario', or 'file' */
25
+ groupBy?: 'endpoint' | 'scenario' | 'file';
26
+ /** HTTP client type */
27
+ httpClientType?: 'fetch' | 'axios';
28
+ /** If true, only generate one test per endpoint */
29
+ uniqueTestsPerEndpoint?: boolean;
30
+ }
31
+
32
+ /**
33
+ * Creates a test generation hook function that can be used with Metro sync middleware
34
+ */
35
+ export function createTestGenerationHook(options: TestGenerationHookOptions) {
36
+ const {
37
+ projectRoot,
38
+ framework = 'jest',
39
+ outputPath = './tests/generated',
40
+ testPattern = '{endpoint}.test.ts',
41
+ includeSetup = true,
42
+ groupBy = 'endpoint',
43
+ httpClientType = 'fetch',
44
+ uniqueTestsPerEndpoint = false,
45
+ } = options;
46
+
47
+ return async (mockData: MockData, filePath: string) => {
48
+ try {
49
+ // Try to require TestGenerator from mockifyer-core
50
+ let TestGeneratorClass: typeof TestGenerator;
51
+ try {
52
+ let mockifyerCore;
53
+ try {
54
+ mockifyerCore = require('@sgedda/mockifyer-core');
55
+ } catch (e) {
56
+ // Fallback: try relative path (for local file: dependencies)
57
+ const corePath = path.join(projectRoot, '../../packages/mockifyer-core/dist/index.js');
58
+ if (fs.existsSync(corePath)) {
59
+ mockifyerCore = require(corePath);
60
+ } else {
61
+ throw new Error(`Could not find mockifyer-core at ${corePath}`);
62
+ }
63
+ }
64
+
65
+ TestGeneratorClass = mockifyerCore?.TestGenerator;
66
+
67
+ if (!TestGeneratorClass) {
68
+ const testGeneratorPath = path.join(projectRoot, '../../packages/mockifyer-core/dist/utils/test-generator.js');
69
+ if (fs.existsSync(testGeneratorPath)) {
70
+ const testGeneratorModule = require(testGeneratorPath);
71
+ TestGeneratorClass = testGeneratorModule.TestGenerator;
72
+ }
73
+ }
74
+ } catch (e) {
75
+ console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${(e as Error).message}`);
76
+ return;
77
+ }
78
+
79
+ if (!TestGeneratorClass) {
80
+ console.log('[MockSync] ⚠️ TestGenerator not available');
81
+ return;
82
+ }
83
+
84
+ const generator = new TestGeneratorClass();
85
+
86
+ const testOptions: TestGenerationOptions = {
87
+ framework,
88
+ outputPath,
89
+ testPattern,
90
+ includeSetup,
91
+ groupBy,
92
+ httpClientType,
93
+ uniqueTestsPerEndpoint,
94
+ };
95
+
96
+ const testInfo = generator.analyzeMock(mockData, httpClientType);
97
+ const testFilePath = generator.determineTestFilePath(mockData, testOptions);
98
+
99
+ const absoluteTestPath = path.resolve(projectRoot, testFilePath);
100
+ const testDir = path.dirname(absoluteTestPath);
101
+
102
+ // If uniqueTestsPerEndpoint is enabled, check if a test file already exists
103
+ if (uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
104
+ console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
105
+ return;
106
+ }
107
+
108
+ // Ensure test directory exists
109
+ if (!fs.existsSync(testDir)) {
110
+ fs.mkdirSync(testDir, { recursive: true });
111
+ }
112
+
113
+ const testCode = generator.generateTest(mockData, testOptions);
114
+
115
+ // Check if test file already exists
116
+ if (fs.existsSync(absoluteTestPath)) {
117
+ const testName = `${testInfo.method} ${testInfo.endpoint}`;
118
+
119
+ const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
120
+ if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
121
+ console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
122
+ return;
123
+ }
124
+
125
+ // Append test to existing file
126
+ const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
127
+ if (testMatch) {
128
+ const newTest = testMatch[0];
129
+ const updatedContent = existingContent.replace(
130
+ /(\s+)(\}\);?\s*)$/,
131
+ `$1${newTest}\n$1$2`
132
+ );
133
+ fs.writeFileSync(absoluteTestPath, updatedContent);
134
+ console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
135
+ }
136
+ } else {
137
+ // Create new test file
138
+ fs.writeFileSync(absoluteTestPath, testCode);
139
+ console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
140
+ }
141
+ } catch (error) {
142
+ console.error(`[MockSync] ❌ Error generating test:`, error);
143
+ }
144
+ };
145
+ }
146
+
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "lib": ["ES2020", "DOM"],
6
+ "declaration": true,
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "resolveJsonModule": true,
14
+ "moduleResolution": "node"
15
+ },
16
+ "include": ["src/**/*"],
17
+ "exclude": ["node_modules", "dist"]
18
+ }
19
+