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