rspack-plugin-mock 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/helper.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { A as ResponseBody, C as HandleFunction, D as MockResponse, E as MockRequest, M as CookiesOption, N as GetCookieOption, O as NextFunction, P as SetCookieOption, S as ExtraRequest, T as Method, _ as RecordedMeta, a as MockWebsocketItem, b as RecordedRes, c as MockHttpItem, d as LogType, f as MockMatchPriority, g as RecordOptions, h as ServerBuildOption, i as MockOptions, j as SimpleHandleFunction, k as NextHandleFunction, l as BodyParserOptions, m as MockServerPluginOptions, n as HttpProxyPlugin, o as WebSocketSetupContext, p as MockMatchSpecialPriority, r as PathFilter, s as MockErrorConfig, t as FormidableFile, u as LogLevel, v as RecordedReq, w as Headers, x as ResolvedRecordOptions, y as RecordedRequest } from "./index-BMMGM-eD.js";
2
- import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
1
+ import { A as ResponseBody, C as HandleFunction, D as MockResponse, E as MockRequest, M as CookiesOption, N as GetCookieOption, O as NextFunction, P as SetCookieOption, S as ExtraRequest, T as Method, _ as RecordedMeta, a as MockWebsocketItem, b as RecordedRes, c as MockHttpItem, d as LogType, f as MockMatchPriority, g as RecordOptions, h as ServerBuildOption, i as MockOptions, j as SimpleHandleFunction, k as NextHandleFunction, l as BodyParserOptions, m as MockServerPluginOptions, n as HttpProxyPlugin, o as WebSocketSetupContext, p as MockMatchSpecialPriority, r as PathFilter, s as MockErrorConfig, t as FormidableFile, u as LogLevel, v as RecordedReq, w as Headers, x as ResolvedRecordOptions, y as RecordedRequest } from "./index-BjZK24gW.js";
3
2
  import { Transform } from "node:stream";
4
-
3
+ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
5
4
  //#region src/helpers/createSSEStream.d.ts
