rspack-plugin-mock 0.1.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/dist/helper.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-DhT3pRJ3.cjs';
2
- export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-DhT3pRJ3.cjs';
1
+ import { b as MockHttpItem, c as MockWebsocketItem, a as MockOptions } from './types-C770q3L0.cjs';
2
+ export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, L as LogLevel, i as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-C770q3L0.cjs';
3
3
  import 'node:buffer';
4
4
  import 'node:http';
5
5
  import 'node:stream';
package/dist/helper.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-DhT3pRJ3.js';
2
- export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, i as LogLevel, L as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-DhT3pRJ3.js';
1
+ import { b as MockHttpItem, c as MockWebsocketItem, a as MockOptions } from './types-C770q3L0.js';
2
+ export { B as BodyParserOptions, E as ExtraRequest, F as FormidableFile, L as LogLevel, i as LogType, f as Method, d as MockMatchPriority, e as MockMatchSpecialPriority, g as MockRequest, h as MockResponse, M as MockServerPluginOptions, R as ResponseBody, S as ServerBuildOption, W as WebSocketSetupContext } from './types-C770q3L0.js';
3
3
  import 'node:buffer';
4
4
  import 'node:http';
5
5
  import 'node:stream';
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 _chunk4BGDHRTOcjs = require('./chunk-4BGDHRTO.cjs');
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 _chunkG53QRHGVcjs = require('./chunk-G53QRHGV.cjs');
13
12
 
14
13
 
15
14
 
@@ -17,4 +16,19 @@ var _chunkG53QRHGVcjs = require('./chunk-G53QRHGV.cjs');
17
16
 
18
17
 
19
18
 
20
- exports.MockServerPlugin = _chunk4BGDHRTOcjs.MockServerPlugin; exports.createDefineMock = _chunkKE2LVHUPcjs.createDefineMock; exports.createManuallyMockMiddleware = _chunkG53QRHGVcjs.createManuallyMockMiddleware; exports.createMockMiddleware = _chunkG53QRHGVcjs.createMockMiddleware; exports.defineMock = _chunkKE2LVHUPcjs.defineMock; exports.resolveMiddleOptions = _chunk4BGDHRTOcjs.resolveMiddleOptions;
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,12 +1,79 @@
1
- export { d as Middleware, a as MiddlewareOptions, M as MockServerPlugin, S as Server, c as createManuallyMockMiddleware, b as createMockMiddleware, r as resolveMiddleOptions } from './rspack-BI-Ifj4a.cjs';
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';
2
3
  export { createDefineMock, defineMock } from './helper.cjs';
3
- import '@rspack/core';
4
- import './types-DhT3pRJ3.cjs';
4
+ import { Compiler, RspackPluginInstance, RspackOptionsNormalized } from '@rspack/core';
5
+ import EventEmitter from 'node:events';
6
+ import { FSWatcher } from 'node:fs';
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';
5
10
  import 'node:buffer';
6
- import 'node:http';
7
11
  import 'node:stream';
8
12
  import 'cookies';
9
13
  import 'cors';
10
14
  import 'formidable';
11
15
  import 'ws';
12
16
  import 'co-body';
