vite-plugin-mock-dev-server 2.0.1 → 2.0.3
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-BbR8Si2U.js → helper-ChmPhNrY.mjs} +19 -3
- package/dist/helper.d.mts +3 -0
- package/dist/helper.mjs +3 -0
- package/dist/{index-CJc2Oax2.d.ts → index-u_3ZZqGO.d.mts} +3 -3
- package/dist/index.d.mts +9 -0
- package/dist/{index.js → index.mjs} +26 -35
- package/dist/{server-G9rXmGpR.js → server-BetGF1ME.mjs} +226 -31
- package/dist/{server-nJXXNIV3.d.ts → server-CvrNrvvb.d.mts} +4 -3
- package/dist/server.d.mts +3 -0
- package/dist/server.mjs +3 -0
- package/dist/{types-BtCJqeLH.d.ts → types-DF6NPJx4.d.mts} +129 -8
- package/dist/types.d.mts +2 -0
- package/package.json +7 -8
- package/dist/helper.d.ts +0 -3
- package/dist/helper.js +0 -3
- package/dist/index.d.ts +0 -9
- package/dist/server.d.ts +0 -3
- package/dist/server.js +0 -3
- package/dist/types.d.ts +0 -2
- /package/dist/{types.js → types.mjs} +0 -0
|
@@ -114,6 +114,14 @@ function createDefineMock(transformer) {
|
|
|
114
114
|
|
|
115
115
|
//#endregion
|
|
116
116
|
//#region src/helper/defineMockData.ts
|
|
117
|
+
/**
|
|
118
|
+
* 由于插件是 分别独立对 `*.mock.*` 等文件作为单独入口进行编译的,
|
|
119
|
+
* 这导致了 mock 文件编译后的依赖关系不一致,每个 mock 文件拥有独立的作用域,
|
|
120
|
+
* 使得即使多个 `*.mock.*` 虽然引入了同一个 `data.ts` 文件,然而确是完全不同两份 `data`,
|
|
121
|
+
* 使得对 `data` 的操作,在不同的 `*.mock.*` 文件中并不能共享。
|
|
122
|
+
*
|
|
123
|
+
* 为此,插件提供了一种基于 memory 的数据共享机制。
|
|
124
|
+
*/
|
|
117
125
|
const mockDataCache = /* @__PURE__ */ new Map();
|
|
118
126
|
const responseCache = /* @__PURE__ */ new WeakMap();
|
|
119
127
|
const staleInterval = 70;
|
|
@@ -136,8 +144,16 @@ var CacheImpl = class {
|
|
|
136
144
|
}
|
|
137
145
|
};
|
|
138
146
|
function defineMockData(key, initialData) {
|
|
139
|
-
|
|
140
|
-
|
|
147
|
+
let cache = mockDataCache.get(key);
|
|
148
|
+
if (!cache) {
|
|
149
|
+
const newCache = new CacheImpl(initialData);
|
|
150
|
+
const existing = mockDataCache.get(key);
|
|
151
|
+
if (existing) cache = existing;
|
|
152
|
+
else {
|
|
153
|
+
mockDataCache.set(key, newCache);
|
|
154
|
+
cache = newCache;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
141
157
|
cache.hotUpdate(initialData);
|
|
142
158
|
if (responseCache.has(cache)) return responseCache.get(cache);
|
|
143
159
|
const res = [() => cache.value, (val) => {
|
|
@@ -157,4 +173,4 @@ function defineMockData(key, initialData) {
|
|
|
157
173
|
}
|
|
158
174
|
|
|
159
175
|
//#endregion
|
|
160
|
-
export {
|
|
176
|
+
export { createSSEStream as i, createDefineMock as n, defineMock as r, defineMockData as t };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
2
|
+
import { a as HeaderStream, i as defineMock, n as defineMockData, o as SSEMessage, r as createDefineMock, s as createSSEStream, t as MockData } from "./index-u_3ZZqGO.mjs";
|
|
3
|
+
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 };
|
package/dist/helper.mjs
ADDED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { MockHttpItem, MockOptions
|
|
2
|
-
import { Transform } from "node:stream";
|
|
1
|
+
import { m as MockWebsocketItem, s as MockHttpItem, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
3
2
|
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
3
|
+
import { Transform } from "node:stream";
|
|
4
4
|
|
|
5
5
|
//#region src/helper/createSSEStream.d.ts
|
|
6
6
|
interface SSEMessage {
|
|
@@ -123,4 +123,4 @@ type MockData<T = any> = readonly [() => T, (val: T | ((val: T) => T | void)) =>
|
|
|
123
123
|
};
|
|
124
124
|
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
125
125
|
//#endregion
|
|
126
|
-
export { HeaderStream,
|
|
126
|
+
export { HeaderStream as a, defineMock as i, defineMockData as n, SSEMessage as o, createDefineMock as r, createSSEStream as s, MockData as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
2
|
+
import { a as HeaderStream, i as defineMock, n as defineMockData, o as SSEMessage, r as createDefineMock, s as createSSEStream, t as MockData } from "./index-u_3ZZqGO.mjs";
|
|
3
|
+
import { a as createLogger, c as processRawData, i as Logger, l as sortByValidator, n as CreateMockMiddlewareOptions, o as logLevels, r as createMockMiddleware, s as processMockData, t as mockWebSocket } from "./server-CvrNrvvb.mjs";
|
|
4
|
+
import { Plugin } from "vite";
|
|
5
|
+
|
|
6
|
+
//#region src/plugin.d.ts
|
|
7
|
+
declare function mockDevServerPlugin(options?: MockServerPluginOptions): Plugin[];
|
|
8
|
+
//#endregion
|
|
9
|
+
export { BodyParserOptions, CreateMockMiddlewareOptions, ExtraRequest, type FormidableFile, HeaderStream, LogLevel, LogType, Logger, Method, MockData, type MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, type MockOptions, type MockRequest, MockResponse, type MockServerPluginOptions, type MockWebsocketItem, ResponseBody, SSEMessage, ServerBuildOption, WebSocketSetupContext, createDefineMock, createLogger, createMockMiddleware, createSSEStream, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, processMockData, processRawData, sortByValidator };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { a as processRawData, c as debug, d as logLevels, f as isPathMatch, h as createMatcher, i as processMockData, l as normalizePath, m as doesProxyContextMatchUrl, n as createMockMiddleware, o as sortByValidator, p as isPackageExists, r as recoverRequest, s as urlParse, t as mockWebSocket, u as createLogger } from "./server-BetGF1ME.mjs";
|
|
2
|
+
import { i as createSSEStream, n as createDefineMock, r as defineMock, t as defineMockData } from "./helper-ChmPhNrY.mjs";
|
|
3
3
|
import { isArray, isBoolean, promiseParallel, toArray, uniq } from "@pengzhanbo/utils";
|
|
4
4
|
import fs, { promises } from "node:fs";
|
|
5
5
|
import fsp from "node:fs/promises";
|
|
@@ -40,9 +40,8 @@ const jsonLoader = {
|
|
|
40
40
|
name: "json-loader",
|
|
41
41
|
setup(build) {
|
|
42
42
|
build.onLoad({ filter: /\.json$/ }, async ({ path: path$1 }) => {
|
|
43
|
-
const content = await fsp.readFile(path$1, "utf-8");
|
|
44
43
|
return {
|
|
45
|
-
contents: `export default ${
|
|
44
|
+
contents: `export default ${await fsp.readFile(path$1, "utf-8")}`,
|
|
46
45
|
loader: "js"
|
|
47
46
|
};
|
|
48
47
|
});
|
|
@@ -68,13 +67,12 @@ function aliasPlugin(alias) {
|
|
|
68
67
|
const matchedEntry = alias.find(({ find: find$1 }) => aliasMatches(find$1, id));
|
|
69
68
|
if (!matchedEntry) return null;
|
|
70
69
|
const { find, replacement } = matchedEntry;
|
|
71
|
-
const result = await build.resolve(id.replace(find, replacement), {
|
|
72
|
-
kind: "import-statement",
|
|
73
|
-
resolveDir: replacement,
|
|
74
|
-
namespace: "file"
|
|
75
|
-
});
|
|
76
70
|
return {
|
|
77
|
-
path:
|
|
71
|
+
path: (await build.resolve(id.replace(find, replacement), {
|
|
72
|
+
kind: "import-statement",
|
|
73
|
+
resolveDir: replacement,
|
|
74
|
+
namespace: "file"
|
|
75
|
+
})).path,
|
|
78
76
|
external: false
|
|
79
77
|
};
|
|
80
78
|
});
|
|
@@ -97,8 +95,7 @@ async function transformWithEsbuild(entryPoint, { isESM = true, define, alias, c
|
|
|
97
95
|
const filename = path.basename(entryPoint);
|
|
98
96
|
const dirname = path.dirname(filepath);
|
|
99
97
|
try {
|
|
100
|
-
const
|
|
101
|
-
const result = await build({
|
|
98
|
+
const result = await (await esbuild())({
|
|
102
99
|
entryPoints: [entryPoint],
|
|
103
100
|
outfile: "out.js",
|
|
104
101
|
write: false,
|
|
@@ -180,7 +177,7 @@ let _rolldown = null;
|
|
|
180
177
|
async function rolldown() {
|
|
181
178
|
_rolldown ||= {
|
|
182
179
|
build: (await import("rolldown")).build,
|
|
183
|
-
aliasPlugin: (await import("rolldown/experimental")).
|
|
180
|
+
aliasPlugin: (await import("rolldown/experimental")).viteAliasPlugin
|
|
184
181
|
};
|
|
185
182
|
return _rolldown;
|
|
186
183
|
}
|
|
@@ -201,12 +198,12 @@ async function transformWithRolldown(entryPoint, { isESM = true, define, alias,
|
|
|
201
198
|
file: "out.js"
|
|
202
199
|
},
|
|
203
200
|
platform: "node",
|
|
204
|
-
define: {
|
|
201
|
+
transform: { define: {
|
|
205
202
|
...define,
|
|
206
203
|
__dirname: JSON.stringify(dirname),
|
|
207
204
|
__filename: JSON.stringify(filename),
|
|
208
205
|
...isESM ? {} : { "import.meta.url": JSON.stringify(pathToFileURL(filepath)) }
|
|
209
|
-
},
|
|
206
|
+
} },
|
|
210
207
|
external(id) {
|
|
211
208
|
if (isAlias(id)) return false;
|
|
212
209
|
if (id[0] !== "." && !path.isAbsolute(id) && id !== "vite-plugin-mock-dev-server") return true;
|
|
@@ -246,14 +243,13 @@ async function compile(filepath, options) {
|
|
|
246
243
|
...options,
|
|
247
244
|
isESM
|
|
248
245
|
});
|
|
249
|
-
const data = await loadFromCode({
|
|
250
|
-
filepath,
|
|
251
|
-
code,
|
|
252
|
-
isESM,
|
|
253
|
-
cwd: options.cwd || process.cwd()
|
|
254
|
-
}) || {};
|
|
255
246
|
return {
|
|
256
|
-
data
|
|
247
|
+
data: await loadFromCode({
|
|
248
|
+
filepath,
|
|
249
|
+
code,
|
|
250
|
+
isESM,
|
|
251
|
+
cwd: options.cwd || process.cwd()
|
|
252
|
+
}) || {},
|
|
257
253
|
deps
|
|
258
254
|
};
|
|
259
255
|
}
|
|
@@ -271,13 +267,13 @@ var Compiler = class extends EventEmitter {
|
|
|
271
267
|
depsWatcher;
|
|
272
268
|
isESM = false;
|
|
273
269
|
_mockData = {};
|
|
270
|
+
options;
|
|
274
271
|
constructor(options) {
|
|
275
272
|
super();
|
|
276
273
|
this.options = options;
|
|
277
274
|
this.cwd = options.cwd || process.cwd();
|
|
278
275
|
try {
|
|
279
|
-
|
|
280
|
-
this.isESM = pkg?.type === "module";
|
|
276
|
+
this.isESM = loadPackageJSONSync(this.cwd)?.type === "module";
|
|
281
277
|
} catch {}
|
|
282
278
|
}
|
|
283
279
|
get mockData() {
|
|
@@ -338,8 +334,7 @@ var Compiler = class extends EventEmitter {
|
|
|
338
334
|
updateModuleDeps(filepath, deps) {
|
|
339
335
|
for (const dep of deps) {
|
|
340
336
|
if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
|
|
341
|
-
|
|
342
|
-
cur.add(filepath);
|
|
337
|
+
this.moduleDeps.get(dep).add(filepath);
|
|
343
338
|
}
|
|
344
339
|
this.emit("update:deps");
|
|
345
340
|
}
|
|
@@ -376,8 +371,7 @@ var Compiler = class extends EventEmitter {
|
|
|
376
371
|
});
|
|
377
372
|
watcher.on("change", (filepath) => {
|
|
378
373
|
filepath = normalizePath(filepath);
|
|
379
|
-
|
|
380
|
-
mockFiles?.forEach((file) => this.emit("mock:update", file));
|
|
374
|
+
this.moduleDeps.get(filepath)?.forEach((file) => this.emit("mock:update", file));
|
|
381
375
|
});
|
|
382
376
|
watcher.on("unlink", (filepath) => {
|
|
383
377
|
filepath = normalizePath(filepath);
|
|
@@ -417,7 +411,7 @@ export default processMockData(mockList);`;
|
|
|
417
411
|
//#endregion
|
|
418
412
|
//#region package.json
|
|
419
413
|
var name = "vite-plugin-mock-dev-server";
|
|
420
|
-
var version = "2.0.
|
|
414
|
+
var version = "2.0.3";
|
|
421
415
|
|
|
422
416
|
//#endregion
|
|
423
417
|
//#region src/build/packageJson.ts
|
|
@@ -573,8 +567,7 @@ function createCorsMiddleware(compiler, { proxies, cors: corsOptions }) {
|
|
|
573
567
|
const { pathname } = urlParse(req.url);
|
|
574
568
|
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) return next();
|
|
575
569
|
const mockData = compiler.mockData;
|
|
576
|
-
|
|
577
|
-
if (!mockUrl) return next();
|
|
570
|
+
if (!Object.keys(mockData).find((pattern) => isPathMatch(pattern, pathname))) return next();
|
|
578
571
|
cors(corsOptions)(req, res, next);
|
|
579
572
|
};
|
|
580
573
|
}
|
|
@@ -819,12 +812,10 @@ function serverPlugin(options) {
|
|
|
819
812
|
config.logger.warn("");
|
|
820
813
|
},
|
|
821
814
|
configureServer({ middlewares, httpServer, ws }) {
|
|
822
|
-
|
|
823
|
-
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
815
|
+
initMockMiddlewares(resolvedOptions, httpServer, ws).forEach((middleware) => middlewares.use(middleware));
|
|
824
816
|
},
|
|
825
817
|
configurePreviewServer({ middlewares, httpServer }) {
|
|
826
|
-
|
|
827
|
-
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
818
|
+
initMockMiddlewares(resolvedOptions, httpServer).forEach((middleware) => middlewares.use(middleware));
|
|
828
819
|
}
|
|
829
820
|
};
|
|
830
821
|
}
|
|
@@ -8,7 +8,8 @@ import Debug from "debug";
|
|
|
8
8
|
import { parse as parse$1 } from "node:querystring";
|
|
9
9
|
import bodyParser from "co-body";
|
|
10
10
|
import formidable from "formidable";
|
|
11
|
-
import
|
|
11
|
+
import http from "node:http";
|
|
12
|
+
import crypto from "node:crypto";
|
|
12
13
|
import { Buffer } from "node:buffer";
|
|
13
14
|
import HTTP_STATUS from "http-status";
|
|
14
15
|
import * as mime from "mime-types";
|
|
@@ -22,11 +23,10 @@ function createMatcher(include, exclude) {
|
|
|
22
23
|
if (item[0] === "!") ignore.push(item.slice(1));
|
|
23
24
|
else pattern.push(item);
|
|
24
25
|
});
|
|
25
|
-
const isMatch = picomatch(pattern, { ignore });
|
|
26
26
|
return {
|
|
27
27
|
pattern,
|
|
28
28
|
ignore,
|
|
29
|
-
isMatch
|
|
29
|
+
isMatch: picomatch(pattern, { ignore })
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
@@ -115,15 +115,14 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
115
115
|
prefix = `[${prefix}]`;
|
|
116
116
|
function output(type, msg, level) {
|
|
117
117
|
level = isBoolean(level) ? level ? defaultLevel : "error" : level;
|
|
118
|
-
|
|
119
|
-
if (thresh >= logLevels[type]) {
|
|
118
|
+
if (logLevels[level] >= logLevels[type]) {
|
|
120
119
|
const method = type === "info" || type === "debug" ? "log" : type;
|
|
121
120
|
const tag = type === "debug" ? ansis.magenta.bold(prefix) : type === "info" ? ansis.cyan.bold(prefix) : type === "warn" ? ansis.yellow.bold(prefix) : ansis.red.bold(prefix);
|
|
122
121
|
const format = `${ansis.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
|
|
123
122
|
console[method](format);
|
|
124
123
|
}
|
|
125
124
|
}
|
|
126
|
-
|
|
125
|
+
return {
|
|
127
126
|
debug(msg, level = defaultLevel) {
|
|
128
127
|
output("debug", msg, level);
|
|
129
128
|
},
|
|
@@ -137,7 +136,6 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
137
136
|
output("error", msg, level);
|
|
138
137
|
}
|
|
139
138
|
};
|
|
140
|
-
return logger;
|
|
141
139
|
}
|
|
142
140
|
|
|
143
141
|
//#endregion
|
|
@@ -160,11 +158,9 @@ function normalizePath(id) {
|
|
|
160
158
|
*/
|
|
161
159
|
function urlParse(input) {
|
|
162
160
|
const url = new URL(input, "http://example.com");
|
|
163
|
-
const pathname = decodeURIComponent(url.pathname);
|
|
164
|
-
const query = parse$1(url.search.replace(/^\?/, ""));
|
|
165
161
|
return {
|
|
166
|
-
pathname,
|
|
167
|
-
query
|
|
162
|
+
pathname: decodeURIComponent(url.pathname),
|
|
163
|
+
query: parse$1(url.search.replace(/^\?/, ""))
|
|
168
164
|
};
|
|
169
165
|
}
|
|
170
166
|
|
|
@@ -233,8 +229,7 @@ function sortByValidator(mocks) {
|
|
|
233
229
|
const { validator } = item;
|
|
234
230
|
if (!validator || isEmptyObject(validator)) return 2;
|
|
235
231
|
if (isFunction(validator)) return 0;
|
|
236
|
-
|
|
237
|
-
return 1 / count;
|
|
232
|
+
return 1 / Object.keys(validator).reduce((prev, key) => prev + keysCount(validator[key]), 0);
|
|
238
233
|
});
|
|
239
234
|
}
|
|
240
235
|
function keysCount(obj) {
|
|
@@ -251,7 +246,7 @@ async function parseRequestBody(req, formidableOptions, bodyParserOptions = {})
|
|
|
251
246
|
const method = req.method.toUpperCase();
|
|
252
247
|
if (["HEAD", "OPTIONS"].includes(method)) return void 0;
|
|
253
248
|
const type = req.headers["content-type"]?.toLocaleLowerCase() || "";
|
|
254
|
-
const { limit, formLimit, jsonLimit, textLimit
|
|
249
|
+
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
|
|
255
250
|
try {
|
|
256
251
|
if (type.startsWith("application/json")) return await bodyParser.json(req, {
|
|
257
252
|
limit: jsonLimit || limit,
|
|
@@ -269,7 +264,6 @@ async function parseRequestBody(req, formidableOptions, bodyParserOptions = {})
|
|
|
269
264
|
} catch (e) {
|
|
270
265
|
console.error(e);
|
|
271
266
|
}
|
|
272
|
-
return void 0;
|
|
273
267
|
}
|
|
274
268
|
const DEFAULT_FORMIDABLE_OPTIONS = {
|
|
275
269
|
keepExtensions: true,
|
|
@@ -340,8 +334,7 @@ function requestLog(request, filepath) {
|
|
|
340
334
|
function fineMockData(mockList, logger, { pathname, method, request }) {
|
|
341
335
|
return mockList.find((mock) => {
|
|
342
336
|
if (!pathname || !mock || !mock.url || mock.ws) return false;
|
|
343
|
-
|
|
344
|
-
if (!methods.includes(method)) return false;
|
|
337
|
+
if (!(mock.method ? isArray(mock.method) ? mock.method : [mock.method] : ["GET", "POST"]).includes(method)) return false;
|
|
345
338
|
const hasMock = isPathMatch(mock.url, pathname);
|
|
346
339
|
if (hasMock && mock.validator) {
|
|
347
340
|
const params = parseRequestParams(mock.url, pathname);
|
|
@@ -364,6 +357,215 @@ function fineMockData(mockList, logger, { pathname, method, request }) {
|
|
|
364
357
|
});
|
|
365
358
|
}
|
|
366
359
|
|
|
360
|
+
//#endregion
|
|
361
|
+
//#region src/cookies/constants.ts
|
|
362
|
+
/**
|
|
363
|
+
* RegExp to match field-content in RFC 7230 sec 3.2
|
|
364
|
+
*
|
|
365
|
+
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
|
366
|
+
* field-vchar = VCHAR / obs-text
|
|
367
|
+
* obs-text = %x80-FF
|
|
368
|
+
*/
|
|
369
|
+
const fieldContentRegExp = /^[\t\u0020-\u007E\u0080-\u00FF]+$/;
|
|
370
|
+
/**
|
|
371
|
+
* RegExp to match Priority cookie attribute value.
|
|
372
|
+
*/
|
|
373
|
+
const PRIORITY_REGEXP = /^(?:low|medium|high)$/i;
|
|
374
|
+
/**
|
|
375
|
+
* Cache for generated name regular expressions.
|
|
376
|
+
*/
|
|
377
|
+
const REGEXP_CACHE = Object.create(null);
|
|
378
|
+
/**
|
|
379
|
+
* RegExp to match all characters to escape in a RegExp.
|
|
380
|
+
*/
|
|
381
|
+
const REGEXP_ESCAPE_CHARS_REGEXP = /[\^$\\.*+?()[\]{}|]/g;
|
|
382
|
+
/**
|
|
383
|
+
* RegExp to match basic restricted name characters for loose validation.
|
|
384
|
+
*/
|
|
385
|
+
const RESTRICTED_NAME_CHARS_REGEXP = /[;=]/;
|
|
386
|
+
/**
|
|
387
|
+
* RegExp to match basic restricted value characters for loose validation.
|
|
388
|
+
*/
|
|
389
|
+
const RESTRICTED_VALUE_CHARS_REGEXP = /;/;
|
|
390
|
+
/**
|
|
391
|
+
* RegExp to match Same-Site cookie attribute value.
|
|
392
|
+
*/
|
|
393
|
+
const SAME_SITE_REGEXP = /^(?:lax|none|strict)$/i;
|
|
394
|
+
|
|
395
|
+
//#endregion
|
|
396
|
+
//#region src/cookies/Cookie.ts
|
|
397
|
+
var Cookie = class {
|
|
398
|
+
name;
|
|
399
|
+
value;
|
|
400
|
+
maxAge;
|
|
401
|
+
expires;
|
|
402
|
+
path = "/";
|
|
403
|
+
domain;
|
|
404
|
+
secure = false;
|
|
405
|
+
httpOnly = true;
|
|
406
|
+
sameSite = false;
|
|
407
|
+
overwrite = false;
|
|
408
|
+
priority;
|
|
409
|
+
partitioned;
|
|
410
|
+
constructor(name, value, options = {}) {
|
|
411
|
+
if (!fieldContentRegExp.test(name) || RESTRICTED_NAME_CHARS_REGEXP.test(name)) throw new TypeError("argument name is invalid");
|
|
412
|
+
if (value && (!fieldContentRegExp.test(value) || RESTRICTED_VALUE_CHARS_REGEXP.test(value))) throw new TypeError("argument value is invalid");
|
|
413
|
+
this.name = name;
|
|
414
|
+
this.value = value;
|
|
415
|
+
Object.assign(this, options);
|
|
416
|
+
if (!this.value) {
|
|
417
|
+
this.expires = /* @__PURE__ */ new Date(0);
|
|
418
|
+
this.maxAge = void 0;
|
|
419
|
+
}
|
|
420
|
+
if (this.path && !fieldContentRegExp.test(this.path)) throw new TypeError("[Cookie] option path is invalid");
|
|
421
|
+
if (this.domain && !fieldContentRegExp.test(this.domain)) throw new TypeError("[Cookie] option domain is invalid");
|
|
422
|
+
if (typeof this.maxAge === "number" ? Number.isNaN(this.maxAge) || !Number.isFinite(this.maxAge) : this.maxAge) throw new TypeError("[Cookie] option maxAge is invalid");
|
|
423
|
+
if (this.priority && !PRIORITY_REGEXP.test(this.priority)) throw new TypeError("[Cookie] option priority is invalid");
|
|
424
|
+
if (this.sameSite && this.sameSite !== true && !SAME_SITE_REGEXP.test(this.sameSite)) throw new TypeError("[Cookie] option sameSite is invalid");
|
|
425
|
+
}
|
|
426
|
+
toString() {
|
|
427
|
+
return `${this.name}=${this.value}`;
|
|
428
|
+
}
|
|
429
|
+
toHeader() {
|
|
430
|
+
let header = this.toString();
|
|
431
|
+
if (this.maxAge) this.expires = new Date(Date.now() + this.maxAge);
|
|
432
|
+
if (this.path) header += `; path=${this.path}`;
|
|
433
|
+
if (this.expires) header += `; expires=${this.expires.toUTCString()}`;
|
|
434
|
+
if (this.domain) header += `; domain=${this.domain}`;
|
|
435
|
+
if (this.priority) header += `; priority=${this.priority.toLowerCase()}`;
|
|
436
|
+
if (this.sameSite) header += `; samesite=${this.sameSite === true ? "strict" : this.sameSite.toLowerCase()}`;
|
|
437
|
+
if (this.secure) header += "; secure";
|
|
438
|
+
if (this.httpOnly) header += "; httponly";
|
|
439
|
+
if (this.partitioned) header += "; partitioned";
|
|
440
|
+
return header;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region src/cookies/timeSafeCompare.ts
|
|
446
|
+
function bufferEqual(a, b) {
|
|
447
|
+
if (a.length !== b.length) return false;
|
|
448
|
+
if (crypto.timingSafeEqual) return crypto.timingSafeEqual(a, b);
|
|
449
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
function createHmac(key, data) {
|
|
453
|
+
return crypto.createHmac("sha256", key).update(data).digest();
|
|
454
|
+
}
|
|
455
|
+
function timeSafeCompare(a, b) {
|
|
456
|
+
const sa = String(a);
|
|
457
|
+
const sb = String(b);
|
|
458
|
+
const key = crypto.randomBytes(32);
|
|
459
|
+
return bufferEqual(createHmac(key, sa), createHmac(key, sb)) && a === b;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
//#endregion
|
|
463
|
+
//#region src/cookies/Keygrip.ts
|
|
464
|
+
const SLASH_PATTERN = /[/+=]/g;
|
|
465
|
+
const REPLACE_MAP = {
|
|
466
|
+
"/": "_",
|
|
467
|
+
"+": "-",
|
|
468
|
+
"=": ""
|
|
469
|
+
};
|
|
470
|
+
var Keygrip = class {
|
|
471
|
+
algorithm;
|
|
472
|
+
encoding;
|
|
473
|
+
keys = [];
|
|
474
|
+
constructor(keys, algorithm, encoding) {
|
|
475
|
+
this.keys = keys;
|
|
476
|
+
this.algorithm = algorithm || "sha256";
|
|
477
|
+
this.encoding = encoding || "base64";
|
|
478
|
+
}
|
|
479
|
+
sign(data, key = this.keys[0]) {
|
|
480
|
+
return crypto.createHmac(this.algorithm, key).update(data).digest(this.encoding).replace(SLASH_PATTERN, (m) => REPLACE_MAP[m]);
|
|
481
|
+
}
|
|
482
|
+
index(data, digest) {
|
|
483
|
+
for (let i = 0, l = this.keys.length; i < l; i++) if (timeSafeCompare(digest, this.sign(data, this.keys[i]))) return i;
|
|
484
|
+
return -1;
|
|
485
|
+
}
|
|
486
|
+
verify(data, digest) {
|
|
487
|
+
return this.index(data, digest) > -1;
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
//#endregion
|
|
492
|
+
//#region src/cookies/Cookies.ts
|
|
493
|
+
var Cookies = class {
|
|
494
|
+
request;
|
|
495
|
+
response;
|
|
496
|
+
secure;
|
|
497
|
+
keys;
|
|
498
|
+
constructor(req, res, options = {}) {
|
|
499
|
+
this.request = req;
|
|
500
|
+
this.response = res;
|
|
501
|
+
this.secure = options.secure;
|
|
502
|
+
if (options.keys instanceof Keygrip) this.keys = options.keys;
|
|
503
|
+
else if (isArray(options.keys)) this.keys = new Keygrip(options.keys);
|
|
504
|
+
}
|
|
505
|
+
set(name, value, options) {
|
|
506
|
+
const req = this.request;
|
|
507
|
+
const res = this.response;
|
|
508
|
+
const headers = toArray(res.getHeader("Set-Cookie"));
|
|
509
|
+
const cookie = new Cookie(name, value, options);
|
|
510
|
+
const signed = options?.signed ?? !!this.keys;
|
|
511
|
+
const secure = this.secure === void 0 ? req.protocol === "https" || isRequestEncrypted(req) : Boolean(this.secure);
|
|
512
|
+
if (!secure && options?.secure) throw new Error("Cannot send secure cookie over unencrypted connection");
|
|
513
|
+
cookie.secure = options?.secure ?? secure;
|
|
514
|
+
pushCookie(headers, cookie);
|
|
515
|
+
if (signed && options) {
|
|
516
|
+
if (!this.keys) throw new Error(".keys required for signed cookies");
|
|
517
|
+
cookie.value = this.keys.sign(cookie.toString());
|
|
518
|
+
cookie.name += ".sig";
|
|
519
|
+
pushCookie(headers, cookie);
|
|
520
|
+
}
|
|
521
|
+
(res.set ? http.OutgoingMessage.prototype.setHeader : res.setHeader).call(res, "Set-Cookie", headers);
|
|
522
|
+
return this;
|
|
523
|
+
}
|
|
524
|
+
get(name, options) {
|
|
525
|
+
const signName = `${name}.sig`;
|
|
526
|
+
const signed = options?.signed ?? !!this.keys;
|
|
527
|
+
const header = this.request.headers.cookie;
|
|
528
|
+
if (!header) return;
|
|
529
|
+
const match$1 = header.match(getPattern(name));
|
|
530
|
+
if (!match$1) return;
|
|
531
|
+
let value = match$1[1];
|
|
532
|
+
if (value[0] === "\"") value = value.slice(1, -1);
|
|
533
|
+
if (!options || !signed) return value;
|
|
534
|
+
const remote = this.get(signName);
|
|
535
|
+
if (!remote) return;
|
|
536
|
+
const data = `${name}=${value}`;
|
|
537
|
+
if (!this.keys) throw new Error(".keys required for signed cookies");
|
|
538
|
+
const index = this.keys.index(data, remote);
|
|
539
|
+
if (index < 0) this.set(signName, null, {
|
|
540
|
+
path: "/",
|
|
541
|
+
signed: false
|
|
542
|
+
});
|
|
543
|
+
else {
|
|
544
|
+
index && this.set(signName, this.keys.sign(data), { signed: false });
|
|
545
|
+
return value;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
/**
|
|
550
|
+
* Get the pattern to search for a cookie in a string.
|
|
551
|
+
*/
|
|
552
|
+
function getPattern(name) {
|
|
553
|
+
if (!REGEXP_CACHE[name]) REGEXP_CACHE[name] = /* @__PURE__ */ new RegExp(`(?:^|;) *${name.replace(REGEXP_ESCAPE_CHARS_REGEXP, "\\$&")}=([^;]*)`);
|
|
554
|
+
return REGEXP_CACHE[name];
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Get the encrypted status for a request.
|
|
558
|
+
*/
|
|
559
|
+
function isRequestEncrypted(req) {
|
|
560
|
+
return Boolean(req.socket ? req.socket.encrypted : req.connection.encrypted);
|
|
561
|
+
}
|
|
562
|
+
function pushCookie(headers, cookie) {
|
|
563
|
+
if (cookie.overwrite) {
|
|
564
|
+
for (let i = headers.length - 1; i >= 0; i--) if (headers[i].indexOf(`${cookie.name}=`) === 0) headers.splice(i, 1);
|
|
565
|
+
}
|
|
566
|
+
headers.push(cookie.toHeader());
|
|
567
|
+
}
|
|
568
|
+
|
|
367
569
|
//#endregion
|
|
368
570
|
//#region src/core/matchingWeight.ts
|
|
369
571
|
const tokensCache = {};
|
|
@@ -396,8 +598,7 @@ function sortFn(rule) {
|
|
|
396
598
|
const tokens = getTokens(rule);
|
|
397
599
|
let w = 0;
|
|
398
600
|
for (let i = 0; i < tokens.length; i++) {
|
|
399
|
-
|
|
400
|
-
if (token.type !== "text") w += 10 ** (i + 1);
|
|
601
|
+
if (tokens[i].type !== "text") w += 10 ** (i + 1);
|
|
401
602
|
w += 10 ** (i + 1);
|
|
402
603
|
}
|
|
403
604
|
return w;
|
|
@@ -406,8 +607,7 @@ function preSort(rules) {
|
|
|
406
607
|
let matched = [];
|
|
407
608
|
const preMatch = [];
|
|
408
609
|
for (const rule of rules) {
|
|
409
|
-
const
|
|
410
|
-
const len = tokens.filter((token) => token.type !== "text").length;
|
|
610
|
+
const len = getTokens(rule).filter((token) => token.type !== "text").length;
|
|
411
611
|
if (!preMatch[len]) preMatch[len] = [];
|
|
412
612
|
preMatch[len].push(rule);
|
|
413
613
|
}
|
|
@@ -468,12 +668,8 @@ function matchingWeight(rules, url, priority) {
|
|
|
468
668
|
function twoPartMatch(rules) {
|
|
469
669
|
const statics = [];
|
|
470
670
|
const dynamics = [];
|
|
471
|
-
for (const rule of rules)
|
|
472
|
-
|
|
473
|
-
const dym = tokens.filter((token) => token.type !== "text");
|
|
474
|
-
if (dym.length > 0) dynamics.push(rule);
|
|
475
|
-
else statics.push(rule);
|
|
476
|
-
}
|
|
671
|
+
for (const rule of rules) if (getTokens(rule).filter((token) => token.type !== "text").length > 0) dynamics.push(rule);
|
|
672
|
+
else statics.push(rule);
|
|
477
673
|
return [statics, dynamics];
|
|
478
674
|
}
|
|
479
675
|
|
|
@@ -503,7 +699,7 @@ function recoverRequest(config) {
|
|
|
503
699
|
const target = proxies[key];
|
|
504
700
|
const options = typeof target === "string" ? { target } : target;
|
|
505
701
|
if (options.ws) return;
|
|
506
|
-
const { configure
|
|
702
|
+
const { configure, ...rest } = options;
|
|
507
703
|
proxies[key] = {
|
|
508
704
|
...rest,
|
|
509
705
|
configure(proxy, options$1) {
|
|
@@ -791,8 +987,7 @@ function mockWebSocket(compiler, server, { wsProxies: proxies, cookiesOptions, l
|
|
|
791
987
|
server?.on("close", () => {
|
|
792
988
|
for (const wssMap of poolMap.values()) {
|
|
793
989
|
for (const wss of wssMap.values()) {
|
|
794
|
-
|
|
795
|
-
cleanupRunner(wssContext.cleanupList);
|
|
990
|
+
cleanupRunner(wssContextMap.get(wss).cleanupList);
|
|
796
991
|
wss.close();
|
|
797
992
|
}
|
|
798
993
|
wssMap.clear();
|
|
@@ -807,4 +1002,4 @@ function cleanupRunner(cleanupList) {
|
|
|
807
1002
|
}
|
|
808
1003
|
|
|
809
1004
|
//#endregion
|
|
810
|
-
export {
|
|
1005
|
+
export { processRawData as a, debug as c, logLevels as d, isPathMatch as f, createMatcher as h, processMockData as i, normalizePath as l, doesProxyContextMatchUrl as m, createMockMiddleware as n, sortByValidator as o, isPackageExists as p, recoverRequest as r, urlParse as s, mockWebSocket as t, createLogger as u };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { g as ServerBuildOption, i as LogLevel, m as MockWebsocketItem, p as MockServerPluginOptions, s as MockHttpItem, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
2
2
|
import { Matcher } from "picomatch";
|
|
3
|
+
import Debug from "debug";
|
|
3
4
|
import EventEmitter from "node:events";
|
|
4
5
|
import { CorsOptions } from "cors";
|
|
5
6
|
import { Server } from "node:http";
|
|
@@ -42,7 +43,6 @@ type ResolvedMockServerPluginOptions = Required<Omit<MockServerPluginOptions, "b
|
|
|
42
43
|
* Mock 文件加载编译,并转换为 Mock 数据
|
|
43
44
|
*/
|
|
44
45
|
declare class Compiler extends EventEmitter {
|
|
45
|
-
options: ResolvedMockServerPluginOptions;
|
|
46
46
|
private moduleCache;
|
|
47
47
|
private moduleDeps;
|
|
48
48
|
cwd: string;
|
|
@@ -50,6 +50,7 @@ declare class Compiler extends EventEmitter {
|
|
|
50
50
|
private depsWatcher;
|
|
51
51
|
private isESM;
|
|
52
52
|
private _mockData;
|
|
53
|
+
options: ResolvedMockServerPluginOptions;
|
|
53
54
|
constructor(options: ResolvedMockServerPluginOptions);
|
|
54
55
|
get mockData(): Record<string, MockOptions>;
|
|
55
56
|
run(watch?: boolean): void;
|
|
@@ -85,4 +86,4 @@ declare function mockWebSocket(compiler: Compiler, server: Server | Http2SecureS
|
|
|
85
86
|
logger
|
|
86
87
|
}: ResolvedMockServerPluginOptions): void;
|
|
87
88
|
//#endregion
|
|
88
|
-
export {
|
|
89
|
+
export { createLogger as a, processRawData as c, Logger as i, sortByValidator as l, CreateMockMiddlewareOptions as n, logLevels as o, createMockMiddleware as r, processMockData as s, mockWebSocket as t };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import "./types-DF6NPJx4.mjs";
|
|
2
|
+
import { a as createLogger, c as processRawData, i as Logger, l as sortByValidator, n as CreateMockMiddlewareOptions, o as logLevels, r as createMockMiddleware, s as processMockData, t as mockWebSocket } from "./server-CvrNrvvb.mjs";
|
|
3
|
+
export { CreateMockMiddlewareOptions, Logger, createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
package/dist/server.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { a as processRawData, d as logLevels, i as processMockData, n as createMockMiddleware, o as sortByValidator, t as mockWebSocket, u as createLogger } from "./server-BetGF1ME.mjs";
|
|
2
|
+
|
|
3
|
+
export { createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
|
@@ -1,15 +1,136 @@
|
|
|
1
1
|
import { CorsOptions } from "cors";
|
|
2
2
|
import { Options } from "co-body";
|
|
3
3
|
import formidable from "formidable";
|
|
4
|
-
import
|
|
4
|
+
import http, { IncomingMessage, ServerResponse } from "node:http";
|
|
5
|
+
import crypto from "node:crypto";
|
|
5
6
|
import { Buffer } from "node:buffer";
|
|
6
7
|
import { WebSocketServer } from "ws";
|
|
7
8
|
import { Readable } from "node:stream";
|
|
8
|
-
import http from "node:http";
|
|
9
9
|
import { Connect } from "vite";
|
|
10
10
|
|
|
11
|
+
//#region src/cookies/Keygrip.d.ts
|
|
12
|
+
declare class Keygrip {
|
|
13
|
+
private algorithm;
|
|
14
|
+
private encoding;
|
|
15
|
+
private keys;
|
|
16
|
+
constructor(keys: string[], algorithm?: string, encoding?: crypto.BinaryToTextEncoding);
|
|
17
|
+
sign(data: string, key?: string): string;
|
|
18
|
+
index(data: string, digest: string): number;
|
|
19
|
+
verify(data: string, digest: string): boolean;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/cookies/types.d.ts
|
|
23
|
+
interface CookiesOption {
|
|
24
|
+
keys?: string[] | Keygrip;
|
|
25
|
+
secure?: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface SetCookieOption {
|
|
28
|
+
/**
|
|
29
|
+
* a number representing the milliseconds from `Date.now()` for expiry
|
|
30
|
+
*
|
|
31
|
+
* 表示从 `Date.now()` 起至过期的毫秒数
|
|
32
|
+
*/
|
|
33
|
+
maxAge?: number;
|
|
34
|
+
/**
|
|
35
|
+
* a Date object indicating the cookie's expiration
|
|
36
|
+
* date (expires at the end of session by default).
|
|
37
|
+
*
|
|
38
|
+
* 一个指示cookie过期时间的 Date 对象(默认在会话结束时过期)。
|
|
39
|
+
*/
|
|
40
|
+
expires?: Date;
|
|
41
|
+
/**
|
|
42
|
+
* a string indicating the path of the cookie (`/` by default).
|
|
43
|
+
*
|
|
44
|
+
* 一个指示cookie路径的字符串(默认为 `/`)。
|
|
45
|
+
*/
|
|
46
|
+
path?: string;
|
|
47
|
+
/**
|
|
48
|
+
* a string indicating the domain of the cookie (no default).
|
|
49
|
+
*
|
|
50
|
+
* 表示 Cookie 域的字符串(无默认值)。
|
|
51
|
+
*/
|
|
52
|
+
domain?: string;
|
|
53
|
+
/**
|
|
54
|
+
* a boolean indicating whether the cookie is only to be sent
|
|
55
|
+
* over HTTPS (false by default for HTTP, true by default for HTTPS).
|
|
56
|
+
*
|
|
57
|
+
* 一个布尔值,指示该 Cookie 是否仅通过 HTTPS 发送(HTTP 默认为 false,HTTPS 默认为 true)。
|
|
58
|
+
*/
|
|
59
|
+
secure?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* a boolean indicating whether the cookie is only to be sent over HTTP(S),
|
|
62
|
+
* and not made available to client JavaScript (true by default).
|
|
63
|
+
*
|
|
64
|
+
* 一个布尔值,指示该 cookie 是否仅通过HTTP(S)发送,而不对客户端JavaScript开放(默认为true)。
|
|
65
|
+
*/
|
|
66
|
+
httpOnly?: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* a boolean or string indicating whether the cookie is a "same site" cookie (false by default).
|
|
69
|
+
* This can be set to 'strict', 'lax', or true (which maps to 'strict').
|
|
70
|
+
*
|
|
71
|
+
* 一个布尔值或字符串,用于指示该cookie是否为“同站”cookie(默认为false)。
|
|
72
|
+
* 可将其设置为'strict'、'lax'或true(true会映射为'strict')。
|
|
73
|
+
*/
|
|
74
|
+
sameSite?: "strict" | "lax" | "none" | boolean;
|
|
75
|
+
/**
|
|
76
|
+
* a boolean indicating whether the cookie is to be signed (false by default).
|
|
77
|
+
* If this is true, another cookie of the same name with the .sig suffix
|
|
78
|
+
* appended will also be sent, with a 27-byte url-safe base64 SHA1 value
|
|
79
|
+
* representing the hash of cookie-name=cookie-value against the first Keygrip key.
|
|
80
|
+
* This signature key is used to detect tampering the next time a cookie is received.
|
|
81
|
+
*
|
|
82
|
+
* 一个布尔值,指示cookie是否需签名(默认为false)。
|
|
83
|
+
* 若设为true,将同时发送另一个同名但附加 `.sig` 后缀的 cookie,其值为 27 字节的URL安全型 base64 SHA1哈希值,
|
|
84
|
+
* 该哈希由cookie名称=cookie值的字符串与首个 Keygrip 密钥计算生成。
|
|
85
|
+
* 此签名密钥用于在下次接收cookie时检测数据是否被篡改。
|
|
86
|
+
*/
|
|
87
|
+
signed?: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* a boolean indicating whether to overwrite previously set
|
|
90
|
+
* cookies of the same name (false by default). If this is true,
|
|
91
|
+
* all cookies set during the same request with the same
|
|
92
|
+
* name (regardless of path or domain) are filtered out of
|
|
93
|
+
* the Set-Cookie header when setting this cookie.
|
|
94
|
+
*
|
|
95
|
+
* 一个布尔值,指示是否覆盖先前设置的同名Cookie(默认为false)。
|
|
96
|
+
* 若设为true,当设置此Cookie时,在同一请求期间设置的所有同名Cookie(无论路径或域)
|
|
97
|
+
* 都将从Set-Cookie标头中过滤掉。
|
|
98
|
+
*/
|
|
99
|
+
overwrite?: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* a string indicating the cookie priority.
|
|
102
|
+
* This can be set to 'low', 'medium', or 'high'.
|
|
103
|
+
*
|
|
104
|
+
* 表示Cookie优先级的字符串。可设置为'low'、'medium'或'high'。
|
|
105
|
+
*/
|
|
106
|
+
priority?: "low" | "medium" | "high";
|
|
107
|
+
/**
|
|
108
|
+
* a boolean indicating whether to partition the cookie in Chrome
|
|
109
|
+
* for the CHIPS Update (false by default). If this is true,
|
|
110
|
+
* Cookies from embedded sites will be partitioned
|
|
111
|
+
* and only readable from the same top level site from which it was created.
|
|
112
|
+
*
|
|
113
|
+
* 一个布尔值,指示是否在Chrome中为CHIPS更新对Cookie进行分区(默认为false)。
|
|
114
|
+
* 若设为true,来自嵌入式站点的Cookie将被分区,且仅可从创建它的同一顶级站点读取。
|
|
115
|
+
*/
|
|
116
|
+
partitioned?: boolean;
|
|
117
|
+
}
|
|
118
|
+
interface GetCookieOption {
|
|
119
|
+
signed: boolean;
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/cookies/Cookies.d.ts
|
|
123
|
+
declare class Cookies {
|
|
124
|
+
request: IncomingMessage;
|
|
125
|
+
response: ServerResponse<IncomingMessage>;
|
|
126
|
+
secure: boolean | undefined;
|
|
127
|
+
keys: Keygrip | undefined;
|
|
128
|
+
constructor(req: IncomingMessage, res: ServerResponse<IncomingMessage>, options?: CookiesOption);
|
|
129
|
+
set(name: string, value?: string | null, options?: SetCookieOption): this;
|
|
130
|
+
get(name: string, options?: GetCookieOption): string | void;
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
11
133
|
//#region src/types.d.ts
|
|
12
|
-
|
|
13
134
|
/**
|
|
14
135
|
* Configure plugin
|
|
15
136
|
*
|
|
@@ -106,7 +227,7 @@ interface MockServerPluginOptions {
|
|
|
106
227
|
* cookies options
|
|
107
228
|
* @see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
|
|
108
229
|
*/
|
|
109
|
-
cookiesOptions?:
|
|
230
|
+
cookiesOptions?: CookiesOption;
|
|
110
231
|
/**
|
|
111
232
|
* Configure to `co-body`
|
|
112
233
|
*
|
|
@@ -287,7 +408,7 @@ interface ExtraRequest {
|
|
|
287
408
|
* 获取 请求中携带的 cookie
|
|
288
409
|
* @see [cookies](https://github.com/pillarjs/cookies#cookiesgetname--options)
|
|
289
410
|
*/
|
|
290
|
-
getCookie:
|
|
411
|
+
getCookie: Cookies["get"];
|
|
291
412
|
}
|
|
292
413
|
type MockRequest = Connect.IncomingMessage & ExtraRequest;
|
|
293
414
|
type MockResponse = http.ServerResponse<http.IncomingMessage> & {
|
|
@@ -297,11 +418,11 @@ type MockResponse = http.ServerResponse<http.IncomingMessage> & {
|
|
|
297
418
|
* 向请求响应中设置 cookie
|
|
298
419
|
* @see [cookies](https://github.com/pillarjs/cookies#cookiessetname--values--options)
|
|
299
420
|
*/
|
|
300
|
-
setCookie:
|
|
421
|
+
setCookie: Cookies["set"];
|
|
301
422
|
};
|
|
302
423
|
type ResponseBodyFn = (request: MockRequest) => ResponseBody | Promise<ResponseBody>;
|
|
303
424
|
type ResponseHeaderFn = (request: MockRequest) => Headers | Promise<Headers>;
|
|
304
|
-
type CookieValue = string | [string,
|
|
425
|
+
type CookieValue = string | [string, SetCookieOption];
|
|
305
426
|
type ResponseCookies = Record<string, CookieValue>;
|
|
306
427
|
type ResponseCookiesFn = (request: MockRequest) => ResponseCookies | Promise<ResponseCookies>;
|
|
307
428
|
interface MockBaseItem {
|
|
@@ -578,4 +699,4 @@ type FormidableFile = formidable.File | formidable.File[];
|
|
|
578
699
|
type LogType = "info" | "warn" | "error" | "debug";
|
|
579
700
|
type LogLevel = LogType | "silent";
|
|
580
701
|
//#endregion
|
|
581
|
-
export {
|
|
702
|
+
export { WebSocketSetupContext as _, LogType as a, MockMatchPriority as c, MockRequest as d, MockResponse as f, ServerBuildOption as g, ResponseBody as h, LogLevel as i, MockMatchSpecialPriority as l, MockWebsocketItem as m, ExtraRequest as n, Method as o, MockServerPluginOptions as p, FormidableFile as r, MockHttpItem as s, BodyParserOptions as t, MockOptions as u };
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-DF6NPJx4.mjs";
|
|
2
|
+
export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-dev-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.3",
|
|
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",
|
|
@@ -61,26 +61,25 @@
|
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"@pengzhanbo/utils": "^2.1.0",
|
|
64
|
-
"ansis": "^4.
|
|
64
|
+
"ansis": "^4.2.0",
|
|
65
65
|
"chokidar": "^4.0.3",
|
|
66
66
|
"co-body": "^6.2.0",
|
|
67
|
-
"cookies": "^0.9.1",
|
|
68
67
|
"cors": "^2.8.5",
|
|
69
|
-
"debug": "^4.4.
|
|
68
|
+
"debug": "^4.4.3",
|
|
70
69
|
"formidable": "3.5.4",
|
|
71
70
|
"http-status": "^2.1.0",
|
|
72
71
|
"is-core-module": "^2.16.1",
|
|
73
72
|
"json5": "^2.2.3",
|
|
74
73
|
"local-pkg": "^1.1.2",
|
|
75
|
-
"mime-types": "^3.0.
|
|
74
|
+
"mime-types": "^3.0.2",
|
|
76
75
|
"path-to-regexp": "^8.3.0",
|
|
77
76
|
"picomatch": "^4.0.3",
|
|
78
|
-
"tinyglobby": "^0.2.
|
|
77
|
+
"tinyglobby": "^0.2.15",
|
|
79
78
|
"ws": "^8.18.3"
|
|
80
79
|
},
|
|
81
80
|
"devDependencies": {
|
|
82
|
-
"esbuild": "^0.
|
|
83
|
-
"rolldown": "^1.0.0-beta.
|
|
81
|
+
"esbuild": "^0.27.0",
|
|
82
|
+
"rolldown": "^1.0.0-beta.51",
|
|
84
83
|
"vite": "npm:rolldown-vite@latest"
|
|
85
84
|
},
|
|
86
85
|
"publishConfig": {
|
package/dist/helper.d.ts
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-BtCJqeLH.js";
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./index-CJc2Oax2.js";
|
|
3
|
-
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 };
|
package/dist/helper.js
DELETED
package/dist/index.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-BtCJqeLH.js";
|
|
2
|
-
import { HeaderStream, MockData, SSEMessage, createDefineMock, createSSEStream, defineMock, defineMockData } from "./index-CJc2Oax2.js";
|
|
3
|
-
import { CreateMockMiddlewareOptions, Logger, createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator } from "./server-nJXXNIV3.js";
|
|
4
|
-
import { Plugin } from "vite";
|
|
5
|
-
|
|
6
|
-
//#region src/plugin.d.ts
|
|
7
|
-
declare function mockDevServerPlugin(options?: MockServerPluginOptions): Plugin[];
|
|
8
|
-
//#endregion
|
|
9
|
-
export { BodyParserOptions, CreateMockMiddlewareOptions, ExtraRequest, type FormidableFile, HeaderStream, LogLevel, LogType, Logger, Method, MockData, type MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, type MockOptions, type MockRequest, MockResponse, type MockServerPluginOptions, type MockWebsocketItem, ResponseBody, SSEMessage, ServerBuildOption, WebSocketSetupContext, createDefineMock, createLogger, createMockMiddleware, createSSEStream, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, processMockData, processRawData, sortByValidator };
|
package/dist/server.d.ts
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import "./types-BtCJqeLH.js";
|
|
2
|
-
import { CreateMockMiddlewareOptions, Logger, createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator } from "./server-nJXXNIV3.js";
|
|
3
|
-
export { CreateMockMiddlewareOptions, Logger, createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
package/dist/server.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator } from "./server-G9rXmGpR.js";
|
|
2
|
-
|
|
3
|
-
export { createLogger, createMockMiddleware, logLevels, mockWebSocket, processMockData, processRawData, sortByValidator };
|
package/dist/types.d.ts
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-BtCJqeLH.js";
|
|
2
|
-
export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext };
|
|
File without changes
|