UNPKG

27.8 kBJavaScriptView Raw
1'use strict';
2
3/* eslint-disable
4 import/order,
5 no-shadow,
6 no-undefined,
7 func-names,
8 multiline-ternary,
9 array-bracket-spacing,
10 space-before-function-paren
11*/
12const fs = require('fs');
13const path = require('path');
14
15const ip = require('ip');
16const tls = require('tls');
17const url = require('url');
18const http = require('http');
19const https = require('https');
20const sockjs = require('sockjs');
21
22const semver = require('semver');
23
24const killable = require('killable');
25
26const del = require('del');
27const chokidar = require('chokidar');
28
29const express = require('express');
30
31const compress = require('compression');
32const serveIndex = require('serve-index');
33const httpProxyMiddleware = require('http-proxy-middleware');
34const historyApiFallback = require('connect-history-api-fallback');
35
36const webpack = require('webpack');
37const webpackDevMiddleware = require('webpack-dev-middleware');
38
39const createLogger = require('./utils/createLogger');
40const createCertificate = require('./utils/createCertificate');
41
42const validateOptions = require('schema-utils');
43const schema = require('./options.json');
44
45// Workaround for sockjs@~0.3.19
46// sockjs will remove Origin header, however Origin header is required for checking host.
47// See https://github.com/webpack/webpack-dev-server/issues/1604 for more information
48{
49 // eslint-disable-next-line global-require
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// Workaround for node ^8.6.0, ^9.0.0
66// DEFAULT_ECDH_CURVE is default to prime256v1 in these version
67// breaking connection when certificate is not signed with prime256v1
68// change it to auto allows OpenSSL to select the curve automatically
69// See https://github.com/nodejs/node/issues/16196 for more infomation
70if (semver.satisfies(process.version, '8.6.0 - 9')) {
71 tls.DEFAULT_ECDH_CURVE = 'auto';
72}
73
74const STATS = {
75 all: false,
76 hash: true,
77 assets: true,
78 warnings: true,
79 errors: true,
80 errorDetails: false,
81};
82
83class 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 // Replace leading and trailing slashes to normalize path
109 this.sockPath = `/${
110 options.sockPath
111 ? options.sockPath.replace(/^\/|\/$/g, '')
112 : 'sockjs-node'
113 }`;
114
115 // Listening for events
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 // Init express server
158 // eslint-disable-next-line
159 const app = (this.app = new express());
160
161 // ref: https://github.com/webpack/webpack-dev-server/issues/1575
162 // remove this when send@^0.16.3
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 // middleware for serving webpack bundle
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 // eslint-disable-next-line
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 // Keep track of websocket proxies for external websocket upgrade.
288 const websocketProxies = [];
289
290 const features = {
291 compress: () => {
292 if (options.compress) {
293 // Enable gzip compression.
294 app.use(compress());
295 }
296 },
297 proxy: () => {
298 if (options.proxy) {
299 /**
300 * Assume a proxy configuration specified as:
301 * proxy: {
302 * 'context': { options }
303 * }
304 * OR
305 * proxy: {
306 * 'context': 'target'
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 // For backwards compatibility reasons.
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 // It is possible to use the `bypass` method without a `target`.
340 // However, the proxy middleware has no use in this case, and will fail to instantiate.
341 if (proxyConfig.target) {
342 return httpProxyMiddleware(context, proxyConfig);
343 }
344 };
345 /**
346 * Assume a proxy configuration specified as:
347 * proxy: [
348 * {
349 * context: ...,
350 * ...options...
351 * },
352 * // or:
353 * function() {
354 * return {
355 * context: ...,
356 * ...options...
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 // Fall back to /index.html if nothing else matches.
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 // Redirect every request to contentBase
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 // Redirect every request to the port contentBase
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 // route content request
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?:)?\/\//.test(contentBase) ||
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 // include our middleware to ensure
491 // it is able to handle '/index.html' request after redirect
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 // compress is placed last and uses unshift so that it will be the first middleware used
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 // for keep supporting CLI parameters
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 // Use a self-signed certificate if no certificate was configured.
582 // Cycle certs every 24 hours
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 // cert is more than 30 days old, kill it with fire
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 // `spdy` is effectively unmaintained, and as a consequence of an
630 // implementation that extensively relies on Node’s non-public APIs, broken
631 // on Node 10 and above. In those cases, only https will be used for now.
632 // Once express supports Node's built-in HTTP/2 support, migrating over to
633 // that should be the best way to go.
634 // The relevant issues are:
635 // - https://github.com/nodejs/node/issues/21665
636 // - https://github.com/webpack/webpack-dev-server/issues/1449
637 // - https://github.com/expressjs/express/issues/3388
638 if (semver.gte(process.version, '10.0.0')) {
639 this.listeningApp = https.createServer(options.https, app);
640 } else {
641 /* eslint-disable global-require */
642 // The relevant issues are:
643 // https://github.com/spdy-http2/node-spdy/issues/350
644 // https://github.com/webpack/webpack-dev-server/issues/1592
645 this.listeningApp = require('spdy').createServer(options.https, app);
646 /* eslint-enable global-require */
647 }
648 } else {
649 this.listeningApp = http.createServer(app);
650 }
651
652 killable(this.listeningApp);
653
654 // Proxy websockets without the initial http request
655 // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
656 websocketProxies.forEach(function(wsProxy) {
657 this.listeningApp.on('upgrade', wsProxy.upgrade);
658 }, this);
659 }
660
661 use() {
662 // eslint-disable-next-line
663 this.app.use.apply(this.app, arguments);
664 }
665
666 setContentHeaders(req, res, next) {
667 if (this.headers) {
668 // eslint-disable-next-line
669 for (const name in this.headers) {
670 // eslint-disable-line
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 // allow user to opt-out this security check, at own risk
688 if (this.disableHostCheck) {
689 return true;
690 }
691
692 if (!headerToCheck) headerToCheck = 'host';
693 // get the Host header and extract hostname
694 // we don't care about port not matching
695 const hostHeader = headers[headerToCheck];
696
697 if (!hostHeader) {
698 return false;
699 }
700
701 // use the node url-parser to retrieve the hostname from the host-header.
702 const hostname = url.parse(
703 // if hostHeader doesn't have scheme, add // for parsing.
704 /^(.+:)?\/\//.test(hostHeader) ? hostHeader : `//${hostHeader}`,
705 false,
706 true
707 ).hostname;
708 // always allow requests with explicit IPv4 or IPv6-address.
709 // A note on IPv6 addresses:
710 // hostHeader will always contain the brackets denoting
711 // an IPv6-address in URLs,
712 // these are removed from the hostname in url.parse(),
713 // so we have the pure IPv6-address in hostname.
714 if (ip.isV4Format(hostname) || ip.isV6Format(hostname)) {
715 return true;
716 }
717 // always allow localhost host, for convience
718 if (hostname === 'localhost') {
719 return true;
720 }
721 // allow if hostname is in allowedHosts
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 // support "." as a subdomain wildcard
729 // e.g. ".example.com" will allow "example.com", "www.example.com", "subdomain.example.com", etc
730 if (allowedHost[0] === '.') {
731 // "example.com"
732 if (hostname === allowedHost.substring(1)) {
733 return true;
734 }
735 // "*.example.com"
736 if (hostname.endsWith(allowedHost)) {
737 return true;
738 }
739 }
740 }
741 }
742
743 // allow hostname of listening adress
744 if (hostname === this.hostname) {
745 return true;
746 }
747
748 // also allow public hostname if provided
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 // disallow
761 return false;
762 }
763
764 // delegate listen call and init sockjs
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 // Use provided up-to-date sockjs-client
771 sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
772 // Limit useless logs
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 // eslint-disable-next-line
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 // Serve a page that executes the javascript
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 // send stats to a socket or multiple sockets
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 // duplicate the same massaging of options that watchpack performs
918 // https://github.com/webpack/watchpack/blob/master/lib/DirectoryWatcher.js#L49
919 // this isn't an elegant solution, but we'll improve it in the future
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// Export this logic,
956// so that other implementations,
957// like task-runners can use it
958Server.addDevServerEntrypoints = require('./utils/addEntries');
959
960module.exports = Server;