rspack-plugin-mock 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/README.zh-CN.md +13 -5
- package/dist/{helper.d.cts → helper.d.mts} +60 -44
- package/dist/helper.mjs +4 -0
- package/dist/index.d.mts +13 -0
- package/dist/index.mjs +1 -0
- package/dist/json5-loader.cjs +1 -32
- package/dist/options-BUfaThYe.mjs +43 -0
- package/dist/rsbuild.d.mts +7 -0
- package/dist/rsbuild.mjs +1 -0
- package/dist/{mockWebsocket-DkVHpZCx.d.cts → server-4ETytB7L.d.mts} +44 -40
- package/dist/server.d.mts +3 -0
- package/dist/server.mjs +1 -0
- package/dist/{types-6lajtJPx.d.cts → types-Bt_OTa7I.d.mts} +139 -10
- package/dist/ws-BM06pHhL.mjs +1 -0
- package/package.json +40 -51
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/helper.cjs +0 -140
- package/dist/helper.d.ts +0 -110
- package/dist/helper.js +0 -136
- package/dist/index.cjs +0 -86
- package/dist/index.d.cts +0 -13
- package/dist/index.d.ts +0 -13
- package/dist/index.js +0 -80
- package/dist/logger-C0V8Cvvd.cjs +0 -800
- package/dist/logger-C48_LmdS.js +0 -710
- package/dist/mockWebsocket-qLVAe-RI.d.ts +0 -85
- package/dist/resolvePluginOptions-Da5uqlBx.cjs +0 -506
- package/dist/resolvePluginOptions-DlkIkykz.js +0 -476
- package/dist/rsbuild.cjs +0 -176
- package/dist/rsbuild.d.cts +0 -7
- package/dist/rsbuild.d.ts +0 -7
- package/dist/rsbuild.js +0 -175
- package/dist/server.cjs +0 -9
- package/dist/server.d.cts +0 -27
- package/dist/server.d.ts +0 -27
- package/dist/server.js +0 -3
- package/dist/types-DPzh7nJq.d.ts +0 -572
|
@@ -1,476 +0,0 @@
|
|
|
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 };
|
package/dist/rsbuild.cjs
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
-
const require_logger = require('./logger-C0V8Cvvd.cjs');
|
|
3
|
-
const require_resolvePluginOptions = require('./resolvePluginOptions-Da5uqlBx.cjs');
|
|
4
|
-
const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
|
|
5
|
-
const node_path = require_chunk.__toESM(require("node:path"));
|
|
6
|
-
const node_process = require_chunk.__toESM(require("node:process"));
|
|
7
|
-
const picocolors = require_chunk.__toESM(require("picocolors"));
|
|
8
|
-
const __rspack_core = require_chunk.__toESM(require("@rspack/core"));
|
|
9
|
-
const node_http = require_chunk.__toESM(require("node:http"));
|
|
10
|
-
const portfinder = require_chunk.__toESM(require("portfinder"));
|
|
11
|
-
|
|
12
|
-
//#region src/rsbuild.ts
|
|
13
|
-
function pluginMockServer(options = {}) {
|
|
14
|
-
return {
|
|
15
|
-
name: "plugin-mock-server",
|
|
16
|
-
setup(api) {
|
|
17
|
-
const rsbuildConfig = api.getRsbuildConfig();
|
|
18
|
-
const resolvedOptions = require_resolvePluginOptions.resolvePluginOptions(options, {
|
|
19
|
-
proxies: resolveConfigProxies(rsbuildConfig),
|
|
20
|
-
alias: {},
|
|
21
|
-
context: api.context.rootPath,
|
|
22
|
-
plugins: [new __rspack_core.default.DefinePlugin(rsbuildConfig.source?.define || {})]
|
|
23
|
-
});
|
|
24
|
-
if (node_process.default.env.NODE_ENV === "production") {
|
|
25
|
-
if (resolvedOptions.build) api.onAfterBuild(async () => {
|
|
26
|
-
const config = api.getNormalizedConfig();
|
|
27
|
-
await require_resolvePluginOptions.buildMockServer(resolvedOptions, node_path.default.resolve(node_process.default.cwd(), config.output.distPath.root || "dist"));
|
|
28
|
-
});
|
|
29
|
-
return;
|
|
30
|
-
}
|
|
31
|
-
const mockCompiler = require_resolvePluginOptions.createMockCompiler(resolvedOptions);
|
|
32
|
-
api.modifyRsbuildConfig((config) => {
|
|
33
|
-
updateServerProxyConfigByHttpMock(config);
|
|
34
|
-
const mockMiddleware = require_resolvePluginOptions.createMockMiddleware(mockCompiler, resolvedOptions);
|
|
35
|
-
config.dev ??= {};
|
|
36
|
-
config.dev.setupMiddlewares ??= [];
|
|
37
|
-
config.dev.setupMiddlewares.push((middlewares, server$1) => {
|
|
38
|
-
mockMiddleware(middlewares, () => server$1.sockWrite("static-changed"));
|
|
39
|
-
});
|
|
40
|
-
});
|
|
41
|
-
let port = 3079;
|
|
42
|
-
const shouldMockWs = (0, __pengzhanbo_utils.toArray)(resolvedOptions.wsPrefix).length > 0;
|
|
43
|
-
if (shouldMockWs) api.modifyRsbuildConfig(async (config) => {
|
|
44
|
-
const defaultPort = (config.server?.port || port) + 1;
|
|
45
|
-
port = await (0, portfinder.getPortPromise)({ port: defaultPort });
|
|
46
|
-
updateServerProxyConfigByWSMock(config, options.wsPrefix || [], port);
|
|
47
|
-
});
|
|
48
|
-
let server;
|
|
49
|
-
function startMockServer() {
|
|
50
|
-
mockCompiler.run();
|
|
51
|
-
if (shouldMockWs) {
|
|
52
|
-
server = (0, node_http.createServer)();
|
|
53
|
-
require_logger.mockWebSocket(mockCompiler, server, resolvedOptions);
|
|
54
|
-
server.listen(port);
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
function close() {
|
|
58
|
-
mockCompiler.close();
|
|
59
|
-
server?.close();
|
|
60
|
-
}
|
|
61
|
-
api.onAfterCreateCompiler(({ compiler }) => {
|
|
62
|
-
if ("compilers" in compiler) compiler.compilers.forEach((compiler$1) => {
|
|
63
|
-
mockCompiler.updateAlias(compiler$1.options.resolve?.alias || {});
|
|
64
|
-
});
|
|
65
|
-
else mockCompiler.updateAlias(compiler.options.resolve?.alias || {});
|
|
66
|
-
});
|
|
67
|
-
api.onAfterStartDevServer(startMockServer);
|
|
68
|
-
api.onAfterStartProdServer(startMockServer);
|
|
69
|
-
api.onExit(close);
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
function onProxyError(err, _req, res) {
|
|
74
|
-
console.error(picocolors.default.red(err?.stack || err.message));
|
|
75
|
-
res.statusCode = 500;
|
|
76
|
-
res.end();
|
|
77
|
-
}
|
|
78
|
-
function updateServerProxyConfigByHttpMock(config) {
|
|
79
|
-
if (!config.server?.proxy) return;
|
|
80
|
-
if ((0, __pengzhanbo_utils.isArray)(config.server.proxy)) config.server.proxy = config.server.proxy.map((item) => {
|
|
81
|
-
if (typeof item !== "function" && !item.ws) {
|
|
82
|
-
const onProxyReq = item.onProxyReq;
|
|
83
|
-
const onError = item.onError;
|
|
84
|
-
return {
|
|
85
|
-
...item,
|
|
86
|
-
onError: onError || onProxyError,
|
|
87
|
-
onProxyReq: (proxyReq, req, ...args) => {
|
|
88
|
-
onProxyReq?.(proxyReq, req, ...args);
|
|
89
|
-
require_logger.rewriteRequest(proxyReq, req);
|
|
90
|
-
}
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
return item;
|
|
94
|
-
});
|
|
95
|
-
else if ("target" in config.server.proxy) {
|
|
96
|
-
const onProxyReq = config.server.proxy.onProxyReq;
|
|
97
|
-
config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
|
|
98
|
-
onProxyReq?.(proxyReq, req, ...args);
|
|
99
|
-
require_logger.rewriteRequest(proxyReq, req);
|
|
100
|
-
};
|
|
101
|
-
config.server.proxy.onError ??= onProxyError;
|
|
102
|
-
} else if (config.server.proxy) {
|
|
103
|
-
const proxy = config.server.proxy;
|
|
104
|
-
Object.keys(proxy).forEach((key) => {
|
|
105
|
-
const target = proxy[key];
|
|
106
|
-
const options = typeof target === "string" ? { target } : target;
|
|
107
|
-
if (options.ws) return;
|
|
108
|
-
const { onProxyReq, onError,...rest } = options;
|
|
109
|
-
proxy[key] = {
|
|
110
|
-
...rest,
|
|
111
|
-
onProxyReq: (proxyReq, req, ...args) => {
|
|
112
|
-
onProxyReq?.(proxyReq, req, ...args);
|
|
113
|
-
require_logger.rewriteRequest(proxyReq, req);
|
|
114
|
-
},
|
|
115
|
-
onError: onError || onProxyError
|
|
116
|
-
};
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
function updateServerProxyConfigByWSMock(config, wsPrefix, port) {
|
|
121
|
-
config.server ??= {};
|
|
122
|
-
const proxy = config.server.proxy ??= {};
|
|
123
|
-
const wsTarget = `ws://localhost:${port}`;
|
|
124
|
-
const prefix = (0, __pengzhanbo_utils.toArray)(wsPrefix);
|
|
125
|
-
const has = (context) => typeof context === "string" && prefix.includes(context);
|
|
126
|
-
const used = /* @__PURE__ */ new Set();
|
|
127
|
-
function updateProxy(item) {
|
|
128
|
-
if ((0, __pengzhanbo_utils.isArray)(item.context)) item.context = item.context.filter(has);
|
|
129
|
-
else if (has(item.context)) {
|
|
130
|
-
used.add(item.context);
|
|
131
|
-
item.target = wsTarget;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
if ((0, __pengzhanbo_utils.isArray)(proxy)) {
|
|
135
|
-
for (const item of proxy) if (typeof item !== "function" && item.context && item.ws) updateProxy(item);
|
|
136
|
-
prefix.filter((context) => !used.has(context)).forEach((context) => proxy.push({
|
|
137
|
-
context,
|
|
138
|
-
target: wsTarget
|
|
139
|
-
}));
|
|
140
|
-
} else if ("target" in proxy) {
|
|
141
|
-
if (proxy.ws) {
|
|
142
|
-
updateProxy(proxy);
|
|
143
|
-
const list = config.server.proxy = [proxy];
|
|
144
|
-
prefix.filter((context) => !used.has(context)).forEach((context) => list.push({
|
|
145
|
-
context,
|
|
146
|
-
target: wsTarget
|
|
147
|
-
}));
|
|
148
|
-
}
|
|
149
|
-
} else {
|
|
150
|
-
Object.entries(proxy).forEach(([, opt]) => {
|
|
151
|
-
if (typeof opt !== "string" && opt.ws) updateProxy(opt);
|
|
152
|
-
});
|
|
153
|
-
prefix.filter((context) => !used.has(context)).forEach((context) => {
|
|
154
|
-
proxy[context] = {
|
|
155
|
-
target: wsTarget,
|
|
156
|
-
ws: true
|
|
157
|
-
};
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
function resolveConfigProxies(config) {
|
|
162
|
-
config.server ??= {};
|
|
163
|
-
const proxy = config.server.proxy ??= {};
|
|
164
|
-
const proxies = [];
|
|
165
|
-
if ((0, __pengzhanbo_utils.isArray)(proxy)) {
|
|
166
|
-
for (const item of proxy) if (typeof item !== "function" && item.context && !item.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(item.context));
|
|
167
|
-
} else if ("target" in proxy) {
|
|
168
|
-
if (!proxy.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(proxy.context));
|
|
169
|
-
} else Object.entries(proxy).forEach(([context, opt]) => {
|
|
170
|
-
if (typeof opt === "string" || !opt.ws) proxies.push(context);
|
|
171
|
-
});
|
|
172
|
-
return proxies;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
//#endregion
|
|
176
|
-
exports.pluginMockServer = pluginMockServer;
|
package/dist/rsbuild.d.cts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-6lajtJPx.cjs";
|
|
2
|
-
import { RsbuildPlugin } from "@rsbuild/core";
|
|
3
|
-
|
|
4
|
-
//#region src/rsbuild.d.ts
|
|
5
|
-
declare function pluginMockServer(options?: MockServerPluginOptions): RsbuildPlugin;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext, pluginMockServer };
|
package/dist/rsbuild.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-DPzh7nJq.js";
|
|
2
|
-
import { RsbuildPlugin } from "@rsbuild/core";
|
|
3
|
-
|
|
4
|
-
//#region src/rsbuild.d.ts
|
|
5
|
-
declare function pluginMockServer(options?: MockServerPluginOptions): RsbuildPlugin;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext, pluginMockServer };
|