rspack-plugin-mock 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rsbuild.cjs CHANGED
@@ -1,202 +1,176 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const require_logger = require('./logger-C0V8Cvvd.cjs');
3
+ const require_resolvePluginOptions = require('./resolvePluginOptions-Da5uqlBx.cjs');
4
+ const __pengzhanbo_utils = require_chunk.__toESM(require("@pengzhanbo/utils"));
5
+ const node_path = require_chunk.__toESM(require("node:path"));
6
+ const node_process = require_chunk.__toESM(require("node:process"));
7
+ const picocolors = require_chunk.__toESM(require("picocolors"));
8
+ const __rspack_core = require_chunk.__toESM(require("@rspack/core"));
9
+ const node_http = require_chunk.__toESM(require("node:http"));
10
+ const portfinder = require_chunk.__toESM(require("portfinder"));
2
11
 
3
-
4
-
5
-
6
- var _chunkM7F5AAOFcjs = require('./chunk-M7F5AAOF.cjs');
7
-
8
-
9
-
10
- var _chunkHTVJXQRMcjs = require('./chunk-HTVJXQRM.cjs');
11
-
12
- // src/rsbuild.ts
13
- var _http = require('http');
14
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
15
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
16
- var _utils = require('@pengzhanbo/utils');
17
- var _core = require('@rspack/core'); var _core2 = _interopRequireDefault(_core);
18
- var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
19
- var _portfinder = require('portfinder');
12
+ //#region src/rsbuild.ts
20
13
  function pluginMockServer(options = {}) {
21
- return {
22
- name: "plugin-mock-server",
23
- setup(api) {
24
- const rsbuildConfig = api.getRsbuildConfig();
25
- const resolvedOptions = _chunkM7F5AAOFcjs.resolvePluginOptions.call(void 0, options, {
26
- proxies: resolveConfigProxies(rsbuildConfig),
27
- alias: {},
28
- context: api.context.rootPath,
29
- plugins: [new _core2.default.DefinePlugin(_optionalChain([rsbuildConfig, 'access', _ => _.source, 'optionalAccess', _2 => _2.define]) || {})]
30
- });
31
- if (_process2.default.env.NODE_ENV === "production") {
32
- if (resolvedOptions.build) {
33
- api.onAfterBuild(async () => {
34
- const config = api.getNormalizedConfig();
35
- await _chunkM7F5AAOFcjs.buildMockServer.call(void 0,
36
- resolvedOptions,
37
- _path2.default.resolve(_process2.default.cwd(), config.output.distPath.root || "dist")
38
- );
39
- });
40
- }
41
- return;
42
- }
43
- const mockCompiler = _chunkM7F5AAOFcjs.createMockCompiler.call(void 0, resolvedOptions);
44
- api.modifyRsbuildConfig((config) => {
45
- updateServerProxyConfigByHttpMock(config);
46
- const mockMiddleware = _chunkM7F5AAOFcjs.createMockMiddleware.call(void 0, mockCompiler, resolvedOptions);
47
- config.dev ??= {};
48
- config.dev.setupMiddlewares ??= [];
49
- config.dev.setupMiddlewares.push((middlewares, server2) => {
50
- mockMiddleware(middlewares, () => server2.sockWrite("static-changed"));
51
- });
52
- });
53
- let port = 3079;
54
- const shouldMockWs = _utils.toArray.call(void 0, resolvedOptions.wsPrefix).length > 0;
55
- if (shouldMockWs) {
56
- api.modifyRsbuildConfig(async (config) => {
57
- const defaultPort = (_optionalChain([config, 'access', _3 => _3.server, 'optionalAccess', _4 => _4.port]) || port) + 1;
58
- port = await _portfinder.getPortPromise.call(void 0, { port: defaultPort });
59
- updateServerProxyConfigByWSMock(config, options.wsPrefix || [], port);
60
- });
61
- }
62
- let server;
63
- function startMockServer() {
64
- mockCompiler.run();
65
- if (shouldMockWs) {
66
- server = _http.createServer.call(void 0, );
67
- _chunkHTVJXQRMcjs.mockWebSocket.call(void 0, mockCompiler, server, resolvedOptions);
68
- server.listen(port);
69
- }
70
- }
71
- function close() {
72
- mockCompiler.close();
73
- _optionalChain([server, 'optionalAccess', _5 => _5.close, 'call', _6 => _6()]);
74
- }
75
- api.onAfterCreateCompiler(({ compiler }) => {
76
- if ("compilers" in compiler) {
77
- compiler.compilers.forEach((compiler2) => {
78
- mockCompiler.updateAlias(_optionalChain([compiler2, 'access', _7 => _7.options, 'access', _8 => _8.resolve, 'optionalAccess', _9 => _9.alias]) || {});
79
- });
80
- } else {
81
- mockCompiler.updateAlias(_optionalChain([compiler, 'access', _10 => _10.options, 'access', _11 => _11.resolve, 'optionalAccess', _12 => _12.alias]) || {});
82
- }
83
- });
84
- api.onAfterStartDevServer(startMockServer);
85
- api.onAfterStartProdServer(startMockServer);
86
- api.onExit(close);
87
- }
88
- };
14
+ return {
15
+ name: "plugin-mock-server",
16
+ setup(api) {
17
+ const rsbuildConfig = api.getRsbuildConfig();
18
+ const resolvedOptions = require_resolvePluginOptions.resolvePluginOptions(options, {
19
+ proxies: resolveConfigProxies(rsbuildConfig),
20
+ alias: {},
21
+ context: api.context.rootPath,
22
+ plugins: [new __rspack_core.default.DefinePlugin(rsbuildConfig.source?.define || {})]
23
+ });
24
+ if (node_process.default.env.NODE_ENV === "production") {
25
+ if (resolvedOptions.build) api.onAfterBuild(async () => {
26
+ const config = api.getNormalizedConfig();
27
+ await require_resolvePluginOptions.buildMockServer(resolvedOptions, node_path.default.resolve(node_process.default.cwd(), config.output.distPath.root || "dist"));
28
+ });
29
+ return;
30
+ }
31
+ const mockCompiler = require_resolvePluginOptions.createMockCompiler(resolvedOptions);
32
+ api.modifyRsbuildConfig((config) => {
33
+ updateServerProxyConfigByHttpMock(config);
34
+ const mockMiddleware = require_resolvePluginOptions.createMockMiddleware(mockCompiler, resolvedOptions);
35
+ config.dev ??= {};
36
+ config.dev.setupMiddlewares ??= [];
37
+ config.dev.setupMiddlewares.push((middlewares, server$1) => {
38
+ mockMiddleware(middlewares, () => server$1.sockWrite("static-changed"));
39
+ });
40
+ });
41
+ let port = 3079;
42
+ const shouldMockWs = (0, __pengzhanbo_utils.toArray)(resolvedOptions.wsPrefix).length > 0;
43
+ if (shouldMockWs) api.modifyRsbuildConfig(async (config) => {
44
+ const defaultPort = (config.server?.port || port) + 1;
45
+ port = await (0, portfinder.getPortPromise)({ port: defaultPort });
46
+ updateServerProxyConfigByWSMock(config, options.wsPrefix || [], port);
47
+ });
48
+ let server;
49
+ function startMockServer() {
50
+ mockCompiler.run();
51
+ if (shouldMockWs) {
52
+ server = (0, node_http.createServer)();
53
+ require_logger.mockWebSocket(mockCompiler, server, resolvedOptions);
54
+ server.listen(port);
55
+ }
56
+ }
57
+ function close() {
58
+ mockCompiler.close();
59
+ server?.close();
60
+ }
61
+ api.onAfterCreateCompiler(({ compiler }) => {
62
+ if ("compilers" in compiler) compiler.compilers.forEach((compiler$1) => {
63
+ mockCompiler.updateAlias(compiler$1.options.resolve?.alias || {});
64
+ });
65
+ else mockCompiler.updateAlias(compiler.options.resolve?.alias || {});
66
+ });
67
+ api.onAfterStartDevServer(startMockServer);
68
+ api.onAfterStartProdServer(startMockServer);
69
+ api.onExit(close);
70
+ }
71
+ };
89
72
  }
