rspack-plugin-mock 0.3.0 → 0.3.1

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.cjs CHANGED
@@ -1,8 +1,19 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/core/defineMock.ts
2
+ var _utils = require('@pengzhanbo/utils');
3
+ function defineMock(config) {
4
+ return config;
5
+ }
6
+ function createDefineMock(transformer) {
7
+ const define = (config) => {
8
+ if (_utils.isArray.call(void 0, config))
9
+ config = config.map((item) => transformer(item) || item);
10
+ else
11
+ config = transformer(config) || config;
12
+ return config;
13
+ };
14
+ return define;
15
+ }
2
16
 
3
17
 
4
- var _chunkKE2LVHUPcjs = require('./chunk-KE2LVHUP.cjs');
5
18
 
6
-
7
-
8
- exports.createDefineMock = _chunkKE2LVHUPcjs.createDefineMock; exports.defineMock = _chunkKE2LVHUPcjs.defineMock;
19
+ exports.createDefineMock = createDefineMock; exports.defineMock = defineMock;
package/dist/helper.d.cts CHANGED
@@ -1,5 +1,5 @@
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';
1
+ import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.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-BgpcN3jm.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 { 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';
1
+ import { a as MockHttpItem, b as MockWebsocketItem, c as MockOptions } from './types-BgpcN3jm.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-BgpcN3jm.js';
3
3
  import 'node:buffer';
4
4
  import 'node:http';
5
5
  import 'node:stream';
package/dist/helper.js CHANGED
@@ -1,7 +1,18 @@
1
- import {
2
- createDefineMock,
3
- defineMock
4
- } from "./chunk-HTOWPFQ7.js";
1
+ // src/core/defineMock.ts
2
+ import { isArray } from "@pengzhanbo/utils";
3
+ function defineMock(config) {
4
+ return config;
5
+ }
6
+ function createDefineMock(transformer) {
7
+ const define = (config) => {
8
+ if (isArray(config))
9
+ config = config.map((item) => transformer(item) || item);
10
+ else
11
+ config = transformer(config) || config;
12
+ return config;
13
+ };
14
+ return define;
15
+ }
5
16
  export {
6
17
  createDefineMock,
7
18
  defineMock
package/dist/index.cjs CHANGED
@@ -1,34 +1,103 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
- var _chunkOYBMX3GQcjs = require('./chunk-OYBMX3GQ.cjs');
5
-
6
-
7
-
8
- var _chunkKE2LVHUPcjs = require('./chunk-KE2LVHUP.cjs');
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
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;
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
+
3
+
4
+
5
+
6
+
7
+ var _chunk4GMRSIINcjs = require('./chunk-4GMRSIIN.cjs');
8
+
9
+
10
+
11
+
12
+ var _chunkZEC4FWWYcjs = require('./chunk-ZEC4FWWY.cjs');
13
+
14
+ // src/rspack.ts
15
+ var _process = require('process'); var _process2 = _interopRequireDefault(_process);
16
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
17
+ var _core = require('@rspack/core'); var _core2 = _interopRequireDefault(_core);
18
+ var _utils = require('@pengzhanbo/utils');
19
+ var PLUGIN_NAME = "rspack-plugin-mock";
20
+ var MockServerPlugin = class {
21
+ constructor(options = {}) {
22
+ this.options = options;
23
+ }
24
+ apply(compiler) {
25
+ const compilerOptions = compiler.options;
26
+ const options = resolvePluginOptions2(compiler, this.options);
27
+ if (_process2.default.env.NODE_ENV !== "production") {
28
+ const mockCompiler = _chunk4GMRSIINcjs.createMockCompiler.call(void 0, options);
29
+ const mockMiddleware = _chunk4GMRSIINcjs.createMockMiddleware.call(void 0, mockCompiler, options);
30
+ const setupMiddlewares = _optionalChain([compilerOptions, 'access', _ => _.devServer, 'optionalAccess', _2 => _2.setupMiddlewares]);
31
+ const waitServer = _chunkZEC4FWWYcjs.waitingFor.call(void 0, (server) => {
32
+ _chunkZEC4FWWYcjs.mockWebSocket.call(void 0, mockCompiler, server, options);
33
+ });
34
+ compilerOptions.devServer = {
35
+ ...compilerOptions.devServer,
36
+ setupMiddlewares: (middlewares, devServer) => {
37
+ middlewares = _optionalChain([setupMiddlewares, 'optionalCall', _3 => _3(middlewares, devServer)]) || middlewares;
38
+ const reload = () => {
39
+ if (_optionalChain([devServer, 'access', _4 => _4.webSocketServer, 'optionalAccess', _5 => _5.clients]))
40
+ devServer.sendMessage(devServer.webSocketServer.clients, "static-changed");
41
+ };
42
+ middlewares = mockMiddleware(middlewares, reload) || middlewares;
43
+ waitServer(() => devServer.server);
44
+ return middlewares;
45
+ }
46
+ };
47
+ const proxy = _optionalChain([compilerOptions, 'access', _6 => _6.devServer, 'optionalAccess', _7 => _7.proxy]) || [];
48
+ const wsPrefix = _utils.toArray.call(void 0, options.wsPrefix);
49
+ if (proxy.length) {
50
+ compilerOptions.devServer.proxy = proxy.map((item) => {
51
+ if (typeof item !== "function" && !item.ws) {
52
+ const onProxyReq = item.onProxyReq;
53
+ item.onProxyReq = (proxyReq, req, ...args) => {
54
+ _optionalChain([onProxyReq, 'optionalCall', _8 => _8(proxyReq, req, ...args)]);
55
+ _chunkZEC4FWWYcjs.rewriteRequest.call(void 0, proxyReq, req);
56
+ };
57
+ }
58
+ return item;
59
+ }).filter((item) => {
60
+ if (typeof item !== "function" && item.ws === true && wsPrefix.length) {
61
+ return !_utils.toArray.call(void 0, item.context).filter(_utils.isString).some((context) => wsPrefix.includes(context));
62
+ }
63
+ return true;
64
+ });
65
+ }
66
+ compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
67
+ compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
68
+ } else if (options.build !== false) {
69
+ compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => _chunk4GMRSIINcjs.buildMockServer.call(void 0,
70
+ options,
71
+ compilerOptions.output.path || _path2.default.resolve(_process2.default.cwd(), "dist")
72
+ ));
73
+ }
74
+ }
75
+ };
76
+ function resolvePluginOptions2(compiler, options) {
77
+ const compilerOptions = compiler.options;
78
+ const alias = _optionalChain([compilerOptions, 'access', _9 => _9.resolve, 'optionalAccess', _10 => _10.alias]) || {};
79
+ const context = compilerOptions.context;
80
+ const definePluginInstance = _optionalChain([compilerOptions, 'access', _11 => _11.plugins, 'optionalAccess', _12 => _12.find, 'call', _13 => _13(
81
+ (plugin) => plugin instanceof _core2.default.DefinePlugin
82
+ )]);
83
+ const proxies = (_optionalChain([compilerOptions, 'access', _14 => _14.devServer, 'optionalAccess', _15 => _15.proxy]) || []).flatMap((item) => {
84
+ if (typeof item !== "function" && item.context && !item.ws) {
85
+ return item.context;
86
+ }
87
+ return [];
88
+ });
89
+ return _chunk4GMRSIINcjs.resolvePluginOptions.call(void 0, options, {
90
+ alias,
91
+ context,
92
+ plugins: _utils.toArray.call(void 0, definePluginInstance),
93
+ proxies
94
+ });
95
+ }
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+ exports.MockCompiler = _chunk4GMRSIINcjs.MockCompiler; exports.MockServerPlugin = MockServerPlugin; exports.createMockCompiler = _chunk4GMRSIINcjs.createMockCompiler; exports.createMockMiddleware = _chunk4GMRSIINcjs.createMockMiddleware; exports.mockWebSocket = _chunkZEC4FWWYcjs.mockWebSocket; exports.resolvePluginOptions = resolvePluginOptions2;
package/dist/index.d.cts CHANGED
@@ -1,79 +1,24 @@
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
- export { createDefineMock, defineMock } from './helper.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';
1
+ import { RspackPluginInstance, Compiler } from '@rspack/core';
2
+ import { M as MockServerPluginOptions } from './types-BgpcN3jm.cjs';
3
+ import { R as ResolvePluginOptions } from './mockWebsocket-Dc9CZBfv.cjs';
4
+ export { a as Middleware, M as MiddlewareOptions, f as MockCompiler, d as MockCompilerOptions, b as MockSocketOptions, S as Server, e as createMockCompiler, c as createMockMiddleware, m as mockWebSocket } from './mockWebsocket-Dc9CZBfv.cjs';
10
5
  import 'node:buffer';
6
+ import 'node:http';
11
7
  import 'node:stream';
12
8
  import 'cookies';
13
9
  import 'cors';
14
10
  import 'formidable';
15
11
  import 'ws';
16
12
  import 'co-body';
13
+ import 'node:http2';
14
+ import 'node:events';
15
+ import 'node:fs';
17
16
 
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;
17
+ declare class MockServerPlugin implements RspackPluginInstance {
18
+ options: MockServerPluginOptions;
19
+ constructor(options?: MockServerPluginOptions);
20
+ apply(compiler: Compiler): void;
25
21
  }
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)[];
22
+ declare function resolvePluginOptions(compiler: Compiler, options: MockServerPluginOptions): ResolvePluginOptions;
78
23
 
