1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const fs = require('fs');
|
13 | const path = require('path');
|
14 |
|
15 | const ip = require('ip');
|
16 | const tls = require('tls');
|
17 | const url = require('url');
|
18 | const http = require('http');
|
19 | const https = require('https');
|
20 | const sockjs = require('sockjs');
|
21 |
|
22 | const semver = require('semver');
|
23 |
|
24 | const killable = require('killable');
|
25 |
|
26 | const del = require('del');
|
27 | const chokidar = require('chokidar');
|
28 |
|
29 | const express = require('express');
|
30 |
|
31 | const compress = require('compression');
|
32 | const serveIndex = require('serve-index');
|
33 | const httpProxyMiddleware = require('http-proxy-middleware');
|
34 | const historyApiFallback = require('connect-history-api-fallback');
|
35 |
|
36 | const webpack = require('webpack');
|
37 | const webpackDevMiddleware = require('webpack-dev-middleware');
|
38 |
|
39 | const createLogger = require('./utils/createLogger');
|
40 | const createCertificate = require('./utils/createCertificate');
|
41 |
|
42 | const validateOptions = require('schema-utils');
|
43 | const schema = require('./options.json');
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | {
|
49 |
|
50 | const SockjsSession = require('sockjs/lib/transport').Session;
|
51 | const decorateConnection = SockjsSession.prototype.decorateConnection;
|
52 | SockjsSession.prototype.decorateConnection = function(req) {
|
53 | decorateConnection.call(this, req);
|
54 | const connection = this.connection;
|
55 | if (
|
56 | connection.headers &&
|
57 | !('origin' in connection.headers) &&
|
58 | 'origin' in req.headers
|
59 | ) {
|
60 | connection.headers.origin = req.headers.origin;
|
61 | }
|
62 | };
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | if (semver.satisfies(process.version, '8.6.0 - 9')) {
|
71 | tls.DEFAULT_ECDH_CURVE = 'auto';
|
72 | }
|
73 |
|
74 | const STATS = {
|
75 | all: false,
|
76 | hash: true,
|
77 | assets: true,
|
78 | warnings: true,
|
79 | errors: true,
|
80 | errorDetails: false,
|
81 | };
|
82 |
|
83 | class Server {
|
84 | constructor(compiler, options = {}, _log) {
|
85 | this.log = _log || createLogger(options);
|
86 |
|
87 | validateOptions(schema, options, 'webpack Dev Server');
|
88 |
|
89 | if (options.lazy && !options.filename) {
|
90 | throw new Error("'filename' option must be set in lazy mode.");
|
91 | }
|
92 |
|
93 | this.hot = options.hot || options.hotOnly;
|
94 | this.headers = options.headers;
|
95 | this.progress = options.progress;
|
96 |
|
97 | this.clientOverlay = options.overlay;
|
98 | this.clientLogLevel = options.clientLogLevel;
|
99 |
|
100 | this.publicHost = options.public;
|
101 | this.allowedHosts = options.allowedHosts;
|
102 | this.disableHostCheck = !!options.disableHostCheck;
|
103 |
|
104 | this.sockets = [];
|
105 |
|
106 | this.watchOptions = options.watchOptions || {};
|
107 | this.contentBaseWatchers = [];
|
108 |
|
109 | this.sockPath = `/${
|
110 | options.sockPath
|
111 | ? options.sockPath.replace(/^\/|\/$/g, '')
|
112 | : 'sockjs-node'
|
113 | }`;
|
114 |
|
115 |
|
116 | const invalidPlugin = () => {
|
117 | this.sockWrite(this.sockets, 'invalid');
|
118 | };
|
119 |
|
120 | if (this.progress) {
|
121 | const progressPlugin = new webpack.ProgressPlugin(
|
122 | (percent, msg, addInfo) => {
|
123 | percent = Math.floor(percent * 100);
|
124 |
|
125 | if (percent === 100) {
|
126 | msg = 'Compilation completed';
|
127 | }
|
128 |
|
129 | if (addInfo) {
|
130 | msg = `${msg} (${addInfo})`;
|
131 | }
|
132 |
|
133 | this.sockWrite(this.sockets, 'progress-update', { percent, msg });
|
134 | }
|
135 | );
|
136 |
|
137 | progressPlugin.apply(compiler);
|
138 | }
|
139 |
|
140 | const addHooks = (compiler) => {
|
141 | const { compile, invalid, done } = compiler.hooks;
|
142 |
|
143 | compile.tap('webpack-dev-server', invalidPlugin);
|
144 | invalid.tap('webpack-dev-server', invalidPlugin);
|
145 | done.tap('webpack-dev-server', (stats) => {
|
146 | this._sendStats(this.sockets, stats.toJson(STATS));
|
147 | this._stats = stats;
|
148 | });
|
149 | };
|
150 |
|
151 | if (compiler.compilers) {
|
152 | compiler.compilers.forEach(addHooks);
|
153 | } else {
|
154 | addHooks(compiler);
|
155 | }
|
156 |
|
157 |
|
158 |
|
159 | const app = (this.app = new express());
|
160 |
|
161 |
|
162 |
|
163 | express.static.mime.types.wasm = 'application/wasm';
|
164 |
|
165 | app.all('*', (req, res, next) => {
|
166 | if (this.checkHost(req.headers)) {
|
167 | return next();
|
168 | }
|
169 |
|
170 | res.send('Invalid Host header');
|
171 | });
|
172 |
|
173 | const wdmOptions = { logLevel: this.log.options.level };
|
174 |
|
175 |
|
176 | this.middleware = webpackDevMiddleware(
|
177 | compiler,
|
178 | Object.assign({}, options, wdmOptions)
|
179 | );
|
180 |
|
181 | app.get('/__webpack_dev_server__/live.bundle.js', (req, res) => {
|
182 | res.setHeader('Content-Type', 'application/javascript');
|
183 |
|
184 | fs.createReadStream(
|
185 | path.join(__dirname, '..', 'client', 'live.bundle.js')
|
186 | ).pipe(res);
|
187 | });
|
188 |
|
189 | app.get('/__webpack_dev_server__/sockjs.bundle.js', (req, res) => {
|
190 | res.setHeader('Content-Type', 'application/javascript');
|
191 |
|
192 | fs.createReadStream(
|
193 | path.join(__dirname, '..', 'client', 'sockjs.bundle.js')
|
194 | ).pipe(res);
|
195 | });
|
196 |
|
197 | app.get('/webpack-dev-server.js', (req, res) => {
|
198 | res.setHeader('Content-Type', 'application/javascript');
|
199 |
|
200 | fs.createReadStream(
|
201 | path.join(__dirname, '..', 'client', 'index.bundle.js')
|
202 | ).pipe(res);
|
203 | });
|
204 |
|
205 | app.get('/webpack-dev-server/*', (req, res) => {
|
206 | res.setHeader('Content-Type', 'text/html');
|
207 |
|
208 | fs.createReadStream(
|
209 | path.join(__dirname, '..', 'client', 'live.html')
|
210 | ).pipe(res);
|
211 | });
|
212 |
|
213 | app.get('/webpack-dev-server', (req, res) => {
|
214 | res.setHeader('Content-Type', 'text/html');
|
215 |
|
216 | res.write(
|
217 | '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>'
|
218 | );
|
219 |
|
220 | const outputPath = this.middleware.getFilenameFromUrl(
|
221 | options.publicPath || '/'
|
222 | );
|
223 |
|
224 | const filesystem = this.middleware.fileSystem;
|
225 |
|
226 | function writeDirectory(baseUrl, basePath) {
|
227 | const content = filesystem.readdirSync(basePath);
|
228 |
|
229 | res.write('<ul>');
|
230 |
|
231 | content.forEach((item) => {
|
232 | const p = `${basePath}/${item}`;
|
233 |
|
234 | if (filesystem.statSync(p).isFile()) {
|
235 | res.write('<li><a href="');
|
236 | res.write(baseUrl + item);
|
237 | res.write('">');
|
238 | res.write(item);
|
239 | res.write('</a></li>');
|
240 |
|
241 | if (/\.js$/.test(item)) {
|
242 | const html = item.substr(0, item.length - 3);
|
243 |
|
244 | res.write('<li><a href="');
|
245 | res.write(baseUrl + html);
|
246 | res.write('">');
|
247 | res.write(html);
|
248 | res.write('</a> (magic html for ');
|
249 | res.write(item);
|
250 | res.write(') (<a href="');
|
251 | res.write(
|
252 | baseUrl.replace(
|
253 |
|
254 | /(^(https?:\/\/[^\/]+)?\/)/,
|
255 | '$1webpack-dev-server/'
|
256 | ) + html
|
257 | );
|
258 | res.write('">webpack-dev-server</a>)</li>');
|
259 | }
|
260 | } else {
|
261 | res.write('<li>');
|
262 | res.write(item);
|
263 | res.write('<br>');
|
264 |
|
265 | writeDirectory(`${baseUrl + item}/`, p);
|
266 |
|
267 | res.write('</li>');
|
268 | }
|
269 | });
|
270 |
|
271 | res.write('</ul>');
|
272 | }
|
273 |
|
274 | writeDirectory(options.publicPath || '/', outputPath);
|
275 |
|
276 | res.end('</body></html>');
|
277 | });
|
278 |
|
279 | let contentBase;
|
280 |
|
281 | if (options.contentBase !== undefined) {
|
282 | contentBase = options.contentBase;
|
283 | } else {
|
284 | contentBase = process.cwd();
|
285 | }
|
286 |
|
287 |
|
288 | const websocketProxies = [];
|
289 |
|
290 | const features = {
|
291 | compress: () => {
|
292 | if (options.compress) {
|
293 |
|
294 | app.use(compress());
|
295 | }
|
296 | },
|
297 | proxy: () => {
|
298 | if (options.proxy) {
|
299 | |
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 | if (!Array.isArray(options.proxy)) {
|
310 | if (Object.prototype.hasOwnProperty.call(options.proxy, 'target')) {
|
311 | options.proxy = [options.proxy];
|
312 | } else {
|
313 | options.proxy = Object.keys(options.proxy).map((context) => {
|
314 | let proxyOptions;
|
315 |
|
316 | const correctedContext = context
|
317 | .replace(/^\*$/, '**')
|
318 | .replace(/\/\*$/, '');
|
319 |
|
320 | if (typeof options.proxy[context] === 'string') {
|
321 | proxyOptions = {
|
322 | context: correctedContext,
|
323 | target: options.proxy[context],
|
324 | };
|
325 | } else {
|
326 | proxyOptions = Object.assign({}, options.proxy[context]);
|
327 | proxyOptions.context = correctedContext;
|
328 | }
|
329 |
|
330 | proxyOptions.logLevel = proxyOptions.logLevel || 'warn';
|
331 |
|
332 | return proxyOptions;
|
333 | });
|
334 | }
|
335 | }
|
336 |
|
337 | const getProxyMiddleware = (proxyConfig) => {
|
338 | const context = proxyConfig.context || proxyConfig.path;
|
339 |
|
340 |
|
341 | if (proxyConfig.target) {
|
342 | return httpProxyMiddleware(context, proxyConfig);
|
343 | }
|
344 | };
|
345 | |
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 | options.proxy.forEach((proxyConfigOrCallback) => {
|
362 | let proxyConfig;
|
363 | let proxyMiddleware;
|
364 |
|
365 | if (typeof proxyConfigOrCallback === 'function') {
|
366 | proxyConfig = proxyConfigOrCallback();
|
367 | } else {
|
368 | proxyConfig = proxyConfigOrCallback;
|
369 | }
|
370 |
|
371 | proxyMiddleware = getProxyMiddleware(proxyConfig);
|
372 |
|
373 | if (proxyConfig.ws) {
|
374 | websocketProxies.push(proxyMiddleware);
|
375 | }
|
376 |
|
377 | app.use((req, res, next) => {
|
378 | if (typeof proxyConfigOrCallback === 'function') {
|
379 | const newProxyConfig = proxyConfigOrCallback();
|
380 |
|
381 | if (newProxyConfig !== proxyConfig) {
|
382 | proxyConfig = newProxyConfig;
|
383 | proxyMiddleware = getProxyMiddleware(proxyConfig);
|
384 | }
|
385 | }
|
386 |
|
387 | const bypass = typeof proxyConfig.bypass === 'function';
|
388 |
|
389 | const bypassUrl =
|
390 | (bypass && proxyConfig.bypass(req, res, proxyConfig)) || false;
|
391 |
|
392 | if (bypassUrl) {
|
393 | req.url = bypassUrl;
|
394 |
|
395 | next();
|
396 | } else if (proxyMiddleware) {
|
397 | return proxyMiddleware(req, res, next);
|
398 | } else {
|
399 | next();
|
400 | }
|
401 | });
|
402 | });
|
403 | }
|
404 | },
|
405 | historyApiFallback: () => {
|
406 | if (options.historyApiFallback) {
|
407 | const fallback =
|
408 | typeof options.historyApiFallback === 'object'
|
409 | ? options.historyApiFallback
|
410 | : null;
|
411 |
|
412 | app.use(historyApiFallback(fallback));
|
413 | }
|
414 | },
|
415 | contentBaseFiles: () => {
|
416 | if (Array.isArray(contentBase)) {
|
417 | contentBase.forEach((item) => {
|
418 | app.get('*', express.static(item));
|
419 | });
|
420 | } else if (/^(https?:)?\/\//.test(contentBase)) {
|
421 | this.log.warn(
|
422 | 'Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
|
423 | );
|
424 |
|
425 | this.log.warn(
|
426 | 'proxy: {\n\t"*": "<your current contentBase configuration>"\n}'
|
427 | );
|
428 |
|
429 | app.get('*', (req, res) => {
|
430 | res.writeHead(302, {
|
431 | Location: contentBase + req.path + (req._parsedUrl.search || ''),
|
432 | });
|
433 |
|
434 | res.end();
|
435 | });
|
436 | } else if (typeof contentBase === 'number') {
|
437 | this.log.warn(
|
438 | 'Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
|
439 | );
|
440 |
|
441 | this.log.warn(
|
442 | 'proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'
|
443 | );
|
444 |
|
445 | app.get('*', (req, res) => {
|
446 | res.writeHead(302, {
|
447 | Location: `//localhost:${contentBase}${req.path}${req._parsedUrl
|
448 | .search || ''}`,
|
449 | });
|
450 |
|
451 | res.end();
|
452 | });
|
453 | } else {
|
454 |
|
455 | app.get('*', express.static(contentBase, options.staticOptions));
|
456 | }
|
457 | },
|
458 | contentBaseIndex: () => {
|
459 | if (Array.isArray(contentBase)) {
|
460 | contentBase.forEach((item) => {
|
461 | app.get('*', serveIndex(item));
|
462 | });
|
463 | } else if (
|
464 | !/^(https?:)?\/\//.test(contentBase) &&
|
465 | typeof contentBase !== 'number'
|
466 | ) {
|
467 | app.get('*', serveIndex(contentBase));
|
468 | }
|
469 | },
|
470 | watchContentBase: () => {
|
471 | if (
|
472 | /^(https?:)?\/\
|
473 | typeof contentBase === 'number'
|
474 | ) {
|
475 | throw new Error('Watching remote files is not supported.');
|
476 | } else if (Array.isArray(contentBase)) {
|
477 | contentBase.forEach((item) => {
|
478 | this._watch(item);
|
479 | });
|
480 | } else {
|
481 | this._watch(contentBase);
|
482 | }
|
483 | },
|
484 | before: () => {
|
485 | if (typeof options.before === 'function') {
|
486 | options.before(app, this);
|
487 | }
|
488 | },
|
489 | middleware: () => {
|
490 |
|
491 |
|
492 | app.use(this.middleware);
|
493 | },
|
494 | after: () => {
|
495 | if (typeof options.after === 'function') {
|
496 | options.after(app, this);
|
497 | }
|
498 | },
|
499 | headers: () => {
|
500 | app.all('*', this.setContentHeaders.bind(this));
|
501 | },
|
502 | magicHtml: () => {
|
503 | app.get('*', this.serveMagicHtml.bind(this));
|
504 | },
|
505 | setup: () => {
|
506 | if (typeof options.setup === 'function') {
|
507 | this.log.warn(
|
508 | 'The `setup` option is deprecated and will be removed in v3. Please update your config to use `before`'
|
509 | );
|
510 |
|
511 | options.setup(app, this);
|
512 | }
|
513 | },
|
514 | };
|
515 |
|
516 | const defaultFeatures = ['setup', 'before', 'headers', 'middleware'];
|
517 |
|
518 | if (options.proxy) {
|
519 | defaultFeatures.push('proxy', 'middleware');
|
520 | }
|
521 |
|
522 | if (contentBase !== false) {
|
523 | defaultFeatures.push('contentBaseFiles');
|
524 | }
|
525 |
|
526 | if (options.watchContentBase) {
|
527 | defaultFeatures.push('watchContentBase');
|
528 | }
|
529 |
|
530 | if (options.historyApiFallback) {
|
531 | defaultFeatures.push('historyApiFallback', 'middleware');
|
532 |
|
533 | if (contentBase !== false) {
|
534 | defaultFeatures.push('contentBaseFiles');
|
535 | }
|
536 | }
|
537 |
|
538 | defaultFeatures.push('magicHtml');
|
539 |
|
540 | if (contentBase !== false) {
|
541 | defaultFeatures.push('contentBaseIndex');
|
542 | }
|
543 |
|
544 | if (options.compress) {
|
545 | defaultFeatures.unshift('compress');
|
546 | }
|
547 |
|
548 | if (options.after) {
|
549 | defaultFeatures.push('after');
|
550 | }
|
551 |
|
552 | (options.features || defaultFeatures).forEach((feature) => {
|
553 | features[feature]();
|
554 | });
|
555 |
|
556 | if (options.https) {
|
557 |
|
558 | if (typeof options.https === 'boolean') {
|
559 | options.https = {
|
560 | ca: options.ca,
|
561 | pfx: options.pfx,
|
562 | key: options.key,
|
563 | cert: options.cert,
|
564 | passphrase: options.pfxPassphrase,
|
565 | requestCert: options.requestCert || false,
|
566 | };
|
567 | }
|
568 |
|
569 | for (const property of ['ca', 'pfx', 'key', 'cert']) {
|
570 | const value = options.https[property];
|
571 | const isBuffer = value instanceof Buffer;
|
572 |
|
573 | if (value && !isBuffer && fs.lstatSync(value).isFile()) {
|
574 | options.https[property] = fs.readFileSync(path.resolve(value));
|
575 | }
|
576 | }
|
577 |
|
578 | let fakeCert;
|
579 |
|
580 | if (!options.https.key || !options.https.cert) {
|
581 |
|
582 |
|
583 | const certPath = path.join(__dirname, '../ssl/server.pem');
|
584 |
|
585 | let certExists = fs.existsSync(certPath);
|
586 |
|
587 | if (certExists) {
|
588 | const certTtl = 1000 * 60 * 60 * 24;
|
589 | const certStat = fs.statSync(certPath);
|
590 |
|
591 | const now = new Date();
|
592 |
|
593 |
|
594 | if ((now - certStat.ctime) / certTtl > 30) {
|
595 | this.log.info(
|
596 | 'SSL Certificate is more than 30 days old. Removing.'
|
597 | );
|
598 |
|
599 | del.sync([certPath], { force: true });
|
600 |
|
601 | certExists = false;
|
602 | }
|
603 | }
|
604 |
|
605 | if (!certExists) {
|
606 | this.log.info('Generating SSL Certificate');
|
607 |
|
608 | const attrs = [{ name: 'commonName', value: 'localhost' }];
|
609 |
|
610 | const pems = createCertificate(attrs);
|
611 |
|
612 | fs.writeFileSync(certPath, pems.private + pems.cert, {
|
613 | encoding: 'utf-8',
|
614 | });
|
615 | }
|
616 |
|
617 | fakeCert = fs.readFileSync(certPath);
|
618 | }
|
619 |
|
620 | options.https.key = options.https.key || fakeCert;
|
621 | options.https.cert = options.https.cert || fakeCert;
|
622 |
|
623 | if (!options.https.spdy) {
|
624 | options.https.spdy = {
|
625 | protocols: ['h2', 'http/1.1'],
|
626 | };
|
627 | }
|
628 |
|
629 |
|
630 |
|
631 |
|
632 |
|
633 |
|
634 |
|
635 |
|
636 |
|
637 |
|
638 | if (semver.gte(process.version, '10.0.0')) {
|
639 | this.listeningApp = https.createServer(options.https, app);
|
640 | } else {
|
641 |
|
642 |
|
643 |
|
644 |
|
645 | this.listeningApp = require('spdy').createServer(options.https, app);
|
646 |
|
647 | }
|
648 | } else {
|
649 | this.listeningApp = http.createServer(app);
|
650 | }
|
651 |
|
652 | killable(this.listeningApp);
|
653 |
|
654 |
|
655 |
|
656 | websocketProxies.forEach(function(wsProxy) {
|
657 | this.listeningApp.on('upgrade', wsProxy.upgrade);
|
658 | }, this);
|
659 | }
|
660 |
|
661 | use() {
|
662 |
|
663 | this.app.use.apply(this.app, arguments);
|
664 | }
|
665 |
|
666 | setContentHeaders(req, res, next) {
|
667 | if (this.headers) {
|
668 |
|
669 | for (const name in this.headers) {
|
670 |
|
671 | res.setHeader(name, this.headers[name]);
|
672 | }
|
673 | }
|
674 |
|
675 | next();
|
676 | }
|
677 |
|
678 | checkHost(headers) {
|
679 | return this.checkHeaders(headers, 'host');
|
680 | }
|
681 |
|
682 | checkOrigin(headers) {
|
683 | return this.checkHeaders(headers, 'origin');
|
684 | }
|
685 |
|
686 | checkHeaders(headers, headerToCheck) {
|
687 |
|
688 | if (this.disableHostCheck) {
|
689 | return true;
|
690 | }
|
691 |
|
692 | if (!headerToCheck) headerToCheck = 'host';
|
693 |
|
694 |
|
695 | const hostHeader = headers[headerToCheck];
|
696 |
|
697 | if (!hostHeader) {
|
698 | return false;
|
699 | }
|
700 |
|
701 |
|
702 | const hostname = url.parse(
|
703 |
|
704 | /^(.+:)?\/\
|
705 | false,
|
706 | true
|
707 | ).hostname;
|
708 |
|
709 |
|
710 |
|
711 |
|
712 |
|
713 |
|
714 | if (ip.isV4Format(hostname) || ip.isV6Format(hostname)) {
|
715 | return true;
|
716 | }
|
717 |
|
718 | if (hostname === 'localhost') {
|
719 | return true;
|
720 | }
|
721 |
|
722 | if (this.allowedHosts && this.allowedHosts.length) {
|
723 | for (let hostIdx = 0; hostIdx < this.allowedHosts.length; hostIdx++) {
|
724 | const allowedHost = this.allowedHosts[hostIdx];
|
725 |
|
726 | if (allowedHost === hostname) return true;
|
727 |
|
728 |
|
729 |
|
730 | if (allowedHost[0] === '.') {
|
731 |
|
732 | if (hostname === allowedHost.substring(1)) {
|
733 | return true;
|
734 | }
|
735 |
|
736 | if (hostname.endsWith(allowedHost)) {
|
737 | return true;
|
738 | }
|
739 | }
|
740 | }
|
741 | }
|
742 |
|
743 |
|
744 | if (hostname === this.hostname) {
|
745 | return true;
|
746 | }
|
747 |
|
748 |
|
749 | if (typeof this.publicHost === 'string') {
|
750 | const idxPublic = this.publicHost.indexOf(':');
|
751 |
|
752 | const publicHostname =
|
753 | idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
|
754 |
|
755 | if (hostname === publicHostname) {
|
756 | return true;
|
757 | }
|
758 | }
|
759 |
|
760 |
|
761 | return false;
|
762 | }
|
763 |
|
764 |
|
765 | listen(port, hostname, fn) {
|
766 | this.hostname = hostname;
|
767 |
|
768 | const returnValue = this.listeningApp.listen(port, hostname, (err) => {
|
769 | const socket = sockjs.createServer({
|
770 |
|
771 | sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
|
772 |
|
773 | log: (severity, line) => {
|
774 | if (severity === 'error') {
|
775 | this.log.error(line);
|
776 | } else {
|
777 | this.log.debug(line);
|
778 | }
|
779 | },
|
780 | });
|
781 |
|
782 | socket.on('connection', (connection) => {
|
783 | if (!connection) {
|
784 | return;
|
785 | }
|
786 |
|
787 | if (
|
788 | !this.checkHost(connection.headers) ||
|
789 | !this.checkOrigin(connection.headers)
|
790 | ) {
|
791 | this.sockWrite([connection], 'error', 'Invalid Host/Origin header');
|
792 |
|
793 | connection.close();
|
794 |
|
795 | return;
|
796 | }
|
797 |
|
798 | this.sockets.push(connection);
|
799 |
|
800 | connection.on('close', () => {
|
801 | const idx = this.sockets.indexOf(connection);
|
802 |
|
803 | if (idx >= 0) {
|
804 | this.sockets.splice(idx, 1);
|
805 | }
|
806 | });
|
807 |
|
808 | if (this.hot) {
|
809 | this.sockWrite([connection], 'hot');
|
810 | }
|
811 |
|
812 | if (this.progress) {
|
813 | this.sockWrite([connection], 'progress', this.progress);
|
814 | }
|
815 |
|
816 | if (this.clientOverlay) {
|
817 | this.sockWrite([connection], 'overlay', this.clientOverlay);
|
818 | }
|
819 |
|
820 | if (this.clientLogLevel) {
|
821 | this.sockWrite([connection], 'log-level', this.clientLogLevel);
|
822 | }
|
823 |
|
824 | if (!this._stats) {
|
825 | return;
|
826 | }
|
827 |
|
828 | this._sendStats([connection], this._stats.toJson(STATS), true);
|
829 | });
|
830 |
|
831 | socket.installHandlers(this.listeningApp, {
|
832 | prefix: this.sockPath,
|
833 | });
|
834 |
|
835 | if (fn) {
|
836 | fn.call(this.listeningApp, err);
|
837 | }
|
838 | });
|
839 |
|
840 | return returnValue;
|
841 | }
|
842 |
|
843 | close(cb) {
|
844 | this.sockets.forEach((socket) => {
|
845 | socket.close();
|
846 | });
|
847 |
|
848 | this.sockets = [];
|
849 |
|
850 | this.contentBaseWatchers.forEach((watcher) => {
|
851 | watcher.close();
|
852 | });
|
853 |
|
854 | this.contentBaseWatchers = [];
|
855 |
|
856 | this.listeningApp.kill(() => {
|
857 | this.middleware.close(cb);
|
858 | });
|
859 | }
|
860 |
|
861 |
|
862 | sockWrite(sockets, type, data) {
|
863 | sockets.forEach((socket) => {
|
864 | socket.write(JSON.stringify({ type, data }));
|
865 | });
|
866 | }
|
867 |
|
868 | serveMagicHtml(req, res, next) {
|
869 | const _path = req.path;
|
870 |
|
871 | try {
|
872 | const isFile = this.middleware.fileSystem
|
873 | .statSync(this.middleware.getFilenameFromUrl(`${_path}.js`))
|
874 | .isFile();
|
875 |
|
876 | if (!isFile) {
|
877 | return next();
|
878 | }
|
879 |
|
880 | res.write(
|
881 | '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="'
|
882 | );
|
883 | res.write(_path);
|
884 | res.write('.js');
|
885 | res.write(req._parsedUrl.search || '');
|
886 |
|
887 | res.end('"></script></body></html>');
|
888 | } catch (err) {
|
889 | return next();
|
890 | }
|
891 | }
|
892 |
|
893 |
|
894 | _sendStats(sockets, stats, force) {
|
895 | if (
|
896 | !force &&
|
897 | stats &&
|
898 | (!stats.errors || stats.errors.length === 0) &&
|
899 | stats.assets &&
|
900 | stats.assets.every((asset) => !asset.emitted)
|
901 | ) {
|
902 | return this.sockWrite(sockets, 'still-ok');
|
903 | }
|
904 |
|
905 | this.sockWrite(sockets, 'hash', stats.hash);
|
906 |
|
907 | if (stats.errors.length > 0) {
|
908 | this.sockWrite(sockets, 'errors', stats.errors);
|
909 | } else if (stats.warnings.length > 0) {
|
910 | this.sockWrite(sockets, 'warnings', stats.warnings);
|
911 | } else {
|
912 | this.sockWrite(sockets, 'ok');
|
913 | }
|
914 | }
|
915 |
|
916 | _watch(watchPath) {
|
917 |
|
918 |
|
919 |
|
920 | const usePolling = this.watchOptions.poll ? true : undefined;
|
921 | const interval =
|
922 | typeof this.watchOptions.poll === 'number'
|
923 | ? this.watchOptions.poll
|
924 | : undefined;
|
925 |
|
926 | const options = {
|
927 | ignoreInitial: true,
|
928 | persistent: true,
|
929 | followSymlinks: false,
|
930 | depth: 0,
|
931 | atomic: false,
|
932 | alwaysStat: true,
|
933 | ignorePermissionErrors: true,
|
934 | ignored: this.watchOptions.ignored,
|
935 | usePolling,
|
936 | interval,
|
937 | };
|
938 |
|
939 | const watcher = chokidar.watch(watchPath, options);
|
940 |
|
941 | watcher.on('change', () => {
|
942 | this.sockWrite(this.sockets, 'content-changed');
|
943 | });
|
944 |
|
945 | this.contentBaseWatchers.push(watcher);
|
946 | }
|
947 |
|
948 | invalidate() {
|
949 | if (this.middleware) {
|
950 | this.middleware.invalidate();
|
951 | }
|
952 | }
|
953 | }
|
954 |
|
955 |
|
956 |
|
957 |
|
958 | Server.addDevServerEntrypoints = require('./utils/addEntries');
|
959 |
|
960 | module.exports = Server;
|