6
5
  interface SSEMessage {
7
6
  data?: string | object;
@@ -16,18 +15,18 @@ interface WriteHeaders {
16
15
  }
17
16
  type HeaderStream = NodeJS.WritableStream & WriteHeaders;
18
17
  /**
19
- * Transforms "messages" to W3C event stream content.
20
- * See https://html.spec.whatwg.org/multipage/server-sent-events.html
21
- * A message is an object with one or more of the following properties:
22
- * - data (String or object, which gets turned into JSON)
23
- * - event
24
- * - id
25
- * - retry
26
- * - comment
27
- *
28
- * If constructed with a HTTP Request, it will optimise the socket for streaming.
29
- * If this stream is piped to an HTTP Response, it will set appropriate headers.
30
- */
18
+ * Transforms "messages" to W3C event stream content.
19
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
20
+ * A message is an object with one or more of the following properties:
21
+ * - data (String or object, which gets turned into JSON)
22
+ * - event
23
+ * - id
24
+ * - retry
25
+ * - comment
26
+ *
27
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
28
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
29
+ */
31
30
  declare class SSEStream extends Transform {
32
31
  constructor(req: IncomingMessage);
33
32
  pipe<T extends HeaderStream>(destination: T, options?: {
@@ -39,126 +38,126 @@ declare class SSEStream extends Transform {
39
38
  destroy(error?: Error): this;
40
39
  }
41
40
  /**
42
- * 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
43
- *
44
- * @example
45
- * ```ts
46
- * import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
47
- *
48
- * export default defineMock({
49
- * url: '/api',
50
- * response: (req, res) => {
51
- * const sse = createSSEStream(req, res)
52
- * sse.write({ event: 'message', data: { message: 'hello world' } })
53
- * }
54
- * })
55
- * ```
56
- */
41
+ * 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
46
+ *
47
+ * export default defineMock({
48
+ * url: '/api',
49
+ * response: (req, res) => {
50
+ * const sse = createSSEStream(req, res)
51
+ * sse.write({ event: 'message', data: { message: 'hello world' } })
52
+ * }
53
+ * })
54
+ * ```
55
+ */
57
56
  declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
58
57
  //#endregion
59
58
  //#region src/helpers/defineMock.d.ts
60
59
  /**
61
- * Mock config Type helper
62
- *
63
- * mock配置 类型帮助函数
64
- * @param config see config docs:
65
- * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
66
- * {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
67
- *
68
- * @example
69
- * Mock Http Request
70
- * ```ts
71
- * export default defineMock({
72
- * url: '/api/example',
73
- * method: ['GET', 'POST'],
74
- * body: { a: 1 },
75
- * })
76
- * ```
77
- * ```ts
78
- * export default defineMock({
79
- * url: '/api/example',
80
- * method: 'GET',
81
- * body: ({ query }) => ({ a: 1, b: query.b }),
82
- * })
83
- * ```
84
- * @example
85
- * Mock WebSocket
86
- * ```ts
87
- * export default defineMock({
88
- * url: '/socket.io',
89
- * ws: true,
90
- * setup(wss) {
91
- * wss.on('connection', (ws) => {
92
- * ws.on('message', (rawData) => console.log(rawData))
93
- * ws.send('data')
94
- * })
95
- * },
96
- * })
97
- * ```
98
- */
60
+ * Mock config Type helper
61
+ *
62
+ * mock配置 类型帮助函数
63
+ * @param config see config docs:
64
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
65
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
66
+ *
67
+ * @example
68
+ * Mock Http Request
69
+ * ```ts
70
+ * export default defineMock({
71
+ * url: '/api/example',
72
+ * method: ['GET', 'POST'],
73
+ * body: { a: 1 },
74
+ * })
75
+ * ```
76
+ * ```ts
77
+ * export default defineMock({
78
+ * url: '/api/example',
79
+ * method: 'GET',
80
+ * body: ({ query }) => ({ a: 1, b: query.b }),
81
+ * })
82
+ * ```
83
+ * @example
84
+ * Mock WebSocket
85
+ * ```ts
86
+ * export default defineMock({
87
+ * url: '/socket.io',
88
+ * ws: true,
89
+ * setup(wss) {
90
+ * wss.on('connection', (ws) => {
91
+ * ws.on('message', (rawData) => console.log(rawData))
92
+ * ws.send('data')
93
+ * })
94
+ * },
95
+ * })
96
+ * ```
97
+ */
99
98
  declare function defineMock(config: MockHttpItem): MockHttpItem;
100
99
  declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
101
100
  declare function defineMock(config: MockOptions): MockOptions;
102
101
  /**
103
- * Return a custom defineMock function to support preprocessing of mock config.
104
- *
105
- * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
106
- * @param transformer preprocessing function
107
- * @example
108
- * ```ts
109
- * const definePostMock = createDefineMock((mock) => {
110
- * mock.url = '/api/post/' + mock.url
111
- * })
112
- * export default definePostMock({
113
- * url: 'list',
114
- * body: [{ title: '1' }, { title: '2' }],
115
- * })
116
- * ```
117
- */
102
+ * Return a custom defineMock function to support preprocessing of mock config.
103
+ *
104
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
105
+ * @param transformer preprocessing function
106
+ * @example
107
+ * ```ts
108
+ * const definePostMock = createDefineMock((mock) => {
109
+ * mock.url = '/api/post/' + mock.url
110
+ * })
111
+ * export default definePostMock({
112
+ * url: 'list',
113
+ * body: [{ title: '1' }, { title: '2' }],
114
+ * })
115
+ * ```
116
+ */
118
117
  declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
119
118
  //#endregion
120
119
  //#region src/helpers/defineMockData.d.ts
121
120
  /**
122
- * Options for defineMockData
123
- *
124
- * defineMockData 的选项
125
- */
121
+ * Options for defineMockData
122
+ *
123
+ * defineMockData 的选项
124
+ */
126
125
  interface DefineMockDataOptions {
127
126
  /**
128
- * Whether to persist the data value on HMR (Hot Module Replacement).
129
- *
130
- * 热更新时是否保持数据值
131
- *
132
- * @default false
133
- */
127
+ * Whether to persist the data value on HMR (Hot Module Replacement).
128
+ *
129
+ * 热更新时是否保持数据值
130
+ *
131
+ * @default false
132
+ */
134
133
  persistOnHMR?: boolean;
135
134
  }
136
135
  /**
137
- * Mock data type with getter, setter, and value property
138
- *
139
- * 带有 getter、setter 和 value 属性的 Mock 数据类型
140
- *
141
- * @template T - Type of mock data / Mock 数据的类型
142
- */
136
+ * Mock data type with getter, setter, and value property
137
+ *
138
+ * 带有 getter、setter 和 value 属性的 Mock 数据类型
139
+ *
140
+ * @template T - Type of mock data / Mock 数据的类型
141
+ */
143
142
  type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
144
143
  /**
145
- * Current value
146
- *
147
- * 当前值
148
- */
144
+ * Current value
145
+ *
146
+ * 当前值
147
+ */
149
148
  value: T;
150
149
  };
151
150
  /**
152
- * Define mock data with memory-based sharing mechanism
153
- *
154
- * 定义带有基于内存的共享机制的 Mock 数据
155
- *
156
- * @template T - Type of mock data / Mock 数据的类型
157
- * @param key - Unique key for mock data / Mock 数据的唯一键
158
- * @param initialData - Initial data value / 初始数据值
159
- * @param options - Options / 选项
160
- * @returns MockData object with getter, setter, and value property / 带有 getter、setter 和 value 属性的 MockData 对象
161
- */
151
+ * Define mock data with memory-based sharing mechanism
152
+ *
153
+ * 定义带有基于内存的共享机制的 Mock 数据
154
+ *
155
+ * @template T - Type of mock data / Mock 数据的类型
156
+ * @param key - Unique key for mock data / Mock 数据的唯一键
157
+ * @param initialData - Initial data value / 初始数据值
158
+ * @param options - Options / 选项
159
+ * @returns MockData object with getter, setter, and value property / 带有 getter、setter 和 value 属性的 MockData 对象
160
+ */
162
161
  declare function defineMockData<T = any>(key: string, initialData: T, options?: DefineMockDataOptions): MockData<T>;
163
162
  //#endregion
164
- export { BodyParserOptions, CookiesOption, DefineMockDataOptions, ExtraRequest, FormidableFile, GetCookieOption, HandleFunction, HeaderStream, Headers, HttpProxyPlugin, LogLevel, LogType, Method, MockData, MockErrorConfig, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, NextFunction, NextHandleFunction, PathFilter, RecordOptions, RecordedMeta, RecordedReq, RecordedRequest, RecordedRes, ResolvedRecordOptions, ResponseBody, SSEMessage, ServerBuildOption, SetCookieOption, SimpleHandleFunction, WebSocketSetupContext, createDefineMock, createSSEStream, defineMock, defineMockData };
163
+ export { type BodyParserOptions, type CookiesOption, DefineMockDataOptions, type ExtraRequest, type FormidableFile, type GetCookieOption, type HandleFunction, HeaderStream, type Headers, type HttpProxyPlugin, type LogLevel, type LogType, type Method, MockData, type MockErrorConfig, type MockHttpItem, type MockMatchPriority, type MockMatchSpecialPriority, type MockOptions, type MockRequest, type MockResponse, type MockServerPluginOptions, type MockWebsocketItem, type NextFunction, type NextHandleFunction, type PathFilter, type RecordOptions, type RecordedMeta, type RecordedReq, type RecordedRequest, type RecordedRes, type ResolvedRecordOptions, type ResponseBody, SSEMessage, type ServerBuildOption, type SetCookieOption, type SimpleHandleFunction, type WebSocketSetupContext, createDefineMock, createSSEStream, defineMock, defineMockData };
package/dist/helper.js CHANGED
@@ -1,20 +1,8 @@
1
1
  import { deepClone, isArray, isFunction } from "@pengzhanbo/utils";
2
2
  import { createHash } from "node:crypto";
3
3
  import { Transform } from "node:stream";
4
- //#region src/helpers/createSSEStream.ts
5
- /**
6
- * Transforms "messages" to W3C event stream content.
7
- * See https://html.spec.whatwg.org/multipage/server-sent-events.html
8
- * A message is an object with one or more of the following properties:
9
- * - data (String or object, which gets turned into JSON)
10
- * - event
11
- * - id
12
- * - retry
13
- * - comment
14
- *
15
- * If constructed with a HTTP Request, it will optimise the socket for streaming.
16
- * If this stream is piped to an HTTP Response, it will set appropriate headers.
17
- */
4
+
5
+
18
6
  var SSEStream = class extends Transform {
19
7
  constructor(req) {
20
8
  super({ objectMode: true });
@@ -60,48 +48,18 @@ function dataString(data) {
60
48
  if (typeof data === "object") return dataString(JSON.stringify(data));
61
49
  return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
62
50
  }
63
- /**
64
- * 创建一个 Server-sent events 写入流,用于支持模拟 EventSource
65
- *
66
- * @example
67
- * ```ts
68
- * import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
69
- *
70
- * export default defineMock({
71
- * url: '/api',
72
- * response: (req, res) => {
73
- * const sse = createSSEStream(req, res)
74
- * sse.write({ event: 'message', data: { message: 'hello world' } })
75
- * }
76
- * })
77
- * ```
78
- */
51
+
79
52
  function createSSEStream(req, res) {
80
53
  const sse = new SSEStream(req);
81
54
  sse.pipe(res);
82
55
  return sse;
83
56
  }
84
- //#endregion
85
- //#region src/helpers/defineMock.ts
57
+
58
+
86
59
  function defineMock(config) {
87
60
  return config;
88
61
  }
89
- /**
90
- * Return a custom defineMock function to support preprocessing of mock config.
91
- *
92
- * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
93
- * @param transformer preprocessing function
94
- * @example
95
- * ```ts
96
- * const definePostMock = createDefineMock((mock) => {
97
- * mock.url = '/api/post/' + mock.url
98
- * })
99
- * export default definePostMock({
100
- * url: 'list',
101
- * body: [{ title: '1' }, { title: '2' }],
102
- * })
103
- * ```
104
- */
62
+
105
63
  function createDefineMock(transformer) {
106
64
  const define = (config) => {
107
65
  if (isArray(config)) config = config.map((item) => transformer(item) || item);
@@ -110,96 +68,33 @@ function createDefineMock(transformer) {
110
68
  };
111
69
  return define;
112
70
  }
113
- //#endregion
114
- //#region src/helpers/defineMockData.ts
115
- /**
116
- * Since the plugin compiles `*.mock.*` files as separate independent entries,
117
- * this leads to inconsistent dependency relationships after mock file compilation,
118
- * with each mock file having its own scope.
119
- * Even if multiple `*.mock.*` files import the same `data.ts` file, they are
120
- * completely different instances of `data`, making operations on `data` not
121
- * shareable across different `*.mock.*` files.
122
- *
123
- * To address this, the plugin provides a memory-based data sharing mechanism.
124
- *
125
- * 由于插件是分别独立对 `*.mock.*` 等文件作为单独入口进行编译的,
126
- * 这导致了 mock 文件编译后的依赖关系不一致,每个 mock 文件拥有独立的作用域,
127
- * 使得即使多个 `*.mock.*` 虽然引入了同一个 `data.ts` 文件,然而确是完全不同两份 `data`,
128
- * 使得对 `data` 的操作,在不同的 `*.mock.*` 文件中并不能共享。
129
- *
130
- * 为此,插件提供了一种基于 memory 的数据共享机制。
131
- */
132
- /**
133
- * Mock data cache
134
- *
135
- * Mock 数据缓存
136
- */
137
- const mockDataCache = /* @__PURE__ */ new Map();
138
- /**
139
- * Response cache for MockData objects
140
- *
141
- * MockData 对象的响应缓存
142
- */
143
- const responseCache = /* @__PURE__ */ new WeakMap();
144
- /**
145
- * Stale interval in milliseconds
146
- *
147
- * 缓存过期间隔(毫秒)
148
- */
71
+
72
+
73
+
74
+
75
+ const mockDataCache = new Map();
76
+
77
+ const responseCache = new WeakMap();
78
+
149
79
  const staleInterval = 70;
150
- /**
151
- * Cache implementation for mock data
152
- *
153
- * Mock 数据缓存实现
154
- *
155
- * @template T - Type of cached data / 缓存数据的类型
156
- */
80
+
157
81
  var CacheImpl = class {
158
- /**
159
- * Current cached value
160
- *
161
- * 当前缓存值
162
- */
82
+
163
83
  value;
164
- /**
165
- * Initial value hash, used to detect if initial data has changed
166
- *
167
- * 初始化数据的哈希值,用于判断传入的初始化数据是否发生变更
168
- */
84
+
169
85
  #hash;
170
- /**
171
- * Last update timestamp
172
- *
173
- * 最后更新时间戳
174
- */
86
+
175
87
  #lastUpdate;
176
- /**
177
- * Whether to persist data on HMR
178
- *
179
- * 热更新时是否保持数据
180
- */
88
+
181
89
  #persistOnHMR;
182
- /**
183
- * Constructor
184
- *
185
- * 构造函数
186
- *
187
- * @param value - Initial value / 初始值
188
- * @param persistOnHMR - Whether to persist data on HMR / 热更新时是否保持数据
189
- */
90
+
190
91
  constructor(value, persistOnHMR) {
191
92
  this.value = value;
192
93
  this.#hash = getHash(value);
193
94
  this.#lastUpdate = Date.now();
194
95
  this.#persistOnHMR = persistOnHMR ?? false;
195
96
  }
196
- /**
197
- * Hot update cached value
198
- *
199
- * 热更新缓存值
200
- *
201
- * @param value - New value / 新值
202
- */
97
+
203
98
  hotUpdate(value) {
204
99
  if (this.#persistOnHMR) return;
205
100
  if (Date.now() - this.#lastUpdate < staleInterval) return;
@@ -210,28 +105,12 @@ var CacheImpl = class {
210
105
  this.#lastUpdate = Date.now();
211
106
  }
212
107
  }
213
- /**
214
- * Set persistOnHMR
215
- *
216
- * 设置 persistOnHMR
217
- *
218
- * @param persistOnHMR - Whether to persist data on HMR / 热更新时是否保持数据
219
- */
108
+
220
109
  setPersistOnHMR(persistOnHMR) {
221
110
  if (!this.#persistOnHMR) this.#persistOnHMR = persistOnHMR;
222
111
  }
223
112
  };
224
- /**
225
- * Define mock data with memory-based sharing mechanism
226
- *
227
- * 定义带有基于内存的共享机制的 Mock 数据
228
- *
229
- * @template T - Type of mock data / Mock 数据的类型
230
- * @param key - Unique key for mock data / Mock 数据的唯一键
231
- * @param initialData - Initial data value / 初始数据值
232
- * @param options - Options / 选项
233
- * @returns MockData object with getter, setter, and value property / 带有 getter、setter 和 value 属性的 MockData 对象
234
- */
113
+
235
114
  function defineMockData(key, initialData, options) {
236
115
  let cache = mockDataCache.get(key);
237
116
  if (!cache) {
@@ -263,5 +142,5 @@ function defineMockData(key, initialData, options) {
263
142
  function getHash(data) {
264
143
  return createHash("sha256").update(JSON.stringify(data)).digest("hex");
265
144
  }
266
- //#endregion
145
+
267
146
  export { createDefineMock, createSSEStream, defineMock, defineMockData };