rspack-plugin-mock 1.1.0 → 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 +22 -22
- 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-M7F5AAOF.cjs
DELETED
|
@@ -1,557 +0,0 @@
|
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
var _chunkHTVJXQRMcjs = require('./chunk-HTVJXQRM.cjs');
|
|
13
|
-
|
|
14
|
-
// src/core/build.ts
|
|
15
|
-
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
16
|
-
var _promises = require('fs/promises'); var _promises2 = _interopRequireDefault(_promises);
|
|
17
|
-
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
18
|
-
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
|
|
19
|
-
var _utils = require('@pengzhanbo/utils');
|
|
20
|
-
var _pluginutils = require('@rollup/pluginutils');
|
|
21
|
-
var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
|
|
22
|
-
var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
|
|
23
|
-
|
|
24
|
-
// src/core/createRspackCompiler.ts
|
|
25
|
-
var _module = require('module');
|
|
26
|
-
var _core = require('@rspack/core'); var rspackCore = _interopRequireWildcard(_core);
|
|
27
|
-
var _iscoremodule = require('is-core-module'); var _iscoremodule2 = _interopRequireDefault(_iscoremodule);
|
|
28
|
-
|
|
29
|
-
var require2 = _module.createRequire.call(void 0, 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(_picocolors2.default.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 (_optionalChain([stats, 'optionalAccess', _ => _.hasErrors, 'call', _2 => _2()])) {
|
|
50
|
-
const info = stats.toJson();
|
|
51
|
-
logError(info.errors);
|
|
52
|
-
}
|
|
53
|
-
const code = _chunkHTVJXQRMcjs.vfs.readFileSync("/output.js", "utf-8");
|
|
54
|
-
const externals = [];
|
|
55
|
-
if (!isWatch) {
|
|
56
|
-
const modules = _optionalChain([stats, 'optionalAccess', _3 => _3.toJson, 'call', _4 => _4(), 'access', _5 => _5.modules]) || [];
|
|
57
|
-
const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
|
|
58
|
-
for (const { name: name2 } of modules) {
|
|
59
|
-
if (_optionalChain([name2, 'optionalAccess', _6 => _6.startsWith, 'call', _7 => _7("external")])) {
|
|
60
|
-
const packageName = normalizePackageName(name2);
|
|
61
|
-
if (!_iscoremodule2.default.call(void 0, 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 = _chunkHTVJXQRMcjs.vfs;
|
|
71
|
-
if (!isWatch) {
|
|
72
|
-
_optionalChain([compiler, 'optionalAccess', _8 => _8.run, 'call', _9 => _9(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 = _path2.default.resolve(_process2.default.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 _promises2.default.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 = _path2.default.resolve(outputDir, options.build.dist);
|
|
180
|
-
options.logger.info(
|
|
181
|
-
`${_picocolors2.default.green("\u2713")} generate mock server in ${_picocolors2.default.cyan(_path2.default.relative(_process2.default.cwd(), dist))}`
|
|
182
|
-
);
|
|
183
|
-
if (!_fs2.default.existsSync(dist)) {
|
|
184
|
-
await _promises2.default.mkdir(dist, { recursive: true });
|
|
185
|
-
}
|
|
186
|
-
for (const { filename, source } of outputList) {
|
|
187
|
-
await _promises2.default.writeFile(_path2.default.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(` ${_picocolors2.default.green(filename)}${space}${_picocolors2.default.bold(_picocolors2.default.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(_utils.toArray.call(void 0, 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 = _pluginutils.createFilter.call(void 0, include, exclude, { resolve: false });
|
|
267
|
-
return await _fastglob2.default.call(void 0, 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 = _chunkHTVJXQRMcjs.normalizePath.call(void 0, _path2.default.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 = _path2.default.dirname(entryFile);
|
|
283
|
-
if (!_fs2.default.existsSync(dirname)) {
|
|
284
|
-
await _promises2.default.mkdir(dirname, { recursive: true });
|
|
285
|
-
}
|
|
286
|
-
await _promises2.default.writeFile(entryFile, code, "utf8");
|
|
287
|
-
}
|
|
288
|
-
function getPluginPackageInfo() {
|
|
289
|
-
let pkg = {};
|
|
290
|
-
try {
|
|
291
|
-
const filepath = _path2.default.join(_chunkHTVJXQRMcjs.packageDir, "../package.json");
|
|
292
|
-
if (_fs2.default.existsSync(filepath)) {
|
|
293
|
-
pkg = JSON.parse(_fs2.default.readFileSync(filepath, "utf8"));
|
|
294
|
-
}
|
|
295
|
-
} catch (e2) {
|
|
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 = _chunkHTVJXQRMcjs.lookupFile.call(void 0, context, ["package.json"]);
|
|
306
|
-
if (content)
|
|
307
|
-
pkg = JSON.parse(content);
|
|
308
|
-
} catch (e3) {
|
|
309
|
-
}
|
|
310
|
-
return { ...pkg.dependencies, ...pkg.devDependencies };
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// src/core/mockCompiler.ts
|
|
314
|
-
var _events = require('events'); var _events2 = _interopRequireDefault(_events);
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
// src/core/loadFromCode.ts
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
var _url = require('url');
|
|
326
|
-
async function loadFromCode({
|
|
327
|
-
filepath,
|
|
328
|
-
code,
|
|
329
|
-
isESM,
|
|
330
|
-
cwd
|
|
331
|
-
}) {
|
|
332
|
-
filepath = _path2.default.resolve(cwd, filepath);
|
|
333
|
-
const ext = isESM ? ".mjs" : ".cjs";
|
|
334
|
-
const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
|
|
335
|
-
const file = _url.pathToFileURL.call(void 0, filepathTmp).toString();
|
|
336
|
-
await _fs.promises.writeFile(filepathTmp, code, "utf8");
|
|
337
|
-
try {
|
|
338
|
-
const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(file)));
|
|
339
|
-
return mod.default || mod;
|
|
340
|
-
} finally {
|
|
341
|
-
try {
|
|
342
|
-
_fs2.default.unlinkSync(filepathTmp);
|
|
343
|
-
} catch (e4) {
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// src/core/mockCompiler.ts
|
|
349
|
-
function createMockCompiler(options) {
|
|
350
|
-
return new MockCompiler(options);
|
|
351
|
-
}
|
|
352
|
-
var MockCompiler = (_class = class extends _events2.default {
|
|
353
|
-
constructor(options) {
|
|
354
|
-
super();_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
|
|
355
|
-
this.options = options;
|
|
356
|
-
this.cwd = options.cwd || _process2.default.cwd();
|
|
357
|
-
const { include, exclude } = this.options;
|
|
358
|
-
this.fileFilter = _pluginutils.createFilter.call(void 0, include, exclude, { resolve: false });
|
|
359
|
-
try {
|
|
360
|
-
const pkg = _chunkHTVJXQRMcjs.lookupFile.call(void 0, this.cwd, ["package.json"]);
|
|
361
|
-
this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
|
|
362
|
-
} catch (e5) {
|
|
363
|
-
}
|
|
364
|
-
this.entryFile = _path2.default.resolve(_process2.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
__init() {this.moduleType = "cjs"}
|
|
369
|
-
|
|
370
|
-
__init2() {this._mockData = {}}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
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 = _chunkHTVJXQRMcjs.transformMockData.call(void 0, _chunkHTVJXQRMcjs.transformRawData.call(void 0, 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
|
-
_optionalChain([this, 'access', _10 => _10.compiler, 'optionalAccess', _11 => _11.close, 'call', _12 => _12(() => {
|
|
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 _fastglob2.default.call(void 0, include, { cwd: this.cwd });
|
|
423
|
-
return files.filter(this.fileFilter);
|
|
424
|
-
}
|
|
425
|
-
watchMockFiles() {
|
|
426
|
-
const { include } = this.options;
|
|
427
|
-
const [firstGlob, ...otherGlob] = _utils.toArray.call(void 0, include);
|
|
428
|
-
const watcher = this.mockWatcher = _chokidar2.default.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
|
-
}, _class);
|
|
451
|
-
|
|
452
|
-
// src/core/mockMiddleware.ts
|
|
453
|
-
var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);
|
|
454
|
-
var _pathtoregexp = require('path-to-regexp');
|
|
455
|
-
function createMockMiddleware(compiler, options) {
|
|
456
|
-
function mockMiddleware(middlewares, reload) {
|
|
457
|
-
middlewares.unshift(_chunkHTVJXQRMcjs.baseMiddleware.call(void 0, compiler, options));
|
|
458
|
-
const corsMiddleware = createCorsMiddleware(compiler, options);
|
|
459
|
-
if (corsMiddleware) {
|
|
460
|
-
middlewares.unshift(corsMiddleware);
|
|
461
|
-
}
|
|
462
|
-
if (options.reload) {
|
|
463
|
-
compiler.on("update", () => _optionalChain([reload, 'optionalCall', _13 => _13()]));
|
|
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 } = _chunkHTVJXQRMcjs.urlParse.call(void 0, req.url);
|
|
481
|
-
if (!pathname || proxies.length === 0 || !proxies.some(
|
|
482
|
-
(context) => _chunkHTVJXQRMcjs.doesProxyContextMatchUrl.call(void 0, context, req.url, req)
|
|
483
|
-
)) {
|
|
484
|
-
return next();
|
|
485
|
-
}
|
|
486
|
-
const mockData = compiler.mockData;
|
|
487
|
-
const mockUrl = Object.keys(mockData).find(
|
|
488
|
-
(key) => _pathtoregexp.pathToRegexp.call(void 0, key).test(pathname)
|
|
489
|
-
);
|
|
490
|
-
if (!mockUrl)
|
|
491
|
-
return next();
|
|
492
|
-
_cors2.default.call(void 0, corsOptions)(req, res, next);
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
// src/core/resolvePluginOptions.ts
|
|
497
|
-
|
|
498
|
-
|
|
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 = _chunkHTVJXQRMcjs.createLogger.call(void 0,
|
|
515
|
-
"rspack:mock",
|
|
516
|
-
_utils.isBoolean.call(void 0, log) ? log ? "info" : "error" : log
|
|
517
|
-
);
|
|
518
|
-
prefix = _utils.toArray.call(void 0, prefix);
|
|
519
|
-
return {
|
|
520
|
-
prefix,
|
|
521
|
-
wsPrefix,
|
|
522
|
-
cwd: cwd || context || _process2.default.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: _utils.toArray.call(void 0, wsPrefix),
|
|
547
|
-
logger
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
exports.buildMockServer = buildMockServer; exports.createMockCompiler = createMockCompiler; exports.MockCompiler = MockCompiler; exports.createMockMiddleware = createMockMiddleware; exports.resolvePluginOptions = resolvePluginOptions;
|