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