Server.js 24 KB

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