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.
- package/README.md +110 -15
- package/README.zh-CN.md +888 -0
- package/dist/{chunk-2S4KCTKW.cjs → chunk-I54ZNZWL.cjs} +294 -117
- package/dist/{chunk-T4AI3L6R.cjs → chunk-OYBMX3GQ.cjs} +15 -8
- package/dist/{chunk-P6DRAHHI.js → chunk-P5FOCSCE.js} +9 -2
- package/dist/{chunk-UJAKORAH.js → chunk-YSJVV4SH.js} +291 -114
- package/dist/index.cjs +17 -3
- package/dist/index.d.cts +28 -9
- package/dist/index.d.ts +28 -9
- package/dist/index.js +18 -4
- package/dist/rsbuild.cjs +85 -64
- package/dist/rsbuild.js +76 -55
- package/dist/{rspack-E_yBzR5v.d.ts → rspack-BB-Jtq4f.d.cts} +6 -3
- package/dist/{rspack-BcdszmoI.d.cts → rspack-h3uerEgg.d.ts} +6 -3
- package/dist/rspack.cjs +3 -3
- package/dist/rspack.d.cts +1 -1
- package/dist/rspack.d.ts +1 -1
- package/dist/rspack.js +2 -2
- package/package.json +10 -9
|
@@ -6,6 +6,9 @@ import { URL as URL2, fileURLToPath } from "url";
|
|
|
6
6
|
import os from "os";
|
|
7
7
|
import Debug from "debug";
|
|
8
8
|
import { match } from "path-to-regexp";
|
|
9
|
+
import { Volume, createFsFromVolume } from "memfs";
|
|
10
|
+
var packageDir = getDirname(import.meta.url);
|
|
11
|
+
var vfs = createFsFromVolume(new 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
|
-
import cors from "cors";
|
|
96
|
-
import { pathToRegexp as pathToRegexp3 } from "path-to-regexp";
|
|
97
|
-
|
|
98
97
|
// src/core/baseMiddleware.ts
|
|
99
98
|
import { Buffer as Buffer2 } from "buffer";
|
|
100
99
|
import {
|
|
@@ -238,7 +237,7 @@ function matchingWeight(rules, url, priority) {
|
|
|
238
237
|
const options = special[specialRule];
|
|
239
238
|
const { rules: lowerRules, when } = isArray(options) ? { rules: options, when: [] } : options;
|
|
240
239
|
if (lowerRules.includes(matched[0])) {
|
|
241
|
-
if (when.length === 0 || when.some((
|
|
240
|
+
if (when.length === 0 || when.some((path6) => pathToRegexp(path6).test(url))) {
|
|
242
241
|
matched = uniq([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
|
+
import cors from "cors";
|
|
605
|
+
import { pathToRegexp as pathToRegexp3 } from "path-to-regexp";
|
|
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
|
-
import process from "process";
|
|
648
|
-
import { isBoolean as isBoolean2, toArray } from "@pengzhanbo/utils";
|
|
649
|
-
|
|
650
647
|
// src/core/logger.ts
|
|
651
648
|
import { isBoolean } from "@pengzhanbo/utils";
|
|
652
649
|
import colors2 from "picocolors";
|
|
@@ -689,6 +686,8 @@ function createLogger(prefix, defaultLevel = "info") {
|
|
|
689
686
|
}
|
|
690
687
|
|
|
691
688
|
// src/core/resolvePluginOptions.ts
|
|
689
|
+
import process from "process";
|
|
690
|
+
import { isBoolean as isBoolean2, toArray } from "@pengzhanbo/utils";
|
|
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
|
-
import EventEmitter from "events";
|
|
745
|
-
import fs3, { promises as fsp2 } from "fs";
|
|
746
|
-
import process2 from "process";
|
|
747
|
-
import path4 from "path";
|
|
748
|
-
import fastGlob from "fast-glob";
|
|
749
|
-
import chokidar from "chokidar";
|
|
750
|
-
import { createFilter } from "@rollup/pluginutils";
|
|
751
|
-
import * as rspackCore from "@rspack/core";
|
|
752
|
-
import { Volume, createFsFromVolume } from "memfs";
|
|
753
|
-
import { toArray as toArray3 } from "@pengzhanbo/utils";
|
|
754
|
-
import color from "picocolors";
|
|
755
|
-
|
|
756
|
-
// src/core/loadFromCode.ts
|
|
757
|
-
import path2 from "path";
|
|
758
|
-
import fs2, { promises as fsp } from "fs";
|
|
759
|
-
async function loadFromCode({
|
|
760
|
-
filepath,
|
|
761
|
-
code,
|
|
762
|
-
isESM,
|
|
763
|
-
cwd
|
|
764
|
-
}) {
|
|
765
|
-
filepath = path2.resolve(cwd, filepath);
|
|
766
|
-
const fileBase = `${filepath}.timestamp-${Date.now()}`;
|
|
767
|
-
const ext = isESM ? ".mjs" : ".cjs";
|
|
768
|
-
const fileNameTmp = `${fileBase}${ext}`;
|
|
769
|
-
await fsp.writeFile(fileNameTmp, code, "utf8");
|
|
770
|
-
try {
|
|
771
|
-
const result = await import(fileNameTmp);
|
|
772
|
-
return result.default || result;
|
|
773
|
-
} finally {
|
|
774
|
-
try {
|
|
775
|
-
fs2.unlinkSync(fileNameTmp);
|
|
776
|
-
} catch {
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
742
|
// src/core/transform.ts
|
|
782
743
|
import {
|
|
783
744
|
isEmptyObject as isEmptyObject3,
|
|
@@ -865,14 +826,84 @@ function keysCount(obj) {
|
|
|
865
826
|
return Object.keys(obj).length;
|
|
866
827
|
}
|
|
867
828
|
|
|
868
|
-
// src/core/
|
|
829
|
+
// src/core/build.ts
|
|
830
|
+
import fs2 from "fs";
|
|
831
|
+
import fsp from "fs/promises";
|
|
869
832
|
import path3 from "path";
|
|
870
|
-
|
|
833
|
+
import process2 from "process";
|
|
834
|
+
import fg from "fast-glob";
|
|
835
|
+
import { createFilter } from "@rollup/pluginutils";
|
|
836
|
+
import color2 from "picocolors";
|
|
837
|
+
import { toArray as toArray3 } from "@pengzhanbo/utils";
|
|
838
|
+
|
|
839
|
+
// src/core/createRspackCompiler.ts
|
|
840
|
+
import path2 from "path";
|
|
841
|
+
import * as rspackCore from "@rspack/core";
|
|
842
|
+
import color from "picocolors";
|
|
843
|
+
import isCore from "is-core-module";
|
|
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 = stats?.compilation.getLogger(name).error || ((...args) => console.error(color.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 (stats?.hasErrors()) {
|
|
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 = stats?.toJson().modules || [];
|
|
865
|
+
const aliasList = Object.keys(options.alias || {}).map((key) => key.replace(/\$$/g, ""));
|
|
866
|
+
for (const { name: name2 } of modules) {
|
|
867
|
+
if (name2?.startsWith("external")) {
|
|
868
|
+
const packageName = normalizePackageName(name2);
|
|
869
|
+
if (!isCore(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
|
+
compiler?.run(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:
|
|
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:
|
|
936
|
+
loader: path2.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 = path3.resolve(process2.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 fsp.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 = path3.resolve(outputDir, options.build.dist);
|
|
986
|
+
options.logger.info(
|
|
987
|
+
`${color2.green("\u2713")} generate mock server in ${color2.cyan(path3.relative(process2.cwd(), dist))}`
|
|
988
|
+
);
|
|
989
|
+
if (!fs2.existsSync(dist)) {
|
|
990
|
+
await fsp.mkdir(dist, { recursive: true });
|
|
991
|
+
}
|
|
992
|
+
for (const { filename, source } of outputList) {
|
|
993
|
+
await fsp.writeFile(path3.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(` ${color2.green(filename)}${space}${color2.bold(color2.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(toArray3(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 = createFilter(include, exclude, { resolve: false });
|
|
1069
|
+
return await fg(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(path3.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 = path3.dirname(entryFile);
|
|
1085
|
+
if (!fs2.existsSync(dirname)) {
|
|
1086
|
+
await fsp.mkdir(dirname, { recursive: true });
|
|
1087
|
+
}
|
|
1088
|
+
await fsp.writeFile(entryFile, code, "utf8");
|
|
1089
|
+
}
|
|
1090
|
+
function getPluginPackageInfo() {
|
|
1091
|
+
let pkg = {};
|
|
1092
|
+
try {
|
|
1093
|
+
const filepath = path3.join(packageDir, "../package.json");
|
|
1094
|
+
if (fs2.existsSync(filepath)) {
|
|
1095
|
+
pkg = JSON.parse(fs2.readFileSync(filepath, "utf8"));
|
|
1096
|
+
}
|
|
1097
|
+
} catch {
|
|
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 {
|
|
1111
|
+
}
|
|
1112
|
+
return { ...pkg.dependencies, ...pkg.devDependencies };
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// src/core/mockCompiler.ts
|
|
1116
|
+
import EventEmitter from "events";
|
|
1117
|
+
import process3 from "process";
|
|
1118
|
+
import path5 from "path";
|
|
1119
|
+
import fastGlob from "fast-glob";
|
|
1120
|
+
import chokidar from "chokidar";
|
|
1121
|
+
import { createFilter as createFilter2 } from "@rollup/pluginutils";
|
|
1122
|
+
import { toArray as toArray4 } from "@pengzhanbo/utils";
|
|
1123
|
+
|
|
1124
|
+
// src/core/loadFromCode.ts
|
|
1125
|
+
import path4 from "path";
|
|
1126
|
+
import fs3, { promises as fsp2 } from "fs";
|
|
1127
|
+
async function loadFromCode({
|
|
1128
|
+
filepath,
|
|
1129
|
+
code,
|
|
1130
|
+
isESM,
|
|
1131
|
+
cwd
|
|
1132
|
+
}) {
|
|
1133
|
+
filepath = path4.resolve(cwd, filepath);
|
|
1134
|
+
const fileBase = `${filepath}.timestamp-${Date.now()}`;
|
|
1135
|
+
const ext = isESM ? ".mjs" : ".cjs";
|
|
1136
|
+
const fileNameTmp = `${fileBase}${ext}`;
|
|
1137
|
+
await fsp2.writeFile(fileNameTmp, code, "utf8");
|
|
1138
|
+
try {
|
|
1139
|
+
const result = await import(fileNameTmp);
|
|
1140
|
+
return result.default || result;
|
|
1141
|
+
} finally {
|
|
1142
|
+
try {
|
|
1143
|
+
fs3.unlinkSync(fileNameTmp);
|
|
1144
|
+
} catch {
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
936
1149
|
// src/core/mockCompiler.ts
|
|
937
|
-
var vfs = createFsFromVolume(new Volume());
|
|
938
1150
|
function createMockCompiler(options) {
|
|
939
1151
|
return new MockCompiler(options);
|
|
940
1152
|
}
|
|
@@ -942,22 +1154,20 @@ var MockCompiler = class extends EventEmitter {
|
|
|
942
1154
|
constructor(options) {
|
|
943
1155
|
super();
|
|
944
1156
|
this.options = options;
|
|
945
|
-
this.cwd = options.cwd ||
|
|
1157
|
+
this.cwd = options.cwd || process3.cwd();
|
|
946
1158
|
const { include, exclude } = this.options;
|
|
947
|
-
this.fileFilter =
|
|
1159
|
+
this.fileFilter = createFilter2(include, exclude, { resolve: false });
|
|
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
1163
|
} catch {
|
|
952
1164
|
}
|
|
953
|
-
this.entryFile =
|
|
954
|
-
this.outputFile = "mock.bundle.js";
|
|
1165
|
+
this.entryFile = path5.resolve(process3.cwd(), "node_modules/.cache/mock-server/mock-server.ts");
|
|
955
1166
|
}
|
|
956
1167
|
cwd;
|
|
957
1168
|
mockWatcher;
|
|
958
1169
|
moduleType = "cjs";
|
|
959
1170
|
entryFile;
|
|
960
|
-
outputFile;
|
|
961
1171
|
_mockData = {};
|
|
962
1172
|
fileFilter;
|
|
963
1173
|
watchInfo;
|
|
@@ -968,33 +1178,27 @@ var MockCompiler = class extends EventEmitter {
|
|
|
968
1178
|
async run() {
|
|
969
1179
|
await this.updateMockEntry();
|
|
970
1180
|
this.watchMockFiles();
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
if (stats?.hasErrors()) {
|
|
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:
|
|
990
|
-
code
|
|
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
|
-
|
|
1201
|
+
this.options.logger.error(e.stack || e.message);
|
|
998
1202
|
}
|
|
999
1203
|
});
|
|
1000
1204
|
}
|
|
@@ -1012,7 +1216,7 @@ var MockCompiler = class extends EventEmitter {
|
|
|
1012
1216
|
}
|
|
1013
1217
|
async updateMockEntry() {
|
|
1014
1218
|
const files = await this.getMockFiles();
|
|
1015
|
-
await this.
|
|
1219
|
+
await writeMockEntryFile(this.entryFile, files, this.cwd);
|
|
1016
1220
|
}
|
|
1017
1221
|
async getMockFiles() {
|
|
1018
1222
|
const { include } = this.options;
|
|
@@ -1021,7 +1225,7 @@ var MockCompiler = class extends EventEmitter {
|
|
|
1021
1225
|
}
|
|
1022
1226
|
watchMockFiles() {
|
|
1023
1227
|
const { include } = this.options;
|
|
1024
|
-
const [firstGlob, ...otherGlob] =
|
|
1228
|
+
const [firstGlob, ...otherGlob] = toArray4(include);
|
|
1025
1229
|
const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
|
|
1026
1230
|
ignoreInitial: true,
|
|
1027
1231
|
cwd: this.cwd
|
|
@@ -1044,40 +1248,6 @@ var MockCompiler = class extends EventEmitter {
|
|
|
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(path4.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 = path4.dirname(this.entryFile);
|
|
1061
|
-
if (!fs3.existsSync(dirname)) {
|
|
1062
|
-
await fsp2.mkdir(dirname, { recursive: true });
|
|
1063
|
-
}
|
|
1064
|
-
await fsp2.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
|
};
|
|
1082
1252
|
|
|
1083
1253
|
// src/core/mockWebsocket.ts
|
|
@@ -1240,8 +1410,15 @@ function cleanupRunner(cleanupList) {
|
|
|
1240
1410
|
export {
|
|
1241
1411
|
waitingFor,
|
|
1242
1412
|
rewriteRequest,
|
|
1413
|
+
baseMiddleware,
|
|
1243
1414
|
createMockMiddleware,
|
|
1415
|
+
logLevels,
|
|
1416
|
+
createLogger,
|
|
1244
1417
|
resolvePluginOptions,
|
|
1418
|
+
transformRawData,
|
|
1419
|
+
transformMockData,
|
|
1420
|
+
sortByValidator,
|
|
1421
|
+
buildMockServer,
|
|
1245
1422
|
createMockCompiler,
|
|
1246
1423
|
mockWebSocket
|
|
1247
1424
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkOYBMX3GQcjs = require('./chunk-OYBMX3GQ.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
@@ -9,7 +9,6 @@ var _chunkKE2LVHUPcjs = require('./chunk-KE2LVHUP.cjs');
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
var _chunk2S4KCTKWcjs = require('./chunk-2S4KCTKW.cjs');
|
|
13
12
|
|
|
14
13
|
|
|
15
14
|
|
|
@@ -17,4 +16,19 @@ var _chunk2S4KCTKWcjs = require('./chunk-2S4KCTKW.cjs');
|
|
|
17
16
|
|
|
18
17
|
|
|
19
18
|
|
|
20
|
-
|
|
19
|
+
var _chunkI54ZNZWLcjs = require('./chunk-I54ZNZWL.cjs');
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
exports.MockServerPlugin = _chunkOYBMX3GQcjs.MockServerPlugin; exports.baseMiddleware = _chunkI54ZNZWLcjs.baseMiddleware; exports.createDefineMock = _chunkKE2LVHUPcjs.createDefineMock; exports.createLogger = _chunkI54ZNZWLcjs.createLogger; exports.createMockCompiler = _chunkI54ZNZWLcjs.createMockCompiler; exports.createMockMiddleware = _chunkI54ZNZWLcjs.createMockMiddleware; exports.defineMock = _chunkKE2LVHUPcjs.defineMock; exports.logLevels = _chunkI54ZNZWLcjs.logLevels; exports.mockWebSocket = _chunkI54ZNZWLcjs.mockWebSocket; exports.resolvePluginOptions = _chunkOYBMX3GQcjs.resolvePluginOptions; exports.sortByValidator = _chunkI54ZNZWLcjs.sortByValidator; exports.transformMockData = _chunkI54ZNZWLcjs.transformMockData; exports.transformRawData = _chunkI54ZNZWLcjs.transformRawData;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { R as ResolvePluginOptions } from './rspack-
|
|
2
|
-
export { M as MockServerPlugin, r as resolvePluginOptions } from './rspack-
|
|
1
|
+
import { L as Logger, R as ResolvePluginOptions } from './rspack-BB-Jtq4f.cjs';
|
|
2
|
+
export { M as MockServerPlugin, c as createLogger, l as logLevels, r as resolvePluginOptions } from './rspack-BB-Jtq4f.cjs';
|
|
3
3
|
export { createDefineMock, defineMock } from './helper.cjs';
|
|
4
|
-
import * as rspackCore from '@rspack/core';
|
|
5
4
|
import { Compiler, RspackPluginInstance, RspackOptionsNormalized } from '@rspack/core';
|
|
6
5
|
import EventEmitter from 'node:events';
|
|
7
6
|
import { FSWatcher } from 'node:fs';
|
|
8
|
-
import { a as MockOptions } from './types-C770q3L0.cjs';
|
|
7
|
+
import { a as MockOptions, M as MockServerPluginOptions, b as MockHttpItem, c as MockWebsocketItem } from './types-C770q3L0.cjs';
|
|
8
|
+
import { Server as Server$1 } from 'node:http';
|
|
9
|
+
import { Http2SecureServer } from 'node:http2';
|
|
9
10
|
import 'node:buffer';
|
|
10
|
-
import 'node:http';
|
|
11
11
|
import 'node:stream';
|
|
12
12
|
import 'cookies';
|
|
13
13
|
import 'cors';
|
|
@@ -21,6 +21,7 @@ interface MockCompilerOptions {
|
|
|
21
21
|
cwd?: string;
|
|
22
22
|
include: string | string[];
|
|
23
23
|
exclude: string | string[];
|
|
24
|
+
logger: Logger;
|
|
24
25
|
}
|
|
25
26
|
declare function createMockCompiler(options: MockCompilerOptions): MockCompiler;
|
|
26
27
|
declare class MockCompiler extends EventEmitter {
|
|
@@ -29,7 +30,6 @@ declare class MockCompiler extends EventEmitter {
|
|
|
29
30
|
mockWatcher: FSWatcher;
|
|
30
31
|
moduleType: 'cjs' | 'esm';
|
|
31
32
|
entryFile: string;
|
|
32
|
-
outputFile: string;
|
|
33
33
|
private _mockData;
|
|
34
34
|
private fileFilter;
|
|
35
35
|
private watchInfo?;
|
|
@@ -42,8 +42,6 @@ declare class MockCompiler extends EventEmitter {
|
|
|
42
42
|
updateMockEntry(): Promise<void>;
|
|
43
43
|
getMockFiles(): Promise<string[]>;
|
|
44
44
|
watchMockFiles(): void;
|
|
45
|
-
resolveEntryFile(fileList: string[]): Promise<void>;
|
|
46
|
-
createCompiler(callback: (e: Error | null, stats?: rspackCore.Stats) => void): void;
|
|
47
45
|
}
|
|
48
46
|
|
|
49
47
|
interface MiddlewareOptions {
|
|
@@ -57,4 +55,25 @@ type SetupMiddlewaresFn = NonNullable<NonNullable<RspackOptionsNormalized['devSe
|
|
|
57
55
|
type Middleware = SetupMiddlewaresFn extends (middlewares: (infer T)[], devServer: any) => void ? T : never;
|
|
58
56
|
type Server = SetupMiddlewaresFn extends (middlewares: any, devServer: infer T) => void ? T : never;
|
|
59
57
|
|
|
60
|
-
|
|
58
|
+
interface BaseMiddlewareOptions {
|
|
59
|
+
formidableOptions: MockServerPluginOptions['formidableOptions'];
|
|
60
|
+
cookiesOptions: MockServerPluginOptions['cookiesOptions'];
|
|
61
|
+
bodyParserOptions: MockServerPluginOptions['bodyParserOptions'];
|
|
62
|
+
proxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
63
|
+
logger: Logger;
|
|
64
|
+
priority: MockServerPluginOptions['priority'];
|
|
65
|
+
}
|
|
66
|
+
declare function baseMiddleware(compiler: MockCompiler, { formidableOptions, bodyParserOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Middleware;
|
|
67
|
+
|
|
68
|
+
interface MockSocketOptions {
|
|
69
|
+
wsProxies: (string | ((pathname: string, req: any) => boolean))[];
|
|
70
|
+
cookiesOptions: MockServerPluginOptions['cookiesOptions'];
|
|
71
|
+
logger: Logger;
|
|
72
|
+
}
|
|
73
|
+
declare function mockWebSocket(compiler: MockCompiler, httpServer: Server$1 | Http2SecureServer, { wsProxies: proxies, cookiesOptions, logger, }: MockSocketOptions): void;
|
|
74
|
+
|
|
75
|
+
declare function transformRawData(rawData: (readonly [any, string])[]): (MockHttpItem | MockWebsocketItem | MockOptions)[];
|
|
76
|
+
declare function transformMockData(mockList: (MockHttpItem | MockWebsocketItem | MockOptions)[]): Record<string, MockOptions>;
|
|
77
|
+
declare function sortByValidator(mocks: MockOptions): (MockHttpItem | MockWebsocketItem)[];
|
|
78
|
+
|
|
79
|
+
export { type BaseMiddlewareOptions, Logger, type Middleware, type MiddlewareOptions, type MockSocketOptions, type Server, baseMiddleware, createMockCompiler, createMockMiddleware, mockWebSocket, sortByValidator, transformMockData, transformRawData };
|