vite-plugin-mock-dev-server 1.6.1 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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 +365 -1390
- package/dist/index.d.cts +20 -728
- package/dist/index.d.ts +20 -727
- package/dist/index.js +308 -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 +34 -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,107 @@ 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
|
-
|
|
161
|
+
filepath = _path2.default.resolve(cwd, filepath);
|
|
162
|
+
const ext = isESM ? ".mjs" : ".cjs";
|
|
163
|
+
const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
|
|
164
|
+
const file = _url.pathToFileURL.call(void 0, filepathTmp).toString();
|
|
165
|
+
await _fs.promises.writeFile(filepathTmp, code, "utf8");
|
|
166
|
+
try {
|
|
167
|
+
const mod = await import(file);
|
|
168
|
+
return mod.default || mod;
|
|
169
|
+
} finally {
|
|
250
170
|
try {
|
|
251
|
-
|
|
252
|
-
}
|
|
253
|
-
try {
|
|
254
|
-
import_node_fs2.default.unlinkSync(fileNameTmp);
|
|
255
|
-
} catch {
|
|
256
|
-
}
|
|
171
|
+
_fs2.default.unlinkSync(filepathTmp);
|
|
172
|
+
} catch (e2) {
|
|
257
173
|
}
|
|
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
174
|
}
|
|
276
175
|
}
|
|
277
176
|
|
|
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);
|
|
177
|
+
// src/core/build.ts
|
|
178
|
+
async function generateMockServer(ctx, options) {
|
|
179
|
+
const include = _utils.toArray.call(void 0, options.include);
|
|
180
|
+
const exclude = _utils.toArray.call(void 0, options.exclude);
|
|
181
|
+
const cwd = options.cwd || _process2.default.cwd();
|
|
368
182
|
let pkg = {};
|
|
369
183
|
try {
|
|
370
|
-
const pkgStr = lookupFile(
|
|
184
|
+
const pkgStr = _chunkS76FMTCDcjs.lookupFile.call(void 0, options.context, ["package.json"]);
|
|
371
185
|
if (pkgStr)
|
|
372
186
|
pkg = JSON.parse(pkgStr);
|
|
373
|
-
} catch {
|
|
187
|
+
} catch (e3) {
|
|
374
188
|
}
|
|
375
189
|
const outputDir = options.build.dist;
|
|
376
190
|
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);
|
|
191
|
+
const mockEntry = _path2.default.join(cwd, `mock-data-${Date.now()}.js`);
|
|
192
|
+
await _promises2.default.writeFile(mockEntry, content, "utf-8");
|
|
193
|
+
const { code, deps } = await transformWithEsbuild(mockEntry, options);
|
|
194
|
+
const mockDeps = getMockDependencies(deps, options.alias);
|
|
195
|
+
await _promises2.default.unlink(mockEntry);
|
|
385
196
|
const outputList = [
|
|
386
197
|
{
|
|
387
|
-
filename:
|
|
198
|
+
filename: _path2.default.join(outputDir, "mock-data.js"),
|
|
388
199
|
source: code
|
|
389
200
|
},
|
|
390
201
|
{
|
|
391
|
-
filename:
|
|
392
|
-
source: generatorServerEntryCode(
|
|
393
|
-
httpProxies,
|
|
394
|
-
wsProxies,
|
|
395
|
-
options.cookiesOptions,
|
|
396
|
-
options.bodyParserOptions,
|
|
397
|
-
options.priority,
|
|
398
|
-
options.build
|
|
399
|
-
)
|
|
202
|
+
filename: _path2.default.join(outputDir, "index.js"),
|
|
203
|
+
source: generatorServerEntryCode(options)
|
|
400
204
|
},
|
|
401
205
|
{
|
|
402
|
-
filename:
|
|
206
|
+
filename: _path2.default.join(outputDir, "package.json"),
|
|
403
207
|
source: generatePackageJson(pkg, mockDeps)
|
|
404
208
|
}
|
|
405
209
|
];
|
|
406
210
|
try {
|
|
407
|
-
if (
|
|
211
|
+
if (_path2.default.isAbsolute(outputDir)) {
|
|
408
212
|
for (const { filename } of outputList) {
|
|
409
|
-
if (
|
|
410
|
-
await
|
|
213
|
+
if (_fs2.default.existsSync(filename))
|
|
214
|
+
await _promises2.default.rm(filename);
|
|
411
215
|
}
|
|
412
|
-
|
|
216
|
+
options.logger.info(`${_picocolors2.default.green("\u2713")} generate mock server in ${_picocolors2.default.cyan(outputDir)}`);
|
|
413
217
|
for (const { filename, source } of outputList) {
|
|
414
|
-
|
|
415
|
-
await
|
|
218
|
+
_fs2.default.mkdirSync(_path2.default.dirname(filename), { recursive: true });
|
|
219
|
+
await _promises2.default.writeFile(filename, source, "utf-8");
|
|
416
220
|
const sourceSize = (source.length / 1024).toFixed(2);
|
|
417
|
-
const name =
|
|
221
|
+
const name = _path2.default.relative(outputDir, filename);
|
|
418
222
|
const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
|
|
419
|
-
|
|
223
|
+
options.logger.info(` ${_picocolors2.default.green(name)}${space}${_picocolors2.default.bold(_picocolors2.default.dim(`${sourceSize} kB`))}`);
|
|
420
224
|
}
|
|
421
225
|
} else {
|
|
422
226
|
for (const { filename, source } of outputList) {
|
|
@@ -433,17 +237,25 @@ async function generateMockServer(ctx, config, options) {
|
|
|
433
237
|
}
|
|
434
238
|
function getMockDependencies(deps, alias) {
|
|
435
239
|
const list = /* @__PURE__ */ new Set();
|
|
436
|
-
const excludeDeps = [
|
|
240
|
+
const excludeDeps = ["vite-plugin-mock-dev-server", "connect", "cors"];
|
|
437
241
|
const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
|
|
438
242
|
Object.keys(deps).forEach((mPath) => {
|
|
439
243
|
const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
|
|
440
244
|
imports.forEach((dep) => {
|
|
441
|
-
|
|
442
|
-
|
|
245
|
+
const name = normalizePackageName(dep);
|
|
246
|
+
if (!excludeDeps.includes(name) && !_iscoremodule2.default.call(void 0, name))
|
|
247
|
+
list.add(name);
|
|
443
248
|
});
|
|
444
249
|
});
|
|
445
250
|
return Array.from(list);
|
|
446
251
|
}
|
|
252
|
+
function normalizePackageName(dep) {
|
|
253
|
+
const [scope, name] = dep.split("/");
|
|
254
|
+
if (scope[0] === "@") {
|
|
255
|
+
return `${scope}/${name}`;
|
|
256
|
+
}
|
|
257
|
+
return scope;
|
|
258
|
+
}
|
|
447
259
|
function generatePackageJson(pkg, mockDeps) {
|
|
448
260
|
const { dependencies = {}, devDependencies = {} } = pkg;
|
|
449
261
|
const dependents = { ...dependencies, ...devDependencies };
|
|
@@ -454,9 +266,9 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
454
266
|
start: "node index.js"
|
|
455
267
|
},
|
|
456
268
|
dependencies: {
|
|
457
|
-
|
|
458
|
-
"vite-plugin-mock-dev-server": `^${
|
|
459
|
-
|
|
269
|
+
connect: "^3.7.0",
|
|
270
|
+
["vite-plugin-mock-dev-server"]: `^${"1.7.0"}`,
|
|
271
|
+
cors: "^2.8.5"
|
|
460
272
|
},
|
|
461
273
|
pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
|
|
462
274
|
};
|
|
@@ -465,35 +277,37 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
465
277
|
});
|
|
466
278
|
return JSON.stringify(mockPkg, null, 2);
|
|
467
279
|
}
|
|
468
|
-
function generatorServerEntryCode(
|
|
280
|
+
function generatorServerEntryCode({
|
|
281
|
+
proxies,
|
|
282
|
+
wsProxies,
|
|
283
|
+
cookiesOptions,
|
|
284
|
+
bodyParserOptions,
|
|
285
|
+
priority,
|
|
286
|
+
build: build2
|
|
287
|
+
}) {
|
|
469
288
|
const { serverPort, log } = build2;
|
|
470
289
|
return `import { createServer } from 'node:http';
|
|
471
290
|
import connect from 'connect';
|
|
472
291
|
import corsMiddleware from 'cors';
|
|
473
|
-
import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server';
|
|
292
|
+
import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server/server';
|
|
474
293
|
import mockData from './mock-data.js';
|
|
475
294
|
|
|
476
295
|
const app = connect();
|
|
477
296
|
const server = createServer(app);
|
|
478
297
|
const logger = createLogger('mock-server', '${log}');
|
|
479
|
-
const
|
|
298
|
+
const proxies = ${JSON.stringify(proxies)};
|
|
480
299
|
const wsProxies = ${JSON.stringify(wsProxies)};
|
|
481
300
|
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
482
301
|
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
483
302
|
const priority = ${JSON.stringify(priority)};
|
|
303
|
+
const compiler = { mockData }
|
|
484
304
|
|
|
485
|
-
mockWebSocket({
|
|
486
|
-
loader: { mockData },
|
|
487
|
-
httpServer: server,
|
|
488
|
-
proxies: wsProxies,
|
|
489
|
-
cookiesOptions,
|
|
490
|
-
logger,
|
|
491
|
-
});
|
|
305
|
+
mockWebSocket(compiler, server, { wsProxies, cookiesOptions, logger });
|
|
492
306
|
|
|
493
307
|
app.use(corsMiddleware());
|
|
494
|
-
app.use(baseMiddleware(
|
|
308
|
+
app.use(baseMiddleware(compiler, {
|
|
495
309
|
formidableOptions: { multiples: true },
|
|
496
|
-
proxies
|
|
310
|
+
proxies,
|
|
497
311
|
priority,
|
|
498
312
|
cookiesOptions,
|
|
499
313
|
bodyParserOptions,
|
|
@@ -506,717 +320,72 @@ console.log('listen: http://localhost:${serverPort}');
|
|
|
506
320
|
`;
|
|
507
321
|
}
|
|
508
322
|
async function generateMockEntryCode(cwd, include, exclude) {
|
|
509
|
-
const includePaths = await (0,
|
|
510
|
-
const includeFilter = (0,
|
|
323
|
+
const includePaths = await _fastglob2.default.call(void 0, include, { cwd });
|
|
324
|
+
const includeFilter = _pluginutils.createFilter.call(void 0, include, exclude, {
|
|
511
325
|
resolve: false
|
|
512
326
|
});
|
|
513
327
|
const mockFiles = includePaths.filter(includeFilter);
|
|
514
328
|
let importers = "";
|
|
515
|
-
|
|
329
|
+
const exporters = [];
|
|
516
330
|
mockFiles.forEach((filepath, index) => {
|
|
517
|
-
const file = normalizePath(
|
|
331
|
+
const file = _chunkS76FMTCDcjs.normalizePath.call(void 0, _path2.default.join(cwd, filepath));
|
|
518
332
|
importers += `import * as m${index} from '${file}';
|
|
519
333
|
`;
|
|
520
|
-
exporters
|
|
334
|
+
exporters.push(`[m${index}, '${filepath}']`);
|
|
521
335
|
});
|
|
522
|
-
return `import { transformMockData } from 'vite-plugin-mock-dev-server';
|
|
336
|
+
return `import { transformMockData, transformRawData } from 'vite-plugin-mock-dev-server/server';
|
|
523
337
|
${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
|
|
338
|
+
const exporters = [
|
|
339
|
+
${exporters.join(",\n ")}
|
|
340
|
+
];
|
|
341
|
+
const mockList = exporters.map(([mod, filepath]) => {
|
|
342
|
+
const raw = mod.default || mod;
|
|
343
|
+
return transformRawData(raw, filepath);
|
|
538
344
|
});
|
|
539
345
|
export default transformMockData(mockList);`;
|
|
540
346
|
}
|
|
541
347
|
|
|
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);
|
|
348
|
+
// src/core/mockMiddleware.ts
|
|
349
|
+
var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);
|
|
350
|
+
var _pathtoregexp = require('path-to-regexp');
|
|
556
351
|
|
|
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
|
-
}
|
|
352
|
+
// src/core/mockCompiler.ts
|
|
353
|
+
var _events = require('events'); var _events2 = _interopRequireDefault(_events);
|
|
696
354
|
|
|
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
355
|
|
|
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
|
-
}
|
|
356
|
+
var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
|
|
1124
357
|
|
|
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
358
|
|
|
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;
|
|
359
|
+
function createMockCompiler(options) {
|
|
360
|
+
return new MockCompiler(options);
|
|
1167
361
|
}
|
|
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 {
|
|
362
|
+
var MockCompiler = (_class = class extends _events2.default {
|
|
1192
363
|
constructor(options) {
|
|
1193
|
-
super();
|
|
364
|
+
super();_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);;
|
|
1194
365
|
this.options = options;
|
|
1195
|
-
this.cwd = options.cwd ||
|
|
366
|
+
this.cwd = options.cwd || _process2.default.cwd();
|
|
1196
367
|
try {
|
|
1197
|
-
const pkg = lookupFile(this.cwd, ["package.json"]);
|
|
368
|
+
const pkg = _chunkS76FMTCDcjs.lookupFile.call(void 0, this.cwd, ["package.json"]);
|
|
1198
369
|
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
1199
|
-
} catch {
|
|
370
|
+
} catch (e4) {
|
|
1200
371
|
}
|
|
1201
372
|
}
|
|
1202
|
-
moduleCache = /* @__PURE__ */ new Map()
|
|
1203
|
-
moduleDeps = /* @__PURE__ */ new Map()
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
moduleType = "cjs"
|
|
1208
|
-
_mockData = {}
|
|
373
|
+
__init() {this.moduleCache = /* @__PURE__ */ new Map()}
|
|
374
|
+
__init2() {this.moduleDeps = /* @__PURE__ */ new Map()}
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
__init3() {this.moduleType = "cjs"}
|
|
379
|
+
__init4() {this._mockData = {}}
|
|
1209
380
|
get mockData() {
|
|
1210
381
|
return this._mockData;
|
|
1211
382
|
}
|
|
1212
|
-
|
|
383
|
+
run() {
|
|
1213
384
|
const { include, exclude } = this.options;
|
|
1214
|
-
const includeFilter = (0,
|
|
1215
|
-
|
|
1216
|
-
});
|
|
1217
|
-
(0, import_fast_glob2.default)(include, { cwd: this.cwd }).then(
|
|
385
|
+
const includeFilter = _pluginutils.createFilter.call(void 0, include, exclude, { resolve: false });
|
|
386
|
+
_fastglob2.default.call(void 0, include, { cwd: this.cwd }).then(
|
|
1218
387
|
(files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))
|
|
1219
|
-
).then((loadList) => (0,
|
|
388
|
+
).then((loadList) => _utils.promiseParallel.call(void 0, loadList, 10)).then(() => this.updateMockList());
|
|
1220
389
|
this.watchMockEntry();
|
|
1221
390
|
this.watchDeps();
|
|
1222
391
|
let timer = null;
|
|
@@ -1242,27 +411,27 @@ var MockLoader = class extends import_node_events.default {
|
|
|
1242
411
|
}
|
|
1243
412
|
watchMockEntry() {
|
|
1244
413
|
const { include } = this.options;
|
|
1245
|
-
const [firstGlob, ...otherGlob] = include;
|
|
1246
|
-
const watcher = this.mockWatcher =
|
|
414
|
+
const [firstGlob, ...otherGlob] = _utils.toArray.call(void 0, include);
|
|
415
|
+
const watcher = this.mockWatcher = _chokidar2.default.watch(firstGlob, {
|
|
1247
416
|
ignoreInitial: true,
|
|
1248
417
|
cwd: this.cwd
|
|
1249
418
|
});
|
|
1250
419
|
if (otherGlob.length > 0)
|
|
1251
420
|
otherGlob.forEach((glob) => watcher.add(glob));
|
|
1252
421
|
watcher.on("add", async (filepath) => {
|
|
1253
|
-
filepath = normalizePath(filepath);
|
|
422
|
+
filepath = _chunkS76FMTCDcjs.normalizePath.call(void 0, filepath);
|
|
1254
423
|
this.emit("mock:update", filepath);
|
|
1255
|
-
debug("watcher:add", filepath);
|
|
424
|
+
_chunkS76FMTCDcjs.debug.call(void 0, "watcher:add", filepath);
|
|
1256
425
|
});
|
|
1257
426
|
watcher.on("change", async (filepath) => {
|
|
1258
|
-
filepath = normalizePath(filepath);
|
|
427
|
+
filepath = _chunkS76FMTCDcjs.normalizePath.call(void 0, filepath);
|
|
1259
428
|
this.emit("mock:update", filepath);
|
|
1260
|
-
debug("watcher:change", filepath);
|
|
429
|
+
_chunkS76FMTCDcjs.debug.call(void 0, "watcher:change", filepath);
|
|
1261
430
|
});
|
|
1262
431
|
watcher.on("unlink", async (filepath) => {
|
|
1263
|
-
filepath = normalizePath(filepath);
|
|
432
|
+
filepath = _chunkS76FMTCDcjs.normalizePath.call(void 0, filepath);
|
|
1264
433
|
this.emit("mock:unlink", filepath);
|
|
1265
|
-
debug("watcher:unlink", filepath);
|
|
434
|
+
_chunkS76FMTCDcjs.debug.call(void 0, "watcher:unlink", filepath);
|
|
1266
435
|
});
|
|
1267
436
|
}
|
|
1268
437
|
/**
|
|
@@ -1271,19 +440,19 @@ var MockLoader = class extends import_node_events.default {
|
|
|
1271
440
|
*/
|
|
1272
441
|
watchDeps() {
|
|
1273
442
|
const oldDeps = [];
|
|
1274
|
-
this.depsWatcher =
|
|
443
|
+
this.depsWatcher = _chokidar2.default.watch([], {
|
|
1275
444
|
ignoreInitial: true,
|
|
1276
445
|
cwd: this.cwd
|
|
1277
446
|
});
|
|
1278
447
|
this.depsWatcher.on("change", (filepath) => {
|
|
1279
|
-
filepath = normalizePath(filepath);
|
|
448
|
+
filepath = _chunkS76FMTCDcjs.normalizePath.call(void 0, filepath);
|
|
1280
449
|
const mockFiles = this.moduleDeps.get(filepath);
|
|
1281
|
-
mockFiles
|
|
450
|
+
_optionalChain([mockFiles, 'optionalAccess', _4 => _4.forEach, 'call', _5 => _5((file) => {
|
|
1282
451
|
this.emit("mock:update", file);
|
|
1283
|
-
});
|
|
452
|
+
})]);
|
|
1284
453
|
});
|
|
1285
454
|
this.depsWatcher.on("unlink", (filepath) => {
|
|
1286
|
-
filepath = normalizePath(filepath);
|
|
455
|
+
filepath = _chunkS76FMTCDcjs.normalizePath.call(void 0, filepath);
|
|
1287
456
|
this.moduleDeps.delete(filepath);
|
|
1288
457
|
});
|
|
1289
458
|
this.on("update:deps", () => {
|
|
@@ -1296,12 +465,11 @@ var MockLoader = class extends import_node_events.default {
|
|
|
1296
465
|
});
|
|
1297
466
|
}
|
|
1298
467
|
close() {
|
|
1299
|
-
|
|
1300
|
-
(
|
|
1301
|
-
(_b = this.depsWatcher) == null ? void 0 : _b.close();
|
|
468
|
+
_optionalChain([this, 'access', _6 => _6.mockWatcher, 'optionalAccess', _7 => _7.close, 'call', _8 => _8()]);
|
|
469
|
+
_optionalChain([this, 'access', _9 => _9.depsWatcher, 'optionalAccess', _10 => _10.close, 'call', _11 => _11()]);
|
|
1302
470
|
}
|
|
1303
471
|
updateMockList() {
|
|
1304
|
-
this._mockData = transformMockData(this.moduleCache);
|
|
472
|
+
this._mockData = _chunkS76FMTCDcjs.transformMockData.call(void 0, this.moduleCache);
|
|
1305
473
|
}
|
|
1306
474
|
updateModuleDeps(filepath, deps) {
|
|
1307
475
|
Object.keys(deps).forEach((mPath) => {
|
|
@@ -1331,227 +499,25 @@ var MockLoader = class extends import_node_events.default {
|
|
|
1331
499
|
{ isESM, define, alias, cwd: this.cwd }
|
|
1332
500
|
);
|
|
1333
501
|
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);
|
|
502
|
+
const raw = await loadFromCode({ filepath, code, isESM, cwd: this.cwd }) || {};
|
|
503
|
+
this.moduleCache.set(filepath, _chunkS76FMTCDcjs.transformRawData.call(void 0, raw, filepath));
|
|
1356
504
|
this.updateModuleDeps(filepath, deps);
|
|
1357
505
|
} catch (e) {
|
|
1358
506
|
console.error(e);
|
|
1359
507
|
}
|
|
1360
508
|
}
|
|
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
|
-
}
|
|
509
|
+
}, _class);
|
|
1523
510
|
|
|
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", () => {
|
|
511
|
+
// src/core/mockMiddleware.ts
|
|
512
|
+
function mockServerMiddleware(options, server, ws) {
|
|
513
|
+
const compiler = createMockCompiler(options);
|
|
514
|
+
compiler.run();
|
|
515
|
+
compiler.on("mock:update-end", () => {
|
|
1539
516
|
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
|
|
517
|
+
_optionalChain([ws, 'optionalAccess', _12 => _12.send, 'call', _13 => _13({ type: "full-reload" })]);
|
|
1554
518
|
});
|
|
519
|
+
_optionalChain([server, 'optionalAccess', _14 => _14.on, 'call', _15 => _15("close", () => compiler.close())]);
|
|
520
|
+
_chunkS76FMTCDcjs.mockWebSocket.call(void 0, compiler, server, options);
|
|
1555
521
|
const middlewares = [];
|
|
1556
522
|
middlewares.push(
|
|
1557
523
|
/**
|
|
@@ -1565,55 +531,116 @@ function mockServerMiddleware(config, options, httpServer, ws) {
|
|
|
1565
531
|
* 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
|
|
1566
532
|
* 而用户的配置也仅对 mock 的接口生效。
|
|
1567
533
|
*/
|
|
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
|
-
})
|
|
534
|
+
corsMiddleware(compiler, options),
|
|
535
|
+
_chunkS76FMTCDcjs.baseMiddleware.call(void 0, compiler, options)
|
|
1577
536
|
);
|
|
1578
537
|
return middlewares.filter(Boolean);
|
|
1579
538
|
}
|
|
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
|
-
)) {
|
|
539
|
+
function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
|
|
540
|
+
return !corsOptions ? void 0 : function(req, res, next) {
|
|
541
|
+
const { pathname } = _chunkS76FMTCDcjs.urlParse.call(void 0, req.url);
|
|
542
|
+
if (!pathname || proxies.length === 0 || !proxies.some((context) => _chunkS76FMTCDcjs.doesProxyContextMatchUrl.call(void 0, context, req.url))) {
|
|
1600
543
|
return next();
|
|
1601
544
|
}
|
|
1602
|
-
const mockData =
|
|
545
|
+
const mockData = compiler.mockData;
|
|
1603
546
|
const mockUrl = Object.keys(mockData).find(
|
|
1604
|
-
(key) => (0,
|
|
547
|
+
(key) => _pathtoregexp.pathToRegexp.call(void 0, key).test(pathname)
|
|
1605
548
|
);
|
|
1606
549
|
if (!mockUrl)
|
|
1607
550
|
return next();
|
|
1608
|
-
(0,
|
|
551
|
+
_cors2.default.call(void 0, corsOptions)(req, res, next);
|
|
1609
552
|
};
|
|
1610
553
|
}
|
|
1611
554
|
|
|
1612
|
-
// src/
|
|
1613
|
-
|
|
555
|
+
// src/core/resolvePluginOptions.ts
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
// src/core/define.ts
|
|
561
|
+
|
|
562
|
+
function viteDefine(config) {
|
|
563
|
+
const processNodeEnv = {};
|
|
564
|
+
const nodeEnv = _process2.default.env.NODE_ENV || config.mode;
|
|
565
|
+
Object.assign(processNodeEnv, {
|
|
566
|
+
"process.env.NODE_ENV": JSON.stringify(nodeEnv),
|
|
567
|
+
"global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
|
|
568
|
+
"globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
|
|
569
|
+
});
|
|
570
|
+
const userDefine = {};
|
|
571
|
+
const userDefineEnv = {};
|
|
572
|
+
for (const key in config.define) {
|
|
573
|
+
const val = config.define[key];
|
|
574
|
+
const isMetaEnv = key.startsWith("import.meta.env.");
|
|
575
|
+
if (typeof val === "string") {
|
|
576
|
+
if (canJsonParse(val)) {
|
|
577
|
+
userDefine[key] = val;
|
|
578
|
+
if (isMetaEnv)
|
|
579
|
+
userDefineEnv[key.slice(16)] = val;
|
|
580
|
+
}
|
|
581
|
+
} else {
|
|
582
|
+
userDefine[key] = handleDefineValue(val);
|
|
583
|
+
if (isMetaEnv)
|
|
584
|
+
userDefineEnv[key.slice(16)] = val;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
const importMetaKeys = {};
|
|
588
|
+
const importMetaEnvKeys = {};
|
|
589
|
+
const importMetaFallbackKeys = {};
|
|
590
|
+
importMetaKeys["import.meta.hot"] = `undefined`;
|
|
591
|
+
for (const key in config.env) {
|
|
592
|
+
const val = JSON.stringify(config.env[key]);
|
|
593
|
+
importMetaKeys[`import.meta.env.${key}`] = val;
|
|
594
|
+
importMetaEnvKeys[key] = val;
|
|
595
|
+
}
|
|
596
|
+
importMetaFallbackKeys["import.meta.env"] = `undefined`;
|
|
597
|
+
const define = {
|
|
598
|
+
...processNodeEnv,
|
|
599
|
+
...importMetaKeys,
|
|
600
|
+
...userDefine,
|
|
601
|
+
...importMetaFallbackKeys
|
|
602
|
+
};
|
|
603
|
+
if ("import.meta.env" in define) {
|
|
604
|
+
define["import.meta.env"] = serializeDefine({
|
|
605
|
+
...importMetaEnvKeys,
|
|
606
|
+
...userDefineEnv
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
return define;
|
|
610
|
+
}
|
|
611
|
+
function serializeDefine(define) {
|
|
612
|
+
let res = `{`;
|
|
613
|
+
const keys = Object.keys(define);
|
|
614
|
+
for (let i = 0; i < keys.length; i++) {
|
|
615
|
+
const key = keys[i];
|
|
616
|
+
const val = define[key];
|
|
617
|
+
res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
|
|
618
|
+
if (i !== keys.length - 1)
|
|
619
|
+
res += `, `;
|
|
620
|
+
}
|
|
621
|
+
return `${res}}`;
|
|
622
|
+
}
|
|
623
|
+
function handleDefineValue(value) {
|
|
624
|
+
if (typeof value === "undefined")
|
|
625
|
+
return "undefined";
|
|
626
|
+
if (typeof value === "string")
|
|
627
|
+
return value;
|
|
628
|
+
return JSON.stringify(value);
|
|
629
|
+
}
|
|
630
|
+
function canJsonParse(value) {
|
|
631
|
+
try {
|
|
632
|
+
JSON.parse(value);
|
|
633
|
+
return true;
|
|
634
|
+
} catch (e5) {
|
|
635
|
+
return false;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// src/core/resolvePluginOptions.ts
|
|
640
|
+
function resolvePluginOptions({
|
|
1614
641
|
prefix = [],
|
|
1615
642
|
wsPrefix = [],
|
|
1616
|
-
cwd
|
|
643
|
+
cwd,
|
|
1617
644
|
include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
|
|
1618
645
|
exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
|
|
1619
646
|
reload = false,
|
|
@@ -1624,15 +651,43 @@ function mockDevServerPlugin({
|
|
|
1624
651
|
cookiesOptions = {},
|
|
1625
652
|
bodyParserOptions = {},
|
|
1626
653
|
priority = {}
|
|
1627
|
-
}
|
|
1628
|
-
const
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
654
|
+
}, config) {
|
|
655
|
+
const logger = _chunkS76FMTCDcjs.createLogger.call(void 0, "vite:mock", _utils.isBoolean.call(void 0, log) ? log ? "info" : "error" : log);
|
|
656
|
+
const { httpProxies } = _chunkS76FMTCDcjs.ensureProxies.call(void 0, config.server.proxy || {});
|
|
657
|
+
const proxies = _utils.uniq.call(void 0, [..._utils.toArray.call(void 0, prefix), ...httpProxies]);
|
|
658
|
+
const wsProxies = _utils.toArray.call(void 0, wsPrefix);
|
|
659
|
+
if (!proxies.length && !wsProxies.length)
|
|
660
|
+
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")}`);
|
|
661
|
+
const enabled = cors2 === false ? false : config.server.cors !== false;
|
|
662
|
+
let corsOptions = {};
|
|
663
|
+
if (enabled && config.server.cors !== false) {
|
|
664
|
+
corsOptions = {
|
|
665
|
+
...corsOptions,
|
|
666
|
+
...typeof config.server.cors === "boolean" ? {} : config.server.cors
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
if (enabled && cors2 !== false) {
|
|
670
|
+
corsOptions = {
|
|
671
|
+
...corsOptions,
|
|
672
|
+
...typeof cors2 === "boolean" ? {} : cors2
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
const alias = [];
|
|
676
|
+
const aliasConfig = config.resolve.alias || [];
|
|
677
|
+
if (_utils.isArray.call(void 0, aliasConfig)) {
|
|
678
|
+
alias.push(...aliasConfig);
|
|
679
|
+
} else {
|
|
680
|
+
Object.entries(aliasConfig).forEach(([find, replacement]) => {
|
|
681
|
+
alias.push({ find, replacement });
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
cwd: cwd || _process2.default.cwd(),
|
|
1632
686
|
include,
|
|
1633
687
|
exclude,
|
|
688
|
+
context: config.root,
|
|
1634
689
|
reload,
|
|
1635
|
-
cors:
|
|
690
|
+
cors: enabled ? corsOptions : false,
|
|
1636
691
|
cookiesOptions,
|
|
1637
692
|
log,
|
|
1638
693
|
formidableOptions: {
|
|
@@ -1648,42 +703,50 @@ function mockDevServerPlugin({
|
|
|
1648
703
|
log: "error"
|
|
1649
704
|
},
|
|
1650
705
|
typeof build2 === "object" ? build2 : {}
|
|
1651
|
-
) : false
|
|
706
|
+
) : false,
|
|
707
|
+
proxies,
|
|
708
|
+
wsProxies,
|
|
709
|
+
logger,
|
|
710
|
+
alias,
|
|
711
|
+
define: viteDefine(config)
|
|
1652
712
|
};
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/plugin.ts
|
|
716
|
+
function mockDevServerPlugin(options = {}) {
|
|
717
|
+
const plugins = [serverPlugin(options)];
|
|
718
|
+
if (options.build)
|
|
719
|
+
plugins.push(buildPlugin(options));
|
|
1656
720
|
return plugins;
|
|
1657
721
|
}
|
|
1658
|
-
function buildPlugin(
|
|
722
|
+
function buildPlugin(options) {
|
|
1659
723
|
let viteConfig = {};
|
|
724
|
+
let resolvedOptions;
|
|
1660
725
|
return {
|
|
1661
726
|
name: "vite-plugin-mock-dev-server-generator",
|
|
1662
727
|
enforce: "post",
|
|
1663
728
|
apply: "build",
|
|
1664
729
|
configResolved(config) {
|
|
1665
730
|
viteConfig = config;
|
|
731
|
+
resolvedOptions = resolvePluginOptions(options, config);
|
|
1666
732
|
config.logger.warn("");
|
|
1667
733
|
},
|
|
1668
734
|
async buildEnd(error) {
|
|
1669
|
-
if (error)
|
|
735
|
+
if (error || viteConfig.command !== "build")
|
|
1670
736
|
return;
|
|
1671
|
-
|
|
1672
|
-
return;
|
|
1673
|
-
await generateMockServer(this, viteConfig, pluginOptions);
|
|
737
|
+
await generateMockServer(this, resolvedOptions);
|
|
1674
738
|
}
|
|
1675
739
|
};
|
|
1676
740
|
}
|
|
1677
|
-
function serverPlugin(
|
|
1678
|
-
let
|
|
741
|
+
function serverPlugin(options) {
|
|
742
|
+
let resolvedOptions;
|
|
1679
743
|
return {
|
|
1680
744
|
name: "vite-plugin-mock-dev-server",
|
|
1681
745
|
enforce: "pre",
|
|
1682
746
|
apply: "serve",
|
|
1683
747
|
config(config) {
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
if (wsPrefix.length && ((_a = config.server) == null ? void 0 : _a.proxy)) {
|
|
748
|
+
const wsPrefix = _utils.toArray.call(void 0, options.wsPrefix);
|
|
749
|
+
if (wsPrefix.length && _optionalChain([config, 'access', _16 => _16.server, 'optionalAccess', _17 => _17.proxy])) {
|
|
1687
750
|
const proxy = {};
|
|
1688
751
|
Object.keys(config.server.proxy).forEach((key) => {
|
|
1689
752
|
if (!wsPrefix.includes(key))
|
|
@@ -1691,124 +754,36 @@ function serverPlugin(pluginOptions) {
|
|
|
1691
754
|
});
|
|
1692
755
|
config.server.proxy = proxy;
|
|
1693
756
|
}
|
|
1694
|
-
recoverRequest(config);
|
|
757
|
+
_chunkS76FMTCDcjs.recoverRequest.call(void 0, config);
|
|
1695
758
|
},
|
|
1696
759
|
configResolved(config) {
|
|
1697
|
-
|
|
760
|
+
resolvedOptions = resolvePluginOptions(options, config);
|
|
1698
761
|
config.logger.warn("");
|
|
1699
762
|
},
|
|
1700
|
-
configureServer({ middlewares,
|
|
1701
|
-
const middlewareList = mockServerMiddleware(
|
|
1702
|
-
config,
|
|
1703
|
-
pluginOptions,
|
|
1704
|
-
httpServer,
|
|
1705
|
-
ws
|
|
1706
|
-
);
|
|
763
|
+
configureServer({ middlewares, httpServer, ws }) {
|
|
764
|
+
const middlewareList = mockServerMiddleware(resolvedOptions, httpServer, ws);
|
|
1707
765
|
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
1708
766
|
},
|
|
1709
767
|
configurePreviewServer({ middlewares, httpServer }) {
|
|
1710
|
-
const middlewareList = mockServerMiddleware(
|
|
1711
|
-
viteConfig,
|
|
1712
|
-
pluginOptions,
|
|
1713
|
-
httpServer
|
|
1714
|
-
);
|
|
768
|
+
const middlewareList = mockServerMiddleware(resolvedOptions, httpServer);
|
|
1715
769
|
middlewareList.forEach((middleware) => middlewares.use(middleware));
|
|
1716
770
|
}
|
|
1717
771
|
};
|
|
1718
772
|
}
|
|
1719
773
|
|
|
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
774
|
// src/index.ts
|
|
1789
775
|
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
776
|
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
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;
|