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