vite-plugin-automock 1.0.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/dist/index.mjs ADDED
@@ -0,0 +1,2682 @@
1
+ import {
2
+ createMockInterceptor,
3
+ initMockInterceptor,
4
+ initMockInterceptorForPureHttp,
5
+ isMockEnabled,
6
+ loadMockData,
7
+ registerHttpInstance,
8
+ setMockEnabled
9
+ } from "./chunk-NWIN2A3G.mjs";
10
+ import {
11
+ buildMockIndex,
12
+ parseMockModule,
13
+ saveMockData,
14
+ writeMockFile
15
+ } from "./chunk-KZB7ARYV.mjs";
16
+
17
+ // src/index.ts
18
+ import path4 from "path";
19
+ import fs3 from "fs-extra";
20
+
21
+ // src/middleware.ts
22
+ import chokidar from "chokidar";
23
+ import debounce from "lodash.debounce";
24
+ import path2 from "path";
25
+ import fs from "fs-extra";
26
+ import http from "http";
27
+ import https from "https";
28
+
29
+ // src/inspector.ts
30
+ import path from "path";
31
+ var DEFAULT_ROUTE = "/__mock/";
32
+ function ensureTrailingSlash(route) {
33
+ return route.endsWith("/") ? route : `${route}/`;
34
+ }
35
+ function escapeHtml(value) {
36
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
37
+ }
38
+ function normalizeInspectorConfig(input) {
39
+ if (input === false || input === void 0) {
40
+ return { route: DEFAULT_ROUTE, enableToggle: true };
41
+ }
42
+ if (input === true) {
43
+ return { route: DEFAULT_ROUTE, enableToggle: true };
44
+ }
45
+ return {
46
+ route: ensureTrailingSlash(input.route ?? DEFAULT_ROUTE),
47
+ enableToggle: input.enableToggle ?? true
48
+ };
49
+ }
50
+ function createInspectorHandler(options) {
51
+ if (!options.inspector) {
52
+ return null;
53
+ }
54
+ const inspectorConfig = normalizeInspectorConfig(options.inspector);
55
+ const inspectorRoute = ensureTrailingSlash(inspectorConfig.route);
56
+ return async (req, res) => {
57
+ if (!req.url) {
58
+ return false;
59
+ }
60
+ const url = new URL(req.url, "http://localhost");
61
+ if (!url.pathname.startsWith(inspectorRoute)) {
62
+ return false;
63
+ }
64
+ await handleInspectorRequest({
65
+ req,
66
+ res,
67
+ mockDir: options.mockDir,
68
+ inspectorRoute,
69
+ apiPrefix: options.apiPrefix,
70
+ inspectorConfig,
71
+ getMockFileMap: options.getMockFileMap
72
+ });
73
+ return true;
74
+ };
75
+ }
76
+ async function handleInspectorRequest(context) {
77
+ const { req, res, inspectorRoute } = context;
78
+ const url = new URL(req.url || inspectorRoute, "http://localhost");
79
+ const normalizedRoute = ensureTrailingSlash(inspectorRoute);
80
+ if (url.pathname === normalizedRoute.slice(0, -1) || url.pathname === normalizedRoute) {
81
+ await serveInspectorHtml(context);
82
+ return;
83
+ }
84
+ const relativePath = url.pathname.startsWith(normalizedRoute) ? url.pathname.slice(normalizedRoute.length) : null;
85
+ if (relativePath && relativePath.startsWith("api/")) {
86
+ await handleInspectorApi({ ...context, pathname: relativePath.slice(4) });
87
+ return;
88
+ }
89
+ res.statusCode = 404;
90
+ res.end("Not Found");
91
+ }
92
+ async function serveInspectorHtml({
93
+ res,
94
+ inspectorRoute,
95
+ apiPrefix,
96
+ inspectorConfig
97
+ }) {
98
+ const routeJson = JSON.stringify(ensureTrailingSlash(inspectorRoute));
99
+ const allowToggleJson = JSON.stringify(inspectorConfig.enableToggle);
100
+ const apiPrefixEscaped = escapeHtml(apiPrefix);
101
+ const html = `<!DOCTYPE html>
102
+ <html lang="en">
103
+ <head>
104
+ <meta charset="UTF-8" />
105
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
106
+ <title>Mock Inspector</title>
107
+ <style>
108
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
109
+
110
+ :root {
111
+ --bg-primary: #ffffff;
112
+ --bg-secondary: #f9fafb;
113
+ --bg-tertiary: #f3f4f6;
114
+ --bg-hover: #e5e7eb;
115
+ --border-color: #e5e7eb;
116
+ --border-subtle: #f3f4f6;
117
+ --text-primary: #111827;
118
+ --text-secondary: #4b5563;
119
+ --text-muted: #9ca3af;
120
+ --accent-indigo: #6366f1;
121
+ --accent-indigo-light: #e0e7ff;
122
+ --accent-indigo-hover: #4f46e5;
123
+ --accent-emerald: #10b981;
124
+ --accent-emerald-light: #d1fae5;
125
+ --accent-amber: #f59e0b;
126
+ --accent-amber-light: #fef3c7;
127
+ --accent-rose: #ef4444;
128
+ --accent-rose-light: #fee2e2;
129
+ --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
130
+ --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
131
+ --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
132
+ --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
133
+ --radius-sm: 6px;
134
+ --radius-md: 8px;
135
+ --radius-lg: 12px;
136
+ }
137
+
138
+ * {
139
+ box-sizing: border-box;
140
+ }
141
+
142
+ body {
143
+ margin: 0;
144
+ background: linear-gradient(135deg, #f8fafc 0%, #e0e7ff 25%, #fdf4ff 50%, #ecfdf5 75%, #f0fdf4 100%);
145
+ color: var(--text-primary);
146
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
147
+ display: flex;
148
+ flex-direction: column;
149
+ height: 100vh;
150
+ overflow: hidden;
151
+ position: relative;
152
+ }
153
+
154
+ /* Multiple ambient gradient orbs */
155
+ body::before {
156
+ content: '';
157
+ position: fixed;
158
+ top: -15%;
159
+ right: -10%;
160
+ width: 60vw;
161
+ height: 60vw;
162
+ background: radial-gradient(circle, rgba(99, 102, 241, 0.25) 0%, rgba(139, 92, 246, 0.15) 30%, transparent 70%);
163
+ filter: blur(100px);
164
+ pointer-events: none;
165
+ z-index: 0;
166
+ animation: float 20s ease-in-out infinite;
167
+ }
168
+
169
+ body::after {
170
+ content: '';
171
+ position: fixed;
172
+ bottom: -15%;
173
+ left: -10%;
174
+ width: 50vw;
175
+ height: 50vw;
176
+ background: radial-gradient(circle, rgba(16, 185, 129, 0.2) 0%, rgba(34, 197, 94, 0.12) 30%, transparent 70%);
177
+ filter: blur(100px);
178
+ pointer-events: none;
179
+ z-index: 0;
180
+ animation: float 25s ease-in-out infinite reverse;
181
+ }
182
+
183
+ @keyframes float {
184
+ 0%, 100% { transform: translate(0, 0) scale(1); }
185
+ 33% { transform: translate(30px, -30px) scale(1.05); }
186
+ 66% { transform: translate(-20px, 20px) scale(0.95); }
187
+ }
188
+
189
+ /* Page load animation */
190
+ @keyframes fadeSlideIn {
191
+ from {
192
+ opacity: 0;
193
+ transform: translateY(8px);
194
+ }
195
+ to {
196
+ opacity: 1;
197
+ transform: translateY(0);
198
+ }
199
+ }
200
+
201
+ body > * {
202
+ animation: fadeSlideIn 0.3s ease-out backwards;
203
+ }
204
+
205
+ header {
206
+ padding: 1rem 1.5rem;
207
+ display: flex;
208
+ align-items: center;
209
+ gap: 1rem;
210
+ border-bottom: 1px solid rgba(99, 102, 241, 0.1);
211
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.85) 0%, rgba(238, 242, 255, 0.75) 50%, rgba(250, 245, 255, 0.85) 100%);
212
+ backdrop-filter: blur(20px);
213
+ flex-shrink: 0;
214
+ position: relative;
215
+ z-index: 1;
216
+ box-shadow: 0 4px 30px rgba(99, 102, 241, 0.1);
217
+ }
218
+
219
+ header h1 {
220
+ font-size: 1.1rem;
221
+ margin: 0;
222
+ font-weight: 600;
223
+ color: var(--text-primary);
224
+ letter-spacing: -0.01em;
225
+ background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #ec4899 100%);
226
+ -webkit-background-clip: text;
227
+ -webkit-text-fill-color: transparent;
228
+ background-clip: text;
229
+ }
230
+
231
+ main {
232
+ flex: 1;
233
+ display: grid;
234
+ grid-template-columns: var(--sidebar-width, 380px) 4px 1fr;
235
+ background: transparent;
236
+ min-height: 0;
237
+ overflow: hidden;
238
+ position: relative;
239
+ z-index: 1;
240
+ }
241
+
242
+ aside {
243
+ background: linear-gradient(180deg, rgba(238, 242, 255, 0.5) 0%, rgba(250, 245, 255, 0.4) 50%, rgba(236, 253, 245, 0.5) 100%);
244
+ backdrop-filter: blur(15px);
245
+ overflow-y: auto;
246
+ overflow-x: hidden;
247
+ min-width: 200px;
248
+ max-width: 800px;
249
+ height: 100%;
250
+ border-right: 1px solid rgba(99, 102, 241, 0.15);
251
+ }
252
+
253
+ aside::-webkit-scrollbar {
254
+ width: 6px;
255
+ }
256
+
257
+ aside::-webkit-scrollbar-track {
258
+ background: transparent;
259
+ }
260
+
261
+ aside::-webkit-scrollbar-thumb {
262
+ background: var(--border-color);
263
+ border-radius: 3px;
264
+ }
265
+
266
+ aside::-webkit-scrollbar-thumb:hover {
267
+ background: var(--text-muted);
268
+ }
269
+
270
+ .resizer {
271
+ background: var(--border-color);
272
+ cursor: col-resize;
273
+ position: relative;
274
+ user-select: none;
275
+ transition: all 0.2s ease;
276
+ }
277
+
278
+ .resizer:hover,
279
+ .resizer.active {
280
+ background: var(--accent-indigo);
281
+ }
282
+
283
+ .resizer::after {
284
+ content: '';
285
+ position: absolute;
286
+ left: 50%;
287
+ top: 50%;
288
+ transform: translate(-50%, -50%);
289
+ width: 3px;
290
+ height: 32px;
291
+ background: var(--text-muted);
292
+ border-radius: 2px;
293
+ opacity: 0;
294
+ transition: opacity 0.2s ease;
295
+ }
296
+
297
+ .resizer:hover::after,
298
+ .resizer.active::after {
299
+ opacity: 1;
300
+ background: white;
301
+ }
302
+
303
+ .global-controls {
304
+ padding: 0.75rem 1rem;
305
+ border-bottom: 1px solid var(--border-color);
306
+ display: flex;
307
+ gap: 0.5rem;
308
+ background: var(--bg-secondary);
309
+ position: sticky;
310
+ top: 0;
311
+ z-index: 10;
312
+ }
313
+
314
+ .global-controls .secondary {
315
+ flex: 1;
316
+ padding: 0.45rem 0.65rem;
317
+ font-size: 0.7rem;
318
+ display: flex;
319
+ align-items: center;
320
+ justify-content: center;
321
+ gap: 0.3rem;
322
+ font-weight: 500;
323
+ }
324
+
325
+ .global-controls .secondary:hover {
326
+ background: var(--accent-indigo-light);
327
+ border-color: var(--accent-indigo);
328
+ color: var(--accent-indigo);
329
+ }
330
+
331
+ /* Tree view styles */
332
+ .tree-node {
333
+ user-select: none;
334
+ }
335
+
336
+ .tree-node-content {
337
+ display: flex;
338
+ align-items: center;
339
+ padding: 0.4rem 0.6rem;
340
+ cursor: pointer;
341
+ transition: all 0.2s ease;
342
+ border-bottom: 1px solid var(--border-subtle);
343
+ position: relative;
344
+ }
345
+
346
+ .tree-node-content::before {
347
+ content: '';
348
+ position: absolute;
349
+ inset: 0;
350
+ background: linear-gradient(135deg, rgba(139, 92, 246, 0.15) 0%, rgba(236, 72, 153, 0.1) 100%);
351
+ opacity: 0;
352
+ transition: opacity 0.2s ease;
353
+ border-radius: var(--radius-sm);
354
+ }
355
+
356
+ .tree-node-content:hover::before {
357
+ opacity: 1;
358
+ }
359
+
360
+ .tree-node-content > * {
361
+ position: relative;
362
+ z-index: 1;
363
+ }
364
+
365
+ .tree-node-content.selected {
366
+ background: linear-gradient(135deg, rgba(139, 92, 246, 0.2) 0%, rgba(236, 72, 153, 0.15) 100%);
367
+ box-shadow: 0 4px 15px rgba(139, 92, 246, 0.25);
368
+ }
369
+
370
+ .tree-expand-icon {
371
+ width: 18px;
372
+ height: 18px;
373
+ display: flex;
374
+ align-items: center;
375
+ justify-content: center;
376
+ margin-right: 0.25rem;
377
+ transition: transform 0.2s ease;
378
+ cursor: pointer;
379
+ color: var(--text-muted);
380
+ font-size: 0.65rem;
381
+ }
382
+
383
+ .tree-expand-icon.expanded {
384
+ transform: rotate(90deg);
385
+ }
386
+
387
+ .tree-expand-icon.hidden {
388
+ visibility: hidden;
389
+ }
390
+
391
+ .tree-node-checkbox {
392
+ appearance: none;
393
+ -webkit-appearance: none;
394
+ width: 16px;
395
+ height: 16px;
396
+ cursor: pointer;
397
+ margin-right: 0.5rem;
398
+ border: 2px solid var(--border-color);
399
+ border-radius: 4px;
400
+ background: var(--bg-primary);
401
+ position: relative;
402
+ transition: all 0.15s ease;
403
+ flex-shrink: 0;
404
+ }
405
+
406
+ .tree-node-checkbox:hover {
407
+ border-color: var(--accent-emerald);
408
+ }
409
+
410
+ .tree-node-checkbox:checked {
411
+ background: var(--bg-primary);
412
+ border-color: var(--accent-emerald);
413
+ }
414
+
415
+ .tree-node-checkbox:checked::after {
416
+ content: '';
417
+ position: absolute;
418
+ top: 50%;
419
+ left: 50%;
420
+ width: 3px;
421
+ height: 6px;
422
+ border: solid var(--accent-emerald);
423
+ border-width: 0 2px 2px 0;
424
+ transform: translate(-50%, -60%) rotate(45deg);
425
+ }
426
+
427
+ .tree-node-checkbox:indeterminate {
428
+ background: var(--bg-primary);
429
+ border-color: var(--accent-emerald);
430
+ }
431
+
432
+ .tree-node-checkbox:indeterminate::after {
433
+ content: '';
434
+ position: absolute;
435
+ top: 50%;
436
+ left: 50%;
437
+ width: 8px;
438
+ height: 2px;
439
+ background: var(--accent-emerald);
440
+ transform: translate(-50%, -50%);
441
+ }
442
+
443
+ .tree-node-label {
444
+ flex: 1;
445
+ font-size: 0.82rem;
446
+ white-space: nowrap;
447
+ overflow: hidden;
448
+ text-overflow: ellipsis;
449
+ min-width: 0;
450
+ }
451
+
452
+ .tree-node-label.folder {
453
+ font-weight: 600;
454
+ color: var(--text-primary);
455
+ display: flex;
456
+ align-items: center;
457
+ gap: 0.25rem;
458
+ }
459
+
460
+ .tree-node-label.folder .tree-node-count {
461
+ flex-shrink: 0;
462
+ }
463
+
464
+ .tree-node-label.file {
465
+ color: var(--text-secondary);
466
+ }
467
+
468
+ .tree-node-method {
469
+ font-size: 0.65rem;
470
+ padding: 0.15rem 0.45rem;
471
+ border-radius: var(--radius-sm);
472
+ margin-right: 0.4rem;
473
+ font-weight: 600;
474
+ text-transform: uppercase;
475
+ letter-spacing: 0.03em;
476
+ }
477
+
478
+ .tree-node-method.get {
479
+ background: linear-gradient(135deg, var(--accent-emerald-light) 0%, rgba(16, 185, 129, 0.15) 100%);
480
+ color: #047857;
481
+ box-shadow: 0 2px 6px rgba(16, 185, 129, 0.15);
482
+ }
483
+
484
+ .tree-node-method.post {
485
+ background: linear-gradient(135deg, var(--accent-amber-light) 0%, rgba(245, 158, 11, 0.15) 100%);
486
+ color: #b45309;
487
+ box-shadow: 0 2px 6px rgba(245, 158, 11, 0.15);
488
+ }
489
+
490
+ .tree-node-method.put {
491
+ background: linear-gradient(135deg, var(--accent-indigo-light) 0%, rgba(99, 102, 241, 0.15) 100%);
492
+ color: #4338ca;
493
+ box-shadow: 0 2px 6px rgba(99, 102, 241, 0.15);
494
+ }
495
+
496
+ .tree-node-method.delete {
497
+ background: linear-gradient(135deg, var(--accent-rose-light) 0%, rgba(239, 68, 68, 0.15) 100%);
498
+ color: #b91c1c;
499
+ box-shadow: 0 2px 6px rgba(239, 68, 68, 0.15);
500
+ }
501
+
502
+ .tree-node-method.patch {
503
+ background: linear-gradient(135deg, #ede9fe 0%, rgba(139, 92, 246, 0.15) 100%);
504
+ color: #7c3aed;
505
+ box-shadow: 0 2px 6px rgba(139, 92, 246, 0.15);
506
+ }
507
+
508
+ .tree-children {
509
+ padding-left: 1rem;
510
+ display: none;
511
+ }
512
+
513
+ .tree-children.expanded {
514
+ display: block;
515
+ }
516
+
517
+ .tree-node-count {
518
+ font-size: 0.7rem;
519
+ color: var(--text-muted);
520
+ margin-left: 0.4rem;
521
+ }
522
+
523
+ .tree-node-delete {
524
+ display: none;
525
+ align-items: center;
526
+ justify-content: center;
527
+ width: 18px;
528
+ height: 18px;
529
+ margin-left: auto;
530
+ border-radius: var(--radius-sm);
531
+ cursor: pointer;
532
+ color: var(--accent-rose);
533
+ font-size: 0.85rem;
534
+ transition: all 0.15s ease;
535
+ user-select: none;
536
+ }
537
+
538
+ .tree-node-delete:hover {
539
+ background: var(--accent-rose-light);
540
+ }
541
+
542
+ .tree-node-content:hover .tree-node-delete {
543
+ display: flex;
544
+ }
545
+
546
+ #mock-details {
547
+ height: calc(100% - 60px);
548
+ }
549
+
550
+ section {
551
+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.6) 0%, rgba(238, 242, 255, 0.5) 50%, rgba(250, 245, 255, 0.6) 100%);
552
+ backdrop-filter: blur(15px);
553
+ padding: 1.5rem;
554
+ overflow-y: auto;
555
+ overflow-x: hidden;
556
+ display: flex;
557
+ flex-direction: column;
558
+ gap: 1rem;
559
+ height: 100%;
560
+ }
561
+
562
+ section::-webkit-scrollbar {
563
+ width: 6px;
564
+ }
565
+
566
+ section::-webkit-scrollbar-track {
567
+ background: transparent;
568
+ }
569
+
570
+ section::-webkit-scrollbar-thumb {
571
+ background: var(--border-color);
572
+ border-radius: 3px;
573
+ }
574
+
575
+ section::-webkit-scrollbar-thumb:hover {
576
+ background: var(--text-muted);
577
+ }
578
+
579
+ section > h3 {
580
+ margin: 0;
581
+ flex-shrink: 0;
582
+ color: var(--text-primary);
583
+ font-size: 0.85rem;
584
+ font-weight: 600;
585
+ text-transform: uppercase;
586
+ letter-spacing: 0.05em;
587
+ }
588
+
589
+ section .data-container {
590
+ flex: 1 1 auto;
591
+ min-height: 0;
592
+ display: flex;
593
+ flex-direction: column;
594
+ overflow: hidden;
595
+ height: 100%;
596
+ }
597
+
598
+ .controls {
599
+ display: flex;
600
+ flex-wrap: wrap;
601
+ gap: 1rem;
602
+ align-items: flex-start;
603
+ flex-shrink: 0;
604
+ }
605
+
606
+ .controls h2 {
607
+ width: 100%;
608
+ margin: 0 0 0.75rem 0;
609
+ font-size: 1rem;
610
+ display: flex;
611
+ align-items: center;
612
+ gap: 0.75rem;
613
+ }
614
+
615
+ .controls label input[type="text"] {
616
+ padding: 0.4rem 0.6rem;
617
+ border-radius: var(--radius-sm);
618
+ border: 1px solid var(--border-color);
619
+ background: var(--bg-primary);
620
+ color: var(--text-primary);
621
+ font-family: inherit;
622
+ font-size: 0.8rem;
623
+ outline: none;
624
+ transition: all 0.15s ease;
625
+ }
626
+
627
+ .controls label input[type="text"]:focus {
628
+ border-color: var(--accent-indigo);
629
+ box-shadow: 0 0 0 3px var(--accent-indigo-light);
630
+ }
631
+
632
+ .badge {
633
+ display: inline-flex;
634
+ align-items: center;
635
+ gap: 0.25rem;
636
+ border-radius: var(--radius-sm);
637
+ padding: 0.25rem 0.65rem;
638
+ font-size: 0.65rem;
639
+ font-weight: 600;
640
+ background: linear-gradient(135deg, #818cf8 0%, #a78bfa 50%, #f472b6 100%);
641
+ color: white;
642
+ text-transform: uppercase;
643
+ letter-spacing: 0.05em;
644
+ box-shadow: 0 4px 15px rgba(139, 92, 246, 0.3);
645
+ }
646
+
647
+ textarea {
648
+ width: 100%;
649
+ flex: 1;
650
+ min-height: 300px;
651
+ font-family: 'JetBrains Mono', 'SF Mono', 'Consolas', monospace;
652
+ font-size: 0.82rem;
653
+ padding: 1rem;
654
+ border: 1px solid var(--border-color);
655
+ border-radius: var(--radius-md);
656
+ resize: none;
657
+ background: var(--bg-secondary);
658
+ color: var(--text-primary);
659
+ overflow-y: auto;
660
+ outline: none;
661
+ transition: all 0.15s ease;
662
+ line-height: 1.6;
663
+ }
664
+
665
+ textarea:focus {
666
+ border-color: var(--accent-indigo);
667
+ box-shadow: 0 0 0 3px var(--accent-indigo-light);
668
+ }
669
+
670
+ label {
671
+ font-size: 0.75rem;
672
+ color: var(--text-secondary);
673
+ display: flex;
674
+ gap: 0.5rem;
675
+ align-items: center;
676
+ }
677
+
678
+ input[type="number"] {
679
+ width: 90px;
680
+ padding: 0.35rem 0.5rem;
681
+ border-radius: var(--radius-sm);
682
+ border: 1px solid var(--border-color);
683
+ background: var(--bg-primary);
684
+ color: var(--text-primary);
685
+ font-family: inherit;
686
+ font-size: 0.8rem;
687
+ outline: none;
688
+ transition: all 0.15s ease;
689
+ }
690
+
691
+ input[type="number"]:focus {
692
+ border-color: var(--accent-indigo);
693
+ box-shadow: 0 0 0 3px var(--accent-indigo-light);
694
+ }
695
+
696
+ .actions {
697
+ display: flex;
698
+ gap: 0.75rem;
699
+ flex-shrink: 0;
700
+ margin-top: 0.5rem;
701
+ }
702
+
703
+ button.primary {
704
+ background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%);
705
+ color: white;
706
+ padding: 0.5rem 1rem;
707
+ border-radius: var(--radius-md);
708
+ border: none;
709
+ cursor: pointer;
710
+ font-weight: 500;
711
+ font-family: inherit;
712
+ font-size: 0.8rem;
713
+ transition: all 0.2s ease;
714
+ box-shadow: 0 4px 20px rgba(139, 92, 246, 0.4);
715
+ display: inline-flex;
716
+ align-items: center;
717
+ gap: 0.4rem;
718
+ position: relative;
719
+ overflow: hidden;
720
+ }
721
+
722
+ button.primary::before {
723
+ content: '';
724
+ position: absolute;
725
+ inset: 0;
726
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, transparent 50%);
727
+ opacity: 0;
728
+ transition: opacity 0.3s ease;
729
+ }
730
+
731
+ button.primary:hover::before {
732
+ opacity: 1;
733
+ }
734
+
735
+ button.primary .btn-icon {
736
+ color: white;
737
+ }
738
+
739
+ button.primary:hover {
740
+ background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #9333ea 100%);
741
+ box-shadow: 0 6px 25px rgba(139, 92, 246, 0.5);
742
+ transform: translateY(-2px);
743
+ }
744
+
745
+ button.secondary {
746
+ background: var(--bg-primary);
747
+ color: var(--text-secondary);
748
+ padding: 0.5rem 1rem;
749
+ border-radius: var(--radius-md);
750
+ border: 1px solid var(--border-color);
751
+ cursor: pointer;
752
+ font-family: inherit;
753
+ font-size: 0.8rem;
754
+ transition: all 0.15s ease;
755
+ }
756
+
757
+ button.secondary:hover {
758
+ background: var(--bg-hover);
759
+ color: var(--text-primary);
760
+ }
761
+
762
+ /* Button icons */
763
+ .btn-icon {
764
+ display: inline-flex;
765
+ align-items: center;
766
+ justify-content: center;
767
+ font-size: 1rem;
768
+ font-weight: 300;
769
+ line-height: 1;
770
+ }
771
+
772
+ .btn-icon-check {
773
+ display: inline-flex;
774
+ align-items: center;
775
+ justify-content: center;
776
+ font-size: 0.85rem;
777
+ font-weight: 600;
778
+ line-height: 1;
779
+ color: var(--accent-emerald);
780
+ }
781
+
782
+ .btn-icon-cross {
783
+ display: inline-flex;
784
+ align-items: center;
785
+ justify-content: center;
786
+ font-size: 0.85rem;
787
+ font-weight: 600;
788
+ line-height: 1;
789
+ color: var(--accent-rose);
790
+ }
791
+
792
+ /* Detail panel checkbox */
793
+ #toggle-enable {
794
+ appearance: none;
795
+ -webkit-appearance: none;
796
+ width: 16px;
797
+ height: 16px;
798
+ cursor: pointer;
799
+ border: 2px solid var(--border-color);
800
+ border-radius: 4px;
801
+ background: var(--bg-primary);
802
+ position: relative;
803
+ transition: all 0.15s ease;
804
+ flex-shrink: 0;
805
+ }
806
+
807
+ #toggle-enable:hover {
808
+ border-color: var(--accent-emerald);
809
+ }
810
+
811
+ #toggle-enable:checked {
812
+ background: var(--bg-primary);
813
+ border-color: var(--accent-emerald);
814
+ }
815
+
816
+ #toggle-enable:checked::after {
817
+ content: '';
818
+ position: absolute;
819
+ top: 50%;
820
+ left: 50%;
821
+ width: 3px;
822
+ height: 6px;
823
+ border: solid var(--accent-emerald);
824
+ border-width: 0 2px 2px 0;
825
+ transform: translate(-50%, -60%) rotate(45deg);
826
+ }
827
+
828
+ .empty {
829
+ display: flex;
830
+ flex-direction: column;
831
+ align-items: center;
832
+ justify-content: center;
833
+ color: var(--text-muted);
834
+ gap: 0.5rem;
835
+ height: 100%;
836
+ font-size: 0.85rem;
837
+ }
838
+
839
+ pre {
840
+ background: var(--bg-secondary);
841
+ padding: 1rem;
842
+ border-radius: var(--radius-md);
843
+ font-family: 'JetBrains Mono', 'SF Mono', 'Consolas', monospace;
844
+ overflow: auto;
845
+ flex: 1;
846
+ margin: 0;
847
+ min-height: 300px;
848
+ color: var(--text-primary);
849
+ font-size: 0.82rem;
850
+ line-height: 1.6;
851
+ border: 1px solid var(--border-color);
852
+ }
853
+
854
+ textarea.error {
855
+ border-color: var(--accent-rose);
856
+ box-shadow: 0 0 0 3px var(--accent-rose-light);
857
+ }
858
+
859
+ /* Modal styles */
860
+ .modal-overlay {
861
+ position: fixed;
862
+ top: 0;
863
+ left: 0;
864
+ right: 0;
865
+ bottom: 0;
866
+ background: linear-gradient(135deg, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.4) 100%);
867
+ backdrop-filter: blur(8px);
868
+ display: none;
869
+ align-items: center;
870
+ justify-content: center;
871
+ z-index: 1000;
872
+ }
873
+
874
+ .modal-overlay.show {
875
+ display: flex;
876
+ animation: modalFadeIn 0.2s ease-out;
877
+ }
878
+
879
+ @keyframes modalFadeIn {
880
+ from {
881
+ opacity: 0;
882
+ }
883
+ to {
884
+ opacity: 1;
885
+ }
886
+ }
887
+
888
+ .modal {
889
+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(238, 242, 255, 0.9) 50%, rgba(250, 245, 255, 0.95) 100%);
890
+ backdrop-filter: blur(25px);
891
+ border: 1px solid rgba(255, 255, 255, 0.6);
892
+ border-radius: var(--radius-lg);
893
+ padding: 2rem;
894
+ max-width: 500px;
895
+ width: 90%;
896
+ box-shadow: 0 25px 50px rgba(139, 92, 246, 0.25), 0 0 100px rgba(236, 72, 153, 0.15);
897
+ animation: modalSlideUp 0.3s ease-out;
898
+ position: relative;
899
+ }
900
+
901
+ .modal::before {
902
+ content: '';
903
+ position: absolute;
904
+ inset: -2px;
905
+ background: linear-gradient(135deg, rgba(139, 92, 246, 0.3), rgba(236, 72, 153, 0.3), rgba(59, 130, 246, 0.3));
906
+ border-radius: calc(var(--radius-lg) + 2px);
907
+ z-index: -1;
908
+ opacity: 0.5;
909
+ }
910
+
911
+ @keyframes modalSlideUp {
912
+ from {
913
+ opacity: 0;
914
+ transform: translateY(16px) scale(0.98);
915
+ }
916
+ to {
917
+ opacity: 1;
918
+ transform: translateY(0) scale(1);
919
+ }
920
+ }
921
+
922
+ .modal h2 {
923
+ margin: 0 0 1.5rem 0;
924
+ color: var(--text-primary);
925
+ font-size: 1.1rem;
926
+ font-weight: 600;
927
+ }
928
+
929
+ .modal .form-group {
930
+ margin-bottom: 1.25rem;
931
+ }
932
+
933
+ .modal .form-group label {
934
+ display: block;
935
+ margin-bottom: 0.5rem;
936
+ font-weight: 500;
937
+ color: var(--text-primary);
938
+ font-size: 0.8rem;
939
+ }
940
+
941
+ .modal .form-group input,
942
+ .modal .form-group select,
943
+ .modal .form-group textarea {
944
+ width: 100%;
945
+ padding: 0.6rem;
946
+ border: 1px solid var(--border-color);
947
+ border-radius: var(--radius-sm);
948
+ font-size: 0.85rem;
949
+ font-family: inherit;
950
+ background: var(--bg-primary);
951
+ color: var(--text-primary);
952
+ outline: none;
953
+ transition: all 0.15s ease;
954
+ }
955
+
956
+ .modal .form-group input:focus,
957
+ .modal .form-group select:focus,
958
+ .modal .form-group textarea:focus {
959
+ border-color: var(--accent-indigo);
960
+ box-shadow: 0 0 0 3px var(--accent-indigo-light);
961
+ }
962
+
963
+ .modal .form-group textarea {
964
+ min-height: 100px;
965
+ font-family: 'JetBrains Mono', 'SF Mono', 'Consolas', monospace;
966
+ font-size: 0.8rem;
967
+ }
968
+
969
+ .modal .form-group small {
970
+ display: block;
971
+ margin-top: 0.35rem;
972
+ color: var(--text-muted);
973
+ font-size: 0.7rem;
974
+ }
975
+
976
+ .modal .form-actions {
977
+ display: flex;
978
+ gap: 1rem;
979
+ justify-content: flex-end;
980
+ margin-top: 1.5rem;
981
+ }
982
+
983
+ /* Animation delays for stagger effect */
984
+ header { animation-delay: 0.05s; }
985
+ main { animation-delay: 0.1s; }
986
+ </style>
987
+ </head>
988
+ <body>
989
+ <header>
990
+ <h1>Mock Inspector</h1>
991
+ <span class="badge">${apiPrefixEscaped}</span>
992
+ <button id="new-api-btn" class="primary" style="margin-left: auto;"><span class="btn-icon">+</span> New API</button>
993
+ </header>
994
+ <main>
995
+ <aside id="sidebar">
996
+ <div class="global-controls">
997
+ <button id="enable-all" class="secondary"><span class="btn-icon-check">\u2713</span> \u5F00\u542F\u6240\u6709</button>
998
+ <button id="disable-all" class="secondary"><span class="btn-icon-cross">\u2717</span> \u5173\u95ED\u6240\u6709</button>
999
+ </div>
1000
+ <ul id="mock-list"></ul>
1001
+ </aside>
1002
+ <div class="resizer" id="resizer"></div>
1003
+ <section>
1004
+ <div id="mock-details" class="empty">
1005
+ <p>Select a mock entry to inspect</p>
1006
+ </div>
1007
+ </section>
1008
+ </main>
1009
+
1010
+ <div id="new-api-modal" class="modal-overlay">
1011
+ <div class="modal">
1012
+ <h2><span class="btn-icon">+</span> New API Mock</h2>
1013
+ <form id="new-api-form">
1014
+ <div class="form-group">
1015
+ <label for="new-api-method">HTTP Method</label>
1016
+ <select id="new-api-method" required>
1017
+ <option value="get">GET</option>
1018
+ <option value="post">POST</option>
1019
+ <option value="put">PUT</option>
1020
+ <option value="delete">DELETE</option>
1021
+ <option value="patch">PATCH</option>
1022
+ </select>
1023
+ </div>
1024
+ <div class="form-group">
1025
+ <label for="new-api-path">API Path (without prefix)</label>
1026
+ <input type="text" id="new-api-path" placeholder="/users/list" required />
1027
+ <small style="color: rgba(15, 23, 42, 0.6); font-size: 0.85rem;">\u4F8B\u5982\uFF1A/users/list \u6216 /api/items</small>
1028
+ </div>
1029
+ <div class="form-group">
1030
+ <label for="new-api-description">Description (Optional)</label>
1031
+ <input type="text" id="new-api-description" placeholder="\u4F8B\u5982\uFF1A\u7528\u6237\u5217\u8868\u63A5\u53E3" />
1032
+ </div>
1033
+ <div class="form-group">
1034
+ <label for="new-api-data">Response Data (JSON)</label>
1035
+ <textarea id="new-api-data" placeholder='{ "code": 200, "data": [] }'>{ "code": 200, "data": [] }</textarea>
1036
+ </div>
1037
+ <div class="form-actions">
1038
+ <button type="button" id="cancel-new-api">Cancel</button>
1039
+ <button type="submit" class="primary">Create</button>
1040
+ </div>
1041
+ </form>
1042
+ </div>
1043
+ </div>
1044
+
1045
+ <script>
1046
+ const inspectorRoute = ${routeJson};
1047
+ const apiBase = (inspectorRoute.endsWith('/') ? inspectorRoute.slice(0, -1) : inspectorRoute) + '/api';
1048
+ const allowToggle = ${allowToggleJson};
1049
+
1050
+ function escapeHtml(value) {
1051
+ if (value == null) return '';
1052
+ return String(value)
1053
+ .replace(/&/g, '&amp;')
1054
+ .replace(/</g, '&lt;')
1055
+ .replace(/>/g, '&gt;')
1056
+ .replace(/"/g, '&quot;')
1057
+ .replace(/'/g, '&#39;');
1058
+ }
1059
+
1060
+ // Tree data structure conversion
1061
+ function buildMockTree(mocks) {
1062
+ const root = { id: 'root', name: 'root', type: 'folder', children: [], checked: false, indeterminate: false };
1063
+
1064
+ mocks.forEach(mock => {
1065
+ // Parse the file path to build tree structure
1066
+ // Example: "automock/api/v1/asset-groups/prod-db-redis/put.js"
1067
+ const parts = mock.file.split('/').filter(p => p);
1068
+ let currentNode = root;
1069
+
1070
+ parts.forEach((part, index) => {
1071
+ const isFile = part.endsWith('.js') || part.endsWith('.ts');
1072
+ const nodeName = isFile ? part.replace(/.(js|ts)$/, '') : part;
1073
+ const nodeId = parts.slice(0, index + 1).join('/');
1074
+
1075
+ let childNode = currentNode.children.find(child => child.name === nodeName);
1076
+
1077
+ if (!childNode) {
1078
+ childNode = {
1079
+ id: nodeId,
1080
+ name: nodeName,
1081
+ type: isFile ? 'file' : 'folder',
1082
+ level: index,
1083
+ children: [],
1084
+ checked: false,
1085
+ indeterminate: false
1086
+ };
1087
+
1088
+ if (isFile) {
1089
+ childNode.mockInfo = mock;
1090
+ }
1091
+
1092
+ currentNode.children.push(childNode);
1093
+ }
1094
+
1095
+ currentNode = childNode;
1096
+ });
1097
+ });
1098
+
1099
+ // Initialize checked state based on mock.config.enable
1100
+ function initCheckedState(node) {
1101
+ if (node.type === 'file' && node.mockInfo) {
1102
+ node.checked = node.mockInfo.config.enable || false;
1103
+ node.indeterminate = false;
1104
+ }
1105
+ if (node.children && node.children.length > 0) {
1106
+ node.children.forEach(initCheckedState);
1107
+ }
1108
+ }
1109
+
1110
+ initCheckedState(root);
1111
+
1112
+ // Calculate parent states
1113
+ function updateParentStates(node) {
1114
+ if (node.children && node.children.length > 0) {
1115
+ node.children.forEach(updateParentStates);
1116
+
1117
+ const allChecked = node.children.every(child => child.checked && !child.indeterminate);
1118
+ const someChecked = node.children.some(child => child.checked || child.indeterminate);
1119
+
1120
+ node.checked = allChecked;
1121
+ node.indeterminate = !allChecked && someChecked;
1122
+ }
1123
+ }
1124
+
1125
+ updateParentStates(root);
1126
+
1127
+ return root.children;
1128
+ }
1129
+
1130
+ // Get all leaf node (file) keys under a node
1131
+ function getAllFileKeys(node) {
1132
+ if (node.type === 'file') {
1133
+ return [node.mockInfo?.key].filter(Boolean);
1134
+ }
1135
+
1136
+ if (node.children && node.children.length > 0) {
1137
+ const keys = [];
1138
+ node.children.forEach(child => {
1139
+ keys.push(...getAllFileKeys(child));
1140
+ });
1141
+ return keys;
1142
+ }
1143
+
1144
+ return [];
1145
+ }
1146
+
1147
+ // Update tree node state recursively
1148
+ function updateTreeNodeState(node, checked, updateChildren = true) {
1149
+ if (updateChildren && node.children && node.children.length > 0) {
1150
+ node.children.forEach(child => {
1151
+ updateTreeNodeState(child, checked, true);
1152
+ });
1153
+ }
1154
+
1155
+ node.checked = checked;
1156
+ node.indeterminate = false;
1157
+ }
1158
+
1159
+ // Update parent states bottom-up
1160
+ function updateParentNodeState(node, tree) {
1161
+ // Find parent node
1162
+ function findParent(n, targetId, parent = null) {
1163
+ if (n.id === targetId) return parent;
1164
+ if (n.children) {
1165
+ for (const child of n.children) {
1166
+ const result = findParent(child, targetId, n);
1167
+ if (result) return result;
1168
+ }
1169
+ }
1170
+ return null;
1171
+ }
1172
+
1173
+ const parent = findParent({ children: tree }, node.id);
1174
+
1175
+ if (parent) {
1176
+ const allChecked = parent.children.every(child => child.checked && !child.indeterminate);
1177
+ const someChecked = parent.children.some(child => child.checked || child.indeterminate);
1178
+
1179
+ parent.checked = allChecked;
1180
+ parent.indeterminate = !allChecked && someChecked;
1181
+
1182
+ updateParentNodeState(parent, tree);
1183
+ }
1184
+ }
1185
+
1186
+ // Render tree node recursively
1187
+ function renderTreeNode(node, level = 0, expandedNodes = new Set()) {
1188
+ const hasChildren = node.children && node.children.length > 0;
1189
+ const isExpanded = expandedNodes.has(node.id);
1190
+ const paddingLeft = level * 1.2 + 0.5;
1191
+
1192
+ let html = '<div class="tree-node" data-node-id="' + escapeHtml(node.id) + '" data-node-type="' + node.type + '">';
1193
+
1194
+ // Node content
1195
+ html += '<div class="tree-node-content" style="padding-left: ' + paddingLeft + 'rem">';
1196
+
1197
+ // Expand/collapse icon
1198
+ if (hasChildren) {
1199
+ html += '<span class="tree-expand-icon' + (isExpanded ? ' expanded' : '') + '">\u25B6</span>';
1200
+ } else {
1201
+ html += '<span class="tree-expand-icon hidden"></span>';
1202
+ }
1203
+
1204
+ // Checkbox
1205
+ const checkedAttr = node.checked ? 'checked' : '';
1206
+ const indeterminateAttr = node.indeterminate ? 'data-indeterminate="true"' : '';
1207
+ html += '<input type="checkbox" class="tree-node-checkbox" ' + checkedAttr + ' ' + indeterminateAttr + ' />';
1208
+
1209
+ // Node label
1210
+ if (node.type === 'file' && node.mockInfo) {
1211
+ const mock = node.mockInfo;
1212
+ const methodClass = mock.method?.toLowerCase() || 'get';
1213
+ html += '<span class="tree-node-method ' + methodClass + '">' + escapeHtml(mock.method?.toUpperCase() || 'GET') + '</span>';
1214
+ html += '<span class="tree-node-label file" title="' + escapeHtml(mock.path) + '">' + escapeHtml(mock.path) + '</span>';
1215
+ if (mock.description) {
1216
+ html += '<span class="tree-node-count" title="' + escapeHtml(mock.description) + '">' + escapeHtml(mock.description) + '</span>';
1217
+ }
1218
+ // Delete button (only for files)
1219
+ html += '<span class="tree-node-delete" data-mock-key="' + escapeHtml(mock.key) + '" data-is-folder="false" title="\u5220\u9664\u6B64 Mock">\u2715</span>';
1220
+ } else {
1221
+ const fileCount = getAllFileKeys(node);
1222
+ const fileKeysJson = JSON.stringify(fileCount);
1223
+ // Put count inside the label to avoid layout shift when delete button appears
1224
+ html += '<span class="tree-node-label folder">' + escapeHtml(node.name) + ' <span class="tree-node-count">(' + fileCount.length + ')</span></span>';
1225
+ // Delete button for folders
1226
+ html += '<span class="tree-node-delete" data-mock-keys="' + escapeHtml(fileKeysJson) + '" data-is-folder="true" data-folder-name="' + escapeHtml(node.name) + '" title="\u5220\u9664\u6B64\u6587\u4EF6\u5939\u53CA\u6240\u6709 Mock">\u2715</span>';
1227
+ }
1228
+
1229
+ html += '</div>';
1230
+
1231
+ // Children container
1232
+ if (hasChildren) {
1233
+ html += '<div class="tree-children' + (isExpanded ? ' expanded' : '') + '">';
1234
+ node.children.forEach(child => {
1235
+ html += renderTreeNode(child, level + 1, expandedNodes);
1236
+ });
1237
+ html += '</div>';
1238
+ }
1239
+
1240
+ html += '</div>';
1241
+
1242
+ return html;
1243
+ }
1244
+
1245
+ // Find node by id in tree
1246
+ function findNodeById(nodes, id) {
1247
+ for (const node of nodes) {
1248
+ if (node.id === id) return node;
1249
+ if (node.children) {
1250
+ const found = findNodeById(node.children, id);
1251
+ if (found) return found;
1252
+ }
1253
+ }
1254
+ return null;
1255
+ }
1256
+
1257
+ // Toggle tree node expand/collapse
1258
+ function toggleTreeNodeExpand(nodeId) {
1259
+ const nodeEl = document.querySelector('.tree-node[data-node-id="' + nodeId + '"]');
1260
+ if (!nodeEl) return;
1261
+
1262
+ const childrenEl = nodeEl.querySelector('.tree-children');
1263
+ const iconEl = nodeEl.querySelector('.tree-expand-icon');
1264
+
1265
+ if (childrenEl && iconEl && !iconEl.classList.contains('hidden')) {
1266
+ const isExpanded = childrenEl.classList.contains('expanded');
1267
+ if (isExpanded) {
1268
+ childrenEl.classList.remove('expanded');
1269
+ iconEl.classList.remove('expanded');
1270
+ } else {
1271
+ childrenEl.classList.add('expanded');
1272
+ iconEl.classList.add('expanded');
1273
+ }
1274
+ }
1275
+ }
1276
+
1277
+ function renderToggleSection(mock) {
1278
+ if (!allowToggle) {
1279
+ return '';
1280
+ }
1281
+ const checked = mock.config.enable ? 'checked' : '';
1282
+ return (
1283
+ '<label>' +
1284
+ '<input type="checkbox" id="toggle-enable" ' + checked + ' />' +
1285
+ 'Enable' +
1286
+ '</label>'
1287
+ );
1288
+ }
1289
+
1290
+ function renderDataSection(mock) {
1291
+ if (mock.editable) {
1292
+ return '<div class="data-container"><textarea id="data-editor"></textarea><div class="actions"><button class="primary" id="save-btn">Save</button></div></div>';
1293
+ }
1294
+ return '<div class="data-container"><pre id="data-preview"></pre></div>';
1295
+ }
1296
+
1297
+ async function fetchMocks() {
1298
+ try {
1299
+ const res = await fetch(apiBase + '/list');
1300
+ if (!res.ok) {
1301
+ throw new Error('HTTP ' + res.status + ': ' + res.statusText);
1302
+ }
1303
+ const data = await res.json();
1304
+ return data.mocks || [];
1305
+ } catch (error) {
1306
+ console.error('[Inspector] Failed to fetch mocks:', error);
1307
+ return [];
1308
+ }
1309
+ }
1310
+
1311
+ function renderMockList(mocks, preserveExpandedState = false) {
1312
+ const list = document.getElementById('mock-list');
1313
+ if (!list) {
1314
+ console.error('[Inspector] Element #mock-list not found!');
1315
+ return;
1316
+ }
1317
+
1318
+ // Save current expanded state if requested
1319
+ let savedExpandedNodes = new Set();
1320
+ if (preserveExpandedState) {
1321
+ list.querySelectorAll('.tree-children.expanded').forEach(el => {
1322
+ const parentNode = el.closest('.tree-node');
1323
+ if (parentNode) {
1324
+ savedExpandedNodes.add(parentNode.dataset.nodeId);
1325
+ }
1326
+ });
1327
+ }
1328
+
1329
+ list.innerHTML = '';
1330
+ if (!mocks || mocks.length === 0) {
1331
+ console.warn('[Inspector] No mocks to display');
1332
+ list.innerHTML = '<div style="padding: 1rem; color: #999;">No mock files found</div>';
1333
+ return;
1334
+ }
1335
+
1336
+ // Build tree structure
1337
+ const tree = buildMockTree(mocks);
1338
+
1339
+ // Use saved expanded state or expand first level by default
1340
+ const expandedNodes = savedExpandedNodes.size > 0 ? savedExpandedNodes : new Set();
1341
+ if (expandedNodes.size === 0) {
1342
+ tree.forEach(node => {
1343
+ if (node.type === 'folder') {
1344
+ expandedNodes.add(node.id);
1345
+ }
1346
+ });
1347
+ }
1348
+
1349
+ let treeHtml = '';
1350
+ tree.forEach(node => {
1351
+ const nodeHtml = renderTreeNode(node, 0, expandedNodes);
1352
+ treeHtml += nodeHtml;
1353
+ });
1354
+
1355
+ list.innerHTML = treeHtml;
1356
+
1357
+ // Attach event listeners
1358
+ attachTreeEventListeners();
1359
+ }
1360
+
1361
+ // Attach event listeners for tree interactions
1362
+ function attachTreeEventListeners() {
1363
+ const list = document.getElementById('mock-list');
1364
+ if (!list) return;
1365
+
1366
+ // Handle expand/collapse clicks
1367
+ list.querySelectorAll('.tree-expand-icon').forEach(icon => {
1368
+ icon.addEventListener('click', (e) => {
1369
+ e.stopPropagation();
1370
+ const nodeEl = icon.closest('.tree-node');
1371
+ if (nodeEl) {
1372
+ const nodeId = nodeEl.dataset.nodeId;
1373
+ toggleTreeNodeExpand(nodeId);
1374
+ }
1375
+ });
1376
+ });
1377
+
1378
+ // Handle checkbox clicks
1379
+ list.querySelectorAll('.tree-node-checkbox').forEach(checkbox => {
1380
+ checkbox.addEventListener('click', async (e) => {
1381
+ e.stopPropagation();
1382
+ const nodeEl = checkbox.closest('.tree-node');
1383
+ if (!nodeEl) return;
1384
+
1385
+ const nodeId = nodeEl.dataset.nodeId;
1386
+ const nodeType = nodeEl.dataset.nodeType;
1387
+ const checked = checkbox.checked;
1388
+
1389
+ // Get current tree data
1390
+ const tree = buildMockTree(currentMocks);
1391
+
1392
+ // Find and update node
1393
+ const node = findNodeById(tree, nodeId);
1394
+ if (node) {
1395
+ // Update children
1396
+ updateTreeNodeState(node, checked, true);
1397
+ // Update parents
1398
+ updateParentNodeState(node, tree);
1399
+
1400
+ // Apply changes to all affected file nodes
1401
+ const affectedKeys = getAllFileKeys(node);
1402
+ await Promise.all(affectedKeys.map(key => toggleMockEnable(key, checked)));
1403
+
1404
+ // Re-render tree with preserved expanded state
1405
+ renderMockList(currentMocks, true);
1406
+ }
1407
+ });
1408
+ });
1409
+
1410
+ // Handle node content clicks (for selection)
1411
+ list.querySelectorAll('.tree-node-content').forEach(content => {
1412
+ content.addEventListener('click', (e) => {
1413
+ // Don't select if clicking on checkbox or expand icon
1414
+ if (e.target.classList.contains('tree-node-checkbox') ||
1415
+ e.target.classList.contains('tree-expand-icon')) {
1416
+ return;
1417
+ }
1418
+
1419
+ const nodeEl = content.closest('.tree-node');
1420
+ if (!nodeEl) return;
1421
+
1422
+ const nodeId = nodeEl.dataset.nodeId;
1423
+ const nodeType = nodeEl.dataset.nodeType;
1424
+
1425
+ // Remove previous selection
1426
+ document.querySelectorAll('.tree-node-content.selected').forEach(el => {
1427
+ el.classList.remove('selected');
1428
+ });
1429
+
1430
+ // Add selection to current node
1431
+ content.classList.add('selected');
1432
+
1433
+ // For file nodes, select the mock
1434
+ if (nodeType === 'file') {
1435
+ const tree = buildMockTree(currentMocks);
1436
+ const node = findNodeById(tree, nodeId);
1437
+ if (node && node.mockInfo) {
1438
+ selectMock(node.mockInfo.key, content);
1439
+ }
1440
+ }
1441
+ });
1442
+ });
1443
+
1444
+ // Set indeterminate state for checkboxes
1445
+ list.querySelectorAll('.tree-node-checkbox[data-indeterminate="true"]').forEach(cb => {
1446
+ cb.indeterminate = true;
1447
+ });
1448
+
1449
+ // Handle delete button clicks
1450
+ list.querySelectorAll('.tree-node-delete').forEach(deleteBtn => {
1451
+ deleteBtn.addEventListener('click', async (e) => {
1452
+ e.stopPropagation();
1453
+
1454
+ // Check if user has chosen "never ask again"
1455
+ const skipConfirm = localStorage.getItem('mockInspector_skipDeleteConfirm') === 'true';
1456
+
1457
+ const isFolder = deleteBtn.dataset.isFolder === 'true';
1458
+ let confirmMessage = '';
1459
+ let keysToDelete = [];
1460
+
1461
+ if (isFolder) {
1462
+ // Folder deletion
1463
+ const folderName = deleteBtn.dataset.folderName || '';
1464
+ const keysJson = deleteBtn.dataset.mockKeys || '[]';
1465
+ keysToDelete = JSON.parse(keysJson);
1466
+ confirmMessage = '\u786E\u5B9A\u8981\u5220\u9664\u6587\u4EF6\u5939 "' + folderName + '" \u53CA\u5176\u5305\u542B\u7684 ' + keysToDelete.length + ' \u4E2A Mock \u6587\u4EF6\u5417\uFF1F\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002';
1467
+ } else {
1468
+ // Single file deletion
1469
+ const mockKey = deleteBtn.dataset.mockKey;
1470
+ if (!mockKey) return;
1471
+ keysToDelete = [mockKey];
1472
+ confirmMessage = '\u786E\u5B9A\u8981\u5220\u9664\u8FD9\u4E2A Mock \u6570\u636E\u5417\uFF1F\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002';
1473
+ }
1474
+
1475
+ // If user chose "never ask again", delete directly
1476
+ if (skipConfirm) {
1477
+ await performDelete(keysToDelete);
1478
+ return;
1479
+ }
1480
+
1481
+ // Otherwise, show custom confirmation dialog
1482
+ showDeleteConfirmDialog(confirmMessage, keysToDelete);
1483
+ });
1484
+ });
1485
+
1486
+ // Custom delete confirmation dialog
1487
+ function showDeleteConfirmDialog(message, keysToDelete) {
1488
+ const modal = document.getElementById('delete-confirm-modal');
1489
+ const messageEl = document.getElementById('delete-confirm-message');
1490
+ const neverAskCheckbox = document.getElementById('delete-never-ask');
1491
+ const confirmBtn = document.getElementById('delete-confirm-btn');
1492
+ const cancelBtn = document.getElementById('delete-cancel-btn');
1493
+
1494
+ messageEl.textContent = message;
1495
+ neverAskCheckbox.checked = false;
1496
+ modal.classList.add('show');
1497
+
1498
+ // Remove old event listeners
1499
+ const newConfirmBtn = confirmBtn.cloneNode(true);
1500
+ const newCancelBtn = cancelBtn.cloneNode(true);
1501
+ confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
1502
+ cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn);
1503
+
1504
+ // Confirm button handler
1505
+ newConfirmBtn.addEventListener('click', async () => {
1506
+ // Save preference if "never ask again" is checked
1507
+ if (neverAskCheckbox.checked) {
1508
+ localStorage.setItem('mockInspector_skipDeleteConfirm', 'true');
1509
+ }
1510
+ modal.classList.remove('show');
1511
+ await performDelete(keysToDelete);
1512
+ });
1513
+
1514
+ // Cancel button handler
1515
+ newCancelBtn.addEventListener('click', () => {
1516
+ modal.classList.remove('show');
1517
+ });
1518
+
1519
+ // Close on overlay click
1520
+ modal.addEventListener('click', (e) => {
1521
+ if (e.target === modal) {
1522
+ modal.classList.remove('show');
1523
+ }
1524
+ });
1525
+ }
1526
+
1527
+ // Perform the actual deletion
1528
+ async function performDelete(keysToDelete) {
1529
+ try {
1530
+ // Delete all keys (either single file or entire folder)
1531
+ const deletePromises = keysToDelete.map(key =>
1532
+ fetch(apiBase + '/delete?key=' + encodeURIComponent(key), {
1533
+ method: 'DELETE'
1534
+ })
1535
+ );
1536
+
1537
+ const results = await Promise.all(deletePromises);
1538
+
1539
+ // Check if any deletion failed
1540
+ const failedDeletions = results.filter(res => !res.ok);
1541
+ if (failedDeletions.length > 0) {
1542
+ const errors = await Promise.all(failedDeletions.map(res => res.json()));
1543
+ throw new Error(errors.map(e => e.error).join(', '));
1544
+ }
1545
+
1546
+ // Refresh the list
1547
+ currentMocks = await fetchMocks();
1548
+ renderMockList(currentMocks, true);
1549
+
1550
+ // Clear details panel if any deleted mock was selected
1551
+ if (keysToDelete.includes(window.currentKey)) {
1552
+ window.currentKey = null;
1553
+ document.getElementById('mock-details').innerHTML = '<p>Select a mock entry to inspect</p>';
1554
+ document.getElementById('mock-details').className = 'empty';
1555
+ }
1556
+ } catch (error) {
1557
+ alert('\u5220\u9664\u5931\u8D25: ' + error.message);
1558
+ }
1559
+ }
1560
+ }
1561
+
1562
+ function renderDetails(mock) {
1563
+ const container = document.getElementById('mock-details');
1564
+ if (!mock) {
1565
+ container.className = 'empty';
1566
+ container.innerHTML = '<p>Select a mock entry to inspect</p>';
1567
+ return;
1568
+ }
1569
+
1570
+ container.className = '';
1571
+ container.innerHTML = [
1572
+ '<div style="display: flex; flex-direction: column; height: 100%;">',
1573
+ ' <div class="controls">',
1574
+ ' <h2>',
1575
+ ' <span class="badge">' + escapeHtml(mock.method.toUpperCase()) + '</span>',
1576
+ ' ' + escapeHtml(mock.path),
1577
+ ' </h2>',
1578
+ ' <label style="flex: 1;" >',
1579
+ ' Desc: ',
1580
+ ' <input type="text" id="description-input" placeholder="\u4F8B\u5982\uFF1A\u7528\u6237\u5217\u8868\u63A5\u53E3" value="' + escapeHtml(mock.description || '') + '" style="width: 100%; margin-top: 0.25rem;" />',
1581
+ ' </label>',
1582
+ ' <label>Delay <input type="number" id="delay-input" value="' + mock.config.delay + '" min="0" step="50" /> ms</label>',
1583
+ ' <label>Status <input type="number" id="status-input" value="' + mock.config.status + '" min="100" max="599" /></label>',
1584
+ ' ' + renderToggleSection(mock),
1585
+ ' </div>',
1586
+ ' <h3>Response Data</h3>',
1587
+ ' ' + renderDataSection(mock),
1588
+ '</div>'
1589
+ ].join('\\n');
1590
+
1591
+ const descriptionInput = document.getElementById('description-input');
1592
+ if (descriptionInput) {
1593
+ descriptionInput.addEventListener('change', () => updateDescription(descriptionInput.value));
1594
+ }
1595
+
1596
+ if (allowToggle) {
1597
+ const enableToggle = document.getElementById('toggle-enable');
1598
+ if (enableToggle) {
1599
+ enableToggle.addEventListener('change', () => updateConfig({ enable: enableToggle.checked }));
1600
+ }
1601
+ }
1602
+
1603
+ const delayInput = document.getElementById('delay-input');
1604
+ if (delayInput) {
1605
+ delayInput.addEventListener('change', () => updateConfig({ delay: Number(delayInput.value) || 0 }));
1606
+ }
1607
+
1608
+ const statusInput = document.getElementById('status-input');
1609
+ if (statusInput) {
1610
+ statusInput.addEventListener('change', () => updateConfig({ status: Number(statusInput.value) || 200 }));
1611
+ }
1612
+
1613
+ if (mock.editable) {
1614
+ const textarea = document.getElementById('data-editor');
1615
+ if (textarea) {
1616
+ textarea.value = mock.dataText || '';
1617
+ const saveBtn = document.getElementById('save-btn');
1618
+ if (saveBtn) {
1619
+ saveBtn.addEventListener('click', async () => {
1620
+ try {
1621
+ const raw = textarea.value || 'null';
1622
+ const parsed = JSON.parse(raw);
1623
+ await updateConfig({ data: parsed });
1624
+ textarea.classList.remove('error');
1625
+ } catch (err) {
1626
+ textarea.classList.add('error');
1627
+ alert('Invalid JSON: ' + err.message);
1628
+ }
1629
+ });
1630
+ }
1631
+ }
1632
+ } else {
1633
+ const pre = document.getElementById('data-preview');
1634
+ if (pre) {
1635
+ pre.textContent = mock.dataText || '';
1636
+ }
1637
+ }
1638
+ }
1639
+
1640
+ let currentMocks = [];
1641
+
1642
+ async function updateConfig(partial) {
1643
+ if (!window.currentKey) return;
1644
+ if (!allowToggle && 'enable' in partial) {
1645
+ delete partial.enable;
1646
+ }
1647
+ const res = await fetch(apiBase + '/update', {
1648
+ method: 'POST',
1649
+ headers: { 'Content-Type': 'application/json' },
1650
+ body: JSON.stringify({ key: window.currentKey, config: partial })
1651
+ });
1652
+ const data = await res.json();
1653
+ const updated = data.mock;
1654
+ const index = currentMocks.findIndex((item) => item.key === window.currentKey);
1655
+ if (index >= 0) {
1656
+ currentMocks[index] = updated;
1657
+ renderDetails(updated);
1658
+ }
1659
+ }
1660
+
1661
+ async function updateDescription(description) {
1662
+ if (!window.currentKey) return;
1663
+ try {
1664
+ const res = await fetch(apiBase + '/update', {
1665
+ method: 'POST',
1666
+ headers: { 'Content-Type': 'application/json' },
1667
+ body: JSON.stringify({ key: window.currentKey, description: description })
1668
+ });
1669
+ const data = await res.json();
1670
+ const updated = data.mock;
1671
+ const index = currentMocks.findIndex((item) => item.key === window.currentKey);
1672
+ if (index >= 0) {
1673
+ currentMocks[index] = updated;
1674
+ renderDetails(updated);
1675
+ // \u91CD\u65B0\u6E32\u67D3\u5217\u8868\u4EE5\u66F4\u65B0\u663E\u793A
1676
+ renderMockList(currentMocks, true);
1677
+ }
1678
+ } catch (error) {
1679
+ console.error('[Inspector] Failed to update description:', error);
1680
+ alert('\u66F4\u65B0\u63CF\u8FF0\u5931\u8D25: ' + error.message);
1681
+ }
1682
+ }
1683
+
1684
+ async function selectMock(key, button) {
1685
+ window.currentKey = key;
1686
+ document.querySelectorAll('aside button').forEach((btn) => btn.classList.remove('active'));
1687
+ button.classList.add('active');
1688
+ const res = await fetch(apiBase + '/detail?key=' + encodeURIComponent(key));
1689
+ const data = await res.json();
1690
+ const mock = data.mock;
1691
+ const index = currentMocks.findIndex((item) => item.key === key);
1692
+ if (index >= 0) {
1693
+ currentMocks[index] = mock;
1694
+ }
1695
+ renderDetails(mock);
1696
+ }
1697
+
1698
+ async function toggleMockEnable(key, enable) {
1699
+ try {
1700
+ const res = await fetch(apiBase + '/update', {
1701
+ method: 'POST',
1702
+ headers: { 'Content-Type': 'application/json' },
1703
+ body: JSON.stringify({ key: key, config: { enable: enable } })
1704
+ });
1705
+ const data = await res.json();
1706
+ const updated = data.mock;
1707
+ const index = currentMocks.findIndex((item) => item.key === key);
1708
+ if (index >= 0) {
1709
+ currentMocks[index] = updated;
1710
+ // \u5982\u679C\u5F53\u524D\u6B63\u5728\u67E5\u770B\u8FD9\u4E2A mock\uFF0C\u66F4\u65B0\u8BE6\u60C5
1711
+ if (window.currentKey === key) {
1712
+ renderDetails(updated);
1713
+ }
1714
+ }
1715
+ } catch (error) {
1716
+ console.error('[Inspector] Failed to toggle mock:', error);
1717
+ alert('\u66F4\u65B0\u5931\u8D25: ' + error.message);
1718
+ }
1719
+ }
1720
+
1721
+ function startEditDescription(li, mock) {
1722
+ // \u6E05\u7A7A li \u5185\u5BB9\uFF0C\u521B\u5EFA\u7F16\u8F91\u6846
1723
+ li.innerHTML = '';
1724
+
1725
+ const input = document.createElement('input');
1726
+ input.type = 'text';
1727
+ input.className = 'description-edit';
1728
+ input.value = mock.description || '';
1729
+ input.placeholder = '\u8F93\u5165\u4E1A\u52A1\u63CF\u8FF0\uFF0C\u4F8B\u5982\uFF1A\u7528\u6237\u5217\u8868\u63A5\u53E3';
1730
+
1731
+ const saveEdit = async () => {
1732
+ const newDescription = input.value.trim();
1733
+ try {
1734
+ const res = await fetch(apiBase + '/update', {
1735
+ method: 'POST',
1736
+ headers: { 'Content-Type': 'application/json' },
1737
+ body: JSON.stringify({ key: mock.key, description: newDescription })
1738
+ });
1739
+ const data = await res.json();
1740
+ const updated = data.mock;
1741
+ const index = currentMocks.findIndex((item) => item.key === mock.key);
1742
+ if (index >= 0) {
1743
+ currentMocks[index] = updated;
1744
+ }
1745
+ // \u91CD\u65B0\u6E32\u67D3\u5217\u8868
1746
+ renderMockList(currentMocks, true);
1747
+ // \u5982\u679C\u5F53\u524D\u6B63\u5728\u67E5\u770B\u8FD9\u4E2A mock\uFF0C\u66F4\u65B0\u8BE6\u60C5
1748
+ if (window.currentKey === mock.key) {
1749
+ renderDetails(updated);
1750
+ }
1751
+ } catch (error) {
1752
+ console.error('[Inspector] Failed to update description:', error);
1753
+ alert('\u66F4\u65B0\u5931\u8D25: ' + error.message);
1754
+ renderMockList(currentMocks, true);
1755
+ }
1756
+ };
1757
+
1758
+ input.addEventListener('blur', saveEdit);
1759
+ input.addEventListener('keydown', (e) => {
1760
+ if (e.key === 'Enter') {
1761
+ saveEdit();
1762
+ } else if (e.key === 'Escape') {
1763
+ renderMockList(currentMocks, true);
1764
+ }
1765
+ });
1766
+
1767
+ li.appendChild(input);
1768
+ input.focus();
1769
+ input.select();
1770
+ }
1771
+
1772
+ async function enableAllMocks() {
1773
+ const promises = currentMocks.map(mock =>
1774
+ toggleMockEnable(mock.key, true)
1775
+ );
1776
+ await Promise.all(promises);
1777
+ // \u91CD\u65B0\u83B7\u53D6\u5217\u8868\u4EE5\u66F4\u65B0 UI
1778
+ currentMocks = await fetchMocks();
1779
+ renderMockList(currentMocks, true);
1780
+ }
1781
+
1782
+ async function disableAllMocks() {
1783
+ const promises = currentMocks.map(mock =>
1784
+ toggleMockEnable(mock.key, false)
1785
+ );
1786
+ await Promise.all(promises);
1787
+ // \u91CD\u65B0\u83B7\u53D6\u5217\u8868\u4EE5\u66F4\u65B0 UI
1788
+ currentMocks = await fetchMocks();
1789
+ renderMockList(currentMocks, true);
1790
+ }
1791
+
1792
+ // Initialize sidebar resizer functionality
1793
+ function initSidebarResizer() {
1794
+ const sidebar = document.getElementById('sidebar');
1795
+ const resizer = document.getElementById('resizer');
1796
+ const main = document.querySelector('main');
1797
+
1798
+ if (!sidebar || !resizer || !main) {
1799
+ console.warn('[Inspector] Sidebar resizer elements not found');
1800
+ return;
1801
+ }
1802
+
1803
+ // Load saved width from localStorage
1804
+ const savedWidth = localStorage.getItem('mockInspectorSidebarWidth');
1805
+ if (savedWidth) {
1806
+ const width = Math.max(200, Math.min(800, parseInt(savedWidth, 10)));
1807
+ main.style.setProperty('--sidebar-width', width + 'px');
1808
+ }
1809
+
1810
+ let isResizing = false;
1811
+ let startX = 0;
1812
+ let startWidth = 0;
1813
+
1814
+ resizer.addEventListener('mousedown', (e) => {
1815
+ isResizing = true;
1816
+ startX = e.clientX;
1817
+ startWidth = sidebar.offsetWidth;
1818
+ resizer.classList.add('active');
1819
+ document.body.style.cursor = 'col-resize';
1820
+ document.body.style.userSelect = 'none';
1821
+ e.preventDefault();
1822
+ });
1823
+
1824
+ document.addEventListener('mousemove', (e) => {
1825
+ if (!isResizing) return;
1826
+
1827
+ const deltaX = e.clientX - startX;
1828
+ const newWidth = Math.max(200, Math.min(800, startWidth + deltaX));
1829
+ main.style.setProperty('--sidebar-width', newWidth + 'px');
1830
+ });
1831
+
1832
+ document.addEventListener('mouseup', () => {
1833
+ if (isResizing) {
1834
+ isResizing = false;
1835
+ resizer.classList.remove('active');
1836
+ document.body.style.cursor = '';
1837
+ document.body.style.userSelect = '';
1838
+
1839
+ // Save width to localStorage
1840
+ const currentWidth = sidebar.offsetWidth;
1841
+ localStorage.setItem('mockInspectorSidebarWidth', currentWidth.toString());
1842
+ }
1843
+ });
1844
+
1845
+ // Touch support for mobile devices
1846
+ resizer.addEventListener('touchstart', (e) => {
1847
+ const touch = e.touches[0];
1848
+ isResizing = true;
1849
+ startX = touch.clientX;
1850
+ startWidth = sidebar.offsetWidth;
1851
+ resizer.classList.add('active');
1852
+ e.preventDefault();
1853
+ }, { passive: false });
1854
+
1855
+ document.addEventListener('touchmove', (e) => {
1856
+ if (!isResizing) return;
1857
+
1858
+ const touch = e.touches[0];
1859
+ const deltaX = touch.clientX - startX;
1860
+ const newWidth = Math.max(200, Math.min(800, startWidth + deltaX));
1861
+ main.style.setProperty('--sidebar-width', newWidth + 'px');
1862
+ }, { passive: false });
1863
+
1864
+ document.addEventListener('touchend', () => {
1865
+ if (isResizing) {
1866
+ isResizing = false;
1867
+ resizer.classList.remove('active');
1868
+
1869
+ // Save width to localStorage
1870
+ const currentWidth = sidebar.offsetWidth;
1871
+ localStorage.setItem('mockInspectorSidebarWidth', currentWidth.toString());
1872
+ }
1873
+ });
1874
+ }
1875
+
1876
+ async function bootstrap() {
1877
+ // Initialize sidebar resizer
1878
+ initSidebarResizer();
1879
+
1880
+ try {
1881
+ currentMocks = await fetchMocks();
1882
+ renderMockList(currentMocks, true);
1883
+
1884
+ // \u7ED1\u5B9A\u5168\u5C40\u63A7\u5236\u6309\u94AE
1885
+ const enableAllBtn = document.getElementById('enable-all');
1886
+ const disableAllBtn = document.getElementById('disable-all');
1887
+ if (enableAllBtn) {
1888
+ enableAllBtn.addEventListener('click', async () => {
1889
+ enableAllBtn.disabled = true;
1890
+ enableAllBtn.textContent = '\u5904\u7406\u4E2D...';
1891
+ await enableAllMocks();
1892
+ enableAllBtn.disabled = false;
1893
+ enableAllBtn.textContent = '\u2713 \u5F00\u542F\u6240\u6709';
1894
+ });
1895
+ }
1896
+ if (disableAllBtn) {
1897
+ disableAllBtn.addEventListener('click', async () => {
1898
+ disableAllBtn.disabled = true;
1899
+ disableAllBtn.textContent = '\u5904\u7406\u4E2D...';
1900
+ await disableAllMocks();
1901
+ disableAllBtn.disabled = false;
1902
+ disableAllBtn.textContent = '\u2717 \u5173\u95ED\u6240\u6709';
1903
+ });
1904
+ }
1905
+
1906
+ // \u7ED1\u5B9A\u65B0\u5EFAAPI\u6309\u94AE
1907
+ const newApiBtn = document.getElementById('new-api-btn');
1908
+ const newApiModal = document.getElementById('new-api-modal');
1909
+ const newApiForm = document.getElementById('new-api-form');
1910
+ const cancelNewApi = document.getElementById('cancel-new-api');
1911
+
1912
+ if (newApiBtn && newApiModal) {
1913
+ newApiBtn.addEventListener('click', () => {
1914
+ newApiModal.classList.add('show');
1915
+ document.getElementById('new-api-path').focus();
1916
+ });
1917
+ }
1918
+
1919
+ if (cancelNewApi && newApiModal) {
1920
+ cancelNewApi.addEventListener('click', () => {
1921
+ newApiModal.classList.remove('show');
1922
+ newApiForm.reset();
1923
+ });
1924
+ }
1925
+
1926
+ // \u70B9\u51FB\u80CC\u666F\u5173\u95ED\u6A21\u6001\u6846
1927
+ if (newApiModal) {
1928
+ newApiModal.addEventListener('click', (e) => {
1929
+ if (e.target === newApiModal) {
1930
+ newApiModal.classList.remove('show');
1931
+ newApiForm.reset();
1932
+ }
1933
+ });
1934
+ }
1935
+
1936
+ // \u5904\u7406\u8868\u5355\u63D0\u4EA4
1937
+ if (newApiForm) {
1938
+ newApiForm.addEventListener('submit', async (e) => {
1939
+ e.preventDefault();
1940
+
1941
+ const method = document.getElementById('new-api-method').value;
1942
+ const path = document.getElementById('new-api-path').value.trim();
1943
+ const description = document.getElementById('new-api-description').value.trim();
1944
+ const dataText = document.getElementById('new-api-data').value.trim();
1945
+
1946
+ if (!path) {
1947
+ alert('\u8BF7\u8F93\u5165 API \u8DEF\u5F84');
1948
+ return;
1949
+ }
1950
+
1951
+ // \u9A8C\u8BC1JSON
1952
+ let data;
1953
+ try {
1954
+ data = JSON.parse(dataText || '{}');
1955
+ } catch (err) {
1956
+ alert('Response Data \u4E0D\u662F\u6709\u6548\u7684 JSON: ' + err.message);
1957
+ return;
1958
+ }
1959
+
1960
+ // \u53D1\u9001\u521B\u5EFA\u8BF7\u6C42
1961
+ try {
1962
+ const submitBtn = newApiForm.querySelector('button[type="submit"]');
1963
+ const originalText = submitBtn.textContent;
1964
+ submitBtn.disabled = true;
1965
+ submitBtn.textContent = 'Creating...';
1966
+
1967
+ const res = await fetch(apiBase + '/create', {
1968
+ method: 'POST',
1969
+ headers: { 'Content-Type': 'application/json' },
1970
+ body: JSON.stringify({
1971
+ method: method,
1972
+ path: path,
1973
+ description: description || path,
1974
+ data: data
1975
+ })
1976
+ });
1977
+
1978
+ const result = await res.json();
1979
+
1980
+ if (!res.ok) {
1981
+ throw new Error(result.error || 'Failed to create API');
1982
+ }
1983
+
1984
+ // \u5173\u95ED\u6A21\u6001\u6846
1985
+ newApiModal.classList.remove('show');
1986
+ newApiForm.reset();
1987
+
1988
+ // \u5237\u65B0\u5217\u8868
1989
+ currentMocks = await fetchMocks();
1990
+ renderMockList(currentMocks, true);
1991
+
1992
+ // \u81EA\u52A8\u9009\u4E2D\u65B0\u521B\u5EFA\u7684 API
1993
+ if (result.mock && result.mock.key) {
1994
+ const button = document.querySelector('aside button[data-key="' + result.mock.key + '"]');
1995
+ if (button) {
1996
+ await selectMock(result.mock.key, button);
1997
+ }
1998
+ }
1999
+
2000
+ alert('\u2705 API Mock \u521B\u5EFA\u6210\u529F\uFF01');
2001
+
2002
+ submitBtn.disabled = false;
2003
+ submitBtn.textContent = originalText;
2004
+ } catch (err) {
2005
+ alert('\u521B\u5EFA\u5931\u8D25: ' + err.message);
2006
+ const submitBtn = newApiForm.querySelector('button[type="submit"]');
2007
+ submitBtn.disabled = false;
2008
+ submitBtn.textContent = 'Create';
2009
+ }
2010
+ });
2011
+ }
2012
+ } catch (error) {
2013
+ console.error('[Inspector] Bootstrap failed:', error);
2014
+ }
2015
+ }
2016
+
2017
+ bootstrap();
2018
+ </script>
2019
+
2020
+ <!-- Delete Confirmation Modal -->
2021
+ <div id="delete-confirm-modal" class="modal-overlay">
2022
+ <div class="modal" style="max-width: 400px;">
2023
+ <h2><span class="btn-icon-cross" style="color: var(--accent-rose);">!</span> \u786E\u8BA4\u5220\u9664</h2>
2024
+ <p id="delete-confirm-message" style="margin-bottom: 1rem; color: var(--text-secondary);"></p>
2025
+ <label style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem; cursor: pointer; user-select: none;">
2026
+ <input type="checkbox" id="delete-never-ask" style="flex-shrink: 0;" />
2027
+ <span>\u4E0D\u518D\u63D0\u9192</span>
2028
+ </label>
2029
+ <div style="display: flex; gap: 0.75rem; justify-content: flex-end;">
2030
+ <button id="delete-cancel-btn" class="secondary">\u53D6\u6D88</button>
2031
+ <button id="delete-confirm-btn" class="primary" style="background: var(--accent-rose);">\u5220\u9664</button>
2032
+ </div>
2033
+ </div>
2034
+ </div>
2035
+ </body>
2036
+ </html>`;
2037
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
2038
+ res.end(html);
2039
+ }
2040
+ async function handleInspectorApi({
2041
+ res,
2042
+ req,
2043
+ pathname,
2044
+ mockDir,
2045
+ apiPrefix,
2046
+ inspectorConfig,
2047
+ getMockFileMap
2048
+ }) {
2049
+ try {
2050
+ const mockFileMap = getMockFileMap();
2051
+ if (pathname === "list") {
2052
+ const list = await Promise.all(
2053
+ Array.from(mockFileMap.entries()).map(async ([key, filePath]) => {
2054
+ const info = await parseMockModule(filePath);
2055
+ return {
2056
+ key,
2057
+ file: path.relative(mockDir, filePath),
2058
+ method: key.split("/").pop()?.replace(/\.js$/, "") ?? "get",
2059
+ path: key.replace(/\/[^/]+\.js$/, ""),
2060
+ config: info.config,
2061
+ editable: info.serializable,
2062
+ description: info.description,
2063
+ dataText: info.dataText
2064
+ };
2065
+ })
2066
+ );
2067
+ sendJson(res, { mocks: list });
2068
+ return;
2069
+ }
2070
+ if (pathname === "detail") {
2071
+ const url = new URL(req.url || "", "http://localhost");
2072
+ const key = url.searchParams.get("key");
2073
+ if (!key) {
2074
+ sendJson(res, { error: "Missing key" }, 400);
2075
+ return;
2076
+ }
2077
+ const filePath = mockFileMap.get(key);
2078
+ if (!filePath) {
2079
+ sendJson(res, { error: "Mock not found" }, 404);
2080
+ return;
2081
+ }
2082
+ const info = await parseMockModule(filePath);
2083
+ sendJson(res, {
2084
+ mock: {
2085
+ key,
2086
+ file: path.relative(mockDir, filePath),
2087
+ method: key.split("/").pop()?.replace(/\.js$/, "") ?? "get",
2088
+ path: key.replace(/\/[^/]+\.js$/, ""),
2089
+ config: info.config,
2090
+ editable: info.serializable,
2091
+ description: info.description,
2092
+ dataText: info.dataText
2093
+ }
2094
+ });
2095
+ return;
2096
+ }
2097
+ if (pathname === "update") {
2098
+ if (req.method !== "POST") {
2099
+ sendJson(res, { error: "Method not allowed" }, 405);
2100
+ return;
2101
+ }
2102
+ const body = await readBody(req);
2103
+ let payload;
2104
+ try {
2105
+ payload = JSON.parse(body);
2106
+ } catch (error) {
2107
+ sendJson(res, { error: "Invalid JSON body" }, 400);
2108
+ return;
2109
+ }
2110
+ const { key, config, description } = payload || {};
2111
+ if (!key) {
2112
+ sendJson(res, { error: "Invalid payload: missing key" }, 400);
2113
+ return;
2114
+ }
2115
+ const filePath = mockFileMap.get(key);
2116
+ if (!filePath) {
2117
+ sendJson(res, { error: "Mock not found" }, 404);
2118
+ return;
2119
+ }
2120
+ const info = await parseMockModule(filePath);
2121
+ let nextConfig = info.config;
2122
+ if (config && typeof config === "object") {
2123
+ if (!inspectorConfig.enableToggle && config.enable !== void 0) {
2124
+ delete config.enable;
2125
+ }
2126
+ nextConfig = {
2127
+ ...info.config,
2128
+ ...config
2129
+ };
2130
+ }
2131
+ const nextDescription = description !== void 0 ? description : info.description;
2132
+ await writeMockFile(filePath, {
2133
+ headerComment: info.headerComment,
2134
+ config: nextConfig,
2135
+ description: nextDescription
2136
+ });
2137
+ const updatedInfo = await parseMockModule(filePath);
2138
+ sendJson(res, {
2139
+ mock: {
2140
+ key,
2141
+ file: path.relative(mockDir, filePath),
2142
+ method: key.split("/").pop()?.replace(/\.js$/, "") ?? "get",
2143
+ path: key.replace(/\/[^/]+\.js$/, ""),
2144
+ config: updatedInfo.config,
2145
+ editable: updatedInfo.serializable,
2146
+ description: updatedInfo.description,
2147
+ dataText: updatedInfo.dataText
2148
+ }
2149
+ });
2150
+ return;
2151
+ }
2152
+ if (pathname === "create") {
2153
+ if (req.method !== "POST") {
2154
+ sendJson(res, { error: "Method not allowed" }, 405);
2155
+ return;
2156
+ }
2157
+ const body = await readBody(req);
2158
+ let payload;
2159
+ try {
2160
+ payload = JSON.parse(body);
2161
+ } catch (error) {
2162
+ sendJson(res, { error: "Invalid JSON body" }, 400);
2163
+ return;
2164
+ }
2165
+ const { method, path: apiPath, description, data } = payload || {};
2166
+ if (!method || !apiPath) {
2167
+ sendJson(
2168
+ res,
2169
+ { error: "Invalid payload: missing method or path" },
2170
+ 400
2171
+ );
2172
+ return;
2173
+ }
2174
+ const { saveMockData: saveMockData2 } = await import("./mockFileUtils-HQCNPI3U.mjs");
2175
+ const fullUrl = apiPrefix + apiPath;
2176
+ try {
2177
+ let dataToSave;
2178
+ if (typeof data === "object" && data !== null) {
2179
+ dataToSave = JSON.stringify(data, null, 2);
2180
+ } else {
2181
+ dataToSave = typeof data === "string" ? data : "";
2182
+ }
2183
+ await saveMockData2(
2184
+ fullUrl,
2185
+ method.toLowerCase(),
2186
+ dataToSave,
2187
+ mockDir,
2188
+ 200
2189
+ );
2190
+ const { buildMockIndex: buildMockIndex2 } = await import("./mockFileUtils-HQCNPI3U.mjs");
2191
+ const newMockFileMap = await buildMockIndex2(mockDir);
2192
+ for (const [key2, value] of newMockFileMap.entries()) {
2193
+ mockFileMap.set(key2, value);
2194
+ }
2195
+ const key = apiPath + "/" + method.toLowerCase() + ".js";
2196
+ const filePath = mockFileMap.get(key);
2197
+ if (!filePath) {
2198
+ sendJson(
2199
+ res,
2200
+ { error: "Mock file created but not found in map" },
2201
+ 500
2202
+ );
2203
+ return;
2204
+ }
2205
+ const info = await parseMockModule(filePath);
2206
+ sendJson(res, {
2207
+ success: true,
2208
+ mock: {
2209
+ key,
2210
+ file: path.relative(mockDir, filePath),
2211
+ method: method.toLowerCase(),
2212
+ path: apiPath,
2213
+ config: info.config,
2214
+ editable: info.serializable,
2215
+ description: info.description,
2216
+ dataText: info.dataText
2217
+ }
2218
+ });
2219
+ return;
2220
+ } catch (error) {
2221
+ const errorMessage = error instanceof Error ? error.message : String(error);
2222
+ sendJson(res, { error: "Failed to create mock: " + errorMessage }, 500);
2223
+ return;
2224
+ }
2225
+ }
2226
+ if (pathname === "delete") {
2227
+ const url = new URL(req.url || "", "http://localhost");
2228
+ const key = url.searchParams.get("key");
2229
+ if (!key) {
2230
+ sendJson(res, { error: "Missing key" }, 400);
2231
+ return;
2232
+ }
2233
+ const filePath = mockFileMap.get(key);
2234
+ if (!filePath) {
2235
+ sendJson(res, { error: "Mock not found" }, 404);
2236
+ return;
2237
+ }
2238
+ const { unlink, rm } = await import("fs/promises");
2239
+ const { stat } = await import("fs/promises");
2240
+ try {
2241
+ const stats = await stat(filePath);
2242
+ if (stats.isDirectory()) {
2243
+ await rm(filePath, { recursive: true, force: true });
2244
+ for (const [mapKey, mapPath] of mockFileMap.entries()) {
2245
+ if (mapPath.startsWith(filePath + path.sep) || mapPath === filePath) {
2246
+ mockFileMap.delete(mapKey);
2247
+ }
2248
+ }
2249
+ } else {
2250
+ await unlink(filePath);
2251
+ mockFileMap.delete(key);
2252
+ }
2253
+ sendJson(res, { success: true });
2254
+ } catch (error) {
2255
+ const errorMessage = error instanceof Error ? error.message : String(error);
2256
+ sendJson(res, { error: "Failed to delete: " + errorMessage }, 500);
2257
+ }
2258
+ return;
2259
+ }
2260
+ sendJson(res, { error: "Unknown inspector endpoint" }, 404);
2261
+ } catch (error) {
2262
+ console.error("\u274C [automock] Inspector request failed:", error);
2263
+ sendJson(res, { error: "Inspector failed" }, 500);
2264
+ }
2265
+ }
2266
+ function sendJson(res, payload, status = 200) {
2267
+ res.statusCode = status;
2268
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2269
+ res.end(JSON.stringify(payload));
2270
+ }
2271
+ function readBody(req) {
2272
+ return new Promise((resolve, reject) => {
2273
+ const chunks = [];
2274
+ req.on("data", (chunk) => chunks.push(chunk));
2275
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
2276
+ req.on("error", reject);
2277
+ });
2278
+ }
2279
+
2280
+ // src/middleware.ts
2281
+ function automock(options) {
2282
+ const {
2283
+ mockDir: configMockDir = path2.join(process.cwd(), "mock"),
2284
+ apiPrefix = "/api",
2285
+ pathRewrite = (p) => p,
2286
+ proxyBaseUrl,
2287
+ inspector = false
2288
+ } = options;
2289
+ const mockDir = path2.isAbsolute(configMockDir) ? configMockDir : path2.resolve(process.cwd(), configMockDir);
2290
+ if (!fs.existsSync(mockDir)) {
2291
+ try {
2292
+ fs.ensureDirSync(mockDir);
2293
+ console.log(`\u2705 [automock] Mock directory created: ${mockDir}`);
2294
+ } catch (error) {
2295
+ console.error(`\u274C [automock] \u521B\u5EFA Mock \u76EE\u5F55\u5931\u8D25: ${mockDir}`, error);
2296
+ }
2297
+ }
2298
+ let watcher;
2299
+ return {
2300
+ name: "vite-plugin-automock",
2301
+ config() {
2302
+ },
2303
+ configureServer(server) {
2304
+ let mockFileMap = buildMockIndex(mockDir);
2305
+ console.log(`\u2705 [automock] Loaded ${mockFileMap.size} mock files`);
2306
+ const rebuildMockFileMap = debounce(() => {
2307
+ mockFileMap = buildMockIndex(mockDir);
2308
+ }, 200);
2309
+ watcher = chokidar.watch(mockDir, {
2310
+ ignoreInitial: true,
2311
+ persistent: true,
2312
+ depth: 30
2313
+ });
2314
+ watcher.on("add", () => rebuildMockFileMap());
2315
+ watcher.on("unlink", () => rebuildMockFileMap());
2316
+ server.httpServer?.on("close", () => {
2317
+ watcher?.close();
2318
+ });
2319
+ const inspectorHandler = createInspectorHandler({
2320
+ inspector,
2321
+ apiPrefix,
2322
+ mockDir,
2323
+ getMockFileMap: () => mockFileMap
2324
+ });
2325
+ if (inspector) {
2326
+ const inspectorConfig = normalizeInspectorConfig(inspector);
2327
+ server.httpServer?.once("listening", () => {
2328
+ setTimeout(() => {
2329
+ const address = server.httpServer?.address();
2330
+ if (address && typeof address === "object") {
2331
+ const protocol = server.config.server.https ? "https" : "http";
2332
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.address;
2333
+ const port = address.port;
2334
+ const inspectorUrl = `${protocol}://${host}:${port}${inspectorConfig.route}`;
2335
+ console.log(
2336
+ ` \u279C \x1B[36mMock Inspector\x1B[0m: \x1B[1m${inspectorUrl}\x1B[0m`
2337
+ );
2338
+ }
2339
+ }, 100);
2340
+ });
2341
+ }
2342
+ server.middlewares.use(
2343
+ async (req, res, next) => {
2344
+ if (inspectorHandler && req.url) {
2345
+ const handled = await inspectorHandler(req, res);
2346
+ if (handled) {
2347
+ return;
2348
+ }
2349
+ }
2350
+ if (!req.url?.startsWith(apiPrefix)) {
2351
+ return next();
2352
+ }
2353
+ const method = (req.method || "GET").toLowerCase();
2354
+ const urlObj = new URL(req.url, "http://localhost");
2355
+ const pathname = urlObj.pathname;
2356
+ const key = `${pathname}/${method}.js`.toLowerCase();
2357
+ const isExist = mockFileMap.has(key);
2358
+ if (isExist) {
2359
+ try {
2360
+ const mockFilePath = mockFileMap.get(key);
2361
+ const absolutePath = path2.isAbsolute(mockFilePath) ? mockFilePath : path2.resolve(process.cwd(), mockFilePath);
2362
+ if (!fs.existsSync(absolutePath)) {
2363
+ throw new Error(`Mock file does not exist: ${absolutePath}`);
2364
+ }
2365
+ const { default: mockModule } = await import(`${absolutePath}?t=${Date.now()}`);
2366
+ const mockResult = typeof mockModule.data === "function" ? mockModule.data() : mockModule;
2367
+ const {
2368
+ enable = true,
2369
+ data,
2370
+ delay = 0,
2371
+ status = 200
2372
+ } = mockResult || {};
2373
+ if (enable) {
2374
+ setTimeout(() => {
2375
+ const isBinaryMock = data?.__binaryFile;
2376
+ if (isBinaryMock) {
2377
+ const binaryFilePath = absolutePath.replace(
2378
+ /\.js$/,
2379
+ "." + data.__binaryFile
2380
+ );
2381
+ if (fs.existsSync(binaryFilePath)) {
2382
+ try {
2383
+ const binaryData = fs.readFileSync(binaryFilePath);
2384
+ const contentType = data.__contentType || "application/octet-stream";
2385
+ res.setHeader("Content-Type", contentType);
2386
+ res.setHeader("Content-Length", binaryData.length);
2387
+ res.setHeader("X-Mock-Response", "true");
2388
+ res.setHeader("X-Mock-Source", "vite-plugin-automock");
2389
+ res.setHeader("X-Mock-Binary-File", "true");
2390
+ res.statusCode = status;
2391
+ res.end(binaryData);
2392
+ } catch (error) {
2393
+ console.error(
2394
+ "\u274C [automock] \u8BFB\u53D6\u4E8C\u8FDB\u5236mock\u6587\u4EF6\u5931\u8D25:",
2395
+ error
2396
+ );
2397
+ res.statusCode = 500;
2398
+ res.end(
2399
+ JSON.stringify({
2400
+ error: "Failed to read binary mock file"
2401
+ })
2402
+ );
2403
+ }
2404
+ } else {
2405
+ console.error(
2406
+ "\u274C [automock] \u4E8C\u8FDB\u5236mock\u6587\u4EF6\u4E0D\u5B58\u5728:",
2407
+ binaryFilePath
2408
+ );
2409
+ res.statusCode = 404;
2410
+ res.end(
2411
+ JSON.stringify({ error: "Binary mock file not found" })
2412
+ );
2413
+ }
2414
+ } else {
2415
+ res.setHeader(
2416
+ "Content-Type",
2417
+ "application/json; charset=utf-8"
2418
+ );
2419
+ res.setHeader("X-Mock-Response", "true");
2420
+ res.setHeader("X-Mock-Source", "vite-plugin-automock");
2421
+ res.statusCode = status;
2422
+ res.end(
2423
+ typeof data === "string" ? data : JSON.stringify(data)
2424
+ );
2425
+ }
2426
+ }, delay);
2427
+ return;
2428
+ }
2429
+ } catch (error) {
2430
+ console.error(`\u274C [automock] \u52A0\u8F7D mock \u6587\u4EF6\u5931\u8D25:`, error);
2431
+ }
2432
+ }
2433
+ const shouldSaveMockData = !isExist;
2434
+ if (!proxyBaseUrl) {
2435
+ res.statusCode = 404;
2436
+ res.end(
2437
+ JSON.stringify({
2438
+ error: "No mock found and proxyBaseUrl not configured"
2439
+ })
2440
+ );
2441
+ return;
2442
+ }
2443
+ try {
2444
+ let sendProxyRequest2 = function(body) {
2445
+ const targetUrlObj = new URL(proxyBaseUrl);
2446
+ const proxyOptions = {
2447
+ method: req.method,
2448
+ headers: {
2449
+ ...req.headers,
2450
+ host: targetUrlObj.host
2451
+ // Override Host header with target server's host
2452
+ },
2453
+ rejectUnauthorized: false
2454
+ };
2455
+ const proxyReq = client.request(
2456
+ targetUrl,
2457
+ proxyOptions,
2458
+ (proxyRes) => {
2459
+ const contentType = proxyRes.headers["content-type"];
2460
+ const chunks = [];
2461
+ proxyRes.on("data", (chunk) => {
2462
+ chunks.push(chunk);
2463
+ });
2464
+ proxyRes.on("end", async () => {
2465
+ try {
2466
+ const responseData = Buffer.concat(chunks);
2467
+ if (shouldSaveMockData) {
2468
+ try {
2469
+ console.log(
2470
+ `\u{1F504} [automock] \u5C1D\u8BD5\u4FDD\u5B58 mock: ${req.url} -> ${pathname}`
2471
+ );
2472
+ const savedFilePath = await saveMockData(
2473
+ req.url,
2474
+ method,
2475
+ responseData,
2476
+ mockDir,
2477
+ proxyRes.statusCode,
2478
+ contentType
2479
+ );
2480
+ if (savedFilePath) {
2481
+ console.log(
2482
+ `\u2705 [automock] \u5DF2\u4FDD\u5B58 mock: ${pathname}`
2483
+ );
2484
+ mockFileMap = buildMockIndex(mockDir);
2485
+ } else {
2486
+ console.log(
2487
+ `\u2139\uFE0F [automock] mock \u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u8DF3\u8FC7: ${pathname}`
2488
+ );
2489
+ }
2490
+ } catch (saveError) {
2491
+ console.error(
2492
+ "\u274C [automock] \u4FDD\u5B58 mock \u5931\u8D25:",
2493
+ saveError
2494
+ );
2495
+ }
2496
+ }
2497
+ res.writeHead(
2498
+ proxyRes.statusCode || 200,
2499
+ proxyRes.headers
2500
+ );
2501
+ res.end(responseData);
2502
+ } catch (error) {
2503
+ console.error("\u274C [automock] \u5904\u7406\u54CD\u5E94\u5931\u8D25:", error);
2504
+ res.writeHead(
2505
+ proxyRes.statusCode || 200,
2506
+ proxyRes.headers
2507
+ );
2508
+ res.end(Buffer.concat(chunks));
2509
+ }
2510
+ });
2511
+ }
2512
+ );
2513
+ proxyReq.on("error", (err) => {
2514
+ console.error("\u274C [automock] \u4EE3\u7406\u8BF7\u6C42\u5931\u8D25:", err);
2515
+ res.statusCode = 500;
2516
+ res.end(JSON.stringify({ error: err.message }));
2517
+ });
2518
+ if (body && (req.method === "POST" || req.method === "PUT" || req.method === "PATCH")) {
2519
+ proxyReq.write(body);
2520
+ }
2521
+ proxyReq.end();
2522
+ };
2523
+ var sendProxyRequest = sendProxyRequest2;
2524
+ const targetUrl = proxyBaseUrl + pathRewrite(req.url || "");
2525
+ const client = targetUrl.startsWith("https") ? https : http;
2526
+ if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
2527
+ let bodyStr = "";
2528
+ req.on("data", (chunk) => {
2529
+ bodyStr += chunk.toString();
2530
+ });
2531
+ req.on("end", () => {
2532
+ sendProxyRequest2(bodyStr);
2533
+ });
2534
+ } else {
2535
+ sendProxyRequest2();
2536
+ }
2537
+ } catch (error) {
2538
+ console.error("\u274C [automock] \u4EE3\u7406\u8BF7\u6C42\u5F02\u5E38:", error);
2539
+ res.statusCode = 500;
2540
+ res.end(JSON.stringify({ error: "Internal server error" }));
2541
+ }
2542
+ }
2543
+ );
2544
+ },
2545
+ closeBundle() {
2546
+ watcher?.close();
2547
+ },
2548
+ transform() {
2549
+ return null;
2550
+ }
2551
+ };
2552
+ }
2553
+
2554
+ // src/mockBundler.ts
2555
+ import path3 from "path";
2556
+ import fs2 from "fs-extra";
2557
+ var DEFAULT_BUNDLE_OPTIONS = {
2558
+ includeDisabled: true,
2559
+ log: true
2560
+ };
2561
+ async function bundleMockFiles(options) {
2562
+ const opts = { ...DEFAULT_BUNDLE_OPTIONS, ...options };
2563
+ const { mockDir, log } = opts;
2564
+ if (!fs2.existsSync(mockDir)) {
2565
+ if (log) {
2566
+ console.log(`[mock-bundler] Mock directory does not exist: ${mockDir}`);
2567
+ }
2568
+ return {};
2569
+ }
2570
+ const mockFileMap = buildMockIndex(mockDir);
2571
+ const bundle = {};
2572
+ let bundledCount = 0;
2573
+ let skippedCount = 0;
2574
+ for (const [key, filePath] of mockFileMap) {
2575
+ try {
2576
+ const mockInfo = await parseMockModule(filePath);
2577
+ if (!mockInfo.serializable) {
2578
+ skippedCount++;
2579
+ if (log) {
2580
+ console.log(`[mock-bundler] Skipping non-serializable mock: ${key}`);
2581
+ }
2582
+ continue;
2583
+ }
2584
+ bundle[key] = {
2585
+ enable: mockInfo.config.enable,
2586
+ data: mockInfo.config.data,
2587
+ delay: mockInfo.config.delay,
2588
+ status: mockInfo.config.status,
2589
+ isBinary: mockInfo.isBinary
2590
+ };
2591
+ bundledCount++;
2592
+ } catch (error) {
2593
+ if (log) {
2594
+ console.error(`[mock-bundler] Failed to bundle mock ${key}:`, error);
2595
+ }
2596
+ }
2597
+ }
2598
+ if (log) {
2599
+ console.log(`[mock-bundler] Bundled ${bundledCount} mocks, skipped ${skippedCount} non-serializable mocks`);
2600
+ }
2601
+ return bundle;
2602
+ }
2603
+ function writeMockBundle(bundle, outputPath) {
2604
+ const outputDir = path3.dirname(outputPath);
2605
+ if (!fs2.existsSync(outputDir)) {
2606
+ fs2.ensureDirSync(outputDir);
2607
+ }
2608
+ fs2.writeFileSync(
2609
+ outputPath,
2610
+ JSON.stringify(bundle, null, 2),
2611
+ "utf-8"
2612
+ );
2613
+ }
2614
+
2615
+ // src/index.ts
2616
+ function automock2(options = {}) {
2617
+ const {
2618
+ bundleMockData = true,
2619
+ bundleOutputPath = "public/mock-data.json",
2620
+ ...pluginOptions
2621
+ } = options;
2622
+ const basePlugin = automock(pluginOptions);
2623
+ let cachedBundle = null;
2624
+ return {
2625
+ ...basePlugin,
2626
+ name: "vite-plugin-automock-with-bundle",
2627
+ buildEnd: async () => {
2628
+ if (bundleMockData && pluginOptions.productionMock !== false) {
2629
+ try {
2630
+ const mockDir = pluginOptions.mockDir || path4.join(process.cwd(), "mock");
2631
+ if (!fs3.existsSync(mockDir)) {
2632
+ console.log("[automock] Mock directory not found, skipping bundle generation");
2633
+ console.log("[automock] Using existing mock-data.json if present");
2634
+ return;
2635
+ }
2636
+ const mockFileMap = buildMockIndex(mockDir);
2637
+ if (mockFileMap.size === 0) {
2638
+ console.log("[automock] No mock files found, skipping bundle generation");
2639
+ return;
2640
+ }
2641
+ cachedBundle = await bundleMockFiles({ mockDir });
2642
+ const outputPath = path4.join(process.cwd(), bundleOutputPath);
2643
+ writeMockBundle(cachedBundle, outputPath);
2644
+ console.log(`[automock] Mock bundle written to: ${outputPath}`);
2645
+ } catch (error) {
2646
+ console.error("[automock] Failed to bundle mock data:", error);
2647
+ }
2648
+ }
2649
+ },
2650
+ writeBundle: async () => {
2651
+ const outputPath = path4.join(process.cwd(), bundleOutputPath);
2652
+ if (!fs3.existsSync(outputPath) && cachedBundle) {
2653
+ console.log("[automock] Re-writing mock bundle in writeBundle...");
2654
+ writeMockBundle(cachedBundle, outputPath);
2655
+ }
2656
+ },
2657
+ closeBundle: async () => {
2658
+ const outputPath = path4.join(process.cwd(), bundleOutputPath);
2659
+ if (!fs3.existsSync(outputPath) && cachedBundle) {
2660
+ console.log("[automock] Re-writing mock bundle in closeBundle...");
2661
+ writeMockBundle(cachedBundle, outputPath);
2662
+ }
2663
+ }
2664
+ };
2665
+ }
2666
+ export {
2667
+ automock2 as automock,
2668
+ buildMockIndex,
2669
+ bundleMockFiles,
2670
+ createMockInterceptor,
2671
+ initMockInterceptor,
2672
+ initMockInterceptorForPureHttp,
2673
+ isMockEnabled,
2674
+ loadMockData,
2675
+ parseMockModule,
2676
+ registerHttpInstance,
2677
+ saveMockData,
2678
+ setMockEnabled,
2679
+ writeMockBundle,
2680
+ writeMockFile
2681
+ };
2682
+ //# sourceMappingURL=index.mjs.map