vite-plugin-mock-dev-server 1.8.6 → 1.9.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/{chunk-BCwAaXi7.cjs → chunk-CUT6urMc.cjs} +0 -1
- package/dist/{helper-PQrLL5uH.cjs → helper-Dwzt-HKi.cjs} +4 -4
- package/dist/{helper-L9yYYkP2.js → helper-XBACG61a.js} +3 -2
- package/dist/{helper-Di4IZQHq.d.cts → helper-iVHsUTZ6.d.cts} +4 -45
- package/dist/{helper-6T1vILP_.d.ts → helper-ssk6rMi5.d.ts} +5 -46
- package/dist/helper.cjs +5 -5
- package/dist/helper.d.cts +2 -2
- package/dist/helper.d.ts +2 -2
- package/dist/helper.js +1 -1
- package/dist/index.cjs +38 -24
- package/dist/index.d.cts +10 -5
- package/dist/index.d.ts +10 -5
- package/dist/index.js +27 -14
- package/dist/{server-CAGUKvhH.d.cts → server-B5Ua2cmP.d.cts} +1 -7
- package/dist/{server-CvxjyuVU.cjs → server-CZwOQzgC.cjs} +20 -12
- package/dist/{server-BKiEqtZe.js → server-Dr9FAgt4.js} +35 -26
- package/dist/{server-CXqFaG_J.d.ts → server-XauDEVqY.d.ts} +2 -8
- package/dist/server.cjs +8 -8
- package/dist/server.d.cts +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/{types-BdGI944Z.d.cts → types-D2dm9iaM.d.ts} +8 -11
- package/dist/{types-CxzZg47I.d.ts → types-DpbHkRjL.d.cts} +8 -11
- package/package.json +5 -5
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
const require_chunk = require('./chunk-BCwAaXi7.cjs');
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
3
2
|
const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
|
|
4
3
|
const node_stream = require_chunk.__toESM(require("node:stream"));
|
|
5
4
|
|
|
@@ -34,10 +33,11 @@ function createDefineMock(transformer) {
|
|
|
34
33
|
|
|
35
34
|
//#endregion
|
|
36
35
|
//#region src/core/defineMockData.ts
|
|
37
|
-
const mockDataCache = new Map();
|
|
38
|
-
const responseCache = new WeakMap();
|
|
36
|
+
const mockDataCache = /* @__PURE__ */ new Map();
|
|
37
|
+
const responseCache = /* @__PURE__ */ new WeakMap();
|
|
39
38
|
const staleInterval = 70;
|
|
40
39
|
var CacheImpl = class {
|
|
40
|
+
value;
|
|
41
41
|
#initialValue;
|
|
42
42
|
#lastUpdate;
|
|
43
43
|
constructor(value) {
|
|
@@ -32,10 +32,11 @@ function createDefineMock(transformer) {
|
|
|
32
32
|
|
|
33
33
|
//#endregion
|
|
34
34
|
//#region src/core/defineMockData.ts
|
|
35
|
-
const mockDataCache = new Map();
|
|
36
|
-
const responseCache = new WeakMap();
|
|
35
|
+
const mockDataCache = /* @__PURE__ */ new Map();
|
|
36
|
+
const responseCache = /* @__PURE__ */ new WeakMap();
|
|
37
37
|
const staleInterval = 70;
|
|
38
38
|
var CacheImpl = class {
|
|
39
|
+
value;
|
|
39
40
|
#initialValue;
|
|
40
41
|
#lastUpdate;
|
|
41
42
|
constructor(value) {
|
|
@@ -1,54 +1,16 @@
|
|
|
1
|
-
import { MockHttpItem, MockOptions, MockWebsocketItem } from "./types-
|
|
1
|
+
import { MockHttpItem, MockOptions, MockWebsocketItem } from "./types-DpbHkRjL.cjs";
|
|
2
2
|
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
3
3
|
import { Transform } from "node:stream";
|
|
4
4
|
|
|
5
5
|
//#region src/core/defineMock.d.ts
|
|
6
|
+
|
|
6
7
|
/**
|
|
7
8
|
* mock config Type helper
|
|
8
9
|
*
|
|
9
10
|
* mock配置 类型帮助函数
|
|
10
11
|
* @param config see config docs:
|
|
11
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/
|
|
12
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* Mock Http Request
|
|
16
|
-
* ```ts
|
|
17
|
-
* export default defineMock({
|
|
18
|
-
* url: '/api/example',
|
|
19
|
-
* method: ['GET', 'POST'],
|
|
20
|
-
* body: { a: 1 },
|
|
21
|
-
* })
|
|
22
|
-
* ```
|
|
23
|
-
* ```ts
|
|
24
|
-
* export default defineMock({
|
|
25
|
-
* url: '/api/example',
|
|
26
|
-
* method: 'GET',
|
|
27
|
-
* body: ({ query }) => ({ a: 1, b: query.b }),
|
|
28
|
-
* })
|
|
29
|
-
* ```
|
|
30
|
-
* @example
|
|
31
|
-
* Mock WebSocket
|
|
32
|
-
* ```ts
|
|
33
|
-
* export default defineMock({
|
|
34
|
-
* url: '/socket.io',
|
|
35
|
-
* ws: true,
|
|
36
|
-
* setup(wss) {
|
|
37
|
-
* wss.on('connection', (ws) => {
|
|
38
|
-
* ws.on('message', (rawData) => console.log(rawData))
|
|
39
|
-
* ws.send('data')
|
|
40
|
-
* })
|
|
41
|
-
* },
|
|
42
|
-
* })
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
/**
|
|
46
|
-
* mock config Type helper
|
|
47
|
-
*
|
|
48
|
-
* mock配置 类型帮助函数
|
|
49
|
-
* @param config see config docs:
|
|
50
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
|
|
51
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
|
|
12
|
+
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
|
|
13
|
+
* {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
|
|
52
14
|
*
|
|
53
15
|
* @example
|
|
54
16
|
* Mock Http Request
|
|
@@ -101,14 +63,12 @@ declare function defineMock(config: MockOptions): MockOptions;
|
|
|
101
63
|
* ```
|
|
102
64
|
*/
|
|
103
65
|
declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
|
|
104
|
-
|
|
105
66
|
//#endregion
|
|
106
67
|
//#region src/core/defineMockData.d.ts
|
|
107
68
|
type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
|
|
108
69
|
value: T;
|
|
109
70
|
};
|
|
110
71
|
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
111
|
-
|
|
112
72
|
//#endregion
|
|
113
73
|
//#region src/core/sse.d.ts
|
|
114
74
|
interface SSEMessage {
|
|
@@ -146,6 +106,5 @@ declare class SSEStream extends Transform {
|
|
|
146
106
|
write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
|
|
147
107
|
}
|
|
148
108
|
declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
|
|
149
|
-
|
|
150
109
|
//#endregion
|
|
151
110
|
export { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
|
|
@@ -1,54 +1,16 @@
|
|
|
1
|
-
import { MockHttpItem, MockOptions, MockWebsocketItem } from "./types-
|
|
1
|
+
import { MockHttpItem, MockOptions, MockWebsocketItem } from "./types-D2dm9iaM.js";
|
|
2
2
|
import { Transform } from "node:stream";
|
|
3
3
|
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
4
4
|
|
|
5
5
|
//#region src/core/defineMock.d.ts
|
|
6
|
+
|
|
6
7
|
/**
|
|
7
8
|
* mock config Type helper
|
|
8
9
|
*
|
|
9
10
|
* mock配置 类型帮助函数
|
|
10
11
|
* @param config see config docs:
|
|
11
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/
|
|
12
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* Mock Http Request
|
|
16
|
-
* ```ts
|
|
17
|
-
* export default defineMock({
|
|
18
|
-
* url: '/api/example',
|
|
19
|
-
* method: ['GET', 'POST'],
|
|
20
|
-
* body: { a: 1 },
|
|
21
|
-
* })
|
|
22
|
-
* ```
|
|
23
|
-
* ```ts
|
|
24
|
-
* export default defineMock({
|
|
25
|
-
* url: '/api/example',
|
|
26
|
-
* method: 'GET',
|
|
27
|
-
* body: ({ query }) => ({ a: 1, b: query.b }),
|
|
28
|
-
* })
|
|
29
|
-
* ```
|
|
30
|
-
* @example
|
|
31
|
-
* Mock WebSocket
|
|
32
|
-
* ```ts
|
|
33
|
-
* export default defineMock({
|
|
34
|
-
* url: '/socket.io',
|
|
35
|
-
* ws: true,
|
|
36
|
-
* setup(wss) {
|
|
37
|
-
* wss.on('connection', (ws) => {
|
|
38
|
-
* ws.on('message', (rawData) => console.log(rawData))
|
|
39
|
-
* ws.send('data')
|
|
40
|
-
* })
|
|
41
|
-
* },
|
|
42
|
-
* })
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
/**
|
|
46
|
-
* mock config Type helper
|
|
47
|
-
*
|
|
48
|
-
* mock配置 类型帮助函数
|
|
49
|
-
* @param config see config docs:
|
|
50
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/en/guide/mock-config en-US DOC} |
|
|
51
|
-
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config zh-CN DOC}
|
|
12
|
+
* {@link https://vite-plugin-mock-dev-server.netlify.app/guide/mock-config en-US DOC} |
|
|
13
|
+
* {@link https://vite-plugin-mock-dev-server.netlify.app/zh/guide/mock-config zh-CN DOC}
|
|
52
14
|
*
|
|
53
15
|
* @example
|
|
54
16
|
* Mock Http Request
|
|
@@ -101,14 +63,12 @@ declare function defineMock(config: MockOptions): MockOptions;
|
|
|
101
63
|
* ```
|
|
102
64
|
*/
|
|
103
65
|
declare function createDefineMock(transformer: (mock: MockHttpItem | MockWebsocketItem) => MockHttpItem | MockWebsocketItem | void): typeof defineMock;
|
|
104
|
-
|
|
105
66
|
//#endregion
|
|
106
67
|
//#region src/core/defineMockData.d.ts
|
|
107
68
|
type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) => void] & {
|
|
108
69
|
value: T;
|
|
109
70
|
};
|
|
110
71
|
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
111
|
-
|
|
112
72
|
//#endregion
|
|
113
73
|
//#region src/core/sse.d.ts
|
|
114
74
|
interface SSEMessage {
|
|
@@ -146,6 +106,5 @@ declare class SSEStream extends Transform {
|
|
|
146
106
|
write(message: SSEMessage, cb?: (error: Error | null | undefined) => void): boolean;
|
|
147
107
|
}
|
|
148
108
|
declare function createSSEStream(req: IncomingMessage, res: ServerResponse): SSEStream;
|
|
149
|
-
|
|
150
109
|
//#endregion
|
|
151
|
-
export { HeaderStream, MockData, SSEMessage, createDefineMock
|
|
110
|
+
export { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
|
package/dist/helper.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const require_helper = require('./helper-
|
|
1
|
+
const require_helper = require('./helper-Dwzt-HKi.cjs');
|
|
2
2
|
|
|
3
|
-
exports.createDefineMock = require_helper.createDefineMock
|
|
4
|
-
exports.createSSEStream = require_helper.createSSEStream
|
|
5
|
-
exports.defineMock = require_helper.defineMock
|
|
6
|
-
exports.defineMockData = require_helper.defineMockData
|
|
3
|
+
exports.createDefineMock = require_helper.createDefineMock;
|
|
4
|
+
exports.createSSEStream = require_helper.createSSEStream;
|
|
5
|
+
exports.defineMock = require_helper.defineMock;
|
|
6
|
+
exports.defineMockData = require_helper.defineMockData;
|
package/dist/helper.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { MockHttpItem, MockOptions, MockRequest, MockWebsocketItem } from "./types-
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-
|
|
1
|
+
import { MockHttpItem, MockOptions, MockRequest, MockWebsocketItem } from "./types-DpbHkRjL.cjs";
|
|
2
|
+
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-iVHsUTZ6.cjs";
|
|
3
3
|
export { HeaderStream, MockData, MockHttpItem, MockOptions, MockRequest, MockWebsocketItem, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
|
package/dist/helper.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { MockHttpItem, MockOptions, MockRequest, MockWebsocketItem } from "./types-
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock
|
|
1
|
+
import { MockHttpItem, MockOptions, MockRequest, MockWebsocketItem } from "./types-D2dm9iaM.js";
|
|
2
|
+
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-ssk6rMi5.js";
|
|
3
3
|
export { HeaderStream, MockData, MockHttpItem, MockOptions, MockRequest, MockWebsocketItem, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData };
|
package/dist/helper.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-
|
|
1
|
+
import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-XBACG61a.js";
|
|
2
2
|
|
|
3
3
|
export { createDefineMock, createSSEStream, defineMock, defineMockData };
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
const require_chunk = require('./chunk-
|
|
3
|
-
const require_helper = require('./helper-
|
|
4
|
-
const require_server = require('./server-
|
|
1
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
3
|
+
const require_helper = require('./helper-Dwzt-HKi.cjs');
|
|
4
|
+
const require_server = require('./server-CZwOQzgC.cjs');
|
|
5
5
|
const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
|
|
6
|
+
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
6
7
|
const node_fs = require_chunk.__toESM(require("node:fs"));
|
|
7
8
|
const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
|
|
8
9
|
const node_path = require_chunk.__toESM(require("node:path"));
|
|
@@ -10,7 +11,6 @@ const node_process = require_chunk.__toESM(require("node:process"));
|
|
|
10
11
|
const __rollup_pluginutils = require_chunk.__toESM(require("@rollup/pluginutils"));
|
|
11
12
|
const fast_glob = require_chunk.__toESM(require("fast-glob"));
|
|
12
13
|
const is_core_module = require_chunk.__toESM(require("is-core-module"));
|
|
13
|
-
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
14
14
|
const node_url = require_chunk.__toESM(require("node:url"));
|
|
15
15
|
const esbuild = require_chunk.__toESM(require("esbuild"));
|
|
16
16
|
const json5 = require_chunk.__toESM(require("json5"));
|
|
@@ -203,9 +203,9 @@ async function generateMockServer(ctx, options) {
|
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
205
|
function getMockDependencies(deps, alias) {
|
|
206
|
-
const list = new Set();
|
|
206
|
+
const list = /* @__PURE__ */ new Set();
|
|
207
207
|
const excludeDeps = [
|
|
208
|
-
|
|
208
|
+
__PACKAGE_NAME__,
|
|
209
209
|
"connect",
|
|
210
210
|
"cors"
|
|
211
211
|
];
|
|
@@ -236,7 +236,7 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
236
236
|
scripts: { start: "node index.js" },
|
|
237
237
|
dependencies: {
|
|
238
238
|
connect: "^3.7.0",
|
|
239
|
-
[
|
|
239
|
+
[__PACKAGE_NAME__]: `^${__PACKAGE_VERSION__}`,
|
|
240
240
|
cors: "^2.8.5"
|
|
241
241
|
},
|
|
242
242
|
pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
|
|
@@ -311,8 +311,11 @@ function createMockCompiler(options) {
|
|
|
311
311
|
* mock配置加载器
|
|
312
312
|
*/
|
|
313
313
|
var MockCompiler = class extends node_events.default {
|
|
314
|
-
moduleCache = new Map();
|
|
315
|
-
moduleDeps = new Map();
|
|
314
|
+
moduleCache = /* @__PURE__ */ new Map();
|
|
315
|
+
moduleDeps = /* @__PURE__ */ new Map();
|
|
316
|
+
cwd;
|
|
317
|
+
mockWatcher;
|
|
318
|
+
depsWatcher;
|
|
316
319
|
moduleType = "cjs";
|
|
317
320
|
_mockData = {};
|
|
318
321
|
constructor(options) {
|
|
@@ -418,7 +421,7 @@ var MockCompiler = class extends node_events.default {
|
|
|
418
421
|
Object.keys(deps).forEach((mPath) => {
|
|
419
422
|
const imports = deps[mPath].imports.map((_) => _.path);
|
|
420
423
|
imports.forEach((dep) => {
|
|
421
|
-
if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, new Set());
|
|
424
|
+
if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
|
|
422
425
|
const cur = this.moduleDeps.get(dep);
|
|
423
426
|
cur.add(filepath);
|
|
424
427
|
});
|
|
@@ -495,7 +498,7 @@ function mockServerMiddleware(options, server, ws) {
|
|
|
495
498
|
*/
|
|
496
499
|
corsMiddleware(compiler, options),
|
|
497
500
|
require_server.baseMiddleware(compiler, options)
|
|
498
|
-
);
|
|
501
|
+
);
|
|
499
502
|
return middlewares.filter(Boolean);
|
|
500
503
|
}
|
|
501
504
|
function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
|
|
@@ -703,15 +706,26 @@ function serverPlugin(options) {
|
|
|
703
706
|
}
|
|
704
707
|
|
|
705
708
|
//#endregion
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
exports.
|
|
717
|
-
exports.
|
|
709
|
+
//#region src/index.ts
|
|
710
|
+
/**
|
|
711
|
+
* @deprecated use named export instead
|
|
712
|
+
*/
|
|
713
|
+
function mockDevServerPluginWithDefaultExportWasDeprecated(options = {}) {
|
|
714
|
+
console.warn(`${picocolors.default.yellow("[vite-plugin-mock-dev-server]")} ${picocolors.default.yellow(picocolors.default.bold("WARNING:"))} The plugin default export is ${picocolors.default.bold("deprecated")}, it will be removed in next major version, use ${picocolors.default.bold("named export")} instead:\n\n ${picocolors.default.green("import { mockDevServerPlugin } from \"vite-plugin-mock-dev-server\"")}\n`);
|
|
715
|
+
return mockDevServerPlugin(options);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
//#endregion
|
|
719
|
+
exports.baseMiddleware = require_server.baseMiddleware;
|
|
720
|
+
exports.createDefineMock = require_helper.createDefineMock;
|
|
721
|
+
exports.createLogger = require_server.createLogger;
|
|
722
|
+
exports.createSSEStream = require_helper.createSSEStream;
|
|
723
|
+
exports.default = mockDevServerPluginWithDefaultExportWasDeprecated;
|
|
724
|
+
exports.defineMock = require_helper.defineMock;
|
|
725
|
+
exports.defineMockData = require_helper.defineMockData;
|
|
726
|
+
exports.logLevels = require_server.logLevels;
|
|
727
|
+
exports.mockDevServerPlugin = mockDevServerPlugin;
|
|
728
|
+
exports.mockWebSocket = require_server.mockWebSocket;
|
|
729
|
+
exports.sortByValidator = require_server.sortByValidator;
|
|
730
|
+
exports.transformMockData = require_server.transformMockData;
|
|
731
|
+
exports.transformRawData = require_server.transformRawData;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { FormidableFile, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem } from "./types-
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-
|
|
3
|
-
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-
|
|
1
|
+
import { FormidableFile, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem } from "./types-DpbHkRjL.cjs";
|
|
2
|
+
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-iVHsUTZ6.cjs";
|
|
3
|
+
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-B5Ua2cmP.cjs";
|
|
4
4
|
import { Plugin } from "vite";
|
|
5
5
|
|
|
6
6
|
//#region src/plugin.d.ts
|
|
7
7
|
declare function mockDevServerPlugin(options?: MockServerPluginOptions): Plugin[];
|
|
8
|
-
|
|
9
8
|
//#endregion
|
|
10
|
-
|
|
9
|
+
//#region src/index.d.ts
|
|
10
|
+
/**
|
|
11
|
+
* @deprecated use named export instead
|
|
12
|
+
*/
|
|
13
|
+
declare function mockDevServerPluginWithDefaultExportWasDeprecated(options?: MockServerPluginOptions): Plugin[];
|
|
14
|
+
//#endregion
|
|
15
|
+
export { BaseMiddlewareOptions, FormidableFile, HeaderStream, Logger, MockData, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem, SSEMessage, baseMiddleware, createDefineMock, createLogger, createSSEStream, mockDevServerPluginWithDefaultExportWasDeprecated as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { FormidableFile, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem } from "./types-
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock
|
|
3
|
-
import { BaseMiddlewareOptions, Logger, baseMiddleware
|
|
1
|
+
import { FormidableFile, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem } from "./types-D2dm9iaM.js";
|
|
2
|
+
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-ssk6rMi5.js";
|
|
3
|
+
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-XauDEVqY.js";
|
|
4
4
|
import { Plugin } from "vite";
|
|
5
5
|
|
|
6
6
|
//#region src/plugin.d.ts
|
|
7
7
|
declare function mockDevServerPlugin(options?: MockServerPluginOptions): Plugin[];
|
|
8
|
-
|
|
9
8
|
//#endregion
|
|
10
|
-
|
|
9
|
+
//#region src/index.d.ts
|
|
10
|
+
/**
|
|
11
|
+
* @deprecated use named export instead
|
|
12
|
+
*/
|
|
13
|
+
declare function mockDevServerPluginWithDefaultExportWasDeprecated(options?: MockServerPluginOptions): Plugin[];
|
|
14
|
+
//#endregion
|
|
15
|
+
export { BaseMiddlewareOptions, FormidableFile, HeaderStream, Logger, MockData, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem, SSEMessage, baseMiddleware, createDefineMock, createLogger, createSSEStream, mockDevServerPluginWithDefaultExportWasDeprecated as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-
|
|
2
|
-
import { baseMiddleware, createLogger, debug, doesProxyContextMatchUrl, ensureProxies, logLevels, lookupFile, mockWebSocket, normalizePath, recoverRequest, sortByValidator, transformMockData, transformRawData, urlParse } from "./server-
|
|
1
|
+
import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-XBACG61a.js";
|
|
2
|
+
import { baseMiddleware, createLogger, debug, doesProxyContextMatchUrl, ensureProxies, logLevels, lookupFile, mockWebSocket, normalizePath, recoverRequest, sortByValidator, transformMockData, transformRawData, urlParse } from "./server-Dr9FAgt4.js";
|
|
3
3
|
import { isArray, isBoolean, promiseParallel, toArray, uniq } from "@pengzhanbo/utils";
|
|
4
|
+
import pc from "picocolors";
|
|
4
5
|
import fs, { promises } from "node:fs";
|
|
5
6
|
import fsp from "node:fs/promises";
|
|
6
7
|
import path from "node:path";
|
|
@@ -8,7 +9,6 @@ import process from "node:process";
|
|
|
8
9
|
import { createFilter } from "@rollup/pluginutils";
|
|
9
10
|
import fg from "fast-glob";
|
|
10
11
|
import isCore from "is-core-module";
|
|
11
|
-
import colors from "picocolors";
|
|
12
12
|
import { pathToFileURL } from "node:url";
|
|
13
13
|
import { build } from "esbuild";
|
|
14
14
|
import JSON5 from "json5";
|
|
@@ -182,14 +182,14 @@ async function generateMockServer(ctx, options) {
|
|
|
182
182
|
try {
|
|
183
183
|
if (path.isAbsolute(outputDir)) {
|
|
184
184
|
for (const { filename } of outputList) if (fs.existsSync(filename)) await fsp.rm(filename);
|
|
185
|
-
options.logger.info(`${
|
|
185
|
+
options.logger.info(`${pc.green("✓")} generate mock server in ${pc.cyan(outputDir)}`);
|
|
186
186
|
for (const { filename, source } of outputList) {
|
|
187
187
|
fs.mkdirSync(path.dirname(filename), { recursive: true });
|
|
188
188
|
await fsp.writeFile(filename, source, "utf-8");
|
|
189
189
|
const sourceSize = (source.length / 1024).toFixed(2);
|
|
190
190
|
const name = path.relative(outputDir, filename);
|
|
191
191
|
const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
|
|
192
|
-
options.logger.info(` ${
|
|
192
|
+
options.logger.info(` ${pc.green(name)}${space}${pc.bold(pc.dim(`${sourceSize} kB`))}`);
|
|
193
193
|
}
|
|
194
194
|
} else for (const { filename, source } of outputList) ctx.emitFile({
|
|
195
195
|
type: "asset",
|
|
@@ -201,9 +201,9 @@ async function generateMockServer(ctx, options) {
|
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
203
|
function getMockDependencies(deps, alias) {
|
|
204
|
-
const list = new Set();
|
|
204
|
+
const list = /* @__PURE__ */ new Set();
|
|
205
205
|
const excludeDeps = [
|
|
206
|
-
|
|
206
|
+
__PACKAGE_NAME__,
|
|
207
207
|
"connect",
|
|
208
208
|
"cors"
|
|
209
209
|
];
|
|
@@ -234,7 +234,7 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
234
234
|
scripts: { start: "node index.js" },
|
|
235
235
|
dependencies: {
|
|
236
236
|
connect: "^3.7.0",
|
|
237
|
-
[
|
|
237
|
+
[__PACKAGE_NAME__]: `^${__PACKAGE_VERSION__}`,
|
|
238
238
|
cors: "^2.8.5"
|
|
239
239
|
},
|
|
240
240
|
pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
|
|
@@ -309,8 +309,11 @@ function createMockCompiler(options) {
|
|
|
309
309
|
* mock配置加载器
|
|
310
310
|
*/
|
|
311
311
|
var MockCompiler = class extends EventEmitter {
|
|
312
|
-
moduleCache = new Map();
|
|
313
|
-
moduleDeps = new Map();
|
|
312
|
+
moduleCache = /* @__PURE__ */ new Map();
|
|
313
|
+
moduleDeps = /* @__PURE__ */ new Map();
|
|
314
|
+
cwd;
|
|
315
|
+
mockWatcher;
|
|
316
|
+
depsWatcher;
|
|
314
317
|
moduleType = "cjs";
|
|
315
318
|
_mockData = {};
|
|
316
319
|
constructor(options) {
|
|
@@ -416,7 +419,7 @@ var MockCompiler = class extends EventEmitter {
|
|
|
416
419
|
Object.keys(deps).forEach((mPath) => {
|
|
417
420
|
const imports = deps[mPath].imports.map((_) => _.path);
|
|
418
421
|
imports.forEach((dep) => {
|
|
419
|
-
if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, new Set());
|
|
422
|
+
if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
|
|
420
423
|
const cur = this.moduleDeps.get(dep);
|
|
421
424
|
cur.add(filepath);
|
|
422
425
|
});
|
|
@@ -493,7 +496,7 @@ function mockServerMiddleware(options, server, ws) {
|
|
|
493
496
|
*/
|
|
494
497
|
corsMiddleware(compiler, options),
|
|
495
498
|
baseMiddleware(compiler, options)
|
|
496
|
-
);
|
|
499
|
+
);
|
|
497
500
|
return middlewares.filter(Boolean);
|
|
498
501
|
}
|
|
499
502
|
function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
|
|
@@ -595,7 +598,7 @@ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["moc
|
|
|
595
598
|
const { httpProxies } = ensureProxies(config.server.proxy || {});
|
|
596
599
|
const proxies = uniq([...toArray(prefix), ...httpProxies]);
|
|
597
600
|
const wsProxies = toArray(wsPrefix);
|
|
598
|
-
if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${
|
|
601
|
+
if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${pc.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
|
|
599
602
|
const enabled = cors$1 === false ? false : config.server.cors !== false;
|
|
600
603
|
let corsOptions = {};
|
|
601
604
|
if (enabled && config.server.cors !== false) corsOptions = {
|
|
@@ -701,4 +704,14 @@ function serverPlugin(options) {
|
|
|
701
704
|
}
|
|
702
705
|
|
|
703
706
|
//#endregion
|
|
704
|
-
|
|
707
|
+
//#region src/index.ts
|
|
708
|
+
/**
|
|
709
|
+
* @deprecated use named export instead
|
|
710
|
+
*/
|
|
711
|
+
function mockDevServerPluginWithDefaultExportWasDeprecated(options = {}) {
|
|
712
|
+
console.warn(`${pc.yellow("[vite-plugin-mock-dev-server]")} ${pc.yellow(pc.bold("WARNING:"))} The plugin default export is ${pc.bold("deprecated")}, it will be removed in next major version, use ${pc.bold("named export")} instead:\n\n ${pc.green("import { mockDevServerPlugin } from \"vite-plugin-mock-dev-server\"")}\n`);
|
|
713
|
+
return mockDevServerPlugin(options);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
//#endregion
|
|
717
|
+
export { baseMiddleware, createDefineMock, createLogger, createSSEStream, mockDevServerPluginWithDefaultExportWasDeprecated as default, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LogLevel, MockHttpItem, MockOptions, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption } from "./types-
|
|
1
|
+
import { LogLevel, MockHttpItem, MockOptions, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption } from "./types-DpbHkRjL.cjs";
|
|
2
2
|
import { CorsOptions } from "cors";
|
|
3
3
|
import { Server } from "node:http";
|
|
4
4
|
import { Alias, Connect } from "vite";
|
|
@@ -15,7 +15,6 @@ interface Logger {
|
|
|
15
15
|
}
|
|
16
16
|
declare const logLevels: Record<LogLevel, number>;
|
|
17
17
|
declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
|
|
18
|
-
|
|
19
18
|
//#endregion
|
|
20
19
|
//#region src/core/resolvePluginOptions.d.ts
|
|
21
20
|
type ResolvedMockServerPluginOptions = Required<Omit<MockServerPluginOptions, "build" | "cors" | "wsPrefix" | "prefix">> & {
|
|
@@ -28,7 +27,6 @@ type ResolvedMockServerPluginOptions = Required<Omit<MockServerPluginOptions, "b
|
|
|
28
27
|
build: false | ServerBuildOption;
|
|
29
28
|
cors: false | CorsOptions;
|
|
30
29
|
};
|
|
31
|
-
|
|
32
30
|
//#endregion
|
|
33
31
|
//#region src/core/mockCompiler.d.ts
|
|
34
32
|
/**
|
|
@@ -57,7 +55,6 @@ declare class MockCompiler extends EventEmitter {
|
|
|
57
55
|
private updateModuleDeps;
|
|
58
56
|
private loadMock;
|
|
59
57
|
}
|
|
60
|
-
|
|
61
58
|
//#endregion
|
|
62
59
|
//#region src/core/baseMiddleware.d.ts
|
|
63
60
|
interface BaseMiddlewareOptions {
|
|
@@ -76,14 +73,12 @@ declare function baseMiddleware(compiler: MockCompiler, {
|
|
|
76
73
|
logger,
|
|
77
74
|
priority
|
|
78
75
|
}: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
79
|
-
|
|
80
76
|
//#endregion
|
|
81
77
|
//#region src/core/transform.d.ts
|
|
82
78
|
type MockRawData = MockOptions | MockHttpItem | MockWebsocketItem | Record<string, MockOptions | MockHttpItem | MockWebsocketItem>;
|
|
83
79
|
declare function transformRawData(raw: MockRawData, __filepath__: string): MockOptions | MockHttpItem | MockWebsocketItem;
|
|
84
80
|
declare function transformMockData(mockList: Map<string, MockHttpItem | MockWebsocketItem | MockOptions> | (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
|
|
85
81
|
declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
|
|
86
|
-
|
|
87
82
|
//#endregion
|
|
88
83
|
//#region src/core/ws.d.ts
|
|
89
84
|
/**
|
|
@@ -94,6 +89,5 @@ declare function mockWebSocket(compiler: MockCompiler, server: Server | Http2Sec
|
|
|
94
89
|
cookiesOptions,
|
|
95
90
|
logger
|
|
96
91
|
}: ResolvedMockServerPluginOptions): void;
|
|
97
|
-
|
|
98
92
|
//#endregion
|
|
99
93
|
export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
const require_chunk = require('./chunk-BCwAaXi7.cjs');
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
3
2
|
const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
|
|
3
|
+
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
4
4
|
const node_fs = require_chunk.__toESM(require("node:fs"));
|
|
5
5
|
const node_path = require_chunk.__toESM(require("node:path"));
|
|
6
|
-
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
7
6
|
const node_url = require_chunk.__toESM(require("node:url"));
|
|
8
7
|
const node_os = require_chunk.__toESM(require("node:os"));
|
|
9
8
|
const node_querystring = require_chunk.__toESM(require("node:querystring"));
|
|
@@ -186,6 +185,12 @@ function twoPartMatch(rules) {
|
|
|
186
185
|
|
|
187
186
|
//#endregion
|
|
188
187
|
//#region src/core/parseReqBody.ts
|
|
188
|
+
const DEFAULT_FORMIDABLE_OPTIONS = {
|
|
189
|
+
keepExtensions: true,
|
|
190
|
+
filename(name, ext, part) {
|
|
191
|
+
return part?.originalFilename || `${name}.${Date.now()}${ext ? `.${ext}` : ""}`;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
189
194
|
async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
190
195
|
const method = req.method.toUpperCase();
|
|
191
196
|
if (["HEAD", "OPTIONS"].includes(method)) return void 0;
|
|
@@ -211,7 +216,10 @@ async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
|
211
216
|
return void 0;
|
|
212
217
|
}
|
|
213
218
|
async function parseMultipart(req, options) {
|
|
214
|
-
const form = (0, formidable.default)(
|
|
219
|
+
const form = (0, formidable.default)({
|
|
220
|
+
...DEFAULT_FORMIDABLE_OPTIONS,
|
|
221
|
+
...options
|
|
222
|
+
});
|
|
215
223
|
return new Promise((resolve, reject) => {
|
|
216
224
|
form.parse(req, (error, fields, files) => {
|
|
217
225
|
if (error) {
|
|
@@ -228,7 +236,7 @@ async function parseMultipart(req, options) {
|
|
|
228
236
|
|
|
229
237
|
//#endregion
|
|
230
238
|
//#region src/core/requestRecovery.ts
|
|
231
|
-
const cache = new WeakMap();
|
|
239
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
232
240
|
function collectRequest(req) {
|
|
233
241
|
const chunks = [];
|
|
234
242
|
req.addListener("data", (chunk) => {
|
|
@@ -290,7 +298,7 @@ function isObjectSubset(source, target) {
|
|
|
290
298
|
}
|
|
291
299
|
function isIncluded(source, target) {
|
|
292
300
|
if ((0, __pengzhanbo_utils.isArray)(source) && (0, __pengzhanbo_utils.isArray)(target)) {
|
|
293
|
-
const seen = new Set();
|
|
301
|
+
const seen = /* @__PURE__ */ new Set();
|
|
294
302
|
return target.every((ti) => source.some((si, i) => {
|
|
295
303
|
if (seen.has(i)) return false;
|
|
296
304
|
const included = isIncluded(si, ti);
|
|
@@ -562,12 +570,12 @@ function keysCount(obj) {
|
|
|
562
570
|
* mock websocket
|
|
563
571
|
*/
|
|
564
572
|
function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, logger }) {
|
|
565
|
-
const hmrMap = new Map();
|
|
566
|
-
const poolMap = new Map();
|
|
567
|
-
const wssContextMap = new WeakMap();
|
|
573
|
+
const hmrMap = /* @__PURE__ */ new Map();
|
|
574
|
+
const poolMap = /* @__PURE__ */ new Map();
|
|
575
|
+
const wssContextMap = /* @__PURE__ */ new WeakMap();
|
|
568
576
|
const getWssMap = (mockUrl) => {
|
|
569
577
|
let wssMap = poolMap.get(mockUrl);
|
|
570
|
-
if (!wssMap) poolMap.set(mockUrl, wssMap = new Map());
|
|
578
|
+
if (!wssMap) poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
|
|
571
579
|
return wssMap;
|
|
572
580
|
};
|
|
573
581
|
const getWss = (wssMap, pathname) => {
|
|
@@ -577,7 +585,7 @@ function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, l
|
|
|
577
585
|
};
|
|
578
586
|
const addHmr = (filepath, mockUrl) => {
|
|
579
587
|
let urlList = hmrMap.get(filepath);
|
|
580
|
-
if (!urlList) hmrMap.set(filepath, urlList = new Set());
|
|
588
|
+
if (!urlList) hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
|
|
581
589
|
urlList.add(mockUrl);
|
|
582
590
|
};
|
|
583
591
|
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
|
|
@@ -695,7 +703,7 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
695
703
|
if (thresh >= logLevels[type]) {
|
|
696
704
|
const method = type === "info" || type === "debug" ? "log" : type;
|
|
697
705
|
const tag = type === "debug" ? picocolors.default.magenta(picocolors.default.bold(prefix)) : type === "info" ? picocolors.default.cyan(picocolors.default.bold(prefix)) : type === "warn" ? picocolors.default.yellow(picocolors.default.bold(prefix)) : picocolors.default.red(picocolors.default.bold(prefix));
|
|
698
|
-
const format = `${picocolors.default.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`;
|
|
706
|
+
const format = `${picocolors.default.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
|
|
699
707
|
console[method](format);
|
|
700
708
|
}
|
|
701
709
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isArray, isBoolean, isEmptyObject, isFunction, isPlainObject, isString, random, sleep, sortBy, timestamp, toArray, uniq } from "@pengzhanbo/utils";
|
|
2
|
+
import pc from "picocolors";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
4
|
-
import colors from "picocolors";
|
|
5
5
|
import { URL as URL$1 } from "node:url";
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import { parse } from "node:querystring";
|
|
@@ -184,6 +184,12 @@ function twoPartMatch(rules) {
|
|
|
184
184
|
|
|
185
185
|
//#endregion
|
|
186
186
|
//#region src/core/parseReqBody.ts
|
|
187
|
+
const DEFAULT_FORMIDABLE_OPTIONS = {
|
|
188
|
+
keepExtensions: true,
|
|
189
|
+
filename(name, ext, part) {
|
|
190
|
+
return part?.originalFilename || `${name}.${Date.now()}${ext ? `.${ext}` : ""}`;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
187
193
|
async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
188
194
|
const method = req.method.toUpperCase();
|
|
189
195
|
if (["HEAD", "OPTIONS"].includes(method)) return void 0;
|
|
@@ -209,7 +215,10 @@ async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
|
209
215
|
return void 0;
|
|
210
216
|
}
|
|
211
217
|
async function parseMultipart(req, options) {
|
|
212
|
-
const form = formidable(
|
|
218
|
+
const form = formidable({
|
|
219
|
+
...DEFAULT_FORMIDABLE_OPTIONS,
|
|
220
|
+
...options
|
|
221
|
+
});
|
|
213
222
|
return new Promise((resolve, reject) => {
|
|
214
223
|
form.parse(req, (error, fields, files) => {
|
|
215
224
|
if (error) {
|
|
@@ -226,7 +235,7 @@ async function parseMultipart(req, options) {
|
|
|
226
235
|
|
|
227
236
|
//#endregion
|
|
228
237
|
//#region src/core/requestRecovery.ts
|
|
229
|
-
const cache = new WeakMap();
|
|
238
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
230
239
|
function collectRequest(req) {
|
|
231
240
|
const chunks = [];
|
|
232
241
|
req.addListener("data", (chunk) => {
|
|
@@ -288,7 +297,7 @@ function isObjectSubset(source, target) {
|
|
|
288
297
|
}
|
|
289
298
|
function isIncluded(source, target) {
|
|
290
299
|
if (isArray(source) && isArray(target)) {
|
|
291
|
-
const seen = new Set();
|
|
300
|
+
const seen = /* @__PURE__ */ new Set();
|
|
292
301
|
return target.every((ti) => source.some((si, i) => {
|
|
293
302
|
if (seen.has(i)) return false;
|
|
294
303
|
const included = isIncluded(si, ti);
|
|
@@ -336,8 +345,8 @@ function baseMiddleware(compiler, { formidableOptions = {}, bodyParserOptions =
|
|
|
336
345
|
}
|
|
337
346
|
}
|
|
338
347
|
if (!mock) {
|
|
339
|
-
const matched = mockUrls.map((m) => m === _mockUrl ?
|
|
340
|
-
logger.warn(`${
|
|
348
|
+
const matched = mockUrls.map((m) => m === _mockUrl ? pc.underline(pc.bold(m)) : pc.dim(m)).join(", ");
|
|
349
|
+
logger.warn(`${pc.green(pathname)} matches ${matched} , but mock data is not found.`);
|
|
341
350
|
return next();
|
|
342
351
|
}
|
|
343
352
|
const request = req;
|
|
@@ -353,14 +362,14 @@ function baseMiddleware(compiler, { formidableOptions = {}, bodyParserOptions =
|
|
|
353
362
|
await provideHeaders(request, response, mock, logger);
|
|
354
363
|
await provideCookies(request, response, mock, logger);
|
|
355
364
|
logger.info(requestLog(request, filepath), logLevel);
|
|
356
|
-
logger.debug(`${
|
|
365
|
+
logger.debug(`${pc.magenta("DEBUG")} ${pc.underline(pathname)} matches: [ ${mockUrls.map((m) => m === _mockUrl ? pc.underline(pc.bold(m)) : pc.dim(m)).join(", ")} ]\n`);
|
|
357
366
|
if (body) {
|
|
358
367
|
try {
|
|
359
368
|
const content = isFunction(body) ? await body(request) : body;
|
|
360
369
|
await realDelay(startTime, delay);
|
|
361
370
|
sendData(response, content, type);
|
|
362
371
|
} catch (e) {
|
|
363
|
-
logger.error(`${
|
|
372
|
+
logger.error(`${pc.red(`mock error at ${pathname}`)}\n${e}\n at body (${pc.underline(filepath)})`, logLevel);
|
|
364
373
|
responseStatus(response, 500);
|
|
365
374
|
res.end("");
|
|
366
375
|
}
|
|
@@ -371,7 +380,7 @@ function baseMiddleware(compiler, { formidableOptions = {}, bodyParserOptions =
|
|
|
371
380
|
await realDelay(startTime, delay);
|
|
372
381
|
await responseFn(request, response, next);
|
|
373
382
|
} catch (e) {
|
|
374
|
-
logger.error(`${
|
|
383
|
+
logger.error(`${pc.red(`mock error at ${pathname}`)}\n${e}\n at response (${pc.underline(filepath)})`, logLevel);
|
|
375
384
|
responseStatus(response, 500);
|
|
376
385
|
res.end("");
|
|
377
386
|
}
|
|
@@ -399,7 +408,7 @@ function fineMock(mockList, logger, { pathname, method, request }) {
|
|
|
399
408
|
}, mock.validator);
|
|
400
409
|
} catch (e) {
|
|
401
410
|
const file = mock.__filepath__;
|
|
402
|
-
logger.error(`${
|
|
411
|
+
logger.error(`${pc.red(`mock error at ${pathname}`)}\n${e}\n at validator (${pc.underline(file)})`, mock.log);
|
|
403
412
|
return false;
|
|
404
413
|
}
|
|
405
414
|
}
|
|
@@ -425,7 +434,7 @@ async function provideHeaders(req, res, mock, logger) {
|
|
|
425
434
|
res.setHeader(key, raw[key]);
|
|
426
435
|
});
|
|
427
436
|
} catch (e) {
|
|
428
|
-
logger.error(`${
|
|
437
|
+
logger.error(`${pc.red(`mock error at ${req.url.split("?")[0]}`)}\n${e}\n at headers (${pc.underline(filepath)})`, mock.log);
|
|
429
438
|
}
|
|
430
439
|
}
|
|
431
440
|
async function provideCookies(req, res, mock, logger) {
|
|
@@ -442,7 +451,7 @@ async function provideCookies(req, res, mock, logger) {
|
|
|
442
451
|
} else res.setCookie(key, cookie);
|
|
443
452
|
});
|
|
444
453
|
} catch (e) {
|
|
445
|
-
logger.error(`${
|
|
454
|
+
logger.error(`${pc.red(`mock error at ${req.url.split("?")[0]}`)}\n${e}\n at cookies (${pc.underline(filepath)})`, mock.log);
|
|
446
455
|
}
|
|
447
456
|
}
|
|
448
457
|
function sendData(res, raw, type) {
|
|
@@ -468,15 +477,15 @@ function getHTTPStatusText(status) {
|
|
|
468
477
|
function requestLog(request, filepath) {
|
|
469
478
|
const { url, method, query, params, body } = request;
|
|
470
479
|
let { pathname } = new URL(url, "http://example.com");
|
|
471
|
-
pathname =
|
|
480
|
+
pathname = pc.green(decodeURIComponent(pathname));
|
|
472
481
|
const format = (prefix, data) => {
|
|
473
|
-
return !data || isEmptyObject(data) ? "" : ` ${
|
|
482
|
+
return !data || isEmptyObject(data) ? "" : ` ${pc.gray(`${prefix}:`)}${JSON.stringify(data)}`;
|
|
474
483
|
};
|
|
475
|
-
const ms =
|
|
484
|
+
const ms = pc.magenta(pc.bold(method));
|
|
476
485
|
const qs = format("query", query);
|
|
477
486
|
const ps = format("params", params);
|
|
478
487
|
const bs = format("body", body);
|
|
479
|
-
const file = ` ${
|
|
488
|
+
const file = ` ${pc.dim(pc.underline(`(${filepath})`))}`;
|
|
480
489
|
return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
|
|
481
490
|
}
|
|
482
491
|
|
|
@@ -560,12 +569,12 @@ function keysCount(obj) {
|
|
|
560
569
|
* mock websocket
|
|
561
570
|
*/
|
|
562
571
|
function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, logger }) {
|
|
563
|
-
const hmrMap = new Map();
|
|
564
|
-
const poolMap = new Map();
|
|
565
|
-
const wssContextMap = new WeakMap();
|
|
572
|
+
const hmrMap = /* @__PURE__ */ new Map();
|
|
573
|
+
const poolMap = /* @__PURE__ */ new Map();
|
|
574
|
+
const wssContextMap = /* @__PURE__ */ new WeakMap();
|
|
566
575
|
const getWssMap = (mockUrl) => {
|
|
567
576
|
let wssMap = poolMap.get(mockUrl);
|
|
568
|
-
if (!wssMap) poolMap.set(mockUrl, wssMap = new Map());
|
|
577
|
+
if (!wssMap) poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
|
|
569
578
|
return wssMap;
|
|
570
579
|
};
|
|
571
580
|
const getWss = (wssMap, pathname) => {
|
|
@@ -575,7 +584,7 @@ function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, l
|
|
|
575
584
|
};
|
|
576
585
|
const addHmr = (filepath, mockUrl) => {
|
|
577
586
|
let urlList = hmrMap.get(filepath);
|
|
578
|
-
if (!urlList) hmrMap.set(filepath, urlList = new Set());
|
|
587
|
+
if (!urlList) hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
|
|
579
588
|
urlList.add(mockUrl);
|
|
580
589
|
};
|
|
581
590
|
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
|
|
@@ -583,10 +592,10 @@ function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, l
|
|
|
583
592
|
mock.setup?.(wss, context);
|
|
584
593
|
wss.on("close", () => wssMap.delete(pathname));
|
|
585
594
|
wss.on("error", (e) => {
|
|
586
|
-
logger.error(`${
|
|
595
|
+
logger.error(`${pc.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
|
|
587
596
|
});
|
|
588
597
|
} catch (e) {
|
|
589
|
-
logger.error(`${
|
|
598
|
+
logger.error(`${pc.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
|
|
590
599
|
}
|
|
591
600
|
};
|
|
592
601
|
const emitConnection = (wss, ws, req, connectionList) => {
|
|
@@ -650,7 +659,7 @@ function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, l
|
|
|
650
659
|
request.params = parseParams(mockUrl, pathname);
|
|
651
660
|
request.getCookie = cookies.get.bind(cookies);
|
|
652
661
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
653
|
-
logger.info(`${
|
|
662
|
+
logger.info(`${pc.magenta(pc.bold("WebSocket"))} ${pc.green(req.url)} connected ${pc.dim(`(${filepath})`)}`, mock.log);
|
|
654
663
|
wssContext.connectionList.push({
|
|
655
664
|
req: request,
|
|
656
665
|
ws
|
|
@@ -692,8 +701,8 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
692
701
|
const thresh = logLevels[level];
|
|
693
702
|
if (thresh >= logLevels[type]) {
|
|
694
703
|
const method = type === "info" || type === "debug" ? "log" : type;
|
|
695
|
-
const tag = type === "debug" ?
|
|
696
|
-
const format = `${
|
|
704
|
+
const tag = type === "debug" ? pc.magenta(pc.bold(prefix)) : type === "info" ? pc.cyan(pc.bold(prefix)) : type === "warn" ? pc.yellow(pc.bold(prefix)) : pc.red(pc.bold(prefix));
|
|
705
|
+
const format = `${pc.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
|
|
697
706
|
console[method](format);
|
|
698
707
|
}
|
|
699
708
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LogLevel, MockHttpItem, MockOptions, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption } from "./types-
|
|
1
|
+
import { LogLevel, MockHttpItem, MockOptions, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption } from "./types-D2dm9iaM.js";
|
|
2
2
|
import { CorsOptions } from "cors";
|
|
3
3
|
import EventEmitter from "node:events";
|
|
4
4
|
import { FSWatcher } from "chokidar";
|
|
@@ -15,7 +15,6 @@ interface Logger {
|
|
|
15
15
|
}
|
|
16
16
|
declare const logLevels: Record<LogLevel, number>;
|
|
17
17
|
declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
|
|
18
|
-
|
|
19
18
|
//#endregion
|
|
20
19
|
//#region src/core/resolvePluginOptions.d.ts
|
|
21
20
|
type ResolvedMockServerPluginOptions = Required<Omit<MockServerPluginOptions, "build" | "cors" | "wsPrefix" | "prefix">> & {
|
|
@@ -28,7 +27,6 @@ type ResolvedMockServerPluginOptions = Required<Omit<MockServerPluginOptions, "b
|
|
|
28
27
|
build: false | ServerBuildOption;
|
|
29
28
|
cors: false | CorsOptions;
|
|
30
29
|
};
|
|
31
|
-
|
|
32
30
|
//#endregion
|
|
33
31
|
//#region src/core/mockCompiler.d.ts
|
|
34
32
|
/**
|
|
@@ -57,7 +55,6 @@ declare class MockCompiler extends EventEmitter {
|
|
|
57
55
|
private updateModuleDeps;
|
|
58
56
|
private loadMock;
|
|
59
57
|
}
|
|
60
|
-
|
|
61
58
|
//#endregion
|
|
62
59
|
//#region src/core/baseMiddleware.d.ts
|
|
63
60
|
interface BaseMiddlewareOptions {
|
|
@@ -76,14 +73,12 @@ declare function baseMiddleware(compiler: MockCompiler, {
|
|
|
76
73
|
logger,
|
|
77
74
|
priority
|
|
78
75
|
}: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
79
|
-
|
|
80
76
|
//#endregion
|
|
81
77
|
//#region src/core/transform.d.ts
|
|
82
78
|
type MockRawData = MockOptions | MockHttpItem | MockWebsocketItem | Record<string, MockOptions | MockHttpItem | MockWebsocketItem>;
|
|
83
79
|
declare function transformRawData(raw: MockRawData, __filepath__: string): MockOptions | MockHttpItem | MockWebsocketItem;
|
|
84
80
|
declare function transformMockData(mockList: Map<string, MockHttpItem | MockWebsocketItem | MockOptions> | (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
|
|
85
81
|
declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
|
|
86
|
-
|
|
87
82
|
//#endregion
|
|
88
83
|
//#region src/core/ws.d.ts
|
|
89
84
|
/**
|
|
@@ -94,6 +89,5 @@ declare function mockWebSocket(compiler: MockCompiler, server: Server | Http2Sec
|
|
|
94
89
|
cookiesOptions,
|
|
95
90
|
logger
|
|
96
91
|
}: ResolvedMockServerPluginOptions): void;
|
|
97
|
-
|
|
98
92
|
//#endregion
|
|
99
|
-
export { BaseMiddlewareOptions, Logger, baseMiddleware
|
|
93
|
+
export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
package/dist/server.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const require_server = require('./server-
|
|
1
|
+
const require_server = require('./server-CZwOQzgC.cjs');
|
|
2
2
|
|
|
3
|
-
exports.baseMiddleware = require_server.baseMiddleware
|
|
4
|
-
exports.createLogger = require_server.createLogger
|
|
5
|
-
exports.logLevels = require_server.logLevels
|
|
6
|
-
exports.mockWebSocket = require_server.mockWebSocket
|
|
7
|
-
exports.sortByValidator = require_server.sortByValidator
|
|
8
|
-
exports.transformMockData = require_server.transformMockData
|
|
9
|
-
exports.transformRawData = require_server.transformRawData
|
|
3
|
+
exports.baseMiddleware = require_server.baseMiddleware;
|
|
4
|
+
exports.createLogger = require_server.createLogger;
|
|
5
|
+
exports.logLevels = require_server.logLevels;
|
|
6
|
+
exports.mockWebSocket = require_server.mockWebSocket;
|
|
7
|
+
exports.sortByValidator = require_server.sortByValidator;
|
|
8
|
+
exports.transformMockData = require_server.transformMockData;
|
|
9
|
+
exports.transformRawData = require_server.transformRawData;
|
package/dist/server.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import "./types-
|
|
2
|
-
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-
|
|
1
|
+
import "./types-DpbHkRjL.cjs";
|
|
2
|
+
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-B5Ua2cmP.cjs";
|
|
3
3
|
export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
package/dist/server.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import "./types-
|
|
2
|
-
import { BaseMiddlewareOptions, Logger, baseMiddleware
|
|
1
|
+
import "./types-D2dm9iaM.js";
|
|
2
|
+
import { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-XauDEVqY.js";
|
|
3
3
|
export { BaseMiddlewareOptions, Logger, baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
package/dist/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-
|
|
1
|
+
import { baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData } from "./server-Dr9FAgt4.js";
|
|
2
2
|
|
|
3
3
|
export { baseMiddleware, createLogger, logLevels, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import Cookies from "cookies";
|
|
1
|
+
import { Readable } from "node:stream";
|
|
3
2
|
import { CorsOptions } from "cors";
|
|
4
|
-
import formidable from "formidable";
|
|
5
3
|
import { Buffer } from "node:buffer";
|
|
4
|
+
import Cookies from "cookies";
|
|
5
|
+
import { Options } from "co-body";
|
|
6
|
+
import formidable from "formidable";
|
|
7
|
+
import { WebSocketServer } from "ws";
|
|
6
8
|
import http from "node:http";
|
|
7
|
-
import { Readable } from "node:stream";
|
|
8
9
|
import { Connect } from "vite";
|
|
9
|
-
import { WebSocketServer } from "ws";
|
|
10
10
|
|
|
11
11
|
//#region src/types.d.ts
|
|
12
|
-
|
|
13
|
-
* Configure plugin
|
|
14
|
-
*
|
|
15
|
-
* 插件配置项
|
|
16
|
-
*/
|
|
12
|
+
|
|
17
13
|
/**
|
|
18
14
|
* Configure plugin
|
|
19
15
|
*
|
|
@@ -572,5 +568,6 @@ interface WebSocketSetupContext {
|
|
|
572
568
|
type MockOptions = (MockHttpItem | MockWebsocketItem)[];
|
|
573
569
|
type FormidableFile = formidable.File | formidable.File[];
|
|
574
570
|
type LogType = "info" | "warn" | "error" | "debug";
|
|
575
|
-
type LogLevel = LogType | "silent";
|
|
571
|
+
type LogLevel = LogType | "silent";
|
|
572
|
+
//#endregion
|
|
576
573
|
export { FormidableFile, LogLevel, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption };
|
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import { Readable } from "node:stream";
|
|
2
|
-
import { CorsOptions } from "cors";
|
|
3
|
-
import { Buffer } from "node:buffer";
|
|
4
|
-
import Cookies from "cookies";
|
|
5
1
|
import { Options } from "co-body";
|
|
2
|
+
import Cookies from "cookies";
|
|
3
|
+
import { CorsOptions } from "cors";
|
|
6
4
|
import formidable from "formidable";
|
|
7
|
-
import {
|
|
5
|
+
import { Buffer } from "node:buffer";
|
|
8
6
|
import http from "node:http";
|
|
7
|
+
import { Readable } from "node:stream";
|
|
9
8
|
import { Connect } from "vite";
|
|
9
|
+
import { WebSocketServer } from "ws";
|
|
10
10
|
|
|
11
11
|
//#region src/types.d.ts
|
|
12
|
-
|
|
13
|
-
* Configure plugin
|
|
14
|
-
*
|
|
15
|
-
* 插件配置项
|
|
16
|
-
*/
|
|
12
|
+
|
|
17
13
|
/**
|
|
18
14
|
* Configure plugin
|
|
19
15
|
*
|
|
@@ -572,5 +568,6 @@ interface WebSocketSetupContext {
|
|
|
572
568
|
type MockOptions = (MockHttpItem | MockWebsocketItem)[];
|
|
573
569
|
type FormidableFile = formidable.File | formidable.File[];
|
|
574
570
|
type LogType = "info" | "warn" | "error" | "debug";
|
|
575
|
-
type LogLevel = LogType | "silent";
|
|
571
|
+
type LogLevel = LogType | "silent";
|
|
572
|
+
//#endregion
|
|
576
573
|
export { FormidableFile, LogLevel, MockHttpItem, MockOptions, MockRequest, MockServerPluginOptions, MockWebsocketItem, ServerBuildOption };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-dev-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.9.0",
|
|
5
5
|
"author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://vite-plugin-mock-dev-server.netlify.app",
|
|
@@ -69,14 +69,14 @@
|
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@pengzhanbo/utils": "^2.1.0",
|
|
72
|
-
"@rollup/pluginutils": "^5.
|
|
72
|
+
"@rollup/pluginutils": "^5.2.0",
|
|
73
73
|
"chokidar": "3.6.0",
|
|
74
74
|
"co-body": "^6.2.0",
|
|
75
75
|
"cookies": "^0.9.1",
|
|
76
76
|
"cors": "^2.8.5",
|
|
77
|
-
"debug": "^4.4.
|
|
77
|
+
"debug": "^4.4.1",
|
|
78
78
|
"fast-glob": "^3.3.3",
|
|
79
|
-
"formidable": "
|
|
79
|
+
"formidable": "3.5.4",
|
|
80
80
|
"http-status": "^2.1.0",
|
|
81
81
|
"is-core-module": "^2.16.1",
|
|
82
82
|
"json5": "^2.2.3",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"ws": "^8.18.2"
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"esbuild": "^0.25.
|
|
89
|
+
"esbuild": "^0.25.5",
|
|
90
90
|
"vite": "^6.3.5"
|
|
91
91
|
},
|
|
92
92
|
"publishConfig": {
|