vite-plugin-mock-dev-server 1.3.4 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -46
- package/README.zh-CN.md +28 -27
- package/dist/index.cjs +1701 -30
- package/dist/index.d.cts +38 -9
- package/dist/index.d.ts +37 -9
- package/dist/index.js +1658 -30
- package/package.json +47 -51
package/dist/index.js
CHANGED
|
@@ -1,17 +1,438 @@
|
|
|
1
|
-
|
|
1
|
+
// src/plugin.ts
|
|
2
|
+
import { toArray as toArray4 } from "@pengzhanbo/utils";
|
|
3
|
+
|
|
4
|
+
// src/build.ts
|
|
5
|
+
import fs3 from "node:fs";
|
|
6
|
+
import fsp2 from "node:fs/promises";
|
|
7
|
+
import path3 from "node:path";
|
|
8
|
+
import process2 from "node:process";
|
|
9
|
+
import { toArray } from "@pengzhanbo/utils";
|
|
10
|
+
import fg from "fast-glob";
|
|
11
|
+
import isCore from "is-core-module";
|
|
12
|
+
import { createFilter, normalizePath } from "vite";
|
|
13
|
+
|
|
14
|
+
// package.json
|
|
15
|
+
var name = "vite-plugin-mock-dev-server";
|
|
16
|
+
var version = "1.4.1";
|
|
17
|
+
|
|
18
|
+
// src/compiler.ts
|
|
19
|
+
import fs2, { promises as fsp } from "node:fs";
|
|
20
|
+
import { createRequire } from "node:module";
|
|
21
|
+
import path2 from "node:path";
|
|
22
|
+
import { pathToFileURL } from "node:url";
|
|
23
|
+
import { build } from "esbuild";
|
|
24
|
+
import JSON5 from "json5";
|
|
25
|
+
|
|
26
|
+
// src/utils.ts
|
|
27
|
+
import fs from "node:fs";
|
|
28
|
+
import path from "node:path";
|
|
29
|
+
import { parse as queryParse } from "node:querystring";
|
|
30
|
+
import { URL as URL2, fileURLToPath } from "node:url";
|
|
31
|
+
import Debug from "debug";
|
|
32
|
+
import { match } from "path-to-regexp";
|
|
33
|
+
function isStream(stream) {
|
|
34
|
+
return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
|
|
35
|
+
}
|
|
36
|
+
function isReadableStream(stream) {
|
|
37
|
+
return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
|
|
38
|
+
}
|
|
39
|
+
function getDirname(importMetaUrl) {
|
|
40
|
+
return path.dirname(fileURLToPath(importMetaUrl));
|
|
41
|
+
}
|
|
42
|
+
var debug = Debug("vite:mock-dev-server");
|
|
43
|
+
function lookupFile(dir, formats, options) {
|
|
44
|
+
for (const format of formats) {
|
|
45
|
+
const fullPath = path.join(dir, format);
|
|
46
|
+
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
|
|
47
|
+
const result = (options == null ? void 0 : options.pathOnly) ? fullPath : fs.readFileSync(fullPath, "utf-8");
|
|
48
|
+
if (!(options == null ? void 0 : options.predicate) || options.predicate(result))
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const parentDir = path.dirname(dir);
|
|
53
|
+
if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir)))
|
|
54
|
+
return lookupFile(parentDir, formats, options);
|
|
55
|
+
}
|
|
56
|
+
function ensureProxies(serverProxy = {}) {
|
|
57
|
+
const httpProxies = [];
|
|
58
|
+
const wsProxies = [];
|
|
59
|
+
Object.keys(serverProxy).forEach((key) => {
|
|
60
|
+
var _a, _b;
|
|
61
|
+
const value = serverProxy[key];
|
|
62
|
+
if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")))
|
|
63
|
+
httpProxies.push(key);
|
|
64
|
+
else
|
|
65
|
+
wsProxies.push(key);
|
|
66
|
+
});
|
|
67
|
+
return { httpProxies, wsProxies };
|
|
68
|
+
}
|
|
69
|
+
function doesProxyContextMatchUrl(context, url) {
|
|
70
|
+
return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
|
|
71
|
+
}
|
|
72
|
+
function parseParams(pattern, url) {
|
|
73
|
+
const urlMatch = match(pattern, { decode: decodeURIComponent })(url) || {
|
|
74
|
+
params: {}
|
|
75
|
+
};
|
|
76
|
+
return urlMatch.params || {};
|
|
77
|
+
}
|
|
78
|
+
function urlParse(input) {
|
|
79
|
+
const url = new URL2(input, "http://example.com");
|
|
80
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
81
|
+
const query = queryParse(url.search.replace(/^\?/, ""));
|
|
82
|
+
return { pathname, query };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/compiler.ts
|
|
86
|
+
var externalizeDeps = {
|
|
87
|
+
name: "externalize-deps",
|
|
88
|
+
setup(build2) {
|
|
89
|
+
build2.onResolve({ filter: /.*/ }, ({ path: id }) => {
|
|
90
|
+
if (id[0] !== "." && !path2.isAbsolute(id))
|
|
91
|
+
return { external: true };
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var json5Loader = {
|
|
96
|
+
name: "json5-loader",
|
|
97
|
+
setup(build2) {
|
|
98
|
+
build2.onLoad({ filter: /\.json5$/ }, async ({ path: path4 }) => {
|
|
99
|
+
const content = await fsp.readFile(path4, "utf-8");
|
|
100
|
+
return {
|
|
101
|
+
contents: `export default ${JSON.stringify(JSON5.parse(content))}`,
|
|
102
|
+
loader: "js"
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var jsonLoader = {
|
|
108
|
+
name: "json-loader",
|
|
109
|
+
setup(build2) {
|
|
110
|
+
build2.onLoad({ filter: /\.json$/ }, async ({ path: path4 }) => {
|
|
111
|
+
const content = await fsp.readFile(path4, "utf-8");
|
|
112
|
+
return {
|
|
113
|
+
contents: `export default ${content}`,
|
|
114
|
+
loader: "js"
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
function aliasPlugin(alias) {
|
|
120
|
+
return {
|
|
121
|
+
name: "alias-plugin",
|
|
122
|
+
setup(build2) {
|
|
123
|
+
build2.onResolve({ filter: /.*/ }, async ({ path: id }) => {
|
|
124
|
+
const matchedEntry = alias.find(({ find: find2 }) => aliasMatches(find2, id));
|
|
125
|
+
if (!matchedEntry)
|
|
126
|
+
return null;
|
|
127
|
+
const { find, replacement } = matchedEntry;
|
|
128
|
+
const result = await build2.resolve(id.replace(find, replacement), {
|
|
129
|
+
kind: "import-statement",
|
|
130
|
+
resolveDir: replacement,
|
|
131
|
+
namespace: "file"
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
path: result.path,
|
|
135
|
+
external: false
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function aliasMatches(pattern, importee) {
|
|
142
|
+
if (pattern instanceof RegExp)
|
|
143
|
+
return pattern.test(importee);
|
|
144
|
+
if (importee.length < pattern.length)
|
|
145
|
+
return false;
|
|
146
|
+
if (importee === pattern)
|
|
147
|
+
return true;
|
|
148
|
+
return importee.startsWith(`${pattern}/`);
|
|
149
|
+
}
|
|
150
|
+
async function transformWithEsbuild(entryPoint, options) {
|
|
151
|
+
var _a;
|
|
152
|
+
const { isESM = true, define, alias } = options;
|
|
153
|
+
try {
|
|
154
|
+
const result = await build({
|
|
155
|
+
entryPoints: [entryPoint],
|
|
156
|
+
outfile: "out.js",
|
|
157
|
+
write: false,
|
|
158
|
+
target: ["node14.18", "node16"],
|
|
159
|
+
platform: "node",
|
|
160
|
+
bundle: true,
|
|
161
|
+
metafile: true,
|
|
162
|
+
format: isESM ? "esm" : "cjs",
|
|
163
|
+
define,
|
|
164
|
+
plugins: [aliasPlugin(alias), externalizeDeps, jsonLoader, json5Loader]
|
|
165
|
+
});
|
|
166
|
+
return {
|
|
167
|
+
code: result.outputFiles[0].text,
|
|
168
|
+
deps: ((_a = result.metafile) == null ? void 0 : _a.inputs) || {}
|
|
169
|
+
};
|
|
170
|
+
} catch (e) {
|
|
171
|
+
console.error(e);
|
|
172
|
+
}
|
|
173
|
+
return { code: "", deps: {} };
|
|
174
|
+
}
|
|
175
|
+
var _dirname = getDirname(import.meta.url);
|
|
176
|
+
var _require = createRequire(_dirname);
|
|
177
|
+
async function loadFromCode(filepath, code, isESM, cwd) {
|
|
178
|
+
if (isESM) {
|
|
179
|
+
const fileBase = `${filepath}.timestamp-${Date.now()}`;
|
|
180
|
+
const fileNameTmp = `${fileBase}.mjs`;
|
|
181
|
+
const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
|
|
182
|
+
await fsp.writeFile(fileNameTmp, code, "utf8");
|
|
183
|
+
try {
|
|
184
|
+
return await import(fileUrl);
|
|
185
|
+
} finally {
|
|
186
|
+
try {
|
|
187
|
+
fs2.unlinkSync(fileNameTmp);
|
|
188
|
+
} catch {
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
} else {
|
|
192
|
+
filepath = path2.resolve(cwd, filepath);
|
|
193
|
+
const extension = path2.extname(filepath);
|
|
194
|
+
const realFileName = fs2.realpathSync(filepath);
|
|
195
|
+
const loaderExt = extension in _require.extensions ? extension : ".js";
|
|
196
|
+
const defaultLoader = _require.extensions[loaderExt];
|
|
197
|
+
_require.extensions[loaderExt] = (module, filename) => {
|
|
198
|
+
if (filename === realFileName) {
|
|
199
|
+
;
|
|
200
|
+
module._compile(code, filename);
|
|
201
|
+
} else {
|
|
202
|
+
defaultLoader(module, filename);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
delete _require.cache[_require.resolve(filepath)];
|
|
206
|
+
const raw = _require(filepath);
|
|
207
|
+
_require.extensions[loaderExt] = defaultLoader;
|
|
208
|
+
return raw.__esModule ? raw : { default: raw };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/define.ts
|
|
213
|
+
import process from "node:process";
|
|
214
|
+
import colors2 from "picocolors";
|
|
215
|
+
|
|
216
|
+
// src/logger.ts
|
|
217
|
+
import { isBoolean } from "@pengzhanbo/utils";
|
|
218
|
+
import colors from "picocolors";
|
|
219
|
+
var logLevels = {
|
|
220
|
+
silent: 0,
|
|
221
|
+
error: 1,
|
|
222
|
+
warn: 2,
|
|
223
|
+
info: 3,
|
|
224
|
+
debug: 4
|
|
225
|
+
};
|
|
226
|
+
function createLogger(prefix, defaultLevel = "info") {
|
|
227
|
+
prefix = `[${prefix}]`;
|
|
228
|
+
function output(type, msg, level) {
|
|
229
|
+
level = isBoolean(level) ? level ? defaultLevel : "error" : level;
|
|
230
|
+
const thresh = logLevels[level];
|
|
231
|
+
if (thresh >= logLevels[type]) {
|
|
232
|
+
const method = type === "info" || type === "debug" ? "log" : type;
|
|
233
|
+
const tag = type === "debug" ? colors.magenta(colors.bold(prefix)) : type === "info" ? colors.cyan(colors.bold(prefix)) : type === "warn" ? colors.yellow(colors.bold(prefix)) : colors.red(colors.bold(prefix));
|
|
234
|
+
const format = `${colors.dim(
|
|
235
|
+
(/* @__PURE__ */ new Date()).toLocaleTimeString()
|
|
236
|
+
)} ${tag} ${msg}`;
|
|
237
|
+
console[method](format);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const logger = {
|
|
241
|
+
debug(msg, level = defaultLevel) {
|
|
242
|
+
output("debug", msg, level);
|
|
243
|
+
},
|
|
244
|
+
info(msg, level = defaultLevel) {
|
|
245
|
+
output("info", msg, level);
|
|
246
|
+
},
|
|
247
|
+
warn(msg, level = defaultLevel) {
|
|
248
|
+
output("warn", msg, level);
|
|
249
|
+
},
|
|
250
|
+
error(msg, level = defaultLevel) {
|
|
251
|
+
output("error", msg, level);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
return logger;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/define.ts
|
|
258
|
+
var metaEnvRe = /import\.meta\.env\.(.+)/;
|
|
259
|
+
function viteDefine(config) {
|
|
260
|
+
const logger = createLogger("vite:mock-dev-server", "warn");
|
|
261
|
+
const processNodeEnv = {};
|
|
262
|
+
const nodeEnv = process.env.NODE_ENV || config.mode;
|
|
263
|
+
Object.assign(processNodeEnv, {
|
|
264
|
+
"process.env.NODE_ENV": JSON.stringify(nodeEnv),
|
|
265
|
+
"global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
|
|
266
|
+
"globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv),
|
|
267
|
+
"__vite_process_env_NODE_ENV": JSON.stringify(nodeEnv)
|
|
268
|
+
});
|
|
269
|
+
const userDefine = {};
|
|
270
|
+
const userDefineEnv = {};
|
|
271
|
+
const defineErrorKeys = [];
|
|
272
|
+
for (const key in config.define) {
|
|
273
|
+
const val = config.define[key];
|
|
274
|
+
if (typeof val === "string") {
|
|
275
|
+
try {
|
|
276
|
+
JSON.parse(val);
|
|
277
|
+
userDefine[key] = val;
|
|
278
|
+
} catch {
|
|
279
|
+
defineErrorKeys.push(key);
|
|
280
|
+
}
|
|
281
|
+
} else {
|
|
282
|
+
userDefine[key] = JSON.stringify(val);
|
|
283
|
+
}
|
|
284
|
+
const match2 = key.match(metaEnvRe);
|
|
285
|
+
if (match2 && userDefine[key])
|
|
286
|
+
userDefineEnv[match2[1]] = `__vite__define__${userDefine[key]}`;
|
|
287
|
+
}
|
|
288
|
+
if (defineErrorKeys.length) {
|
|
289
|
+
logger.warn(
|
|
290
|
+
`The following keys: ${colors2.yellow(
|
|
291
|
+
colors2.underline(defineErrorKeys.join(", "))
|
|
292
|
+
)} declared in 'define' cannot be parsed as regular code snippets.`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
const importMetaKeys = {};
|
|
296
|
+
const importMetaFallbackKeys = {};
|
|
297
|
+
importMetaKeys["import.meta.hot"] = "undefined";
|
|
298
|
+
for (const key in config.env)
|
|
299
|
+
importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
|
|
300
|
+
Object.assign(importMetaFallbackKeys, {
|
|
301
|
+
"import.meta.env": JSON.stringify({
|
|
302
|
+
...config.env,
|
|
303
|
+
...userDefineEnv
|
|
304
|
+
}).replace(
|
|
305
|
+
/"__vite__define__(.+?)"([,}])/g,
|
|
306
|
+
(_, val, suffix) => `${val.replace(/(^\\")|(\\"$)/g, '"')}${suffix}`
|
|
307
|
+
)
|
|
308
|
+
});
|
|
309
|
+
return {
|
|
310
|
+
...importMetaKeys,
|
|
311
|
+
...userDefine,
|
|
312
|
+
...importMetaFallbackKeys,
|
|
313
|
+
...processNodeEnv
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/build.ts
|
|
318
|
+
async function generateMockServer(ctx, config, options) {
|
|
319
|
+
const include = toArray(options.include);
|
|
320
|
+
const exclude = toArray(options.exclude);
|
|
321
|
+
const define = viteDefine(config);
|
|
322
|
+
const { httpProxies } = ensureProxies(config.server.proxy || {});
|
|
323
|
+
httpProxies.push(...toArray(options.prefix));
|
|
324
|
+
const wsProxies = toArray(options.wsPrefix);
|
|
325
|
+
let pkg = {};
|
|
326
|
+
try {
|
|
327
|
+
const pkgStr = lookupFile(config.root, ["package.json"]);
|
|
328
|
+
if (pkgStr)
|
|
329
|
+
pkg = JSON.parse(pkgStr);
|
|
330
|
+
} catch {
|
|
331
|
+
}
|
|
332
|
+
const outputDir = options.build.dist;
|
|
333
|
+
const content = await generateMockEntryCode(process2.cwd(), include, exclude);
|
|
334
|
+
const mockEntry = path3.join(config.root, `mock-data-${Date.now()}.js`);
|
|
335
|
+
await fsp2.writeFile(mockEntry, content, "utf-8");
|
|
336
|
+
const { code, deps } = await transformWithEsbuild(mockEntry, {
|
|
337
|
+
define,
|
|
338
|
+
alias: config.resolve.alias
|
|
339
|
+
});
|
|
340
|
+
const mockDeps = getMockDependencies(deps, config.resolve.alias);
|
|
341
|
+
await fsp2.unlink(mockEntry);
|
|
342
|
+
const outputList = [
|
|
343
|
+
{
|
|
344
|
+
filename: path3.join(outputDir, "mock-data.js"),
|
|
345
|
+
source: code
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
filename: path3.join(outputDir, "index.js"),
|
|
349
|
+
source: generatorServerEntryCode(
|
|
350
|
+
httpProxies,
|
|
351
|
+
wsProxies,
|
|
352
|
+
options.cookiesOptions,
|
|
353
|
+
options.priority,
|
|
354
|
+
options.build.serverPort
|
|
355
|
+
)
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
filename: path3.join(outputDir, "package.json"),
|
|
359
|
+
source: generatePackageJson(pkg, mockDeps)
|
|
360
|
+
}
|
|
361
|
+
];
|
|
362
|
+
try {
|
|
363
|
+
if (path3.isAbsolute(outputDir)) {
|
|
364
|
+
await fsp2.rm(outputDir, { recursive: true });
|
|
365
|
+
fs3.mkdirSync(outputDir, { recursive: true });
|
|
366
|
+
for (const { filename, source } of outputList)
|
|
367
|
+
await fsp2.writeFile(filename, source, "utf-8");
|
|
368
|
+
} else {
|
|
369
|
+
for (const { filename, source } of outputList) {
|
|
370
|
+
ctx.emitFile({
|
|
371
|
+
type: "asset",
|
|
372
|
+
fileName: filename,
|
|
373
|
+
source
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
function getMockDependencies(deps, alias) {
|
|
381
|
+
const list = /* @__PURE__ */ new Set();
|
|
382
|
+
const excludeDeps = [name, "connect", "cors"];
|
|
383
|
+
const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
|
|
384
|
+
Object.keys(deps).forEach((mPath) => {
|
|
385
|
+
const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
|
|
386
|
+
imports.forEach((dep) => {
|
|
387
|
+
if (!excludeDeps.includes(dep) && !isCore(dep))
|
|
388
|
+
list.add(dep);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
return Array.from(list);
|
|
392
|
+
}
|
|
393
|
+
function generatePackageJson(pkg, mockDeps) {
|
|
394
|
+
const { dependencies = {}, devDependencies = {} } = pkg;
|
|
395
|
+
const dependents = { ...dependencies, ...devDependencies };
|
|
396
|
+
const mockPkg = {
|
|
397
|
+
name: "mock-server",
|
|
398
|
+
type: "module",
|
|
399
|
+
scripts: {
|
|
400
|
+
start: "node index.js"
|
|
401
|
+
},
|
|
402
|
+
dependencies: {
|
|
403
|
+
"connect": "^3.7.0",
|
|
404
|
+
"vite-plugin-mock-dev-server": `^${version}`,
|
|
405
|
+
"cors": "^2.8.5"
|
|
406
|
+
},
|
|
407
|
+
pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
|
|
408
|
+
};
|
|
409
|
+
mockDeps.forEach((dep) => {
|
|
410
|
+
mockPkg.dependencies[dep] = dependents[dep] || "latest";
|
|
411
|
+
});
|
|
412
|
+
return JSON.stringify(mockPkg, null, 2);
|
|
413
|
+
}
|
|
414
|
+
function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, port = 8080) {
|
|
415
|
+
return `import { createServer } from 'node:http';
|
|
2
416
|
import connect from 'connect';
|
|
3
417
|
import corsMiddleware from 'cors';
|
|
4
|
-
import { baseMiddleware, mockWebSocket } from 'vite-plugin-mock-dev-server';
|
|
418
|
+
import { baseMiddleware, mockWebSocket, createLogger } from 'vite-plugin-mock-dev-server';
|
|
5
419
|
import mockData from './mock-data.js';
|
|
6
420
|
|
|
7
421
|
const app = connect();
|
|
8
422
|
const server = createServer(app);
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const
|
|
423
|
+
const logger = createLogger('mock-server', 'error');
|
|
424
|
+
const httpProxies = ${JSON.stringify(httpProxies)};
|
|
425
|
+
const wsProxies = ${JSON.stringify(wsProxies)};
|
|
426
|
+
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
427
|
+
const priority = ${JSON.stringify(priority)};
|
|
13
428
|
|
|
14
|
-
mockWebSocket({
|
|
429
|
+
mockWebSocket({
|
|
430
|
+
loader: { mockData },
|
|
431
|
+
httpServer: server,
|
|
432
|
+
proxies: wsProxies,
|
|
433
|
+
cookiesOptions,
|
|
434
|
+
logger,
|
|
435
|
+
});
|
|
15
436
|
|
|
16
437
|
app.use(corsMiddleware());
|
|
17
438
|
app.use(baseMiddleware({ mockData }, {
|
|
@@ -19,15 +440,31 @@ app.use(baseMiddleware({ mockData }, {
|
|
|
19
440
|
proxies: httpProxies,
|
|
20
441
|
priority,
|
|
21
442
|
cookiesOptions,
|
|
443
|
+
logger,
|
|
22
444
|
}));
|
|
23
445
|
|
|
24
|
-
server.listen(${
|
|
446
|
+
server.listen(${port});
|
|
25
447
|
|
|
26
|
-
console.log('listen: http://localhost:${
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
448
|
+
console.log('listen: http://localhost:${port}');
|
|
449
|
+
`;
|
|
450
|
+
}
|
|
451
|
+
async function generateMockEntryCode(cwd, include, exclude) {
|
|
452
|
+
const includePaths = await fg(include, { cwd });
|
|
453
|
+
const includeFilter = createFilter(include, exclude, {
|
|
454
|
+
resolve: false
|
|
455
|
+
});
|
|
456
|
+
const mockFiles = includePaths.filter(includeFilter);
|
|
457
|
+
let importers = "";
|
|
458
|
+
let exporters = "";
|
|
459
|
+
mockFiles.forEach((filepath, index) => {
|
|
460
|
+
const file = normalizePath(path3.join(cwd, filepath));
|
|
461
|
+
importers += `import * as m${index} from '${file}';
|
|
462
|
+
`;
|
|
463
|
+
exporters += `m${index}, `;
|
|
464
|
+
});
|
|
465
|
+
return `import { transformMockData } from 'vite-plugin-mock-dev-server';
|
|
466
|
+
${importers}
|
|
467
|
+
const exporters = [${exporters}];
|
|
31
468
|
const mockList = exporters.map((raw) => {
|
|
32
469
|
let mockConfig
|
|
33
470
|
if (raw.default) {
|
|
@@ -35,26 +472,1217 @@ const mockList = exporters.map((raw) => {
|
|
|
35
472
|
} else {
|
|
36
473
|
mockConfig = []
|
|
37
474
|
Object.keys(raw || {}).forEach((key) => {
|
|
38
|
-
isArray(raw[key])
|
|
475
|
+
Array.isArray(raw[key])
|
|
39
476
|
? mockConfig.push(...raw[key])
|
|
40
477
|
: mockConfig.push(raw[key])
|
|
41
478
|
})
|
|
42
479
|
}
|
|
43
480
|
return mockConfig
|
|
44
481
|
});
|
|
45
|
-
export default transformMockData(mockList)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
482
|
+
export default transformMockData(mockList);`;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/mockMiddleware.ts
|
|
486
|
+
import { isBoolean as isBoolean2, toArray as toArray3 } from "@pengzhanbo/utils";
|
|
487
|
+
import cors from "cors";
|
|
488
|
+
import { pathToRegexp as pathToRegexp4 } from "path-to-regexp";
|
|
489
|
+
|
|
490
|
+
// src/baseMiddleware.ts
|
|
491
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
492
|
+
import {
|
|
493
|
+
isArray as isArray3,
|
|
494
|
+
isEmptyObject as isEmptyObject2,
|
|
495
|
+
isFunction,
|
|
496
|
+
random,
|
|
497
|
+
sleep,
|
|
498
|
+
timestamp
|
|
499
|
+
} from "@pengzhanbo/utils";
|
|
500
|
+
import Cookies from "cookies";
|
|
501
|
+
import HTTP_STATUS from "http-status";
|
|
502
|
+
import * as mime from "mime-types";
|
|
503
|
+
import { pathToRegexp as pathToRegexp2 } from "path-to-regexp";
|
|
504
|
+
import colors3 from "picocolors";
|
|
505
|
+
|
|
506
|
+
// src/matchingWeight.ts
|
|
507
|
+
import {
|
|
508
|
+
isArray,
|
|
509
|
+
isEmptyObject,
|
|
510
|
+
isString,
|
|
511
|
+
sortBy,
|
|
512
|
+
uniq
|
|
513
|
+
} from "@pengzhanbo/utils";
|
|
514
|
+
import { parse, pathToRegexp } from "path-to-regexp";
|
|
515
|
+
var tokensCache = {};
|
|
516
|
+
function getTokens(rule) {
|
|
517
|
+
if (tokensCache[rule])
|
|
518
|
+
return tokensCache[rule];
|
|
519
|
+
const tks = parse(rule);
|
|
520
|
+
const tokens = [];
|
|
521
|
+
for (const tk of tks) {
|
|
522
|
+
if (!isString(tk)) {
|
|
523
|
+
tokens.push(tk);
|
|
524
|
+
} else {
|
|
525
|
+
const hasPrefix = tk[0] === "/";
|
|
526
|
+
const subTks = hasPrefix ? tk.slice(1).split("/") : tk.split("/");
|
|
527
|
+
tokens.push(
|
|
528
|
+
`${hasPrefix ? "/" : ""}${subTks[0]}`,
|
|
529
|
+
...subTks.slice(1).map((t) => `/${t}`)
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
tokensCache[rule] = tokens;
|
|
534
|
+
return tokens;
|
|
535
|
+
}
|
|
536
|
+
function getHighest(rules) {
|
|
537
|
+
let weights = rules.map((rule) => getTokens(rule).length);
|
|
538
|
+
weights = weights.length === 0 ? [1] : weights;
|
|
539
|
+
return Math.max(...weights) + 2;
|
|
540
|
+
}
|
|
541
|
+
function sortFn(rule) {
|
|
542
|
+
const tokens = getTokens(rule);
|
|
543
|
+
let w = 0;
|
|
544
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
545
|
+
const token = tokens[i];
|
|
546
|
+
if (!isString(token))
|
|
547
|
+
w += 10 ** (i + 1);
|
|
548
|
+
w += 10 ** (i + 1);
|
|
549
|
+
}
|
|
550
|
+
return w;
|
|
551
|
+
}
|
|
552
|
+
function preSort(rules) {
|
|
553
|
+
let matched = [];
|
|
554
|
+
const preMatch = [];
|
|
555
|
+
for (const rule of rules) {
|
|
556
|
+
const tokens = getTokens(rule);
|
|
557
|
+
const len = tokens.filter((token) => typeof token !== "string").length;
|
|
558
|
+
if (!preMatch[len])
|
|
559
|
+
preMatch[len] = [];
|
|
560
|
+
preMatch[len].push(rule);
|
|
561
|
+
}
|
|
562
|
+
for (const match2 of preMatch.filter((v) => v && v.length > 0))
|
|
563
|
+
matched = [...matched, ...sortBy(match2, sortFn).reverse()];
|
|
564
|
+
return matched;
|
|
565
|
+
}
|
|
566
|
+
function defaultPriority(rules) {
|
|
567
|
+
const highest = getHighest(rules);
|
|
568
|
+
return sortBy(rules, (rule) => {
|
|
569
|
+
const tokens = getTokens(rule);
|
|
570
|
+
const dym = tokens.filter((token) => typeof token !== "string");
|
|
571
|
+
if (dym.length === 0)
|
|
572
|
+
return 0;
|
|
573
|
+
let weight = dym.length;
|
|
574
|
+
let exp = 0;
|
|
575
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
576
|
+
const token = tokens[i];
|
|
577
|
+
const isDynamic = !isString(token);
|
|
578
|
+
const {
|
|
579
|
+
pattern = "",
|
|
580
|
+
modifier,
|
|
581
|
+
prefix,
|
|
582
|
+
name: name2
|
|
583
|
+
} = isDynamic ? token : {};
|
|
584
|
+
const isGlob = pattern && pattern.includes(".*");
|
|
585
|
+
const isSlash = prefix === "/";
|
|
586
|
+
const isNamed = isString(name2);
|
|
587
|
+
exp += isDynamic && isSlash ? 1 : 0;
|
|
588
|
+
if (i === tokens.length - 1 && isGlob) {
|
|
589
|
+
weight += 5 * 10 ** (tokens.length === 1 ? highest + 1 : highest);
|
|
590
|
+
} else {
|
|
591
|
+
if (isGlob) {
|
|
592
|
+
weight += 3 * 10 ** (highest - 1);
|
|
593
|
+
} else if (pattern) {
|
|
594
|
+
if (isSlash) {
|
|
595
|
+
weight += (isNamed ? 2 : 1) * 10 ** (exp + 1);
|
|
596
|
+
} else {
|
|
597
|
+
weight -= 1 * 10 ** exp;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (modifier === "+")
|
|
602
|
+
weight += 1 * 10 ** (highest - 1);
|
|
603
|
+
if (modifier === "*")
|
|
604
|
+
weight += 1 * 10 ** (highest - 1) + 1;
|
|
605
|
+
if (modifier === "?")
|
|
606
|
+
weight += 1 * 10 ** (exp + (isSlash ? 1 : 0));
|
|
607
|
+
}
|
|
608
|
+
return weight;
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
function matchingWeight(rules, url, priority) {
|
|
612
|
+
let matched = defaultPriority(
|
|
613
|
+
preSort(rules.filter((rule) => pathToRegexp(rule).test(url)))
|
|
614
|
+
);
|
|
615
|
+
const { global = [], special = {} } = priority;
|
|
616
|
+
if (global.length === 0 && isEmptyObject(special) || matched.length === 0)
|
|
617
|
+
return matched;
|
|
618
|
+
const [statics, dynamics] = twoPartMatch(matched);
|
|
619
|
+
const globalMatch = global.filter((rule) => dynamics.includes(rule));
|
|
620
|
+
if (globalMatch.length > 0) {
|
|
621
|
+
matched = uniq([...statics, ...globalMatch, ...dynamics]);
|
|
622
|
+
}
|
|
623
|
+
if (isEmptyObject(special))
|
|
624
|
+
return matched;
|
|
625
|
+
const specialRule = Object.keys(special).filter(
|
|
626
|
+
(rule) => matched.includes(rule)
|
|
627
|
+
)[0];
|
|
628
|
+
if (!specialRule)
|
|
629
|
+
return matched;
|
|
630
|
+
const options = special[specialRule];
|
|
631
|
+
const { rules: lowerRules, when } = isArray(options) ? { rules: options, when: [] } : options;
|
|
632
|
+
if (lowerRules.includes(matched[0])) {
|
|
633
|
+
if (when.length === 0 || when.some((path4) => pathToRegexp(path4).test(url))) {
|
|
634
|
+
matched = uniq([specialRule, ...matched]);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return matched;
|
|
638
|
+
}
|
|
639
|
+
function twoPartMatch(rules) {
|
|
640
|
+
const statics = [];
|
|
641
|
+
const dynamics = [];
|
|
642
|
+
for (const rule of rules) {
|
|
643
|
+
const tokens = getTokens(rule);
|
|
644
|
+
const dym = tokens.filter((token) => typeof token !== "string");
|
|
645
|
+
if (dym.length > 0)
|
|
646
|
+
dynamics.push(rule);
|
|
647
|
+
else
|
|
648
|
+
statics.push(rule);
|
|
649
|
+
}
|
|
650
|
+
return [statics, dynamics];
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// src/parseReqBody.ts
|
|
654
|
+
import bodyParser from "co-body";
|
|
655
|
+
import formidable from "formidable";
|
|
656
|
+
async function parseReqBody(req, options) {
|
|
657
|
+
var _a;
|
|
658
|
+
const method = req.method.toUpperCase();
|
|
659
|
+
if (["GET", "DELETE", "HEAD"].includes(method))
|
|
660
|
+
return void 0;
|
|
661
|
+
const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
|
|
662
|
+
try {
|
|
663
|
+
if (type.startsWith("application/json"))
|
|
664
|
+
return await bodyParser.json(req);
|
|
665
|
+
if (type.startsWith("application/x-www-form-urlencoded"))
|
|
666
|
+
return await bodyParser.form(req);
|
|
667
|
+
if (type.startsWith("text/plain"))
|
|
668
|
+
return await bodyParser.text(req);
|
|
669
|
+
if (type.startsWith("multipart/form-data"))
|
|
670
|
+
return await parseMultipart(req, options);
|
|
671
|
+
} catch (e) {
|
|
672
|
+
console.error(e);
|
|
673
|
+
}
|
|
674
|
+
return void 0;
|
|
675
|
+
}
|
|
676
|
+
async function parseMultipart(req, options) {
|
|
677
|
+
const form = formidable(options);
|
|
678
|
+
return new Promise((resolve, reject) => {
|
|
679
|
+
form.parse(req, (error, fields, files) => {
|
|
680
|
+
if (error) {
|
|
681
|
+
reject(error);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
resolve({ ...fields, ...files });
|
|
685
|
+
});
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// src/requestRecovery.ts
|
|
690
|
+
import { Buffer } from "node:buffer";
|
|
691
|
+
var cache = /* @__PURE__ */ new WeakMap();
|
|
692
|
+
function collectRequest(req) {
|
|
693
|
+
const chunks = [];
|
|
694
|
+
req.addListener("data", (chunk) => {
|
|
695
|
+
chunks.push(Buffer.from(chunk));
|
|
696
|
+
});
|
|
697
|
+
req.addListener("end", () => {
|
|
698
|
+
if (chunks.length)
|
|
699
|
+
cache.set(req, Buffer.concat(chunks));
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
function recoverRequest(config) {
|
|
703
|
+
if (!config.server)
|
|
704
|
+
return;
|
|
705
|
+
const proxies = config.server.proxy || {};
|
|
706
|
+
Object.keys(proxies).forEach((key) => {
|
|
707
|
+
const target = proxies[key];
|
|
708
|
+
const options = typeof target === "string" ? { target } : target;
|
|
709
|
+
if (options.ws)
|
|
710
|
+
return;
|
|
711
|
+
const { configure, ...rest } = options;
|
|
712
|
+
proxies[key] = {
|
|
713
|
+
...rest,
|
|
714
|
+
configure(proxy, options2) {
|
|
715
|
+
configure == null ? void 0 : configure(proxy, options2);
|
|
716
|
+
proxy.on("proxyReq", (proxyReq, req) => {
|
|
717
|
+
const buffer = cache.get(req);
|
|
718
|
+
if (buffer) {
|
|
719
|
+
cache.delete(req);
|
|
720
|
+
if (!proxyReq.headersSent)
|
|
721
|
+
proxyReq.setHeader("Content-Length", buffer.byteLength);
|
|
722
|
+
if (!proxyReq.writableEnded)
|
|
723
|
+
proxyReq.write(buffer);
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// src/validator.ts
|
|
732
|
+
import { isArray as isArray2, isObject } from "@pengzhanbo/utils";
|
|
733
|
+
function validate(request, validator) {
|
|
734
|
+
return isObjectSubset(request.headers, validator.headers) && isObjectSubset(request.body, validator.body) && isObjectSubset(request.params, validator.params) && isObjectSubset(request.query, validator.query) && isObjectSubset(request.refererQuery, validator.refererQuery);
|
|
735
|
+
}
|
|
736
|
+
function isObjectSubset(source, target) {
|
|
737
|
+
if (!target)
|
|
738
|
+
return true;
|
|
739
|
+
for (const key in target) {
|
|
740
|
+
if (!isIncluded(source[key], target[key]))
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
return true;
|
|
744
|
+
}
|
|
745
|
+
function isIncluded(source, target) {
|
|
746
|
+
if (isArray2(source) && isArray2(target)) {
|
|
747
|
+
const seen = /* @__PURE__ */ new Set();
|
|
748
|
+
return target.every(
|
|
749
|
+
(ti) => source.some((si, i) => {
|
|
750
|
+
if (seen.has(i))
|
|
751
|
+
return false;
|
|
752
|
+
const included = isIncluded(si, ti);
|
|
753
|
+
if (included)
|
|
754
|
+
seen.add(i);
|
|
755
|
+
return included;
|
|
756
|
+
})
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
if (isObject(source) && isObject(target))
|
|
760
|
+
return isObjectSubset(source, target);
|
|
761
|
+
return Object.is(source, target);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/baseMiddleware.ts
|
|
765
|
+
function baseMiddleware(mockLoader, {
|
|
766
|
+
formidableOptions = {},
|
|
767
|
+
proxies,
|
|
768
|
+
cookiesOptions,
|
|
769
|
+
logger,
|
|
770
|
+
priority = {}
|
|
771
|
+
}) {
|
|
772
|
+
return async function(req, res, next) {
|
|
773
|
+
const startTime = timestamp();
|
|
774
|
+
const { query, pathname } = urlParse(req.url);
|
|
775
|
+
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
|
|
776
|
+
return next();
|
|
777
|
+
const mockData = mockLoader.mockData;
|
|
778
|
+
const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
|
|
779
|
+
if (mockUrls.length === 0)
|
|
780
|
+
return next();
|
|
781
|
+
collectRequest(req);
|
|
782
|
+
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
783
|
+
const reqBody = await parseReqBody(req, formidableOptions);
|
|
784
|
+
const cookies = new Cookies(req, res, cookiesOptions);
|
|
785
|
+
const getCookie = cookies.get.bind(cookies);
|
|
786
|
+
const method = req.method.toUpperCase();
|
|
787
|
+
let mock;
|
|
788
|
+
let _mockUrl;
|
|
789
|
+
for (const mockUrl of mockUrls) {
|
|
790
|
+
mock = fineMock(mockData[mockUrl], logger, {
|
|
791
|
+
pathname,
|
|
792
|
+
method,
|
|
793
|
+
request: {
|
|
794
|
+
query,
|
|
795
|
+
refererQuery,
|
|
796
|
+
body: reqBody,
|
|
797
|
+
headers: req.headers,
|
|
798
|
+
getCookie
|
|
799
|
+
}
|
|
800
|
+
});
|
|
801
|
+
if (mock) {
|
|
802
|
+
_mockUrl = mockUrl;
|
|
803
|
+
break;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
if (!mock) {
|
|
807
|
+
const matched = mockUrls.map(
|
|
808
|
+
(m) => m === _mockUrl ? colors3.underline(colors3.bold(m)) : colors3.dim(m)
|
|
809
|
+
).join(", ");
|
|
810
|
+
logger.warn(
|
|
811
|
+
`${colors3.green(
|
|
812
|
+
pathname
|
|
813
|
+
)} matches ${matched} , but mock data is not found.`
|
|
814
|
+
);
|
|
815
|
+
return next();
|
|
816
|
+
}
|
|
817
|
+
const request = req;
|
|
818
|
+
const response = res;
|
|
819
|
+
request.body = reqBody;
|
|
820
|
+
request.query = query;
|
|
821
|
+
request.refererQuery = refererQuery;
|
|
822
|
+
request.params = parseParams(mock.url, pathname);
|
|
823
|
+
request.getCookie = getCookie;
|
|
824
|
+
response.setCookie = cookies.set.bind(cookies);
|
|
825
|
+
const {
|
|
826
|
+
body,
|
|
827
|
+
delay,
|
|
828
|
+
type = "json",
|
|
829
|
+
response: responseFn,
|
|
830
|
+
status = 200,
|
|
831
|
+
statusText,
|
|
832
|
+
log: logLevel,
|
|
833
|
+
__filepath__: filepath
|
|
834
|
+
} = mock;
|
|
835
|
+
responseStatus(response, status, statusText);
|
|
836
|
+
await provideHeaders(request, response, mock, logger);
|
|
837
|
+
await provideCookies(request, response, mock, logger);
|
|
838
|
+
logger.info(requestLog(request, filepath), logLevel);
|
|
839
|
+
logger.debug(
|
|
840
|
+
`${colors3.magenta("DEBUG")} ${colors3.underline(
|
|
841
|
+
pathname
|
|
842
|
+
)} matches: [ ${mockUrls.map(
|
|
843
|
+
(m) => m === _mockUrl ? colors3.underline(colors3.bold(m)) : colors3.dim(m)
|
|
844
|
+
).join(", ")} ]
|
|
845
|
+
`
|
|
846
|
+
);
|
|
847
|
+
if (body) {
|
|
848
|
+
try {
|
|
849
|
+
const content = isFunction(body) ? await body(request) : body;
|
|
850
|
+
await realDelay(startTime, delay);
|
|
851
|
+
sendData(response, content, type);
|
|
852
|
+
} catch (e) {
|
|
853
|
+
logger.error(
|
|
854
|
+
`${colors3.red(
|
|
855
|
+
`mock error at ${pathname}`
|
|
856
|
+
)}
|
|
857
|
+
${e}
|
|
858
|
+
at body (${colors3.underline(filepath)})`,
|
|
859
|
+
logLevel
|
|
860
|
+
);
|
|
861
|
+
responseStatus(response, 500);
|
|
862
|
+
res.end("");
|
|
863
|
+
}
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (responseFn) {
|
|
867
|
+
try {
|
|
868
|
+
await realDelay(startTime, delay);
|
|
869
|
+
await responseFn(request, response, next);
|
|
870
|
+
} catch (e) {
|
|
871
|
+
logger.error(
|
|
872
|
+
`${colors3.red(
|
|
873
|
+
`mock error at ${pathname}`
|
|
874
|
+
)}
|
|
875
|
+
${e}
|
|
876
|
+
at response (${colors3.underline(filepath)})`,
|
|
877
|
+
logLevel
|
|
878
|
+
);
|
|
879
|
+
responseStatus(response, 500);
|
|
880
|
+
res.end("");
|
|
881
|
+
}
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
res.end("");
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
function fineMock(mockList, logger, {
|
|
888
|
+
pathname,
|
|
889
|
+
method,
|
|
890
|
+
request
|
|
891
|
+
}) {
|
|
892
|
+
return mockList.find((mock) => {
|
|
893
|
+
if (!pathname || !mock || !mock.url || mock.ws === true)
|
|
894
|
+
return false;
|
|
895
|
+
const methods = mock.method ? isArray3(mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
|
|
896
|
+
if (!methods.includes(method))
|
|
897
|
+
return false;
|
|
898
|
+
const hasMock = pathToRegexp2(mock.url).test(pathname);
|
|
899
|
+
if (hasMock && mock.validator) {
|
|
900
|
+
const params = parseParams(mock.url, pathname);
|
|
901
|
+
if (isFunction(mock.validator)) {
|
|
902
|
+
return mock.validator({ params, ...request });
|
|
903
|
+
} else {
|
|
904
|
+
try {
|
|
905
|
+
return validate({ params, ...request }, mock.validator);
|
|
906
|
+
} catch (e) {
|
|
907
|
+
const file = mock.__filepath__;
|
|
908
|
+
logger.error(
|
|
909
|
+
`${colors3.red(
|
|
910
|
+
`mock error at ${pathname}`
|
|
911
|
+
)}
|
|
912
|
+
${e}
|
|
913
|
+
at validator (${colors3.underline(file)})`,
|
|
914
|
+
mock.log
|
|
915
|
+
);
|
|
916
|
+
return false;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return hasMock;
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
function responseStatus(response, status = 200, statusText) {
|
|
924
|
+
response.statusCode = status;
|
|
925
|
+
response.statusMessage = statusText || getHTTPStatusText(status);
|
|
926
|
+
}
|
|
927
|
+
async function provideHeaders(req, res, mock, logger) {
|
|
928
|
+
const { headers, type = "json" } = mock;
|
|
929
|
+
const filepath = mock.__filepath__;
|
|
930
|
+
const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
|
|
931
|
+
contentType2 && res.setHeader("Content-Type", contentType2);
|
|
932
|
+
res.setHeader("Cache-Control", "no-cache,max-age=0");
|
|
933
|
+
res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
|
|
934
|
+
res.setHeader("X-File-Path", filepath);
|
|
935
|
+
if (!headers)
|
|
936
|
+
return;
|
|
937
|
+
try {
|
|
938
|
+
const raw = isFunction(headers) ? await headers(req) : headers;
|
|
939
|
+
Object.keys(raw).forEach((key) => {
|
|
940
|
+
res.setHeader(key, raw[key]);
|
|
941
|
+
});
|
|
942
|
+
} catch (e) {
|
|
943
|
+
logger.error(
|
|
944
|
+
`${colors3.red(
|
|
945
|
+
`mock error at ${req.url.split("?")[0]}`
|
|
946
|
+
)}
|
|
947
|
+
${e}
|
|
948
|
+
at headers (${colors3.underline(filepath)})`,
|
|
949
|
+
mock.log
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
async function provideCookies(req, res, mock, logger) {
|
|
954
|
+
const { cookies } = mock;
|
|
955
|
+
const filepath = mock.__filepath__;
|
|
956
|
+
if (!cookies)
|
|
957
|
+
return;
|
|
958
|
+
try {
|
|
959
|
+
const raw = isFunction(cookies) ? await cookies(req) : cookies;
|
|
960
|
+
Object.keys(raw).forEach((key) => {
|
|
961
|
+
const cookie = raw[key];
|
|
962
|
+
if (isArray3(cookie)) {
|
|
963
|
+
const [value, options] = cookie;
|
|
964
|
+
res.setCookie(key, value, options);
|
|
965
|
+
} else {
|
|
966
|
+
res.setCookie(key, cookie);
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
} catch (e) {
|
|
970
|
+
logger.error(
|
|
971
|
+
`${colors3.red(
|
|
972
|
+
`mock error at ${req.url.split("?")[0]}`
|
|
973
|
+
)}
|
|
974
|
+
${e}
|
|
975
|
+
at cookies (${colors3.underline(filepath)})`,
|
|
976
|
+
mock.log
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
function sendData(res, raw, type) {
|
|
981
|
+
if (isReadableStream(raw)) {
|
|
982
|
+
raw.pipe(res);
|
|
983
|
+
} else if (Buffer2.isBuffer(raw)) {
|
|
984
|
+
res.end(type === "text" || type === "json" ? raw.toString("utf-8") : raw);
|
|
985
|
+
} else {
|
|
986
|
+
const content = typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
987
|
+
res.end(type === "buffer" ? Buffer2.from(content) : content);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
async function realDelay(startTime, delay) {
|
|
991
|
+
if (!delay || typeof delay === "number" && delay <= 0 || isArray3(delay) && delay.length !== 2)
|
|
992
|
+
return;
|
|
993
|
+
let realDelay2 = 0;
|
|
994
|
+
if (isArray3(delay)) {
|
|
995
|
+
const [min, max] = delay;
|
|
996
|
+
realDelay2 = random(min, max);
|
|
997
|
+
} else {
|
|
998
|
+
realDelay2 = delay - (timestamp() - startTime);
|
|
999
|
+
}
|
|
1000
|
+
if (realDelay2 > 0)
|
|
1001
|
+
await sleep(realDelay2);
|
|
1002
|
+
}
|
|
1003
|
+
function getHTTPStatusText(status) {
|
|
1004
|
+
return HTTP_STATUS[status] || "Unknown";
|
|
1005
|
+
}
|
|
1006
|
+
function requestLog(request, filepath) {
|
|
1007
|
+
const { url, method, query, params, body } = request;
|
|
1008
|
+
let { pathname } = new URL(url, "http://example.com");
|
|
1009
|
+
pathname = colors3.green(decodeURIComponent(pathname));
|
|
1010
|
+
const format = (prefix, data) => {
|
|
1011
|
+
return !data || isEmptyObject2(data) ? "" : ` ${colors3.gray(`${prefix}:`)}${JSON.stringify(data)}`;
|
|
1012
|
+
};
|
|
1013
|
+
const ms = colors3.magenta(colors3.bold(method));
|
|
1014
|
+
const qs = format("query", query);
|
|
1015
|
+
const ps = format("params", params);
|
|
1016
|
+
const bs = format("body", body);
|
|
1017
|
+
const file = ` ${colors3.dim(colors3.underline(`(${filepath})`))}`;
|
|
1018
|
+
return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// src/MockLoader.ts
|
|
1022
|
+
import EventEmitter from "node:events";
|
|
1023
|
+
import process3 from "node:process";
|
|
1024
|
+
import { hasOwn, isArray as isArray5, promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
|
|
1025
|
+
import chokidar from "chokidar";
|
|
1026
|
+
import fastGlob from "fast-glob";
|
|
1027
|
+
import { createFilter as createFilter2, normalizePath as normalizePath2 } from "vite";
|
|
1028
|
+
|
|
1029
|
+
// src/transform.ts
|
|
1030
|
+
import {
|
|
1031
|
+
isArray as isArray4,
|
|
1032
|
+
isEmptyObject as isEmptyObject3,
|
|
1033
|
+
isFunction as isFunction2,
|
|
1034
|
+
isObject as isObject2,
|
|
1035
|
+
sortBy as sortBy2
|
|
1036
|
+
} from "@pengzhanbo/utils";
|
|
1037
|
+
function transformMockData(mockList) {
|
|
1038
|
+
const list = [];
|
|
1039
|
+
for (const [, handle] of mockList.entries()) {
|
|
1040
|
+
if (handle)
|
|
1041
|
+
isArray4(handle) ? list.push(...handle) : list.push(handle);
|
|
1042
|
+
}
|
|
1043
|
+
const mocks = {};
|
|
1044
|
+
list.filter((mock) => isObject2(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
|
|
1045
|
+
const { pathname, query } = urlParse(mock.url);
|
|
1046
|
+
const list2 = mocks[pathname] ??= [];
|
|
1047
|
+
const current = { ...mock, url: pathname };
|
|
1048
|
+
if (current.ws !== true) {
|
|
1049
|
+
const validator = current.validator;
|
|
1050
|
+
if (!isEmptyObject3(query)) {
|
|
1051
|
+
if (isFunction2(validator)) {
|
|
1052
|
+
current.validator = function(request) {
|
|
1053
|
+
return isObjectSubset(request.query, query) && validator(request);
|
|
1054
|
+
};
|
|
1055
|
+
} else if (validator) {
|
|
1056
|
+
current.validator = { ...validator };
|
|
1057
|
+
current.validator.query = current.validator.query ? { ...query, ...current.validator.query } : query;
|
|
1058
|
+
} else {
|
|
1059
|
+
current.validator = { query };
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
list2.push(current);
|
|
1064
|
+
});
|
|
1065
|
+
Object.keys(mocks).forEach((key) => {
|
|
1066
|
+
mocks[key] = sortByValidator(mocks[key]);
|
|
1067
|
+
});
|
|
1068
|
+
return mocks;
|
|
1069
|
+
}
|
|
1070
|
+
function sortByValidator(mocks) {
|
|
1071
|
+
return sortBy2(mocks, (item) => {
|
|
1072
|
+
if (item.ws === true)
|
|
1073
|
+
return 0;
|
|
1074
|
+
const { validator } = item;
|
|
1075
|
+
if (!validator || isEmptyObject3(validator))
|
|
1076
|
+
return 2;
|
|
1077
|
+
if (isFunction2(validator))
|
|
1078
|
+
return 0;
|
|
1079
|
+
const count = Object.keys(validator).reduce(
|
|
1080
|
+
(prev, key) => prev + keysCount(validator[key]),
|
|
1081
|
+
0
|
|
1082
|
+
);
|
|
1083
|
+
return 1 / count;
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
function keysCount(obj) {
|
|
1087
|
+
if (!obj)
|
|
1088
|
+
return 0;
|
|
1089
|
+
return Object.keys(obj).length;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// src/MockLoader.ts
|
|
1093
|
+
var MockLoader = class extends EventEmitter {
|
|
1094
|
+
constructor(options) {
|
|
1095
|
+
super();
|
|
1096
|
+
this.options = options;
|
|
1097
|
+
this.cwd = options.cwd || process3.cwd();
|
|
1098
|
+
try {
|
|
1099
|
+
const pkg = lookupFile(this.cwd, ["package.json"]);
|
|
1100
|
+
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
1101
|
+
} catch (e) {
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
moduleCache = /* @__PURE__ */ new Map();
|
|
1105
|
+
moduleDeps = /* @__PURE__ */ new Map();
|
|
1106
|
+
cwd;
|
|
1107
|
+
mockWatcher;
|
|
1108
|
+
depsWatcher;
|
|
1109
|
+
moduleType = "cjs";
|
|
1110
|
+
_mockData = {};
|
|
1111
|
+
get mockData() {
|
|
1112
|
+
return this._mockData;
|
|
1113
|
+
}
|
|
1114
|
+
load() {
|
|
1115
|
+
const { include, exclude } = this.options;
|
|
1116
|
+
const includeFilter = createFilter2(include, exclude, {
|
|
1117
|
+
resolve: false
|
|
1118
|
+
});
|
|
1119
|
+
fastGlob(include, { cwd: this.cwd }).then(
|
|
1120
|
+
(files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))
|
|
1121
|
+
).then((loadList) => promiseParallel(loadList, 10)).then(() => this.updateMockList());
|
|
1122
|
+
this.watchMockEntry();
|
|
1123
|
+
this.watchDeps();
|
|
1124
|
+
let timer = null;
|
|
1125
|
+
this.on("mock:update", async (filepath) => {
|
|
1126
|
+
if (!includeFilter(filepath))
|
|
1127
|
+
return;
|
|
1128
|
+
await this.loadMock(filepath);
|
|
1129
|
+
timer && clearImmediate(timer);
|
|
1130
|
+
timer = setImmediate(() => {
|
|
1131
|
+
this.updateMockList();
|
|
1132
|
+
this.emit("mock:update-end", filepath);
|
|
1133
|
+
timer = null;
|
|
1134
|
+
});
|
|
1135
|
+
});
|
|
1136
|
+
this.on("mock:unlink", async (filepath) => {
|
|
1137
|
+
if (!includeFilter(filepath))
|
|
1138
|
+
return;
|
|
1139
|
+
this.moduleCache.delete(filepath);
|
|
1140
|
+
this.updateMockList();
|
|
1141
|
+
this.emit("mock:update-end", filepath);
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
watchMockEntry() {
|
|
1145
|
+
const { include } = this.options;
|
|
1146
|
+
const [firstGlob, ...otherGlob] = include;
|
|
1147
|
+
const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
|
|
1148
|
+
ignoreInitial: true,
|
|
1149
|
+
cwd: this.cwd
|
|
1150
|
+
});
|
|
1151
|
+
otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
|
|
1152
|
+
watcher.on("add", async (filepath) => {
|
|
1153
|
+
filepath = normalizePath2(filepath);
|
|
1154
|
+
this.emit("mock:update", filepath);
|
|
1155
|
+
debug("watcher:add", filepath);
|
|
1156
|
+
});
|
|
1157
|
+
watcher.on("change", async (filepath) => {
|
|
1158
|
+
filepath = normalizePath2(filepath);
|
|
1159
|
+
this.emit("mock:update", filepath);
|
|
1160
|
+
debug("watcher:change", filepath);
|
|
1161
|
+
});
|
|
1162
|
+
watcher.on("unlink", async (filepath) => {
|
|
1163
|
+
filepath = normalizePath2(filepath);
|
|
1164
|
+
this.emit("mock:unlink", filepath);
|
|
1165
|
+
debug("watcher:unlink", filepath);
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* 监听 mock文件依赖的本地文件变动,
|
|
1170
|
+
* mock依赖文件更新,mock文件也一并更新
|
|
1171
|
+
*/
|
|
1172
|
+
watchDeps() {
|
|
1173
|
+
const oldDeps = [];
|
|
1174
|
+
this.depsWatcher = chokidar.watch([], {
|
|
1175
|
+
ignoreInitial: true,
|
|
1176
|
+
cwd: this.cwd
|
|
1177
|
+
});
|
|
1178
|
+
this.depsWatcher.on("change", (filepath) => {
|
|
1179
|
+
filepath = normalizePath2(filepath);
|
|
1180
|
+
const mockFiles = this.moduleDeps.get(filepath);
|
|
1181
|
+
mockFiles && mockFiles.forEach((file) => {
|
|
1182
|
+
this.emit("mock:update", file);
|
|
1183
|
+
});
|
|
1184
|
+
});
|
|
1185
|
+
this.depsWatcher.on("unlink", (filepath) => {
|
|
1186
|
+
filepath = normalizePath2(filepath);
|
|
1187
|
+
this.moduleDeps.delete(filepath);
|
|
1188
|
+
});
|
|
1189
|
+
this.on("update:deps", () => {
|
|
1190
|
+
const deps = [];
|
|
1191
|
+
for (const [dep] of this.moduleDeps.entries())
|
|
1192
|
+
deps.push(dep);
|
|
1193
|
+
const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
|
|
1194
|
+
exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
close() {
|
|
1198
|
+
var _a, _b;
|
|
1199
|
+
(_a = this.mockWatcher) == null ? void 0 : _a.close();
|
|
1200
|
+
(_b = this.depsWatcher) == null ? void 0 : _b.close();
|
|
1201
|
+
}
|
|
1202
|
+
updateMockList() {
|
|
1203
|
+
this._mockData = transformMockData(this.moduleCache);
|
|
1204
|
+
}
|
|
1205
|
+
updateModuleDeps(filepath, deps) {
|
|
1206
|
+
Object.keys(deps).forEach((mPath) => {
|
|
1207
|
+
const imports = deps[mPath].imports.map((_) => _.path);
|
|
1208
|
+
imports.forEach((dep) => {
|
|
1209
|
+
if (!this.moduleDeps.has(dep))
|
|
1210
|
+
this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
|
|
1211
|
+
const cur = this.moduleDeps.get(dep);
|
|
1212
|
+
cur.add(filepath);
|
|
1213
|
+
});
|
|
1214
|
+
});
|
|
1215
|
+
this.emit("update:deps");
|
|
1216
|
+
}
|
|
1217
|
+
async loadMock(filepath) {
|
|
1218
|
+
if (!filepath)
|
|
1219
|
+
return;
|
|
1220
|
+
let isESM = false;
|
|
1221
|
+
if (/\.m[jt]s$/.test(filepath))
|
|
1222
|
+
isESM = true;
|
|
1223
|
+
else if (/\.c[jt]s$/.test(filepath))
|
|
1224
|
+
isESM = false;
|
|
1225
|
+
else
|
|
1226
|
+
isESM = this.moduleType === "esm";
|
|
1227
|
+
const { define, alias } = this.options;
|
|
1228
|
+
const { code, deps } = await transformWithEsbuild(filepath, {
|
|
1229
|
+
isESM,
|
|
1230
|
+
define,
|
|
1231
|
+
alias
|
|
1232
|
+
});
|
|
1233
|
+
try {
|
|
1234
|
+
const raw = await loadFromCode(
|
|
1235
|
+
filepath,
|
|
1236
|
+
code,
|
|
1237
|
+
isESM,
|
|
1238
|
+
this.cwd
|
|
1239
|
+
) || {};
|
|
1240
|
+
let mockConfig;
|
|
1241
|
+
if (hasOwn(raw, "default")) {
|
|
1242
|
+
mockConfig = raw.default;
|
|
1243
|
+
} else {
|
|
1244
|
+
mockConfig = [];
|
|
1245
|
+
Object.keys(raw).forEach(
|
|
1246
|
+
(key) => mockConfig.push(...toArray2(raw[key]))
|
|
1247
|
+
);
|
|
1248
|
+
}
|
|
1249
|
+
if (isArray5(mockConfig)) {
|
|
1250
|
+
mockConfig.forEach((mock) => mock.__filepath__ = filepath);
|
|
1251
|
+
} else {
|
|
1252
|
+
;
|
|
1253
|
+
mockConfig.__filepath__ = filepath;
|
|
1254
|
+
}
|
|
1255
|
+
this.moduleCache.set(filepath, mockConfig);
|
|
1256
|
+
this.updateModuleDeps(filepath, deps);
|
|
1257
|
+
} catch (e) {
|
|
1258
|
+
console.error(e);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
|
|
1263
|
+
// src/ws.ts
|
|
1264
|
+
import Cookies2 from "cookies";
|
|
1265
|
+
import { pathToRegexp as pathToRegexp3 } from "path-to-regexp";
|
|
1266
|
+
import colors4 from "picocolors";
|
|
1267
|
+
import { WebSocketServer } from "ws";
|
|
1268
|
+
function mockWebSocket({
|
|
1269
|
+
loader,
|
|
1270
|
+
httpServer,
|
|
1271
|
+
proxies,
|
|
1272
|
+
cookiesOptions,
|
|
1273
|
+
logger
|
|
1274
|
+
}) {
|
|
1275
|
+
var _a;
|
|
1276
|
+
const hmrMap = /* @__PURE__ */ new Map();
|
|
1277
|
+
const poolMap = /* @__PURE__ */ new Map();
|
|
1278
|
+
const wssContextMap = /* @__PURE__ */ new WeakMap();
|
|
1279
|
+
const getWssMap = (mockUrl) => {
|
|
1280
|
+
let wssMap = poolMap.get(mockUrl);
|
|
1281
|
+
!wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
|
|
1282
|
+
return wssMap;
|
|
1283
|
+
};
|
|
1284
|
+
const getWss = (wssMap, pathname) => {
|
|
1285
|
+
let wss = wssMap.get(pathname);
|
|
1286
|
+
!wss && wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
|
|
1287
|
+
return wss;
|
|
1288
|
+
};
|
|
1289
|
+
const addHmr = (filepath, mockUrl) => {
|
|
1290
|
+
let urlList = hmrMap.get(filepath);
|
|
1291
|
+
!urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
|
|
1292
|
+
urlList.add(mockUrl);
|
|
1293
|
+
};
|
|
1294
|
+
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
|
|
1295
|
+
var _a2;
|
|
1296
|
+
try {
|
|
1297
|
+
(_a2 = mock.setup) == null ? void 0 : _a2.call(mock, wss, context);
|
|
1298
|
+
wss.on("close", () => wssMap.delete(pathname));
|
|
1299
|
+
wss.on("error", (e) => {
|
|
1300
|
+
logger.error(
|
|
1301
|
+
`${colors4.red(
|
|
1302
|
+
`WebSocket mock error at ${wss.path}`
|
|
1303
|
+
)}
|
|
1304
|
+
${e}
|
|
1305
|
+
at setup (${filepath})`,
|
|
1306
|
+
mock.log
|
|
1307
|
+
);
|
|
1308
|
+
});
|
|
1309
|
+
} catch (e) {
|
|
1310
|
+
logger.error(
|
|
1311
|
+
`${colors4.red(
|
|
1312
|
+
`WebSocket mock error at ${wss.path}`
|
|
1313
|
+
)}
|
|
1314
|
+
${e}
|
|
1315
|
+
at setup (${filepath})`,
|
|
1316
|
+
mock.log
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
const emitConnection = (wss, ws, req, connectionList) => {
|
|
1321
|
+
wss.emit("connection", ws, req);
|
|
1322
|
+
ws.on("close", () => {
|
|
1323
|
+
const i = connectionList.findIndex((item) => item.ws === ws);
|
|
1324
|
+
if (i !== -1)
|
|
1325
|
+
connectionList.splice(i, 1);
|
|
1326
|
+
});
|
|
1327
|
+
};
|
|
1328
|
+
const restartWss = (wssMap, wss, mock, pathname, filepath) => {
|
|
1329
|
+
const { cleanupList, connectionList, context } = wssContextMap.get(wss);
|
|
1330
|
+
cleanupRunner(cleanupList);
|
|
1331
|
+
connectionList.forEach(({ ws }) => ws.removeAllListeners());
|
|
1332
|
+
wss.removeAllListeners();
|
|
1333
|
+
setupWss(wssMap, wss, mock, context, pathname, filepath);
|
|
1334
|
+
connectionList.forEach(
|
|
1335
|
+
({ ws, req }) => emitConnection(wss, ws, req, connectionList)
|
|
1336
|
+
);
|
|
1337
|
+
};
|
|
1338
|
+
(_a = loader.on) == null ? void 0 : _a.call(loader, "mock:update-end", (filepath) => {
|
|
1339
|
+
if (!hmrMap.has(filepath))
|
|
1340
|
+
return;
|
|
1341
|
+
const mockUrlList = hmrMap.get(filepath);
|
|
1342
|
+
if (!mockUrlList)
|
|
1343
|
+
return;
|
|
1344
|
+
for (const mockUrl of mockUrlList.values()) {
|
|
1345
|
+
for (const mock of loader.mockData[mockUrl]) {
|
|
1346
|
+
if (!mock.ws || mock.__filepath__ !== filepath)
|
|
1347
|
+
return;
|
|
1348
|
+
const wssMap = getWssMap(mockUrl);
|
|
1349
|
+
for (const [pathname, wss] of wssMap.entries())
|
|
1350
|
+
restartWss(wssMap, wss, mock, pathname, filepath);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
});
|
|
1354
|
+
httpServer == null ? void 0 : httpServer.on("upgrade", (req, socket, head) => {
|
|
1355
|
+
const { pathname, query } = urlParse(req.url);
|
|
1356
|
+
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
|
|
1357
|
+
return;
|
|
1358
|
+
const mockData = loader.mockData;
|
|
1359
|
+
const mockUrl = Object.keys(mockData).find((key) => {
|
|
1360
|
+
return pathToRegexp3(key).test(pathname);
|
|
1361
|
+
});
|
|
1362
|
+
if (!mockUrl)
|
|
1363
|
+
return;
|
|
1364
|
+
const mock = mockData[mockUrl].find((mock2) => {
|
|
1365
|
+
return mock2.url && mock2.ws && pathToRegexp3(mock2.url).test(pathname);
|
|
1366
|
+
});
|
|
1367
|
+
if (!mock)
|
|
1368
|
+
return;
|
|
1369
|
+
const filepath = mock.__filepath__;
|
|
1370
|
+
addHmr(filepath, mockUrl);
|
|
1371
|
+
const wssMap = getWssMap(mockUrl);
|
|
1372
|
+
const wss = getWss(wssMap, pathname);
|
|
1373
|
+
let wssContext = wssContextMap.get(wss);
|
|
1374
|
+
if (!wssContext) {
|
|
1375
|
+
const cleanupList = [];
|
|
1376
|
+
const context = {
|
|
1377
|
+
onCleanup: (cleanup) => cleanupList.push(cleanup)
|
|
1378
|
+
};
|
|
1379
|
+
wssContext = { cleanupList, context, connectionList: [] };
|
|
1380
|
+
wssContextMap.set(wss, wssContext);
|
|
1381
|
+
setupWss(wssMap, wss, mock, context, pathname, filepath);
|
|
1382
|
+
}
|
|
1383
|
+
const request = req;
|
|
1384
|
+
const cookies = new Cookies2(req, req, cookiesOptions);
|
|
1385
|
+
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
1386
|
+
request.query = query;
|
|
1387
|
+
request.refererQuery = refererQuery;
|
|
1388
|
+
request.params = parseParams(mockUrl, pathname);
|
|
1389
|
+
request.getCookie = cookies.get.bind(cookies);
|
|
1390
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
1391
|
+
logger.info(
|
|
1392
|
+
`${colors4.magenta(colors4.bold("WebSocket"))} ${colors4.green(
|
|
1393
|
+
req.url
|
|
1394
|
+
)} connected ${colors4.dim(`(${filepath})`)}`,
|
|
1395
|
+
mock.log
|
|
1396
|
+
);
|
|
1397
|
+
wssContext.connectionList.push({ req: request, ws });
|
|
1398
|
+
emitConnection(wss, ws, request, wssContext.connectionList);
|
|
1399
|
+
});
|
|
1400
|
+
});
|
|
1401
|
+
httpServer == null ? void 0 : httpServer.on("close", () => {
|
|
1402
|
+
for (const wssMap of poolMap.values()) {
|
|
1403
|
+
for (const wss of wssMap.values()) {
|
|
1404
|
+
const wssContext = wssContextMap.get(wss);
|
|
1405
|
+
cleanupRunner(wssContext.cleanupList);
|
|
1406
|
+
wss.close();
|
|
1407
|
+
}
|
|
1408
|
+
wssMap.clear();
|
|
1409
|
+
}
|
|
1410
|
+
poolMap.clear();
|
|
1411
|
+
hmrMap.clear();
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
function cleanupRunner(cleanupList) {
|
|
1415
|
+
let cleanup;
|
|
1416
|
+
while (cleanup = cleanupList.shift())
|
|
1417
|
+
cleanup == null ? void 0 : cleanup();
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// src/mockMiddleware.ts
|
|
1421
|
+
function mockServerMiddleware(config, options, httpServer, ws) {
|
|
1422
|
+
const logger = createLogger(
|
|
1423
|
+
"vite:mock",
|
|
1424
|
+
isBoolean2(options.log) ? options.log ? "info" : "error" : options.log
|
|
1425
|
+
);
|
|
1426
|
+
const loader = new MockLoader({
|
|
1427
|
+
include: toArray3(options.include),
|
|
1428
|
+
exclude: toArray3(options.exclude),
|
|
1429
|
+
define: viteDefine(config),
|
|
1430
|
+
alias: config.resolve.alias
|
|
1431
|
+
});
|
|
1432
|
+
loader.load();
|
|
1433
|
+
loader.on("mock:update-end", () => {
|
|
1434
|
+
if (options.reload)
|
|
1435
|
+
ws == null ? void 0 : ws.send({ type: "full-reload" });
|
|
1436
|
+
});
|
|
1437
|
+
httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
|
|
1438
|
+
const { httpProxies } = ensureProxies(config.server.proxy || {});
|
|
1439
|
+
const prefix = toArray3(options.prefix);
|
|
1440
|
+
const proxies = [...prefix, ...httpProxies];
|
|
1441
|
+
mockWebSocket({
|
|
1442
|
+
loader,
|
|
1443
|
+
httpServer,
|
|
1444
|
+
proxies: toArray3(options.wsPrefix),
|
|
1445
|
+
cookiesOptions: options.cookiesOptions,
|
|
1446
|
+
logger
|
|
1447
|
+
});
|
|
1448
|
+
const middlewares = [];
|
|
1449
|
+
middlewares.push(
|
|
1450
|
+
/**
|
|
1451
|
+
* 在 vite 的开发服务中,由于插件 的 enforce 为 `pre`,
|
|
1452
|
+
* mock 中间件的执行顺序 早于 vite 内部的 cors 中间件执行,
|
|
1453
|
+
* 这导致了 vite 默认开启的 cors 对 mock 请求不生效。
|
|
1454
|
+
* 在一些比如 微前端项目、或者联合项目中,会由于端口不一致而导致跨域问题。
|
|
1455
|
+
* 所以在这里,使用 cors 中间件 来解决这个问题。
|
|
1456
|
+
*
|
|
1457
|
+
* 同时为了使 插件内的 cors 和 vite 的 cors 不产生冲突,并拥有一致的默认行为,
|
|
1458
|
+
* 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
|
|
1459
|
+
* 而用户的配置也仅对 mock 的接口生效。
|
|
1460
|
+
*/
|
|
1461
|
+
corsMiddleware(loader, proxies, config, options),
|
|
1462
|
+
baseMiddleware(loader, {
|
|
1463
|
+
formidableOptions: options.formidableOptions,
|
|
1464
|
+
proxies,
|
|
1465
|
+
cookiesOptions: options.cookiesOptions,
|
|
1466
|
+
priority: options.priority,
|
|
1467
|
+
logger
|
|
1468
|
+
})
|
|
1469
|
+
);
|
|
1470
|
+
return middlewares.filter(Boolean);
|
|
1471
|
+
}
|
|
1472
|
+
function corsMiddleware(mockLoader, proxies, config, options) {
|
|
1473
|
+
let corsOptions = {};
|
|
1474
|
+
const enabled = options.cors === false ? false : config.server.cors !== false;
|
|
1475
|
+
if (enabled && config.server.cors !== false) {
|
|
1476
|
+
corsOptions = {
|
|
1477
|
+
...corsOptions,
|
|
1478
|
+
...typeof config.server.cors === "boolean" ? {} : config.server.cors
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
if (enabled && options.cors !== false) {
|
|
1482
|
+
corsOptions = {
|
|
1483
|
+
...corsOptions,
|
|
1484
|
+
...typeof options.cors === "boolean" ? {} : options.cors
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
return !enabled ? void 0 : function(req, res, next) {
|
|
1488
|
+
const { pathname } = urlParse(req.url);
|
|
1489
|
+
if (!pathname || proxies.length === 0 || !proxies.some(
|
|
1490
|
+
(context) => doesProxyContextMatchUrl(context, req.url)
|
|
1491
|
+
))
|
|
1492
|
+
return next();
|
|
1493
|
+
const mockData = mockLoader.mockData;
|
|
1494
|
+
const mockUrl = Object.keys(mockData).find(
|
|
1495
|
+
(key) => pathToRegexp4(key).test(pathname)
|
|
1496
|
+
);
|
|
1497
|
+
if (!mockUrl)
|
|
1498
|
+
return next();
|
|
1499
|
+
cors(corsOptions)(req, res, next);
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// src/plugin.ts
|
|
1504
|
+
function mockDevServerPlugin({
|
|
1505
|
+
prefix = [],
|
|
1506
|
+
wsPrefix = [],
|
|
1507
|
+
include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
|
|
1508
|
+
exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
|
|
1509
|
+
reload = false,
|
|
1510
|
+
log = "info",
|
|
1511
|
+
cors: cors2 = true,
|
|
1512
|
+
formidableOptions = {},
|
|
1513
|
+
build: build2 = false,
|
|
1514
|
+
cookiesOptions = {},
|
|
1515
|
+
priority = {}
|
|
1516
|
+
} = {}) {
|
|
1517
|
+
const pluginOptions = {
|
|
1518
|
+
prefix,
|
|
1519
|
+
wsPrefix,
|
|
1520
|
+
include,
|
|
1521
|
+
exclude,
|
|
1522
|
+
reload,
|
|
1523
|
+
cors: cors2,
|
|
1524
|
+
cookiesOptions,
|
|
1525
|
+
log,
|
|
1526
|
+
formidableOptions: {
|
|
1527
|
+
multiples: true,
|
|
1528
|
+
...formidableOptions
|
|
1529
|
+
},
|
|
1530
|
+
priority,
|
|
1531
|
+
build: build2 ? Object.assign(
|
|
1532
|
+
{
|
|
1533
|
+
serverPort: 8080,
|
|
1534
|
+
dist: "mockServer"
|
|
1535
|
+
},
|
|
1536
|
+
typeof build2 === "object" ? build2 : {}
|
|
1537
|
+
) : false
|
|
1538
|
+
};
|
|
1539
|
+
const plugins = [serverPlugin(pluginOptions)];
|
|
1540
|
+
if (pluginOptions.build)
|
|
1541
|
+
plugins.push(buildPlugin(pluginOptions));
|
|
1542
|
+
return plugins;
|
|
1543
|
+
}
|
|
1544
|
+
function buildPlugin(pluginOptions) {
|
|
1545
|
+
let viteConfig = {};
|
|
1546
|
+
return {
|
|
1547
|
+
name: "vite-plugin-mock-dev-server-generator",
|
|
1548
|
+
enforce: "post",
|
|
1549
|
+
apply: "build",
|
|
1550
|
+
configResolved(config) {
|
|
1551
|
+
viteConfig = config;
|
|
1552
|
+
config.logger.warn("");
|
|
1553
|
+
},
|
|
1554
|
+
async buildEnd(error) {
|
|
1555
|
+
if (error)
|
|
1556
|
+
return;
|
|
1557
|
+
if (viteConfig.command !== "build")
|
|
1558
|
+
return;
|
|
1559
|
+
await generateMockServer(this, viteConfig, pluginOptions);
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
function serverPlugin(pluginOptions) {
|
|
1564
|
+
let viteConfig = {};
|
|
1565
|
+
return {
|
|
1566
|
+
name: "vite-plugin-mock-dev-server",
|
|
1567
|
+
enforce: "pre",
|
|
1568
|
+
apply: "serve",
|
|
1569
|
+
config(config) {
|
|
1570
|
+
var _a;
|
|
1571
|
+
const wsPrefix = toArray4(pluginOptions.wsPrefix);
|
|
1572
|
+
if (wsPrefix.length && ((_a = config.server) == null ? void 0 : _a.proxy)) {
|
|
1573
|
+
const proxy = {};
|
|
1574
|
+
Object.keys(config.server.proxy).forEach((key) => {
|
|
1575
|
+
if (!wsPrefix.includes(key))
|
|
1576
|
+
proxy[key] = config.server.proxy[key];
|
|
1577
|
+
});
|
|
1578
|
+
config.server.proxy = proxy;
|
|
1579
|
+
}
|
|
1580
|
+
recoverRequest(config);
|
|
1581
|
+
},
|
|
1582
|
+
configResolved(config) {
|
|
1583
|
+
viteConfig = config;
|
|
1584
|
+
config.logger.warn("");
|
|
1585
|
+
},
|
|
1586
|
+
configureServer({ middlewares, config, httpServer, ws }) {
|
|
1587
|
+
const middlewareList = mockServerMiddleware(
|
|
1588
|
+
config,
|
|
1589
|
+
pluginOptions,
|
|
1590
|
+
httpServer,
|
|
1591
|
+
ws
|
|
1592
|
+
);
|
|
1593
|
+
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
1594
|
+
},
|
|
1595
|
+
configurePreviewServer({ middlewares, httpServer }) {
|
|
1596
|
+
const middlewareList = mockServerMiddleware(
|
|
1597
|
+
viteConfig,
|
|
1598
|
+
pluginOptions,
|
|
1599
|
+
httpServer
|
|
1600
|
+
);
|
|
1601
|
+
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
1602
|
+
}
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/defineMock.ts
|
|
1607
|
+
import { isArray as isArray6 } from "@pengzhanbo/utils";
|
|
1608
|
+
function defineMock(config) {
|
|
1609
|
+
return config;
|
|
1610
|
+
}
|
|
1611
|
+
function createDefineMock(transformer) {
|
|
1612
|
+
const define = (config) => {
|
|
1613
|
+
if (isArray6(config))
|
|
1614
|
+
config = config.map((item) => transformer(item) || item);
|
|
1615
|
+
else
|
|
1616
|
+
config = transformer(config) || config;
|
|
1617
|
+
return config;
|
|
1618
|
+
};
|
|
1619
|
+
return define;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// src/defineMockData.ts
|
|
1623
|
+
import { deepClone, deepEqual, isFunction as isFunction3 } from "@pengzhanbo/utils";
|
|
1624
|
+
var mockDataCache = /* @__PURE__ */ new Map();
|
|
1625
|
+
var responseCache = /* @__PURE__ */ new WeakMap();
|
|
1626
|
+
var staleInterval = 70;
|
|
1627
|
+
var CacheImpl = class {
|
|
1628
|
+
value;
|
|
1629
|
+
// 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
|
|
1630
|
+
#initialValue;
|
|
1631
|
+
#lastUpdate;
|
|
1632
|
+
constructor(value) {
|
|
1633
|
+
this.value = value;
|
|
1634
|
+
this.#initialValue = deepClone(value);
|
|
1635
|
+
this.#lastUpdate = Date.now();
|
|
1636
|
+
}
|
|
1637
|
+
hotUpdate(value) {
|
|
1638
|
+
if (Date.now() - this.#lastUpdate < staleInterval)
|
|
1639
|
+
return;
|
|
1640
|
+
if (!deepEqual(value, this.#initialValue)) {
|
|
1641
|
+
this.value = value;
|
|
1642
|
+
this.#initialValue = deepClone(value);
|
|
1643
|
+
this.#lastUpdate = Date.now();
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
};
|
|
1647
|
+
function defineMockData(key, initialData) {
|
|
1648
|
+
if (!mockDataCache.has(key))
|
|
1649
|
+
mockDataCache.set(key, new CacheImpl(initialData));
|
|
1650
|
+
const cache2 = mockDataCache.get(key);
|
|
1651
|
+
cache2.hotUpdate(initialData);
|
|
1652
|
+
if (responseCache.has(cache2))
|
|
1653
|
+
return responseCache.get(cache2);
|
|
1654
|
+
const res = [
|
|
1655
|
+
() => cache2.value,
|
|
1656
|
+
(val) => {
|
|
1657
|
+
if (isFunction3(val))
|
|
1658
|
+
val = val(cache2.value) ?? cache2.value;
|
|
1659
|
+
cache2.value = val;
|
|
1660
|
+
}
|
|
1661
|
+
];
|
|
1662
|
+
Object.defineProperty(res, "value", {
|
|
1663
|
+
get() {
|
|
1664
|
+
return cache2.value;
|
|
1665
|
+
},
|
|
1666
|
+
set(val) {
|
|
1667
|
+
cache2.value = val;
|
|
1668
|
+
}
|
|
1669
|
+
});
|
|
1670
|
+
responseCache.set(cache2, res);
|
|
1671
|
+
return res;
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
// src/index.ts
|
|
1675
|
+
var src_default = mockDevServerPlugin;
|
|
1676
|
+
export {
|
|
1677
|
+
baseMiddleware,
|
|
1678
|
+
createDefineMock,
|
|
1679
|
+
createLogger,
|
|
1680
|
+
src_default as default,
|
|
1681
|
+
defineMock,
|
|
1682
|
+
defineMockData,
|
|
1683
|
+
logLevels,
|
|
1684
|
+
mockDevServerPlugin,
|
|
1685
|
+
mockWebSocket,
|
|
1686
|
+
sortByValidator,
|
|
1687
|
+
transformMockData
|
|
1688
|
+
};
|