vite-plugin-mock-dev-server 1.4.7 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,11 +7,12 @@
7
7
  </p>
8
8
 
9
9
  <br>
10
+
10
11
  <p align="center">
11
12
  <a href="https://www.npmjs.com/package/vite-plugin-mock-dev-server"><img alt="npm" src="https://img.shields.io/npm/v/vite-plugin-mock-dev-server?style=flat-square"></a>
12
13
  <img alt="node-current" src="https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square">
13
14
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/vite-plugin-mock-dev-server/peer/vite?style=flat-square">
14
- <img alt="npm" src="https://img.shields.io/npm/dt/vite-plugin-mock-dev-server?style=flat-square">
15
+ <img alt="npm" src="https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square">
15
16
  <br>
16
17
  <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/vite-plugin-mock-dev-server/lint.yml?style=flat-square">
17
18
  <a href="https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_shield"><img alt="fossa status" src="https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=shield"></a>
@@ -67,6 +68,7 @@ pnpm add -D vite-plugin-mock-dev-server
67
68
  ### Configuration
68
69
 
69
70
  `vite.config.ts`
71
+
70
72
  ``` ts
71
73
  import { defineConfig } from 'vite'
72
74
  import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
@@ -84,6 +86,7 @@ export default defineConfig({
84
86
  }
85
87
  })
86
88
  ```
89
+
87
90
  The plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs.
88
91
 
89
92
  The plugin will also read the `define` configuration, which supports direct use in mock files.
@@ -97,6 +100,7 @@ The plugin will also read the `define` configuration, which supports direct use
97
100
  By default, write mock data in the `mock` directory of your project's root directory:
98
101
 
99
102
  `mock/**/*.mock.ts` :
103
+
100
104
  ``` ts
101
105
  import { defineMock } from 'vite-plugin-mock-dev-server'
102
106
 
@@ -113,6 +117,7 @@ export default defineMock({
113
117
  Vite plugin
114
118
 
115
119
  `vite.config.ts`
120
+
116
121
  ``` ts
117
122
  import { defineConfig } from 'vite'
118
123
  import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
