index.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. "use strict";
  2. const fs = require("node:fs");
  3. const path = require("node:path");
  4. const memfs = require("memfs");
  5. const mime = require("mime-types");
  6. const middleware = require("./middleware");
  7. const {
  8. nodeReadableToWebStream
  9. } = require("./utils");
  10. const noop = () => {};
  11. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  12. /** @typedef {import("webpack").Compiler} Compiler */
  13. /** @typedef {import("webpack").MultiCompiler} MultiCompiler */
  14. /** @typedef {import("webpack").Configuration} Configuration */
  15. /** @typedef {import("webpack").Stats} Stats */
  16. /** @typedef {import("webpack").MultiStats} MultiStats */
  17. /** @typedef {import("fs").ReadStream} ReadStream */
  18. /** @typedef {import("./middleware").FilenameWithExtra} FilenameWithExtra */
  19. // eslint-disable-next-line jsdoc/reject-any-type
  20. /** @typedef {any} EXPECTED_ANY */
  21. // eslint-disable-next-line jsdoc/reject-function-type
  22. /** @typedef {Function} EXPECTED_FUNCTION */
  23. /**
  24. * @typedef {object} ExtendedServerResponse
  25. * @property {{ webpack?: { devMiddleware?: Context<IncomingMessage, ServerResponse> } }=} locals locals
  26. */
  27. /** @typedef {import("http").IncomingMessage} IncomingMessage */
  28. /** @typedef {import("http").ServerResponse & ExtendedServerResponse} ServerResponse */
  29. /**
  30. * @callback NextFunction
  31. * @param {EXPECTED_ANY=} err error
  32. * @returns {void}
  33. */
  34. /** @typedef {NonNullable<Configuration["watchOptions"]>} WatchOptions */
  35. /** @typedef {Compiler["watching"]} Watching */
  36. /** @typedef {ReturnType<MultiCompiler["watch"]>} MultiWatching */
  37. /** @typedef {import("webpack").OutputFileSystem & { createReadStream?: import("fs").createReadStream, statSync: import("fs").statSync, readFileSync: import("fs").readFileSync }} OutputFileSystem */
  38. /** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
  39. /**
  40. * @callback Callback
  41. * @param {(Stats | MultiStats)=} stats
  42. */
  43. /**
  44. * @typedef {object} ResponseData
  45. * @property {Buffer | ReadStream} data data
  46. * @property {number} byteLength byte length
  47. */
  48. /**
  49. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  50. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  51. * @callback ModifyResponseData
  52. * @param {RequestInternal} req req
  53. * @param {ResponseInternal} res res
  54. * @param {Buffer | ReadStream} data data
  55. * @param {number} byteLength byte length
  56. * @returns {ResponseData}
  57. */
  58. /**
  59. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  60. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  61. * @typedef {object} Context
  62. * @property {boolean} state state
  63. * @property {Stats | MultiStats | undefined} stats stats
  64. * @property {Callback[]} callbacks callbacks
  65. * @property {Options<RequestInternal, ResponseInternal>} options options
  66. * @property {Compiler | MultiCompiler} compiler compiler
  67. * @property {Watching | MultiWatching} watching watching
  68. * @property {Logger} logger logger
  69. * @property {OutputFileSystem} outputFileSystem output file system
  70. */
  71. /**
  72. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  73. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  74. * @typedef {WithoutUndefined<Context<RequestInternal, ResponseInternal>, "watching">} FilledContext
  75. */
  76. /** @typedef {Record<string, string | number> | { key: string, value: number | string }[]} NormalizedHeaders */
  77. /**
  78. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  79. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  80. * @typedef {NormalizedHeaders | ((req: RequestInternal, res: ResponseInternal, context: Context<RequestInternal, ResponseInternal>) => void | undefined | NormalizedHeaders) | undefined} Headers
  81. */
  82. /**
  83. * @template {IncomingMessage} [RequestInternal = IncomingMessage]
  84. * @template {ServerResponse} [ResponseInternal = ServerResponse]
  85. * @typedef {object} Options
  86. * @property {{ [key: string]: string }=} mimeTypes mime types
  87. * @property {(string | undefined)=} mimeTypeDefault mime type default
  88. * @property {(boolean | ((targetPath: string) => boolean))=} writeToDisk write to disk
  89. * @property {string[]=} methods methods
  90. * @property {Headers<RequestInternal, ResponseInternal>=} headers headers
  91. * @property {NonNullable<Configuration["output"]>["publicPath"]=} publicPath public path
  92. * @property {Configuration["stats"]=} stats stats
  93. * @property {boolean=} serverSideRender is server side render
  94. * @property {OutputFileSystem=} outputFileSystem output file system
  95. * @property {(boolean | string)=} index index
  96. * @property {ModifyResponseData<RequestInternal, ResponseInternal>=} modifyResponseData modify response data
  97. * @property {"weak" | "strong"=} etag options to generate etag header
  98. * @property {boolean=} lastModified options to generate last modified header
  99. * @property {(boolean | number | string | { maxAge?: number, immutable?: boolean })=} cacheControl options to generate cache headers
  100. * @property {boolean=} cacheImmutable is cache immutable
  101. * @property {boolean=} forwardError forward error to next middleware
  102. */
  103. /**
  104. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  105. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  106. * @callback Middleware
  107. * @param {RequestInternal} req request
  108. * @param {ResponseInternal} res response
  109. * @param {NextFunction} next next function
  110. * @returns {Promise<void>}
  111. */
  112. /**
  113. * @callback GetFilenameFromUrl
  114. * @param {string} url request URL
  115. * @returns {Promise<FilenameWithExtra | undefined>} a filename with additional information, or `undefined` if nothing is found
  116. */
  117. /**
  118. * @callback WaitUntilValid
  119. * @param {Callback} callback
  120. */
  121. /**
  122. * @callback Invalidate
  123. * @param {Callback} callback
  124. */
  125. /**
  126. * @callback Close
  127. * @param {(err: Error | null | undefined) => void} callback
  128. */
  129. /**
  130. * @template {IncomingMessage} RequestInternal
  131. * @template {ServerResponse} ResponseInternal
  132. * @typedef {object} AdditionalMethods
  133. * @property {GetFilenameFromUrl} getFilenameFromUrl get filename from url
  134. * @property {WaitUntilValid} waitUntilValid wait until valid
  135. * @property {Invalidate} invalidate invalidate
  136. * @property {Close} close close
  137. * @property {Context<RequestInternal, ResponseInternal>} context context
  138. */
  139. /**
  140. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  141. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  142. * @typedef {Middleware<RequestInternal, ResponseInternal> & AdditionalMethods<RequestInternal, ResponseInternal>} API
  143. */
  144. /**
  145. * @template T
  146. * @template {keyof T} K
  147. * @typedef {Omit<T, K> & Partial<T>} WithOptional
  148. */
  149. /**
  150. * @template T
  151. * @template {keyof T} K
  152. * @typedef {T & { [P in K]: NonNullable<T[P]> }} WithoutUndefined
  153. */
  154. /**
  155. * @param {Compiler | MultiCompiler} compiler compiler
  156. * @returns {compiler is MultiCompiler} true when is multi compiler, otherwise false
  157. */
  158. function isMultipleCompiler(compiler) {
  159. return typeof (/** @type {MultiCompiler} */compiler.compilers) !== "undefined";
  160. }
  161. /**
  162. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  163. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  164. * @param {Compiler | MultiCompiler} compiler compiler
  165. * @param {Options<RequestInternal, ResponseInternal>} options options
  166. */
  167. const internalValidate = (compiler, options) => {
  168. const schema = require("./options.json");
  169. const firstCompiler = /** @type {Compiler & { validate: EXPECTED_ANY }} */
  170. isMultipleCompiler(compiler) ? compiler.compilers[0] : compiler;
  171. if (typeof firstCompiler.validate === "function") {
  172. firstCompiler.validate(schema, options, {
  173. name: "Dev Middleware",
  174. baseDataPath: "options"
  175. });
  176. return;
  177. }
  178. // TODO in the next major release bump minimum supported webpack version and remove it in favor of `compiler.validate` (above)
  179. const {
  180. validate
  181. } = require("schema-utils");
  182. validate(/** @type {Schema} */schema, options, {
  183. name: "Dev Middleware",
  184. baseDataPath: "options"
  185. });
  186. };
  187. /** @typedef {Configuration["stats"]} StatsOptions */
  188. /** @typedef {{ children: Configuration["stats"][] }} MultiStatsOptions */
  189. /** @typedef {Exclude<Configuration["stats"], boolean | string | undefined>} StatsObjectOptions */
  190. /**
  191. * @param {StatsOptions} statsOptions stats options
  192. * @returns {StatsObjectOptions} object stats options
  193. */
  194. function normalizeStatsOptions(statsOptions) {
  195. if (typeof statsOptions === "undefined") {
  196. statsOptions = {
  197. preset: "normal"
  198. };
  199. } else if (typeof statsOptions === "boolean") {
  200. statsOptions = statsOptions ? {
  201. preset: "normal"
  202. } : {
  203. preset: "none"
  204. };
  205. } else if (typeof statsOptions === "string") {
  206. statsOptions = {
  207. preset: statsOptions
  208. };
  209. }
  210. return statsOptions;
  211. }
  212. // Compatibility with rspack
  213. /**
  214. * @returns {boolean} true when color supported, otherwise false
  215. */
  216. function isColorSupported() {
  217. const {
  218. env = {},
  219. argv = [],
  220. platform = ""
  221. } = typeof process === "undefined" ? {} : process;
  222. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  223. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  224. const isWindows = platform === "win32";
  225. const isDumbTerminal = env.TERM === "dumb";
  226. const tty = require("node:tty");
  227. const isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
  228. const isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  229. return !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
  230. }
  231. /**
  232. * @template {IncomingMessage} Request
  233. * @template {ServerResponse} Response
  234. * @param {Stats | MultiStats} stats stats
  235. * @param {WithOptional<Context<Request, Response>, "watching" | "outputFileSystem">} context context
  236. */
  237. function printStats(stats, context) {
  238. const {
  239. compiler,
  240. logger,
  241. options
  242. } = context;
  243. logger.log("Compilation finished");
  244. const isMultiCompilerMode = isMultipleCompiler(compiler);
  245. /**
  246. * @type {StatsOptions | MultiStatsOptions | undefined}
  247. */
  248. let statsOptions;
  249. if (typeof options.stats !== "undefined") {
  250. statsOptions = isMultiCompilerMode ? {
  251. children: /** @type {MultiCompiler} */
  252. compiler.compilers.map(() => options.stats)
  253. } : options.stats;
  254. } else {
  255. statsOptions = isMultiCompilerMode ? {
  256. children: /** @type {MultiCompiler} */
  257. compiler.compilers.map(child => child.options.stats)
  258. } : /** @type {Compiler} */compiler.options.stats;
  259. }
  260. if (isMultiCompilerMode) {
  261. /** @type {MultiStatsOptions} */
  262. statsOptions.children = /** @type {MultiStatsOptions} */
  263. statsOptions.children.map(
  264. /**
  265. * @param {StatsOptions} childStatsOptions child stats options
  266. * @returns {StatsObjectOptions} object child stats options
  267. */
  268. childStatsOptions => {
  269. childStatsOptions = normalizeStatsOptions(childStatsOptions);
  270. if (typeof childStatsOptions.colors === "undefined") {
  271. const [firstCompiler] = /** @type {MultiCompiler} */
  272. compiler.compilers;
  273. childStatsOptions.colors =
  274. // rspack compatibility
  275. firstCompiler.webpack.cli && typeof firstCompiler.webpack.cli.isColorSupported === "function" ? firstCompiler.webpack.cli.isColorSupported() : isColorSupported();
  276. }
  277. return childStatsOptions;
  278. });
  279. } else {
  280. statsOptions = normalizeStatsOptions(/** @type {StatsOptions} */statsOptions);
  281. if (typeof statsOptions.colors === "undefined") {
  282. const {
  283. compiler
  284. } = /** @type {{ compiler: Compiler }} */context;
  285. statsOptions.colors =
  286. // rspack compatibility
  287. compiler.webpack.cli && typeof compiler.webpack.cli.isColorSupported === "function" ? compiler.webpack.cli.isColorSupported() : isColorSupported();
  288. }
  289. }
  290. const printedStats = stats.toString(/** @type {StatsObjectOptions} */
  291. statsOptions);
  292. // Avoid extra empty line when `stats: 'none'`
  293. if (printedStats) {
  294. // eslint-disable-next-line no-console
  295. console.log(printedStats);
  296. }
  297. }
  298. const PLUGIN_NAME = "DevMiddleware";
  299. /**
  300. * @template {IncomingMessage} Request
  301. * @template {ServerResponse} Response
  302. * @param {Compiler} compiler compiler
  303. * @param {WithOptional<Context<Request, Response>, "watching" | "outputFileSystem">} context context
  304. */
  305. function hookForWriteToDisk(compiler, context) {
  306. compiler.hooks.emit.tap(PLUGIN_NAME, () => {
  307. // @ts-expect-error
  308. if (compiler.hasWebpackDevMiddlewareAssetEmittedCallback) {
  309. return;
  310. }
  311. compiler.hooks.assetEmitted.tapAsync(PLUGIN_NAME, (file, info, callback) => {
  312. const {
  313. targetPath,
  314. content
  315. } = info;
  316. const {
  317. writeToDisk: filter
  318. } = context.options;
  319. const allowWrite = filter && typeof filter === "function" ? filter(targetPath) : true;
  320. if (!allowWrite) {
  321. return callback();
  322. }
  323. const dir = path.dirname(targetPath);
  324. const name = compiler.options.name ? `Child "${compiler.options.name}": ` : "";
  325. return fs.mkdir(dir, {
  326. recursive: true
  327. }, mkdirError => {
  328. if (mkdirError) {
  329. context.logger.error(`${name}Unable to write "${dir}" directory to disk:\n${mkdirError}`);
  330. return callback(mkdirError);
  331. }
  332. return fs.writeFile(targetPath, content, writeFileError => {
  333. if (writeFileError) {
  334. context.logger.error(`${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError}`);
  335. return callback(writeFileError);
  336. }
  337. context.logger.log(`${name}Asset written to disk: "${targetPath}"`);
  338. return callback();
  339. });
  340. });
  341. });
  342. // @ts-expect-error
  343. compiler.hasWebpackDevMiddlewareAssetEmittedCallback = true;
  344. });
  345. }
  346. /**
  347. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  348. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  349. * @param {Compiler | MultiCompiler} compiler compiler
  350. * @param {Options<RequestInternal, ResponseInternal>=} options options
  351. * @param {boolean} isPlugin true when will use as a plugin, otherwise false
  352. * @returns {API<RequestInternal, ResponseInternal>} webpack dev middleware
  353. */
  354. function wdm(compiler, options = {}, isPlugin = false) {
  355. internalValidate(compiler, options);
  356. const {
  357. mimeTypes
  358. } = options;
  359. if (mimeTypes) {
  360. const {
  361. types
  362. } = mime;
  363. // mimeTypes from user provided options should take priority
  364. // over existing, known types
  365. // @ts-expect-error
  366. mime.types = {
  367. ...types,
  368. ...mimeTypes
  369. };
  370. }
  371. /**
  372. * @type {WithOptional<Context<RequestInternal, ResponseInternal>, "watching" | "outputFileSystem">}
  373. */
  374. const context = {
  375. state: false,
  376. stats: undefined,
  377. callbacks: [],
  378. options,
  379. compiler,
  380. logger: compiler.getInfrastructureLogger("webpack-dev-middleware")
  381. };
  382. // Adding hooks
  383. /**
  384. * @returns {void}
  385. */
  386. const invalid = () => {
  387. if (context.state) {
  388. context.logger.log("Compilation starting...");
  389. }
  390. // We are now in invalid state
  391. context.state = false;
  392. context.stats = undefined;
  393. };
  394. /**
  395. * @param {Stats | MultiStats} stats stats
  396. * @returns {void}
  397. */
  398. const done = stats => {
  399. // We are now on valid state
  400. context.state = true;
  401. context.stats = stats;
  402. // Do the stuff in nextTick, because bundle may be invalidated if a change happened while compiling
  403. process.nextTick(() => {
  404. const {
  405. state,
  406. callbacks
  407. } = context;
  408. // Check if still in valid state
  409. if (!state) {
  410. return;
  411. }
  412. // For plugin support we should print nothing, because webpack/webpack-cli/webpack-dev-server will print them on using `stats.toString()`
  413. if (!isPlugin) {
  414. printStats(stats, context);
  415. }
  416. context.callbacks = [];
  417. // Execute callback that are delayed
  418. for (const callback of callbacks) {
  419. callback(stats);
  420. }
  421. });
  422. };
  423. compiler.hooks.watchRun.tap(PLUGIN_NAME, invalid);
  424. compiler.hooks.invalid.tap(PLUGIN_NAME, invalid);
  425. compiler.hooks.done.tap(PLUGIN_NAME, done);
  426. const compilersToModify = isMultipleCompiler(compiler) ? compiler.compilers.filter(item => item.options.devServer !== false) : [compiler];
  427. if (typeof options.writeToDisk === "function") {
  428. for (const compiler of compilersToModify) {
  429. hookForWriteToDisk(compiler, context);
  430. }
  431. }
  432. // Modify output file system
  433. /** @type {OutputFileSystem} */
  434. let outputFileSystem;
  435. if (context.options.outputFileSystem) {
  436. const {
  437. outputFileSystem: outputFileSystemFromOptions
  438. } = context.options;
  439. outputFileSystem = outputFileSystemFromOptions;
  440. }
  441. // Don't use `memfs` when developer wants to write everything to a disk, because it doesn't make sense.
  442. else if (context.options.writeToDisk === true) {
  443. // Prefer compiler with `devServer` option or fallback to the first one
  444. ({
  445. outputFileSystem
  446. } = /** @type {Compiler & { outputFileSystem: OutputFileSystem }} */
  447. isMultipleCompiler(compiler) ? compilersToModify[0] || compiler.compilers[0] : compiler);
  448. } else {
  449. outputFileSystem = /** @type {OutputFileSystem} */
  450. /** @type {unknown} */memfs.createFsFromVolume(new memfs.Volume());
  451. }
  452. context.outputFileSystem = outputFileSystem;
  453. for (const compiler of compilersToModify) {
  454. compiler.outputFileSystem = outputFileSystem;
  455. }
  456. // Start watching, but only for standalone usage, for plugin usage stats will be printed by external code, for example - webpack-cli
  457. if (!isPlugin) {
  458. /**
  459. * @param {Error | null} err err
  460. */
  461. const errorHandler = err => {
  462. if (err) {
  463. // For example - `writeToDisk` can throw an error and right now it is ends watching.
  464. // We can improve that and keep watching active, but it is require API on webpack side.
  465. // Let's implement that in webpack@5 because it is rare case.
  466. context.logger.error(err);
  467. }
  468. };
  469. if (compiler.watching) {
  470. // Reuse the active watching session instead of starting a second one
  471. // (exposed on `MultiCompiler` since webpack 5.109).
  472. context.watching = compiler.watching;
  473. } else if (isMultipleCompiler(compiler)) {
  474. context.watching = compiler.watch(compiler.compilers.map(compiler => compiler.options.watchOptions || {}), errorHandler);
  475. } else {
  476. context.watching = compiler.watch(compiler.options.watchOptions || {}, errorHandler);
  477. }
  478. }
  479. const filledContext = /** @type {FilledContext<RequestInternal, ResponseInternal>} */
  480. context;
  481. const instance = /** @type {API<RequestInternal, ResponseInternal>} */
  482. middleware(filledContext);
  483. // API
  484. instance.getFilenameFromUrl = url => middleware.getFilenameFromUrl(filledContext, url);
  485. instance.waitUntilValid = (callback = noop) => {
  486. middleware.ready(filledContext, callback);
  487. };
  488. instance.invalidate = (callback = noop) => {
  489. middleware.ready(filledContext, callback);
  490. // TODO for plugin usage (`isPlugin = true`) `watching` is `undefined` and this throws —
  491. // invalidate the host's `compiler.watching` (each child's one for a `MultiCompiler`) instead
  492. filledContext.watching.invalidate();
  493. };
  494. instance.close = (callback = noop) => {
  495. // For plugin usage the host (webpack-cli, webpack-dev-server, etc.) owns `compiler.watch()`,
  496. // so there is no `watching` of our own to close (`compiler.close()` on the host handles it)
  497. if (!filledContext.watching) {
  498. filledContext.logger.warn("The `close` method was called, but there is no own `watching` instance to close. When using the middleware as a plugin, the host owns watching, so use `compiler.close()` instead.");
  499. callback(null);
  500. return;
  501. }
  502. filledContext.watching.close(callback);
  503. };
  504. instance.context = filledContext;
  505. return instance;
  506. }
  507. /**
  508. * @template S
  509. * @template O
  510. * @typedef {object} HapiPluginBase
  511. * @property {(server: S, options: O) => void | Promise<void>} register register
  512. */
  513. /**
  514. * @template S
  515. * @template O
  516. * @typedef {HapiPluginBase<S, O> & { pkg: { name: string }, multiple: boolean }} HapiPlugin
  517. */
  518. /**
  519. * @typedef {Options & { compiler: Compiler | MultiCompiler }} HapiOptions
  520. */
  521. /**
  522. * @template HapiServer
  523. * @template {HapiOptions} HapiOptionsInternal
  524. * @param {boolean=} usePlugin true when need to use as a plugin, otherwise false
  525. * @returns {HapiPlugin<HapiServer, HapiOptionsInternal>} hapi wrapper
  526. */
  527. function hapiWrapper(usePlugin = false) {
  528. return {
  529. pkg: {
  530. name: "webpack-dev-middleware"
  531. },
  532. // Allow to have multiple middleware
  533. multiple: true,
  534. register(server, options) {
  535. const {
  536. compiler,
  537. ...rest
  538. } = options;
  539. if (!compiler) {
  540. throw new Error("The compiler options is required.");
  541. }
  542. const devMiddleware = wdm(compiler, rest, usePlugin);
  543. // @ts-expect-error
  544. if (!server.decorations.server.includes("webpackDevMiddleware")) {
  545. // @ts-expect-error
  546. server.decorate("server", "webpackDevMiddleware", devMiddleware);
  547. }
  548. // @ts-expect-error
  549. // eslint-disable-next-line id-length
  550. server.ext("onRequest", (request, h) => new Promise((resolve, reject) => {
  551. let isFinished = false;
  552. /**
  553. * @param {(string | Buffer)=} data
  554. */
  555. request.raw.res.send = data => {
  556. isFinished = true;
  557. request.raw.res.end(data);
  558. };
  559. /**
  560. * @param {(string | Buffer)=} data
  561. */
  562. request.raw.res.finish = data => {
  563. isFinished = true;
  564. request.raw.res.end(data);
  565. };
  566. devMiddleware(request.raw.req, request.raw.res, error => {
  567. if (error) {
  568. reject(error);
  569. return;
  570. }
  571. if (!isFinished) {
  572. resolve(request);
  573. }
  574. });
  575. }).then(() => h.continue).catch(error => {
  576. throw error;
  577. }));
  578. }
  579. };
  580. }
  581. wdm.hapiWrapper = hapiWrapper;
  582. /**
  583. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  584. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  585. * @param {Compiler | MultiCompiler} compiler compiler
  586. * @param {Options<RequestInternal, ResponseInternal>=} options options
  587. * @param {boolean=} usePlugin whether to use as webpack plugin
  588. * @returns {(ctx: EXPECTED_ANY, next: EXPECTED_FUNCTION) => Promise<void> | void} kow wrapper
  589. */
  590. function koaWrapper(compiler, options = {}, usePlugin = false) {
  591. const devMiddleware = wdm(compiler, options, usePlugin);
  592. /**
  593. * @param {{ req: RequestInternal, res: ResponseInternal & import("./utils").ExpectedServerResponse, status: number, body: string | Buffer | import("fs").ReadStream | { message: string }, state: object }} ctx context
  594. * @param {EXPECTED_FUNCTION} next next
  595. * @returns {Promise<void>}
  596. */
  597. async function webpackDevMiddleware(ctx, next) {
  598. const {
  599. req,
  600. res
  601. } = ctx;
  602. res.locals = ctx.state;
  603. let {
  604. status
  605. } = ctx;
  606. /**
  607. * @returns {number} code
  608. */
  609. res.getStatusCode = () => status;
  610. /**
  611. * @param {number} statusCode status code
  612. */
  613. res.setStatusCode = statusCode => {
  614. status = statusCode;
  615. ctx.status = statusCode;
  616. };
  617. let isFinished = false;
  618. let needNext = false;
  619. try {
  620. await new Promise(
  621. /**
  622. * @param {(value: void) => void} resolve resolve
  623. * @param {(reason?: Error) => void} reject reject
  624. */
  625. (resolve, reject) => {
  626. /**
  627. * @param {import("fs").ReadStream} stream readable stream
  628. */
  629. res.stream = stream => {
  630. let resolved = false;
  631. /**
  632. * @param {Error=} err error
  633. */
  634. const onEvent = err => {
  635. if (resolved) return;
  636. resolved = true;
  637. stream.removeListener("error", onEvent);
  638. stream.removeListener("readable", onEvent);
  639. if (err) {
  640. reject(err);
  641. return;
  642. }
  643. ctx.body = stream;
  644. isFinished = true;
  645. resolve();
  646. };
  647. stream.once("error", onEvent);
  648. stream.once("readable", onEvent);
  649. // Empty stream
  650. stream.once("end", onEvent);
  651. };
  652. /**
  653. * @param {string | Buffer} data data
  654. */
  655. res.send = data => {
  656. ctx.body = data;
  657. isFinished = true;
  658. resolve();
  659. };
  660. /**
  661. * @param {(string | Buffer)=} data data
  662. */
  663. res.finish = data => {
  664. ctx.status = status;
  665. res.end(data);
  666. isFinished = true;
  667. resolve();
  668. };
  669. devMiddleware(req, res, err => {
  670. if (err) {
  671. reject(err);
  672. return;
  673. }
  674. needNext = true;
  675. if (!isFinished) {
  676. resolve();
  677. }
  678. });
  679. });
  680. } catch (err) {
  681. if (options?.forwardError) {
  682. await next();
  683. // need the return for prevent to execute the code below and override the status and body set by user in the next middleware
  684. return;
  685. }
  686. ctx.status = /** @type {Error & { statusCode: number }} */err.statusCode || /** @type {Error & { status: number }} */err.status || 500;
  687. ctx.body = {
  688. message: /** @type {Error} */err.message
  689. };
  690. }
  691. if (needNext) {
  692. await next();
  693. }
  694. }
  695. webpackDevMiddleware.devMiddleware = devMiddleware;
  696. return webpackDevMiddleware;
  697. }
  698. wdm.koaWrapper = koaWrapper;
  699. /**
  700. * @template {IncomingMessage} [RequestInternal=IncomingMessage]
  701. * @template {ServerResponse} [ResponseInternal=ServerResponse]
  702. * @param {Compiler | MultiCompiler} compiler compiler
  703. * @param {Options<RequestInternal, ResponseInternal>=} options options
  704. * @param {boolean=} usePlugin true when need to use as a plugin, otherwise false
  705. * @returns {(ctx: EXPECTED_ANY, next: EXPECTED_FUNCTION) => Promise<void> | void} hono wrapper
  706. */
  707. function honoWrapper(compiler, options = {}, usePlugin = false) {
  708. const devMiddleware = wdm(compiler, options, usePlugin);
  709. /**
  710. * @param {{ env: EXPECTED_ANY, body: EXPECTED_ANY, json: EXPECTED_ANY, status: EXPECTED_ANY, set: EXPECTED_ANY, req: RequestInternal & import("./utils").ExpectedIncomingMessage & { header: (name: string) => string }, res: ResponseInternal & import("./utils").ExpectedServerResponse & { headers: EXPECTED_ANY, status: EXPECTED_ANY } }} context context
  711. * @param {EXPECTED_FUNCTION} next next function
  712. * @returns {Promise<void>}
  713. */
  714. async function webpackDevMiddleware(context, next) {
  715. const {
  716. req,
  717. res
  718. } = context;
  719. context.set("webpack", {
  720. devMiddleware: devMiddleware.context
  721. });
  722. /**
  723. * @returns {string | undefined} method
  724. */
  725. req.getMethod = () => context.req.method;
  726. /**
  727. * @param {string} name name
  728. * @returns {string | string[] | undefined} header value
  729. */
  730. req.getHeader = name => context.req.header(name);
  731. /**
  732. * @returns {string | undefined} URL
  733. */
  734. req.getURL = () => context.req.url;
  735. let {
  736. status
  737. } = context.res;
  738. /**
  739. * @returns {number} code code
  740. */
  741. res.getStatusCode = () => status;
  742. /**
  743. * @param {number} code code
  744. */
  745. res.setStatusCode = code => {
  746. status = code;
  747. };
  748. /**
  749. * @param {string} name header name
  750. * @returns {string | string[] | undefined} header
  751. */
  752. res.getHeader = name => context.res.headers.get(name);
  753. /**
  754. * @param {string} name header name
  755. * @param {string | number | Readonly<string[]>} value value
  756. * @returns {ResponseInternal & import("./utils").ExpectedServerResponse & { headers: EXPECTED_ANY, status: EXPECTED_ANY }} response
  757. */
  758. res.setHeader = (name, value) => {
  759. context.res.headers.append(name, value);
  760. return context.res;
  761. };
  762. /**
  763. * @param {string} name header name
  764. */
  765. res.removeHeader = name => {
  766. context.res.headers.delete(name);
  767. };
  768. /**
  769. * @returns {string[]} response headers
  770. */
  771. res.getResponseHeaders = () => [...context.res.headers.keys()];
  772. /**
  773. * @returns {ServerResponse} server response
  774. */
  775. res.getOutgoing = () => context.env.outgoing;
  776. res.setState = () => {
  777. // Do nothing, because we set it before
  778. };
  779. res.getHeadersSent = () => context.env.outgoing.headersSent;
  780. let body;
  781. let isFinished = false;
  782. try {
  783. await new Promise(
  784. /**
  785. * @param {(value: void) => void} resolve resolve
  786. * @param {(reason?: Error) => void} reject reject
  787. */
  788. (resolve, reject) => {
  789. /**
  790. * @param {import("fs").ReadStream} stream readable stream
  791. */
  792. res.stream = stream => {
  793. let isResolved = false;
  794. /**
  795. * @param {Error=} err err
  796. */
  797. const onEvent = err => {
  798. if (isResolved) return;
  799. isResolved = true;
  800. stream.removeListener("error", onEvent);
  801. stream.removeListener("readable", onEvent);
  802. stream.removeListener("end", onEvent);
  803. if (err) {
  804. stream.destroy();
  805. reject(err);
  806. return;
  807. }
  808. // Wrap as a Web ReadableStream so `@hono/node-server` takes its
  809. // fast path and Node's internal `Readable.toWeb` adapter is not
  810. // involved (it races on late `error`/`close` from fs streams).
  811. body = nodeReadableToWebStream(stream);
  812. isFinished = true;
  813. resolve();
  814. };
  815. stream.once("error", onEvent);
  816. stream.once("readable", onEvent);
  817. // Empty stream
  818. stream.once("end", onEvent);
  819. if (stream.pending === false) {
  820. onEvent();
  821. }
  822. };
  823. /**
  824. * @param {string | Buffer} data data
  825. */
  826. res.send = data => {
  827. // Hono sets `Content-Length` by default
  828. context.res.headers.delete("Content-Length");
  829. body = data;
  830. isFinished = true;
  831. resolve();
  832. };
  833. /**
  834. * @param {(string | Buffer)=} data data
  835. */
  836. res.finish = data => {
  837. const isDataExist = typeof data !== "undefined";
  838. // Hono sets `Content-Length` by default
  839. if (isDataExist) {
  840. context.res.headers.delete("Content-Length");
  841. }
  842. body = isDataExist ? data : null;
  843. isFinished = true;
  844. resolve();
  845. };
  846. devMiddleware(req, res, err => {
  847. if (err) {
  848. reject(err);
  849. return;
  850. }
  851. if (!isFinished) {
  852. resolve();
  853. }
  854. });
  855. });
  856. } catch (err) {
  857. if (options?.forwardError) {
  858. await next();
  859. // need the return for prevent to execute the code below and override the status and body set by user in the next middleware
  860. return;
  861. }
  862. context.status(500);
  863. return context.json({
  864. message: /** @type {Error} */err.message
  865. });
  866. }
  867. if (typeof body !== "undefined") {
  868. return context.body(body, status);
  869. }
  870. await next();
  871. }
  872. webpackDevMiddleware.devMiddleware = devMiddleware;
  873. return webpackDevMiddleware;
  874. }
  875. wdm.honoWrapper = honoWrapper;
  876. module.exports = wdm;