90
73
  function onProxyError(err, _req, res) {
91
- console.error(_picocolors2.default.red(_optionalChain([err, 'optionalAccess', _13 => _13.stack]) || err.message));
92
- res.statusCode = 500;
93
- res.end();
74
+ console.error(picocolors.default.red(err?.stack || err.message));
75
+ res.statusCode = 500;
76
+ res.end();
94
77
  }
95
78
  function updateServerProxyConfigByHttpMock(config) {
96
- if (!_optionalChain([config, 'access', _14 => _14.server, 'optionalAccess', _15 => _15.proxy]))
97
- return;
98
- if (_utils.isArray.call(void 0, config.server.proxy)) {
99
- config.server.proxy = config.server.proxy.map((item) => {
100
- if (typeof item !== "function" && !item.ws) {
101
- const onProxyReq = item.onProxyReq;
102
- const onError = item.onError;
103
- return {
104
- ...item,
105
- onError: onError || onProxyError,
106
- onProxyReq: (proxyReq, req, ...args) => {
107
- _optionalChain([onProxyReq, 'optionalCall', _16 => _16(proxyReq, req, ...args)]);
108
- _chunkHTVJXQRMcjs.rewriteRequest.call(void 0, proxyReq, req);
109
- }
110
- };
111
- }
112
- return item;
113
- });
114
- } else if ("target" in config.server.proxy) {
115
- const onProxyReq = config.server.proxy.onProxyReq;
116
- config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
117
- _optionalChain([onProxyReq, 'optionalCall', _17 => _17(proxyReq, req, ...args)]);
118
- _chunkHTVJXQRMcjs.rewriteRequest.call(void 0, proxyReq, req);
119
- };
120
- config.server.proxy.onError ??= onProxyError;
121
- } else if (config.server.proxy) {
122
- const proxy = config.server.proxy;
123
- Object.keys(proxy).forEach((key) => {
124
- const target = proxy[key];
125
- const options = typeof target === "string" ? { target } : target;
126
- if (options.ws)
127
- return;
128
- const { onProxyReq, onError, ...rest } = options;
129
- proxy[key] = {
130
- ...rest,
131
- onProxyReq: (proxyReq, req, ...args) => {
132
- _optionalChain([onProxyReq, 'optionalCall', _18 => _18(proxyReq, req, ...args)]);
133
- _chunkHTVJXQRMcjs.rewriteRequest.call(void 0, proxyReq, req);
134
- },
135
- onError: onError || onProxyError
136
- };
137
- });
138
- }
79
+ if (!config.server?.proxy) return;
80
+ if ((0, __pengzhanbo_utils.isArray)(config.server.proxy)) config.server.proxy = config.server.proxy.map((item) => {
81
+ if (typeof item !== "function" && !item.ws) {
82
+ const onProxyReq = item.onProxyReq;
83
+ const onError = item.onError;
84
+ return {
85
+ ...item,
86
+ onError: onError || onProxyError,
87
+ onProxyReq: (proxyReq, req, ...args) => {
88
+ onProxyReq?.(proxyReq, req, ...args);
89
+ require_logger.rewriteRequest(proxyReq, req);
90
+ }
91
+ };
92
+ }
93
+ return item;
94
+ });
95
+ else if ("target" in config.server.proxy) {
96
+ const onProxyReq = config.server.proxy.onProxyReq;
97
+ config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
98
+ onProxyReq?.(proxyReq, req, ...args);
99
+ require_logger.rewriteRequest(proxyReq, req);
100
+ };
101
+ config.server.proxy.onError ??= onProxyError;
102
+ } else if (config.server.proxy) {
103
+ const proxy = config.server.proxy;
104
+ Object.keys(proxy).forEach((key) => {
105
+ const target = proxy[key];
106
+ const options = typeof target === "string" ? { target } : target;
107
+ if (options.ws) return;
108
+ const { onProxyReq, onError,...rest } = options;
109
+ proxy[key] = {
110
+ ...rest,
111
+ onProxyReq: (proxyReq, req, ...args) => {
112
+ onProxyReq?.(proxyReq, req, ...args);
113
+ require_logger.rewriteRequest(proxyReq, req);
114
+ },
115
+ onError: onError || onProxyError
116
+ };
117
+ });
118
+ }
139
119
  }
