@umijs/bundler-webpack 4.0.0-rc.13 → 4.0.0-rc.16

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.
Files changed (42) hide show
  1. package/client/client/client.js +15 -7
  2. package/dist/build.js +48 -58
  3. package/dist/cli.js +6 -15
  4. package/dist/client/client.js +48 -53
  5. package/dist/config/_sampleFeature.js +6 -17
  6. package/dist/config/assetRules.js +44 -55
  7. package/dist/config/bundleAnalyzerPlugin.js +12 -23
  8. package/dist/config/compressPlugin.js +68 -76
  9. package/dist/config/config.d.ts +1 -0
  10. package/dist/config/config.js +177 -184
  11. package/dist/config/copyPlugin.js +29 -40
  12. package/dist/config/cssRules.js +93 -83
  13. package/dist/config/definePlugin.js +11 -19
  14. package/dist/config/detectDeadCodePlugin.js +16 -21
  15. package/dist/config/fastRefreshPlugin.js +11 -22
  16. package/dist/config/forkTSCheckerPlugin.js +11 -22
  17. package/dist/config/harmonyLinkingErrorPlugin.js +3 -14
  18. package/dist/config/ignorePlugin.js +10 -21
  19. package/dist/config/javaScriptRules.d.ts +1 -0
  20. package/dist/config/javaScriptRules.js +149 -136
  21. package/dist/config/manifestPlugin.js +10 -18
  22. package/dist/config/miniCSSExtractPlugin.js +12 -23
  23. package/dist/config/nodePolyfill.js +14 -20
  24. package/dist/config/nodePrefixPlugin.js +8 -19
  25. package/dist/config/progressPlugin.js +7 -18
  26. package/dist/config/purgecssWebpackPlugin.js +15 -26
  27. package/dist/config/speedMeasureWebpackPlugin.js +12 -23
  28. package/dist/config/svgRules.js +43 -47
  29. package/dist/dev.js +103 -100
  30. package/dist/loader/svgr.js +4 -13
  31. package/dist/loader/swc.js +9 -14
  32. package/dist/plugins/ESBuildCSSMinifyPlugin.js +23 -34
  33. package/dist/plugins/ParcelCSSMinifyPlugin.js +30 -32
  34. package/dist/plugins/RuntimePublicPathPlugin.js +1 -1
  35. package/dist/schema.js +19 -6
  36. package/dist/server/server.d.ts +1 -1
  37. package/dist/server/server.js +161 -182
  38. package/dist/server/ws.d.ts +3 -1
  39. package/dist/types.d.ts +3 -6
  40. package/package.json +10 -10
  41. package/dist/server/https.d.ts +0 -5
  42. package/dist/server/https.js +0 -73
@@ -1,18 +1,10 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
14
5
  Object.defineProperty(exports, "__esModule", { value: true });
15
6
  exports.createServer = void 0;
7
+ const bundler_utils_1 = require("@umijs/bundler-utils");
16
8
  const express_1 = __importDefault(require("@umijs/bundler-utils/compiled/express"));
17
9
  const http_proxy_middleware_1 = require("@umijs/bundler-webpack/compiled/http-proxy-middleware");
18
10
  const webpack_1 = __importDefault(require("@umijs/bundler-webpack/compiled/webpack"));
@@ -21,194 +13,181 @@ const fs_1 = require("fs");
21
13
  const http_1 = __importDefault(require("http"));
22
14
  const path_1 = require("path");
23
15
  const constants_1 = require("../constants");
24
- const https_1 = require("./https");
25
16
  const ws_1 = require("./ws");
