rspack-plugin-mock 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ Object.defineProperty(exports, '__toESM', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return __toESM;
29
+ }
30
+ });
package/dist/helper.cjs CHANGED
@@ -1,129 +1,140 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/defineMock.ts
2
- var _utils = require('@pengzhanbo/utils');
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
3
+ const node_stream = require_chunk.__toESM(require("node:stream"));
4
+
5
+ //#region src/core/defineMock.ts
3
6
  function defineMock(config) {
4
- return config;
7
+ return config;
5
8
  }
9
+ /**
10
+ * Return a custom defineMock function to support preprocessing of mock config.
11
+ *
12
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
13
+ * @param transformer preprocessing function
14
+ * @example
15
+ * ```ts
16
+ * const definePostMock = createDefineMock((mock) => {
17
+ * mock.url = '/api/post/' + mock.url
18
+ * })
19
+ * export default definePostMock({
20
+ * url: 'list',
21
+ * body: [{ title: '1' }, { title: '2' }],
22
+ * })
23
+ * ```
24
+ */
6
25
  function createDefineMock(transformer) {
7
- const define = (config) => {
8
- if (_utils.isArray.call(void 0, config))
9
- config = config.map((item) => transformer(item) || item);
10
- else
11
- config = transformer(config) || config;
12
- return config;
13
- };
14
- return define;
26
+ const define = (config) => {
27
+ if ((0, __pengzhanbo_utils.isArray)(config)) config = config.map((item) => transformer(item) || item);
28
+ else config = transformer(config) || config;
29
+ return config;
30
+ };
31
+ return define;
15
32
  }
16
33
 