@@ -192,6 +197,7 @@ export default defineConfig({
192
197
  **Default:** `{}`
193
198
 
194
199
  example: Configure to file upload dir
200
+
195
201
  ``` ts
196
202
  MockDevServerPlugin({
197
203
  formidableOptions: {
@@ -206,6 +212,12 @@ export default defineConfig({
206
212
 
207
213
  **Default:** `{}`
208
214
 
215
+ - `options.bodyParserOptions`
216
+
217
+ Configure to `co-body`, see [co-body](https://github.com/cojs/co-body#options)
218
+
219
+ **Default:** `{}`
220
+
209
221
  - `options.build`
210
222
 
211
223
  The configuration needed to build a small, independently deployable mock service.
@@ -236,7 +248,7 @@ export default defineConfig({
236
248
 
237
249
  - `options.priority`
238
250
 
239
- Custom path matching rule priority。[read more](#Custom-Path-Matching-Priority)
251
+ Custom path matching rule priority。[read more](#custom-path-matching-priority)
240
252
 
241
253
  **Default:** `undefined`
242
254
 
@@ -399,6 +411,7 @@ export default defineMock({
399
411
  },
400
412
  })
401
413
  ```
414
+
402
415
  ``` ts
403
416
  // Configure the WebSocket mock
404
417
  export default defineMock({
@@ -486,8 +499,10 @@ type defineMockData<T> = (
486
499
  ) => [getter, setter] & { value: T }
487
500
  ```
488
501
 
489
- #### Exp:
502
+ ### Exp
503
+
490
504
  `data.ts`
505
+
491
506
  ```ts
492
507
  import { defineMockData } from 'vite-plugin-mock-dev-server'
493
508
 
@@ -496,7 +511,9 @@ export default defineMockData('posts', [
496
511
  { id: '2', title: 'title2', content: 'content2' },
497
512
  ])
498
513
  ```
514
+
499
515
  `*.mock.ts`
516
+
500
517
  ```ts
501
518
  import { defineMock } from 'vite-plugin-mock-dev-server'
502
519
  import posts from './data'
@@ -529,6 +546,7 @@ export default defineMock([
529
546
  The priority of the path matching rules built into the plugin can already meet most needs, but if you need more flexible customization of the matching rule priority, you can use the `priority` parameter.
530
547
 
531
548
  Exp:
549
+
532
550
  ```ts
533
551
  import { defineConfig } from 'vite'
534
552
  import mockPlugin from 'vite-plugin-mock-dev-server'
@@ -576,6 +594,7 @@ export default defineConfig({
576
594
  See more examples: [example](/example/)
577
595
 
578
596
  **exp:** Match `/api/test`, And returns a response body content with empty data
597
+
579
598
  ``` ts
580
599
  export default defineMock({
581
600
  url: '/api/test',
@@ -583,6 +602,7 @@ export default defineMock({
583
602
  ```
584
603
 
585
604
  **exp:** Match `/api/test` , And returns a static content data
605
+
586
606
  ``` ts
587
607
  export default defineMock({
588
608
  url: '/api/test',
@@ -591,6 +611,7 @@ export default defineMock({
591
611
  ```
592
612
 
593
613
  **exp:** Only Support `GET` Method
614
+
594
615
  ``` ts
595
616
  export default defineMock({
596
617
  url: '/api/test',
@@ -599,6 +620,7 @@ export default defineMock({
599
620
  ```
600
621
 
601
622
  **exp:** In the response header, add a custom header and cookie
623
+
602
624
  ``` ts
603
625
  export default defineMock({
604
626
  url: '/api/test',
@@ -606,6 +628,7 @@ export default defineMock({
606
628
  cookies: { 'my-cookie': '123456789' },
607
629
  })
608
630
  ```
631
+
609
632
  ``` ts
610
633
  export default defineMock({
611
634
  url: '/api/test',
@@ -619,6 +642,7 @@ export default defineMock({
619
642
  ```
620
643
 
621
644
  **exp:** Define multiple mock requests for the same URL and match valid rules with validators
645
+
622
646
  ``` ts
623
647
  export default defineMock([
624
648
  // Match /api/test?a=1
@@ -653,6 +677,7 @@ export default defineMock([
653
677
  ```
654
678
 
655
679
  **exp:** Response Delay
680
+
656
681
  ``` ts
657
682
  export default defineMock({
658
683
  url: '/api/test',
@@ -661,6 +686,7 @@ export default defineMock({
661
686
  ```
662
687
 
663
688
  **exp:** The interface request failed
689
+
664
690
  ``` ts
665
691
  export default defineMock({
666
692
  url: '/api/test',
@@ -670,6 +696,7 @@ export default defineMock({
670
696
  ```
671
697
 
672
698
  **exp:** Dynamic route matching
699
+
673
700
  ``` ts
674
701
  export default defineMock({
675
702
  url: '/api/user/:userId',
@@ -682,6 +709,7 @@ export default defineMock({
682
709
  The `userId` in the route will be resolved into the `request.params` object.
683
710
 
684
711
  **exp**:** Use the buffer to respond data
712
+
685
713
  ```ts
686
714
  import { Buffer } from 'node:buffer'
687
715
 
@@ -693,6 +721,7 @@ export default defineMock({
693
721
  body: Buffer.from(JSON.stringify({ a: 1 }))
694
722
  })
695
723
  ```
724
+
696
725
  ``` ts
697
726
  // When the type is buffer, the content-type is application/octet-stream.
698
727
  // The data passed in through body will be converted to a buffer.
@@ -707,6 +736,7 @@ export default defineMock({
707
736
  **exp:** Response file type
708
737
 
709
738
  Simulate file download, and pass in the file reading stream.
739
+
710
740
  ``` ts
711
741
  import { createReadStream } from 'node:fs'
712
742
 
@@ -717,11 +747,13 @@ export default defineMock({
717
747
  body: () => createReadStream('./my-app.dmg')
718
748
  })
719
749
  ```
750
+
720
751
  ```html
721
752
  <a href="/api/download" download="my-app.dmg">Download File</a>
722
753
  ```
723
754
 
724
755
  **exp:** Use `mockjs`:
756
+
725
757
  ``` ts
726
758
  import Mock from 'mockjs'
727
759
 
@@ -734,9 +766,11 @@ export default defineMock({
734
766
  })
735
767
  })
736
768
  ```
769
+
737
770
  You need install `mockjs`
738
771
 
739
772
  **exp:** Use `response` to customize the response
773
+
740
774
  ``` ts
741
775
  export default defineMock({
742
776
  url: '/api/test',
@@ -756,6 +790,7 @@ export default defineMock({
756
790
  ```
757
791
 
758
792
  **exp:** Use json / json5
793
+
759
794
  ``` json
760
795
  {
761
796
  "url": "/api/test",
@@ -768,6 +803,7 @@ export default defineMock({
768
803
  **exp:** multipart, upload files.
769
804
 
770
805
  use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support.
806
+
771
807
  ``` html
772
808
  <form action="/api/upload" method="post" enctype="multipart/form-data">
773
809
  <p>
@@ -785,6 +821,7 @@ use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support.
785
821
  ```
786
822
 
787
823
  fields `files` mapping to `formidable.File`
824
+
788
825
  ``` ts
789
826
  export default defineMock({
790
827
  url: '/api/upload',
@@ -800,6 +837,7 @@ export default defineMock({
800
837
  ```
801
838
 
802
839
  **exp:** Graphql
840
+
803
841
  ``` ts
804
842
  import { buildSchema, graphql } from 'graphql'
805
843
 
@@ -829,6 +867,7 @@ fetch('/api/graphql', {
829
867
  ```
830
868
 
831
869
  **exp:** WebSocket Mock
870
+
832
871
  ``` ts
833
872
  // ws.mock.ts
834
873
  export default defineMock({
@@ -857,6 +896,7 @@ export default defineMock({
857
896
  }
858
897
  })
859
898
  ```
899
+
860
900
  ``` ts
861
901
  // app.ts
862
902
  const ws = new WebSocket('ws://localhost:5173/socket.io')
@@ -878,6 +918,7 @@ In some scenarios, it may be necessary to use the data provided by mock services
878
918
  To meet such scenarios, on one hand, the plugin provides support under `vite preview`, and on the other hand, it also builds a small independent mock service application that can be deployed to relevant environments during `vite build`. This can then be forwarded through other HTTP servers like Nginx to actual ports for mock support.
879
919
 
880
920
  The default output is built into the directory `dist/mockServer`, generating files as follows:
921
+
881
922
  ``` sh
882
923
  ./mockServer
883
924
  ├── index.js
@@ -898,7 +939,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
898
939
  ## Contributors
899
940
 
900
941
  <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
901
- [![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors-)
942
+ [![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors)
902
943
  <!-- ALL-CONTRIBUTORS-BADGE:END -->
903
944
 
904
945
  <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
package/README.zh-CN.md CHANGED
@@ -13,7 +13,7 @@
13
13
  <a href="https://www.npmjs.com/package/vite-plugin-mock-dev-server"><img alt="npm" src="https://img.shields.io/npm/v/vite-plugin-mock-dev-server?style=flat-square"></a>
14
14
  <img alt="node-current" src="https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square">
15
15
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/vite-plugin-mock-dev-server/peer/vite?style=flat-square">
16
- <img alt="npm" src="https://img.shields.io/npm/dt/vite-plugin-mock-dev-server?style=flat-square">
16
+ <img alt="npm" src="https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square">
17
17
  <br>
18
18
  <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/vite-plugin-mock-dev-server/lint.yml?style=flat-square">
19
19
  <a href="https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_shield"><img alt="fossa status" src="https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=shield"></a>
@@ -69,6 +69,7 @@ pnpm add -D vite-plugin-mock-dev-server
69
69
  ### 配置
70
70
 
71
71
  `vite.config.ts`
72
+
72
73
  ```ts
73
74
  import { defineConfig } from 'vite'
74
75
  import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
@@ -86,6 +87,7 @@ export default defineConfig({
86
87
  }
87
88
  })
88
89
  ```
90
+
89
91
  插件会读取 `server.proxy` 或 `options.prefix` 的配置,对匹配的 url 启用mock 匹配。
90
92
 
91
93
  插件也会读取 `define` 配置, 支持在 mock 文件中直接使用。
@@ -98,6 +100,7 @@ export default defineConfig({
98
100
  默认配置,在你的项目根目录的 `mock` 目录中编写mock数据:
99
101
 
100
102
  `mock/**/*.mock.ts` :
103
+
101
104
  ```ts
102
105
  import { defineMock } from 'vite-plugin-mock-dev-server'
103
106
 
@@ -114,6 +117,7 @@ export default defineMock({
114
117
  vite plugin
115
118
 
116
119
  `vite.config.ts`
120
+
117
121
  ```ts
118
122
  import { defineConfig } from 'vite'
119
123
  import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
@@ -192,6 +196,7 @@ export default defineConfig({
192
196
  **默认值:** `{}`
193
197
 
194
198
  示例: 配置文件上传的存放目录
199
+
195
200
  ```ts
196
201
  MockDevServerPlugin({
197
202
  formidableOptions: {
@@ -199,12 +204,17 @@ export default defineConfig({
199
204
  }
200
205
  })
201
206
  ```
207
+
202
208
  - `options.cookiesOptions`
203
209
 
204
210
  配置 `cookies`, 查看 [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
205
211
 
206
212
  **默认值:** `{}`
207
213
 
214
+ - `options.bodyParserOptions`
215
+
216
+ 配置 `co-body`, 查看 [co-body](https://github.com/cojs/co-body#options)
217
+
208
218
  - `options.build`
209
219
 
210
220
  需要构建可独立部署的小型mock服务时配置。
@@ -397,6 +407,7 @@ export default defineMock({
397
407
  },
398
408
  })
399
409
  ```
410
+
400
411
  ```ts
401
412
  // 配置 WebSocket mock
402
413
  export default defineMock({
@@ -481,8 +492,10 @@ type defineMockData<T> = (
481
492
  ) => [getter, setter] & { value: T }
482
493
  ```
483
494
 
484
- #### 用法:
495
+ ### 用法
496
+
485
497
  `data.ts`
498
+
486
499
  ```ts
487
500
  import { defineMockData } from 'vite-plugin-mock-dev-server'
488
501
 
@@ -491,7 +504,9 @@ export default defineMockData('posts', [
491
504
  { id: '2', title: 'title2', content: 'content2' },
492
505
  ])
493
506
  ```
507
+
494
508
  `*.mock.ts`
509
+
495
510
  ```ts
496
511
  import { defineMock } from 'vite-plugin-mock-dev-server'
497
512
  import posts from './data'
@@ -525,6 +540,7 @@ export default defineMock([
525
540
  可以使用 `priority` 参数。
526
541
 
527
542
  示例:
543
+
528
544
  ```ts
529
545
  import { defineConfig } from 'vite'
530
546
  import mockPlugin from 'vite-plugin-mock-dev-server'
@@ -557,7 +573,7 @@ export default defineConfig({
557
573
 
558
574
  > **注意:**
559
575
  >
560
- > `priority` 虽然可以调整优先级,但大多数时候,你都没有必要这么做。
576
+ > `priority` 虽然可以调整优先级,但大多数时候,你都没有必要这么做。
561
577
  > 对于一些特殊情况的请求,可以使用 静态规则来替代 `priority`,静态规则总是拥有最高优先级。
562
578
 
563
579
  ## Example
@@ -567,6 +583,7 @@ export default defineConfig({
567
583
  查看更多示例: [example](/example/)
568
584
 
569
585
  **exp:** 命中 `/api/test` 请求,并返回一个 数据为空的响应体内容
586
+
570
587
  ```ts
571
588
  export default defineMock({
572
589
  url: '/api/test',
@@ -574,12 +591,14 @@ export default defineMock({
574
591
  ```
575
592
 
576
593
  **exp:** 命中 `/api/test` 请求,并返回一个固定内容数据
594
+
577
595
  ```ts
578
596
  export default defineMock({
579
597
  url: '/api/test',
580
598
  body: { a: 1 },
581
599
  })
582
600
  ```
601
+
583
602
  ```ts
584
603
  export default defineMock({
585
604
  url: '/api/test',
@@ -588,6 +607,7 @@ export default defineMock({
588
607
  ```
589
608
 
590
609
  **exp:** 限定只允许 `GET` 请求
610
+
591
611
  ```ts
592
612
  export default defineMock({
593
613
  url: '/api/test',
@@ -596,6 +616,7 @@ export default defineMock({
596
616
  ```
597
617
 
598
618
  **exp:** 在返回的响应头中,添加自定义 header 和 cookie
619
+
599
620
  ```ts
600
621
  export default defineMock({
601
622
  url: '/api/test',
@@ -603,6 +624,7 @@ export default defineMock({
603
624
  cookies: { 'my-cookie': '123456789' },
604
625
  })
605
626
  ```
627
+
606
628
  ```ts
607
629
  export default defineMock({
608
630
  url: '/api/test',
@@ -616,6 +638,7 @@ export default defineMock({
616
638
  ```
617
639
 
618
640
  **exp:** 定义多个相同url请求mock,并使用验证器匹配生效规则
641
+
619
642
  ```ts
620
643
  export default defineMock([
621
644
  // 命中 /api/test?a=1
@@ -649,6 +672,7 @@ export default defineMock([
649
672
  ```
650
673
 
651
674
  **exp:** 延迟接口响应:
675
+
652
676
  ```ts
653
677
  export default defineMock({
654
678
  url: '/api/test',
@@ -657,6 +681,7 @@ export default defineMock({
657
681
  ```
658
682
 
659
683
  **exp:** 使接口请求失败
684
+
660
685
  ```ts
661
686
  export default defineMock({
662
687
  url: '/api/test',
@@ -666,6 +691,7 @@ export default defineMock({
666
691
  ```
667
692
 
668
693
  **exp:** 动态路由匹配
694
+
669
695
  ```ts
670
696
  export default defineMock({
671
697
  url: '/api/user/:userId',
@@ -678,6 +704,7 @@ export default defineMock({
678
704
  路由中的 `userId`将会解析到 `request.params` 对象中.
679
705
 
680
706
  **exp:** 使用 buffer 响应数据
707
+
681
708
  ```ts
682
709
  import { Buffer } from 'node:buffer'
683
710
 
@@ -688,6 +715,7 @@ export default defineMock({
688
715
  body: Buffer.from(JSON.stringify({ a: 1 }))
689
716
  })
690
717
  ```
718
+
691
719
  ```ts
692
720
  // 当 type 为 buffer 时,content-type 为 application/octet-stream,
693
721
  // body 传入的数据会被转为 buffer
@@ -702,6 +730,7 @@ export default defineMock({
702
730
  **exp:** 响应文件类型
703
731
 
704
732
  模拟文件下载,传入文件读取流
733
+
705
734
  ```ts
706
735
  import { createReadStream } from 'node:fs'
707
736
 
@@ -712,11 +741,13 @@ export default defineMock({
712
741
  body: () => createReadStream('./my-app.dmg')
713
742
  })
714
743
  ```
744
+
715
745
  ```html
716
746
  <a href="/api/download" download="my-app.dmg">下载文件</a>
717
747
  ```
718
748
 
719
749
  **exp:** 使用 `mockjs` 生成响应数据:
750
+
720
751
  ```ts
721
752
  import Mock from 'mockjs'
722
753
 
@@ -729,9 +760,11 @@ export default defineMock({
729
760
  })
730
761
  })
731
762
  ```
763
+
732
764
  请先安装 `mockjs`
733
765
 
734
766
  **exp:** 使用 `response` 自定义响应
767
+
735
768
  ```ts
736
769
  export default defineMock({
737
770
  url: '/api/test',
@@ -751,6 +784,7 @@ export default defineMock({
751
784
  ```
752
785
 
753
786
  **exp:** 使用 json / json5
787
+
754
788
  ```json
755
789
  {
756
790
  "url": "/api/test",
@@ -763,6 +797,7 @@ export default defineMock({
763
797
  **exp:** multipart, 文件上传.
764
798
 
765
799
  通过 [`formidable`](https://www.npmjs.com/package/formidable#readme) 支持。
800
+
766
801
  ``` html
767
802
  <form action="/api/upload" method="post" enctype="multipart/form-data">
768
803
  <p>
@@ -780,6 +815,7 @@ export default defineMock({
780
815
  ```
781
816
 
782
817
  fields `files` 映射为 `formidable.File` 类型。
818
+
783
819
  ``` ts
784
820
  export default defineMock({
785
821
  url: '/api/upload',
@@ -795,6 +831,7 @@ export default defineMock({
795
831
  ```
796
832
 
797
833
  **exp:** Graphql
834
+
798
835
  ```ts
799
836
  import { buildSchema, graphql } from 'graphql'
800
837
 
@@ -824,6 +861,7 @@ fetch('/api/graphql', {
824
861
  ```
825
862
 
826
863
  **exp:** WebSocket Mock
864
+
827
865
  ```ts
828
866
  // ws.mock.ts
829
867
  export default defineMock({
@@ -852,6 +890,7 @@ export default defineMock({
852
890
  }
853
891
  })
854
892
  ```
893
+
855
894
  ```ts
856
895
  // app.ts
857
896
  const ws = new WebSocket('ws://localhost:5173/socket.io')
@@ -873,6 +912,7 @@ ws.addEventListener('message', (raw) => {
873
912
  为了能够满足这类场景,插件一方面提供了 `vite preview` 下的支持,同时还提供了在 `vite build` 时,也构建一个可独立部署的 小型mock服务应用,可以将这个应用部署到相关的环境,后通过其他http服务器如nginx做代理转发到实际端口实现mock支持。
874
913
 
875
914
  构建默认输出到 `dist/mockServer` 目录中,并生成如下文件:
915
+
876
916
  ```sh
877
917
  ./mockServer
878
918
  ├── index.js
package/dist/index.cjs CHANGED
@@ -44,7 +44,7 @@ __export(src_exports, {
44
44
  });
45
45
  module.exports = __toCommonJS(src_exports);
46
46
 
47
- // node_modules/.pnpm/tsup@8.0.1_typescript@5.3.3/node_modules/tsup/assets/cjs_shims.js
47
+ // node_modules/.pnpm/tsup@8.1.0_postcss@8.4.38_typescript@5.5.2/node_modules/tsup/assets/cjs_shims.js
48
48
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
49
49
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
50
50
 
@@ -98,8 +98,9 @@ function lookupFile(dir, formats, options) {
98
98
  }
99
99
  }
100
100
  const parentDir = import_node_path.default.dirname(dir);
101
- if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir)))
101
+ if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir))) {
102
102
  return lookupFile(parentDir, formats, options);
103
+ }
103
104
  }
104
105
  function ensureProxies(serverProxy = {}) {
105
106
  const httpProxies = [];
@@ -107,10 +108,11 @@ function ensureProxies(serverProxy = {}) {
107
108
  Object.keys(serverProxy).forEach((key) => {
108
109
  var _a, _b;
109
110
  const value = serverProxy[key];
110
- if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")))
111
+ if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:"))) {
111
112
  httpProxies.push(key);
112
- else
113
+ } else {
113
114
  wsProxies.push(key);
115
+ }
114
116
  });
115
117
  return { httpProxies, wsProxies };
116
118
  }
@@ -344,7 +346,7 @@ function canJsonParse(value) {
344
346
 
345
347
  // src/build.ts
346
348
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
347
- var packageVersion = true ? "1.4.7" : "latest";
349
+ var packageVersion = true ? "1.5.1" : "latest";
348
350
  async function generateMockServer(ctx, config, options) {
349
351
  const include = (0, import_utils2.toArray)(options.include);
350
352
  const exclude = (0, import_utils2.toArray)(options.exclude);
@@ -380,6 +382,7 @@ async function generateMockServer(ctx, config, options) {
380
382
  httpProxies,
381
383
  wsProxies,
382
384
  options.cookiesOptions,
385
+ options.bodyParserOptions,
383
386
  options.priority,
384
387
  options.build
385
388
  )
@@ -451,7 +454,7 @@ function generatePackageJson(pkg, mockDeps) {
451
454
  });
452
455
  return JSON.stringify(mockPkg, null, 2);
453
456
  }
454
- function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
457
+ function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, bodyParserOptions = {}, priority = {}, build2) {
455
458
  const { serverPort, log } = build2;
456
459
  return `import { createServer } from 'node:http';
457
460
  import connect from 'connect';
@@ -465,6 +468,7 @@ const logger = createLogger('mock-server', '${log}');
465
468
  const httpProxies = ${JSON.stringify(httpProxies)};
466
469
  const wsProxies = ${JSON.stringify(wsProxies)};
467
470
  const cookiesOptions = ${JSON.stringify(cookiesOptions)};
471
+ const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
468
472
  const priority = ${JSON.stringify(priority)};
469
473
 
470
474
  mockWebSocket({
@@ -481,6 +485,7 @@ app.use(baseMiddleware({ mockData }, {
481
485
  proxies: httpProxies,
482
486
  priority,
483
487
  cookiesOptions,
488
+ bodyParserOptions,
484
489
  logger,
485
490
  }));
486
491
 
@@ -673,8 +678,7 @@ function twoPartMatch(rules) {
673
678
  const dym = tokens.filter((token) => typeof token !== "string");
674
679
  if (dym.length > 0)
675
680
  dynamics.push(rule);
676
- else
677
- statics.push(rule);
681
+ else statics.push(rule);
678
682
  }
679
683
  return [statics, dynamics];
680
684
  }
@@ -682,21 +686,34 @@ function twoPartMatch(rules) {
682
686
  // src/parseReqBody.ts
683
687
  var import_co_body = __toESM(require("co-body"), 1);
684
688
  var import_formidable = __toESM(require("formidable"), 1);
685
- async function parseReqBody(req, options) {
689
+ async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
686
690
  var _a;
687
691
  const method = req.method.toUpperCase();
688
692
  if (["GET", "DELETE", "HEAD"].includes(method))
689
693
  return void 0;
690
694
  const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
695
+ const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
691
696
  try {
692
- if (type.startsWith("application/json"))
693
- return await import_co_body.default.json(req);
694
- if (type.startsWith("application/x-www-form-urlencoded"))
695
- return await import_co_body.default.form(req);
696
- if (type.startsWith("text/plain"))
697
- return await import_co_body.default.text(req);
697
+ if (type.startsWith("application/json")) {
698
+ return await import_co_body.default.json(req, {
699
+ limit: jsonLimit || limit,
700
+ ...rest
701
+ });
702
+ }
703
+ if (type.startsWith("application/x-www-form-urlencoded")) {
704
+ return await import_co_body.default.form(req, {
705
+ limit: formLimit || limit,
706
+ ...rest
707
+ });
708
+ }
709
+ if (type.startsWith("text/plain")) {
710
+ return await import_co_body.default.text(req, {
711
+ limit: textLimit || limit,
712
+ ...rest
713
+ });
714
+ }
698
715
  if (type.startsWith("multipart/form-data"))
699
- return await parseMultipart(req, options);
716
+ return await parseMultipart(req, formidableOptions);
700
717
  } catch (e) {
701
718
  console.error(e);
702
719
  }
@@ -793,6 +810,7 @@ function isIncluded(source, target) {
793
810
  // src/baseMiddleware.ts
794
811
  function baseMiddleware(mockLoader, {
795
812
  formidableOptions = {},
813
+ bodyParserOptions = {},
796
814
  proxies,
797
815
  cookiesOptions,
798
816
  logger,
@@ -801,15 +819,17 @@ function baseMiddleware(mockLoader, {
801
819
  return async function(req, res, next) {
802
820
  const startTime = (0, import_utils6.timestamp)();
803
821
  const { query, pathname } = urlParse(req.url);
804
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
822
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
805
823
  return next();
824
+ }
806
825
  const mockData = mockLoader.mockData;
807
826
  const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
808
- if (mockUrls.length === 0)
827
+ if (mockUrls.length === 0) {
809
828
  return next();
829
+ }
810
830
  collectRequest(req);
811
831
  const { query: refererQuery } = urlParse(req.headers.referer || "");
812
- const reqBody = await parseReqBody(req, formidableOptions);
832
+ const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
813
833
  const cookies = new import_cookies.default(req, res, cookiesOptions);
814
834
  const getCookie = cookies.get.bind(cookies);
815
835
  const method = req.method.toUpperCase();
@@ -1017,8 +1037,9 @@ function sendData(res, raw, type) {
1017
1037
  }
1018
1038
  }
1019
1039
  async function realDelay(startTime, delay) {
1020
- if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils6.isArray)(delay) && delay.length !== 2)
1040
+ if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils6.isArray)(delay) && delay.length !== 2) {
1021
1041
  return;
1042
+ }
1022
1043
  let realDelay2 = 0;
1023
1044
  if ((0, import_utils6.isArray)(delay)) {
1024
1045
  const [min, max] = delay;
@@ -1289,11 +1310,10 @@ var MockLoader = class extends import_node_events.default {
1289
1310
  else
1290
1311
  isESM = this.moduleType === "esm";
1291
1312
  const { define, alias } = this.options;
1292
- const { code, deps } = await transformWithEsbuild(filepath, {
1293
- isESM,
1294
- define,
1295
- alias
1296
- });
1313
+ const { code, deps } = await transformWithEsbuild(
1314
+ filepath,
1315
+ { isESM, define, alias }
1316
+ );
1297
1317
  try {
1298
1318
  const raw = await loadFromCode(
1299
1319
  filepath,
@@ -1417,8 +1437,9 @@ ${e}
1417
1437
  });
1418
1438
  httpServer == null ? void 0 : httpServer.on("upgrade", (req, socket, head) => {
1419
1439
  const { pathname, query } = urlParse(req.url);
1420
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
1440
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
1421
1441
  return;
1442
+ }
1422
1443
  const mockData = loader.mockData;
1423
1444
  const mockUrl = Object.keys(mockData).find((key) => {
1424
1445
  return (0, import_path_to_regexp4.pathToRegexp)(key).test(pathname);
@@ -1529,6 +1550,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1529
1550
  formidableOptions: options.formidableOptions,
1530
1551
  proxies,
1531
1552
  cookiesOptions: options.cookiesOptions,
1553
+ bodyParserOptions: options.bodyParserOptions,
1532
1554
  priority: options.priority,
1533
1555
  logger
1534
1556
  })
@@ -1554,8 +1576,9 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1554
1576
  const { pathname } = urlParse(req.url);
1555
1577
  if (!pathname || proxies.length === 0 || !proxies.some(
1556
1578
  (context) => doesProxyContextMatchUrl(context, req.url)
1557
- ))
1579
+ )) {
1558
1580
  return next();
1581
+ }
1559
1582
  const mockData = mockLoader.mockData;
1560
1583
  const mockUrl = Object.keys(mockData).find(
1561
1584
  (key) => (0, import_path_to_regexp5.pathToRegexp)(key).test(pathname)
@@ -1578,6 +1601,7 @@ function mockDevServerPlugin({
1578
1601
  formidableOptions = {},
1579
1602
  build: build2 = false,
1580
1603
  cookiesOptions = {},
1604
+ bodyParserOptions = {},
1581
1605
  priority = {}
1582
1606
  } = {}) {
1583
1607
  const pluginOptions = {
@@ -1593,6 +1617,7 @@ function mockDevServerPlugin({
1593
1617
  multiples: true,
1594
1618
  ...formidableOptions
1595
1619
  },
1620
+ bodyParserOptions,
1596
1621
  priority,
1597
1622
  build: build2 ? Object.assign(
1598
1623
  {
package/dist/index.d.cts CHANGED
@@ -6,6 +6,7 @@ import Cookies from 'cookies';
6
6
  import { CorsOptions } from 'cors';
7
7
  import formidable from 'formidable';
8
8
  import { WebSocketServer } from 'ws';
9
+ import { Options } from 'co-body';
9
10
  import EventEmitter from 'node:events';
10
11
  import chokidar from 'chokidar';
11
12
  import { Http2SecureServer } from 'node:http2';
@@ -91,6 +92,14 @@ interface MockServerPluginOptions {
91
92
  * @see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
92
93
  */
93
94
  cookiesOptions?: Cookies.Option;
95
+ /**
96
+ * Configure to `co-body`
97
+ *
98
+ * 配置 `co-body`
99
+ *
100
+ * @see [co-body](https://github.com/cojs/co-body#options)
101
+ */
102
+ bodyParserOptions?: BodyParserOptions;
94
103
  /**
95
104
  * When you need to build a small mock service, you can configure this option.
96
105
  *
@@ -193,6 +202,11 @@ interface MockMatchSpecialPriority {
193
202
  when: string[];
194
203
  };
195
204
  }
205
+ type BodyParserOptions = Options & {
206
+ jsonLimit?: string | number;
207
+ formLimit?: string | number;
208
+ textLimit?: string | number;
209
+ };
196
210
  interface ServerBuildOption {
197
211
  /**
198
212
  * Service startup port
@@ -550,7 +564,7 @@ type LogType = 'info' | 'warn' | 'error' | 'debug';
550
564
  type LogLevel = LogType | 'silent';
551
565
 
552
566
  /** @deprecated The CJS build of vite-plugin-mock-dev-server's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details. */
553
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, priority, }?: MockServerPluginOptions): Plugin[];
567
+ declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
554
568
 
555
569
  /**
556
570
  * mock config Type helper
@@ -627,10 +641,10 @@ type MockData<T = any> = readonly [
627
641
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
628
642
 
629
643
  interface Logger {
630
- debug(msg: string, level?: boolean | LogLevel): void;
631
- info(msg: string, level?: boolean | LogLevel): void;
632
- warn(msg: string, level?: boolean | LogLevel): void;
633
- error(msg: string, level?: boolean | LogLevel): void;
644
+ debug: (msg: string, level?: boolean | LogLevel) => void;
645
+ info: (msg: string, level?: boolean | LogLevel) => void;
646
+ warn: (msg: string, level?: boolean | LogLevel) => void;
647
+ error: (msg: string, level?: boolean | LogLevel) => void;
634
648
  }
635
649
  declare const logLevels: Record<LogLevel, number>;
636
650
  declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
@@ -672,11 +686,12 @@ declare class MockLoader extends EventEmitter {
672
686
  interface BaseMiddlewareOptions {
673
687
  formidableOptions: MockServerPluginOptions['formidableOptions'];
674
688
  cookiesOptions: MockServerPluginOptions['cookiesOptions'];
689
+ bodyParserOptions: MockServerPluginOptions['bodyParserOptions'];
675
690
  proxies: string[];
676
691
  logger: Logger;
677
692
  priority: MockServerPluginOptions['priority'];
678
693
  }
679
- declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
694
+ declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, bodyParserOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
680
695
 
681
696
  /**
682
697
  * 不复用 `viteConfig.server.proxy` 中 websocket proxy的原因是,
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ import Cookies from 'cookies';
6
6
  import { CorsOptions } from 'cors';
7
7
  import formidable from 'formidable';
8
8
  import { WebSocketServer } from 'ws';
9
+ import { Options } from 'co-body';
9
10
  import EventEmitter from 'node:events';
10
11
  import chokidar from 'chokidar';
11
12
  import { Http2SecureServer } from 'node:http2';
@@ -91,6 +92,14 @@ interface MockServerPluginOptions {
91
92
  * @see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
92
93
  */
93
94
  cookiesOptions?: Cookies.Option;
95
+ /**
96
+ * Configure to `co-body`
97
+ *
98
+ * 配置 `co-body`
99
+ *
100
+ * @see [co-body](https://github.com/cojs/co-body#options)
101
+ */
102
+ bodyParserOptions?: BodyParserOptions;
94
103
  /**
95
104
  * When you need to build a small mock service, you can configure this option.
96
105
  *
@@ -193,6 +202,11 @@ interface MockMatchSpecialPriority {
193
202
  when: string[];
194
203
  };
195
204
  }
205
+ type BodyParserOptions = Options & {
206
+ jsonLimit?: string | number;
207
+ formLimit?: string | number;
208
+ textLimit?: string | number;
209
+ };
196
210
  interface ServerBuildOption {
197
211
  /**
198
212
  * Service startup port
@@ -549,7 +563,7 @@ type FormidableFile = formidable.File | formidable.File[];
549
563
  type LogType = 'info' | 'warn' | 'error' | 'debug';
550
564
  type LogLevel = LogType | 'silent';
551
565
 
552
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, priority, }?: MockServerPluginOptions): Plugin[];
566
+ declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
553
567
 
554
568
  /**
555
569
  * mock config Type helper
@@ -626,10 +640,10 @@ type MockData<T = any> = readonly [
626
640
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
627
641
 
628
642
  interface Logger {
629
- debug(msg: string, level?: boolean | LogLevel): void;
630
- info(msg: string, level?: boolean | LogLevel): void;
631
- warn(msg: string, level?: boolean | LogLevel): void;
632
- error(msg: string, level?: boolean | LogLevel): void;
643
+ debug: (msg: string, level?: boolean | LogLevel) => void;
644
+ info: (msg: string, level?: boolean | LogLevel) => void;
645
+ warn: (msg: string, level?: boolean | LogLevel) => void;
646
+ error: (msg: string, level?: boolean | LogLevel) => void;
633
647
  }
634
648
  declare const logLevels: Record<LogLevel, number>;
635
649
  declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
@@ -671,11 +685,12 @@ declare class MockLoader extends EventEmitter {
671
685
  interface BaseMiddlewareOptions {
672
686
  formidableOptions: MockServerPluginOptions['formidableOptions'];
673
687
  cookiesOptions: MockServerPluginOptions['cookiesOptions'];
688
+ bodyParserOptions: MockServerPluginOptions['bodyParserOptions'];
674
689
  proxies: string[];
675
690
  logger: Logger;
676
691
  priority: MockServerPluginOptions['priority'];
677
692
  }
678
- declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
693
+ declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, bodyParserOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
679
694
 
680
695
  /**
681
696
  * 不复用 `viteConfig.server.proxy` 中 websocket proxy的原因是,
package/dist/index.js CHANGED
@@ -48,8 +48,9 @@ function lookupFile(dir, formats, options) {
48
48
  }
49
49
  }
50
50
  const parentDir = path.dirname(dir);
51
- if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir)))
51
+ if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir))) {
52
52
  return lookupFile(parentDir, formats, options);
53
+ }
53
54
  }
54
55
  function ensureProxies(serverProxy = {}) {
55
56
  const httpProxies = [];
@@ -57,10 +58,11 @@ function ensureProxies(serverProxy = {}) {
57
58
  Object.keys(serverProxy).forEach((key) => {
58
59
  var _a, _b;
59
60
  const value = serverProxy[key];
60
- if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")))
61
+ if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:"))) {
61
62
  httpProxies.push(key);
62
- else
63
+ } else {
63
64
  wsProxies.push(key);
65
+ }
64
66
  });
65
67
  return { httpProxies, wsProxies };
66
68
  }
@@ -294,7 +296,7 @@ function canJsonParse(value) {
294
296
 
295
297
  // src/build.ts
296
298
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
297
- var packageVersion = true ? "1.4.7" : "latest";
299
+ var packageVersion = true ? "1.5.1" : "latest";
298
300
  async function generateMockServer(ctx, config, options) {
299
301
  const include = toArray(options.include);
300
302
  const exclude = toArray(options.exclude);
@@ -330,6 +332,7 @@ async function generateMockServer(ctx, config, options) {
330
332
  httpProxies,
331
333
  wsProxies,
332
334
  options.cookiesOptions,
335
+ options.bodyParserOptions,
333
336
  options.priority,
334
337
  options.build
335
338
  )
@@ -401,7 +404,7 @@ function generatePackageJson(pkg, mockDeps) {
401
404
  });
402
405
  return JSON.stringify(mockPkg, null, 2);
403
406
  }
404
- function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
407
+ function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, bodyParserOptions = {}, priority = {}, build2) {
405
408
  const { serverPort, log } = build2;
406
409
  return `import { createServer } from 'node:http';
407
410
  import connect from 'connect';
@@ -415,6 +418,7 @@ const logger = createLogger('mock-server', '${log}');
415
418
  const httpProxies = ${JSON.stringify(httpProxies)};
416
419
  const wsProxies = ${JSON.stringify(wsProxies)};
417
420
  const cookiesOptions = ${JSON.stringify(cookiesOptions)};
421
+ const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
418
422
  const priority = ${JSON.stringify(priority)};
419
423
 
420
424
  mockWebSocket({
@@ -431,6 +435,7 @@ app.use(baseMiddleware({ mockData }, {
431
435
  proxies: httpProxies,
432
436
  priority,
433
437
  cookiesOptions,
438
+ bodyParserOptions,
434
439
  logger,
435
440
  }));
436
441
 
@@ -636,8 +641,7 @@ function twoPartMatch(rules) {
636
641
  const dym = tokens.filter((token) => typeof token !== "string");
637
642
  if (dym.length > 0)
638
643
  dynamics.push(rule);
639
- else
640
- statics.push(rule);
644
+ else statics.push(rule);
641
645
  }
642
646
  return [statics, dynamics];
643
647
  }
@@ -645,21 +649,34 @@ function twoPartMatch(rules) {
645
649
  // src/parseReqBody.ts
646
650
  import bodyParser from "co-body";
647
651
  import formidable from "formidable";
648
- async function parseReqBody(req, options) {
652
+ async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
649
653
  var _a;
650
654
  const method = req.method.toUpperCase();
651
655
  if (["GET", "DELETE", "HEAD"].includes(method))
652
656
  return void 0;
653
657
  const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
658
+ const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
654
659
  try {
655
- if (type.startsWith("application/json"))
656
- return await bodyParser.json(req);
657
- if (type.startsWith("application/x-www-form-urlencoded"))
658
- return await bodyParser.form(req);
659
- if (type.startsWith("text/plain"))
660
- return await bodyParser.text(req);
660
+ if (type.startsWith("application/json")) {
661
+ return await bodyParser.json(req, {
662
+ limit: jsonLimit || limit,
663
+ ...rest
664
+ });
665
+ }
666
+ if (type.startsWith("application/x-www-form-urlencoded")) {
667
+ return await bodyParser.form(req, {
668
+ limit: formLimit || limit,
669
+ ...rest
670
+ });
671
+ }
672
+ if (type.startsWith("text/plain")) {
673
+ return await bodyParser.text(req, {
674
+ limit: textLimit || limit,
675
+ ...rest
676
+ });
677
+ }
661
678
  if (type.startsWith("multipart/form-data"))
662
- return await parseMultipart(req, options);
679
+ return await parseMultipart(req, formidableOptions);
663
680
  } catch (e) {
664
681
  console.error(e);
665
682
  }
@@ -756,6 +773,7 @@ function isIncluded(source, target) {
756
773
  // src/baseMiddleware.ts
757
774
  function baseMiddleware(mockLoader, {
758
775
  formidableOptions = {},
776
+ bodyParserOptions = {},
759
777
  proxies,
760
778
  cookiesOptions,
761
779
  logger,
@@ -764,15 +782,17 @@ function baseMiddleware(mockLoader, {
764
782
  return async function(req, res, next) {
765
783
  const startTime = timestamp();
766
784
  const { query, pathname } = urlParse(req.url);
767
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
785
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
768
786
  return next();
787
+ }
769
788
  const mockData = mockLoader.mockData;
770
789
  const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
771
- if (mockUrls.length === 0)
790
+ if (mockUrls.length === 0) {
772
791
  return next();
792
+ }
773
793
  collectRequest(req);
774
794
  const { query: refererQuery } = urlParse(req.headers.referer || "");
775
- const reqBody = await parseReqBody(req, formidableOptions);
795
+ const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
776
796
  const cookies = new Cookies(req, res, cookiesOptions);
777
797
  const getCookie = cookies.get.bind(cookies);
778
798
  const method = req.method.toUpperCase();
@@ -980,8 +1000,9 @@ function sendData(res, raw, type) {
980
1000
  }
981
1001
  }
982
1002
  async function realDelay(startTime, delay) {
983
- if (!delay || typeof delay === "number" && delay <= 0 || isArray3(delay) && delay.length !== 2)
1003
+ if (!delay || typeof delay === "number" && delay <= 0 || isArray3(delay) && delay.length !== 2) {
984
1004
  return;
1005
+ }
985
1006
  let realDelay2 = 0;
986
1007
  if (isArray3(delay)) {
987
1008
  const [min, max] = delay;
@@ -1258,11 +1279,10 @@ var MockLoader = class extends EventEmitter {
1258
1279
  else
1259
1280
  isESM = this.moduleType === "esm";
1260
1281
  const { define, alias } = this.options;
1261
- const { code, deps } = await transformWithEsbuild(filepath, {
1262
- isESM,
1263
- define,
1264
- alias
1265
- });
1282
+ const { code, deps } = await transformWithEsbuild(
1283
+ filepath,
1284
+ { isESM, define, alias }
1285
+ );
1266
1286
  try {
1267
1287
  const raw = await loadFromCode(
1268
1288
  filepath,
@@ -1386,8 +1406,9 @@ ${e}
1386
1406
  });
1387
1407
  httpServer == null ? void 0 : httpServer.on("upgrade", (req, socket, head) => {
1388
1408
  const { pathname, query } = urlParse(req.url);
1389
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
1409
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
1390
1410
  return;
1411
+ }
1391
1412
  const mockData = loader.mockData;
1392
1413
  const mockUrl = Object.keys(mockData).find((key) => {
1393
1414
  return pathToRegexp3(key).test(pathname);
@@ -1498,6 +1519,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1498
1519
  formidableOptions: options.formidableOptions,
1499
1520
  proxies,
1500
1521
  cookiesOptions: options.cookiesOptions,
1522
+ bodyParserOptions: options.bodyParserOptions,
1501
1523
  priority: options.priority,
1502
1524
  logger
1503
1525
  })
@@ -1523,8 +1545,9 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1523
1545
  const { pathname } = urlParse(req.url);
1524
1546
  if (!pathname || proxies.length === 0 || !proxies.some(
1525
1547
  (context) => doesProxyContextMatchUrl(context, req.url)
1526
- ))
1548
+ )) {
1527
1549
  return next();
1550
+ }
1528
1551
  const mockData = mockLoader.mockData;
1529
1552
  const mockUrl = Object.keys(mockData).find(
1530
1553
  (key) => pathToRegexp4(key).test(pathname)
@@ -1547,6 +1570,7 @@ function mockDevServerPlugin({
1547
1570
  formidableOptions = {},
1548
1571
  build: build2 = false,
1549
1572
  cookiesOptions = {},
1573
+ bodyParserOptions = {},
1550
1574
  priority = {}
1551
1575
  } = {}) {
1552
1576
  const pluginOptions = {
@@ -1562,6 +1586,7 @@ function mockDevServerPlugin({
1562
1586
  multiples: true,
1563
1587
  ...formidableOptions
1564
1588
  },
1589
+ bodyParserOptions,
1565
1590
  priority,
1566
1591
  build: build2 ? Object.assign(
1567
1592
  {
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
3
  "type": "module",
4
- "version": "1.4.7",
5
- "packageManager": "pnpm@8.14.1",
4
+ "version": "1.5.1",
6
5
  "author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
7
6
  "license": "MIT",
8
7
  "homepage": "https://vite-plugin-mock-dev-server.netlify.app",
@@ -37,50 +36,50 @@
37
36
  "dist"
38
37
  ],
39
38
  "engines": {
40
- "node": "^16 || ^18 || >= 20"
39
+ "node": "^18 || >= 20"
41
40
  },
42
41
  "peerDependencies": {
43
42
  "vite": ">=3.0.0"
44
43
  },
45
44
  "dependencies": {
46
- "@pengzhanbo/utils": "^1.1.1",
45
+ "@pengzhanbo/utils": "^1.1.2",
47
46
  "@rollup/pluginutils": "^5.1.0",
48
- "chokidar": "^3.5.3",
49
- "co-body": "^6.1.0",
47
+ "chokidar": "^3.6.0",
48
+ "co-body": "^6.2.0",
50
49
  "cookies": "^0.9.1",
51
50
  "cors": "^2.8.5",
52
- "debug": "^4.3.4",
53
- "esbuild": "^0.19.11",
51
+ "debug": "^4.3.5",
52
+ "esbuild": "^0.21.5",
54
53
  "fast-glob": "^3.3.2",
55
54
  "formidable": "2.1.2",
56
- "http-status": "^1.7.3",
57
- "is-core-module": "^2.13.1",
55
+ "http-status": "^1.7.4",
56
+ "is-core-module": "^2.14.0",
58
57
  "json5": "^2.2.3",
59
58
  "mime-types": "^2.1.35",
60
- "path-to-regexp": "^6.2.1",
61
- "picocolors": "^1.0.0",
62
- "ws": "^8.16.0"
59
+ "path-to-regexp": "6.2.2",
60
+ "picocolors": "^1.0.1",
61
+ "ws": "^8.17.1"
63
62
  },
64
63
  "devDependencies": {
65
- "@pengzhanbo/eslint-config": "^1.5.3",
64
+ "@pengzhanbo/eslint-config": "^1.11.2",
66
65
  "@types/co-body": "^6.1.3",
67
- "@types/cookies": "^0.7.10",
66
+ "@types/cookies": "^0.9.0",
68
67
  "@types/cors": "^2.8.17",
69
68
  "@types/debug": "^4.1.12",
70
69
  "@types/formidable": "2.0.6",
71
70
  "@types/is-core-module": "^2.2.2",
72
71
  "@types/mime-types": "^2.1.4",
73
- "@types/node": "^20.11.5",
72
+ "@types/node": "^20.14.9",
74
73
  "@types/ws": "^8.5.10",
75
- "bumpp": "^9.3.0",
76
- "conventional-changelog-cli": "^4.1.0",
77
- "eslint": "^8.56.0",
74
+ "bumpp": "^9.4.1",
75
+ "conventional-changelog-cli": "^5.0.0",
76
+ "eslint": "^9.6.0",
78
77
  "mockjs": "^1.1.0",
79
- "tsup": "^8.0.1",
80
- "typescript": "^5.3.3",
81
- "vite": "^5.0.11",
82
- "vitepress": "^1.0.0-rc.39",
83
- "vitest": "^1.2.1"
78
+ "tsup": "^8.1.0",
79
+ "typescript": "^5.5.2",
80
+ "vite": "^5.3.2",
81
+ "vitepress": "^1.2.3",
82
+ "vitest": "^1.6.0"
84
83
  },
85
84
  "scripts": {
86
85
  "build": "tsup && node ./deprecate.mjs",