17
+
18
+ interface MockCompilerOptions {
19
+ alias?: Record<string, false | string | (string | false)[]>;
20
+ plugins: RspackPluginInstance[];
21
+ cwd?: string;
22
+ include: string | string[];
23
+ exclude: string | string[];
24
+ logger: Logger;
25
+ }
26
+ declare function createMockCompiler(options: MockCompilerOptions): MockCompiler;
27
+ declare class MockCompiler extends EventEmitter {
28
+ options: MockCompilerOptions;
29
+ cwd: string;
30
+ mockWatcher: FSWatcher;
31
+ moduleType: 'cjs' | 'esm';
32
+ entryFile: string;
33
+ private _mockData;
34
+ private fileFilter;
35
+ private watchInfo?;
36
+ compiler?: Compiler | null;
37
+ constructor(options: MockCompilerOptions);
38
+ get mockData(): Record<string, MockOptions>;
39
+ run(): Promise<void>;
40
+ close(): void;
41
+ updateAlias(alias: Record<string, false | string | (string | false)[]>): void;
42
+ updateMockEntry(): Promise<void>;
43
+ getMockFiles(): Promise<string[]>;
44
+ watchMockFiles(): void;
45
+ }
46
+
47
+ interface MiddlewareOptions {
48
+ alias: Record<string, false | string | (string | false)[]>;
49
+ proxies: (string | ((pathname: string, req: any) => boolean))[];
50
+ context?: string;
51
+ plugins: RspackPluginInstance[];
52
+ }
53
+ declare function createMockMiddleware(compiler: MockCompiler, options: ResolvePluginOptions): (middlewares: Middleware[], reload?: () => void) => Middleware[];
54
+ type SetupMiddlewaresFn = NonNullable<NonNullable<RspackOptionsNormalized['devServer']>['setupMiddlewares']>;
55
+ type Middleware = SetupMiddlewaresFn extends (middlewares: (infer T)[], devServer: any) => void ? T : never;
56
+ type Server = SetupMiddlewaresFn extends (middlewares: any, devServer: infer T) => void ? T : never;
57
+
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 };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,79 @@
1
- export { d as Middleware, a as MiddlewareOptions, M as MockServerPlugin, S as Server, c as createManuallyMockMiddleware, b as createMockMiddleware, r as resolveMiddleOptions } from './rspack-Db7drzDm.js';
1
+ import { L as Logger, R as ResolvePluginOptions } from './rspack-h3uerEgg.js';
2
+ export { M as MockServerPlugin, c as createLogger, l as logLevels, r as resolvePluginOptions } from './rspack-h3uerEgg.js';
2
3
  export { createDefineMock, defineMock } from './helper.js';
3
- import '@rspack/core';
4
- import './types-DhT3pRJ3.js';
4
+ import { Compiler, RspackPluginInstance, RspackOptionsNormalized } from '@rspack/core';
5
+ import EventEmitter from 'node:events';
6
+ import { FSWatcher } from 'node:fs';
7
+ import { a as MockOptions, M as MockServerPluginOptions, b as MockHttpItem, c as MockWebsocketItem } from './types-C770q3L0.js';
8
+ import { Server as Server$1 } from 'node:http';
9
+ import { Http2SecureServer } from 'node:http2';
5
10
  import 'node:buffer';
6
- import 'node:http';
7
11
  import 'node:stream';
8
12
  import 'cookies';
9
13
  import 'cors';
10
14
  import 'formidable';
11
15
  import 'ws';
12
16
  import 'co-body';
17
+
18
+ interface MockCompilerOptions {
19
+ alias?: Record<string, false | string | (string | false)[]>;
20
+ plugins: RspackPluginInstance[];
21
+ cwd?: string;
22
+ include: string | string[];
23
+ exclude: string | string[];
24
+ logger: Logger;
25
+ }
26
+ declare function createMockCompiler(options: MockCompilerOptions): MockCompiler;
27
+ declare class MockCompiler extends EventEmitter {
28
+ options: MockCompilerOptions;
29
+ cwd: string;
30
+ mockWatcher: FSWatcher;
31
+ moduleType: 'cjs' | 'esm';
32
+ entryFile: string;
33
+ private _mockData;
34
+ private fileFilter;
35
+ private watchInfo?;
36
+ compiler?: Compiler | null;
37
+ constructor(options: MockCompilerOptions);
38
+ get mockData(): Record<string, MockOptions>;
39
+ run(): Promise<void>;
40
+ close(): void;
41
+ updateAlias(alias: Record<string, false | string | (string | false)[]>): void;
42
+ updateMockEntry(): Promise<void>;
43
+ getMockFiles(): Promise<string[]>;
44
+ watchMockFiles(): void;
45
+ }
46
+
47
+ interface MiddlewareOptions {
48
+ alias: Record<string, false | string | (string | false)[]>;
49
+ proxies: (string | ((pathname: string, req: any) => boolean))[];
50
+ context?: string;
51
+ plugins: RspackPluginInstance[];
52
+ }
53
+ declare function createMockMiddleware(compiler: MockCompiler, options: ResolvePluginOptions): (middlewares: Middleware[], reload?: () => void) => Middleware[];
54
+ type SetupMiddlewaresFn = NonNullable<NonNullable<RspackOptionsNormalized['devServer']>['setupMiddlewares']>;
55
+ type Middleware = SetupMiddlewaresFn extends (middlewares: (infer T)[], devServer: any) => void ? T : never;
56
+ type Server = SetupMiddlewaresFn extends (middlewares: any, devServer: infer T) => void ? T : never;
57
+
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 };
package/dist/index.js CHANGED
@@ -1,20 +1,34 @@
1
1
  import {
2
2
  MockServerPlugin,
3
- resolveMiddleOptions
4
- } from "./chunk-B56QNVSS.js";
3
+ resolvePluginOptions
4
+ } from "./chunk-P5FOCSCE.js";
5
5
  import {
6
6
  createDefineMock,
7
7
  defineMock
8
8
  } from "./chunk-HTOWPFQ7.js";