17
- // src/core/defineMockData.ts
18
-
19
- var mockDataCache = /* @__PURE__ */ new Map();
20
- var responseCache = /* @__PURE__ */ new WeakMap();
21
- var staleInterval = 70;
34
+ //#endregion
35
+ //#region src/core/defineMockData.ts
36
+ const mockDataCache = /* @__PURE__ */ new Map();
37
+ const responseCache = /* @__PURE__ */ new WeakMap();
38
+ const staleInterval = 70;
22
39
  var CacheImpl = class {
23
-
24
- // 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
25
- #initialValue;
26
- #lastUpdate;
27
- constructor(value) {
28
- this.value = value;
29
- this.#initialValue = _utils.deepClone.call(void 0, value);
30
- this.#lastUpdate = Date.now();
31
- }
32
- hotUpdate(value) {
33
- if (Date.now() - this.#lastUpdate < staleInterval)
34
- return;
35
- if (!_utils.deepEqual.call(void 0, value, this.#initialValue)) {
36
- this.value = value;
37
- this.#initialValue = _utils.deepClone.call(void 0, value);
38
- this.#lastUpdate = Date.now();
39
- }
40
- }
40
+ value;
41
+ #initialValue;
42
+ #lastUpdate;
43
+ constructor(value) {
44
+ this.value = value;
45
+ this.#initialValue = (0, __pengzhanbo_utils.deepClone)(value);
46
+ this.#lastUpdate = Date.now();
47
+ }
48
+ hotUpdate(value) {
49
+ if (Date.now() - this.#lastUpdate < staleInterval) return;
50
+ if (!(0, __pengzhanbo_utils.deepEqual)(value, this.#initialValue)) {
51
+ this.value = value;
52
+ this.#initialValue = (0, __pengzhanbo_utils.deepClone)(value);
53
+ this.#lastUpdate = Date.now();
54
+ }
55
+ }
41
56
  };
42
57
  function defineMockData(key, initialData) {
43
- if (!mockDataCache.has(key))
44
- mockDataCache.set(key, new CacheImpl(initialData));
45
- const cache = mockDataCache.get(key);
46
- cache.hotUpdate(initialData);
47
- if (responseCache.has(cache))
48
- return responseCache.get(cache);
49
- const res = [
50
- () => cache.value,
51
- (val) => {
52
- if (_utils.isFunction.call(void 0, val))
53
- val = _nullishCoalesce(val(cache.value), () => ( cache.value));
54
- cache.value = val;
55
- }
56
- ];
57
- Object.defineProperty(res, "value", {
58
- get() {
59
- return cache.value;
60
- },
61
- set(val) {
62
- cache.value = val;
63
- }
64
- });
65
- responseCache.set(cache, res);
66
- return res;
58
+ if (!mockDataCache.has(key)) mockDataCache.set(key, new CacheImpl(initialData));
59
+ const cache = mockDataCache.get(key);
60
+ cache.hotUpdate(initialData);
61
+ if (responseCache.has(cache)) return responseCache.get(cache);
62
+ const res = [() => cache.value, (val) => {
63
+ if ((0, __pengzhanbo_utils.isFunction)(val)) val = val(cache.value) ?? cache.value;
64
+ cache.value = val;
65
+ }];
66
+ Object.defineProperty(res, "value", {
67
+ get() {
68
+ return cache.value;
69
+ },
70
+ set(val) {
71
+ cache.value = val;
72
+ }
73
+ });
74
+ responseCache.set(cache, res);
75
+ return res;
67
76
  }
68
77
 
69
- // src/core/sse.ts
70
- var _stream = require('stream');
71
- var SSEStream = class extends _stream.Transform {
72
- constructor(req) {
73
- super({ objectMode: true });
74
- req.socket.setKeepAlive(true);
75
- req.socket.setNoDelay(true);
76
- req.socket.setTimeout(0);
77
- }
78
- pipe(destination, options) {
79
- if (destination.writeHead) {
80
- destination.writeHead(200, {
81
- "Content-Type": "text/event-stream; charset=utf-8",
82
- "Transfer-Encoding": "identity",
83
- "Cache-Control": "no-cache",
84
- "Connection": "keep-alive"
85
- });
86
- _optionalChain([destination, 'access', _ => _.flushHeaders, 'optionalCall', _2 => _2()]);
87
- }
88
- destination.write(":ok\n\n");
89
- return super.pipe(destination, options);
90
- }
91
- _transform(message, encoding, callback) {
92
- if (message.comment)
93
- this.push(`: ${message.comment}
94
- `);
95
- if (message.event)
96
- this.push(`event: ${message.event}
97
- `);
98
- if (message.id)
99
- this.push(`id: ${message.id}
100
- `);
101
- if (message.retry)
102
- this.push(`retry: ${message.retry}
103
- `);
104
- if (message.data)
105
- this.push(dataString(message.data));
106
- this.push("\n");
107
- callback();
108
- }
109
- write(message, ...args) {
110
- return super.write(message, ...args);
111
- }
78
+ //#endregion
79
+ //#region src/core/sse.ts
80
+ /**
81
+ * Transforms "messages" to W3C event stream content.
82
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
83
+ * A message is an object with one or more of the following properties:
84
+ * - data (String or object, which gets turned into JSON)
85
+ * - event
86
+ * - id
87
+ * - retry
88
+ * - comment
89
+ *
90
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
91
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
92
+ */
93
+ var SSEStream = class extends node_stream.Transform {
94
+ constructor(req) {
95
+ super({ objectMode: true });
96
+ req.socket.setKeepAlive(true);
97
+ req.socket.setNoDelay(true);
98
+ req.socket.setTimeout(0);
99
+ }
100
+ pipe(destination, options) {
101
+ if (destination.writeHead) {
102
+ destination.writeHead(200, {
103
+ "Content-Type": "text/event-stream; charset=utf-8",
104
+ "Transfer-Encoding": "identity",
105
+ "Cache-Control": "no-cache",
106
+ "Connection": "keep-alive"
107
+ });
108
+ destination.flushHeaders?.();
109
+ }
110
+ destination.write(":ok\n\n");
111
+ return super.pipe(destination, options);
112
+ }
113
+ _transform(message, encoding, callback) {
114
+ if (message.comment) this.push(`: ${message.comment}\n`);
115
+ if (message.event) this.push(`event: ${message.event}\n`);
116
+ if (message.id) this.push(`id: ${message.id}\n`);
117
+ if (message.retry) this.push(`retry: ${message.retry}\n`);
118
+ if (message.data) this.push(dataString(message.data));
119
+ this.push("\n");
120
+ callback();
121
+ }
122
+ write(message, ...args) {
123
+ return super.write(message, ...args);
124
+ }
112
125
  };
113
126
  function dataString(data) {
114
- if (typeof data === "object")
115
- return dataString(JSON.stringify(data));
116
- return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}
117
- `).join("");
127
+ if (typeof data === "object") return dataString(JSON.stringify(data));
128
+ return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
118
129
  }
119
130
  function createSSEStream(req, res) {
120
- const sse = new SSEStream(req);
121
- sse.pipe(res);
122
- return sse;
131
+ const sse = new SSEStream(req);
132
+ sse.pipe(res);
133
+ return sse;
123
134
  }
124
135
 
125
-
126
-
127
-
128
-
129
- exports.createDefineMock = createDefineMock; exports.createSSEStream = createSSEStream; exports.defineMock = defineMock; exports.defineMockData = defineMockData;
136
+ //#endregion
137
+ exports.createDefineMock = createDefineMock;
138
+ exports.createSSEStream = createSSEStream;
139
+ exports.defineMock = defineMock;
140
+ exports.defineMockData = defineMockData;
package/dist/helper.d.cts CHANGED
@@ -1,122 +1,110 @@
1
- import { M as MockHttpItem, a as MockWebsocketItem, b as MockOptions } from './types-Aw0AciTG.cjs';
2
- export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, c as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-Aw0AciTG.cjs';
3
- import { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http';
4
- import { Transform } from 'node:stream';
5
- import 'co-body';
6
- import 'cookies';
7
- import 'cors';
8
- import 'formidable';
9
- import 'node:buffer';
10
- import 'ws';
1
+ import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-6lajtJPx.cjs";
2
+ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
3
+ import { Transform } from "node:stream";
4
+
5
+ //#region src/core/defineMock.d.ts
11
6
 
12
7
  /**
13
- * mock config Type helper
14
- *
15
- * mock配置 类型帮助函数
16
- * @param config see config docs:
17
- * {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
18
- * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
19
- *
20
- * @example
21
- * Mock Http Request
22
- * ```ts
23
- * export default defineMock({
24
- * url: '/api/example',
25
- * method: ['GET', 'POST'],
26
- * body: { a: 1 },
27
- * })
28
- * ```
29
- * ```ts
30
- * export default defineMock({
31
- * url: '/api/example',
32
- * method: 'GET',
33
- * body: ({ query }) => ({ a: 1, b: query.b }),
34
- * })
35
- * ```
36
- * @example
37
- * Mock WebSocket
38
- * ```ts
39
- * export default defineMock({
40
- * url: '/socket.io',
41
- * ws: true,
42
- * setup(wss) {
43
- * wss.on('connection', (ws) => {
44
- * ws.on('message', (rawData) => console.log(rawData))
45
- * ws.send('data')
46
- * })
47
- * },
48
- * })
49
- * ```
50
- */
8
+ * mock config Type helper
9
+ *
10
+ * mock配置 类型帮助函数
11
+ * @param config see config docs:
12
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
13
+ * {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
14
+ *
15
+ * @example
16
+ * Mock Http Request
17
+ * ```ts
18
+ * export default defineMock({
19
+ * url: '/api/example',
20
+ * method: ['GET', 'POST'],
21
+ * body: { a: 1 },
22
+ * })
23
+ * ```
24
+ * ```ts
25
+ * export default defineMock({
26
+ * url: '/api/example',
27
+ * method: 'GET',
28
+ * body: ({ query }) => ({ a: 1, b: query.b }),
29
+ * })
30
+ * ```
31
+ * @example
32
+ * Mock WebSocket
33
+ * ```ts
34
+ * export default defineMock({
35
+ * url: '/socket.io',
36
+ * ws: true,
37
+ * setup(wss) {
38
+ * wss.on('connection', (ws) => {
39
+ * ws.on('message', (rawData) => console.log(rawData))
40
+ * ws.send('data')
41
+ * })
42
+ * },
43
+ * })
44
+ * ```
45
+ */
51
46
  declare function defineMock(config: MockHttpItem): MockHttpItem;
52
47
  declare function defineMock(config: MockWebsocketItem): MockWebsocketItem;
53
48
  declare function defineMock(config: MockOptions): MockOptions;
54
49
  /**
55
- * Return a custom defineMock function to support preprocessing of mock config.
56
- *
57
- * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
58
- * @param transformer preprocessing function
59
- * @example
60
- * ```ts
61
- * const definePostMock = createDefineMock((mock) => {
62
- * mock.url = '/api/post/' + mock.url
63
- * })
64
- * export default definePostMock({
65
- * url: 'list',
66
- * body: [{ title: '1' }, { title: '2' }],
67
- * })
68
- * ```
69
- */
50
+ * Return a custom defineMock function to support preprocessing of mock config.
51
+ *
52
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
53
+ * @param transformer preprocessing function
54
+ * @example
55
+ * ```ts
56
+ * const definePostMock = createDefineMock((mock) => {
57
+ * mock.url = '/api/post/' + mock.url
58
+ * })
59
+ * export default definePostMock({
60
+ * url: 'list',
61
+ * body: [{ title: '1' }, { title: '2' }],
62
+ * })
63
+ * ```
64
+ */
70
65
  declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
71
-
72
- type MockData<T = any> = readonly [
73
- /**
74
- * getter
75
- */
76
- () => T,
77
- /**
78
- * setter
79
- */
80
- (val: T | ((val: T) => T | void)) => void
81
- ] & {
82
- value: T;
66
+ //#endregion
67
+ //#region src/core/defineMockData.d.ts
68
+ type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
69
+ value: T;
83
70
  };
84
71
  declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
85
-
72
+ //#endregion
73
+ //#region src/core/sse.d.ts
86
74
  interface SSEMessage {
87
- data?: string | object;
88
- comment?: string;
89
- event?: string;
90
- id?: string;
91
- retry?: number;
75
+ data?: string | object;
76
+ comment?: string;
77
+ event?: string;
78
+ id?: string;
79
+ retry?: number;
92
80
  }
93
81
  interface WriteHeaders {
94
- writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
95
- flushHeaders?: () => void;
82
+ writeHead?: (statusCode: number, headers?: OutgoingHttpHeaders) => WriteHeaders;
83
+ flushHeaders?: () => void;
96
84
  }
97
85
  type HeaderStream = NodeJS.WritableStream & WriteHeaders;
98
86
  /**
99
- * Transforms "messages" to W3C event stream content.
100
- * See https://html.spec.whatwg.org/multipage/server-sent-events.html
101
- * A message is an object with one or more of the following properties:
102
- * - data (String or object, which gets turned into JSON)
103
- * - event
104
- * - id
105
- * - retry
106
- * - comment
107
- *
108
- * If constructed with a HTTP Request, it will optimise the socket for streaming.
109
- * If this stream is piped to an HTTP Response, it will set appropriate headers.
110
- */
87
+ * Transforms "messages" to W3C event stream content.
88
+ * See https://html.spec.whatwg.org/multipage/server-sent-events.html
89
+ * A message is an object with one or more of the following properties:
90
+ * - data (String or object, which gets turned into JSON)
91
+ * - event
92
+ * - id
93
+ * - retry
94
+ * - comment
95
+ *
96
+ * If constructed with a HTTP Request, it will optimise the socket for streaming.
97
+ * If this stream is piped to an HTTP Response, it will set appropriate headers.
98
+ */
111
99
  declare class SSEStream extends Transform {
112
- constructor(req: IncomingMessage);
113
- pipe<T extends HeaderStream>(destination: T, options?: {
114
- end?: boolean;
115
- }): T;
116
- _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
117
- write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
118
- write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
100
+ constructor(req: IncomingMessage);
101
+ pipe<T extends HeaderStream>(destination: T, options?: {
102
+ end?: boolean;
103
+ }): T;
104
+ _transform(message: SSEMessage, encoding: string, callback: (error?: (Error | null), data?: any) => void): void;
105
+ write(message: SSEMessage, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
106
+ write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
119
107
  }
120
108
  declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
121
-
122
- export { type HeaderStream, type MockData, MockHttpItem, MockOptions, MockWebsocketItem, type SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
109
+ //#endregion
110
+ export { BodyParserOptions, ExtraRequest, FormidableFile, HeaderStream, LogLevel, LogType, Method, MockData, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, SSEMessage, ServerBuildOption, WebSocketSetupContext, createDefineMock, createSSEStream, defineMock, defineMockData };