140
120
  function updateServerProxyConfigByWSMock(config, wsPrefix, port) {
141
- config.server ??= {};
142
- const proxy = config.server.proxy ??= {};
143
- const wsTarget = `ws://localhost:${port}`;
144
- const prefix = _utils.toArray.call(void 0, wsPrefix);
145
- const has = (context) => typeof context === "string" && prefix.includes(context);
146
- const used = /* @__PURE__ */ new Set();
147
- function updateProxy(item) {
148
- if (_utils.isArray.call(void 0, item.context)) {
149
- item.context = item.context.filter(has);
150
- } else if (has(item.context)) {
151
- used.add(item.context);
152
- item.target = wsTarget;
153
- }
154
- }
155
- if (_utils.isArray.call(void 0, proxy)) {
156
- for (const item of proxy) {
157
- if (typeof item !== "function" && item.context && item.ws) {
158
- updateProxy(item);
159
- }
160
- }
161
- prefix.filter((context) => !used.has(context)).forEach((context) => proxy.push({ context, target: wsTarget }));
162
- } else if ("target" in proxy) {
163
- if (proxy.ws) {
164
- updateProxy(proxy);
165
- const list = config.server.proxy = [proxy];
166
- prefix.filter((context) => !used.has(context)).forEach((context) => list.push({ context, target: wsTarget }));
167
- }
168
- } else {
169
- Object.entries(proxy).forEach(([, opt]) => {
170
- if (typeof opt !== "string" && opt.ws) {
171
- updateProxy(opt);
172
- }
173
- });
174
- prefix.filter((context) => !used.has(context)).forEach((context) => {
175
- proxy[context] = { target: wsTarget, ws: true };
176
- });
177
- }
121
+ config.server ??= {};
122
+ const proxy = config.server.proxy ??= {};
123
+ const wsTarget = `ws://localhost:${port}`;
124
+ const prefix = (0, __pengzhanbo_utils.toArray)(wsPrefix);
125
+ const has = (context) => typeof context === "string" && prefix.includes(context);
126
+ const used = /* @__PURE__ */ new Set();
127
+ function updateProxy(item) {
128
+ if ((0, __pengzhanbo_utils.isArray)(item.context)) item.context = item.context.filter(has);
129
+ else if (has(item.context)) {
130
+ used.add(item.context);
131
+ item.target = wsTarget;
132
+ }
133
+ }
134
+ if ((0, __pengzhanbo_utils.isArray)(proxy)) {
135
+ for (const item of proxy) if (typeof item !== "function" && item.context && item.ws) updateProxy(item);
136
+ prefix.filter((context) => !used.has(context)).forEach((context) => proxy.push({
137
+ context,
138
+ target: wsTarget
139
+ }));
140
+ } else if ("target" in proxy) {
141
+ if (proxy.ws) {
142
+ updateProxy(proxy);
143
+ const list = config.server.proxy = [proxy];
144
+ prefix.filter((context) => !used.has(context)).forEach((context) => list.push({
145
+ context,
146
+ target: wsTarget
147
+ }));
148
+ }
149
+ } else {
150
+ Object.entries(proxy).forEach(([, opt]) => {
151
+ if (typeof opt !== "string" && opt.ws) updateProxy(opt);
152
+ });
153
+ prefix.filter((context) => !used.has(context)).forEach((context) => {
154
+ proxy[context] = {
155
+ target: wsTarget,
156
+ ws: true
157
+ };
158
+ });
159
+ }
178
160
  }
