rspack-plugin-mock 0.2.0 → 0.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.
@@ -6,6 +6,9 @@ var _url = require('url');
6
6
  var _os = require('os'); var _os2 = _interopRequireDefault(_os);
7
7
  var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
8
8
  var _pathtoregexp = require('path-to-regexp');
9
+ var _memfs = require('memfs');
10
+ var packageDir = getDirname(import.meta.url);
11
+ var vfs = _memfs.createFsFromVolume.call(void 0, new (0, _memfs.Volume)());
9
12
  function isStream(stream) {
10
13
  return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
11
14
  }
@@ -91,10 +94,6 @@ function rewriteRequest(proxyReq, req) {
91
94
  }
92
95
  }
93
96
 
94
- // src/core/mockMiddleware.ts
95
- var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);
96
-
97
-
98
97
  // src/core/baseMiddleware.ts
99
98
 
100
99
 
@@ -238,7 +237,7 @@ function matchingWeight(rules, url, priority) {
238
237
  const options = special[specialRule];
239
238
  const { rules: lowerRules, when } = _utils.isArray.call(void 0, options) ? { rules: options, when: [] } : options;
240
239
  if (lowerRules.includes(matched[0])) {
241
- if (when.length === 0 || when.some((path5) => _pathtoregexp.pathToRegexp.call(void 0, path5).test(url))) {
240
+ if (when.length === 0 || when.some((path6) => _pathtoregexp.pathToRegexp.call(void 0, path6).test(url))) {
242
241
  matched = _utils.uniq.call(void 0, [specialRule, ...matched]);
243
242
  }
244
243
  }
@@ -602,6 +601,8 @@ function requestLog(request, filepath) {
602
601
  }
603
602
 
604
603
  // src/core/mockMiddleware.ts
604
+ var _cors = require('cors'); var _cors2 = _interopRequireDefault(_cors);
605
+
605
606
  function createMockMiddleware(compiler, options) {
606
607
  function mockMiddleware(middlewares, reload) {
607
608
  middlewares.unshift(baseMiddleware(compiler, options));
@@ -643,10 +644,6 @@ function createCorsMiddleware(compiler, options) {
643
644
  };
644
645
  }
645
646
 
646
- // src/core/resolvePluginOptions.ts
647
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
648
-
649
-
650
647
  // src/core/logger.ts
651
648
 
652
649
 
@@ -689,6 +686,8 @@ function createLogger(prefix, defaultLevel = "info") {
689
686
  }
690
687
 
691
688
  // src/core/resolvePluginOptions.ts
689
+ var _process = require('process'); var _process2 = _interopRequireDefault(_process);
690
+
692
691
  function resolvePluginOptions({
693
692
  prefix = [],
694
693
  wsPrefix = [],
@@ -740,44 +739,6 @@ function resolvePluginOptions({
740
739
  };
741
740
  }
742
741
 
743
- // src/core/mockCompiler.ts
744
- var _events = require('events'); var _events2 = _interopRequireDefault(_events);
745
-
746
-
747
-
748
- var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
749
- var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
750
- var _pluginutils = require('@rollup/pluginutils');
751
- var _core = require('@rspack/core'); var rspackCore = _interopRequireWildcard(_core);
752
- var _memfs = require('memfs');
753
-
754
-
755
-
756
- // src/core/loadFromCode.ts
757
-
758
-
759
- async function loadFromCode({
760
- filepath,
761
- code,
762
- isESM,
763
- cwd
764
- }) {
765
- filepath = _path2.default.resolve(cwd, filepath);
766
- const fileBase = `${filepath}.timestamp-${Date.now()}`;
767
- const ext = isESM ? ".mjs" : ".cjs";
768
- const fileNameTmp = `${fileBase}${ext}`;
769
- await _fs.promises.writeFile(fileNameTmp, code, "utf8");
770
- try {
771
- const result = await Promise.resolve().then(() => _interopRequireWildcard(require(fileNameTmp)));
772
- return result.default || result;
773
- } finally {
774
- try {
775
- _fs2.default.unlinkSync(fileNameTmp);
776
- } catch (e2) {
777
- }
778
- }
779
- }
780
-
781
742
  // src/core/transform.ts
782
743
 
783
744
 
@@ -865,14 +826,84 @@ function keysCount(obj) {
865
826
  return Object.keys(obj).length;
866
827
  }
867
828
 
868
- // src/core/resolveRspackOptions.ts
829
+ // src/core/build.ts
830
+
831
+ var _promises = require('fs/promises'); var _promises2 = _interopRequireDefault(_promises);
832
+
833
+
834
+ var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
835
+ var _pluginutils = require('@rollup/pluginutils');
836
+
837
+
838
+
839
+ // src/core/createRspackCompiler.ts
869
840
 
870
- var _dirname = getDirname(import.meta.url);
841
+ var _core = require('@rspack/core'); var rspackCore = _interopRequireWildcard(_core);
842
+
843
+ var _iscoremodule = require('is-core-module'); var _iscoremodule2 = _interopRequireDefault(_iscoremodule);
844
+ function createCompiler(options, callback) {
845
+ const rspackOptions = resolveRspackOptions(options);
846
+ const isWatch = rspackOptions.watch === true;
847
+ async function handler(err, stats) {
848
+ const name = "[rspack:mock]";
849
+ const logError = _optionalChain([stats, 'optionalAccess', _10 => _10.compilation, 'access', _11 => _11.getLogger, 'call', _12 => _12(name), 'access', _13 => _13.error]) || ((...args) => console.error(_picocolors2.default.red(name), ...args));
850
+ if (err) {
851
+ logError(err.stack || err);
852
+ if ("details" in err) {
853
+ logError(err.details);
854
+ }
855
+ return;
856
+ }
857
+ if (_optionalChain([stats, 'optionalAccess', _14 => _14.hasErrors, 'call', _15 => _15()])) {
858
+ const info = stats.toJson();
859
+ logError(info.errors);
860
+ }
861
+ const code = vfs.readFileSync("/output.js", "utf-8");
862
+ const externals = [];
863
+ if (!isWatch) {
864
+ const modules = _optionalChain([stats, 'optionalAccess', _16 => _16.toJson, 'call', _17 => _17(), 'access', _18 => _18.modules]) || [];
865
+ const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
866
+ for (const { name: name2 } of modules) {
867
+ if (_optionalChain([name2, 'optionalAccess', _19 => _19.startsWith, 'call', _20 => _20("external")])) {
868
+ const packageName = normalizePackageName(name2);
869
+ if (!_iscoremodule2.default.call(void 0, packageName) && !aliasList.includes(packageName))
870
+ externals.push(normalizePackageName(name2));
871
+ }
872
+ }
873
+ }
874
+ await callback({ code, externals });
875
+ }
876
+ const compiler = rspackCore.rspack(rspackOptions, isWatch ? handler : void 0);
877
+ if (compiler)
878
+ compiler.outputFileSystem = vfs;
879
+ if (!isWatch) {
880
+ _optionalChain([compiler, 'optionalAccess', _21 => _21.run, 'call', _22 => _22(async (...args) => {
881
+ await handler(...args);
882
+ compiler.close(() => {
883
+ });
884
+ })]);
885
+ }
886
+ return compiler;
887
+ }
888
+ function transformWithRspack(options) {
889
+ return new Promise((resolve) => {
890
+ createCompiler({ ...options, watch: false }, (result) => {
891
+ resolve(result);
892
+ });
893
+ });
894
+ }
895
+ function normalizePackageName(name) {
896
+ const filepath = name.replace("external ", "").slice(1, -1);
897
+ const [scope, packageName] = filepath.split("/");
898
+ if (filepath[0] === "@") {
899
+ return `${scope}/${packageName}`;
900
+ }
901
+ return scope;
902
+ }
871
903
  function resolveRspackOptions({
872
904
  cwd,
873
- isEsm,
905
+ isEsm = true,
874
906
  entryFile,
875
- outputFile,
876
907
  plugins,
877
908
  alias,
878
909
  watch = false
@@ -893,15 +924,16 @@ function resolveRspackOptions({
893
924
  plugins,
894
925
  output: {
895
926
  library: { type: !isEsm ? "commonjs2" : "module" },
896
- filename: outputFile,
927
+ filename: "output.js",
897
928
  path: "/"
898
929
  },
899
930
  experiments: { outputModule: isEsm },
931
+ optimization: { minimize: !watch },
900
932
  module: {
901
933
  rules: [
902
934
  {
903
935
  test: /\.json5?$/,
904
- loader: _path2.default.join(_dirname, "json5-loader.cjs"),
936
+ loader: _path2.default.join(packageDir, "json5-loader.cjs"),
905
937
  type: "javascript/auto"
906
938
  },
907
939
  {
@@ -933,8 +965,188 @@ function resolveRspackOptions({
933
965
  };
934
966
  }
935
967
 
968
+ // src/core/build.ts
969
+ async function buildMockServer(options, outputDir) {
970
+ const entryFile = _path2.default.resolve(_process2.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
971
+ const mockFileList = await getMockFileList(options);
972
+ await writeMockEntryFile(entryFile, mockFileList, options.cwd);
973
+ const { code, externals } = await transformWithRspack({
974
+ entryFile,
975
+ cwd: options.cwd,
976
+ plugins: options.plugins,
977
+ alias: options.alias
978
+ });
979
+ await _promises2.default.unlink(entryFile);
980
+ const outputList = [
981
+ { filename: "mock-data.js", source: code },
982
+ { filename: "index.js", source: generatorServerEntryCode(options) },
983
+ { filename: "package.json", source: generatePackageJson(options, externals) }
984
+ ];
985
+ const dist = _path2.default.resolve(outputDir, options.build.dist);
986
+ options.logger.info(
987
+ `${_picocolors2.default.green("\u2713")} generate mock server in ${_picocolors2.default.cyan(_path2.default.relative(_process2.default.cwd(), dist))}`
988
+ );
989
+ if (!_fs2.default.existsSync(dist)) {
990
+ await _promises2.default.mkdir(dist, { recursive: true });
991
+ }
992
+ for (const { filename, source } of outputList) {
993
+ await _promises2.default.writeFile(_path2.default.join(dist, filename), source, "utf8");
994
+ const sourceSize = (source.length / 1024).toFixed(2);
995
+ const space = filename.length < 24 ? " ".repeat(24 - filename.length) : "";
996
+ options.logger.info(` ${_picocolors2.default.green(filename)}${space}${_picocolors2.default.bold(_picocolors2.default.dim(`${sourceSize} kB`))}`);
997
+ }
998
+ }
999
+ function generatePackageJson(options, externals) {
1000
+ const deps = getHostDependencies(options.cwd);
1001
+ const { name, version } = getPluginPackageInfo();
1002
+ const mockPkg = {
1003
+ name: "mock-server",
1004
+ type: "module",
1005
+ scripts: {
1006
+ start: "node index.js"
1007
+ },
1008
+ dependencies: {
1009
+ connect: "^3.7.0",
1010
+ [name]: `^${version}`,
1011
+ cors: "^2.8.5"
1012
+ }
1013
+ };
1014
+ externals.forEach((dep) => {
1015
+ mockPkg.dependencies[dep] = deps[dep] || "latest";
1016
+ });
1017
+ return JSON.stringify(mockPkg, null, 2);
1018
+ }
1019
+ function generatorServerEntryCode({
1020
+ proxies,
1021
+ wsPrefix,
1022
+ cookiesOptions,
1023
+ bodyParserOptions,
1024
+ priority,
1025
+ build
1026
+ }) {
1027
+ const { serverPort, log } = build;
1028
+ return `import { createServer } from 'node:http';
1029
+ import connect from 'connect';
1030
+ import corsMiddleware from 'cors';
1031
+ import {
1032
+ baseMiddleware,
1033
+ createLogger,
1034
+ mockWebSocket,
1035
+ transformMockData,
1036
+ transformRawData
1037
+ } from 'rspack-plugin-mock';
1038
+ import rawData from './mock-data.js';
1039
+
1040
+ const app = connect();
1041
+ const server = createServer(app);
1042
+ const logger = createLogger('mock-server', '${log}');
1043
+ const proxies = ${JSON.stringify(proxies)};
1044
+ const wsProxies = ${JSON.stringify(_utils.toArray.call(void 0, wsPrefix))};
1045
+ const cookiesOptions = ${JSON.stringify(cookiesOptions)};
1046
+ const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
1047
+ const priority = ${JSON.stringify(priority)};
1048
+ const data = { mockData: transformMockData(transformRawData(rawData)) };
1049
+
1050
+ mockWebSocket(data, server, { wsProxies, cookiesOptions, logger });
1051
+
1052
+ app.use(corsMiddleware());
1053
+ app.use(baseMiddleware(data, {
1054
+ formidableOptions: { multiples: true },
1055
+ proxies,
1056
+ priority,
1057
+ cookiesOptions,
1058
+ bodyParserOptions,
1059
+ logger,
1060
+ }));
1061
+
1062
+ server.listen(${serverPort});
1063
+
1064
+ console.log('listen: http://localhost:${serverPort}');
1065
+ `;
1066
+ }
1067
+ async function getMockFileList({ cwd, include, exclude }) {
1068
+ const filter = _pluginutils.createFilter.call(void 0, include, exclude, { resolve: false });
1069
+ return await _fastglob2.default.call(void 0, include, { cwd }).then((files) => files.filter(filter));
1070
+ }
1071
+ async function writeMockEntryFile(entryFile, files, cwd) {
1072
+ const importers = [];
1073
+ const exporters = [];
1074
+ for (const [index, filepath] of files.entries()) {
1075
+ const file = normalizePath(_path2.default.join(cwd, filepath));
1076
+ importers.push(`import * as m${index} from '${file}'`);
1077
+ exporters.push(`[m${index}, '${filepath}']`);
1078
+ }
1079
+ const code = `${importers.join("\n")}
1080
+
1081
+ export default [
1082
+ ${exporters.join(",\n ")}
1083
+ ]`;
1084
+ const dirname = _path2.default.dirname(entryFile);
1085
+ if (!_fs2.default.existsSync(dirname)) {
1086
+ await _promises2.default.mkdir(dirname, { recursive: true });
1087
+ }
1088
+ await _promises2.default.writeFile(entryFile, code, "utf8");
1089
+ }
1090
+ function getPluginPackageInfo() {
1091
+ let pkg = {};
1092
+ try {
1093
+ const filepath = _path2.default.join(packageDir, "../package.json");
1094
+ if (_fs2.default.existsSync(filepath)) {
1095
+ pkg = JSON.parse(_fs2.default.readFileSync(filepath, "utf8"));
1096
+ }
1097
+ } catch (e2) {
1098
+ }
1099
+ return {
1100
+ name: pkg.name || "rspack-plugin-mock",
1101
+ version: pkg.version || "latest"
1102
+ };
1103
+ }
1104
+ function getHostDependencies(context) {
1105
+ let pkg = {};
1106
+ try {
1107
+ const content = lookupFile(context, ["package.json"]);
1108
+ if (content)
1109
+ pkg = JSON.parse(content);
1110
+ } catch (e3) {
1111
+ }
1112
+ return { ...pkg.dependencies, ...pkg.devDependencies };
1113
+ }
1114
+
1115
+ // src/core/mockCompiler.ts
1116
+ var _events = require('events'); var _events2 = _interopRequireDefault(_events);
1117
+
1118
+
1119
+
1120
+ var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
1121
+
1122
+
1123
+
1124
+ // src/core/loadFromCode.ts
1125
+
1126
+
1127
+ async function loadFromCode({
1128
+ filepath,
1129
+ code,
1130
+ isESM,
1131
+ cwd
1132
+ }) {
1133
+ filepath = _path2.default.resolve(cwd, filepath);
1134
+ const fileBase = `${filepath}.timestamp-${Date.now()}`;
1135
+ const ext = isESM ? ".mjs" : ".cjs";
1136
+ const fileNameTmp = `${fileBase}${ext}`;
1137
+ await _fs.promises.writeFile(fileNameTmp, code, "utf8");
1138
+ try {
1139
+ const result = await Promise.resolve().then(() => _interopRequireWildcard(require(fileNameTmp)));
1140
+ return result.default || result;
1141
+ } finally {
1142
+ try {
1143
+ _fs2.default.unlinkSync(fileNameTmp);
1144
+ } catch (e4) {
1145
+ }
1146
+ }
1147
+ }
1148
+
936
1149
  // src/core/mockCompiler.ts
937
- var vfs = _memfs.createFsFromVolume.call(void 0, new (0, _memfs.Volume)());
938
1150
  function createMockCompiler(options) {
939
1151
  return new MockCompiler(options);
940
1152
  }
@@ -948,16 +1160,14 @@ var MockCompiler = (_class = class extends _events2.default {
948
1160
  try {
949
1161
  const pkg = lookupFile(this.cwd, ["package.json"]);
950
1162
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
951
- } catch (e3) {
1163
+ } catch (e5) {
952
1164
  }
953
1165
  this.entryFile = _path2.default.resolve(_process2.default.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
954
- this.outputFile = "mock.bundle.js";
955
1166
  }
956
1167
 
957
1168
 
958
1169
  __init() {this.moduleType = "cjs"}
959
1170
 
960
-
961
1171
  __init2() {this._mockData = {}}
962
1172
 
963
1173
 
@@ -968,39 +1178,33 @@ var MockCompiler = (_class = class extends _events2.default {
968
1178
  async run() {
969
1179
  await this.updateMockEntry();
970
1180
  this.watchMockFiles();
971
- this.createCompiler(async (err, stats) => {
972
- const name = "[rspack:mock]";
973
- const logError = _optionalChain([stats, 'optionalAccess', _10 => _10.compilation, 'access', _11 => _11.getLogger, 'call', _12 => _12(name), 'access', _13 => _13.error]) || ((...args) => console.error(_picocolors2.default.red(name), ...args));
974
- if (err) {
975
- logError(err.stack || err);
976
- if ("details" in err) {
977
- logError(err.details);
978
- }
979
- return;
980
- }
981
- if (_optionalChain([stats, 'optionalAccess', _14 => _14.hasErrors, 'call', _15 => _15()])) {
982
- const info = stats.toJson();
983
- logError(info.errors);
984
- return;
985
- }
986
- const content = vfs.readFileSync(`/${this.outputFile}`, "utf-8");
1181
+ const { plugins, alias } = this.options;
1182
+ const options = {
1183
+ isEsm: this.moduleType === "esm",
1184
+ cwd: this.cwd,
1185
+ plugins,
1186
+ entryFile: this.entryFile,
1187
+ alias,
1188
+ watch: true
1189
+ };
1190
+ this.compiler = createCompiler(options, async ({ code }) => {
987
1191
  try {
988
1192
  const result = await loadFromCode({
989
- filepath: this.outputFile,
990
- code: content,
1193
+ filepath: "mock.bundle.js",
1194
+ code,
991
1195
  isESM: this.moduleType === "esm",
992
1196
  cwd: this.cwd
993
1197
  });
994
1198
  this._mockData = transformMockData(transformRawData(result));
995
1199
  this.emit("update", this.watchInfo || {});
996
1200
  } catch (e) {
997
- logError(e);
1201
+ this.options.logger.error(e.stack || e.message);
998
1202
  }
999
1203
  });
1000
1204
  }
1001
1205
  close() {
1002
1206
  this.mockWatcher.close();
1003
- _optionalChain([this, 'access', _16 => _16.compiler, 'optionalAccess', _17 => _17.close, 'call', _18 => _18(() => {
1207
+ _optionalChain([this, 'access', _23 => _23.compiler, 'optionalAccess', _24 => _24.close, 'call', _25 => _25(() => {
1004
1208
  })]);
1005
1209
  this.emit("close");
1006
1210
  }
@@ -1012,7 +1216,7 @@ var MockCompiler = (_class = class extends _events2.default {
1012
1216
  }
1013
1217
  async updateMockEntry() {
1014
1218
  const files = await this.getMockFiles();
1015
- await this.resolveEntryFile(files);
1219
+ await writeMockEntryFile(this.entryFile, files, this.cwd);
1016
1220
  }
1017
1221
  async getMockFiles() {
1018
1222
  const { include } = this.options;
@@ -1044,40 +1248,6 @@ var MockCompiler = (_class = class extends _events2.default {
1044
1248
  this.updateMockEntry();
1045
1249
  });
1046
1250
  }
1047
- async resolveEntryFile(fileList) {
1048
- const importers = [];
1049
- const exporters = [];
1050
- for (const [index, filepath] of fileList.entries()) {
1051
- const file = normalizePath(_path2.default.join(this.cwd, filepath));
1052
- importers.push(`import * as m${index} from '${file}'`);
1053
- exporters.push(`[m${index}, '${filepath}']`);
1054
- }
1055
- const code = `${importers.join("\n")}
1056
-
1057
- export default [
1058
- ${exporters.join(",\n ")}
1059
- ]`;
1060
- const dirname = _path2.default.dirname(this.entryFile);
1061
- if (!_fs2.default.existsSync(dirname)) {
1062
- await _fs.promises.mkdir(dirname, { recursive: true });
1063
- }
1064
- await _fs.promises.writeFile(this.entryFile, code, "utf8");
1065
- }
1066
- createCompiler(callback) {
1067
- const { plugins, alias } = this.options;
1068
- const options = resolveRspackOptions({
1069
- isEsm: this.moduleType === "esm",
1070
- cwd: this.cwd,
1071
- plugins,
1072
- entryFile: this.entryFile,
1073
- outputFile: this.outputFile,
1074
- alias,
1075
- watch: true
1076
- });
1077
- this.compiler = rspackCore.rspack(options, callback);
1078
- if (this.compiler)
1079
- this.compiler.outputFileSystem = vfs;
1080
- }
1081
1251
  }, _class);
1082
1252
 
1083
1253
  // src/core/mockWebsocket.ts
@@ -1113,7 +1283,7 @@ function mockWebSocket(compiler, httpServer, {
1113
1283
  };
1114
1284
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
1115
1285
  try {
1116
- _optionalChain([mock, 'access', _19 => _19.setup, 'optionalCall', _20 => _20(wss, context)]);
1286
+ _optionalChain([mock, 'access', _26 => _26.setup, 'optionalCall', _27 => _27(wss, context)]);
1117
1287
  wss.on("close", () => wssMap.delete(pathname));
1118
1288
  wss.on("error", (e) => {
1119
1289
  logger.error(
@@ -1170,7 +1340,7 @@ ${e}
1170
1340
  }
1171
1341
  }
1172
1342
  });
1173
- _optionalChain([httpServer, 'optionalAccess', _21 => _21.on, 'call', _22 => _22("upgrade", (req, socket, head) => {
1343
+ _optionalChain([httpServer, 'optionalAccess', _28 => _28.on, 'call', _29 => _29("upgrade", (req, socket, head) => {
1174
1344
  const { pathname, query } = urlParse(req.url);
1175
1345
  if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url, req))) {
1176
1346
  return;
@@ -1218,7 +1388,7 @@ ${e}
1218
1388
  emitConnection(wss, ws, request, wssContext.connectionList);
1219
1389
  });
1220
1390
  })]);
1221
- _optionalChain([httpServer, 'optionalAccess', _23 => _23.on, 'call', _24 => _24("close", () => {
1391
+ _optionalChain([httpServer, 'optionalAccess', _30 => _30.on, 'call', _31 => _31("close", () => {
1222
1392
  for (const wssMap of poolMap.values()) {
1223
1393
  for (const wss of wssMap.values()) {
1224
1394
  const wssContext = wssContextMap.get(wss);
@@ -1234,7 +1404,7 @@ ${e}
1234
1404
  function cleanupRunner(cleanupList) {
1235
1405
  let cleanup;
1236
1406
  while (cleanup = cleanupList.shift())
1237
- _optionalChain([cleanup, 'optionalCall', _25 => _25()]);
1407
+ _optionalChain([cleanup, 'optionalCall', _32 => _32()]);
1238
1408
  }
1239
1409
 
1240
1410
 
@@ -1244,4 +1414,11 @@ function cleanupRunner(cleanupList) {
1244
1414
 
1245
1415
 
1246
1416
 
1247
- exports.waitingFor = waitingFor; exports.rewriteRequest = rewriteRequest; exports.createMockMiddleware = createMockMiddleware; exports.resolvePluginOptions = resolvePluginOptions; exports.createMockCompiler = createMockCompiler; exports.mockWebSocket = mockWebSocket;
1417
+
1418
+
1419
+
1420
+
1421
+
1422
+
1423
+
1424
+ exports.waitingFor = waitingFor; exports.rewriteRequest = rewriteRequest; exports.baseMiddleware = baseMiddleware; exports.createMockMiddleware = createMockMiddleware; exports.logLevels = logLevels; exports.createLogger = createLogger; exports.resolvePluginOptions = resolvePluginOptions; exports.transformRawData = transformRawData; exports.transformMockData = transformMockData; exports.sortByValidator = sortByValidator; exports.buildMockServer = buildMockServer; exports.createMockCompiler = createMockCompiler; exports.mockWebSocket = mockWebSocket;
@@ -5,10 +5,12 @@
5
5
 
6
6
 
7
7
 
8
- var _chunk2S4KCTKWcjs = require('./chunk-2S4KCTKW.cjs');
8
+
9
+ var _chunkI54ZNZWLcjs = require('./chunk-I54ZNZWL.cjs');
9
10
 
10
11
  // src/rspack.ts
11
12
  var _process = require('process'); var _process2 = _interopRequireDefault(_process);
13
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
12
14
  var _core = require('@rspack/core'); var _core2 = _interopRequireDefault(_core);
13
15
  var _utils = require('@pengzhanbo/utils');
14
16
  var PLUGIN_NAME = "rspack-plugin-mock";
@@ -18,13 +20,13 @@ var MockServerPlugin = class {
18
20
  }
19
21
  apply(compiler) {
20
22
  const compilerOptions = compiler.options;
23
+ const options = resolvePluginOptions2(compiler, this.options);
21
24
  if (_process2.default.env.NODE_ENV !== "production") {
22
- const options = resolvePluginOptions2(compiler, this.options);
23
- const mockCompiler = _chunk2S4KCTKWcjs.createMockCompiler.call(void 0, options);
24
- const mockMiddleware = _chunk2S4KCTKWcjs.createMockMiddleware.call(void 0, mockCompiler, options);
25
+ const mockCompiler = _chunkI54ZNZWLcjs.createMockCompiler.call(void 0, options);
26
+ const mockMiddleware = _chunkI54ZNZWLcjs.createMockMiddleware.call(void 0, mockCompiler, options);
25
27
  const setupMiddlewares = _optionalChain([compilerOptions, 'access', _ => _.devServer, 'optionalAccess', _2 => _2.setupMiddlewares]);
26
- const waitServer = _chunk2S4KCTKWcjs.waitingFor.call(void 0, (server) => {
27
- _chunk2S4KCTKWcjs.mockWebSocket.call(void 0, mockCompiler, server, options);
28
+ const waitServer = _chunkI54ZNZWLcjs.waitingFor.call(void 0, (server) => {
29
+ _chunkI54ZNZWLcjs.mockWebSocket.call(void 0, mockCompiler, server, options);
28
30
  });
29
31
  compilerOptions.devServer = {
30
32
  ...compilerOptions.devServer,
@@ -47,7 +49,7 @@ var MockServerPlugin = class {
47
49
  const onProxyReq = item.onProxyReq;
48
50
  item.onProxyReq = (proxyReq, req, ...args) => {
49
51
  _optionalChain([onProxyReq, 'optionalCall', _8 => _8(proxyReq, req, ...args)]);
50
- _chunk2S4KCTKWcjs.rewriteRequest.call(void 0, proxyReq, req);
52
+ _chunkI54ZNZWLcjs.rewriteRequest.call(void 0, proxyReq, req);
51
53
  };
52
54
  }
53
55
  return item;
@@ -60,6 +62,11 @@ var MockServerPlugin = class {
60
62
  }
61
63
  compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
62
64
  compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
65
+ } else if (options.build !== false) {
66
+ compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => _chunkI54ZNZWLcjs.buildMockServer.call(void 0,
67
+ options,
68
+ compilerOptions.output.path || _path2.default.resolve(_process2.default.cwd(), "dist")
69
+ ));
63
70
  }
64
71
  }
65
72
  };
@@ -76,7 +83,7 @@ function resolvePluginOptions2(compiler, options) {
76
83
  }
77
84
  return [];
78
85
  });
79
- return _chunk2S4KCTKWcjs.resolvePluginOptions.call(void 0, options, {
86
+ return _chunkI54ZNZWLcjs.resolvePluginOptions.call(void 0, options, {
80
87
  alias,
81
88
  context,
82
89
  plugins: _utils.toArray.call(void 0, definePluginInstance),
@@ -1,14 +1,16 @@
1
1
  import {
2
+ buildMockServer,
2
3
  createMockCompiler,
3
4
  createMockMiddleware,
4
5
  mockWebSocket,
5
6
  resolvePluginOptions,
6
7
  rewriteRequest,
7
8
  waitingFor
8
- } from "./chunk-UJAKORAH.js";
9
+ } from "./chunk-YSJVV4SH.js";
9
10
 
10
11
  // src/rspack.ts
11
12
  import process from "process";
13
+ import path from "path";
12
14
  import rspack from "@rspack/core";
13
15
  import { isString, toArray } from "@pengzhanbo/utils";
14
16
  var PLUGIN_NAME = "rspack-plugin-mock";
@@ -18,8 +20,8 @@ var MockServerPlugin = class {
18
20
  }
19
21
  apply(compiler) {
20
22
  const compilerOptions = compiler.options;
23
+ const options = resolvePluginOptions2(compiler, this.options);
21
24
  if (process.env.NODE_ENV !== "production") {
22
- const options = resolvePluginOptions2(compiler, this.options);
23
25
  const mockCompiler = createMockCompiler(options);
24
26
  const mockMiddleware = createMockMiddleware(mockCompiler, options);
25
27
  const setupMiddlewares = compilerOptions.devServer?.setupMiddlewares;
@@ -60,6 +62,11 @@ var MockServerPlugin = class {
60
62
  }
61
63
  compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
62
64
  compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
65
+ } else if (options.build !== false) {
66
+ compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => buildMockServer(
67
+ options,
68
+ compilerOptions.output.path || path.resolve(process.cwd(), "dist")
69
+ ));
63
70
  }
64
71
  }
65
72
  };