vite-plugin-automock 1.1.5 → 1.2.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.
package/README.md CHANGED
@@ -6,13 +6,14 @@ Effortless API mock auto-generation for legacy projects. No manual files, just a
6
6
 
7
7
  ## Features
8
8
 
9
- - 🚀 Automatically captures API requests and generates local mock data
10
- - 🏆 Perfect for legacy projects, easily backfill missing mocks
11
- - 🛠️ Supports manual mock file creation with a simple format
12
- - Zero-config, plug-and-play
13
- - 🧩 Fully compatible with the Vite plugin ecosystem
14
- - 📦 Production-ready with client-side interceptor
15
- - 🎛️ Visual mock inspector panel
9
+ - Automatically captures API requests and generates local mock data
10
+ - Perfect for legacy projects, easily backfill missing mocks
11
+ - Supports manual mock file creation with a simple format
12
+ - Fine-grained control: enable/disable mock, proxy, and capture independently
13
+ - Visual mock inspector panel for managing mock files
14
+ - Production-ready with client-side interceptor (Axios / PureHttp)
15
+ - Fully compatible with the Vite plugin ecosystem
16
+ - Zero-config, plug-and-play
16
17
 
17
18
  ## Installation
18
19
 
@@ -26,8 +27,6 @@ yarn add -D vite-plugin-automock
26
27
 
27
28
  ## Quick Start
28
29
 
29
- ### 1. Configure Vite Plugin
30
-
31
30
  ```typescript
32
31
  // vite.config.ts
33
32
  import { automock } from 'vite-plugin-automock'
@@ -35,36 +34,136 @@ import { automock } from 'vite-plugin-automock'
35
34
  export default defineConfig({
36
35
  plugins: [
37
36
  automock({
37
+ proxyBaseUrl: 'https://api.example.com', // Required for proxy/capture
38
+ })
39
+ ]
40
+ })
41
+ ```
42
+
43
+ That's it! The plugin will:
44
+
45
+ 1. Intercept requests matching `apiPrefix` (default `/api`)
46
+ 2. Return mock data if a mock file exists
47
+ 3. Proxy to `proxyBaseUrl` and auto-save the response as a mock file
48
+
49
+ ## Configuration Options
50
+
51
+ ### Plugin Options
52
+
53
+ | Option | Type | Required | Default | Description |
54
+ | ------ | ---- | -------- | ------- | ----------- |
55
+ | `proxyBaseUrl` | `string` | No | - | Base URL of your API server. Required only when `proxy` or `capture` is used |
56
+ | `mockDir` | `string` | No | `'mock'` | Directory to store mock files |
57
+ | `apiPrefix` | `string` | No | `'/api'` | API path prefix to intercept |
58
+ | `pathRewrite` | `(path: string) => string` | No | `(path) => path` | Function to rewrite request paths |
59
+ | `enabled` | `boolean` | No | `true` | Global switch. When `false`, all requests pass through without mock handling |
60
+ | `proxy` | `boolean` | No | `true` | Whether to proxy unmatched requests to `proxyBaseUrl` |
61
+ | `capture` | `boolean` | No | `true` | Whether to auto-capture proxy responses and save as mock files |
62
+ | `productionMock` | `boolean \| 'auto'` | No | `false` | Enable client-side mock bundle support |
63
+ | `inspector` | `boolean \| InspectorOptions` | No | `false` | Enable visual mock inspector UI |
64
+
65
+ ### Bundle Options
66
+
67
+ These options are available when using the `automock()` function (which includes bundle support):
68
+
69
+ | Option | Type | Default | Description |
70
+ | ------ | ---- | ------- | ----------- |
71
+ | `bundleMockData` | `boolean` | `true` | Whether to bundle mock data for production |
72
+ | `bundleOutputPath` | `string` | `'public/mock-data.json'` | Output path for the mock bundle file |
73
+
74
+ For a complete explanation of option interactions, see [Configuration Guide](docs/CONFIGURATION_CN.md).
75
+
76
+ ### Inspector Options
77
+
78
+ When `inspector` is an object:
79
+
80
+ | Option | Type | Default | Description |
81
+ | ------ | ---- | ------- | ----------- |
82
+ | `route` | `string` | `'/__mock/'` | Route path for the inspector UI |
83
+ | `enableToggle` | `boolean` | `true` | Allow toggling mock enable/disable in the UI |
84
+
85
+ ### Full Configuration Example
86
+
87
+ ```typescript
88
+ import { automock } from 'vite-plugin-automock'
89
+
90
+ export default defineConfig({
91
+ plugins: [
92
+ automock({
93
+ // Basic
94
+ proxyBaseUrl: 'https://api.example.com',
38
95
  mockDir: 'mock',
39
96
  apiPrefix: '/api',
40
- bundleMockData: true, // Bundle mock data for production
41
- productionMock: true, // Enable mock in production
42
- proxyBaseUrl: 'https://api.example.com'
97
+ pathRewrite: (path) => path.replace(/^\/api/, ''),
98
+
99
+ // Fine-grained control
100
+ enabled: true,
101
+ proxy: true,
102
+ capture: true,
103
+
104
+ // Production
105
+ productionMock: 'auto',
106
+ bundleMockData: true,
107
+ bundleOutputPath: 'public/mock-data.json',
108
+
109
+ // Inspector
110
+ inspector: {
111
+ route: '/__mock/',
112
+ enableToggle: true,
113
+ },
43
114
  })
44
115
  ]
45
116
  })
46
117
  ```