9
9
  import {
10
- createManuallyMockMiddleware,
11
- createMockMiddleware
12
- } from "./chunk-5MGZAMDI.js";
10
+ baseMiddleware,
11
+ createLogger,
12
+ createMockCompiler,
13
+ createMockMiddleware,
14
+ logLevels,
15
+ mockWebSocket,
16
+ sortByValidator,
17
+ transformMockData,
18
+ transformRawData
19
+ } from "./chunk-YSJVV4SH.js";
13
20
  export {
14
21
  MockServerPlugin,
22
+ baseMiddleware,
15
23
  createDefineMock,
16
- createManuallyMockMiddleware,
24
+ createLogger,
25
+ createMockCompiler,
17
26
  createMockMiddleware,
18
27
  defineMock,
19
- resolveMiddleOptions
28
+ logLevels,
29
+ mockWebSocket,
30
+ resolvePluginOptions,
31
+ sortByValidator,
32
+ transformMockData,
33
+ transformRawData
20
34
  };
package/dist/rsbuild.cjs CHANGED
@@ -1,121 +1,200 @@
1
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; }
2
2
 
3
3
 
4
- var _chunkG53QRHGVcjs = require('./chunk-G53QRHGV.cjs');
4
+
5
+
6
+
7
+
8
+ var _chunkI54ZNZWLcjs = require('./chunk-I54ZNZWL.cjs');
5
9
 
6
10
  // src/rsbuild.ts
7
11
  var _process = require('process'); var _process2 = _interopRequireDefault(_process);
12
+ var _http = require('http');
13
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
8
14
  var _utils = require('@pengzhanbo/utils');
9
15
  var _core = require('@rspack/core'); var _core2 = _interopRequireDefault(_core);