79
- export { type BaseMiddlewareOptions, Logger, type Middleware, type MiddlewareOptions, type MockSocketOptions, type Server, baseMiddleware, createMockCompiler, createMockMiddleware, mockWebSocket, sortByValidator, transformMockData, transformRawData };
24
+ export { MockServerPlugin, resolvePluginOptions };
package/dist/index.d.ts CHANGED
@@ -1,79 +1,24 @@
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';
3
- export { createDefineMock, defineMock } from './helper.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';
1
+ import { RspackPluginInstance, Compiler } from '@rspack/core';
2
+ import { M as MockServerPluginOptions } from './types-BgpcN3jm.js';
3
+ import { R as ResolvePluginOptions } from './mockWebsocket-CPuTAvL0.js';
4
+ export { a as Middleware, M as MiddlewareOptions, f as MockCompiler, d as MockCompilerOptions, b as MockSocketOptions, S as Server, e as createMockCompiler, c as createMockMiddleware, m as mockWebSocket } from './mockWebsocket-CPuTAvL0.js';
10
5
  import 'node:buffer';
6
+ import 'node:http';
11
7
  import 'node:stream';
12
8
  import 'cookies';
13
9
  import 'cors';
14
10
  import 'formidable';
15
11
  import 'ws';
16
12
  import 'co-body';