47
118
 
48
- ### 2. Create Mock Files
119
+ ## Behavior Modes
120
+
121
+ The `enabled`, `proxy`, and `capture` options control different parts of the development middleware. `enabled=false` is a global bypass: the plugin will not read mocks, proxy, or capture.
122
+
123
+ ### Mock-only Mode
124
+
125
+ Only return mock data, never proxy to backend. Useful when you want strict offline development:
49
126
 
50
127
  ```typescript
51
- // mock/users.ts
52
- import { MockFileConfig } from 'vite-plugin-automock'
128
+ automock({
129
+ proxyBaseUrl: 'https://api.example.com',
130
+ enabled: true, // Intercept requests
131
+ proxy: false, // Don't proxy to backend
132
+ capture: false, // Don't save new mocks
133
+ })
134
+ ```
53
135
 
54
- export default {
55
- enable: true,
56
- data: { users: [{ id: 1, name: 'Alice' }] },
57
- delay: 100,
58
- status: 200
59
- } as MockFileConfig
136
+ ### Pass-through Mode
137
+
138
+ Bypass all automock handling and let later Vite middleware, including `server.proxy`, handle the request:
139
+
140
+ ```typescript
141
+ automock({
142
+ enabled: false,
143
+ })
144
+ ```
145
+
146
+ ### Default Mode (Recommended)
147
+
148
+ All features enabled - mock first, proxy fallback, auto-capture:
149
+
150
+ ```typescript
151
+ automock({
152
+ proxyBaseUrl: 'https://api.example.com',
153
+ // enabled: true (default)
154
+ // proxy: true (default)
155
+ // capture: true (default)
156
+ })
60
157
  ```
61
158
 
62
- ### 3. Initialize Client Interceptor
159
+ ## Client API Reference
63
160
 
64
- For PureHttp wrapper:
161
+ The client-side interceptor is used for **production mode** mock support. Import from `vite-plugin-automock/client`.
162
+
163
+ ### For PureHttp Wrapper
65
164
 