16
+ var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
17
+ var _portfinder = require('portfinder');
10
18
  function pluginMockServer(options = {}) {
11
19
  return {
12
20
  name: "plugin-mock-server",
13
21
  setup(api) {
14
- if (_process2.default.env.NODE_ENV === "production")
15
- return;
16
- api.modifyRsbuildConfig((config) => {
17
- if (!_optionalChain([config, 'access', _ => _.server, 'optionalAccess', _2 => _2.proxy]))
18
- return;
19
- const onProxyError = (err, req, res) => {
20
- console.error(_optionalChain([err, 'optionalAccess', _3 => _3.stack]) || err);
21
- res.statusCode = 500;
22
- res.end();
23
- };
24
- if (_utils.isArray.call(void 0, config.server.proxy)) {
25
- config.server.proxy = config.server.proxy.map((item) => {
26
- if (typeof item !== "function" && !item.ws) {
27
- const onProxyReq = item.onProxyReq;
28
- const onError = item.onError;
29
- return {
30
- ...item,
31
- onError: onError || onProxyError,
32
- onProxyReq: (proxyReq, req, ...args) => {
33
- _optionalChain([onProxyReq, 'optionalCall', _4 => _4(proxyReq, req, ...args)]);
34
- _chunkG53QRHGVcjs.rewriteRequest.call(void 0, proxyReq, req);
35
- }
36
- };
37
- }
38
- return item;
39
- });
40
- } else if ("target" in config.server.proxy) {
41
- const onProxyReq = config.server.proxy.onProxyReq;
42
- config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
43
- _optionalChain([onProxyReq, 'optionalCall', _5 => _5(proxyReq, req, ...args)]);
44
- _chunkG53QRHGVcjs.rewriteRequest.call(void 0, proxyReq, req);
45
- };
46
- config.server.proxy.onError ??= onProxyError;
47
- } else if (config.server.proxy) {
48
- const proxy = config.server.proxy;
49
- Object.keys(proxy).forEach((key) => {
50
- const target = proxy[key];
51
- const options2 = typeof target === "string" ? { target } : target;
52
- if (options2.ws)
53
- return;
54
- const { onProxyReq, onError, ...rest } = options2;
55
- proxy[key] = {
56
- ...rest,
57
- onProxyReq: (proxyReq, req, ...args) => {
58
- _optionalChain([onProxyReq, 'optionalCall', _6 => _6(proxyReq, req, ...args)]);
59
- _chunkG53QRHGVcjs.rewriteRequest.call(void 0, proxyReq, req);
60
- },
61
- onError: onError || onProxyError
62
- };
63
- });
64
- }
22
+ const rsbuildConfig = api.getRsbuildConfig();
23
+ const resolvedOptions = _chunkI54ZNZWLcjs.resolvePluginOptions.call(void 0, options, {
24
+ proxies: resolveConfigProxies(rsbuildConfig),
25
+ alias: {},
26
+ context: api.context.rootPath,
27
+ plugins: [new _core2.default.DefinePlugin(_optionalChain([rsbuildConfig, 'access', _ => _.source, 'optionalAccess', _2 => _2.define]) || {})]
65
28
  });
66
- let compilerRun;
67
- let compilerClose;
68
- let compilerUpdateAlias;
69
- api.modifyRsbuildConfig((config) => {
70
- const proxy = _optionalChain([config, 'access', _7 => _7.server, 'optionalAccess', _8 => _8.proxy]) || [];
71
- const proxies = [];
72
- if (_utils.isArray.call(void 0, proxy)) {
73
- for (const item of proxy) {
74
- if (typeof item !== "function" && !item.ws && item.context) {
75
- proxies.push(..._utils.toArray.call(void 0, item.context));
76
- }
77
- }
78
- } else if ("target" in proxy) {
79
- proxies.push(..._utils.toArray.call(void 0, proxy.context));
80
- } else {
81
- Object.entries(proxy).forEach(([context, opt]) => {
82
- if (typeof opt === "string" || !opt.ws) {
83
- proxies.push(context);
84
- }
29
+ if (_process2.default.env.NODE_ENV === "production") {
30
+ if (resolvedOptions.build) {
31
+ api.onAfterBuild(async () => {
32
+ const config = api.getNormalizedConfig();
33
+ await _chunkI54ZNZWLcjs.buildMockServer.call(void 0,
34
+ resolvedOptions,
35
+ _path2.default.resolve(_process2.default.cwd(), config.output.distPath.root || "dist")
36
+ );
85
37
  });
86
38
  }
87
- const { mockMiddleware, run, close, updateAlias } = _chunkG53QRHGVcjs.createManuallyMockMiddleware.call(void 0, {
88
- plugins: [new _core2.default.DefinePlugin(_optionalChain([config, 'access', _9 => _9.source, 'optionalAccess', _10 => _10.define]) || {})],
89
- alias: {},
90
- proxies,
91
- context: api.context.rootPath
92
- }, options);
93
- compilerRun = run;
94
- compilerClose = close;
95
- compilerUpdateAlias = updateAlias;
39
+ return;
40
+ }
41
+ const mockCompiler = _chunkI54ZNZWLcjs.createMockCompiler.call(void 0, resolvedOptions);
42
+ api.modifyRsbuildConfig((config) => {
43
+ updateServerProxyConfigByHttpMock(config);
44
+ const mockMiddleware = _chunkI54ZNZWLcjs.createMockMiddleware.call(void 0, mockCompiler, resolvedOptions);
96
45
  config.dev ??= {};
97
46
  config.dev.setupMiddlewares ??= [];
98
- config.dev.setupMiddlewares.push((middlewares) => {
99
- mockMiddleware(middlewares);
47
+ config.dev.setupMiddlewares.push((middlewares, server2) => {
48
+ mockMiddleware(middlewares, () => server2.sockWrite("static-changed"));
100
49
  });
101
50
  });
51
+ let port = 3079;
52
+ const shouldMockWs = _utils.toArray.call(void 0, resolvedOptions.wsPrefix).length > 0;
53
+ if (shouldMockWs) {
54
+ api.modifyRsbuildConfig(async (config) => {
55
+ const defaultPort = (_optionalChain([config, 'access', _3 => _3.server, 'optionalAccess', _4 => _4.port]) || port) + 1;
56
+ port = await _portfinder.getPortPromise.call(void 0, { port: defaultPort });
57
+ updateServerProxyConfigByWSMock(config, options.wsPrefix || [], port);
58
+ });
59
+ }
60
+ let server;
61
+ function startMockServer() {
62
+ mockCompiler.run();
63
+ if (shouldMockWs) {
64
+ server = _http.createServer.call(void 0, );
65
+ _chunkI54ZNZWLcjs.mockWebSocket.call(void 0, mockCompiler, server, resolvedOptions);
66
+ server.listen(port);
67
+ }
68
+ }
69
+ function close() {
70
+ mockCompiler.close();
71
+ _optionalChain([server, 'optionalAccess', _5 => _5.close, 'call', _6 => _6()]);
72
+ }
102
73
  api.onAfterCreateCompiler(({ compiler }) => {
103
- if (compilerUpdateAlias) {
104
- if ("compilers" in compiler) {
105
- compiler.compilers.forEach((compiler2) => {
106
- _optionalChain([compilerUpdateAlias, 'optionalCall', _11 => _11(_optionalChain([compiler2, 'access', _12 => _12.options, 'access', _13 => _13.resolve, 'optionalAccess', _14 => _14.alias]) || {})]);
107
- });
108
- } else {
109
- _optionalChain([compilerUpdateAlias, 'optionalCall', _15 => _15(_optionalChain([compiler, 'access', _16 => _16.options, 'access', _17 => _17.resolve, 'optionalAccess', _18 => _18.alias]) || {})]);
110
- }
74
+ if ("compilers" in compiler) {
75
+ compiler.compilers.forEach((compiler2) => {
76
+ mockCompiler.updateAlias(_optionalChain([compiler2, 'access', _7 => _7.options, 'access', _8 => _8.resolve, 'optionalAccess', _9 => _9.alias]) || {});
77
+ });
78
+ } else {
79
+ mockCompiler.updateAlias(_optionalChain([compiler, 'access', _10 => _10.options, 'access', _11 => _11.resolve, 'optionalAccess', _12 => _12.alias]) || {});
111
80
  }
112
81
  });
113
- api.onAfterStartDevServer(() => _optionalChain([compilerRun, 'optionalCall', _19 => _19()]));
114
- api.onAfterStartProdServer(() => _optionalChain([compilerRun, 'optionalCall', _20 => _20()]));
115
- api.onExit(() => _optionalChain([compilerClose, 'optionalCall', _21 => _21()]));
82
+ api.onAfterStartDevServer(startMockServer);
83
+ api.onAfterStartProdServer(startMockServer);
84
+ api.onExit(close);
116
85
  }
117
86
  };
118
87
  }
88
+ function updateServerProxyConfigByHttpMock(config) {
89
+ if (!_optionalChain([config, 'access', _13 => _13.server, 'optionalAccess', _14 => _14.proxy]))
90
+ return;
91
+ const onProxyError = (err, _req, res) => {
92
+ console.error(_picocolors2.default.red(_optionalChain([err, 'optionalAccess', _15 => _15.stack]) || err.message));
93
+ res.statusCode = 500;
94
+ res.end();
95
+ };
96
+ if (_utils.isArray.call(void 0, config.server.proxy)) {
97
+ config.server.proxy = config.server.proxy.map((item) => {
98
+ if (typeof item !== "function" && !item.ws) {
99
+ const onProxyReq = item.onProxyReq;
100
+ const onError = item.onError;
101
+ return {
102
+ ...item,
103
+ onError: onError || onProxyError,
104
+ onProxyReq: (proxyReq, req, ...args) => {
105
+ _optionalChain([onProxyReq, 'optionalCall', _16 => _16(proxyReq, req, ...args)]);
106
+ _chunkI54ZNZWLcjs.rewriteRequest.call(void 0, proxyReq, req);
107
+ }
108
+ };
109
+ }
110
+ return item;
111
+ });
112
+ } else if ("target" in config.server.proxy) {
113
+ const onProxyReq = config.server.proxy.onProxyReq;
114
+ config.server.proxy.onProxyReq = (proxyReq, req, ...args) => {
115
+ _optionalChain([onProxyReq, 'optionalCall', _17 => _17(proxyReq, req, ...args)]);
116
+ _chunkI54ZNZWLcjs.rewriteRequest.call(void 0, proxyReq, req);
117
+ };
118
+ config.server.proxy.onError ??= onProxyError;
119
+ } else if (config.server.proxy) {
120
+ const proxy = config.server.proxy;
121
+ Object.keys(proxy).forEach((key) => {
122
+ const target = proxy[key];
123
+ const options = typeof target === "string" ? { target } : target;
124
+ if (options.ws)
125
+ return;
126
+ const { onProxyReq, onError, ...rest } = options;
127
+ proxy[key] = {
128
+ ...rest,
129
+ onProxyReq: (proxyReq, req, ...args) => {
130
+ _optionalChain([onProxyReq, 'optionalCall', _18 => _18(proxyReq, req, ...args)]);
131
+ _chunkI54ZNZWLcjs.rewriteRequest.call(void 0, proxyReq, req);
132
+ },
133
+ onError: onError || onProxyError
134
+ };
135
+ });
136
+ }
137
+ }
138
+ function updateServerProxyConfigByWSMock(config, wsPrefix, port) {
139
+ config.server ??= {};
140
+ const proxy = config.server.proxy ??= {};
141
+ const wsTarget = `ws://localhost:${port}`;
142
+ const prefix = _utils.toArray.call(void 0, wsPrefix);
143
+ const has = (context) => typeof context === "string" && prefix.includes(context);
144
+ const used = /* @__PURE__ */ new Set();
145
+ function updateProxy(item) {
146
+ if (_utils.isArray.call(void 0, item.context)) {
147
+ item.context = item.context.filter(has);
148
+ } else if (has(item.context)) {
149
+ used.add(item.context);
150
+ item.target = wsTarget;
151
+ }
152
+ }
153
+ if (_utils.isArray.call(void 0, proxy)) {
154
+ for (const item of proxy) {
155
+ if (typeof item !== "function" && item.context && item.ws) {
156
+ updateProxy(item);
157
+ }
158
+ }
159
+ prefix.filter((context) => !used.has(context)).forEach((context) => proxy.push({ context, target: wsTarget }));
160
+ } else if ("target" in proxy) {
161
+ if (proxy.ws) {
162
+ updateProxy(proxy);
163
+ const list = config.server.proxy = [proxy];
164
+ prefix.filter((context) => !used.has(context)).forEach((context) => list.push({ context, target: wsTarget }));
165
+ }
166
+ } else {
167
+ Object.entries(proxy).forEach(([, opt]) => {
168
+ if (typeof opt !== "string" && opt.ws) {
169
+ updateProxy(opt);
170
+ }
171
+ });
172
+ prefix.filter((context) => !used.has(context)).forEach((context) => {
173
+ proxy[context] = { target: wsTarget, ws: true };
174
+ });
175
+ }
176
+ }
177
+ function resolveConfigProxies(config) {
178
+ config.server ??= {};
179
+ const proxy = config.server.proxy ??= {};
180
+ const proxies = [];
181
+ if (_utils.isArray.call(void 0, proxy)) {
182
+ for (const item of proxy) {
183
+ if (typeof item !== "function" && item.context && !item.ws) {
184
+ proxies.push(..._utils.toArray.call(void 0, item.context));
185
+ }
186
+ }
187
+ } else if ("target" in proxy) {
188
+ if (!proxy.ws)
189
+ proxies.push(..._utils.toArray.call(void 0, proxy.context));
190
+ } else {
191
+ Object.entries(proxy).forEach(([context, opt]) => {
192
+ if (typeof opt === "string" || !opt.ws)
193
+ proxies.push(context);
194
+ });
195
+ }
196
+ return proxies;
197
+ }
119
198
 
120
199
 
121
200
  exports.pluginMockServer = pluginMockServer;
@@ -1,5 +1,5 @@
1
1
  import { RsbuildPlugin } from '@rsbuild/core';
2
- import { M as MockServerPluginOptions } from './types-DhT3pRJ3.cjs';
2
+ import { M as MockServerPluginOptions } from './types-C770q3L0.cjs';
3
3
  import 'node:buffer';
4
4
  import 'node:http';
5
5
  import 'node:stream';
package/dist/rsbuild.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RsbuildPlugin } from '@rsbuild/core';
2
- import { M as MockServerPluginOptions } from './types-DhT3pRJ3.js';
2
+ import { M as MockServerPluginOptions } from './types-C770q3L0.js';
3
3
  import 'node:buffer';
4
4
  import 'node:http';
5
5
  import 'node:stream';