Server.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. 'use strict';
  2. /* eslint-disable
  3. no-shadow,
  4. no-undefined,
  5. func-names
  6. */
  7. const fs = require('fs');
  8. const path = require('path');
  9. const tls = require('tls');
  10. const url = require('url');
  11. const http = require('http');
  12. const https = require('https');
  13. const ip = require('ip');
  14. const semver = require('semver');
  15. const killable = require('killable');
  16. const chokidar = require('chokidar');
  17. const express = require('express');
  18. const httpProxyMiddleware = require('http-proxy-middleware');
  19. const historyApiFallback = require('connect-history-api-fallback');
  20. const compress = require('compression');
  21. const serveIndex = require('serve-index');
  22. const webpack = require('webpack');
  23. const webpackDevMiddleware = require('webpack-dev-middleware');
  24. const validateOptions = require('schema-utils');
  25. const updateCompiler = require('./utils/updateCompiler');
  26. const createLogger = require('./utils/createLogger');
  27. const getCertificate = require('./utils/getCertificate');
  28. const status = require('./utils/status');
  29. const createDomain = require('./utils/createDomain');
  30. const runBonjour = require('./utils/runBonjour');
  31. const routes = require('./utils/routes');
  32. const getSocketServerImplementation = require('./utils/getSocketServerImplementation');
  33. const schema = require('./options.json');
  34. // Workaround for node ^8.6.0, ^9.0.0
  35. // DEFAULT_ECDH_CURVE is default to prime256v1 in these version
  36. // breaking connection when certificate is not signed with prime256v1
  37. // change it to auto allows OpenSSL to select the curve automatically
  38. // See https://github.com/nodejs/node/issues/16196 for more information
  39. if (semver.satisfies(process.version, '8.6.0 - 9')) {
  40. tls.DEFAULT_ECDH_CURVE = 'auto';
  41. }
  42. if (!process.env.WEBPACK_DEV_SERVER) {
  43. process.env.WEBPACK_DEV_SERVER = true;
  44. }
  45. class Server {
  46. constructor(compiler, options = {}, _log) {
  47. if (options.lazy && !options.filename) {
  48. throw new Error("'filename' option must be set in lazy mode.");
  49. }
  50. validateOptions(schema, options, 'webpack Dev Server');
  51. updateCompiler(compiler, options);
  52. this.compiler = compiler;
  53. this.options = options;
  54. // Setup default value
  55. this.options.contentBase =
  56. this.options.contentBase !== undefined
  57. ? this.options.contentBase
  58. : process.cwd();
  59. this.log = _log || createLogger(options);
  60. if (this.options.serverMode === undefined) {
  61. this.options.serverMode = 'sockjs';
  62. } else {
  63. this.log.warn(
  64. 'serverMode is an experimental option, meaning its usage could potentially change without warning'
  65. );
  66. }
  67. // this.SocketServerImplementation is a class, so it must be instantiated before use
  68. this.socketServerImplementation = getSocketServerImplementation(
  69. this.options
  70. );
  71. this.originalStats =
  72. this.options.stats && Object.keys(this.options.stats).length
  73. ? this.options.stats
  74. : {};
  75. this.sockets = [];
  76. this.contentBaseWatchers = [];
  77. // TODO this.<property> is deprecated (remove them in next major release.) in favor this.options.<property>
  78. this.hot = this.options.hot || this.options.hotOnly;
  79. this.headers = this.options.headers;
  80. this.progress = this.options.progress;
  81. this.serveIndex = this.options.serveIndex;
  82. this.clientOverlay = this.options.overlay;
  83. this.clientLogLevel = this.options.clientLogLevel;
  84. this.publicHost = this.options.public;
  85. this.allowedHosts = this.options.allowedHosts;
  86. this.disableHostCheck = !!this.options.disableHostCheck;
  87. if (!this.options.watchOptions) {
  88. this.options.watchOptions = {};
  89. }
  90. this.watchOptions = options.watchOptions || {};
  91. // Replace leading and trailing slashes to normalize path
  92. this.sockPath = `/${
  93. this.options.sockPath
  94. ? this.options.sockPath.replace(/^\/|\/$/g, '')
  95. : 'sockjs-node'
  96. }`;
  97. if (this.progress) {
  98. this.setupProgressPlugin();
  99. }
  100. this.setupHooks();
  101. this.setupApp();
  102. this.setupCheckHostRoute();
  103. this.setupDevMiddleware();
  104. // set express routes
  105. routes(this.app, this.middleware, this.options);
  106. // Keep track of websocket proxies for external websocket upgrade.
  107. this.websocketProxies = [];
  108. this.setupFeatures();
  109. this.setupHttps();
  110. this.createServer();
  111. killable(this.listeningApp);
  112. // Proxy websockets without the initial http request
  113. // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
  114. this.websocketProxies.forEach(function(wsProxy) {
  115. this.listeningApp.on('upgrade', wsProxy.upgrade);
  116. }, this);
  117. }
  118. setupProgressPlugin() {
  119. const progressPlugin = new webpack.ProgressPlugin(
  120. (percent, msg, addInfo) => {
  121. percent = Math.floor(percent * 100);
  122. if (percent === 100) {
  123. msg = 'Compilation completed';
  124. }
  125. if (addInfo) {
  126. msg = `${msg} (${addInfo})`;
  127. }
  128. this.sockWrite(this.sockets, 'progress-update', { percent, msg });
  129. }
  130. );
  131. progressPlugin.apply(this.compiler);
  132. }
  133. setupApp() {
  134. // Init express server
  135. // eslint-disable-next-line new-cap
  136. this.app = new express();
  137. }
  138. setupHooks() {
  139. // Listening for events
  140. const invalidPlugin = () => {
  141. this.sockWrite(this.sockets, 'invalid');
  142. };
  143. const addHooks = (compiler) => {
  144. const { compile, invalid, done } = compiler.hooks;
  145. compile.tap('webpack-dev-server', invalidPlugin);
  146. invalid.tap('webpack-dev-server', invalidPlugin);
  147. done.tap('webpack-dev-server', (stats) => {
  148. this._sendStats(this.sockets, this.getStats(stats));
  149. this._stats = stats;
  150. });
  151. };
  152. if (this.compiler.compilers) {
  153. this.compiler.compilers.forEach(addHooks);
  154. } else {
  155. addHooks(this.compiler);
  156. }
  157. }
  158. setupCheckHostRoute() {
  159. this.app.all('*', (req, res, next) => {
  160. if (this.checkHost(req.headers)) {
  161. return next();
  162. }
  163. res.send('Invalid Host header');
  164. });
  165. }
  166. setupDevMiddleware() {
  167. // middleware for serving webpack bundle
  168. this.middleware = webpackDevMiddleware(
  169. this.compiler,
  170. Object.assign({}, this.options, { logLevel: this.log.options.level })
  171. );
  172. }
  173. setupCompressFeature() {
  174. this.app.use(compress());
  175. }
  176. setupProxyFeature() {
  177. /**
  178. * Assume a proxy configuration specified as:
  179. * proxy: {
  180. * 'context': { options }
  181. * }
  182. * OR
  183. * proxy: {
  184. * 'context': 'target'
  185. * }
  186. */
  187. if (!Array.isArray(this.options.proxy)) {
  188. if (Object.prototype.hasOwnProperty.call(this.options.proxy, 'target')) {
  189. this.options.proxy = [this.options.proxy];
  190. } else {
  191. this.options.proxy = Object.keys(this.options.proxy).map((context) => {
  192. let proxyOptions;
  193. // For backwards compatibility reasons.
  194. const correctedContext = context
  195. .replace(/^\*$/, '**')
  196. .replace(/\/\*$/, '');
  197. if (typeof this.options.proxy[context] === 'string') {
  198. proxyOptions = {
  199. context: correctedContext,
  200. target: this.options.proxy[context],
  201. };
  202. } else {
  203. proxyOptions = Object.assign({}, this.options.proxy[context]);
  204. proxyOptions.context = correctedContext;
  205. }
  206. proxyOptions.logLevel = proxyOptions.logLevel || 'warn';
  207. return proxyOptions;
  208. });
  209. }
  210. }
  211. const getProxyMiddleware = (proxyConfig) => {
  212. const context = proxyConfig.context || proxyConfig.path;
  213. // It is possible to use the `bypass` method without a `target`.
  214. // However, the proxy middleware has no use in this case, and will fail to instantiate.
  215. if (proxyConfig.target) {
  216. return httpProxyMiddleware(context, proxyConfig);
  217. }
  218. };
  219. /**
  220. * Assume a proxy configuration specified as:
  221. * proxy: [
  222. * {
  223. * context: ...,
  224. * ...options...
  225. * },
  226. * // or:
  227. * function() {
  228. * return {
  229. * context: ...,
  230. * ...options...
  231. * };
  232. * }
  233. * ]
  234. */
  235. this.options.proxy.forEach((proxyConfigOrCallback) => {
  236. let proxyConfig;
  237. let proxyMiddleware;
  238. if (typeof proxyConfigOrCallback === 'function') {
  239. proxyConfig = proxyConfigOrCallback();
  240. } else {
  241. proxyConfig = proxyConfigOrCallback;
  242. }
  243. proxyMiddleware = getProxyMiddleware(proxyConfig);
  244. if (proxyConfig.ws) {
  245. this.websocketProxies.push(proxyMiddleware);
  246. }
  247. this.app.use((req, res, next) => {
  248. if (typeof proxyConfigOrCallback === 'function') {
  249. const newProxyConfig = proxyConfigOrCallback();
  250. if (newProxyConfig !== proxyConfig) {
  251. proxyConfig = newProxyConfig;
  252. proxyMiddleware = getProxyMiddleware(proxyConfig);
  253. }
  254. }
  255. // - Check if we have a bypass function defined
  256. // - In case the bypass function is defined we'll retrieve the
  257. // bypassUrl from it otherwise byPassUrl would be null
  258. const isByPassFuncDefined = typeof proxyConfig.bypass === 'function';
  259. const bypassUrl = isByPassFuncDefined
  260. ? proxyConfig.bypass(req, res, proxyConfig)
  261. : null;
  262. if (typeof bypassUrl === 'boolean') {
  263. // skip the proxy
  264. req.url = null;
  265. next();
  266. } else if (typeof bypassUrl === 'string') {
  267. // byPass to that url
  268. req.url = bypassUrl;
  269. next();
  270. } else if (proxyMiddleware) {
  271. return proxyMiddleware(req, res, next);
  272. } else {
  273. next();
  274. }
  275. });
  276. });
  277. }
  278. setupHistoryApiFallbackFeature() {
  279. const fallback =
  280. typeof this.options.historyApiFallback === 'object'
  281. ? this.options.historyApiFallback
  282. : null;
  283. // Fall back to /index.html if nothing else matches.
  284. this.app.use(historyApiFallback(fallback));
  285. }
  286. setupStaticFeature() {
  287. const contentBase = this.options.contentBase;
  288. if (Array.isArray(contentBase)) {
  289. contentBase.forEach((item) => {
  290. this.app.get('*', express.static(item));
  291. });
  292. } else if (/^(https?:)?\/\//.test(contentBase)) {
  293. this.log.warn(
  294. 'Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
  295. );
  296. this.log.warn(
  297. 'proxy: {\n\t"*": "<your current contentBase configuration>"\n}'
  298. );
  299. // Redirect every request to contentBase
  300. this.app.get('*', (req, res) => {
  301. res.writeHead(302, {
  302. Location: contentBase + req.path + (req._parsedUrl.search || ''),
  303. });
  304. res.end();
  305. });
  306. } else if (typeof contentBase === 'number') {
  307. this.log.warn(
  308. 'Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
  309. );
  310. this.log.warn(
  311. 'proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'
  312. );
  313. // Redirect every request to the port contentBase
  314. this.app.get('*', (req, res) => {
  315. res.writeHead(302, {
  316. Location: `//localhost:${contentBase}${req.path}${req._parsedUrl
  317. .search || ''}`,
  318. });
  319. res.end();
  320. });
  321. } else {
  322. // route content request
  323. this.app.get(
  324. '*',
  325. express.static(contentBase, this.options.staticOptions)
  326. );
  327. }
  328. }
  329. setupServeIndexFeature() {
  330. const contentBase = this.options.contentBase;
  331. if (Array.isArray(contentBase)) {
  332. contentBase.forEach((item) => {
  333. this.app.get('*', serveIndex(item));
  334. });
  335. } else if (
  336. !/^(https?:)?\/\//.test(contentBase) &&
  337. typeof contentBase !== 'number'
  338. ) {
  339. this.app.get('*', serveIndex(contentBase));
  340. }
  341. }
  342. setupWatchStaticFeature() {
  343. const contentBase = this.options.contentBase;
  344. if (
  345. /^(https?:)?\/\//.test(contentBase) ||
  346. typeof contentBase === 'number'
  347. ) {
  348. throw new Error('Watching remote files is not supported.');
  349. } else if (Array.isArray(contentBase)) {
  350. contentBase.forEach((item) => {
  351. this._watch(item);
  352. });
  353. } else {
  354. this._watch(contentBase);
  355. }
  356. }
  357. setupBeforeFeature() {
  358. // Todo rename onBeforeSetupMiddleware in next major release
  359. // Todo pass only `this` argument
  360. this.options.before(this.app, this, this.compiler);
  361. }
  362. setupMiddleware() {
  363. this.app.use(this.middleware);
  364. }
  365. setupAfterFeature() {
  366. // Todo rename onAfterSetupMiddleware in next major release
  367. // Todo pass only `this` argument
  368. this.options.after(this.app, this, this.compiler);
  369. }
  370. setupHeadersFeature() {
  371. this.app.all('*', this.setContentHeaders.bind(this));
  372. }
  373. setupMagicHtmlFeature() {
  374. this.app.get('*', this.serveMagicHtml.bind(this));
  375. }
  376. setupSetupFeature() {
  377. this.log.warn(
  378. 'The `setup` option is deprecated and will be removed in v4. Please update your config to use `before`'
  379. );
  380. this.options.setup(this.app, this);
  381. }
  382. setupFeatures() {
  383. const features = {
  384. compress: () => {
  385. if (this.options.compress) {
  386. this.setupCompressFeature();
  387. }
  388. },
  389. proxy: () => {
  390. if (this.options.proxy) {
  391. this.setupProxyFeature();
  392. }
  393. },
  394. historyApiFallback: () => {
  395. if (this.options.historyApiFallback) {
  396. this.setupHistoryApiFallbackFeature();
  397. }
  398. },
  399. // Todo rename to `static` in future major release
  400. contentBaseFiles: () => {
  401. this.setupStaticFeature();
  402. },
  403. // Todo rename to `serveIndex` in future major release
  404. contentBaseIndex: () => {
  405. this.setupServeIndexFeature();
  406. },
  407. // Todo rename to `watchStatic` in future major release
  408. watchContentBase: () => {
  409. this.setupWatchStaticFeature();
  410. },
  411. before: () => {
  412. if (typeof this.options.before === 'function') {
  413. this.setupBeforeFeature();
  414. }
  415. },
  416. middleware: () => {
  417. // include our middleware to ensure
  418. // it is able to handle '/index.html' request after redirect
  419. this.setupMiddleware();
  420. },
  421. after: () => {
  422. if (typeof this.options.after === 'function') {
  423. this.setupAfterFeature();
  424. }
  425. },
  426. headers: () => {
  427. this.setupHeadersFeature();
  428. },
  429. magicHtml: () => {
  430. this.setupMagicHtmlFeature();
  431. },
  432. setup: () => {
  433. if (typeof this.options.setup === 'function') {
  434. this.setupSetupFeature();
  435. }
  436. },
  437. };
  438. const runnableFeatures = [];
  439. // compress is placed last and uses unshift so that it will be the first middleware used
  440. if (this.options.compress) {
  441. runnableFeatures.push('compress');
  442. }
  443. runnableFeatures.push('setup', 'before', 'headers', 'middleware');
  444. if (this.options.proxy) {
  445. runnableFeatures.push('proxy', 'middleware');
  446. }
  447. if (this.options.contentBase !== false) {
  448. runnableFeatures.push('contentBaseFiles');
  449. }
  450. if (this.options.historyApiFallback) {
  451. runnableFeatures.push('historyApiFallback', 'middleware');
  452. if (this.options.contentBase !== false) {
  453. runnableFeatures.push('contentBaseFiles');
  454. }
  455. }
  456. // checking if it's set to true or not set (Default : undefined => true)
  457. this.serveIndex = this.serveIndex || this.serveIndex === undefined;
  458. if (this.options.contentBase && this.serveIndex) {
  459. runnableFeatures.push('contentBaseIndex');
  460. }
  461. if (this.options.watchContentBase) {
  462. runnableFeatures.push('watchContentBase');
  463. }
  464. runnableFeatures.push('magicHtml');
  465. if (this.options.after) {
  466. runnableFeatures.push('after');
  467. }
  468. (this.options.features || runnableFeatures).forEach((feature) => {
  469. features[feature]();
  470. });
  471. }
  472. setupHttps() {
  473. // if the user enables http2, we can safely enable https
  474. if (this.options.http2 && !this.options.https) {
  475. this.options.https = true;
  476. }
  477. if (this.options.https) {
  478. // for keep supporting CLI parameters
  479. if (typeof this.options.https === 'boolean') {
  480. this.options.https = {
  481. ca: this.options.ca,
  482. pfx: this.options.pfx,
  483. key: this.options.key,
  484. cert: this.options.cert,
  485. passphrase: this.options.pfxPassphrase,
  486. requestCert: this.options.requestCert || false,
  487. };
  488. }
  489. for (const property of ['ca', 'pfx', 'key', 'cert']) {
  490. const value = this.options.https[property];
  491. const isBuffer = value instanceof Buffer;
  492. if (value && !isBuffer) {
  493. let stats = null;
  494. try {
  495. stats = fs.lstatSync(fs.realpathSync(value)).isFile();
  496. } catch (error) {
  497. // ignore error
  498. }
  499. // It is file
  500. this.options.https[property] = stats
  501. ? fs.readFileSync(path.resolve(value))
  502. : value;
  503. }
  504. }
  505. let fakeCert;
  506. if (!this.options.https.key || !this.options.https.cert) {
  507. fakeCert = getCertificate(this.log);
  508. }
  509. this.options.https.key = this.options.https.key || fakeCert;
  510. this.options.https.cert = this.options.https.cert || fakeCert;
  511. // note that options.spdy never existed. The user was able
  512. // to set options.https.spdy before, though it was not in the
  513. // docs. Keep options.https.spdy if the user sets it for
  514. // backwards compatibility, but log a deprecation warning.
  515. if (this.options.https.spdy) {
  516. // for backwards compatibility: if options.https.spdy was passed in before,
  517. // it was not altered in any way
  518. this.log.warn(
  519. 'Providing custom spdy server options is deprecated and will be removed in the next major version.'
  520. );
  521. } else {
  522. // if the normal https server gets this option, it will not affect it.
  523. this.options.https.spdy = {
  524. protocols: ['h2', 'http/1.1'],
  525. };
  526. }
  527. }
  528. }
  529. createServer() {
  530. if (this.options.https) {
  531. // Only prevent HTTP/2 if http2 is explicitly set to false
  532. const isHttp2 = this.options.http2 !== false;
  533. // `spdy` is effectively unmaintained, and as a consequence of an
  534. // implementation that extensively relies on Node’s non-public APIs, broken
  535. // on Node 10 and above. In those cases, only https will be used for now.
  536. // Once express supports Node's built-in HTTP/2 support, migrating over to
  537. // that should be the best way to go.
  538. // The relevant issues are:
  539. // - https://github.com/nodejs/node/issues/21665
  540. // - https://github.com/webpack/webpack-dev-server/issues/1449
  541. // - https://github.com/expressjs/express/issues/3388
  542. if (semver.gte(process.version, '10.0.0') || !isHttp2) {
  543. if (this.options.http2) {
  544. // the user explicitly requested http2 but is not getting it because
  545. // of the node version.
  546. this.log.warn(
  547. 'HTTP/2 is currently unsupported for Node 10.0.0 and above, but will be supported once Express supports it'
  548. );
  549. }
  550. this.listeningApp = https.createServer(this.options.https, this.app);
  551. } else {
  552. // The relevant issues are:
  553. // https://github.com/spdy-http2/node-spdy/issues/350
  554. // https://github.com/webpack/webpack-dev-server/issues/1592
  555. // eslint-disable-next-line global-require
  556. this.listeningApp = require('spdy').createServer(
  557. this.options.https,
  558. this.app
  559. );
  560. }
  561. } else {
  562. this.listeningApp = http.createServer(this.app);
  563. }
  564. }
  565. createSocketServer() {
  566. const SocketServerImplementation = this.socketServerImplementation;
  567. this.socketServer = new SocketServerImplementation(this);
  568. this.socketServer.onConnection((connection) => {
  569. if (!connection) {
  570. return;
  571. }
  572. if (
  573. !this.checkHost(connection.headers) ||
  574. !this.checkOrigin(connection.headers)
  575. ) {
  576. this.sockWrite([connection], 'error', 'Invalid Host/Origin header');
  577. connection.close();
  578. return;
  579. }
  580. this.sockets.push(connection);
  581. connection.on('close', () => {
  582. const idx = this.sockets.indexOf(connection);
  583. if (idx >= 0) {
  584. this.sockets.splice(idx, 1);
  585. }
  586. });
  587. if (this.clientLogLevel) {
  588. this.sockWrite([connection], 'log-level', this.clientLogLevel);
  589. }
  590. if (this.hot) {
  591. this.sockWrite([connection], 'hot');
  592. }
  593. // TODO: change condition at major version
  594. if (this.options.liveReload !== false) {
  595. this.sockWrite([connection], 'liveReload', this.options.liveReload);
  596. }
  597. if (this.progress) {
  598. this.sockWrite([connection], 'progress', this.progress);
  599. }
  600. if (this.clientOverlay) {
  601. this.sockWrite([connection], 'overlay', this.clientOverlay);
  602. }
  603. if (!this._stats) {
  604. return;
  605. }
  606. this._sendStats([connection], this.getStats(this._stats), true);
  607. });
  608. }
  609. showStatus() {
  610. const suffix =
  611. this.options.inline !== false || this.options.lazy === true
  612. ? '/'
  613. : '/webpack-dev-server/';
  614. const uri = `${createDomain(this.options, this.listeningApp)}${suffix}`;
  615. status(
  616. uri,
  617. this.options,
  618. this.log,
  619. this.options.stats && this.options.stats.colors
  620. );
  621. }
  622. listen(port, hostname, fn) {
  623. this.hostname = hostname;
  624. return this.listeningApp.listen(port, hostname, (err) => {
  625. this.createSocketServer();
  626. if (this.options.bonjour) {
  627. runBonjour(this.options);
  628. }
  629. this.showStatus();
  630. if (fn) {
  631. fn.call(this.listeningApp, err);
  632. }
  633. if (typeof this.options.onListening === 'function') {
  634. this.options.onListening(this);
  635. }
  636. });
  637. }
  638. close(cb) {
  639. this.sockets.forEach((socket) => {
  640. this.socketServer.close(socket);
  641. });
  642. this.sockets = [];
  643. this.contentBaseWatchers.forEach((watcher) => {
  644. watcher.close();
  645. });
  646. this.contentBaseWatchers = [];
  647. this.listeningApp.kill(() => {
  648. this.middleware.close(cb);
  649. });
  650. }
  651. static get DEFAULT_STATS() {
  652. return {
  653. all: false,
  654. hash: true,
  655. assets: true,
  656. warnings: true,
  657. errors: true,
  658. errorDetails: false,
  659. };
  660. }
  661. getStats(statsObj) {
  662. const stats = Server.DEFAULT_STATS;
  663. if (this.originalStats.warningsFilter) {
  664. stats.warningsFilter = this.originalStats.warningsFilter;
  665. }
  666. return statsObj.toJson(stats);
  667. }
  668. use() {
  669. // eslint-disable-next-line
  670. this.app.use.apply(this.app, arguments);
  671. }
  672. setContentHeaders(req, res, next) {
  673. if (this.headers) {
  674. // eslint-disable-next-line
  675. for (const name in this.headers) {
  676. res.setHeader(name, this.headers[name]);
  677. }
  678. }
  679. next();
  680. }
  681. checkHost(headers) {
  682. return this.checkHeaders(headers, 'host');
  683. }
  684. checkOrigin(headers) {
  685. return this.checkHeaders(headers, 'origin');
  686. }
  687. checkHeaders(headers, headerToCheck) {
  688. // allow user to opt-out this security check, at own risk
  689. if (this.disableHostCheck) {
  690. return true;
  691. }
  692. if (!headerToCheck) {
  693. headerToCheck = 'host';
  694. }
  695. // get the Host header and extract hostname
  696. // we don't care about port not matching
  697. const hostHeader = headers[headerToCheck];
  698. if (!hostHeader) {
  699. return false;
  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 convenience
  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. if (allowedHost === hostname) {
  726. 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. // allow hostname of listening address
  743. if (hostname === this.hostname) {
  744. return true;
  745. }
  746. // also allow public hostname if provided
  747. if (typeof this.publicHost === 'string') {
  748. const idxPublic = this.publicHost.indexOf(':');
  749. const publicHostname =
  750. idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
  751. if (hostname === publicHostname) {
  752. return true;
  753. }
  754. }
  755. // disallow
  756. return false;
  757. }
  758. // eslint-disable-next-line
  759. sockWrite(sockets, type, data) {
  760. sockets.forEach((socket) => {
  761. this.socketServer.send(socket, JSON.stringify({ type, data }));
  762. });
  763. }
  764. serveMagicHtml(req, res, next) {
  765. const _path = req.path;
  766. try {
  767. const isFile = this.middleware.fileSystem
  768. .statSync(this.middleware.getFilenameFromUrl(`${_path}.js`))
  769. .isFile();
  770. if (!isFile) {
  771. return next();
  772. }
  773. // Serve a page that executes the javascript
  774. res.write(
  775. '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="'
  776. );
  777. res.write(_path);
  778. res.write('.js');
  779. res.write(req._parsedUrl.search || '');
  780. res.end('"></script></body></html>');
  781. } catch (err) {
  782. return next();
  783. }
  784. }
  785. // send stats to a socket or multiple sockets
  786. _sendStats(sockets, stats, force) {
  787. if (
  788. !force &&
  789. stats &&
  790. (!stats.errors || stats.errors.length === 0) &&
  791. stats.assets &&
  792. stats.assets.every((asset) => !asset.emitted)
  793. ) {
  794. return this.sockWrite(sockets, 'still-ok');
  795. }
  796. this.sockWrite(sockets, 'hash', stats.hash);
  797. if (stats.errors.length > 0) {
  798. this.sockWrite(sockets, 'errors', stats.errors);
  799. } else if (stats.warnings.length > 0) {
  800. this.sockWrite(sockets, 'warnings', stats.warnings);
  801. } else {
  802. this.sockWrite(sockets, 'ok');
  803. }
  804. }
  805. _watch(watchPath) {
  806. // duplicate the same massaging of options that watchpack performs
  807. // https://github.com/webpack/watchpack/blob/master/lib/DirectoryWatcher.js#L49
  808. // this isn't an elegant solution, but we'll improve it in the future
  809. const usePolling = this.watchOptions.poll ? true : undefined;
  810. const interval =
  811. typeof this.watchOptions.poll === 'number'
  812. ? this.watchOptions.poll
  813. : undefined;
  814. const watchOptions = {
  815. ignoreInitial: true,
  816. persistent: true,
  817. followSymlinks: false,
  818. atomic: false,
  819. alwaysStat: true,
  820. ignorePermissionErrors: true,
  821. ignored: this.watchOptions.ignored,
  822. usePolling,
  823. interval,
  824. };
  825. const watcher = chokidar.watch(watchPath, watchOptions);
  826. // disabling refreshing on changing the content
  827. if (this.options.liveReload !== false) {
  828. watcher.on('change', () => {
  829. this.sockWrite(this.sockets, 'content-changed');
  830. });
  831. }
  832. this.contentBaseWatchers.push(watcher);
  833. }
  834. invalidate(callback) {
  835. if (this.middleware) {
  836. this.middleware.invalidate(callback);
  837. }
  838. }
  839. }
  840. // Export this logic,
  841. // so that other implementations,
  842. // like task-runners can use it
  843. Server.addDevServerEntrypoints = require('./utils/addEntries');
  844. module.exports = Server;