26
- function createServer(opts) {
27
- return __awaiter(this, void 0, void 0, function* () {
28
- const { webpackConfig, userConfig } = opts;
29
- const { proxy } = userConfig;
30
- const app = (0, express_1.default)();
31
- // basename middleware
32
- app.use((req, _res, next) => {
33
- const { url, path } = req;
34
- const { basename, history } = userConfig;
35
- if ((history === null || history === void 0 ? void 0 : history.type) === 'browser' &&
36
- basename !== '/' &&
37
- url.startsWith(basename)) {
38
- req.url = url.slice(basename.length);
39
- req.path = path.slice(basename.length);
40
- }
41
- next();
42
- });
43
- // cros
44
- app.use((_req, res, next) => {
45
- res.header('Access-Control-Allow-Origin', '*');
46
- res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
47
- res.header('Access-Control-Allow-Methods', 'GET, HEAD, PUT, POST, PATCH, DELETE, OPTIONS');
17
+ async function createServer(opts) {
18
+ const { webpackConfig, userConfig } = opts;
19
+ const { proxy } = userConfig;
20
+ const app = (0, express_1.default)();
21
+ // cros
22
+ app.use((_req, res, next) => {
23
+ res.header('Access-Control-Allow-Origin', '*');
24
+ res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
25
+ res.header('Access-Control-Allow-Methods', 'GET, HEAD, PUT, POST, PATCH, DELETE, OPTIONS');
26
+ next();
27
+ });
28
+ // compression
29
+ app.use(require('@umijs/bundler-webpack/compiled/compression')());
30
+ // TODO: headers
31
+ // before middlewares
32
+ (opts.beforeMiddlewares || []).forEach((m) => app.use(m));
33
+ // TODO: add to before middleware
34
+ app.use((req, res, next) => {
35
+ if (req.path === '/umi.js' && (0, fs_1.existsSync)((0, path_1.join)(opts.cwd, 'umi.js'))) {
36
+ res.setHeader('Content-Type', 'application/javascript');
37
+ (0, fs_1.createReadStream)((0, path_1.join)(opts.cwd, 'umi.js')).on('error', next).pipe(res);
38
+ }
39
+ else {
48
40
  next();
41
+ }
42
+ });
43
+ // webpack dev middleware
44
+ const configs = Array.isArray(webpackConfig)
45
+ ? webpackConfig
46
+ : [webpackConfig];
47
+ const progresses = [];
48
+ if (opts.onProgress) {
49
+ configs.forEach((config) => {
50
+ const progress = {
51
+ percent: 0,
52
+ status: 'waiting',
53
+ };
54
+ progresses.push(progress);
55
+ config.plugins.push(new webpack_1.default.ProgressPlugin((percent, msg) => {
56
+ progress.percent = percent;
57
+ progress.status = msg;
58
+ opts.onProgress({ progresses });
59
+ }));
49
60
  });
50
- // compression
51
- app.use(require('@umijs/bundler-webpack/compiled/compression')());
52
- // TODO: headers
53
- // before middlewares
54
- (opts.beforeMiddlewares || []).forEach((m) => app.use(m));
55
- // TODO: add to before middleware
56
- app.use((req, res, next) => {
57
- if (req.path === '/umi.js' && (0, fs_1.existsSync)((0, path_1.join)(opts.cwd, 'umi.js'))) {
58
- res.setHeader('Content-Type', 'application/javascript');
59
- (0, fs_1.createReadStream)((0, path_1.join)(opts.cwd, 'umi.js')).on('error', next).pipe(res);
60
- }
61
- else {
62
- next();
63
- }
61
+ }
62
+ const compiler = (0, webpack_1.default)(configs);
63
+ const webpackDevMiddleware = require('@umijs/bundler-webpack/compiled/webpack-dev-middleware');
64
+ const compilerMiddleware = webpackDevMiddleware(compiler, {
65
+ publicPath: userConfig.publicPath || '/',
66
+ writeToDisk: userConfig.writeToDisk,
67
+ stats: 'none',
68
+ // watchOptions: { ignored }
69
+ });
70
+ app.use(compilerMiddleware);
71
+ // hmr hooks
72
+ let stats;
73
+ let isFirstCompile = true;
74
+ compiler.compilers.forEach(addHooks);
75
+ function addHooks(compiler) {
76
+ compiler.hooks.invalid.tap('server', () => {
77
+ sendMessage(constants_1.MESSAGE_TYPE.invalid);
64
78
  });
65
- // webpack dev middleware
66
- const configs = Array.isArray(webpackConfig)
67
- ? webpackConfig
68
- : [webpackConfig];
69
- const progresses = [];
70
- if (opts.onProgress) {
71
- configs.forEach((config) => {
72
- const progress = {
73
- percent: 0,
74
- status: 'waiting',
75
- };
76
- progresses.push(progress);
77
- config.plugins.push(new webpack_1.default.ProgressPlugin((percent, msg) => {
78
- progress.percent = percent;
79
- progress.status = msg;
80
- opts.onProgress({ progresses });
81
- }));
79
+ compiler.hooks.done.tap('server', (_stats) => {
80
+ var _a;
81
+ stats = _stats;
82
+ sendStats(getStats(stats));
83
+ (_a = opts.onDevCompileDone) === null || _a === void 0 ? void 0 : _a.call(opts, {
84
+ stats,
85
+ isFirstCompile,
86
+ time: stats.endTime - stats.startTime,
82
87
  });
83
- }
84
- const compiler = (0, webpack_1.default)(configs);
85
- const webpackDevMiddleware = require('@umijs/bundler-webpack/compiled/webpack-dev-middleware');
86
- const compilerMiddleware = webpackDevMiddleware(compiler, {
87
- publicPath: userConfig.publicPath || '/',
88
- writeToDisk: userConfig.writeToDisk,
89
- stats: 'none',
90
- // watchOptions: { ignored }
88
+ isFirstCompile = false;
91
89
  });
92
- app.use(compilerMiddleware);
93
- // hmr hooks
94
- let stats;
95
- let isFirstCompile = true;
96
- compiler.compilers.forEach(addHooks);
97
- function addHooks(compiler) {
98
- compiler.hooks.invalid.tap('server', () => {
99
- sendMessage(constants_1.MESSAGE_TYPE.invalid);
100
- });
101
- compiler.hooks.done.tap('server', (_stats) => {
102
- var _a;
103
- stats = _stats;
104
- sendStats(getStats(stats));
105
- (_a = opts.onDevCompileDone) === null || _a === void 0 ? void 0 : _a.call(opts, {
106
- stats,
107
- isFirstCompile,
108
- time: stats.endTime - stats.startTime,
109
- });
110
- isFirstCompile = false;
111
- });
90
+ }
91
+ function sendStats(stats, force, sender) {
92
+ const shouldEmit = !force &&
93
+ stats &&
94
+ (!stats.errors || stats.errors.length === 0) &&
95
+ (!stats.warnings || stats.warnings.length === 0) &&
96
+ stats.assets &&
97
+ stats.assets.every((asset) => !asset.emitted);
98
+ if (shouldEmit) {
99
+ sendMessage(constants_1.MESSAGE_TYPE.stillOk, null, sender);
100
+ return;
112
101
  }
113
- function sendStats(stats, force, sender) {
114
- const shouldEmit = !force &&
115
- stats &&
116
- (!stats.errors || stats.errors.length === 0) &&
117
- (!stats.warnings || stats.warnings.length === 0) &&
118
- stats.assets &&
119
- stats.assets.every((asset) => !asset.emitted);
120
- if (shouldEmit) {
121
- sendMessage(constants_1.MESSAGE_TYPE.stillOk, null, sender);
122
- return;
123
- }
124
- sendMessage(constants_1.MESSAGE_TYPE.hash, stats.hash, sender);
125
- if ((stats.errors && stats.errors.length > 0) ||
126
- (stats.warnings && stats.warnings.length > 0)) {
127
- if (stats.warnings && stats.warnings.length > 0) {
128
- sendMessage(constants_1.MESSAGE_TYPE.warnings, stats.warnings, sender);
129
- }
130
- if (stats.errors && stats.errors.length > 0) {
131
- sendMessage(constants_1.MESSAGE_TYPE.errors, stats.errors, sender);
132
- }
102
+ sendMessage(constants_1.MESSAGE_TYPE.hash, stats.hash, sender);
103
+ if ((stats.errors && stats.errors.length > 0) ||
104
+ (stats.warnings && stats.warnings.length > 0)) {
105
+ if (stats.warnings && stats.warnings.length > 0) {
106
+ sendMessage(constants_1.MESSAGE_TYPE.warnings, stats.warnings, sender);
133
107
  }
134
- else {
135
- sendMessage(constants_1.MESSAGE_TYPE.ok, null, sender);
108
+ if (stats.errors && stats.errors.length > 0) {
109
+ sendMessage(constants_1.MESSAGE_TYPE.errors, stats.errors, sender);
136
110
  }
137
111
  }
138
- function getStats(stats) {
139
- return stats.toJson({
140
- all: false,
141
- hash: true,
142
- assets: true,
143
- warnings: true,
144
- errors: true,
145
- errorDetails: false,
146
- });
147
- }
148
- function sendMessage(type, data, sender) {
149
- (sender || ws).send(JSON.stringify({ type, data }));
112
+ else {
113
+ sendMessage(constants_1.MESSAGE_TYPE.ok, null, sender);
150
114
  }
151
- // mock
152
- // proxy
153
- if (proxy) {
154
- Object.keys(proxy).forEach((key) => {
155
- const proxyConfig = proxy[key];
156
- const target = proxyConfig.target;
157
- if (target) {
158
- app.use(key, (0, http_proxy_middleware_1.createProxyMiddleware)(key, Object.assign(Object.assign({}, proxy[key]), {
159
- // Add x-real-url in response header
160
- onProxyRes(proxyRes, req) {
161
- var _a;
162
- proxyRes.headers['x-real-url'] =
163
- ((_a = new URL(req.url || '', target)) === null || _a === void 0 ? void 0 : _a.href) || '';
164
- } })));
165
- }
166
- });
167
- }
168
- // after middlewares
169
- (opts.afterMiddlewares || []).forEach((m) => {
170
- // TODO: FIXME
171
- app.use(m.toString().includes(`{ compiler }`) ? m({ compiler }) : m);
172
- });
173
- // history fallback
174
- app.use(require('@umijs/bundler-webpack/compiled/connect-history-api-fallback')({
175
- index: '/',
176
- }));
177
- // hmr reconnect ping
178
- app.use('/__umi_ping', (_, res) => {
179
- res.end('pong');
115
+ }
116
+ function getStats(stats) {
117
+ return stats.toJson({
118
+ all: false,
119
+ hash: true,
120
+ assets: true,
121
+ warnings: true,
122
+ errors: true,
123
+ errorDetails: false,
180
124
  });
181
- // index.html
182
- // TODO: remove me
183
- app.get('/', (_req, res, next) => {
184
- res.set('Content-Type', 'text/html');
185
- const htmlPath = (0, path_1.join)(opts.cwd, 'index.html');
186
- if ((0, fs_1.existsSync)(htmlPath)) {
187
- (0, fs_1.createReadStream)(htmlPath).on('error', next).pipe(res);
188
- }
189
- else {
190
- next();
125
+ }
126
+ function sendMessage(type, data, sender) {
127
+ (sender || ws).send(JSON.stringify({ type, data }));
128
+ }
129
+ // mock
130
+ // proxy
131
+ if (proxy) {
132
+ Object.keys(proxy).forEach((key) => {
133
+ const proxyConfig = proxy[key];
134
+ const target = proxyConfig.target;
135
+ if (target) {
136
+ app.use(key, (0, http_proxy_middleware_1.createProxyMiddleware)(key, {
137
+ ...proxy[key],
138
+ // Add x-real-url in response header
139
+ onProxyRes(proxyRes, req) {
140
+ var _a;
141
+ proxyRes.headers['x-real-url'] =
142
+ ((_a = new URL(req.url || '', target)) === null || _a === void 0 ? void 0 : _a.href) || '';
143
+ },
144
+ }));
191
145
  }
192
146
  });
193
- const server = userConfig.https
194
- ? yield (0, https_1.createHttpsServer)(app, userConfig.https)
195
- : http_1.default.createServer(app);
196
- if (!server) {
197
- return null;
147
+ }
148
+ // after middlewares
149
+ (opts.afterMiddlewares || []).forEach((m) => {
150
+ // TODO: FIXME
151
+ app.use(m.toString().includes(`{ compiler }`) ? m({ compiler }) : m);
152
+ });
153
+ // history fallback
154
+ app.use(require('@umijs/bundler-webpack/compiled/connect-history-api-fallback')({
155
+ index: '/',
156
+ }));
157
+ // hmr reconnect ping
158
+ app.use('/__umi_ping', (_, res) => {
159
+ res.end('pong');
160
+ });
161
+ // index.html
162
+ // TODO: remove me
163
+ app.get('/', (_req, res, next) => {
164
+ res.set('Content-Type', 'text/html');
165
+ const htmlPath = (0, path_1.join)(opts.cwd, 'index.html');
166
+ if ((0, fs_1.existsSync)(htmlPath)) {
167
+ (0, fs_1.createReadStream)(htmlPath).on('error', next).pipe(res);
198
168
  }
199
- const ws = (0, ws_1.createWebSocketServer)(server);
200
- ws.wss.on('connection', (socket) => {
201
- if (stats) {
202
- sendStats(getStats(stats), false, socket);
203
- }
204
- });
205
- const protocol = userConfig.https ? 'https:' : 'http:';
206
- const port = opts.port || 8000;
207
- server.listen(port, () => {
208
- const host = opts.host && opts.host !== '0.0.0.0' ? opts.host : '127.0.0.1';
209
- utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`${protocol}//${host}:${port}`)}`);
210
- });
211
- return server;
169
+ else {
170
+ next();
171
+ }
172
+ });
173
+ const server = userConfig.https
174
+ ? await (0, bundler_utils_1.createHttpsServer)(app, userConfig.https)
175
+ : http_1.default.createServer(app);
176
+ if (!server) {
177
+ return null;
178
+ }
179
+ const ws = (0, ws_1.createWebSocketServer)(server);
180
+ ws.wss.on('connection', (socket) => {
181
+ if (stats) {
182
+ sendStats(getStats(stats), false, socket);
183
+ }
184
+ });
185
+ const protocol = userConfig.https ? 'https:' : 'http:';
186
+ const port = opts.port || 8000;
187
+ server.listen(port, () => {
188
+ const host = opts.host && opts.host !== '0.0.0.0' ? opts.host : '127.0.0.1';
189
+ utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`${protocol}//${host}:${port}`)}`);
212
190
  });
191
+ return server;
213
192
  }
214
193
  exports.createServer = createServer;
@@ -1,8 +1,10 @@
1
1
  /// <reference types="node" />
2
+ import type { SpdyServer as Server } from '@umijs/bundler-utils';
2
3
  import { Server as HttpServer } from 'http';
4
+ import { Http2Server } from 'http2';
3
5
  import { Server as HttpsServer } from 'https';
4
6
  import WebSocket from '../../compiled/ws';
5
- export declare function createWebSocketServer(server: HttpServer | HttpsServer): {
7
+ export declare function createWebSocketServer(server: HttpServer | HttpsServer | Http2Server | Server): {
6
8
  send(message: string): void;
7
9
  wss: WebSocket.Server;
8
10
  close(): void;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Config as SwcConfig } from '@swc/core';
2
+ import type { HttpsServerOptions } from '@umijs/bundler-utils';
2
3
  import type { Options as ProxyOptions } from '../compiled/http-proxy-middleware';
3
4
  import { Configuration } from '../compiled/webpack';
4
5
  import Config from '../compiled/webpack-5-chain';
@@ -41,11 +42,6 @@ export interface DeadCodeParams {
41
42
  detectUnusedExport?: boolean;
42
43
  context?: string;
43
44
  }
44
- export interface HttpsParams {
45
- key?: string;
46
- cert?: string;
47
- hosts?: string[];
48
- }
49
45
  export interface IConfig {
50
46
  alias?: Record<string, string>;
51
47
  autoCSSModules?: boolean;
@@ -68,13 +64,14 @@ export interface IConfig {
68
64
  depTranspiler?: Transpiler;
69
65
  devtool?: Config.DevTool;
70
66
  deadCode?: DeadCodeParams;
71
- https?: HttpsParams;
67
+ https?: HttpsServerOptions;
72
68
  externals?: WebpackConfig['externals'];
73
69
  esm?: {
74
70
  [key: string]: any;
75
71
  };
76
72
  extraBabelPlugins?: IBabelPlugin[];
77
73
  extraBabelPresets?: IBabelPlugin[];
74
+ extraBabelIncludes?: string[];
78
75
  extraPostCSSPlugins?: any[];
79
76
  hash?: boolean;
80
77
  ignoreMomentLocale?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/bundler-webpack",
3
- "version": "4.0.0-rc.13",
3
+ "version": "4.0.0-rc.16",
4
4
  "description": "@umijs/bundler-webpack",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/bundler-webpack#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -23,28 +23,28 @@
23
23
  "scripts": {
24
24
  "build": "pnpm tsc",
25
25
  "build:client": "pnpm tsc --project ./tsconfig.client.json",
26
- "build:deps": "pnpm esno ../../scripts/bundleDeps.ts",
26
+ "build:deps": "umi-scripts bundleDeps",
27
27
  "dev": "pnpm build -- --watch",
28
28
  "generate:webpackPackages": "zx ./scripts/generateWebpackPackages.mjs",
29
- "test": "jest -c ../../jest.turbo.config.ts"
29
+ "test": "umi-scripts jest-turbo"
30
30
  },
31
31
  "dependencies": {
32
- "@parcel/css": "1.8.1",
32
+ "@parcel/css": "1.8.2",
33
33
  "@pmmmwh/react-refresh-webpack-plugin": "0.5.5",
34
34
  "@svgr/core": "6.2.1",
35
35
  "@svgr/plugin-jsx": "^6.2.1",
36
36
  "@svgr/plugin-svgo": "^6.2.0",
37
37
  "@types/hapi__joi": "17.1.8",
38
- "@umijs/babel-preset-umi": "4.0.0-rc.13",
39
- "@umijs/bundler-utils": "4.0.0-rc.13",
40
- "@umijs/mfsu": "4.0.0-rc.13",
41
- "@umijs/utils": "4.0.0-rc.13",
38
+ "@umijs/babel-preset-umi": "4.0.0-rc.16",
39
+ "@umijs/bundler-utils": "4.0.0-rc.16",
40
+ "@umijs/mfsu": "4.0.0-rc.16",
41
+ "@umijs/utils": "4.0.0-rc.16",
42
42
  "css-loader": "6.7.1",
43
43
  "es5-imcompatible-versions": "^0.1.73",
44
44
  "jest-worker": "27.5.1",
45
45
  "node-libs-browser": "2.2.1",
46
- "postcss": "^8.4.12",
47
- "postcss-preset-env": "7.4.3",
46
+ "postcss": "^8.4.13",
47
+ "postcss-preset-env": "7.5.0",
48
48
  "react-error-overlay": "6.0.9"
49
49
  },
50
50
  "devDependencies": {
@@ -1,5 +0,0 @@
1
- /// <reference types="node" />
2
- import { RequestListener } from 'http';
3
- import https from 'https';
4
- import { HttpsParams } from '../types';
5
- export declare function createHttpsServer(app: RequestListener, httpsConfig: HttpsParams): Promise<https.Server>;
@@ -1,73 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createHttpsServer = void 0;
16
- const utils_1 = require("@umijs/utils");
17
- const fs_1 = require("fs");
18
- const https_1 = __importDefault(require("https"));
19
- const path_1 = require("path");
20
- const defaultHttpsHosts = ['localhost', '127.0.0.1'];
21
- function createHttpsServer(app, httpsConfig) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- utils_1.logger.wait('[HTTPS] Starting service in https mode...');
24
- // Check if mkcert is installed
25
- try {
26
- yield utils_1.execa.execa('mkcert', ['--version']);
27
- }
28
- catch (e) {
29
- utils_1.logger.error('[HTTPS] The mkcert has not been installed.');
30
- utils_1.logger.info('[HTTPS] Please follow the guide to install manually.');
31
- switch (process.platform) {
32
- case 'darwin':
33
- console.log(utils_1.chalk.green('$ brew install mkcert'));
34
- console.log(utils_1.chalk.gray('# If you use firefox, please install nss.'));
35
- console.log(utils_1.chalk.green('$ brew install nss'));
36
- console.log(utils_1.chalk.green('$ mkcert -install'));
37
- break;
38
- case 'win32':
39
- console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#windows'));
40
- break;
41
- case 'linux':
42
- console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#linux'));
43
- break;
44
- default:
45
- break;
46
- }
47
- throw new Error(`[HTTPS] mkcert not found.`);
48
- }
49
- let { key, cert, hosts } = httpsConfig;
50
- hosts = hosts || defaultHttpsHosts;
51
- if (!key || !cert) {
52
- key = (0, path_1.join)(__dirname, 'umi.key.pem');
53
- cert = (0, path_1.join)(__dirname, 'umi.pem');
54
- }
55
- // Generate cert and key files if they are not exist.
56
- if (!(0, fs_1.existsSync)(key) || !(0, fs_1.existsSync)(cert)) {
57
- utils_1.logger.wait('[HTTPS] Generating cert and key files...');
58
- yield utils_1.execa.execa('mkcert', [
59
- '-cert-file',
60
- cert,
61
- '-key-file',
62
- key,
63
- ...hosts,
64
- ]);
65
- }
66
- // Create server
67
- return https_1.default.createServer({
68
- key: (0, fs_1.readFileSync)(key, 'utf-8'),
69
- cert: (0, fs_1.readFileSync)(cert, 'utf-8'),
70
- }, app);
71
- });
72
- }
73
- exports.createHttpsServer = createHttpsServer;