webpack-dev-server 2.4.5 → 2.6.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/lib/Server.js CHANGED
@@ -1,551 +1,599 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const chokidar = require("chokidar");
5
- const path = require("path");
6
- const webpackDevMiddleware = require("webpack-dev-middleware");
7
- const express = require("express");
8
- const compress = require("compression");
9
- const sockjs = require("sockjs");
10
- const http = require("http");
11
- const spdy = require("spdy");
12
- const httpProxyMiddleware = require("http-proxy-middleware");
13
- const serveIndex = require("serve-index");
14
- const historyApiFallback = require("connect-history-api-fallback");
15
- const webpack = require("webpack");
16
- const OptionsValidationError = require("./OptionsValidationError");
17
- const optionsSchema = require("./optionsSchema.json");
18
-
19
- const clientStats = { errorDetails: false };
20
-
21
- function Server(compiler, options) {
22
- // Default options
23
- if(!options) options = {};
24
-
25
- const validationErrors = webpack.validateSchema(optionsSchema, options);
26
- if(validationErrors.length) {
27
- throw new OptionsValidationError(validationErrors);
28
- }
29
-
30
- if(options.lazy && !options.filename) {
31
- throw new Error("'filename' option must be set in lazy mode.");
32
- }
33
-
34
- this.hot = options.hot || options.hotOnly;
35
- this.headers = options.headers;
36
- this.clientLogLevel = options.clientLogLevel;
37
- this.clientOverlay = options.overlay;
38
- this.disableHostCheck = !!options.disableHostCheck;
39
- this.publicHost = options.public;
40
- this.sockets = [];
41
- this.contentBaseWatchers = [];
42
-
43
- // Listening for events
44
- const invalidPlugin = () => {
45
- this.sockWrite(this.sockets, "invalid");
46
- };
47
- compiler.plugin("compile", invalidPlugin);
48
- compiler.plugin("invalid", invalidPlugin);
49
- compiler.plugin("done", (stats) => {
50
- this._sendStats(this.sockets, stats.toJson(clientStats));
51
- this._stats = stats;
52
- });
53
-
54
- // Init express server
55
- const app = this.app = new express();
56
-
57
- app.all("*", (req, res, next) => {
58
- if(this.checkHost(req.headers))
59
- return next();
60
- res.send("Invalid Host header");
61
- });
62
-
63
- // middleware for serving webpack bundle
64
- this.middleware = webpackDevMiddleware(compiler, options);
65
-
66
- app.get("/__webpack_dev_server__/live.bundle.js", (req, res) => {
67
- res.setHeader("Content-Type", "application/javascript");
68
- fs.createReadStream(path.join(__dirname, "..", "client", "live.bundle.js")).pipe(res);
69
- });
70
-
71
- app.get("/__webpack_dev_server__/sockjs.bundle.js", (req, res) => {
72
- res.setHeader("Content-Type", "application/javascript");
73
- fs.createReadStream(path.join(__dirname, "..", "client", "sockjs.bundle.js")).pipe(res);
74
- });
75
-
76
- app.get("/webpack-dev-server.js", (req, res) => {
77
- res.setHeader("Content-Type", "application/javascript");
78
- fs.createReadStream(path.join(__dirname, "..", "client", "index.bundle.js")).pipe(res);
79
- });
80
-
81
- app.get("/webpack-dev-server/*", (req, res) => {
82
- res.setHeader("Content-Type", "text/html");
83
- fs.createReadStream(path.join(__dirname, "..", "client", "live.html")).pipe(res);
84
- });
85
-
86
- app.get("/webpack-dev-server", (req, res) => {
87
- res.setHeader("Content-Type", "text/html");
88
- /* eslint-disable quotes */
89
- res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>');
90
- const path = this.middleware.getFilenameFromUrl(options.publicPath || "/");
91
- const fs = this.middleware.fileSystem;
92
-
93
- function writeDirectory(baseUrl, basePath) {
94
- const content = fs.readdirSync(basePath);
95
- res.write("<ul>");
96
- content.forEach(function(item) {
97
- const p = `${basePath}/${item}`;
98
- if(fs.statSync(p).isFile()) {
99
- res.write('<li><a href="');
100
- res.write(baseUrl + item);
101
- res.write('">');
102
- res.write(item);
103
- res.write('</a></li>');
104
- if(/\.js$/.test(item)) {
105
- const htmlItem = item.substr(0, item.length - 3);
106
- res.write('<li><a href="');
107
- res.write(baseUrl + htmlItem);
108
- res.write('">');
109
- res.write(htmlItem);
110
- res.write('</a> (magic html for ');
111
- res.write(item);
112
- res.write(') (<a href="');
113
- res.write(baseUrl.replace(/(^(https?:\/\/[^\/]+)?\/)/, "$1webpack-dev-server/") + htmlItem);
114
- res.write('">webpack-dev-server</a>)</li>');
115
- }
116
- } else {
117
- res.write('<li>');
118
- res.write(item);
119
- res.write('<br>');
120
- writeDirectory(`${baseUrl + item}/`, p);
121
- res.write('</li>');
122
- }
123
- });
124
- res.write("</ul>");
125
- }
126
- /* eslint-enable quotes */
127
- writeDirectory(options.publicPath || "/", path);
128
- res.end("</body></html>");
129
- });
130
-
131
- let contentBase;
132
- if(options.contentBase !== undefined) {
133
- contentBase = options.contentBase;
134
- } else {
135
- contentBase = process.cwd();
136
- }
137
-
138
- // Keep track of websocket proxies for external websocket upgrade.
139
- const websocketProxies = [];
140
-
141
- const features = {
142
- compress() {
143
- if(options.compress) {
144
- // Enable gzip compression.
145
- app.use(compress());
146
- }
147
- },
148
-
149
- proxy() {
150
- if(options.proxy) {
151
- /**
152
- * Assume a proxy configuration specified as:
153
- * proxy: {
154
- * 'context': { options }
155
- * }
156
- * OR
157
- * proxy: {
158
- * 'context': 'target'
159
- * }
160
- */
161
- if(!Array.isArray(options.proxy)) {
162
- options.proxy = Object.keys(options.proxy).map((context) => {
163
- let proxyOptions;
164
- // For backwards compatibility reasons.
165
- const correctedContext = context.replace(/^\*$/, "**").replace(/\/\*$/, "");
166
-
167
- if(typeof options.proxy[context] === "string") {
168
- proxyOptions = {
169
- context: correctedContext,
170
- target: options.proxy[context]
171
- };
172
- } else {
173
- proxyOptions = Object.assign({}, options.proxy[context]);
174
- proxyOptions.context = correctedContext;
175
- }
176
- proxyOptions.logLevel = proxyOptions.logLevel || "warn";
177
-
178
- return proxyOptions;
179
- });
180
- }
181
-
182
- const getProxyMiddleware = (proxyConfig) => {
183
- const context = proxyConfig.context || proxyConfig.path;
184
-
185
- // It is possible to use the `bypass` method without a `target`.
186
- // However, the proxy middleware has no use in this case, and will fail to instantiate.
187
- if(proxyConfig.target) {
188
- return httpProxyMiddleware(context, proxyConfig);
189
- }
190
- }
191
-
192
- /**
193
- * Assume a proxy configuration specified as:
194
- * proxy: [
195
- * {
196
- * context: ...,
197
- * ...options...
198
- * },
199
- * // or:
200
- * function() {
201
- * return {
202
- * context: ...,
203
- * ...options...
204
- * };
205
- * }
206
- * ]
207
- */
208
- options.proxy.forEach((proxyConfigOrCallback) => {
209
- let proxyConfig;
210
- let proxyMiddleware;
211
-
212
- if(typeof proxyConfigOrCallback === "function") {
213
- proxyConfig = proxyConfigOrCallback();
214
- } else {
215
- proxyConfig = proxyConfigOrCallback;
216
- }
217
-
218
- proxyMiddleware = getProxyMiddleware(proxyConfig);
219
- if(proxyConfig.ws) {
220
- websocketProxies.push(proxyMiddleware);
221
- }
222
-
223
- app.use((req, res, next) => {
224
- if(typeof proxyConfigOrCallback === "function") {
225
- const newProxyConfig = proxyConfigOrCallback();
226
- if(newProxyConfig !== proxyConfig) {
227
- proxyConfig = newProxyConfig;
228
- proxyMiddleware = getProxyMiddleware(proxyConfig);
229
- }
230
- }
231
- const bypass = typeof proxyConfig.bypass === "function";
232
- const bypassUrl = bypass && proxyConfig.bypass(req, res, proxyConfig) || false;
233
-
234
- if(bypassUrl) {
235
- req.url = bypassUrl;
236
- next();
237
- } else if(proxyMiddleware) {
238
- return proxyMiddleware(req, res, next);
239
- } else {
240
- next();
241
- }
242
- });
243
- });
244
- }
245
- },
246
-
247
- historyApiFallback() {
248
- if(options.historyApiFallback) {
249
- // Fall back to /index.html if nothing else matches.
250
- app.use(
251
- historyApiFallback(typeof options.historyApiFallback === "object" ? options.historyApiFallback : null)
252
- );
253
- }
254
- },
255
-
256
- contentBaseFiles() {
257
- if(Array.isArray(contentBase)) {
258
- contentBase.forEach((item) => {
259
- app.get("*", express.static(item));
260
- });
261
- } else if(/^(https?:)?\/\//.test(contentBase)) {
262
- console.log("Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.");
263
- console.log('proxy: {\n\t"*": "<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
264
- // Redirect every request to contentBase
265
- app.get("*", (req, res) => {
266
- res.writeHead(302, {
267
- "Location": contentBase + req.path + (req._parsedUrl.search || "")
268
- });
269
- res.end();
270
- });
271
- } else if(typeof contentBase === "number") {
272
- console.log("Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.");
273
- console.log('proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
274
- // Redirect every request to the port contentBase
275
- app.get("*", (req, res) => {
276
- res.writeHead(302, {
277
- "Location": `//localhost:${contentBase}${req.path}${req._parsedUrl.search || ""}`
278
- });
279
- res.end();
280
- });
281
- } else {
282
- // route content request
283
- app.get("*", express.static(contentBase, options.staticOptions));
284
- }
285
- },
286
-
287
- contentBaseIndex() {
288
- if(Array.isArray(contentBase)) {
289
- contentBase.forEach((item) => {
290
- app.get("*", serveIndex(item));
291
- });
292
- } else if(!/^(https?:)?\/\//.test(contentBase) && typeof contentBase !== "number") {
293
- app.get("*", serveIndex(contentBase));
294
- }
295
- },
296
-
297
- watchContentBase: () => {
298
- if(/^(https?:)?\/\//.test(contentBase) || typeof contentBase === "number") {
299
- throw new Error("Watching remote files is not supported.");
300
- } else if(Array.isArray(contentBase)) {
301
- contentBase.forEach((item) => {
302
- this._watch(item);
303
- });
304
- } else {
305
- this._watch(contentBase);
306
- }
307
- },
308
-
309
- middleware: () => {
310
- // include our middleware to ensure it is able to handle '/index.html' request after redirect
311
- app.use(this.middleware);
312
- },
313
-
314
- headers: () => {
315
- app.all("*", this.setContentHeaders.bind(this));
316
- },
317
-
318
- magicHtml: () => {
319
- app.get("*", this.serveMagicHtml.bind(this));
320
- },
321
-
322
- setup: () => {
323
- if(typeof options.setup === "function")
324
- options.setup(app, this);
325
- }
326
- };
327
-
328
- const defaultFeatures = ["setup", "headers", "middleware"];
329
- if(options.proxy)
330
- defaultFeatures.push("proxy", "middleware");
331
- if(contentBase !== false)
332
- defaultFeatures.push("contentBaseFiles");
333
- if(options.watchContentBase)
334
- defaultFeatures.push("watchContentBase");
335
- if(options.historyApiFallback) {
336
- defaultFeatures.push("historyApiFallback", "middleware");
337
- if(contentBase !== false)
338
- defaultFeatures.push("contentBaseFiles");
339
- }
340
- defaultFeatures.push("magicHtml");
341
- if(contentBase !== false)
342
- defaultFeatures.push("contentBaseIndex");
343
- // compress is placed last and uses unshift so that it will be the first middleware used
344
- if(options.compress)
345
- defaultFeatures.unshift("compress");
346
-
347
- (options.features || defaultFeatures).forEach((feature) => {
348
- features[feature]();
349
- });
350
-
351
- if(options.https) {
352
- // for keep supporting CLI parameters
353
- if(typeof options.https === "boolean") {
354
- options.https = {
355
- key: options.key,
356
- cert: options.cert,
357
- ca: options.ca,
358
- pfx: options.pfx,
359
- passphrase: options.pfxPassphrase
360
- };
361
- }
362
-
363
- // Use built-in self-signed certificate if no certificate was configured
364
- const fakeCert = fs.readFileSync(path.join(__dirname, "../ssl/server.pem"));
365
- options.https.key = options.https.key || fakeCert;
366
- options.https.cert = options.https.cert || fakeCert;
367
-
368
- if(!options.https.spdy) {
369
- options.https.spdy = {
370
- protocols: ["h2", "http/1.1"]
371
- };
372
- }
373
-
374
- this.listeningApp = spdy.createServer(options.https, app);
375
- } else {
376
- this.listeningApp = http.createServer(app);
377
- }
378
-
379
- // Proxy websockets without the initial http request
380
- // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
381
- websocketProxies.forEach(function(wsProxy) {
382
- this.listeningApp.on("upgrade", wsProxy.upgrade);
383
- }, this);
384
- }
385
-
386
- Server.prototype.use = function() {
387
- this.app.use.apply(this.app, arguments);
388
- }
389
-
390
- Server.prototype.setContentHeaders = function(req, res, next) {
391
- if(this.headers) {
392
- for(const name in this.headers) {
393
- res.setHeader(name, this.headers[name]);
394
- }
395
- }
396
-
397
- next();
398
- }
399
-
400
- Server.prototype.checkHost = function(headers) {
401
- // allow user to opt-out this security check, at own risk
402
- if(this.disableHostCheck) return true;
403
-
404
- // get the Host header and extract hostname
405
- // we don't care about port not matching
406
- const hostHeader = headers.host;
407
- if(!hostHeader) return false;
408
- const idx = hostHeader.indexOf(":");
409
- const hostname = idx >= 0 ? hostHeader.substr(0, idx) : hostHeader;
410
-
411
- // always allow localhost host, for convience
412
- if(hostname === "127.0.0.1" || hostname === "localhost") return true;
413
-
414
- // allow hostname of listening adress
415
- if(hostname === this.listenHostname) return true;
416
-
417
- // also allow public hostname if provided
418
- if(typeof this.publicHost === "string") {
419
- const idxPublic = this.publicHost.indexOf(":");
420
- const publicHostname = idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
421
- if(hostname === publicHostname) return true;
422
- }
423
-
424
- // disallow
425
- return false;
426
- }
427
-
428
- // delegate listen call and init sockjs
429
- Server.prototype.listen = function(port, hostname) {
430
- this.listenHostname = hostname;
431
- const returnValue = this.listeningApp.listen.apply(this.listeningApp, arguments);
432
- const sockServer = sockjs.createServer({
433
- // Use provided up-to-date sockjs-client
434
- sockjs_url: "/__webpack_dev_server__/sockjs.bundle.js",
435
- // Limit useless logs
436
- log: function(severity, line) {
437
- if(severity === "error") {
438
- console.log(line);
439
- }
440
- }
441
- });
442
- sockServer.on("connection", (conn) => {
443
- if(!conn) return;
444
- if(!this.checkHost(conn.headers)) {
445
- this.sockWrite([conn], "error", "Invalid Host header");
446
- conn.close();
447
- return;
448
- }
449
- this.sockets.push(conn);
450
-
451
- conn.on("close", () => {
452
- const connIndex = this.sockets.indexOf(conn);
453
- if(connIndex >= 0) {
454
- this.sockets.splice(connIndex, 1);
455
- }
456
- });
457
-
458
- if(this.clientLogLevel)
459
- this.sockWrite([conn], "log-level", this.clientLogLevel);
460
-
461
- if(this.clientOverlay)
462
- this.sockWrite([conn], "overlay", this.clientOverlay);
463
-
464
- if(this.hot) this.sockWrite([conn], "hot");
465
-
466
- if(!this._stats) return;
467
- this._sendStats([conn], this._stats.toJson(clientStats), true);
468
- });
469
-
470
- sockServer.installHandlers(this.listeningApp, {
471
- prefix: "/sockjs-node"
472
- });
473
- return returnValue;
474
- }
475
-
476
- Server.prototype.close = function(callback) {
477
- this.sockets.forEach((sock) => {
478
- sock.close();
479
- });
480
- this.sockets = [];
481
- this.listeningApp.close(() => {
482
- this.middleware.close(callback);
483
- });
484
-
485
- this.contentBaseWatchers.forEach((watcher) => {
486
- watcher.close();
487
- });
488
- this.contentBaseWatchers = [];
489
- }
490
-
491
- Server.prototype.sockWrite = function(sockets, type, data) {
492
- sockets.forEach((sock) => {
493
- sock.write(JSON.stringify({
494
- type: type,
495
- data: data
496
- }));
497
- });
498
- }
499
-
500
- Server.prototype.serveMagicHtml = function(req, res, next) {
501
- const _path = req.path;
502
- try {
503
- if(!this.middleware.fileSystem.statSync(this.middleware.getFilenameFromUrl(`${_path}.js`)).isFile())
504
- return next();
505
- // Serve a page that executes the javascript
506
- /* eslint-disable quotes */
507
- res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="');
508
- res.write(_path);
509
- res.write('.js');
510
- res.write(req._parsedUrl.search || "");
511
- res.end('"></script></body></html>');
512
- /* eslint-enable quotes */
513
- } catch(e) {
514
- return next();
515
- }
516
- }
517
-
518
- // send stats to a socket or multiple sockets
519
- Server.prototype._sendStats = function(sockets, stats, force) {
520
- if(!force &&
521
- stats &&
522
- (!stats.errors || stats.errors.length === 0) &&
523
- stats.assets &&
524
- stats.assets.every((asset) => !asset.emitted)
525
- )
526
- return this.sockWrite(sockets, "still-ok");
527
- this.sockWrite(sockets, "hash", stats.hash);
528
- if(stats.errors.length > 0)
529
- this.sockWrite(sockets, "errors", stats.errors);
530
- else if(stats.warnings.length > 0)
531
- this.sockWrite(sockets, "warnings", stats.warnings);
532
- else
533
- this.sockWrite(sockets, "ok");
534
- }
535
-
536
- Server.prototype._watch = function(path) {
537
- const watcher = chokidar.watch(path).on("change", () => {
538
- this.sockWrite(this.sockets, "content-changed");
539
- });
540
-
541
- this.contentBaseWatchers.push(watcher);
542
- }
543
-
544
- Server.prototype.invalidate = function() {
545
- if(this.middleware) this.middleware.invalidate();
546
- }
547
-
548
- // Export this logic, so that other implementations, like task-runners can use it
549
- Server.addDevServerEntrypoints = require("./util/addDevServerEntrypoints");
550
-
551
- module.exports = Server;
1
+ "use strict";
2
+
3
+ const chokidar = require("chokidar");
4
+ const compress = require("compression");
5
+ const del = require("del");
6
+ const express = require("express");
7
+ const fs = require("fs");
8
+ const http = require("http");
9
+ const httpProxyMiddleware = require("http-proxy-middleware");
10
+ const serveIndex = require("serve-index");
11
+ const historyApiFallback = require("connect-history-api-fallback");
12
+ const path = require("path");
13
+ const selfsigned = require("selfsigned");
14
+ const sockjs = require("sockjs");
15
+ const spdy = require("spdy");
16
+ const webpack = require("webpack");
17
+ const webpackDevMiddleware = require("webpack-dev-middleware");
18
+
19
+ const OptionsValidationError = require("./OptionsValidationError");
20
+ const optionsSchema = require("./optionsSchema.json");
21
+
22
+ const clientStats = { errorDetails: false };
23
+
24
+ function Server(compiler, options) {
25
+ // Default options
26
+ if(!options) options = {};
27
+
28
+ const validationErrors = webpack.validateSchema(optionsSchema, options);
29
+ if(validationErrors.length) {
30
+ throw new OptionsValidationError(validationErrors);
31
+ }
32
+
33
+ if(options.lazy && !options.filename) {
34
+ throw new Error("'filename' option must be set in lazy mode.");
35
+ }
36
+
37
+ this.hot = options.hot || options.hotOnly;
38
+ this.headers = options.headers;
39
+ this.clientLogLevel = options.clientLogLevel;
40
+ this.clientOverlay = options.overlay;
41
+ this.disableHostCheck = !!options.disableHostCheck;
42
+ this.publicHost = options.public;
43
+ this.allowedHosts = options.allowedHosts;
44
+ this.sockets = [];
45
+ this.contentBaseWatchers = [];
46
+
47
+ // Listening for events
48
+ const invalidPlugin = () => {
49
+ this.sockWrite(this.sockets, "invalid");
50
+ };
51
+ compiler.plugin("compile", invalidPlugin);
52
+ compiler.plugin("invalid", invalidPlugin);
53
+ compiler.plugin("done", (stats) => {
54
+ this._sendStats(this.sockets, stats.toJson(clientStats));
55
+ this._stats = stats;
56
+ });
57
+
58
+ // Init express server
59
+ const app = this.app = new express();
60
+
61
+ app.all("*", (req, res, next) => {
62
+ if(this.checkHost(req.headers))
63
+ return next();
64
+ res.send("Invalid Host header");
65
+ });
66
+
67
+ // middleware for serving webpack bundle
68
+ this.middleware = webpackDevMiddleware(compiler, options);
69
+
70
+ app.get("/__webpack_dev_server__/live.bundle.js", (req, res) => {
71
+ res.setHeader("Content-Type", "application/javascript");
72
+ fs.createReadStream(path.join(__dirname, "..", "client", "live.bundle.js")).pipe(res);
73
+ });
74
+
75
+ app.get("/__webpack_dev_server__/sockjs.bundle.js", (req, res) => {
76
+ res.setHeader("Content-Type", "application/javascript");
77
+ fs.createReadStream(path.join(__dirname, "..", "client", "sockjs.bundle.js")).pipe(res);
78
+ });
79
+
80
+ app.get("/webpack-dev-server.js", (req, res) => {
81
+ res.setHeader("Content-Type", "application/javascript");
82
+ fs.createReadStream(path.join(__dirname, "..", "client", "index.bundle.js")).pipe(res);
83
+ });
84
+
85
+ app.get("/webpack-dev-server/*", (req, res) => {
86
+ res.setHeader("Content-Type", "text/html");
87
+ fs.createReadStream(path.join(__dirname, "..", "client", "live.html")).pipe(res);
88
+ });
89
+
90
+ app.get("/webpack-dev-server", (req, res) => {
91
+ res.setHeader("Content-Type", "text/html");
92
+ /* eslint-disable quotes */
93
+ res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>');
94
+ const path = this.middleware.getFilenameFromUrl(options.publicPath || "/");
95
+ const fs = this.middleware.fileSystem;
96
+
97
+ function writeDirectory(baseUrl, basePath) {
98
+ const content = fs.readdirSync(basePath);
99
+ res.write("<ul>");
100
+ content.forEach(function(item) {
101
+ const p = `${basePath}/${item}`;
102
+ if(fs.statSync(p).isFile()) {
103
+ res.write('<li><a href="');
104
+ res.write(baseUrl + item);
105
+ res.write('">');
106
+ res.write(item);
107
+ res.write('</a></li>');
108
+ if(/\.js$/.test(item)) {
109
+ const htmlItem = item.substr(0, item.length - 3);
110
+ res.write('<li><a href="');
111
+ res.write(baseUrl + htmlItem);
112
+ res.write('">');
113
+ res.write(htmlItem);
114
+ res.write('</a> (magic html for ');
115
+ res.write(item);
116
+ res.write(') (<a href="');
117
+ res.write(baseUrl.replace(/(^(https?:\/\/[^\/]+)?\/)/, "$1webpack-dev-server/") + htmlItem);
118
+ res.write('">webpack-dev-server</a>)</li>');
119
+ }
120
+ } else {
121
+ res.write('<li>');
122
+ res.write(item);
123
+ res.write('<br>');
124
+ writeDirectory(`${baseUrl + item}/`, p);
125
+ res.write('</li>');
126
+ }
127
+ });
128
+ res.write("</ul>");
129
+ }
130
+ /* eslint-enable quotes */
131
+ writeDirectory(options.publicPath || "/", path);
132
+ res.end("</body></html>");
133
+ });
134
+
135
+ let contentBase;
136
+ if(options.contentBase !== undefined) {
137
+ contentBase = options.contentBase;
138
+ } else {
139
+ contentBase = process.cwd();
140
+ }
141
+
142
+ // Keep track of websocket proxies for external websocket upgrade.
143
+ const websocketProxies = [];
144
+
145
+ const features = {
146
+ compress() {
147
+ if(options.compress) {
148
+ // Enable gzip compression.
149
+ app.use(compress());
150
+ }
151
+ },
152
+
153
+ proxy() {
154
+ if(options.proxy) {
155
+ /**
156
+ * Assume a proxy configuration specified as:
157
+ * proxy: {
158
+ * 'context': { options }
159
+ * }
160
+ * OR
161
+ * proxy: {
162
+ * 'context': 'target'
163
+ * }
164
+ */
165
+ if(!Array.isArray(options.proxy)) {
166
+ options.proxy = Object.keys(options.proxy).map((context) => {
167
+ let proxyOptions;
168
+ // For backwards compatibility reasons.
169
+ const correctedContext = context.replace(/^\*$/, "**").replace(/\/\*$/, "");
170
+
171
+ if(typeof options.proxy[context] === "string") {
172
+ proxyOptions = {
173
+ context: correctedContext,
174
+ target: options.proxy[context]
175
+ };
176
+ } else {
177
+ proxyOptions = Object.assign({}, options.proxy[context]);
178
+ proxyOptions.context = correctedContext;
179
+ }
180
+ proxyOptions.logLevel = proxyOptions.logLevel || "warn";
181
+
182
+ return proxyOptions;
183
+ });
184
+ }
185
+
186
+ const getProxyMiddleware = (proxyConfig) => {
187
+ const context = proxyConfig.context || proxyConfig.path;
188
+
189
+ // It is possible to use the `bypass` method without a `target`.
190
+ // However, the proxy middleware has no use in this case, and will fail to instantiate.
191
+ if(proxyConfig.target) {
192
+ return httpProxyMiddleware(context, proxyConfig);
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Assume a proxy configuration specified as:
198
+ * proxy: [
199
+ * {
200
+ * context: ...,
201
+ * ...options...
202
+ * },
203
+ * // or:
204
+ * function() {
205
+ * return {
206
+ * context: ...,
207
+ * ...options...
208
+ * };
209
+ * }
210
+ * ]
211
+ */
212
+ options.proxy.forEach((proxyConfigOrCallback) => {
213
+ let proxyConfig;
214
+ let proxyMiddleware;
215
+
216
+ if(typeof proxyConfigOrCallback === "function") {
217
+ proxyConfig = proxyConfigOrCallback();
218
+ } else {
219
+ proxyConfig = proxyConfigOrCallback;
220
+ }
221
+
222
+ proxyMiddleware = getProxyMiddleware(proxyConfig);
223
+ if(proxyConfig.ws) {
224
+ websocketProxies.push(proxyMiddleware);
225
+ }
226
+
227
+ app.use((req, res, next) => {
228
+ if(typeof proxyConfigOrCallback === "function") {
229
+ const newProxyConfig = proxyConfigOrCallback();
230
+ if(newProxyConfig !== proxyConfig) {
231
+ proxyConfig = newProxyConfig;
232
+ proxyMiddleware = getProxyMiddleware(proxyConfig);
233
+ }
234
+ }
235
+ const bypass = typeof proxyConfig.bypass === "function";
236
+ const bypassUrl = bypass && proxyConfig.bypass(req, res, proxyConfig) || false;
237
+
238
+ if(bypassUrl) {
239
+ req.url = bypassUrl;
240
+ next();
241
+ } else if(proxyMiddleware) {
242
+ return proxyMiddleware(req, res, next);
243
+ } else {
244
+ next();
245
+ }
246
+ });
247
+ });
248
+ }
249
+ },
250
+
251
+ historyApiFallback() {
252
+ if(options.historyApiFallback) {
253
+ // Fall back to /index.html if nothing else matches.
254
+ app.use(
255
+ historyApiFallback(typeof options.historyApiFallback === "object" ? options.historyApiFallback : null)
256
+ );
257
+ }
258
+ },
259
+
260
+ contentBaseFiles() {
261
+ if(Array.isArray(contentBase)) {
262
+ contentBase.forEach((item) => {
263
+ app.get("*", express.static(item));
264
+ });
265
+ } else if(/^(https?:)?\/\//.test(contentBase)) {
266
+ console.log("Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.");
267
+ console.log('proxy: {\n\t"*": "<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
268
+ // Redirect every request to contentBase
269
+ app.get("*", (req, res) => {
270
+ res.writeHead(302, {
271
+ "Location": contentBase + req.path + (req._parsedUrl.search || "")
272
+ });
273
+ res.end();
274
+ });
275
+ } else if(typeof contentBase === "number") {
276
+ console.log("Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.");
277
+ console.log('proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
278
+ // Redirect every request to the port contentBase
279
+ app.get("*", (req, res) => {
280
+ res.writeHead(302, {
281
+ "Location": `//localhost:${contentBase}${req.path}${req._parsedUrl.search || ""}`
282
+ });
283
+ res.end();
284
+ });
285
+ } else {
286
+ // route content request
287
+ app.get("*", express.static(contentBase, options.staticOptions));
288
+ }
289
+ },
290
+
291
+ contentBaseIndex() {
292
+ if(Array.isArray(contentBase)) {
293
+ contentBase.forEach((item) => {
294
+ app.get("*", serveIndex(item));
295
+ });
296
+ } else if(!/^(https?:)?\/\//.test(contentBase) && typeof contentBase !== "number") {
297
+ app.get("*", serveIndex(contentBase));
298
+ }
299
+ },
300
+
301
+ watchContentBase: () => {
302
+ if(/^(https?:)?\/\//.test(contentBase) || typeof contentBase === "number") {
303
+ throw new Error("Watching remote files is not supported.");
304
+ } else if(Array.isArray(contentBase)) {
305
+ contentBase.forEach((item) => {
306
+ this._watch(item);
307
+ });
308
+ } else {
309
+ this._watch(contentBase);
310
+ }
311
+ },
312
+
313
+ middleware: () => {
314
+ // include our middleware to ensure it is able to handle '/index.html' request after redirect
315
+ app.use(this.middleware);
316
+ },
317
+
318
+ headers: () => {
319
+ app.all("*", this.setContentHeaders.bind(this));
320
+ },
321
+
322
+ magicHtml: () => {
323
+ app.get("*", this.serveMagicHtml.bind(this));
324
+ },
325
+
326
+ setup: () => {
327
+ if(typeof options.setup === "function")
328
+ options.setup(app, this);
329
+ }
330
+ };
331
+
332
+ const defaultFeatures = ["setup", "headers", "middleware"];
333
+ if(options.proxy)
334
+ defaultFeatures.push("proxy", "middleware");
335
+ if(contentBase !== false)
336
+ defaultFeatures.push("contentBaseFiles");
337
+ if(options.watchContentBase)
338
+ defaultFeatures.push("watchContentBase");
339
+ if(options.historyApiFallback) {
340
+ defaultFeatures.push("historyApiFallback", "middleware");
341
+ if(contentBase !== false)
342
+ defaultFeatures.push("contentBaseFiles");
343
+ }
344
+ defaultFeatures.push("magicHtml");
345
+ if(contentBase !== false)
346
+ defaultFeatures.push("contentBaseIndex");
347
+ // compress is placed last and uses unshift so that it will be the first middleware used
348
+ if(options.compress)
349
+ defaultFeatures.unshift("compress");
350
+
351
+ (options.features || defaultFeatures).forEach((feature) => {
352
+ features[feature]();
353
+ });
354
+
355
+ if(options.https) {
356
+ // for keep supporting CLI parameters
357
+ if(typeof options.https === "boolean") {
358
+ options.https = {
359
+ key: options.key,
360
+ cert: options.cert,
361
+ ca: options.ca,
362
+ pfx: options.pfx,
363
+ passphrase: options.pfxPassphrase
364
+ };
365
+ }
366
+
367
+ // Use a self-signed certificate if no certificate was configured.
368
+ // Cycle certs every 24 hours
369
+ const certPath = path.join(__dirname, "../ssl/server.pem");
370
+ let certExists = fs.existsSync(certPath);
371
+
372
+ if(certExists) {
373
+ const certStat = fs.statSync(certPath);
374
+ const certTtl = 1000 * 60 * 60 * 24;
375
+ const now = new Date();
376
+
377
+ // cert is more than 30 days old, kill it with fire
378
+ if((now - certStat.ctime) / certTtl > 30) {
379
+ console.log("SSL Certificate is more than 30 days old. Removing.");
380
+ del.sync([certPath], { force: true });
381
+ certExists = false;
382
+ }
383
+ }
384
+
385
+ if(!certExists) {
386
+ console.log("Generating SSL Certificate");
387
+ const attrs = [{ name: "commonName", value: "localhost" }];
388
+ const pems = selfsigned.generate(attrs, {
389
+ algorithm: "sha256",
390
+ days: 30,
391
+ keySize: 2048
392
+ });
393
+
394
+ fs.writeFileSync(certPath, pems.private + pems.cert, { encoding: "utf-8" });
395
+ }
396
+
397
+ const fakeCert = fs.readFileSync(certPath);
398
+ options.https.key = options.https.key || fakeCert;
399
+ options.https.cert = options.https.cert || fakeCert;
400
+
401
+ if(!options.https.spdy) {
402
+ options.https.spdy = {
403
+ protocols: ["h2", "http/1.1"]
404
+ };
405
+ }
406
+
407
+ this.listeningApp = spdy.createServer(options.https, app);
408
+ } else {
409
+ this.listeningApp = http.createServer(app);
410
+ }
411
+
412
+ // Proxy websockets without the initial http request
413
+ // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
414
+ websocketProxies.forEach(function(wsProxy) {
415
+ this.listeningApp.on("upgrade", wsProxy.upgrade);
416
+ }, this);
417
+ }
418
+
419
+ Server.prototype.use = function() {
420
+ this.app.use.apply(this.app, arguments);
421
+ }
422
+
423
+ Server.prototype.setContentHeaders = function(req, res, next) {
424
+ if(this.headers) {
425
+ for(const name in this.headers) {
426
+ res.setHeader(name, this.headers[name]);
427
+ }
428
+ }
429
+
430
+ next();
431
+ }
432
+
433
+ Server.prototype.checkHost = function(headers) {
434
+ // allow user to opt-out this security check, at own risk
435
+ if(this.disableHostCheck) return true;
436
+
437
+ // get the Host header and extract hostname
438
+ // we don't care about port not matching
439
+ const hostHeader = headers.host;
440
+ if(!hostHeader) return false;
441
+ const idx = hostHeader.indexOf(":");
442
+ const hostname = idx >= 0 ? hostHeader.substr(0, idx) : hostHeader;
443
+
444
+ // always allow localhost host, for convience
445
+ if(hostname === "127.0.0.1" || hostname === "localhost") return true;
446
+
447
+ // allow if hostname is in allowedHosts
448
+ if(this.allowedHosts && this.allowedHosts.length) {
449
+ for(let hostIdx = 0; hostIdx < this.allowedHosts.length; hostIdx++) {
450
+ const allowedHost = this.allowedHosts[hostIdx];
451
+ if(allowedHost === hostname) return true;
452
+
453
+ // support "." as a subdomain wildcard
454
+ // e.g. ".example.com" will allow "example.com", "www.example.com", "subdomain.example.com", etc
455
+ if(allowedHost[0] === ".") {
456
+ if(hostname === allowedHost.substring(1)) return true; // "example.com"
457
+ if(hostname.endsWith(allowedHost)) return true; // "*.example.com"
458
+ }
459
+ }
460
+ }
461
+
462
+ // allow hostname of listening adress
463
+ if(hostname === this.listenHostname) return true;
464
+
465
+ // also allow public hostname if provided
466
+ if(typeof this.publicHost === "string") {
467
+ const idxPublic = this.publicHost.indexOf(":");
468
+ const publicHostname = idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
469
+ if(hostname === publicHostname) return true;
470
+ }
471
+
472
+ // disallow
473
+ return false;
474
+ }
475
+
476
+ // delegate listen call and init sockjs
477
+ Server.prototype.listen = function(port, hostname) {
478
+ this.listenHostname = hostname;
479
+ const returnValue = this.listeningApp.listen.apply(this.listeningApp, arguments);
480
+ const sockServer = sockjs.createServer({
481
+ // Use provided up-to-date sockjs-client
482
+ sockjs_url: "/__webpack_dev_server__/sockjs.bundle.js",
483
+ // Limit useless logs
484
+ log: function(severity, line) {
485
+ if(severity === "error") {
486
+ console.log(line);
487
+ }
488
+ }
489
+ });
490
+ sockServer.on("connection", (conn) => {
491
+ if(!conn) return;
492
+ if(!this.checkHost(conn.headers)) {
493
+ this.sockWrite([conn], "error", "Invalid Host header");
494
+ conn.close();
495
+ return;
496
+ }
497
+ this.sockets.push(conn);
498
+
499
+ conn.on("close", () => {
500
+ const connIndex = this.sockets.indexOf(conn);
501
+ if(connIndex >= 0) {
502
+ this.sockets.splice(connIndex, 1);
503
+ }
504
+ });
505
+
506
+ if(this.clientLogLevel)
507
+ this.sockWrite([conn], "log-level", this.clientLogLevel);
508
+
509
+ if(this.clientOverlay)
510
+ this.sockWrite([conn], "overlay", this.clientOverlay);
511
+
512
+ if(this.hot) this.sockWrite([conn], "hot");
513
+
514
+ if(!this._stats) return;
515
+ this._sendStats([conn], this._stats.toJson(clientStats), true);
516
+ });
517
+
518
+ sockServer.installHandlers(this.listeningApp, {
519
+ prefix: "/sockjs-node"
520
+ });
521
+ return returnValue;
522
+ }
523
+
524
+ Server.prototype.close = function(callback) {
525
+ this.sockets.forEach((sock) => {
526
+ sock.close();
527
+ });
528
+ this.sockets = [];
529
+ this.listeningApp.close(() => {
530
+ this.middleware.close(callback);
531
+ });
532
+
533
+ this.contentBaseWatchers.forEach((watcher) => {
534
+ watcher.close();
535
+ });
536
+ this.contentBaseWatchers = [];
537
+ }
538
+
539
+ Server.prototype.sockWrite = function(sockets, type, data) {
540
+ sockets.forEach((sock) => {
541
+ sock.write(JSON.stringify({
542
+ type: type,
543
+ data: data
544
+ }));
545
+ });
546
+ }
547
+
548
+ Server.prototype.serveMagicHtml = function(req, res, next) {
549
+ const _path = req.path;
550
+ try {
551
+ if(!this.middleware.fileSystem.statSync(this.middleware.getFilenameFromUrl(`${_path}.js`)).isFile())
552
+ return next();
553
+ // Serve a page that executes the javascript
554
+ /* eslint-disable quotes */
555
+ res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="');
556
+ res.write(_path);
557
+ res.write('.js');
558
+ res.write(req._parsedUrl.search || "");
559
+ res.end('"></script></body></html>');
560
+ /* eslint-enable quotes */
561
+ } catch(e) {
562
+ return next();
563
+ }
564
+ }
565
+
566
+ // send stats to a socket or multiple sockets
567
+ Server.prototype._sendStats = function(sockets, stats, force) {
568
+ if(!force &&
569
+ stats &&
570
+ (!stats.errors || stats.errors.length === 0) &&
571
+ stats.assets &&
572
+ stats.assets.every((asset) => !asset.emitted)
573
+ )
574
+ return this.sockWrite(sockets, "still-ok");
575
+ this.sockWrite(sockets, "hash", stats.hash);
576
+ if(stats.errors.length > 0)
577
+ this.sockWrite(sockets, "errors", stats.errors);
578
+ else if(stats.warnings.length > 0)
579
+ this.sockWrite(sockets, "warnings", stats.warnings);
580
+ else
581
+ this.sockWrite(sockets, "ok");
582
+ }
583
+
584
+ Server.prototype._watch = function(path) {
585
+ const watcher = chokidar.watch(path).on("change", () => {
586
+ this.sockWrite(this.sockets, "content-changed");
587
+ });
588
+
589
+ this.contentBaseWatchers.push(watcher);
590
+ }
591
+
592
+ Server.prototype.invalidate = function() {
593
+ if(this.middleware) this.middleware.invalidate();
594
+ }
595
+
596
+ // Export this logic, so that other implementations, like task-runners can use it
597
+ Server.addDevServerEntrypoints = require("./util/addDevServerEntrypoints");
598
+
599
+ module.exports = Server;