rspack-plugin-mock 1.0.1 → 1.2.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/dist/chunk-CUT6urMc.cjs +30 -0
- package/dist/helper.cjs +124 -113
- package/dist/helper.d.cts +92 -104
- package/dist/helper.d.ts +92 -104
- package/dist/helper.js +120 -113
- package/dist/index.cjs +82 -99
- package/dist/index.d.cts +10 -22
- package/dist/index.d.ts +10 -22
- package/dist/index.js +74 -97
- package/dist/json5-loader.cjs +30 -15
- package/dist/logger-C0V8Cvvd.cjs +800 -0
- package/dist/logger-C48_LmdS.js +710 -0
- package/dist/mockWebsocket-DkVHpZCx.d.cts +85 -0
- package/dist/mockWebsocket-qLVAe-RI.d.ts +85 -0
- package/dist/resolvePluginOptions-Da5uqlBx.cjs +506 -0
- package/dist/resolvePluginOptions-DlkIkykz.js +476 -0
- package/dist/rsbuild.cjs +164 -190
- package/dist/rsbuild.d.cts +5 -13
- package/dist/rsbuild.d.ts +5 -13
- package/dist/rsbuild.js +161 -188
- package/dist/server.cjs +9 -18
- package/dist/server.d.cts +21 -25
- package/dist/server.d.ts +21 -25
- package/dist/server.js +3 -18
- package/dist/types-6lajtJPx.d.cts +572 -0
- package/dist/types-DPzh7nJq.d.ts +572 -0
- package/package.json +28 -28
- package/dist/chunk-HTVJXQRM.cjs +0 -906
- package/dist/chunk-HV5L72CY.js +0 -557
- package/dist/chunk-M7F5AAOF.cjs +0 -557
- package/dist/chunk-OGWV5ZGG.js +0 -906
- package/dist/mockWebsocket-DBgZBsdo.d.ts +0 -76
- package/dist/mockWebsocket-Ki_cShTv.d.cts +0 -76
- package/dist/types-Aw0AciTG.d.cts +0 -570
- package/dist/types-Aw0AciTG.d.ts +0 -570
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import { baseMiddleware, createLogger, doesProxyContextMatchUrl, lookupFile, normalizePath, packageDir, transformMockData, transformRawData, urlParse, vfs } from "./logger-C48_LmdS.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { isBoolean, toArray } from "@pengzhanbo/utils";
|
|
4
|
+
import EventEmitter from "node:events";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import process from "node:process";
|
|
7
|
+
import { createFilter } from "@rollup/pluginutils";
|
|
8
|
+
import chokidar from "chokidar";
|
|
9
|
+
import fastGlob from "fast-glob";
|
|
10
|
+
import fs, { promises } from "node:fs";
|
|
11
|
+
import fsp from "node:fs/promises";
|
|
12
|
+
import color from "picocolors";
|
|
13
|
+
import * as rspackCore from "@rspack/core";
|
|
14
|
+
import isCore from "is-core-module";
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { pathToRegexp } from "path-to-regexp";
|
|
17
|
+
import cors from "cors";
|
|
18
|
+
|
|
19
|
+
//#region src/core/createRspackCompiler.ts
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
function createCompiler(options, callback) {
|
|
22
|
+
const rspackOptions = resolveRspackOptions(options);
|
|
23
|
+
const isWatch = rspackOptions.watch === true;
|
|
24
|
+
async function handler(err, stats) {
|
|
25
|
+
const name = "[rspack:mock]";
|
|
26
|
+
const logError = (...args) => {
|
|
27
|
+
if (stats) stats.compilation.getLogger(name).error(...args);
|
|
28
|
+
else console.error(color.red(name), ...args);
|
|
29
|
+
};
|
|
30
|
+
if (err) {
|
|
31
|
+
logError(err.stack || err);
|
|
32
|
+
if ("details" in err) logError(err.details);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (stats?.hasErrors()) {
|
|
36
|
+
const info = stats.toJson();
|
|
37
|
+
logError(info.errors);
|
|
38
|
+
}
|
|
39
|
+
const code = vfs.readFileSync("/output.js", "utf-8");
|
|
40
|
+
const externals = [];
|
|
41
|
+
if (!isWatch) {
|
|
42
|
+
const modules = stats?.toJson().modules || [];
|
|
43
|
+
const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
|
|
44
|
+
for (const { name: name$1 } of modules) if (name$1?.startsWith("external")) {
|
|
45
|
+
const packageName = normalizePackageName(name$1);
|
|
46
|
+
if (!isCore(packageName) && !aliasList.includes(packageName)) externals.push(normalizePackageName(name$1));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
await callback({
|
|
50
|
+
code,
|
|
51
|
+
externals
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
const compiler = rspackCore.rspack(rspackOptions, isWatch ? handler : void 0);
|
|
55
|
+
if (compiler) compiler.outputFileSystem = vfs;
|
|
56
|
+
if (!isWatch) compiler?.run(async (...args) => {
|
|
57
|
+
await handler(...args);
|
|
58
|
+
compiler.close(() => {});
|
|
59
|
+
});
|
|
60
|
+
return compiler;
|
|
61
|
+
}
|
|
62
|
+
function transformWithRspack(options) {
|
|
63
|
+
return new Promise((resolve) => {
|
|
64
|
+
createCompiler({
|
|
65
|
+
...options,
|
|
66
|
+
watch: false
|
|
67
|
+
}, (result) => {
|
|
68
|
+
resolve(result);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function normalizePackageName(name) {
|
|
73
|
+
const filepath = name.replace("external ", "").slice(1, -1);
|
|
74
|
+
const [scope, packageName] = filepath.split("/");
|
|
75
|
+
if (filepath[0] === "@") return `${scope}/${packageName}`;
|
|
76
|
+
return scope;
|
|
77
|
+
}
|
|
78
|
+
function resolveRspackOptions({ cwd, isEsm = true, entryFile, plugins, alias, watch = false }) {
|
|
79
|
+
const targets = ["node >= 18.0.0"];
|
|
80
|
+
if (alias && "@swc/helpers" in alias) delete alias["@swc/helpers"];
|
|
81
|
+
return {
|
|
82
|
+
mode: "production",
|
|
83
|
+
context: cwd,
|
|
84
|
+
entry: entryFile,
|
|
85
|
+
watch,
|
|
86
|
+
target: "node18.0",
|
|
87
|
+
externalsType: isEsm ? "module" : "commonjs2",
|
|
88
|
+
resolve: {
|
|
89
|
+
alias,
|
|
90
|
+
extensions: [
|
|
91
|
+
".js",
|
|
92
|
+
".ts",
|
|
93
|
+
".cjs",
|
|
94
|
+
".mjs",
|
|
95
|
+
".json5",
|
|
96
|
+
".json"
|
|
97
|
+
]
|
|
98
|
+
},
|
|
99
|
+
plugins,
|
|
100
|
+
output: {
|
|
101
|
+
library: { type: !isEsm ? "commonjs2" : "module" },
|
|
102
|
+
filename: "output.js",
|
|
103
|
+
path: "/"
|
|
104
|
+
},
|
|
105
|
+
experiments: { outputModule: isEsm },
|
|
106
|
+
optimization: { minimize: !watch },
|
|
107
|
+
module: { rules: [
|
|
108
|
+
{
|
|
109
|
+
test: /\.json5?$/,
|
|
110
|
+
loader: require.resolve("#json5-loader"),
|
|
111
|
+
type: "javascript/auto"
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
test: /\.[cm]?js$/,
|
|
115
|
+
use: [{
|
|
116
|
+
loader: "builtin:swc-loader",
|
|
117
|
+
options: {
|
|
118
|
+
jsc: { parser: { syntax: "ecmascript" } },
|
|
119
|
+
env: { targets }
|
|
120
|
+
}
|
|
121
|
+
}]
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
test: /\.[cm]?ts$/,
|
|
125
|
+
use: [{
|
|
126
|
+
loader: "builtin:swc-loader",
|
|
127
|
+
options: {
|
|
128
|
+
jsc: { parser: { syntax: "typescript" } },
|
|
129
|
+
env: { targets }
|
|
130
|
+
}
|
|
131
|
+
}]
|
|
132
|
+
}
|
|
133
|
+
] }
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/core/build.ts
|
|
139
|
+
async function buildMockServer(options, outputDir) {
|
|
140
|
+
const entryFile = path.resolve(process.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
141
|
+
const mockFileList = await getMockFileList(options);
|
|
142
|
+
await writeMockEntryFile(entryFile, mockFileList, options.cwd);
|
|
143
|
+
const { code, externals } = await transformWithRspack({
|
|
144
|
+
entryFile,
|
|
145
|
+
cwd: options.cwd,
|
|
146
|
+
plugins: options.plugins,
|
|
147
|
+
alias: options.alias
|
|
148
|
+
});
|
|
149
|
+
await fsp.unlink(entryFile);
|
|
150
|
+
const outputList = [
|
|
151
|
+
{
|
|
152
|
+
filename: "mock-data.js",
|
|
153
|
+
source: code
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
filename: "index.js",
|
|
157
|
+
source: generatorServerEntryCode(options)
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
filename: "package.json",
|
|
161
|
+
source: generatePackageJson(options, externals)
|
|
162
|
+
}
|
|
163
|
+
];
|
|
164
|
+
const dist = path.resolve(outputDir, options.build.dist);
|
|
165
|
+
options.logger.info(`${color.green("✓")} generate mock server in ${color.cyan(path.relative(process.cwd(), dist))}`);
|
|
166
|
+
if (!fs.existsSync(dist)) await fsp.mkdir(dist, { recursive: true });
|
|
167
|
+
for (const { filename, source } of outputList) {
|
|
168
|
+
await fsp.writeFile(path.join(dist, filename), source, "utf8");
|
|
169
|
+
const sourceSize = (source.length / 1024).toFixed(2);
|
|
170
|
+
const space = filename.length < 24 ? " ".repeat(24 - filename.length) : "";
|
|
171
|
+
options.logger.info(` ${color.green(filename)}${space}${color.bold(color.dim(`${sourceSize} kB`))}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function generatePackageJson(options, externals) {
|
|
175
|
+
const deps = getHostDependencies(options.cwd);
|
|
176
|
+
const { name, version } = getPluginPackageInfo();
|
|
177
|
+
const exclude = [
|
|
178
|
+
name,
|
|
179
|
+
"connect",
|
|
180
|
+
"cors"
|
|
181
|
+
];
|
|
182
|
+
const mockPkg = {
|
|
183
|
+
name: "mock-server",
|
|
184
|
+
type: "module",
|
|
185
|
+
scripts: { start: "node index.js" },
|
|
186
|
+
dependencies: {
|
|
187
|
+
connect: "^3.7.0",
|
|
188
|
+
[name]: `^${version}`,
|
|
189
|
+
cors: "^2.8.5"
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
externals.filter((dep) => !exclude.includes(dep)).forEach((dep) => {
|
|
193
|
+
mockPkg.dependencies[dep] = deps[dep] || "latest";
|
|
194
|
+
});
|
|
195
|
+
return JSON.stringify(mockPkg, null, 2);
|
|
196
|
+
}
|
|
197
|
+
function generatorServerEntryCode({ proxies, wsPrefix, cookiesOptions, bodyParserOptions, priority, build }) {
|
|
198
|
+
const { serverPort, log } = build;
|
|
199
|
+
return `import { createServer } from 'node:http';
|
|
200
|
+
import connect from 'connect';
|
|
201
|
+
import corsMiddleware from 'cors';
|
|
202
|
+
import {
|
|
203
|
+
baseMiddleware,
|
|
204
|
+
createLogger,
|
|
205
|
+
mockWebSocket,
|
|
206
|
+
transformMockData,
|
|
207
|
+
transformRawData
|
|
208
|
+
} from 'rspack-plugin-mock/server';
|
|
209
|
+
import rawData from './mock-data.js';
|
|
210
|
+
|
|
211
|
+
const app = connect();
|
|
212
|
+
const server = createServer(app);
|
|
213
|
+
const logger = createLogger('mock-server', '${log}');
|
|
214
|
+
const proxies = ${JSON.stringify(proxies)};
|
|
215
|
+
const wsProxies = ${JSON.stringify(toArray(wsPrefix))};
|
|
216
|
+
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
217
|
+
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
218
|
+
const priority = ${JSON.stringify(priority)};
|
|
219
|
+
const mockConfig = {
|
|
220
|
+
mockData: transformMockData(transformRawData(rawData)),
|
|
221
|
+
on: () => {},
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
mockWebSocket(mockConfig, server, { wsProxies, cookiesOptions, logger });
|
|
225
|
+
|
|
226
|
+
app.use(corsMiddleware());
|
|
227
|
+
app.use(baseMiddleware(mockConfig, {
|
|
228
|
+
formidableOptions: { multiples: true },
|
|
229
|
+
proxies,
|
|
230
|
+
priority,
|
|
231
|
+
cookiesOptions,
|
|
232
|
+
bodyParserOptions,
|
|
233
|
+
logger,
|
|
234
|
+
}));
|
|
235
|
+
|
|
236
|
+
server.listen(${serverPort});
|
|
237
|
+
|
|
238
|
+
console.log('listen: http://localhost:${serverPort}');
|
|
239
|
+
`;
|
|
240
|
+
}
|
|
241
|
+
async function getMockFileList({ cwd, include, exclude }) {
|
|
242
|
+
const filter = createFilter(include, exclude, { resolve: false });
|
|
243
|
+
return await fastGlob(include, { cwd }).then((files) => files.filter(filter));
|
|
244
|
+
}
|
|
245
|
+
async function writeMockEntryFile(entryFile, files, cwd) {
|
|
246
|
+
const importers = [];
|
|
247
|
+
const exporters = [];
|
|
248
|
+
for (const [index, filepath] of files.entries()) {
|
|
249
|
+
const file = normalizePath(path.join(cwd, filepath));
|
|
250
|
+
importers.push(`import * as m${index} from '${file}'`);
|
|
251
|
+
exporters.push(`[m${index}, '${filepath}']`);
|
|
252
|
+
}
|
|
253
|
+
const code = `${importers.join("\n")}\n\nexport default [\n ${exporters.join(",\n ")}\n]`;
|
|
254
|
+
const dirname = path.dirname(entryFile);
|
|
255
|
+
if (!fs.existsSync(dirname)) await fsp.mkdir(dirname, { recursive: true });
|
|
256
|
+
await fsp.writeFile(entryFile, code, "utf8");
|
|
257
|
+
}
|
|
258
|
+
function getPluginPackageInfo() {
|
|
259
|
+
let pkg = {};
|
|
260
|
+
try {
|
|
261
|
+
const filepath = path.join(packageDir, "../package.json");
|
|
262
|
+
if (fs.existsSync(filepath)) pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
|
|
263
|
+
} catch {}
|
|
264
|
+
return {
|
|
265
|
+
name: pkg.name || "rspack-plugin-mock",
|
|
266
|
+
version: pkg.version || "latest"
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function getHostDependencies(context) {
|
|
270
|
+
let pkg = {};
|
|
271
|
+
try {
|
|
272
|
+
const content = lookupFile(context, ["package.json"]);
|
|
273
|
+
if (content) pkg = JSON.parse(content);
|
|
274
|
+
} catch {}
|
|
275
|
+
return {
|
|
276
|
+
...pkg.dependencies,
|
|
277
|
+
...pkg.devDependencies
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/core/loadFromCode.ts
|
|
283
|
+
async function loadFromCode({ filepath, code, isESM, cwd }) {
|
|
284
|
+
filepath = path.resolve(cwd, filepath);
|
|
285
|
+
const ext = isESM ? ".mjs" : ".cjs";
|
|
286
|
+
const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
|
|
287
|
+
const file = pathToFileURL(filepathTmp).toString();
|
|
288
|
+
await promises.writeFile(filepathTmp, code, "utf8");
|
|
289
|
+
try {
|
|
290
|
+
const mod = await import(file);
|
|
291
|
+
return mod.default || mod;
|
|
292
|
+
} finally {
|
|
293
|
+
try {
|
|
294
|
+
fs.unlinkSync(filepathTmp);
|
|
295
|
+
} catch {}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
//#endregion
|
|
300
|
+
//#region src/core/mockCompiler.ts
|
|
301
|
+
function createMockCompiler(options) {
|
|
302
|
+
return new MockCompiler(options);
|
|
303
|
+
}
|
|
304
|
+
var MockCompiler = class extends EventEmitter {
|
|
305
|
+
cwd;
|
|
306
|
+
mockWatcher;
|
|
307
|
+
moduleType = "cjs";
|
|
308
|
+
entryFile;
|
|
309
|
+
_mockData = {};
|
|
310
|
+
fileFilter;
|
|
311
|
+
watchInfo;
|
|
312
|
+
compiler;
|
|
313
|
+
constructor(options) {
|
|
314
|
+
super();
|
|
315
|
+
this.options = options;
|
|
316
|
+
this.cwd = options.cwd || process.cwd();
|
|
317
|
+
const { include, exclude } = this.options;
|
|
318
|
+
this.fileFilter = createFilter(include, exclude, { resolve: false });
|
|
319
|
+
try {
|
|
320
|
+
const pkg = lookupFile(this.cwd, ["package.json"]);
|
|
321
|
+
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
322
|
+
} catch {}
|
|
323
|
+
this.entryFile = path.resolve(process.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
324
|
+
}
|
|
325
|
+
get mockData() {
|
|
326
|
+
return this._mockData;
|
|
327
|
+
}
|
|
328
|
+
async run() {
|
|
329
|
+
await this.updateMockEntry();
|
|
330
|
+
this.watchMockFiles();
|
|
331
|
+
const { plugins, alias } = this.options;
|
|
332
|
+
const options = {
|
|
333
|
+
isEsm: this.moduleType === "esm",
|
|
334
|
+
cwd: this.cwd,
|
|
335
|
+
plugins,
|
|
336
|
+
entryFile: this.entryFile,
|
|
337
|
+
alias,
|
|
338
|
+
watch: true
|
|
339
|
+
};
|
|
340
|
+
this.compiler = createCompiler(options, async ({ code }) => {
|
|
341
|
+
try {
|
|
342
|
+
const result = await loadFromCode({
|
|
343
|
+
filepath: "mock.bundle.js",
|
|
344
|
+
code,
|
|
345
|
+
isESM: this.moduleType === "esm",
|
|
346
|
+
cwd: this.cwd
|
|
347
|
+
});
|
|
348
|
+
this._mockData = transformMockData(transformRawData(result));
|
|
349
|
+
this.emit("update", this.watchInfo || {});
|
|
350
|
+
} catch (e) {
|
|
351
|
+
this.options.logger.error(e.stack || e.message);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
close() {
|
|
356
|
+
this.mockWatcher.close();
|
|
357
|
+
this.compiler?.close(() => {});
|
|
358
|
+
this.emit("close");
|
|
359
|
+
}
|
|
360
|
+
updateAlias(alias) {
|
|
361
|
+
this.options.alias = {
|
|
362
|
+
...this.options.alias,
|
|
363
|
+
...alias
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
async updateMockEntry() {
|
|
367
|
+
const files = await this.getMockFiles();
|
|
368
|
+
await writeMockEntryFile(this.entryFile, files, this.cwd);
|
|
369
|
+
}
|
|
370
|
+
async getMockFiles() {
|
|
371
|
+
const { include } = this.options;
|
|
372
|
+
const files = await fastGlob(include, { cwd: this.cwd });
|
|
373
|
+
return files.filter(this.fileFilter);
|
|
374
|
+
}
|
|
375
|
+
watchMockFiles() {
|
|
376
|
+
const { include } = this.options;
|
|
377
|
+
const [firstGlob, ...otherGlob] = toArray(include);
|
|
378
|
+
const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
|
|
379
|
+
ignoreInitial: true,
|
|
380
|
+
cwd: this.cwd
|
|
381
|
+
});
|
|
382
|
+
if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
|
|
383
|
+
watcher.on("add", (filepath) => {
|
|
384
|
+
if (this.fileFilter(filepath)) {
|
|
385
|
+
this.watchInfo = {
|
|
386
|
+
filepath,
|
|
387
|
+
type: "add"
|
|
388
|
+
};
|
|
389
|
+
this.updateMockEntry();
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
watcher.on("change", (filepath) => {
|
|
393
|
+
if (this.fileFilter(filepath)) this.watchInfo = {
|
|
394
|
+
filepath,
|
|
395
|
+
type: "change"
|
|
396
|
+
};
|
|
397
|
+
});
|
|
398
|
+
watcher.on("unlink", async (filepath) => {
|
|
399
|
+
this.watchInfo = {
|
|
400
|
+
filepath,
|
|
401
|
+
type: "unlink"
|
|
402
|
+
};
|
|
403
|
+
this.updateMockEntry();
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/core/mockMiddleware.ts
|
|
410
|
+
function createMockMiddleware(compiler, options) {
|
|
411
|
+
return function mockMiddleware(middlewares, reload) {
|
|
412
|
+
middlewares.unshift(baseMiddleware(compiler, options));
|
|
413
|
+
const corsMiddleware = createCorsMiddleware(compiler, options);
|
|
414
|
+
if (corsMiddleware) middlewares.unshift(corsMiddleware);
|
|
415
|
+
if (options.reload) compiler.on("update", () => reload?.());
|
|
416
|
+
return middlewares;
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
function createCorsMiddleware(compiler, options) {
|
|
420
|
+
let corsOptions = {};
|
|
421
|
+
const enabled = options.cors !== false;
|
|
422
|
+
if (enabled) corsOptions = {
|
|
423
|
+
...corsOptions,
|
|
424
|
+
...typeof options.cors === "boolean" ? {} : options.cors
|
|
425
|
+
};
|
|
426
|
+
const proxies = options.proxies;
|
|
427
|
+
return !enabled ? void 0 : function(req, res, next) {
|
|
428
|
+
const { pathname } = urlParse(req.url);
|
|
429
|
+
if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) return next();
|
|
430
|
+
const mockData = compiler.mockData;
|
|
431
|
+
const mockUrl = Object.keys(mockData).find((key) => pathToRegexp(key).test(pathname));
|
|
432
|
+
if (!mockUrl) return next();
|
|
433
|
+
cors(corsOptions)(req, res, next);
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region src/core/resolvePluginOptions.ts
|
|
439
|
+
function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [
|
|
440
|
+
"**/node_modules/**",
|
|
441
|
+
"**/.vscode/**",
|
|
442
|
+
"**/.git/**"
|
|
443
|
+
], reload = false, log = "info", cors: cors$1 = true, formidableOptions = {}, build = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, { alias, context, plugins, proxies }) {
|
|
444
|
+
const logger = createLogger("rspack:mock", isBoolean(log) ? log ? "info" : "error" : log);
|
|
445
|
+
prefix = toArray(prefix);
|
|
446
|
+
return {
|
|
447
|
+
prefix,
|
|
448
|
+
wsPrefix,
|
|
449
|
+
cwd: cwd || context || process.cwd(),
|
|
450
|
+
include,
|
|
451
|
+
exclude,
|
|
452
|
+
reload,
|
|
453
|
+
cors: cors$1,
|
|
454
|
+
cookiesOptions,
|
|
455
|
+
log,
|
|
456
|
+
formidableOptions: {
|
|
457
|
+
multiples: true,
|
|
458
|
+
...formidableOptions
|
|
459
|
+
},
|
|
460
|
+
bodyParserOptions,
|
|
461
|
+
priority,
|
|
462
|
+
build: build ? Object.assign({
|
|
463
|
+
serverPort: 8080,
|
|
464
|
+
dist: "mockServer",
|
|
465
|
+
log: "error"
|
|
466
|
+
}, typeof build === "object" ? build : {}) : false,
|
|
467
|
+
alias,
|
|
468
|
+
plugins,
|
|
469
|
+
proxies: [...proxies, ...prefix],
|
|
470
|
+
wsProxies: toArray(wsPrefix),
|
|
471
|
+
logger
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
//#endregion
|
|
476
|
+
export { MockCompiler, buildMockServer, createMockCompiler, createMockMiddleware, resolvePluginOptions };
|