@modern-js/server 1.4.4 → 1.4.7-canary.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.
@@ -17,6 +17,8 @@ var _webpackDevMiddleware = _interopRequireDefault(require("webpack-dev-middlewa
17
17
 
18
18
  var _prodServer = require("@modern-js/prod-server");
19
19
 
20
+ var _constants = require("../constants");
21
+
20
22
  var _mock = require("../dev-tools/mock");
21
23
 
22
24
  var _socketServer = _interopRequireDefault(require("../dev-tools/socket-server"));
@@ -37,27 +39,10 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
37
39
 
38
40
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
39
41
 
40
- const DEFAULT_DEV_OPTIONS = {
41
- client: {
42
- port: '8080',
43
- overlay: false,
44
- logging: 'none',
45
- path: _utils.HMR_SOCK_PATH,
46
- host: 'localhost'
47
- },
48
- https: false,
49
- dev: {
50
- writeToDisk: true
51
- },
52
- watch: true,
53
- hot: true,
54
- liveReload: true
55
- };
56
-
57
42
  class ModernDevServer extends _prodServer.ModernServer {
58
43
  constructor(options) {
59
- super(options);
60
- this.devProxyHandler = null;
44
+ super(options); // dev server should work in pwd
45
+
61
46
  this.mockHandler = null;
62
47
  this.dev = void 0;
63
48
  this.compiler = void 0;
@@ -68,27 +53,25 @@ class ModernDevServer extends _prodServer.ModernServer {
68
53
 
69
54
  this.compiler = options.compiler; // set dev server options, like webpack-dev-server
70
55
 
71
- this.dev = typeof options.dev === 'boolean' ? DEFAULT_DEV_OPTIONS : _objectSpread(_objectSpread({}, DEFAULT_DEV_OPTIONS), options.dev);
56
+ this.dev = _objectSpread(_objectSpread({}, _constants.DEFAULT_DEV_OPTIONS), typeof options.dev === 'boolean' ? {} : options.dev);
72
57
  (0, _register.enableRegister)(this.pwd, this.conf);
73
58
  } // Complete the preparation of services
74
59
 
75
60
 
76
- async init(runner) {
61
+ async onInit(runner) {
77
62
  var _conf$tools, _conf$tools$devServer;
78
63
 
79
64
  const {
80
65
  conf,
81
66
  pwd,
82
- compiler
67
+ compiler,
68
+ dev
83
69
  } = this; // mock handler
84
70
 
85
71
  this.mockHandler = (0, _mock.createMockHandler)({
86
72
  pwd
87
73
  });
88
74
  this.addHandler((ctx, next) => {
89
- ctx.res.setHeader('Access-Control-Allow-Origin', '*');
90
- ctx.res.setHeader('Access-Control-Allow-Credentials', 'false');
91
-
92
75
  if (this.mockHandler) {
93
76
  this.mockHandler(ctx, next);
94
77
  } else {
@@ -96,10 +79,10 @@ class ModernDevServer extends _prodServer.ModernServer {
96
79
  }
97
80
  }); // dev proxy handler, each proxy has own handler
98
81
 
99
- this.devProxyHandler = (0, _prodServer.createProxyHandler)((_conf$tools = conf.tools) === null || _conf$tools === void 0 ? void 0 : (_conf$tools$devServer = _conf$tools.devServer) === null || _conf$tools$devServer === void 0 ? void 0 : _conf$tools$devServer.proxy);
82
+ const proxyHandlers = (0, _prodServer.createProxyHandler)((_conf$tools = conf.tools) === null || _conf$tools === void 0 ? void 0 : (_conf$tools$devServer = _conf$tools.devServer) === null || _conf$tools$devServer === void 0 ? void 0 : _conf$tools$devServer.proxy);
100
83
 
101
- if (this.devProxyHandler) {
102
- this.devProxyHandler.forEach(handler => {
84
+ if (proxyHandlers) {
85
+ proxyHandlers.forEach(handler => {
103
86
  this.addHandler(handler);
104
87
  });
105
88
  } // do webpack build / plugin apply / socket server when pass compiler instance
@@ -107,7 +90,7 @@ class ModernDevServer extends _prodServer.ModernServer {
107
90
 
108
91
  if (compiler) {
109
92
  // init socket server
110
- this.socketServer = new _socketServer.default(this.dev); // open file in edtor.
93
+ this.socketServer = new _socketServer.default(dev); // open file in edtor.
111
94
 
112
95
  this.addHandler((0, _launchEditor.createLaunchEditorHandler)()); // setup compiler in server, also add dev-middleware to handler static file in memory
113
96
 
@@ -115,32 +98,17 @@ class ModernDevServer extends _prodServer.ModernServer {
115
98
  this.addHandler(devMiddlewareHandler);
116
99
  }
117
100
 
118
- await super.init(runner); // watch mock/ server/ api/ dir file change
101
+ await super.onInit(runner); // watch mock/ server/ api/ dir file change
119
102
 
120
- if (this.dev.watch) {
103
+ if (dev.watch) {
121
104
  this.startWatcher();
122
105
  }
123
106
  }
124
107
 
125
- ready(options = {}) {
126
- // reset the routing management instance every times the service starts
127
- this.router.reset(this.filterRoutes(options.routes || this.presetRoutes || []));
128
- this.cleanSSRCache(); // reset static file
129
-
130
- this.reader.updateFile();
131
- this.runner.reset();
132
- }
133
-
134
- onListening(app) {
108
+ async onClose() {
135
109
  var _this$socketServer;
136
110
 
137
- (_this$socketServer = this.socketServer) === null || _this$socketServer === void 0 ? void 0 : _this$socketServer.prepare(app);
138
- }
139
-
140
- async close() {
141
- var _this$socketServer2;
142
-
143
- super.close();
111
+ await super.onClose();
144
112
  await this.watcher.close();
145
113
  await new Promise(resolve => {
146
114
  if (this.devMiddleware) {
@@ -151,7 +119,28 @@ class ModernDevServer extends _prodServer.ModernServer {
151
119
  resolve();
152
120
  }
153
121
  });
154
- (_this$socketServer2 = this.socketServer) === null || _this$socketServer2 === void 0 ? void 0 : _this$socketServer2.close();
122
+ (_this$socketServer = this.socketServer) === null || _this$socketServer === void 0 ? void 0 : _this$socketServer.close();
123
+ }
124
+
125
+ onRepack(options = {}) {
126
+ // reset the routing management instance every times the service starts
127
+ if (Array.isArray(options.routes)) {
128
+ this.router.reset(this.filterRoutes(options.routes));
129
+ } // clean ssr bundle cache
130
+
131
+
132
+ this.cleanSSRCache(); // reset static file
133
+
134
+ this.reader.updateFile(); // emit reset hook
135
+
136
+ this.runner.reset();
137
+ super.onRepack(options);
138
+ }
139
+
140
+ onListening(app) {
141
+ var _this$socketServer2;
142
+
143
+ (_this$socketServer2 = this.socketServer) === null || _this$socketServer2 === void 0 ? void 0 : _this$socketServer2.prepare(app);
155
144
  }
156
145
 
157
146
  async createHTTPServer(handler) {
@@ -172,7 +161,36 @@ class ModernDevServer extends _prodServer.ModernServer {
172
161
  }
173
162
  }
174
163
 
175
- warmupSSRBundle() {// empty
164
+ warmupSSRBundle() {// not warmup ssr bundle on development
165
+ }
166
+
167
+ onServerChange({
168
+ filepath
169
+ }) {
170
+ const {
171
+ pwd
172
+ } = this;
173
+ const {
174
+ mock
175
+ } = _prodServer.AGGRED_DIR;
176
+
177
+ const mockPath = _path.default.normalize(_path.default.join(pwd, mock));
178
+
179
+ this.runner.reset();
180
+
181
+ if (filepath.startsWith(mockPath)) {
182
+ this.mockHandler = (0, _mock.createMockHandler)({
183
+ pwd
184
+ });
185
+ } else {
186
+ try {
187
+ super.onServerChange({
188
+ filepath
189
+ });
190
+ } catch (e) {
191
+ this.logger.error(e);
192
+ }
193
+ }
176
194
  } // set up plugin to each compiler
177
195
  // register hooks for each compilation, update socket stats if recompiled
178
196
  // start dev middleware
@@ -223,8 +241,8 @@ class ModernDevServer extends _prodServer.ModernServer {
223
241
  if (stats.toJson({
224
242
  all: false
225
243
  }).name === 'client') {
226
- this.ready({
227
- routes: this.readRouteSpec()
244
+ this.onRepack({
245
+ routes: this.getRoutes()
228
246
  });
229
247
  }
230
248
  });
@@ -275,9 +293,6 @@ class ModernDevServer extends _prodServer.ModernServer {
275
293
  } = _prodServer.AGGRED_DIR;
276
294
  const defaultWatched = [`${mock}/**/*`, `${_utils.SERVER_DIR}/**/*`, `${_utils.API_DIR}/**`, `${_utils.SHARED_DIR}/**/*`];
277
295
  const defaultWatchedPaths = defaultWatched.map(p => _path.default.normalize(_path.default.join(pwd, p)));
278
-
279
- const mockPath = _path.default.normalize(_path.default.join(pwd, mock));
280
-
281
296
  const watcher = new _watcher.default();
282
297
  watcher.createDepTree(); // 监听文件变动,如果有变动则给 client,也就是 start 启动的插件发消息
283
298
 
@@ -288,19 +303,9 @@ class ModernDevServer extends _prodServer.ModernServer {
288
303
  }, filepath => {
289
304
  watcher.updateDepTree();
290
305
  watcher.cleanDepCache(filepath);
291
- this.runner.reset();
292
-
293
- if (filepath.startsWith(mockPath)) {
294
- this.mockHandler = (0, _mock.createMockHandler)({
295
- pwd
296
- });
297
- } else {
298
- try {
299
- this.prepareFrameHandler();
300
- } catch (e) {
301
- this.logger.error(e);
302
- }
303
- }
306
+ this.onServerChange({
307
+ filepath
308
+ });
304
309
  });
305
310
  this.watcher = watcher;
306
311
  }
@@ -0,0 +1,2 @@
1
+ import { DevServerOptions } from './types';
2
+ export declare const DEFAULT_DEV_OPTIONS: DevServerOptions;
@@ -1,16 +1,16 @@
1
1
  import type { APIServerStartInput } from '@modern-js/server-core';
2
2
  import { ServerRoute as ModernRouteInterface } from '@modern-js/types';
3
- import { ApiServerMode } from '@modern-js/prod-server';
3
+ import { ApiServerMode, HookNames } from '@modern-js/prod-server';
4
4
  import { ModernDevServer } from './dev-server';
5
5
  export declare class ModernSSRDevServer extends ModernDevServer {
6
6
  protected prepareAPIHandler(_m: ApiServerMode, _: APIServerStartInput['config']): any;
7
- protected prepareWebHandler(extension: {
8
- middleware: any[];
9
- }): Promise<import("@modern-js/server-core").Adapter>;
10
7
  protected filterRoutes(routes: ModernRouteInterface[]): ModernRouteInterface[];
8
+ protected preServerInit(): Promise<void>;
9
+ protected emitRouteHook(_: HookNames, _input: any): Promise<void>;
11
10
  }
12
11
  export declare class ModernAPIDevServer extends ModernDevServer {
13
- protected prepareAPIHandler(mode: ApiServerMode, extension: APIServerStartInput['config']): Promise<import("@modern-js/server-core").Adapter>;
12
+ protected prepareWebHandler(_: APIServerStartInput['config']): any;
14
13
  protected filterRoutes(routes: ModernRouteInterface[]): ModernRouteInterface[];
15
14
  protected preServerInit(): Promise<void>;
15
+ protected emitRouteHook(_: HookNames, _input: any): Promise<void>;
16
16
  }
@@ -1,9 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import http, { Server, IncomingMessage, ServerResponse } from 'http';
3
- import { ServerHookRunner, ReadyOptions, ModernServer } from '@modern-js/prod-server';
3
+ import { ServerHookRunner, ModernServer, BuildOptions } from '@modern-js/prod-server';
4
4
  import { ModernDevServerOptions } from '../types';
5
5
  export declare class ModernDevServer extends ModernServer {
6
- private devProxyHandler;
7
6
  private mockHandler;
8
7
  private readonly dev;
9
8
  private readonly compiler?;
@@ -11,12 +10,17 @@ export declare class ModernDevServer extends ModernServer {
11
10
  private watcher;
12
11
  private devMiddleware;
13
12
  constructor(options: ModernDevServerOptions);
14
- init(runner: ServerHookRunner): Promise<void>;
15
- ready(options?: ReadyOptions): void;
13
+ onInit(runner: ServerHookRunner): Promise<void>;
14
+ onClose(): Promise<void>;
15
+ onRepack(options?: BuildOptions): void;
16
16
  onListening(app: Server): void;
17
- close(): Promise<void>;
18
17
  createHTTPServer(handler: (req: IncomingMessage, res: ServerResponse, next?: () => void) => void): Promise<http.Server | import("https").Server>;
19
18
  protected warmupSSRBundle(): void;
19
+ protected onServerChange({
20
+ filepath
21
+ }: {
22
+ filepath: string;
23
+ }): void;
20
24
  private setupCompiler;
21
25
  private setupDevServerPlugin;
22
26
  private setupHooks;
package/package.json CHANGED
@@ -11,9 +11,9 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.4.4",
14
+ "version": "1.4.7-canary.0",
15
15
  "jsnext:source": "./src/index.ts",
16
- "types": "./dist/types/index.d.ts",
16
+ "types": "./src/index.ts",
17
17
  "main": "./dist/js/node/index.js",
18
18
  "module": "./dist/js/treeshaking/index.js",
19
19
  "jsnext:modern": "./dist/js/modern/index.js",
@@ -27,12 +27,21 @@
27
27
  "default": "./dist/js/treeshaking/index.js"
28
28
  }
29
29
  },
30
+ "scripts": {
31
+ "prepare": "pnpm build",
32
+ "prepublishOnly": "pnpm build --platform",
33
+ "new": "modern new",
34
+ "build": "modern build",
35
+ "dev": "modern build --watch",
36
+ "test": "jest"
37
+ },
30
38
  "dependencies": {
31
- "@modern-js/prod-server": "^1.0.1",
39
+ "@modern-js/prod-server": "workspace:^1.0.2",
32
40
  "@babel/register": "^7.15.3",
33
- "@modern-js/hmr-client": "^1.2.2",
34
- "@modern-js/server-utils": "^1.2.1",
35
- "@modern-js/utils": "^1.3.3",
41
+ "@modern-js/bff-utils": "workspace:^1.2.2",
42
+ "@modern-js/hmr-client": "workspace:^1.2.2",
43
+ "@modern-js/server-utils": "workspace:^1.2.1",
44
+ "@modern-js/utils": "workspace:^1.3.4",
36
45
  "chokidar": "^3.5.2",
37
46
  "devcert": "^1.1.3",
38
47
  "launch-editor": "^2.2.1",
@@ -43,19 +52,19 @@
43
52
  "ws": "^8.2.0"
44
53
  },
45
54
  "devDependencies": {
46
- "@modern-js/server-core": "^1.2.2",
47
- "@modern-js/core": "^1.4.4",
48
- "@scripts/build": "0.0.0",
49
- "@modern-js/types": "^1.3.4",
55
+ "@modern-js/server-core": "workspace:^1.2.2",
56
+ "@modern-js/core": "workspace:^1.4.6",
57
+ "@scripts/build": "workspace:*",
58
+ "@modern-js/types": "workspace:^1.3.4",
50
59
  "@types/jest": "^26",
51
60
  "@types/minimatch": "^3.0.5",
52
61
  "@types/node": "^14",
53
62
  "@types/webpack-dev-middleware": "^5.0.2",
54
63
  "@types/ws": "^7.4.7",
64
+ "jest": "^27",
55
65
  "typescript": "^4",
56
66
  "webpack": "^5.54.0",
57
- "jest": "^27",
58
- "@scripts/jest-config": "0.0.0",
67
+ "@scripts/jest-config": "workspace:*",
59
68
  "websocket": "^1"
60
69
  },
61
70
  "peerDependencies": {
@@ -69,13 +78,7 @@
69
78
  },
70
79
  "publishConfig": {
71
80
  "registry": "https://registry.npmjs.org/",
72
- "access": "public"
73
- },
74
- "scripts": {
75
- "new": "modern new",
76
- "build": "modern build",
77
- "dev": "modern build --watch",
78
- "test": "jest --passWithNoTests"
79
- },
80
- "readme": "\n<p align=\"center\">\n <a href=\"https://modernjs.dev\" target=\"blank\"><img src=\"https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png\" width=\"300\" alt=\"Modern.js Logo\" /></a>\n</p>\n<p align=\"center\">\n现代 Web 工程体系\n <br/>\n <a href=\"https://modernjs.dev\" target=\"blank\">\n modernjs.dev\n </a>\n</p>\n<p align=\"center\">\n The meta-framework suite designed from scratch for frontend-focused modern web development\n</p>\n\n# Introduction\n\n> The doc site ([modernjs.dev](https://modernjs.dev)) and articles are only available in Chinese for now, we are planning to add English versions soon.\n\n- [Modern.js: Hello, World!](https://zhuanlan.zhihu.com/p/426707646)\n\n## Getting Started\n\n- [Quick Start](https://modernjs.dev/docs/start)\n- [Guides](https://modernjs.dev/docs/guides)\n- [API References](https://modernjs.dev/docs/apis)\n\n## Contributing\n\n- [Contributing Guide](https://github.com/modern-js-dev/modern.js/blob/main/CONTRIBUTING.md)\n"
81
- }
81
+ "access": "public",
82
+ "types": "./dist/types/index.d.ts"
83
+ }
84
+ }
package/tests/dev.test.ts CHANGED
@@ -1,19 +1,7 @@
1
1
  import http from 'http';
2
- import path from 'path';
3
- import { webpack } from 'webpack';
4
- import { fs, LAUNCH_EDITOR_ENDPOINT } from '@modern-js/utils';
2
+ import { webpack, HotModuleReplacementPlugin } from 'webpack';
5
3
  import SocketServer from '../src/dev-tools/socket-server';
6
4
  import DevServerPlugin from '../src/dev-tools/dev-server-plugin';
7
- import Watcher, { getWatchedFiles } from '../src/dev-tools/watcher';
8
- import { StatsCache } from '../src/dev-tools/watcher/stats-cache';
9
- import { createMockHandler } from '../src/dev-tools/mock';
10
- import getMockData, { getMatched } from '../src/dev-tools/mock/getMockData';
11
- import { createLaunchEditorHandler } from '../src/dev-tools/launch-editor';
12
- import { genHttpsOptions } from '../src/dev-tools/https';
13
-
14
- const noop = () => {
15
- // empty
16
- };
17
5
 
18
6
  function getRandomPort() {
19
7
  return Math.floor(Math.random() * (8000 - 1024)) + 1024;
@@ -80,8 +68,10 @@ describe('test dev tools', () => {
80
68
  app.close();
81
69
  });
82
70
 
83
- test('should dev server plugin work correctly', () => {
84
- const compiler = webpack({});
71
+ test('should dev server plugin work correctly with hot plugin', () => {
72
+ const compiler = webpack({
73
+ plugins: [new HotModuleReplacementPlugin()],
74
+ });
85
75
  new DevServerPlugin({
86
76
  client: {
87
77
  port: '8080',
@@ -109,247 +99,32 @@ describe('test dev tools', () => {
109
99
  expect(hotPluginHook.length).toBe(1);
110
100
  });
111
101
 
112
- describe('test watcher', () => {
113
- let watcher: any;
114
- const baseDir = path.join(__dirname, 'fixtures');
115
- const watchDir = path.join(baseDir, 'watch/**');
116
- const filepath = path.join(baseDir, 'watch', 'index.ts');
117
- const filepatha = path.join(baseDir, 'watch', 'a.ts');
118
- const txt = path.join(baseDir, 'watch', 'stats.txt');
119
-
120
- afterEach(() => {
121
- if (watcher) {
122
- watcher.close();
123
- }
124
- fs.writeFileSync(txt, '1');
125
- });
126
-
127
- it('should create watcher instance correctly', resolve => {
128
- watcher = new Watcher();
129
- expect(watcher.dependencyTree).toBeNull();
130
- watcher.createDepTree();
131
- expect(watcher.dependencyTree).not.toBeNull();
132
-
133
- expect(watcher.watcher).toBeUndefined();
134
- watcher.listen([watchDir], {}, () => {
135
- // empty
136
- });
137
-
138
- expect(watcher.watcher).toBeDefined();
139
- require(filepath);
140
- expect(watcher.dependencyTree.getNode(filepath)).toBeUndefined();
141
- watcher.updateDepTree();
142
- expect(watcher.dependencyTree.getNode(filepath)).toBeDefined();
143
- watcher.cleanDepCache(filepath);
144
- expect(watcher.dependencyTree.getNode(filepath)).toBeDefined();
145
-
146
- jest.resetModules();
147
- watcher.updateDepTree();
148
- expect(watcher.dependencyTree.getNode(filepath)).toBeUndefined();
149
-
150
- setTimeout(() => {
151
- const fl = getWatchedFiles(watcher.watcher);
152
- expect(fl.includes(filepatha)).toBeTruthy();
153
- expect(fl.includes(filepath)).toBeTruthy();
154
- expect(fl.includes(txt)).toBeTruthy();
155
- resolve();
156
- }, 1000);
157
- });
158
-
159
- it('should stats cache instance work correctly', () => {
160
- const statsCache = new StatsCache();
161
-
162
- // should not exist false before add
163
- expect(statsCache.has(txt)).toBeFalsy();
164
-
165
- // should exist true after add
166
- statsCache.add([txt]);
167
- expect(statsCache.has(txt)).toBeTruthy();
168
-
169
- // should diff correctly
170
- fs.writeFileSync(txt, 'foo');
171
- expect(statsCache.isDiff(txt)).toBeTruthy();
172
-
173
- // should not diff if not refresh
174
- fs.writeFileSync(txt, '1');
175
- expect(statsCache.isDiff(txt)).toBeFalsy();
176
-
177
- // should diff after refresh
178
- fs.writeFileSync(txt, 'foo');
179
- statsCache.refresh(txt);
180
- fs.writeFileSync(txt, '1');
181
- expect(statsCache.isDiff(txt)).toBeTruthy();
182
-
183
- // should diff when content change
184
- statsCache.refresh(txt);
185
- fs.writeFileSync(txt, '2');
186
- expect(statsCache.isDiff(txt)).toBeTruthy();
187
-
188
- // should not exist after del
189
- statsCache.del(txt);
190
- expect(statsCache.has(txt)).toBeFalsy();
191
- });
192
- });
193
-
194
- describe('should mock middleware work correctly', () => {
195
- const pwd = path.join(__dirname, './fixtures/mock');
196
-
197
- it('should return null if no config mock dir', () => {
198
- expect(createMockHandler({ pwd: path.join(pwd, 'empty') })).toBeNull();
199
- });
200
-
201
- it('should return null if no api dir', () => {
202
- expect(createMockHandler({ pwd: path.join(pwd, 'zero') })).toBeNull();
203
- });
204
-
205
- it('should return middleware if mock api exist', async () => {
206
- const middleware = createMockHandler({ pwd: path.join(pwd, 'exist') });
207
-
208
- expect(middleware).not.toBeNull();
209
-
210
- let response: any;
211
- const context: any = {
212
- path: '/api/getInfo',
213
- method: 'get',
214
- res: {
215
- setHeader: noop,
216
- end: (data: any) => {
217
- response = JSON.parse(data);
218
- },
219
- },
220
- };
221
- await middleware?.(context, noop);
222
- expect(response).toEqual({
223
- data: [1, 2, 3, 4],
224
- });
225
- });
226
-
227
- it('should get api list correctly', () => {
228
- const apiList = getMockData(path.join(pwd, 'exist/config/mock/index.ts'));
229
- expect(apiList.length).toBe(3);
230
-
231
- const pathList = apiList.map(api => api.path);
232
- expect(pathList).toEqual([
233
- '/api/getInfo',
234
- '/api/getExample',
235
- '/api/addInfo',
236
- ]);
237
-
238
- let response: any;
239
- const context: any = {
240
- res: {
241
- setHeader: noop,
242
- end: (data: any) => {
243
- response = JSON.parse(data);
244
- },
245
- },
246
- };
247
-
248
- apiList[0].handler(context, noop as any);
249
- expect(response).toEqual({
250
- data: [1, 2, 3, 4],
251
- });
252
- apiList[1].handler(context, noop as any);
253
- expect(response).toEqual({ id: 1 });
254
- });
255
-
256
- it('should match api correctly', () => {
257
- const apiList = [
258
- {
259
- method: 'get',
260
- path: '/api/getInfo',
261
- handler: noop,
262
- },
263
- {
264
- method: 'get',
265
- path: '/api/getExample',
266
- handler: noop,
267
- },
268
- {
269
- method: 'get',
270
- path: '/api/addInfo',
271
- handler: noop,
272
- },
273
- ];
274
- const matched = getMatched(
275
- { path: '/api/getInfo', method: 'get' } as any,
276
- apiList,
277
- );
278
- expect(matched).toBe(apiList[0]);
279
-
280
- const missMethod = getMatched(
281
- { path: '/api/getModern', method: 'post' } as any,
282
- apiList,
283
- );
284
- expect(missMethod).toBeUndefined();
285
- });
286
- });
287
-
288
- describe('should createLaunchEditorHandler work correctly', () => {
289
- const middleware = createLaunchEditorHandler();
290
-
291
- it('should return 200 if filename exist', () => {
292
- let response: any;
293
- const context: any = {
294
- url: LAUNCH_EDITOR_ENDPOINT,
295
- query: {
296
- filename: 'test.ts',
297
- },
298
- res: {
299
- end: (data: any) => {
300
- response = data;
301
- },
302
- },
303
- };
304
- middleware(context, noop);
305
- expect(context.status).toBe(200);
306
- expect(response).toBeUndefined();
307
- });
308
-
309
- it('should return 500 if filename not exist', () => {
310
- let response: any;
311
- const context: any = {
312
- url: LAUNCH_EDITOR_ENDPOINT,
313
- query: {
314
- filename: '',
315
- },
316
- res: {
317
- end: (data: any) => {
318
- response = data;
319
- },
320
- },
321
- };
322
- middleware(context, noop);
323
- expect(context.status).toBe(500);
324
- expect(typeof response === 'string').toBeTruthy();
325
- });
326
-
327
- it('should invoke next if not launch editor url', () => {
328
- let response: any;
329
- const context: any = {
330
- url: '',
331
- res: {
332
- end: (data: any) => {
333
- response = data;
334
- },
335
- },
336
- };
337
- middleware(context, noop);
338
- expect(context.status).toBeUndefined();
339
- expect(response).toBeUndefined();
340
- });
341
- });
342
-
343
- test('should get http cert correctly', async () => {
344
- // const options = await genHttpsOptions(true);
345
- // expect(options.key).toBeDefined();
346
- // expect(options.cert).toBeDefined();
102
+ test('should dev server plugin work correctly', () => {
103
+ const compiler = webpack({});
104
+ new DevServerPlugin({
105
+ client: {
106
+ port: '8080',
107
+ overlay: false,
108
+ logging: 'error',
109
+ path: '/',
110
+ host: '127.0.0.1',
111
+ },
112
+ dev: {
113
+ writeToDisk: false,
114
+ },
115
+ watch: true,
116
+ hot: true,
117
+ liveReload: true,
118
+ }).apply(compiler);
347
119
 
348
- const useOpt = await genHttpsOptions({
349
- key: 'foo',
350
- cert: 'baz',
351
- });
352
- expect(useOpt.key).toBe('foo');
353
- expect(useOpt.cert).toBe('baz');
120
+ // expect(compiler.options.entry)
121
+ const entryPluginHook = compiler.hooks.compilation.taps.filter(
122
+ tap => tap.name === 'EntryPlugin',
123
+ );
124
+ const hotPluginHook = compiler.hooks.compilation.taps.filter(
125
+ tap => tap.name === 'HotModuleReplacementPlugin',
126
+ );
127
+ expect(entryPluginHook.length).toBe(3);
128
+ expect(hotPluginHook.length).toBe(1);
354
129
  });
355
130
  });