Server.js 23 KB

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