13
+ import 'node:http2';
14
+ import 'node:events';
15
+ import 'node:fs';
17
16
 
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;
17
+ declare class MockServerPlugin implements RspackPluginInstance {
18
+ options: MockServerPluginOptions;
19
+ constructor(options?: MockServerPluginOptions);
20
+ apply(compiler: Compiler): void;
25
21
  }
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)[];
22
+ declare function resolvePluginOptions(compiler: Compiler, options: MockServerPluginOptions): ResolvePluginOptions;
78
23
 
79
- export { type BaseMiddlewareOptions, Logger, type Middleware, type MiddlewareOptions, type MockSocketOptions, type Server, baseMiddleware, createMockCompiler, createMockMiddleware, mockWebSocket, sortByValidator, transformMockData, transformRawData };
24
+ export { MockServerPlugin, resolvePluginOptions };
package/dist/index.js CHANGED
@@ -1,34 +1,103 @@
1
1
  import {
2
- MockServerPlugin,
3
- resolvePluginOptions
4
- } from "./chunk-P5FOCSCE.js";
5
- import {
6
- createDefineMock,
7
- defineMock
8
- } from "./chunk-HTOWPFQ7.js";
9
- import {
10
- baseMiddleware,
11
- createLogger,
2
+ MockCompiler,
3
+ buildMockServer,
12
4
  createMockCompiler,
13
5
  createMockMiddleware,
14
- logLevels,
6
+ resolvePluginOptions
7
+ } from "./chunk-B5W3PWCX.js";
8
+ import {
15
9
  mockWebSocket,
16
- sortByValidator,
17
- transformMockData,
18
- transformRawData
19
- } from "./chunk-YSJVV4SH.js";
10
+ rewriteRequest,
11
+ waitingFor
12
+ } from "./chunk-EY46RSAC.js";
13
+
14
+ // src/rspack.ts
15
+ import process from "process";
16
+ import path from "path";
17
+ import rspack from "@rspack/core";
18
+ import { isString, toArray } from "@pengzhanbo/utils";
19
+ var PLUGIN_NAME = "rspack-plugin-mock";
20
+ var MockServerPlugin = class {
21
+ constructor(options = {}) {
22
+ this.options = options;
23
+ }
24
+ apply(compiler) {
25
+ const compilerOptions = compiler.options;
26
+ const options = resolvePluginOptions2(compiler, this.options);
27
+ if (process.env.NODE_ENV !== "production") {
28
+ const mockCompiler = createMockCompiler(options);
29
+ const mockMiddleware = createMockMiddleware(mockCompiler, options);
30
+ const setupMiddlewares = compilerOptions.devServer?.setupMiddlewares;
31
+ const waitServer = waitingFor((server) => {
32
+ mockWebSocket(mockCompiler, server, options);
33
+ });
34
+ compilerOptions.devServer = {
35
+ ...compilerOptions.devServer,
36
+ setupMiddlewares: (middlewares, devServer) => {
37
+ middlewares = setupMiddlewares?.(middlewares, devServer) || middlewares;
38
+ const reload = () => {
39
+ if (devServer.webSocketServer?.clients)
40
+ devServer.sendMessage(devServer.webSocketServer.clients, "static-changed");
41
+ };
42
+ middlewares = mockMiddleware(middlewares, reload) || middlewares;
43
+ waitServer(() => devServer.server);
44
+ return middlewares;
45
+ }
46
+ };
47
+ const proxy = compilerOptions.devServer?.proxy || [];
48
+ const wsPrefix = toArray(options.wsPrefix);
49
+ if (proxy.length) {
50
+ compilerOptions.devServer.proxy = proxy.map((item) => {
51
+ if (typeof item !== "function" && !item.ws) {
52
+ const onProxyReq = item.onProxyReq;
53
+ item.onProxyReq = (proxyReq, req, ...args) => {
54
+ onProxyReq?.(proxyReq, req, ...args);
55
+ rewriteRequest(proxyReq, req);
56
+ };
57
+ }
58
+ return item;
59
+ }).filter((item) => {
60
+ if (typeof item !== "function" && item.ws === true && wsPrefix.length) {
61
+ return !toArray(item.context).filter(isString).some((context) => wsPrefix.includes(context));
62
+ }
63
+ return true;
64
+ });
65
+ }
66
+ compiler.hooks.watchRun.tap(PLUGIN_NAME, () => mockCompiler.run());
67
+ compiler.hooks.watchClose.tap(PLUGIN_NAME, () => mockCompiler.close());
68
+ } else if (options.build !== false) {
69
+ compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => buildMockServer(
70
+ options,
71
+ compilerOptions.output.path || path.resolve(process.cwd(), "dist")
72
+ ));
73
+ }
74
+ }
75
+ };
76
+ function resolvePluginOptions2(compiler, options) {
77
+ const compilerOptions = compiler.options;
78
+ const alias = compilerOptions.resolve?.alias || {};
79
+ const context = compilerOptions.context;
80
+ const definePluginInstance = compilerOptions.plugins?.find(
81
+ (plugin) => plugin instanceof rspack.DefinePlugin
82
+ );
83
+ const proxies = (compilerOptions.devServer?.proxy || []).flatMap((item) => {
84
+ if (typeof item !== "function" && item.context && !item.ws) {
85
+ return item.context;
86
+ }
87
+ return [];
88
+ });
89
+ return resolvePluginOptions(options, {
90
+ alias,
91
+ context,
92
+ plugins: toArray(definePluginInstance),
93
+ proxies
94
+ });
95
+ }
20
96
  export {
97
+ MockCompiler,
21
98
  MockServerPlugin,
22
- baseMiddleware,
23
- createDefineMock,
24
- createLogger,
25
99
  createMockCompiler,
26
100
  createMockMiddleware,
27
- defineMock,
28
- logLevels,
29
101
  mockWebSocket,
30
- resolvePluginOptions,
31
- sortByValidator,
32
- transformMockData,
33
- transformRawData
102
+ resolvePluginOptions2 as resolvePluginOptions
34
103
  };