66
165
  ```typescript
67
- // src/main.ts or src/api/index.ts
166
+ // src/main.ts
68
167
  import {
69
168
  initMockInterceptorForPureHttp,
70
169
  setMockEnabled,
@@ -77,12 +176,8 @@ registerHttpInstance(http)
77
176
 
78
177
  // Initialize mock interceptor
79
178
  initMockInterceptorForPureHttp()
80
- .then(() => {
81
- console.log('[MockInterceptor] Initialized successfully')
82
- })
83
- .catch(error => {
84
- console.error('[MockInterceptor] Failed to initialize:', error)
85
- })
179
+ .then(() => console.log('[MockInterceptor] Initialized'))
180
+ .catch(error => console.error('[MockInterceptor] Failed:', error))
86
181
 
87
182
  // Enable mock in development
88
183
  if (import.meta.env.DEV) {
@@ -90,167 +185,94 @@ if (import.meta.env.DEV) {
90
185
  }
91
186
  ```
92
187
 
93
- For plain Axios:
188
+ ### For Plain Axios
94
189
 
95
190
  ```typescript
96
191
  // src/main.ts
97
192
  import { initMockInterceptor, setMockEnabled } from 'vite-plugin-automock/client'
98
193
  import axios from 'axios'
99
194
 
100
- // Initialize with axios instance
101
195
  initMockInterceptor(axios)
102
- .then(() => {
103
- console.log('[MockInterceptor] Initialized successfully')
104
- })
105
- .catch(error => {
106
- console.error('[MockInterceptor] Failed to initialize:', error)
107
- })
196
+ .then(() => console.log('[MockInterceptor] Initialized'))
197
+ .catch(error => console.error('[MockInterceptor] Failed:', error))
108
198
 
109
- // Enable mock in development
110
199
  if (import.meta.env.DEV) {
111
200
  setMockEnabled(true)
112
201
  }
113
202
  ```
114
203
 
115
- ## Documentation
116
-
117
- For detailed usage instructions, configuration options, and examples, see:
118
-
119
- **[📚 Complete Usage Guide](./docs/USAGE_GUIDE.md)**
120
-
121
- Topics covered:
122
- - Development vs Production modes
123
- - Client interceptor configuration
124
- - Runtime mock toggle
125
- - Visual inspector
126
- - API reference
127
- - Common scenarios
128
-
129
- ---
130
-
131
- ## Basic Usage (Development Mode)
204
+ ### Client Exports
132
205
 
133
- Import and register the plugin in your `vite.config.ts`:
206
+ | Export | Type | Description |
207
+ | ------ | ---- | ----------- |
208
+ | `initMockInterceptor` | `(axios: AxiosInstance) => Promise<void>` | Initialize interceptor with an Axios instance |
209
+ | `initMockInterceptorForPureHttp` | `() => Promise<void>` | Initialize interceptor for PureHttp (call `registerHttpInstance` first) |
210
+ | `registerHttpInstance` | `(http: { constructor: { axiosInstance: AxiosInstance } }) => void` | Register a PureHttp instance |
211
+ | `setMockEnabled` | `(enabled: boolean) => void` | Enable/disable mock at runtime |
212
+ | `isMockEnabled` | `() => boolean` | Check if mock is currently enabled |
213
+ | `loadMockData` | `() => Promise<Record<string, MockBundleData>>` | Load mock data from the bundled JSON file |
214
+ | `createMockInterceptor` | `(options: MockInterceptorOptions) => MockInterceptor` | Create a custom interceptor instance |
134
215
 
