rspack-plugin-mock 1.2.0 → 2.0.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.
@@ -1,22 +1,20 @@
1
- import { baseMiddleware, createLogger, doesProxyContextMatchUrl, lookupFile, normalizePath, packageDir, transformMockData, transformRawData, urlParse, vfs } from "./logger-C48_LmdS.js";
1
+ import { a as processRawData, c as normalizePath, f as getPackageDepList, i as processMockData, l as vfs, m as createMatcher, p as getPackageDeps, u as createLogger } from "./ws-BcLCWVaK.js";
2
2
  import { createRequire } from "node:module";
3
- import { isBoolean, toArray } from "@pengzhanbo/utils";
4
- import EventEmitter from "node:events";
3
+ import { attemptAsync, isBoolean, isPlainObject, toArray, uniq } from "@pengzhanbo/utils";
5
4
  import path from "node:path";
6
5
  import process from "node:process";
7
- import { createFilter } from "@rollup/pluginutils";
8
- import chokidar from "chokidar";
9
- import fastGlob from "fast-glob";
6
+ import * as rspackCore from "@rspack/core";
10
7
  import fs, { promises } from "node:fs";
11
8
  import fsp from "node:fs/promises";
12
- import color from "picocolors";
13
- import * as rspackCore from "@rspack/core";
9
+ import ansis from "ansis";
10
+ import { glob } from "tinyglobby";
14
11
  import isCore from "is-core-module";
12
+ import { loadPackageJSONSync } from "local-pkg";
15
13
  import { pathToFileURL } from "node:url";
16
- import { pathToRegexp } from "path-to-regexp";
17
- import cors from "cors";
18
-
19
- //#region src/core/createRspackCompiler.ts
14
+ import { createHash } from "node:crypto";
15
+ import EventEmitter from "node:events";
16
+ import chokidar from "chokidar";
17
+ //#region src/compiler/createRspackCompiler.ts
20
18
  const require = createRequire(import.meta.url);
21
19
  function createCompiler(options, callback) {
22
20
  const rspackOptions = resolveRspackOptions(options);
@@ -25,25 +23,22 @@ function createCompiler(options, callback) {
25
23
  const name = "[rspack:mock]";
26
24
  const logError = (...args) => {
27
25
  if (stats) stats.compilation.getLogger(name).error(...args);
28
- else console.error(color.red(name), ...args);
26
+ else console.error(ansis.red(name), ...args);
29
27
  };
30
28
  if (err) {
31
29
  logError(err.stack || err);
32
30
  if ("details" in err) logError(err.details);
33
31
  return;
34
32
  }
35
- if (stats?.hasErrors()) {
36
- const info = stats.toJson();
37
- logError(info.errors);
38
- }
33
+ if (stats?.hasErrors()) logError(stats.toJson().errors);
39
34
  const code = vfs.readFileSync("/output.js", "utf-8");
40
35
  const externals = [];
41
36
  if (!isWatch) {
42
37
  const modules = stats?.toJson().modules || [];
43
38
  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));
39
+ for (const { name } of modules) if (name?.startsWith("external")) {
40
+ const packageName = normalizePackageName(name);
41
+ if (!isCore(packageName) && !aliasList.includes(packageName)) externals.push(normalizePackageName(name));
47
42
  }
48
43
  }
49
44
  await callback({
@@ -51,12 +46,13 @@ function createCompiler(options, callback) {
51
46
  externals
52
47
  });
53
48
  }