@@ -0,0 +1,76 @@
1
+ import { RspackPluginInstance, Compiler, RspackOptionsNormalized } from '@rspack/core';
2
+ import { i as LogLevel, M as MockServerPluginOptions, S as ServerBuildOption, c as MockOptions } from './types-BgpcN3jm.js';
3
+ import { Server as Server$1 } from 'node:http';
4
+ import { Http2SecureServer } from 'node:http2';
5
+ import EventEmitter from 'node:events';
6
+ import { FSWatcher } from 'node:fs';
7
+
8
+ interface Logger {
9
+ debug: (msg: string, level?: boolean | LogLevel) => void;
10
+ info: (msg: string, level?: boolean | LogLevel) => void;
11
+ warn: (msg: string, level?: boolean | LogLevel) => void;
12
+ error: (msg: string, level?: boolean | LogLevel) => void;
13
+ }
14
+ declare const logLevels: Record<LogLevel, number>;
15
+ declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
16
+
17
+ interface ResolvedCompilerOptions {
18
+ alias: Record<string, false | string | (string | false)[]>;
19
+ proxies: (string | ((pathname: string, req: any) => boolean))[];
20
+ wsProxies: (string | ((pathname: string, req: any) => boolean))[];
21
+ plugins: RspackPluginInstance[];
22
+ context?: string;
23
+ }
24
+ type ResolvePluginOptions = Required<Omit<MockServerPluginOptions, 'build'>> & ResolvedCompilerOptions & {
25
+ logger: Logger;
26
+ build: false | ServerBuildOption;
27
+ };
28
+
29
+ interface MockCompilerOptions {
30
+ alias?: Record<string, false | string | (string | false)[]>;
31
+ plugins: RspackPluginInstance[];
32
+ cwd?: string;
33
+ include: string | string[];
34
+ exclude: string | string[];
35
+ logger: Logger;
36
+ }
37
+ declare function createMockCompiler(options: MockCompilerOptions): MockCompiler;
38
+ declare class MockCompiler extends EventEmitter {
39
+ options: MockCompilerOptions;
40
+ cwd: string;
41
+ mockWatcher: FSWatcher;
42
+ moduleType: 'cjs' | 'esm';
43
+ entryFile: string;
44
+ private _mockData;
45
+ private fileFilter;
46
+ private watchInfo?;
47
+ compiler?: Compiler | null;
48
+ constructor(options: MockCompilerOptions);
49
+ get mockData(): Record<string, MockOptions>;
50
+ run(): Promise<void>;
51
+ close(): void;
52
+ updateAlias(alias: Record<string, false | string | (string | false)[]>): void;
53
+ updateMockEntry(): Promise<void>;
54
+ getMockFiles(): Promise<string[]>;
55
+ watchMockFiles(): void;
56
+ }
57
+
58
+ interface MiddlewareOptions {
59
+ alias: Record<string, false | string | (string | false)[]>;
60
+ proxies: (string | ((pathname: string, req: any) => boolean))[];
61
+ context?: string;
62
+ plugins: RspackPluginInstance[];
63
+ }
64
+ declare function createMockMiddleware(compiler: MockCompiler, options: ResolvePluginOptions): (middlewares: Middleware[], reload?: () => void) => Middleware[];
65
+ type SetupMiddlewaresFn = NonNullable<NonNullable<RspackOptionsNormalized['devServer']>['setupMiddlewares']>;
66
+ type Middleware = SetupMiddlewaresFn extends (middlewares: (infer T)[], devServer: any) => void ? T : never;
67
+ type Server = SetupMiddlewaresFn extends (middlewares: any, devServer: infer T) => void ? T : never;
68
+
69
+ interface MockSocketOptions {
70
+ wsProxies: (string | ((pathname: string, req: any) => boolean))[];
71
+ cookiesOptions: MockServerPluginOptions['cookiesOptions'];
72
+ logger: Logger;
73
+ }
74
+ declare function mockWebSocket(compiler: MockCompiler, httpServer: Server$1 | Http2SecureServer, { wsProxies: proxies, cookiesOptions, logger, }: MockSocketOptions): void;
75
+
76
+ export { type Logger as L, type MiddlewareOptions as M, type ResolvePluginOptions as R, type Server as S, type Middleware as a, type MockSocketOptions as b, createMockMiddleware as c, type MockCompilerOptions as d, createMockCompiler as e, MockCompiler as f, createLogger as g, logLevels as l, mockWebSocket as m };