webpack-dev-middleware
Version:
A development middleware for webpack
1,488 lines • 54.9 kB
JavaScript
const fs = require("node:fs");
const path = require("node:path");
// `stream/web` is flagged experimental by the n/eslint plugin until Node 21,
// but `ReadableStream` is stable in practice on Node 20.9+ (our minimum) and
// already pulled in by hono/web frameworks we integrate with.
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const {
ReadableStream
} = require("node:stream/web");
const memfs = require("memfs");
const {
createHot
} = require("./hot");
const {
HOT_DEFAULT_PATH
} = require("./hot");
const middleware = require("./middleware");
const {
createMimeTypes,
injectHotClient,
nodeReadableToWebStream
} = require("./utils");
const noop = () => {};
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").MultiCompiler} MultiCompiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("webpack").Configuration} Configuration */
/** @typedef {import("webpack").Stats} Stats */
/** @typedef {import("webpack").MultiStats} MultiStats */
/** @typedef {import("fs").ReadStream} ReadStream */
/** @typedef {import("stream").Readable} Readable */
/** @typedef {import("./middleware").FilenameWithExtra} FilenameWithExtra */
/** @typedef {import("./hot").HotOptions} HotOptions */
/** @typedef {import("./hot").HotInstance} HotInstance */
/** @typedef {import("./utils").MimeTypes} MimeTypes */
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
// eslint-disable-next-line jsdoc/reject-function-type
/** @typedef {Function} EXPECTED_FUNCTION */
/**
* @typedef {object} ExtendedServerResponse
* @property {{ webpack?: { devMiddleware?: Context<IncomingMessage, ServerResponse> } }=} locals locals
*/
/** @typedef {import("http").IncomingMessage} IncomingMessage */
/** @typedef {import("http").ServerResponse & ExtendedServerResponse} ServerResponse */
/**
* @callback NextFunction
* @param {EXPECTED_ANY=} err error
* @returns {void}
*/
/** @typedef {NonNullable<Configuration["watchOptions"]>} WatchOptions */
/** @typedef {Compiler["watching"]} Watching */
/** @typedef {ReturnType<MultiCompiler["watch"]>} MultiWatching */
/** @typedef {import("webpack").OutputFileSystem & { createReadStream?: import("fs").createReadStream, statSync: import("fs").statSync, readFileSync: import("fs").readFileSync }} OutputFileSystem */
/** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
/**
* @callback Callback
* @param {(Stats | MultiStats)=} stats
*/
/**
* @typedef {object} ResponseData
* @property {Buffer | Readable} data data
* @property {number} byteLength byte length
*/
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @callback ModifyResponseData
* @param {RequestInternal} req req
* @param {ResponseInternal} res res
* @param {Buffer | Readable} data the body: a `Buffer`, a `ReadStream` of the file or of one range of it, or for more than one range a `Readable` of the `multipart/byteranges` body
* @param {number} byteLength byte length
* @returns {ResponseData}
*/
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @typedef {object} Context
* @property {boolean} state state
* @property {Stats | MultiStats | undefined} stats stats
* @property {Callback[]} callbacks callbacks
* @property {NormalizedOptions<RequestInternal, ResponseInternal>} options options, with `cache` and `mime` filled in
* @property {Compiler | MultiCompiler} compiler compiler
* @property {Watching | MultiWatching} watching watching
* @property {Logger} logger logger
* @property {OutputFileSystem} outputFileSystem output file system
* @property {HotInstance=} hot hot module replacement instance
* @property {MimeTypes} mimeTypes extension to media type, for this instance
*/
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @typedef {WithoutUndefined<Context<RequestInternal, ResponseInternal>, "watching">} FilledContext
*/
/** @typedef {Record<string, string | number> | { key: string, value: number | string }[]} NormalizedHeaders */
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @typedef {NormalizedHeaders | ((req: RequestInternal, res: ResponseInternal, context: Context<RequestInternal, ResponseInternal>) => void | undefined | NormalizedHeaders) | undefined} Headers
*/
/**
* @typedef {object} CacheOptions
* @property {("weak" | "strong")=} etag generate an `ETag` header, weak or strong
* @property {boolean=} lastModified generate a `Last-Modified` header from the file system's value
* @property {(boolean | number | string | { maxAge?: number, immutable?: boolean })=} control set a `Cache-Control` header
* @property {boolean=} immutable send `Cache-Control: public, max-age=31536000, immutable` for an asset with a hash in its name
*/
/**
* The options as everything below the entry point sees them: the legacy flat
* spellings have been folded in, so `cache` and `mime` are always objects.
* @template {IncomingMessage} [RequestInternal = IncomingMessage]
* @template {ServerResponse} [ResponseInternal = ServerResponse]
* @typedef {Options<RequestInternal, ResponseInternal> & { cache: CacheOptions, mime: MimeOptions }} NormalizedOptions
*/
/**
* @typedef {object} MimeOptions
* @property {{ [key: string]: string }=} types register custom media types or extension mappings
* @property {string=} default the media type to fall back on when the content type cannot be determined
*/
/**
* @template {IncomingMessage} [RequestInternal = IncomingMessage]
* @template {ServerResponse} [ResponseInternal = ServerResponse]
* @typedef {object} Options
* @property {CacheOptions=} cache how responses are cached
* @property {MimeOptions=} mime how a file's media type is decided
* @property {{ [key: string]: string }=} mimeTypes deprecated, use `mime.types`
* @property {(string | undefined)=} mimeTypeDefault deprecated, use `mime.default`
* @property {(boolean | ((targetPath: string) => boolean))=} writeToDisk write to disk
* @property {string[]=} methods methods
* @property {Headers<RequestInternal, ResponseInternal>=} headers headers
* @property {NonNullable<Configuration["output"]>["publicPath"]=} publicPath public path
* @property {Configuration["stats"]=} stats stats
* @property {boolean=} serverSideRender is server side render
* @property {OutputFileSystem=} outputFileSystem output file system
* @property {(boolean | string)=} index index
* @property {ModifyResponseData<RequestInternal, ResponseInternal>=} modifyResponseData modify response data
* @property {("weak" | "strong")=} etag deprecated, use `cache.etag`
* @property {boolean=} lastModified deprecated, use `cache.lastModified`
* @property {(boolean | number | string | { maxAge?: number, immutable?: boolean })=} cacheControl deprecated, use `cache.control`
* @property {boolean=} cacheImmutable deprecated, use `cache.immutable`
* @property {boolean=} forwardError forward error to next middleware
* @property {(boolean | HotOptions)=} hot enable hot module replacement
*/
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @callback Middleware
* @param {RequestInternal} req request
* @param {ResponseInternal} res response
* @param {NextFunction} next next function
* @returns {Promise<void>}
*/
/**
* @callback GetFilenameFromUrl
* @param {string} url request URL
* @returns {Promise<FilenameWithExtra | undefined>} a filename with additional information, or `undefined` if nothing is found
*/
/**
* @callback WaitUntilValid
* @param {Callback} callback
*/
/**
* @callback Invalidate
* @param {Callback} callback
*/
/**
* @callback Attach
* @param {import("node:http").Server} server HTTP server the `hot.transport: "ws"` endpoint answers upgrades on
*/
/**
* @callback HandleUpgrade
* @param {IncomingMessage} req the request being upgraded
* @param {import("node:stream").Duplex} socket the request's socket
* @param {Buffer} head the first packet of the upgraded stream
* @returns {boolean} true when the endpoint answered the upgrade, false when the request was not its own — or `hot` is off, or the transport answers no upgrades
*/
/**
* @callback Publish
* @param {import("./hot").Payload | import("./hot").CustomPayload} payload the payload to publish to every client
*/
/**
* @callback PublishTo
* @param {EXPECTED_ANY} client a client `onConnect` handed over
* @param {import("./hot").Payload | import("./hot").CustomPayload} payload the payload to publish to it
*/
/**
* @callback OnConnect
* @param {(client: EXPECTED_ANY, req: IncomingMessage) => void} fn called with each client once it has joined, and the request it joined with, before anything is published to it
*/
/**
* @callback Close
* @param {(err: Error | null | undefined) => void} callback
*/
/**
* @template {IncomingMessage} RequestInternal
* @template {ServerResponse} ResponseInternal
* @typedef {object} AdditionalMethods
* @property {GetFilenameFromUrl} getFilenameFromUrl get filename from url
* @property {WaitUntilValid} waitUntilValid wait until valid
* @property {Invalidate} invalidate invalidate
* @property {Attach} attach answer WebSocket upgrades on this server
* @property {HandleUpgrade} handleUpgrade answer one WebSocket upgrade, for a server that owns its own `upgrade` event
* @property {OnConnect} onConnect called with each client that joins, and the request it joined with
* @property {Publish} publish put a payload of your own on the hot stream, for what a server measures itself — a no-op when `hot` is off
* @property {PublishTo} publishTo put a payload on the hot stream for one client, for answering a single connection — whichever transport is carrying it, and a no-op when `hot` is off
* @property {(string | false | undefined)=} token the secret the hot endpoint's client is given, for a client of your own to put on the url; false when there is none, undefined when `hot` is off
* @property {Close} close close
* @property {Context<RequestInternal, ResponseInternal>} context context
*/
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @typedef {Middleware<RequestInternal, ResponseInternal> & AdditionalMethods<RequestInternal, ResponseInternal>} API
*/
/**
* @template T
* @template {keyof T} K
* @typedef {Omit<T, K> & Partial<T>} WithOptional
*/
/**
* @template T
* @template {keyof T} K
* @typedef {T & { [P in K]: NonNullable<T[P]> }} WithoutUndefined
*/
/**
* @param {Compiler | MultiCompiler} compiler compiler
* @returns {compiler is MultiCompiler} true when is multi compiler, otherwise false
*/
function isMultipleCompiler(compiler) {
return typeof (/** @type {MultiCompiler} */compiler.compilers) !== "undefined";
}
/**
* Throw unless the options match the schema.
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @param {Compiler | MultiCompiler} compiler compiler
* @param {Options<RequestInternal, ResponseInternal>} options options
* @returns {void}
*/
const internalValidate = (compiler, options) => {
const firstCompiler = /** @type {Compiler & { validate: EXPECTED_ANY }} */
isMultipleCompiler(compiler) ? compiler.compilers[0] : compiler;
// `compiler.hooks.validate` and `compiler.validate`'s lazy-schema and
// precompiled-check parameters landed together in webpack 5.106, so the hook
// doubles as the feature probe for them. Probed with `in` because rspack's
// `compiler.hooks` throws on reading a hook it doesn't implement.
if ("validate" in firstCompiler.hooks) {
firstCompiler.validate(() => require("./options.json"), options, {
name: "Dev Middleware",
baseDataPath: "options"
},
/**
* @param {Options<RequestInternal, ResponseInternal>} value options to check
* @returns {boolean} whether they match the schema
*/
value => require("./options.check")(value));
return;
}
// TODO in the next major release raise the `webpack` peer range to ^5.106.0
// and delete this fallback, the `Schema` typedef above, and the
// `schema-utils` dependency with it — `compiler.validate` is the whole of
// what validation needs from 5.106 on, and webpack carries its own copy of
// `schema-utils` to do it with.
//
// The precompiled validator answers the common case in ~2ms, against the
// ~160ms `schema-utils` spends compiling the schema on its first call, so
// `./options.json` stays unread until something is actually wrong.
if (require("./options.check")(options)) {
return;
}
const {
validate
} = require("schema-utils");
validate(/** @type {Schema} */require("./options.json"), options, {
name: "Dev Middleware",
baseDataPath: "options"
});
};
// Where the six flat options that became `cache` and `mime` are translated, so
// everything below reads one shape. The legacy keys are left on the object
// rather than deleted: `instance.context.options` is reachable, and something
// may still be reading them.
//
// TODO in the next major release remove this, the legacy properties and the
// warnings, and take `cache` and `mime` as the only spellings.
const LEGACY_GROUPED = [["etag", "cache", "etag"], ["lastModified", "cache", "lastModified"], ["cacheControl", "cache", "control"], ["cacheImmutable", "cache", "immutable"], ["mimeTypes", "mime", "types"], ["mimeTypeDefault", "mime", "default"]];
/**
* @template {IncomingMessage} RequestInternal
* @template {ServerResponse} ResponseInternal
* @param {Options<RequestInternal, ResponseInternal>} options the options as they were given
* @param {Logger} logger logger
* @returns {NormalizedOptions<RequestInternal, ResponseInternal>} the same options with `cache` and `mime` filled in
*/
function normalizeOptions(options, logger) {
/** @type {EXPECTED_ANY} */
const cache = {
...options.cache,
// An object-form `control` is read on every response, so it is copied: a
// caller changing theirs after the middleware exists must not change the
// header it sends.
...(options.cache && typeof options.cache.control === "object" && options.cache.control !== null ? {
control: {
...options.cache.control
}
} : {})
};
/** @type {EXPECTED_ANY} */
const mime = {
...options.mime
};
/** @type {EXPECTED_ANY} */
const groups = {
cache,
mime
};
for (const [legacy, group, key] of LEGACY_GROUPED) {
if (!Object.hasOwn(options, legacy)) {
continue;
}
// The grouped spelling wins. A migration that sets the new one and forgets
// to delete the old would otherwise silently not apply.
if (Object.hasOwn(groups[group], key)) {
logger.warn(`The '${legacy}' option is deprecated and '${group}.${key}' is set as well, so '${group}.${key}' is what applies. Remove '${legacy}'.`);
continue;
}
logger.warn(`The '${legacy}' option is deprecated and will be removed in the next major release. Use '${group}.${key}' instead.`);
groups[group][key] = options[(/** @type {keyof typeof options} */legacy)];
}
return {
...options,
cache,
mime
};
}
/** @typedef {Configuration["stats"]} StatsOptions */
/** @typedef {{ children: Configuration["stats"][] }} MultiStatsOptions */
/** @typedef {Exclude<Configuration["stats"], boolean | string | undefined>} StatsObjectOptions */
/**
* @param {StatsOptions} statsOptions stats options
* @returns {StatsObjectOptions} object stats options
*/
function normalizeStatsOptions(statsOptions) {
if (typeof statsOptions === "undefined") {
statsOptions = {
preset: "normal"
};
} else if (typeof statsOptions === "boolean") {
statsOptions = statsOptions ? {
preset: "normal"
} : {
preset: "none"
};
} else if (typeof statsOptions === "string") {
statsOptions = {
preset: statsOptions
};
}
return statsOptions;
}
// Compatibility with rspack
/**
* @returns {boolean} true when color supported, otherwise false
*/
function isColorSupported() {
const {
env = {},
argv = [],
platform = ""
} = typeof process === "undefined" ? {} : process;
const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
const isForced = "FORCE_COLOR" in env || argv.includes("--color");
const isWindows = platform === "win32";
const isDumbTerminal = env.TERM === "dumb";
const tty = require("node:tty");
const isCompatibleTerminal = tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
const isCI = "CI" in env && ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
return !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
}
/**
* @template {IncomingMessage} Request
* @template {ServerResponse} Response
* @param {Stats | MultiStats} stats stats
* @param {WithOptional<Context<Request, Response>, "watching" | "outputFileSystem">} context context
*/
function printStats(stats, context) {
const {
compiler,
logger,
options
} = context;
logger.log("Compilation finished");
const isMultiCompilerMode = isMultipleCompiler(compiler);
/**
* @type {StatsOptions | MultiStatsOptions | undefined}
*/
let statsOptions;
if (typeof options.stats !== "undefined") {
statsOptions = isMultiCompilerMode ? {
children: /** @type {MultiCompiler} */
compiler.compilers.map(() => options.stats)
} : options.stats;
} else {
statsOptions = isMultiCompilerMode ? {
children: /** @type {MultiCompiler} */
compiler.compilers.map(child => child.options.stats)
} : /** @type {Compiler} */compiler.options.stats;
}
if (isMultiCompilerMode) {
/** @type {MultiStatsOptions} */
statsOptions.children = /** @type {MultiStatsOptions} */
statsOptions.children.map(
/**
* @param {StatsOptions} childStatsOptions child stats options
* @returns {StatsObjectOptions} object child stats options
*/
childStatsOptions => {
childStatsOptions = normalizeStatsOptions(childStatsOptions);
if (typeof childStatsOptions.colors === "undefined") {
const [firstCompiler] = /** @type {MultiCompiler} */
compiler.compilers;
childStatsOptions.colors =
// rspack compatibility
firstCompiler.webpack.cli && typeof firstCompiler.webpack.cli.isColorSupported === "function" ? firstCompiler.webpack.cli.isColorSupported() : isColorSupported();
}
return childStatsOptions;
});
} else {
statsOptions = normalizeStatsOptions(/** @type {StatsOptions} */statsOptions);
if (typeof statsOptions.colors === "undefined") {
const {
compiler
} = /** @type {{ compiler: Compiler }} */context;
statsOptions.colors =
// rspack compatibility
compiler.webpack.cli && typeof compiler.webpack.cli.isColorSupported === "function" ? compiler.webpack.cli.isColorSupported() : isColorSupported();
}
}
const printedStats = stats.toString(/** @type {StatsObjectOptions} */
statsOptions);
// Avoid extra empty line when `stats: 'none'`
if (printedStats) {
// eslint-disable-next-line no-console
console.log(printedStats);
}
}
const PLUGIN_NAME = "DevMiddleware";
/**
* Whether a file system is the disk: Node.js `fs`, as Rspack's output file
* system, or `graceful-fs` wrapping it, as webpack's.
* @param {OutputFileSystem} fileSystem a file system
* @returns {boolean} true when it writes to disk
*/
function isDiskFileSystem(fileSystem) {
return /** @type {unknown} */fileSystem === fs || typeof (/** @type {EXPECTED_ANY} */fileSystem.gracefulify) === "function";
}
// TODO in the next major release replace this file system with one of:
// - a webpack hook for additional outputs, where the middleware adds the disk
// with `writeToDisk` as its filter and webpack writes and cleans both itself;
// - a file system helper webpack exports, mirroring one file system to another;
// - `writeToDisk: true` only, with the disk as webpack's only output and files
// served from it; deprecate the function form first, as it needs this layer.
/**
* The output file system webpack is given when `writeToDisk` writes to disk
* besides the file system files are served from. Writes go to that one and,
* for the paths `writeToDisk` takes, to disk; removals reach both, and
* listings and `lstat` see the disk too. So webpack's own `output.clean`
* cleans the disk as it cleans its output. What webpack reads to decide
* whether to write a file comes from the served file system alone.
* @template {IncomingMessage} Request
* @template {ServerResponse} Response
* @param {OutputFileSystem} outputFileSystem the file system files are served from
* @param {WithOptional<Context<Request, Response>, "watching" | "outputFileSystem">} context context
* @param {Compiler[]} compilers the compilers given this file system
* @returns {OutputFileSystem} the file system writing to both
*/
function createDiskWritingFileSystem(outputFileSystem, context, compilers) {
/** @type {EXPECTED_ANY} */
const served = outputFileSystem;
/** @type {WeakMap<Compiler, Compilation>} */
const compilations = new WeakMap();
for (const compiler of compilers) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
compilations.set(compiler, compilation);
});
}
/**
* @param {string} targetPath absolute path of a file
* @returns {boolean} true when it is written to disk
*/
const takes = targetPath => {
const {
writeToDisk
} = context.options;
return typeof writeToDisk === "function" ? writeToDisk(targetPath) : true;
};
/**
* Whether `output.clean` keeps a file in a compiler's output, decided as
* `CleanPlugin` decides it: its `keep` hook first, then `clean.keep`.
* @param {Compiler} compiler compiler
* @param {string} file path relative to the output, with `/` separators
* @returns {boolean} true when it is kept
*/
const isKept = (compiler, file) => {
const {
clean
} = compiler.options.output;
if (!clean || typeof clean === "object" && clean.dry) {
return true;
}
const compilation = compilations.get(compiler);
const {
CleanPlugin
} = compiler.webpack;
const byHook = compilation && CleanPlugin && CleanPlugin.getCompilationHooks ? CleanPlugin.getCompilationHooks(compilation).keep.call(file) : undefined;
if (byHook !== undefined) {
return byHook;
}
const keep = typeof clean === "object" ? clean.keep : undefined;
if (keep === undefined) {
return false;
}
if (typeof keep === "string") {
return file.startsWith(keep);
}
if (keep instanceof RegExp) {
return keep.test(file);
}
if (typeof keep === "function") {
return Boolean(keep(file));
}
// A glob condition is not matched here, so what it might keep is kept.
return true;
};
/**
* Whether `output.clean` would remove a disk copy, left by an earlier
* session, of a file `writeToDisk` leaves out: one webpack counts as current.
* @param {string} targetPath absolute path of a file
* @returns {boolean} true when it is cleaned
*/
const isCleaned = targetPath => compilers.some(compiler => {
const file = path.relative(compiler.outputPath, targetPath);
return !file.startsWith("..") && !path.isAbsolute(file) && !isKept(compiler, file.replaceAll("\\", "/"));
});
/**
* A write on the served file system, repeated on disk for the paths
* `writeToDisk` takes once it succeeded there.
* @param {"writeFile" | "symlink" | "chmod" | "utimes"} name the method
* @param {number} pathIndex which argument is the path written
* @returns {(...args: EXPECTED_ANY[]) => void} the method
*/
const mirror = (name, pathIndex) => (...args) => {
const callback = args.pop();
const targetPath = args[pathIndex];
served[name](...args, (/** @type {Error | null=} */err) => {
if (err) {
return callback(err);
}
if (!takes(targetPath)) {
return isCleaned(targetPath) ? fs.unlink(targetPath, () => callback()) : callback();
}
const dir = path.dirname(targetPath);
const write = () => /** @type {EXPECTED_ANY} */fs[name](...args, (/** @type {Error | null} */writeError) => {
if (writeError) {
context.logger.error(`Unable to write "${targetPath}" asset to disk:\n${writeError}`);
return callback(writeError);
}
context.logger.log(`Asset written to disk: "${targetPath}"`);
callback();
});
fs.mkdir(dir, {
recursive: true
}, mkdirError => {
if (mkdirError) {
context.logger.error(`Unable to write "${dir}" directory to disk:\n${mkdirError}`);
return callback(mkdirError);
}
// A link replaces whatever was there, as webpack replaces it.
if (name === "symlink") {
return fs.unlink(targetPath, write);
}
write();
});
});
};
/**
* A removal on both, done once either removed it.
* @param {"unlink" | "rmdir"} name the method
* @returns {(targetPath: string, callback: (err?: Error | null) => void) => void} the method
*/
const removeFromBoth = name => (targetPath, callback) => {
const run = (/** @type {EXPECTED_ANY} */fileSystem) => new Promise(resolve => {
if (fileSystem[name]) {
fileSystem[name](targetPath, (/** @type {Error | null} */err) => {
resolve(err || null);
});
} else {
resolve(undefined);
}
});
Promise.all([run(served), run(fs)]).then(errors => {
callback(errors.includes(null) ? null : errors.find(Boolean));
});
};
// What is not here, such as `readFile`, `stat` and `mkdir`, reaches the
// served file system alone; `lstat` and `readdir` see the disk too, which is
// how `output.clean` finds what an earlier session left there.
/** @type {Record<string, EXPECTED_ANY>} */
const methods = {
writeFile: mirror("writeFile", 0),
unlink: removeFromBoth("unlink"),
rmdir: removeFromBoth("rmdir"),
lstat: (/** @type {string} */targetPath, /** @type {(err: Error | null, stats?: EXPECTED_ANY) => void} */callback) => (served.lstat || served.stat).call(served, targetPath, (/** @type {NodeJS.ErrnoException | null} */err, /** @type {EXPECTED_ANY} */stats) => err && err.code === "ENOENT" ? fs.lstat(targetPath, callback) : callback(err, stats)),
readdir: (/** @type {string} */targetPath, /** @type {(err: Error | null, entries?: string[]) => void} */callback) => {
/**
* @param {Error | null} servedError error from the served file system
* @param {string[]=} servedEntries entries on the served file system
* @returns {void}
*/
const withDisk = (servedError, servedEntries) => fs.readdir(targetPath, (diskError, diskEntries) => servedError && diskError ? callback(servedError) : callback(null, [...new Set([...(servedEntries || []), ...(diskEntries || [])])]));
if (!served.readdir) {
return withDisk(null, []);
}
served.readdir(targetPath, withDisk);
}
};
// Methods webpack can do without stay out where the served file system lacks them.
for (const [name, pathIndex] of (/** @type {const} */[["symlink", 1], ["chmod", 0], ["utimes", 0]])) {
if (served[name]) {
methods[name] = mirror(name, pathIndex);
}
}
return /** @type {OutputFileSystem} */Object.create(outputFileSystem, Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, {
value
}])));
}
// TODO in the next major release remove the standalone mode, where the
// middleware starts `compiler.watch()` and prints stats itself, and keep only
// the plugin one, where the host (webpack-cli, webpack-dev-server) owns
// watching and stats, as webpack-dev-server uses it: drop `isPlugin` here and
// `usePlugin` from the framework wrappers, with the watching, `close()` and
// `printStats` paths that exist only for standalone use.
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @param {Compiler | MultiCompiler} compiler compiler
* @param {Options<RequestInternal, ResponseInternal>=} options options
* @param {boolean} isPlugin true when will use as a plugin, otherwise false
* @returns {API<RequestInternal, ResponseInternal>} webpack dev middleware
*/
function wdm(compiler, options = {}, isPlugin = false) {
internalValidate(compiler, options);
const logger = compiler.getInfrastructureLogger("webpack-dev-middleware");
// Before anything reads them, so only one shape reaches the rest of the
// module even when the legacy flat names were used.
const normalizedOptions = normalizeOptions(options, logger);
/**
* @type {WithOptional<Context<RequestInternal, ResponseInternal>, "watching" | "outputFileSystem">}
*/
const context = {
state: false,
stats: undefined,
callbacks: [],
options: normalizedOptions,
compiler,
logger,
// Per instance, with the `mime.types` option over the known extensions
// rather than written into them: the table `mime-db` exports is one object
// shared by everything in the process that requires it.
mimeTypes: createMimeTypes(normalizedOptions.mime.types)
};
// Adding hooks
/**
* @returns {void}
*/
const invalid = () => {
if (context.state) {
context.logger.log("Compilation starting...");
}
// We are now in invalid state
context.state = false;
context.stats = undefined;
};
/**
* @param {Stats | MultiStats} stats stats
* @returns {void}
*/
const done = stats => {
// We are now on valid state
context.state = true;
context.stats = stats;
// Do the stuff in nextTick, because bundle may be invalidated if a change happened while compiling
process.nextTick(() => {
const {
state,
callbacks
} = context;
// Check if still in valid state
if (!state) {
return;
}
// For plugin support we should print nothing, because webpack/webpack-cli/webpack-dev-server will print them on using `stats.toString()`
if (!isPlugin) {
printStats(stats, context);
}
context.callbacks = [];
// Execute callback that are delayed
for (const callback of callbacks) {
callback(stats);
}
});
};
compiler.hooks.watchRun.tap(PLUGIN_NAME, invalid);
compiler.hooks.invalid.tap(PLUGIN_NAME, invalid);
compiler.hooks.done.tap(PLUGIN_NAME, done);
if (options.hot) {
context.hot = createHot(compiler, options.hot === true ? {} : options.hot, options.stats);
// The hot transport ends with the compiler: in plugin mode the host owns
// watching, so `compiler.close()` may be its only shutdown call and
// `close()` never comes. Closing twice is a no-op.
const closeHot = () => {
if (context.hot) {
context.hot.close();
context.hot = undefined;
}
};
// TODO in the next major release, once the webpack peer dependency has
// `MultiCompiler.hooks.shutdown`, tap `compiler.hooks.shutdown` alone.
const shutdownCompilers = /** @type {Compiler} */compiler.hooks.shutdown || !isMultipleCompiler(compiler) ? [compiler] : compiler.compilers;
for (const shutdownCompiler of shutdownCompilers) {
/** @type {Compiler} */shutdownCompiler.hooks.shutdown.tap(PLUGIN_NAME, closeHot);
}
}
const compilersToModify = isMultipleCompiler(compiler) ? compiler.compilers.filter(item => item.options.devServer !== false) : [compiler];
if (options.hot) {
const hotOptions = options.hot === true ? {} : options.hot;
injectHotClient(compilersToModify, {
path: hotOptions.path || HOT_DEFAULT_PATH,
transport: hotOptions.transport || "sse",
inject: hotOptions.inject,
client: hotOptions.client,
// The one `createHot` minted just above, so the client it injects and
// the endpoint it serves agree.
token: context.hot?.token,
tokenRequired: context.hot?.tokenRequired
}, /** @type {Logger} */context.logger);
}
// Modify output file system
/** @type {OutputFileSystem} */
let outputFileSystem;
if (context.options.outputFileSystem) {
const {
outputFileSystem: outputFileSystemFromOptions
} = context.options;
outputFileSystem = outputFileSystemFromOptions;
}
// Don't use `memfs` when developer wants to write everything to a disk, because it doesn't make sense.
else if (context.options.writeToDisk === true) {
// Prefer compiler with `devServer` option or fallback to the first one
({
outputFileSystem
} = /** @type {Compiler & { outputFileSystem: OutputFileSystem }} */
isMultipleCompiler(compiler) ? compilersToModify[0] || compiler.compilers[0] : compiler);
} else {
outputFileSystem = /** @type {OutputFileSystem} */
/** @type {unknown} */memfs.createFsFromVolume(new memfs.Volume());
}
context.outputFileSystem = outputFileSystem;
// Written to disk besides the served file system unless that is the disk
// itself: with `true` and a file system of your own, on the compiler or in
// `outputFileSystem`, nothing was written to disk before.
const compilerOutputFileSystem = options.writeToDisk && !isDiskFileSystem(outputFileSystem) ? createDiskWritingFileSystem(outputFileSystem, context, compilersToModify) : outputFileSystem;
for (const compiler of compilersToModify) {
compiler.outputFileSystem = compilerOutputFileSystem;
}
// Start watching, but only for standalone usage, for plugin usage stats will be printed by external code, for example - webpack-cli
// TODO in the next major release remove, with the standalone mode (see `wdm`).
if (!isPlugin) {
/**
* @param {Error | null} err err
*/
const errorHandler = err => {
if (err) {
// For example - `writeToDisk` can throw an error and right now it is ends watching.
// We can improve that and keep watching active, but it is require API on webpack side.
// Let's implement that in webpack@5 because it is rare case.
context.logger.error(err);
}
};
if (compiler.watching) {
// Reuse the active watching session instead of starting a second one
// (exposed on `MultiCompiler` since webpack 5.109).
context.watching = compiler.watching;
} else if (isMultipleCompiler(compiler)) {
context.watching = compiler.watch(compiler.compilers.map(compiler => compiler.options.watchOptions || {}), errorHandler);
} else {
context.watching = compiler.watch(compiler.options.watchOptions || {}, errorHandler);
}
}
const filledContext = /** @type {FilledContext<RequestInternal, ResponseInternal>} */
context;
const instance = /** @type {API<RequestInternal, ResponseInternal>} */
middleware(filledContext);
// API
instance.getFilenameFromUrl = url => middleware.getFilenameFromUrl(filledContext, url);
// A WebSocket handshake is an upgrade the HTTP server answers, which the
// middleware never sees, so the server is handed over rather than inferred.
instance.attach = server => {
if (filledContext.hot) {
filledContext.hot.attach(server);
}
};
// For a server that would rather decide each upgrade than hand itself over:
// it keeps its own `upgrade` listener and calls in, so it can turn a request
// away before a handshake ever happens.
instance.handleUpgrade = (req, socket, head) => {
if (!filledContext.hot) {
return false;
}
return filledContext.hot.handleUpgrade(req, socket, head);
};
// Everything the middleware knows about a client that joined. What may be
// done about it is the caller's to decide — the middleware has no policy of
// its own and applies none.
instance.onConnect = fn => {
if (filledContext.hot) {
filledContext.hot.onConnect(fn);
}
};
// Put a payload of your own on the hot stream.
//
// The middleware publishes what it knows about — a build starting, finishing,
// failing. Anything else a server measures is its own: `ProgressPlugin` is
// the example, and it belongs to whoever decided to measure rather than to
// the middleware that carries the result. The client already renders
// `{ action: "progress" }`, so a server with its own plugin has everywhere to
// put it and needed only this.
//
// A no-op when `hot` is off, so a caller does not have to ask first.
instance.publish = payload => {
if (filledContext.hot) {
filledContext.hot.publish(payload);
}
};
// The same, to one client: what a server refusing a connection needs to say
// why, without having to know which transport is carrying it. A WebSocket
// client and an event-stream client are not the same kind of object, and
// writing to the wrong one is a message that silently never arrives.
//
// A no-op when `hot` is off, like `publish`.
instance.publishTo = (client, payload) => {
if (filledContext.hot) {
filledContext.hot.publishTo(client, payload);
}
};
// The secret the hot endpoint requires, for a client of your own: the
// injected one is handed it through its entry query, but anything you wrote
// yourself has to put it on the url. `false` when the endpoint requires
// none, `undefined` when `hot` is off.
instance.token = filledContext.hot ? filledContext.hot.token : undefined;
instance.waitUntilValid = (callback = noop) => {
middleware.ready(filledContext, callback);
};
instance.invalidate = (callback = noop) => {
const {
compiler: contextCompiler,
watching
} = filledContext;
// Collected before anything is invalidated: with nothing to invalidate,
// no build follows, and `ready` would queue the callback against one that
// never comes.
/** @type {{ invalidate: () => void }[]} */
const invalidating = [];
if (watching) {
invalidating.push(watching);
} else if (contextCompiler.watching) {
// For plugin usage the host (webpack-cli, webpack-dev-server, etc.) owns
// `compiler.watch()`, so invalidate the host's `watching` instead
invalidating.push(contextCompiler.watching);
} else if (isMultipleCompiler(contextCompiler)) {
// `MultiCompiler` exposes `watching` only since webpack 5.109, fall back
// to each child compiler's own `watching`
for (const childCompiler of contextCompiler.compilers) {
if (childCompiler.watching) {
invalidating.push(childCompiler.watching);
}
}
}
if (invalidating.length === 0) {
filledContext.logger.warn("The `invalidate` method was called, but the compiler is not watching, so there is nothing to invalidate.");
// No stats to hand over: unlike `close`, this callback takes the build
// result, and no build ran.
callback();
return;
}
middleware.ready(filledContext, callback);
for (const target of invalidating) {
target.invalidate();
}
};
instance.close = (callback = noop) => {
if (filledContext.hot) {
filledContext.hot.close();
// Also detach the SSE intercept so later requests fall through to the
// regular middleware instead of reaching the closed hot instance.
filledContext.hot = undefined;
}
// For plugin usage the host (webpack-cli, webpack-dev-server, etc.) owns `compiler.watch()`,
// so there is no `watching` of our own to close (`compiler.close()` on the host handles it)
if (!filledContext.watching) {
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.");
callback(null);
return;
}
filledContext.watching.close(callback);
};
instance.context = filledContext;
return instance;
}
/**
* @template S
* @template O
* @typedef {object} HapiPluginBase
* @property {(server: S, options: O) => void | Promise<void>} register register
*/
/**
* @template S
* @template O
* @typedef {HapiPluginBase<S, O> & { pkg: { name: string }, multiple: boolean }} HapiPlugin
*/
/**
* @typedef {Options & { compiler: Compiler | MultiCompiler }} HapiOptions
*/
/**
* @template HapiServer
* @template {HapiOptions} HapiOptionsInternal
* @param {boolean=} usePlugin true when need to use as a plugin, otherwise false
* @returns {HapiPlugin<HapiServer, HapiOptionsInternal>} hapi wrapper
*/
function hapiWrapper(usePlugin = false) {
return {
pkg: {
name: "webpack-dev-middleware"
},
// Allow to have multiple middleware
multiple: true,
register(server, options) {
const {
compiler,
...rest
} = options;
if (!compiler) {
throw new Error("The compiler options is required.");
}
const devMiddleware = wdm(compiler, rest, usePlugin);
// @ts-expect-error
if (!server.decorations.server.includes("webpackDevMiddleware")) {
// @ts-expect-error
server.decorate("server", "webpackDevMiddleware", devMiddleware);
}
// @ts-expect-error
// eslint-disable-next-line id-length
server.ext("onRequest", (request, h) => new Promise((resolve, reject) => {
let isFinished = false;
/**
* @param {(string | Buffer)=} data
*/
request.raw.res.send = data => {
isFinished = true;
request.raw.res.end(data);
};
/**
* @param {(string | Buffer)=} data
*/
request.raw.res.finish = data => {
isFinished = true;
request.raw.res.end(data);
};
devMiddleware(request.raw.req, request.raw.res, error => {
if (error) {
reject(error);
return;
}
if (!isFinished) {
resolve(request);
}
});
}).then(() => h.continue).catch(error => {
throw error;
}));
}
};
}
wdm.hapiWrapper = hapiWrapper;
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @param {Compiler | MultiCompiler} compiler compiler
* @param {Options<RequestInternal, ResponseInternal>=} options options
* @param {boolean=} usePlugin whether to use as webpack plugin
* @returns {((ctx: EXPECTED_ANY, next: EXPECTED_FUNCTION) => Promise<void> | void) & { devMiddleware: API<RequestInternal, ResponseInternal> }} koa wrapper
*/
function koaWrapper(compiler, options = {}, usePlugin = false) {
const devMiddleware = wdm(compiler, options, usePlugin);
/**
* @param {{ req: RequestInternal, res: ResponseInternal & import("./utils").ExpectedServerResponse, status: number, body: string | Buffer | import("fs").ReadStream | { message: string }, state: object }} ctx context
* @param {EXPECTED_FUNCTION} next next
* @returns {Promise<void>}
*/
async function webpackDevMiddleware(ctx, next) {
const {
req,
res
} = ctx;
res.locals = ctx.state;
let {
status
} = ctx;
/**
* @returns {number} code
*/
res.getStatusCode = () => status;
/**
* @param {number} statusCode status code
*/
res.setStatusCode = statusCode => {
status = statusCode;
ctx.status = statusCode;
};
let isFinished = false;
let needNext = false;
try {
await new Promise(
/**
* @param {(value: void) => void} resolve resolve
* @param {(reason?: Error) => void} reject reject
*/
(resolve, reject) => {
/**
* @param {import("fs").ReadStream} stream readable stream
*/
res.stream = stream => {
let resolved = false;
/**
* @param {Error=} err error
*/
const onEvent = err => {
if (resolved) return;
resolved = true;
stream.removeListener("error", onEvent);
stream.removeListener("readable", onEvent);
if (err) {
reject(err);
return;
}
ctx.body = stream;
isFinished = true;
resolve();
};
stream.once("error", onEvent);
stream.once("readable", onEvent);
// Empty stream
stream.once("end", onEvent);
};
/**
* @param {string | Buffer} data data
*/
res.send = data => {
ctx.body = data;
isFinished = true;
resolve();
};
/**
* @param {(string | Buffer)=} data data
*/
res.finish = data => {
ctx.status = status;
res.end(data);
isFinished = true;
resolve();
};
devMiddleware(req, res, err => {
if (err) {
reject(err);
return;
}
needNext = true;
if (!isFinished) {
resolve();
}
});
});
} catch (err) {
if (options?.forwardError) {
await next();
// need the return for prevent to execute the code below and override the status and body set by user in the next middleware
return;
}
ctx.status = /** @type {Error & { statusCode: number }} */err.statusCode || /** @type {Error & { status: number }} */err.status || 500;
ctx.body = {
message: /** @type {Error} */err.message
};
}
if (needNext) {
await next();
}
}
webpackDevMiddleware.devMiddleware = devMiddleware;
return webpackDevMiddleware;
}
wdm.koaWrapper = koaWrapper;
/**
* @template {IncomingMessage} [RequestInternal=IncomingMessage]
* @template {ServerResponse} [ResponseInternal=ServerResponse]
* @param {Compiler | MultiCompiler} compiler compiler
* @param {Options<RequestInternal, ResponseInternal>=} options options
* @param {boolean=} usePlugin true when need to use as a plugin, otherwise false
* @returns {((ctx: EXPECTED_ANY, next: EXPECTED_FUNCTION) => Promise<void> | void) & { devMiddleware: API<RequestInternal, ResponseInternal> }} hono wrapper
*/
function honoWrapper(compiler, options = {}, usePlugin = false) {
const devMiddleware = wdm(compiler, options, usePlugin);
/**
* @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
* @param {EXPECTED_FUNCTION} next next function
* @returns {Promise<void>}
*/
async function webpackDevMiddleware(context, next) {
const {
req,
res
} = context;
context.set("webpack", {
devMiddleware: devMiddleware.context
});
/**
* @returns {string | undefined} method
*/
req.getMethod = () => context.req.method;
/**
* @param {string} name name
* @returns {string | string[] | undefined} header value
*/
req.getHeader = name => context.req.header(name);
/**
* @returns {string | undefined} URL
*/
req.getURL = () => context.req.url;
let {
status
} = context.res;
/**
* @returns {number} code code
*/
res.getStatusCode = () => status;
/**
* @param {number} code code
*/
res.setStatusCode = code => {
status = code;
};
/**
* @param {string} name header name
* @returns {string | string[] | undefined} header
*/
res.getHeader = name => context.res.headers.get(name);
/**
* @param {string} name header name
* @param {string | number | Readonly<string[]>} value value
* @returns {ResponseInternal & import("./utils").ExpectedServerResponse & { headers: EXPECTED_ANY, status: EXPECTED_ANY }} response
*/
res.setHeader = (name, value) => {
context.res.headers.append(name, value);
return context.res;
};
/**
* @param {string} name header name
*/
res.removeHeader = name => {
context.res.headers.delete(name);
};
/**
* @returns {string[]} response headers
*/
res.getResponseHeaders = () => [...context.res.headers.keys()];
/**
* @returns {ServerResponse} server response
*/
res.getOutgoing = () => context.env.outgoing;
res.setState = () => {
// Do nothing, because we set it before
};
res.getHeadersSent = () => context.env.outgoing.headersSent;
let body;
let isFinished = false;
// Hot middleware writes raw chunks via `res.writeHead` / `res.write` / `res.end`.
// Hono's response object is Web API-style, so we shim those methods on top of a
// Web ReadableStream that hono streams back to the client.
/** @type {ReadableStreamDefaultController | undefined} */
let sseController;
let sseClosed = false;
/** @type {(() => void)[]} */
const closeHandlers = [];
/**
* @param {string} event event name
* @param {() => void} handler handler
* @returns {EXPECTED_ANY} req
*/
const reqOn = (event, handler) => {
if (event === "close") {
closeHandlers.push(handler);
if (sseClosed) handler();
}
return req;
};
if (typeof (/** @type {EXPECTED_ANY} */req.on) !== "function") {
/** @type {EXPECTED_ANY} */
req.on = reqOn;
}
try {
await new Promise(
/**
* @param {(value: void) => void} resolve resolve
* @param {(reason?: Error) => void} reject reject
*/
(resolve, reject) => {
/** @type {EXPECTED_ANY} */
res.writeHead =
/**
* @param {number} statusCode status code
* @param {Record<string, string | number | string[]>=} headers headers
*/
(statusCode, headers) => {
status = statusCode;
if (headers) {
for (const name of Object.keys(headers)) {
// `set`, not `append`: writeHead replaces headers left by
// earlier middleware instead of comma-joining values.
context.res.headers.set(name, String(headers[name]));
}
}
body = new ReadableStream({
start(controller) {
sseController = controller;
},
cancel() {
sseClosed = true;
for (const fn of closeHandlers) fn();
}
});
isFinished = true;
resolve();
};
/** @type {EXPECTED_ANY} */
res.write =
/**
* @param {string | Buffer} chunk chunk to write
* @returns {boolean} true when written
*/
chunk => {
if (!sseController || sseClosed) return false;
try {
sseController.enqueue(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk);
} catch {
return false;
}
return true;
};
/** @type {EXPECTED_ANY} */
res.end = () => {
if (!sseController || sseClosed) return;
sseClosed = true;
try {
sseController.close();
} catch {
// already closed
}
};
Object.defineProperty(res, "writableEnded", {
configurable: true,
get() {
return sseClosed;
}
});
/**
* @param {import("fs").ReadStream} stream readable stream
*/
res.stream = stream => {
let isResolved = false;
/**
* @param {Error=} err err
*/
const onEvent = err => {
if (isResolved) return;
isResolved = true;
stream.removeListener("error", onEvent);
stream.removeListener("readable", onEvent);
stream.removeListener("end", onEvent);
if (err) {
stream.destroy();
reject(err);
return;
}
// Wrap as a Web ReadableStream so `@hono/node-server` takes its
// fast path and Node's internal `Readable.toWeb` adapter is not
// involved (it races on late `error`/`close` from fs streams).
body = nodeReadableToWebStream(stream);
isFinished = true;
resolve();
};
stream.once("error", onEvent);
stream.once("readable", onEvent);
// Empty stream
stream.once("end", onEvent);
if (stream.pending === false) {
onEvent();
}
};
/**
* @param {string | Buffer} data data
*/
res.send = data => {
// Hono sets `Content-Length` by default
context.res.headers.delete("Content-Length");
body = data;
isFinished = true;
resolve();
};
/**
* @param {(string | Buffer)=} data data
*/
res.finish = data => {
const isDataExist = typeof data !== "undefined";
// Hono sets `Content-Length` by default
if (isDataExist) {
context.res.headers.delete("Content-Length");
}
body = isDataExist ? data : null;
isFinished = true;
resolve();
};
devMiddleware(req, res, err => {
if (err) {
reject(err);
return;
}
if (!isFinished) {
resolve();
}
});
});
} catch (err) {
if (options?.forwardError) {
await next();
// need the return for prevent to execute the code below and override the status and body set by user in the next middleware
return;
}
context.status(500);
return context.json({
message: /** @type {Error} */err.message
});
}
if (typeof body !== "undefined") {
return context.body(body, status);
}
await next();
}
webpackDevMiddleware.devMiddleware = devMiddleware;
return webpackDevMiddleware;
}
wdm.honoWrapper = honoWrapper;
module.exports = wdm;