54
- const compiler = rspackCore.rspack(rspackOptions, isWatch ? handler : void 0);
55
- if (compiler) compiler.outputFileSystem = vfs;
56
- if (!isWatch) compiler?.run(async (...args) => {
49
+ const compiler = rspackCore.rspack(rspackOptions);
50
+ compiler.outputFileSystem = vfs;
51
+ if (!isWatch) compiler.run(async (...args) => {
57
52
  await handler(...args);
58
53
  compiler.close(() => {});
59
54
  });
55
+ else compiler.watch({}, handler);
60
56
  return compiler;
61
57
  }
62
58
  function transformWithRspack(options) {
@@ -76,15 +72,18 @@ function normalizePackageName(name) {
76
72
  return scope;
77
73
  }
78
74
  function resolveRspackOptions({ cwd, isEsm = true, entryFile, plugins, alias, watch = false }) {
79
- const targets = ["node >= 18.0.0"];
75
+ const targets = ["node >= 20.0.0"];
80
76
  if (alias && "@swc/helpers" in alias) delete alias["@swc/helpers"];
77
+ const externals = getPackageDepList(cwd);
78
+ const externalPattern = new RegExp(`^(${externals.join("|")})($|/)`, "i");
81
79
  return {
82
80
  mode: "production",
83
81
  context: cwd,
84
82
  entry: entryFile,
85
83
  watch,
86
- target: "node18.0",
84
+ target: `node${(process.versions.node || "").replace(/\.\d+$/, "")}`,
87
85
  externalsType: isEsm ? "module" : "commonjs2",
86
+ externals: [externalPattern],
88
87
  resolve: {
89
88
  alias,
90
89
  extensions: [
@@ -100,10 +99,14 @@ function resolveRspackOptions({ cwd, isEsm = true, entryFile, plugins, alias, wa
100
99
  output: {
101
100
  library: { type: !isEsm ? "commonjs2" : "module" },
102
101
  filename: "output.js",
102
+ module: isEsm,
103
103
  path: "/"
104
104
  },
105
- experiments: { outputModule: isEsm },
106
105
  optimization: { minimize: !watch },
106
+ node: {
107
+ __dirname: false,
108
+ __filename: false
109
+ },
107
110
  module: { rules: [
108
111
  {
109
112
  test: /\.json5?$/,
@@ -133,192 +136,45 @@ function resolveRspackOptions({ cwd, isEsm = true, entryFile, plugins, alias, wa
133
136
  ] }
134
137
  };
135
138
  }
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
139
  //#endregion
282
- //#region src/core/loadFromCode.ts
140
+ //#region src/compiler/loadFromCode.ts
283
141
  async function loadFromCode({ filepath, code, isESM, cwd }) {
284
142
  filepath = path.resolve(cwd, filepath);
285
143
  const ext = isESM ? ".mjs" : ".cjs";
286
- const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
287
- const file = pathToFileURL(filepathTmp).toString();
144
+ const filepathTmp = `${filepath}.${getHash(code)}${ext}`;
288
145
  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
- }
146
+ const [, mod] = await attemptAsync(importDefault, String(pathToFileURL(filepathTmp)));
147
+ await attemptAsync(promises.unlink, filepathTmp);
148
+ return mod;
149
+ }
150
+ async function importDefault(filepath) {
151
+ const mod = await import(filepath);
152
+ return mod.default || mod;
153
+ }
154
+ function getHash(str) {
155
+ return createHash("md5").update(str).digest("hex");
297
156
  }
298
-
299
157
  //#endregion
300
- //#region src/core/mockCompiler.ts
158
+ //#region src/compiler/mockCompiler.ts
301
159
  function createMockCompiler(options) {
302
160
  return new MockCompiler(options);
303
161
  }
304
162
  var MockCompiler = class extends EventEmitter {
305
163
  cwd;
306
164
  mockWatcher;
307
- moduleType = "cjs";
308
165
  entryFile;
166
+ deps = [];
167
+ isESM = false;
309
168
  _mockData = {};
310
- fileFilter;
311
169
  watchInfo;
312
170
  compiler;
313
171
  constructor(options) {
314
172
  super();
315
173
  this.options = options;
316
174
  this.cwd = options.cwd || process.cwd();
317
- const { include, exclude } = this.options;
318
- this.fileFilter = createFilter(include, exclude, { resolve: false });
319
175
  try {
320
- const pkg = lookupFile(this.cwd, ["package.json"]);
321
- this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
176
+ const pkg = loadPackageJSONSync(this.cwd);
177
+ this.isESM = pkg?.type === "module";
322
178
  } catch {}
323
179
  this.entryFile = path.resolve(process.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
324
180
  }
@@ -326,11 +182,18 @@ var MockCompiler = class extends EventEmitter {
326
182
  return this._mockData;
327
183
  }
328
184
  async run() {
329
- await this.updateMockEntry();
330
- this.watchMockFiles();
185
+ const { include, exclude } = this.options;
186
+ const { pattern, ignore, isMatch } = createMatcher(include, exclude);
187
+ const files = await glob(pattern, {
188
+ ignore,
189
+ cwd: path.join(this.cwd, this.options.dir)
190
+ });
191
+ this.deps = files.map((file) => normalizePath(file));
192
+ this.updateMockEntry();
193
+ this.watchMockFiles(isMatch);
331
194
  const { plugins, alias } = this.options;
332
195
  const options = {
333
- isEsm: this.moduleType === "esm",
196
+ isEsm: this.isESM,
334
197
  cwd: this.cwd,
335
198
  plugins,
336
199
  entryFile: this.entryFile,
@@ -342,10 +205,10 @@ var MockCompiler = class extends EventEmitter {
342
205
  const result = await loadFromCode({
343
206
  filepath: "mock.bundle.js",
344
207
  code,
345
- isESM: this.moduleType === "esm",
208
+ isESM: this.isESM,
346
209
  cwd: this.cwd
347
210
  });
348
- this._mockData = transformMockData(transformRawData(result));
211
+ this._mockData = processMockData(processRawData(result));
349
212
  this.emit("update", this.watchInfo || {});
350
213
  } catch (e) {
351
214
  this.options.logger.error(e.stack || e.message);
@@ -364,93 +227,200 @@ var MockCompiler = class extends EventEmitter {
364
227
  };
365
228
  }
366
229
  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);
230
+ await writeMockEntryFile(this.entryFile, this.deps, this.cwd, this.options.dir);
374
231
  }
375
- watchMockFiles() {
376
- const { include } = this.options;
377
- const [firstGlob, ...otherGlob] = toArray(include);
378
- const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
232
+ watchMockFiles(isMatch) {
233
+ const watcher = this.mockWatcher = chokidar.watch(this.options.dir, {
379
234
  ignoreInitial: true,
380
- cwd: this.cwd
235
+ cwd: this.cwd,
236
+ ignored: (filepath, stats) => {
237
+ if (filepath.includes("node_modules")) return true;
238
+ return !!stats?.isFile() && !isMatch(filepath);
239
+ }
381
240
  });
382
- if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
383
241
  watcher.on("add", (filepath) => {
384
- if (this.fileFilter(filepath)) {
242
+ filepath = normalizePath(filepath);
243
+ if (isMatch(filepath)) {
385
244
  this.watchInfo = {
386
245
  filepath,
387
246
  type: "add"
388
247
  };
248
+ this.deps = uniq([...this.deps, filepath]);
389
249
  this.updateMockEntry();
390
250
  }
391
251
  });
392
252
  watcher.on("change", (filepath) => {
393
- if (this.fileFilter(filepath)) this.watchInfo = {
253
+ filepath = normalizePath(filepath);
254
+ if (isMatch(filepath)) this.watchInfo = {
394
255
  filepath,
395
256
  type: "change"
396
257
  };
397
258
  });
398
259
  watcher.on("unlink", async (filepath) => {
399
- this.watchInfo = {
400
- filepath,
401
- type: "unlink"
402
- };
403
- this.updateMockEntry();
260
+ filepath = normalizePath(filepath);
261
+ if (isMatch(filepath)) {
262
+ this.watchInfo = {
263
+ filepath,
264
+ type: "unlink"
265
+ };
266
+ this.deps = this.deps.filter((dep) => dep !== filepath);
267
+ this.updateMockEntry();
268
+ }
404
269
  });
405
270
  }
406
271
  };
407
-
408
272
  //#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);
273
+ //#region package.json
274
+ var name = "rspack-plugin-mock";
275
+ var version = "2.0.0";
276
+ //#endregion
277
+ //#region src/build/packageJson.ts
278
+ function generatePackageJson(options, externals) {
279
+ const deps = getPackageDeps(options.context);
280
+ const exclude = [
281
+ name,
282
+ "connect",
283
+ "cors"
284
+ ];
285
+ const mockPkg = {
286
+ name: "mock-server",
287
+ type: "module",
288
+ scripts: { start: "node index.js" },
289
+ dependencies: {
290
+ connect: "^3.7.0",
291
+ [name]: `^${version}`,
292
+ cors: "^2.8.5"
293
+ }
434
294
  };
295
+ externals.filter((dep) => !exclude.includes(dep)).forEach((dep) => {
296
+ mockPkg.dependencies[dep] = deps[dep] || "latest";
297
+ });
298
+ return JSON.stringify(mockPkg, null, 2);
435
299
  }
300
+ //#endregion
301
+ //#region src/build/serverEntryCode.ts
302
+ function generatorServerEntryCode({ proxies, wsPrefix, cookiesOptions, bodyParserOptions, priority, build }) {
303
+ const { serverPort, log } = build;
304
+ return `import { createServer } from 'node:http';
305
+ import connect from 'connect';
306
+ import corsMiddleware from 'cors';
307
+ import {
308
+ baseMiddleware,
309
+ createLogger,
310
+ mockWebSocket,
311
+ processMockData,
312
+ processRawData
313
+ } from 'rspack-plugin-mock/server';
314
+ import rawData from './mock-data.js';
315
+
316
+ const app = connect();
317
+ const server = createServer(app);
318
+ const logger = createLogger('mock-server', '${log}');
319
+ const proxies = ${JSON.stringify(proxies)};
320
+ const wsProxies = ${JSON.stringify(toArray(wsPrefix))};
321
+ const cookiesOptions = ${JSON.stringify(cookiesOptions)};
322
+ const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
323
+ const priority = ${JSON.stringify(priority)};
324
+ const mockConfig = {
325
+ mockData: processMockData(processRawData(rawData)),
326
+ on: () => {},
327
+ };
436
328
 
329
+ mockWebSocket(mockConfig, server, { wsProxies, cookiesOptions, logger });
330
+
331
+ app.use(corsMiddleware());
332
+ app.use(baseMiddleware(mockConfig, {
333
+ formidableOptions: { multiples: true },
334
+ proxies,
335
+ priority,
336
+ cookiesOptions,
337
+ bodyParserOptions,
338
+ logger,
339
+ }));
340
+
341
+ server.listen(${serverPort});
342
+
343
+ console.log('listen: http://localhost:${serverPort}');
344
+ `;
345
+ }
437
346
  //#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 }) {
347
+ //#region src/build/writeEntryFile.ts
348
+ async function writeMockEntryFile(entryFile, files, cwd, dir) {
349
+ const importers = [];
350
+ const exporters = [];
351
+ for (const [index, filepath] of files.entries()) {
352
+ const relative = normalizePath(path.join(dir, filepath));
353
+ const file = normalizePath(path.join(cwd, relative));
354
+ importers.push(`import * as m${index} from '${file}'`);
355
+ exporters.push(`[m${index}, '${relative}']`);
356
+ }
357
+ const code = `${importers.join("\n")}\n\nexport default [\n ${exporters.join(",\n ")}\n]`;
358
+ const dirname = path.dirname(entryFile);
359
+ if (!fs.existsSync(dirname)) await fsp.mkdir(dirname, { recursive: true });
360
+ await fsp.writeFile(entryFile, code, "utf8");
361
+ }
362
+ //#endregion
363
+ //#region src/build/generate.ts
364
+ async function buildMockServer(options, outputDir) {
365
+ const entryFile = path.resolve(process.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
366
+ const { pattern, ignore } = createMatcher(options.include, options.exclude);
367
+ await writeMockEntryFile(entryFile, await glob(pattern, {
368
+ ignore,
369
+ cwd: path.join(options.cwd, options.dir)
370
+ }), options.cwd, options.dir);
371
+ const { code, externals } = await transformWithRspack({
372
+ entryFile,
373
+ cwd: options.cwd,
374
+ plugins: options.plugins,
375
+ alias: options.alias
376
+ });
377
+ await fsp.unlink(entryFile);
378
+ const outputList = [
379
+ {
380
+ filename: "mock-data.js",
381
+ source: code
382
+ },
383
+ {
384
+ filename: "index.js",
385
+ source: generatorServerEntryCode(options)
386
+ },
387
+ {
388
+ filename: "package.json",
389
+ source: generatePackageJson(options, externals)
390
+ }
391
+ ];
392
+ const dist = path.resolve(outputDir, options.build.dist);
393
+ options.logger.info(`${ansis.green("✓")} generate mock server in ${ansis.cyan(path.relative(process.cwd(), dist))}`);
394
+ if (!fs.existsSync(dist)) await fsp.mkdir(dist, { recursive: true });
395
+ for (const { filename, source } of outputList) {
396
+ await fsp.writeFile(path.join(dist, filename), source, "utf8");
397
+ const sourceSize = (source.length / 1024).toFixed(2);
398
+ const space = filename.length < 24 ? " ".repeat(24 - filename.length) : "";
399
+ options.logger.info(` ${ansis.green(filename)}${space}${ansis.bold.dim(`${sourceSize} kB`)}`);
400
+ }
401
+ }
402
+ //#endregion
403
+ //#region src/options.ts
404
+ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, dir = "mock", include = ["**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [], reload = false, log = "info", cors = true, formidableOptions = {}, build = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, { alias, context, plugins, proxies: rawProxies }) {
444
405
  const logger = createLogger("rspack:mock", isBoolean(log) ? log ? "info" : "error" : log);
445
- prefix = toArray(prefix);
406
+ const proxies = [...toArray(prefix), ...rawProxies];
407
+ const wsProxies = toArray(wsPrefix);
408
+ if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${ansis.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
409
+ const enabled = !!cors;
410
+ let corsOptions = {};
411
+ if (enabled && isPlainObject(cors)) corsOptions = {
412
+ ...corsOptions,
413
+ ...cors
414
+ };
446
415
  return {
447
416
  prefix,
448
417
  wsPrefix,
449
418
  cwd: cwd || context || process.cwd(),
419
+ dir,
450
420
  include,
451
421
  exclude,
452
422
  reload,
453
- cors: cors$1,
423
+ cors: enabled ? corsOptions : false,
454
424
  cookiesOptions,
455
425
  log,
456
426
  formidableOptions: {
@@ -459,18 +429,18 @@ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["moc
459
429
  },
460
430
  bodyParserOptions,
461
431
  priority,
462
- build: build ? Object.assign({
432
+ build: build ? {
463
433
  serverPort: 8080,
464
434
  dist: "mockServer",
465
- log: "error"
466
- }, typeof build === "object" ? build : {}) : false,
435
+ log: "error",
436
+ ...typeof build === "object" ? build : {}
437
+ } : false,
467
438
  alias,
468
439
  plugins,
469
- proxies: [...proxies, ...prefix],
470
- wsProxies: toArray(wsPrefix),
440
+ proxies,
441
+ wsProxies,
471
442
  logger
472
443
  };
473
444
  }
474
-
475
445
  //#endregion
476
- export { MockCompiler, buildMockServer, createMockCompiler, createMockMiddleware, resolvePluginOptions };
446
+ export { buildMockServer as n, createMockCompiler as r, resolvePluginOptions as t };
package/dist/rsbuild.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-DPzh7nJq.js";
1
+ import { _ as WebSocketSetupContext, a as LogType, c as MockMatchPriority, d as MockRequest, f as MockResponse, g as ServerBuildOption, h as ResponseBody, i as LogLevel, l as MockMatchSpecialPriority, m as MockWebsocketItem, n as ExtraRequest, o as Method, p as MockServerPluginOptions, r as FormidableFile, s as MockHttpItem, t as BodyParserOptions, u as MockOptions } from "./types-GT6M6WuI.js";
2
2
  import { RsbuildPlugin } from "@rsbuild/core";
3
3
 
4
4
  //#region src/rsbuild.d.ts