index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. "use strict";
  2. const {
  3. validate
  4. } = require("schema-utils");
  5. const mime = require("mime-types");
  6. const middleware = require("./middleware");
  7. const getFilenameFromUrl = require("./utils/getFilenameFromUrl");
  8. const setupHooks = require("./utils/setupHooks");
  9. const setupWriteToDisk = require("./utils/setupWriteToDisk");
  10. const setupOutputFileSystem = require("./utils/setupOutputFileSystem");
  11. const ready = require("./utils/ready");
  12. const schema = require("./options.json");
  13. const noop = () => {};
  14. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  15. /** @typedef {import("webpack").Compiler} Compiler */
  16. /** @typedef {import("webpack").MultiCompiler} MultiCompiler */
  17. /** @typedef {import("webpack").Configuration} Configuration */
  18. /** @typedef {import("webpack").Stats} Stats */
  19. /** @typedef {import("webpack").MultiStats} MultiStats */
  20. /** @typedef {import("fs").ReadStream} ReadStream */
  21. /**
  22. * @typedef {Object} ExtendedServerResponse
  23. * @property {{ webpack?: { devMiddleware?: Context<IncomingMessage, ServerResponse> } }} [locals]
  24. */
  25. /** @typedef {import("http").IncomingMessage} IncomingMessage */
  26. /** @typedef {import("http").ServerResponse & ExtendedServerResponse} ServerResponse */
  27. /**
  28. * @callback NextFunction
  29. * @param {any} [err]
  30. * @return {void}
  31. */
  32. /**
  33. * @typedef {NonNullable<Configuration["watchOptions"]>} WatchOptions
  34. */
  35. /**
  36. * @typedef {Compiler["watching"]} Watching
  37. */
  38. /**
  39. * @typedef {ReturnType<MultiCompiler["watch"]>} MultiWatching
  40. */
  41. /**
  42. * @typedef {import("webpack").OutputFileSystem & { createReadStream?: import("fs").createReadStream, statSync: import("fs").statSync, readFileSync: import("fs").readFileSync }} OutputFileSystem
  43. */
  44. /** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
  45. /**
  46. * @callback Callback
  47. * @param {Stats | MultiStats} [stats]
  48. */
  49. /**
  50. * @typedef {Object} ResponseData
  51. * @property {Buffer | ReadStream} data
  52. * @property {number} byteLength
  53. */
  54. /**
  55. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  56. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  57. * @callback ModifyResponseData
  58. * @param {RequestInternal} req
  59. * @param {ResponseInternal} res
  60. * @param {Buffer | ReadStream} data
  61. * @param {number} byteLength
  62. * @return {ResponseData}
  63. */
  64. /**
  65. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  66. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  67. * @typedef {Object} Context
  68. * @property {boolean} state
  69. * @property {Stats | MultiStats | undefined} stats
  70. * @property {Callback[]} callbacks
  71. * @property {Options<RequestInternal, ResponseInternal>} options
  72. * @property {Compiler | MultiCompiler} compiler
  73. * @property {Watching | MultiWatching | undefined} watching
  74. * @property {Logger} logger
  75. * @property {OutputFileSystem} outputFileSystem
  76. */
  77. /**
  78. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  79. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  80. * @typedef {WithoutUndefined<Context<RequestInternal, ResponseInternal>, "watching">} FilledContext
  81. */
  82. /** @typedef {Record<string, string | number> | Array<{ key: string, value: number | string }>} NormalizedHeaders */
  83. /**
  84. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  85. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  86. * @typedef {NormalizedHeaders | ((req: RequestInternal, res: ResponseInternal, context: Context<RequestInternal, ResponseInternal>) => void | undefined | NormalizedHeaders) | undefined} Headers
  87. */
  88. /**
  89. * @template {IncomingMessage} [RequestInternal = IncomingMessage]
  90. * @template {ServerResponse} [ResponseInternal = ServerResponse]
  91. * @typedef {Object} Options
  92. * @property {{[key: string]: string}} [mimeTypes]
  93. * @property {string | undefined} [mimeTypeDefault]
  94. * @property {boolean | ((targetPath: string) => boolean)} [writeToDisk]
  95. * @property {string[]} [methods]
  96. * @property {Headers<RequestInternal, ResponseInternal>} [headers]
  97. * @property {NonNullable<Configuration["output"]>["publicPath"]} [publicPath]
  98. * @property {Configuration["stats"]} [stats]
  99. * @property {boolean} [serverSideRender]
  100. * @property {OutputFileSystem} [outputFileSystem]
  101. * @property {boolean | string} [index]
  102. * @property {ModifyResponseData<RequestInternal, ResponseInternal>} [modifyResponseData]
  103. * @property {"weak" | "strong"} [etag]
  104. * @property {boolean} [lastModified]
  105. */
  106. /**
  107. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  108. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  109. * @callback Middleware
  110. * @param {RequestInternal} req
  111. * @param {ResponseInternal} res
  112. * @param {NextFunction} next
  113. * @return {Promise<void>}
  114. */
  115. /** @typedef {import("./utils/getFilenameFromUrl").Extra} Extra */
  116. /**
  117. * @callback GetFilenameFromUrl
  118. * @param {string} url
  119. * @param {Extra=} extra
  120. * @returns {string | undefined}
  121. */
  122. /**
  123. * @callback WaitUntilValid
  124. * @param {Callback} callback
  125. */
  126. /**
  127. * @callback Invalidate
  128. * @param {Callback} callback
  129. */
  130. /**
  131. * @callback Close
  132. * @param {(err: Error | null | undefined) => void} callback
  133. */
  134. /**
  135. * @template {IncomingMessage} RequestInternal
  136. * @template {ServerResponse} ResponseInternal
  137. * @typedef {Object} AdditionalMethods
  138. * @property {GetFilenameFromUrl} getFilenameFromUrl
  139. * @property {WaitUntilValid} waitUntilValid
  140. * @property {Invalidate} invalidate
  141. * @property {Close} close
  142. * @property {Context<RequestInternal, ResponseInternal>} context
  143. */
  144. /**
  145. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  146. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  147. * @typedef {Middleware<RequestInternal, ResponseInternal> & AdditionalMethods<RequestInternal, ResponseInternal>} API
  148. */
  149. /**
  150. * @template T
  151. * @template {keyof T} K
  152. * @typedef {Omit<T, K> & Partial<T>} WithOptional
  153. */
  154. /**
  155. * @template T
  156. * @template {keyof T} K
  157. * @typedef {T & { [P in K]: NonNullable<T[P]> }} WithoutUndefined
  158. */
  159. /**
  160. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  161. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  162. * @param {Compiler | MultiCompiler} compiler
  163. * @param {Options<RequestInternal, ResponseInternal>} [options]
  164. * @returns {API<RequestInternal, ResponseInternal>}
  165. */
  166. function wdm(compiler, options = {}) {
  167. validate( /** @type {Schema} */schema, options, {
  168. name: "Dev Middleware",
  169. baseDataPath: "options"
  170. });
  171. const {
  172. mimeTypes
  173. } = options;
  174. if (mimeTypes) {
  175. const {
  176. types
  177. } = mime;
  178. // mimeTypes from user provided options should take priority
  179. // over existing, known types
  180. // @ts-ignore
  181. mime.types = {
  182. ...types,
  183. ...mimeTypes
  184. };
  185. }
  186. /**
  187. * @type {WithOptional<Context<RequestInternal, ResponseInternal>, "watching" | "outputFileSystem">}
  188. */
  189. const context = {
  190. state: false,
  191. // eslint-disable-next-line no-undefined
  192. stats: undefined,
  193. callbacks: [],
  194. options,
  195. compiler,
  196. logger: compiler.getInfrastructureLogger("webpack-dev-middleware")
  197. };
  198. setupHooks(context);
  199. if (options.writeToDisk) {
  200. setupWriteToDisk(context);
  201. }
  202. setupOutputFileSystem(context);
  203. // Start watching
  204. if ( /** @type {Compiler} */context.compiler.watching) {
  205. context.watching = /** @type {Compiler} */context.compiler.watching;
  206. } else {
  207. /**
  208. * @param {Error | null | undefined} error
  209. */
  210. const errorHandler = error => {
  211. if (error) {
  212. // TODO: improve that in future
  213. // For example - `writeToDisk` can throw an error and right now it is ends watching.
  214. // We can improve that and keep watching active, but it is require API on webpack side.
  215. // Let's implement that in webpack@5 because it is rare case.
  216. context.logger.error(error);
  217. }
  218. };
  219. if (Array.isArray( /** @type {MultiCompiler} */context.compiler.compilers)) {
  220. const c = /** @type {MultiCompiler} */context.compiler;
  221. const watchOptions = c.compilers.map(childCompiler => childCompiler.options.watchOptions || {});
  222. context.watching = compiler.watch(watchOptions, errorHandler);
  223. } else {
  224. const c = /** @type {Compiler} */context.compiler;
  225. const watchOptions = c.options.watchOptions || {};
  226. context.watching = compiler.watch(watchOptions, errorHandler);
  227. }
  228. }
  229. const filledContext = /** @type {FilledContext<RequestInternal, ResponseInternal>} */
  230. context;
  231. const instance = /** @type {API<RequestInternal, ResponseInternal>} */
  232. middleware(filledContext);
  233. // API
  234. instance.getFilenameFromUrl = (url, extra) => getFilenameFromUrl(filledContext, url, extra);
  235. instance.waitUntilValid = (callback = noop) => {
  236. ready(filledContext, callback);
  237. };
  238. instance.invalidate = (callback = noop) => {
  239. ready(filledContext, callback);
  240. filledContext.watching.invalidate();
  241. };
  242. instance.close = (callback = noop) => {
  243. filledContext.watching.close(callback);
  244. };
  245. instance.context = filledContext;
  246. return instance;
  247. }
  248. /**
  249. * @template S
  250. * @template O
  251. * @typedef {Object} HapiPluginBase
  252. * @property {(server: S, options: O) => void | Promise<void>} register
  253. */
  254. /**
  255. * @template S
  256. * @template O
  257. * @typedef {HapiPluginBase<S, O> & { pkg: { name: string } }} HapiPlugin
  258. */
  259. /**
  260. * @typedef {Options & { compiler: Compiler | MultiCompiler }} HapiOptions
  261. */
  262. /**
  263. * @template HapiServer
  264. * @template {HapiOptions} HapiOptionsInternal
  265. * @returns {HapiPlugin<HapiServer, HapiOptionsInternal>}
  266. */
  267. function hapiWrapper() {
  268. return {
  269. pkg: {
  270. name: "webpack-dev-middleware"
  271. },
  272. register(server, options) {
  273. const {
  274. compiler,
  275. ...rest
  276. } = options;
  277. if (!compiler) {
  278. throw new Error("The compiler options is required.");
  279. }
  280. const devMiddleware = wdm(compiler, rest);
  281. // @ts-ignore
  282. server.decorate("server", "webpackDevMiddleware", devMiddleware);
  283. // @ts-ignore
  284. server.ext("onRequest", (request, h) => new Promise((resolve, reject) => {
  285. let isFinished = false;
  286. /**
  287. * @param {string | Buffer} [data]
  288. */
  289. // eslint-disable-next-line no-param-reassign
  290. request.raw.res.send = data => {
  291. isFinished = true;
  292. request.raw.res.end(data);
  293. };
  294. /**
  295. * @param {string | Buffer} [data]
  296. */
  297. // eslint-disable-next-line no-param-reassign
  298. request.raw.res.finish = data => {
  299. isFinished = true;
  300. request.raw.res.end(data);
  301. };
  302. devMiddleware(request.raw.req, request.raw.res, error => {
  303. if (error) {
  304. reject(error);
  305. return;
  306. }
  307. if (!isFinished) {
  308. resolve(request);
  309. }
  310. });
  311. }).then(() => h.continue).catch(error => {
  312. throw error;
  313. }));
  314. }
  315. };
  316. }
  317. wdm.hapiWrapper = hapiWrapper;
  318. /**
  319. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  320. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  321. * @param {Compiler | MultiCompiler} compiler
  322. * @param {Options<RequestInternal, ResponseInternal>} [options]
  323. * @returns {(ctx: any, next: Function) => Promise<void> | void}
  324. */
  325. function koaWrapper(compiler, options) {
  326. const devMiddleware = wdm(compiler, options);
  327. /**
  328. * @param {{ req: RequestInternal, res: ResponseInternal & import("./utils/compatibleAPI").ExpectedServerResponse, status: number, body: string | Buffer | import("fs").ReadStream | { message: string }, state: Object }} ctx
  329. * @param {Function} next
  330. * @returns {Promise<void>}
  331. */
  332. const wrapper = async function webpackDevMiddleware(ctx, next) {
  333. const {
  334. req,
  335. res
  336. } = ctx;
  337. res.locals = ctx.state;
  338. let {
  339. status
  340. } = ctx;
  341. /**
  342. * @returns {number} code
  343. */
  344. res.getStatusCode = () => status;
  345. /**
  346. * @param {number} statusCode status code
  347. */
  348. res.setStatusCode = statusCode => {
  349. status = statusCode;
  350. // eslint-disable-next-line no-param-reassign
  351. ctx.status = statusCode;
  352. };
  353. res.getReadyReadableStreamState = () => "open";
  354. try {
  355. await new Promise(
  356. /**
  357. * @param {(value: void) => void} resolve
  358. * @param {(reason?: any) => void} reject
  359. */
  360. (resolve, reject) => {
  361. /**
  362. * @param {import("fs").ReadStream} stream readable stream
  363. */
  364. res.stream = stream => {
  365. // eslint-disable-next-line no-param-reassign
  366. ctx.body = stream;
  367. };
  368. /**
  369. * @param {string | Buffer} data data
  370. */
  371. res.send = data => {
  372. // eslint-disable-next-line no-param-reassign
  373. ctx.body = data;
  374. };
  375. /**
  376. * @param {string | Buffer} [data] data
  377. */
  378. res.finish = data => {
  379. // eslint-disable-next-line no-param-reassign
  380. ctx.status = status;
  381. res.end(data);
  382. };
  383. devMiddleware(req, res, err => {
  384. if (err) {
  385. reject(err);
  386. return;
  387. }
  388. resolve();
  389. });
  390. });
  391. } catch (err) {
  392. // eslint-disable-next-line no-param-reassign
  393. ctx.status = /** @type {Error & { statusCode: number }} */err.statusCode || /** @type {Error & { status: number }} */err.status || 500;
  394. // eslint-disable-next-line no-param-reassign
  395. ctx.body = {
  396. message: /** @type {Error} */err.message
  397. };
  398. }
  399. await next();
  400. };
  401. wrapper.devMiddleware = devMiddleware;
  402. return wrapper;
  403. }
  404. wdm.koaWrapper = koaWrapper;
  405. /**
  406. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  407. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  408. * @param {Compiler | MultiCompiler} compiler
  409. * @param {Options<RequestInternal, ResponseInternal>} [options]
  410. * @returns {(ctx: any, next: Function) => Promise<void> | void}
  411. */
  412. function honoWrapper(compiler, options) {
  413. const devMiddleware = wdm(compiler, options);
  414. /**
  415. * @param {{ env: any, body: any, json: any, status: any, set:any, req: RequestInternal & import("./utils/compatibleAPI").ExpectedIncomingMessage & { header: (name: string) => string }, res: ResponseInternal & import("./utils/compatibleAPI").ExpectedServerResponse & { headers: any, status: any } }} c
  416. * @param {Function} next
  417. * @returns {Promise<void>}
  418. */
  419. // eslint-disable-next-line consistent-return
  420. const wrapper = async function webpackDevMiddleware(c, next) {
  421. const {
  422. req,
  423. res
  424. } = c;
  425. c.set("webpack", {
  426. devMiddleware: devMiddleware.context
  427. });
  428. /**
  429. * @returns {string | undefined}
  430. */
  431. req.getMethod = () => c.req.method;
  432. /**
  433. * @param {string} name
  434. * @returns {string | string[] | undefined}
  435. */
  436. req.getHeader = name => c.req.header(name);
  437. /**
  438. * @returns {string | undefined}
  439. */
  440. req.getURL = () => c.req.url;
  441. let {
  442. status
  443. } = c.res;
  444. /**
  445. * @returns {number} code
  446. */
  447. res.getStatusCode = () => status;
  448. /**
  449. * @param {number} code
  450. */
  451. res.setStatusCode = code => {
  452. status = code;
  453. };
  454. /**
  455. * @param {string} name header name
  456. */
  457. res.getHeader = name => c.res.headers.get(name);
  458. /**
  459. * @param {string} name
  460. * @param {string | number | Readonly<string[]>} value
  461. */
  462. res.setHeader = (name, value) => {
  463. c.res.headers.append(name, value);
  464. return c.res;
  465. };
  466. /**
  467. * @param {string} name
  468. */
  469. res.removeHeader = name => {
  470. c.res.headers.delete(name);
  471. };
  472. /**
  473. * @returns {string[]}
  474. */
  475. res.getResponseHeaders = () => Array.from(c.res.headers.keys());
  476. /**
  477. * @returns {ServerResponse}
  478. */
  479. res.getOutgoing = () => c.env.outgoing;
  480. res.setState = () => {
  481. // Do nothing, because we set it before
  482. };
  483. res.getReadyReadableStreamState = () => "readable";
  484. let body;
  485. try {
  486. await new Promise(
  487. /**
  488. * @param {(value: void) => void} resolve
  489. * @param {(reason?: any) => void} reject
  490. */
  491. (resolve, reject) => {
  492. /**
  493. * @param {import("fs").ReadStream} stream readable stream
  494. */
  495. res.stream = stream => {
  496. body = stream;
  497. // responseHandler(stream);
  498. };
  499. /**
  500. * @param {string | Buffer} data data
  501. */
  502. res.send = data => {
  503. body = data;
  504. };
  505. /**
  506. * @param {string | Buffer} [data] data
  507. */
  508. res.finish = data => {
  509. body = typeof data !== "undefined" ? data : null;
  510. };
  511. devMiddleware(req, res, err => {
  512. if (err) {
  513. reject(err);
  514. return;
  515. }
  516. resolve();
  517. });
  518. });
  519. } catch (err) {
  520. c.status(500);
  521. return c.json({
  522. message: /** @type {Error} */err.message
  523. });
  524. }
  525. if (typeof body !== "undefined") {
  526. return c.body(body, status);
  527. }
  528. await next();
  529. };
  530. wrapper.devMiddleware = devMiddleware;
  531. return wrapper;
  532. }
  533. wdm.honoWrapper = honoWrapper;
  534. module.exports = wdm;