135
- ```js
136
- import { automock } from "vite-plugin-automock";
216
+ ### MockInterceptorOptions
137
217
 
138
- export default {
139
- plugins: [
140
- automock({
141
- proxyBaseUrl: "http://localhost:8888", // Required: Your API server URL
142
- mockDir: "mock", // Optional: Directory for mock files (default: 'mock')
143
- apiPrefix: "/api", // Optional: API prefix to intercept (default: '/api')
144
- pathRewrite: (path) => path, // Optional: Path rewrite function
145
- inspector: true, // Optional: Enable visual inspector (default: false)
146
- }),
147
- ],
148
- };
149
- ```
150
-
151
- ### With Custom Inspector Configuration
218
+ ```typescript
219
+ interface MockInterceptorOptions {
220
+ mockData: Record<string, MockBundleData>
221
+ enabled?: boolean | (() => boolean)
222
+ onMockHit?: (url: string, method: string, mock: MockBundleData) => void
223
+ onBypass?: (url: string, method: string, reason: string) => void
224
+ }
152
225
 
153
- ```js
154
- automock({
155
- proxyBaseUrl: "http://localhost:8888",
156
- inspector: {
157
- route: "/__inspector/", // Custom route for inspector UI
158
- enableToggle: true, // Allow toggling enable/disable
159
- },
160
- });
226
+ interface MockBundleData {
227
+ enable: boolean
228
+ data: unknown
229
+ delay?: number
230
+ status?: number
231
+ isBinary?: boolean
232
+ }
161
233
  ```
162
234
 
163
- ## Configuration Options
235
+ ## Production Mode
164
236
 
165
- | Option | Type | Required | Default | Description |
166
- | -------------- | ----------------- | -------- | ---------------- | --------------------------------- |
167
- | `proxyBaseUrl` | string | ✅ | - | Base URL of your API server |
168
- | `mockDir` | string | ❌ | `'mock'` | Directory to store mock files |
169
- | `apiPrefix` | string | ❌ | `'/api'` | API path prefix to intercept |
170
- | `pathRewrite` | function | ❌ | `(path) => path` | Function to rewrite request paths |
171
- | `inspector` | boolean \| object | ❌ | `false` | Enable visual mock inspector UI |
237
+ To use mock data in production builds:
172
238
 
173
- ## Common Pitfalls
174
-
175
- ### ⚠️ Dual Proxy Configuration
176
-
177
- **Do NOT** configure both Vite's `server.proxy` and automock's `proxyBaseUrl` for the same API prefix. This will cause conflicts and requests may hang.
178
-
179
- **❌ Wrong:**
180
- ```typescript
181
- export default defineConfig({
182
- plugins: [
183
- automock({
184
- proxyBaseUrl: "http://localhost:8888",
185
- apiPrefix: "/api",
186
- })
187
- ],
188
- server: {
189
- proxy: {
190
- "/api": { // ❌ CONFLICTS with automock
191
- target: "http://localhost:8888",
192
- changeOrigin: true,
193
- }
194
- }
195
- }
196
- })
197
- ```
239
+ 1. Enable `productionMock` and `bundleMockData`:
198
240
 
199
- **✅ Correct:**
200
241
  ```typescript