179
161
  function resolveConfigProxies(config) {
180
- config.server ??= {};
181
- const proxy = config.server.proxy ??= {};
182
- const proxies = [];
183
- if (_utils.isArray.call(void 0, proxy)) {
184
- for (const item of proxy) {
185
- if (typeof item !== "function" && item.context && !item.ws) {
186
- proxies.push(..._utils.toArray.call(void 0, item.context));
187
- }
188
- }
189
- } else if ("target" in proxy) {
190
- if (!proxy.ws)
191
- proxies.push(..._utils.toArray.call(void 0, proxy.context));
192
- } else {
193
- Object.entries(proxy).forEach(([context, opt]) => {
194
- if (typeof opt === "string" || !opt.ws)
195
- proxies.push(context);
196
- });
197
- }
198
- return proxies;
162
+ config.server ??= {};
163
+ const proxy = config.server.proxy ??= {};
164
+ const proxies = [];
165
+ if ((0, __pengzhanbo_utils.isArray)(proxy)) {
166
+ for (const item of proxy) if (typeof item !== "function" && item.context && !item.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(item.context));
167
+ } else if ("target" in proxy) {
168
+ if (!proxy.ws) proxies.push(...(0, __pengzhanbo_utils.toArray)(proxy.context));
169
+ } else Object.entries(proxy).forEach(([context, opt]) => {
170
+ if (typeof opt === "string" || !opt.ws) proxies.push(context);
171
+ });
172
+ return proxies;
199
173
  }