201
- export default defineConfig({
202
- plugins: [
203
- automock({
204
- proxyBaseUrl: "http://localhost:8888",
205
- apiPrefix: "/api",
206
- })
207
- ],
208
- // ✅ Remove server.proxy or use a different prefix
242
+ automock({
243
+ proxyBaseUrl: 'https://api.example.com',
244
+ productionMock: true, // or 'auto'
245
+ bundleMockData: true, // default
246
+ bundleOutputPath: 'public/mock-data.json',
209
247
  })
210
248
  ```
211
249
 
212
- The plugin will automatically warn you if a conflicting proxy configuration is detected.
250
+ 2. The plugin will generate `public/mock-data.json` at build time containing all mock data.
213
251
 
214
- ### Inspector Options
252
+ 3. Initialize the client interceptor in your app (see [Client API Reference](#client-api-reference)).
215
253
 
216
- When `inspector` is an object, you can customize:
254
+ 4. The `productionMock: 'auto'` option enables mock outside `production` mode and disables it in `production` mode.
217
255
 
218
- | Option | Type | Default | Description |
219
- | -------------- | ------- | ------------ | ---------------------------------- |
220
- | `route` | string | `'/__mock/'` | Route path for the inspector UI |
221
- | `enableToggle` | boolean | `true` | Allow toggling mock enable/disable |
256
+ ## Mock Inspector
222
257
 
223
- ## Mock Inspector 🎨
258
+ The visual inspector provides a web UI to manage mock files:
224
259
 
225
- **NEW!** Visual interface to manage your mock files:
226
-
227
- ```js
260
+ ```typescript
228
261
  automock({
229
- proxyBaseUrl: "http://localhost:8888",
230
- inspector: true, // Enable inspector UI
231
- });
262
+ proxyBaseUrl: 'https://api.example.com',
263
+ inspector: true, // or { route: '/__mock/', enableToggle: true }
264
+ })
232
265
  ```
233
266
 
234
267
  Then visit `http://localhost:5173/__mock/` to:
235
268
 
236
- - 📋 **Browse** all mock files organized by URL
237
- - 🎛️ **Toggle** mock enable/disable status
238
- - ⏱️ **Adjust** response delay and status codes
239
- - ✏️ **Edit** JSON response data directly
240
- - 💾 **Save** changes with a single click
241
-
242
- ![Inspector Demo](https://via.placeholder.com/800x400?text=Mock+Inspector+UI)
243
-
244
- ## How It Works
245
-
246
- 1. **Request Interception**: The plugin intercepts all requests matching the `apiPrefix`
247
- 2. **Mock Check**: Checks if a corresponding mock file exists
248
- 3. **Conditional Response**:
249
- - If mock exists → Returns mock data
250
- - If mock doesn't exist → Proxies to real API and saves response as mock
251
- 4. **Auto-Generation**: Real API responses are automatically saved as mock files
252
- 5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
253
- 6. **Visual Inspector**: Manage and edit mocks through the web UI
269
+ - **Browse** all mock files organized by URL
270
+ - **Toggle** mock enable/disable status
271
+ - **Adjust** response delay and status codes
272
+ - **Edit** JSON response data directly
273
+ - **Create** new mock files
274
+ - **Delete** existing mock files
275
+ - **Batch update** multiple mocks at once
254
276
 
255
277
  ## Mock File Structure
256
278
 
@@ -267,7 +289,7 @@ mock/
267
289
  │ └── post.js # POST /api/items
268
290
  ```
269
291
 
270
- Each mock file exports an object with this structure:
292
+ Each mock file exports an object:
271
293
 
272
294
  ```javascript
273
295
  /**
@@ -275,9 +297,8 @@ Each mock file exports an object with this structure:
275
297
  * Generated at 2025-01-11T10:30:00.000Z
276
298
  */
277
299
  export default {
278
- enable: false, // Whether to use this mock (default: false)
300
+ enable: false, // Whether to use this mock
279
301
  data: {
280
- // Response data
281
302
  code: 0,
282
303
  message: "success",
283
304
  data: [
@@ -285,55 +306,77 @@ export default {
285
306
  { id: 2, name: "User 2" },
286
307
  ],
287
308
  },
288
- delay: 0, // Artificial delay in milliseconds
309
+ delay: 0, // Artificial delay in milliseconds
289
310
  status: 200, // HTTP status code
290
- };
311
+ }
291
312
  ```
292
313
 
293
- ## Quick Start
314
+ ### Dynamic Mock Data
294
315
 
295
- 1. **Try the Example**:
316
+ ```javascript
317
+ export default {
318
+ enable: true,
319
+ data: () => ({
320
+ timestamp: new Date().toISOString(),
321
+ randomId: Math.floor(Math.random() * 1000),
322
+ }),
323
+ }
324
+ ```
296
325
 
297
- ```bash
298
- pnpm run example
299
- ```
326
+ ## Common Pitfalls
300
327
 
301
- This starts the playground with a demo API server.
328
+ ### Dual Proxy Configuration
302
329
 
303
- 2. **Manual Setup**:
330
+ **Do NOT** configure both Vite's `server.proxy` and automock's `proxyBaseUrl` for the same API prefix:
331
+
332
+ ```typescript
333
+ // ❌ Wrong - will cause request conflicts
334
+ export default defineConfig({
335
+ plugins: [
336
+ automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
337
+ ],
338
+ server: {
339
+ proxy: {
340
+ '/api': { target: 'http://localhost:8888', changeOrigin: true } // CONFLICTS
341
+ }
342
+ }
343
+ })
304
344
 
305
- ```bash
306
- # Install the plugin
307
- pnpm add -D vite-plugin-automock
345
+ // ✅ Correct - use automock for /api, remove server.proxy
346
+ export default defineConfig({
347
+ plugins: [
348
+ automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
349
+ ]
350
+ })
351
+ ```
308
352
 
309
- # Add to your vite.config.js
310
- import { automock } from "vite-plugin-automock";
353
+ The plugin will automatically warn you if a conflicting proxy is detected.
311
354
 
312
- export default {
313
- plugins: [
314
- automock({
315
- proxyBaseUrl: "http://localhost:8888"
316
- })
317
- ]
318
- };
319
- ```
355
+ ## How It Works
320
356
 
321
- 3. **Start Development**:
322
- - Start your API server
323
- - Start Vite dev server
324
- - Make API calls from your frontend
325
- - Check the mock directory for generated files
357
+ 1. **Request Interception**: The plugin intercepts all requests matching `apiPrefix`
358
+ 2. **Mock Check**: Checks if a corresponding mock file exists and is enabled
359
+ 3. **Conditional Response**:
360
+ - Mock exists and enabled -> Returns mock data
361
+ - Mock exists but disabled -> Skips to proxy or next middleware
362
+ - Mock doesn't exist -> Proxies to real API (if `proxy: true`)
363
+ 4. **Auto-Capture**: Real API responses are automatically saved as mock files (if `capture: true`)
364
+ 5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
365
+ 6. **Bundle**: Mock data is bundled into JSON for production use
326
366
 
327
367
  ## Comparison with Traditional Mock Plugins
328
368
 
329
- | Feature | Traditional Mock Plugins | vite-plugin-automock |
330
- | ---------------------- | ------------------------ | -------------------- |
331
- | Auto backfill | | |
332
- | Legacy project support | | |
333
- | Manual mock files | | |
334
- | Config complexity | High | Very low |
335
- | Zero setup | | |
336
- | Real API integration | | |
369
+ | Feature | Traditional Mock Plugins | vite-plugin-automock |
370
+ | ------- | ----------------------- | -------------------- |
371
+ | Auto backfill | - | Yes |
372
+ | Legacy project support | - | Yes |
373
+ | Manual mock files | Yes | Yes |
374
+ | Config complexity | High | Very low |
375
+ | Zero setup | - | Yes |
376
+ | Real API integration | - | Yes |
377
+ | Fine-grained control | - | Yes |
378
+ | Visual inspector | - | Yes |
379
+ | Production mock | - | Yes |
337
380
 
338
381
  ## When to Use
339
382
 
@@ -343,45 +386,6 @@ export default {
343
386
  - **Testing**: Consistent test data without external dependencies
344
387
  - **Demo/Presentation**: Reliable demo data that doesn't change
345
388
 
346
- ## Advanced Usage
347
-
348
- ### Custom Path Rewriting
349
-
350
- ```javascript
351
- automock({
352
- proxyBaseUrl: "http://api.example.com",
353
- pathRewrite: (path) => {
354
- // Remove /api prefix when proxying
355
- return path.replace(/^\/api/, "");
356
- },
357
- });
358
- ```
359
-
360
- ### Conditional Mock Enabling
361
-
362
- ```javascript
363
- // In your mock file
364
- export default {
365
- enable: process.env.NODE_ENV === "development",
366
- data: {
367
- /* mock data */
368
- },
369
- };
370
- ```
371
-
372
- ### Dynamic Mock Data
373
-
374
- ```javascript
375
- // In your mock file
376
- export default {
377
- enable: true,
378
- data: () => ({
379
- timestamp: new Date().toISOString(),
380
- randomId: Math.floor(Math.random() * 1000),
381
- }),
382
- };
383
- ```
384
-
385
389
  ## Contributing
386
390
 
387
391
  We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.