200
174
 
201
-
202
- exports.pluginMockServer = pluginMockServer;
175
+ //#endregion
176
+ exports.pluginMockServer = pluginMockServer;
@@ -1,15 +1,7 @@
1
- import { RsbuildPlugin } from '@rsbuild/core';
2
- import { c as MockServerPluginOptions } from './types-Aw0AciTG.cjs';
3
- export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, M as MockHttpItem, d as MockMatchPriority, e as MockMatchSpecialPriority, b as MockOptions, g as MockRequest, h as MockResponse, a as MockWebsocketItem, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-Aw0AciTG.cjs';
4
- import 'co-body';
5
- import 'cookies';
6
- import 'cors';
7
- import 'formidable';
8
- import 'node:buffer';
9
- import 'node:http';
10
- import 'node:stream';
11
- import 'ws';
1
+ import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-6lajtJPx.cjs";
2
+ import { RsbuildPlugin } from "@rsbuild/core";
12
3
 
4
+ //#region src/rsbuild.d.ts
13
5
  declare function pluginMockServer(options?: MockServerPluginOptions): RsbuildPlugin;
14
-
15
- export { MockServerPluginOptions, pluginMockServer };
6
+ //#endregion
7
+ export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext, pluginMockServer };
package/dist/rsbuild.d.ts CHANGED
@@ -1,15 +1,7 @@
1
- import { RsbuildPlugin } from '@rsbuild/core';
2
- import { c as MockServerPluginOptions } from './types-Aw0AciTG.js';
3
- export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, M as MockHttpItem, d as MockMatchPriority, e as MockMatchSpecialPriority, b as MockOptions, g as MockRequest, h as MockResponse, a as MockWebsocketItem, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-Aw0AciTG.js';
4
- import 'co-body';
5
- import 'cookies';
6
- import 'cors';
7
- import 'formidable';
8
- import 'node:buffer';
9
- import 'node:http';
10
- import 'node:stream';
11
- import 'ws';
1
+ import { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext } from "./types-DPzh7nJq.js";
2
+ import { RsbuildPlugin } from "@rsbuild/core";
12
3
 
4
+ //#region src/rsbuild.d.ts
13
5
  declare function pluginMockServer(options?: MockServerPluginOptions): RsbuildPlugin;
14
-
15
- export { MockServerPluginOptions, pluginMockServer };
6
+ //#endregion
7
+ export { BodyParserOptions, ExtraRequest, FormidableFile, LogLevel, LogType, Method, MockHttpItem, MockMatchPriority, MockMatchSpecialPriority, MockOptions, MockRequest, MockResponse, MockServerPluginOptions, MockWebsocketItem, ResponseBody, ServerBuildOption, WebSocketSetupContext, pluginMockServer };