Skip to content

Commit 0b50966

Browse files
feat(hot): speak webpack-dev-server's protocol with hot.protocol
`hot.protocol: { type: "webpack-dev-server", hot, liveReload }` puts that server's runtime in the page instead of this package's, and speaks its `{ type, data }` protocol over either transport — what that server did, ported as it was: - the runtime goes where a browser runs the compilation, with the query that server wrote, in its order; `webpack/hot/dev-server` (or `only-dev-server`) wherever `hot` is on; `__webpack_dev_server_client__` everywhere; `HotModuleReplacementPlugin`, with that server's warning when the configuration already has one; and the `EventTarget` emitter for a universal ES module build. `entry` and `hotEntry` name other modules for the first two, which is how that server's own `client/index.js` and a subclass's overrides keep working. - a client is told `hot`, `liveReload`, `progress`, `reconnect` and `overlay` when it connects, then the last build's result; each build sends `invalid`, then `hash` and `ok`, `still-ok`, `warnings` (with `preventReloading` beside errors) or `errors`, serialized with that server's stats options and `warningsFilter`. In this mode the middleware logs under that server's name. The `ws` server behind `"ws"` is handed out as `hot.implementation`, which that server exposes as `webSocketServer.implementation`. The Server-Sent Events client skips the heartbeat, which that runtime would parse, and connects from the `ws:` url it builds. TODO in the next major release remove `hot.protocol`, once webpack-dev-server runs on this package's own runtime. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UjuMAuk9o6UazjHzcAQCTA
1 parent f038ad2 commit 0b50966

20 files changed

Lines changed: 2387 additions & 33 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack-dev-middleware": minor
3+
---
4+
5+
`hot.protocol: { type: "webpack-dev-server" }` speaks webpack-dev-server 6's `{ type, data }` protocol and puts that server's own runtime in the page, unchanged, instead of this package's: what webpack-dev-server runs on until its next major release, so nothing its users rely on changes, React Refresh's overlay reading `webpack-dev-server/client/socket` included. The runtime ships as `webpack-dev-middleware/client/webpack-dev-server/*`, the `ws` server behind `hot.transport: "ws"` is handed out as `instance.context.hot.implementation`, and the Server-Sent Events client skips the heartbeat and connects from the `ws:` url that runtime builds.

‎README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,49 @@ Add the client entry and `HotModuleReplacementPlugin` to the compilation. Set it
660660

661661
Turn it off when you have a client of your own that the middleware will not recognize as one (anything other than `webpack-dev-middleware/client`), or when you do not want the hot runtime in your bundle at all and are using the endpoint through [`subscribe`](#custom-events) instead.
662662

663+
#### `hot.protocol`
664+
665+
Type: `Object`
666+
Default: `undefined`
667+
668+
> [!NOTE]
669+
>
670+
> This is for webpack-dev-server, which runs on it until its next major release, when it is removed. Anything else wants this package's own runtime, which is what you get without it.
671+
672+
Speak webpack-dev-server 6's protocol — its `{ type, data }` messages — and put that server's runtime in the page instead of this package's own. Whatever its users rely on comes with it unchanged: `webpack-dev-server/client/socket` and the messages React Refresh's overlay reads from it, the console, the overlay and the progress bar, and updates applied by `webpack/hot/dev-server`.
673+
674+
```js
675+
const middleware = require("webpack-dev-middleware");
676+
677+
app.use(
678+
middleware(compiler, {
679+
hot: {
680+
transport: "ws",
681+
path: "/ws",
682+
protocol: { type: "webpack-dev-server", hot: true, liveReload: true },
683+
client: { logging: "info", overlay: true, reconnect: 10 },
684+
},
685+
}),
686+
);
687+
```
688+
689+
- `type` — `"webpack-dev-server"`.
690+
- `hot` — that server's option of the same name: `true` applies updates in place and reloads when one cannot be applied, `"only"` never reloads, `false` applies none. `true` by default.
691+
- `liveReload` — reload the page on a build whose updates are not applied in place. `true` by default.
692+
- `entry` — the runtime module, which its query is appended to. This package's copy by default; webpack-dev-server names its own `client/index.js`, which re-exports it.
693+
- `hotEntry` — what applies the updates the runtime announces: `webpack/hot/dev-server`, or `webpack/hot/only-dev-server` for `hot: "only"`, by default, and `false` for nothing.
694+
695+
[`hot.client`](#client-options) is read as that server's `client` option: `path` in parts — `protocol`, `username`, `password`, `hostname`, `port`, `pathname` — and `logging`, `progress`, `overlay`, `reconnect` and `transport`. Each compilation that is not `devServer: false` gets what that server gave it:
696+
697+
| Added | When |
698+
| :----------------------------------------------------------- | :----------------------------------------------------------- |
699+
| `entry`, with those options on its query | a browser runs the compilation and `hot.client` is not false |
700+
| `hotEntry` | it is not `false` — by default, `hot` is not `false` |
701+
| `__webpack_dev_server_client__`, the client it connects with | always |
702+
| `HotModuleReplacementPlugin` | `hot` is not `false` |
703+
704+
A client is told `hot`, `liveReload`, `progress`, `reconnect` and `overlay` when it connects, then the last build's result; every build after that starts with `invalid` and ends with its `hash` and `ok`, `still-ok`, `warnings` or `errors`.
705+
663706
#### `hot.statsOptions`
664707

665708
> [!WARNING]

‎client-src/clients/EventSourceClient.js‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
// Long enough that a slow build does not look like a dead connection.
55
const DEFAULT_TIMEOUT = 20 * 1000;
66

7+
// What the endpoint sends while there is nothing to say.
8+
const HEARTBEAT = "💓";
9+
710
/**
811
* Server-Sent Events. A connection can die without the browser firing `error`
912
* — a proxy that stops forwarding, a laptop that slept — so this one watches
@@ -32,7 +35,9 @@ export default class EventSourceClient {
3235
this.closed = false;
3336
this.lastActivity = Date.now();
3437

35-
this.client = new self.EventSource(url);
38+
// webpack-dev-server's runtime builds a `ws:` url for whatever transport
39+
// it is given, and an `EventSource` only speaks `http:`.
40+
this.client = new self.EventSource(url.replace(/^ws(s?):/i, "http$1:"));
3641

3742
this.client.addEventListener("open", () => {
3843
if (this.closed) {
@@ -53,8 +58,17 @@ export default class EventSourceClient {
5358

5459
this.lastActivity = Date.now();
5560

61+
const { data } = /** @type {{ data: string }} */ (event);
62+
63+
// The heartbeat keeps the connection from looking dead, which it has
64+
// just done; it is not a message, and a runtime parsing every message
65+
// as JSON would throw on it.
66+
if (data === HEARTBEAT) {
67+
return;
68+
}
69+
5670
if (this.messageHandler) {
57-
this.messageHandler(/** @type {{ data: string }} */ (event).data);
71+
this.messageHandler(data);
5872
}
5973
});
6074

‎src/hot.js‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,23 @@
7272
* @property {(boolean | string)=} token a secret the injected client carries and the endpoint requires; `true` mints one per run, a string uses that one, `false` requires none. Defaults to `false` on both transports; `true` in the next major release
7373
* @property {boolean=} inject add the hot client entry and `HotModuleReplacementPlugin` to the compilation (default `true`); turn it off to wire them yourself
7474
* @property {(HotClientOptions | false)=} client options handed to the browser runtime through its entry query; `false` adds no runtime to the page and still applies `HotModuleReplacementPlugin`
75+
* @property {DevServerProtocol=} protocol speak webpack-dev-server 6's protocol and put its runtime in the page instead of this package's own, for webpack-dev-server itself until its next major release
76+
*/
77+
78+
/**
79+
* webpack-dev-server 6's protocol and runtime. `hot` and `liveReload` are that
80+
* server's options of the same names, and `hot.client` is read as its `client`
81+
* option: `path` in parts, `logging`, `progress`, `overlay`, `reconnect` and
82+
* `transport`.
83+
*
84+
* TODO in the next major release remove this, once webpack-dev-server runs on
85+
* this package's own runtime.
86+
* @typedef {object} DevServerProtocol
87+
* @property {"webpack-dev-server"} type the protocol
88+
* @property {(boolean | "only")=} hot apply updates in place, `"only"` without falling back to a reload when one cannot be applied; `true` by default
89+
* @property {boolean=} liveReload reload the page on a build when updates are not applied in place; `true` by default
90+
* @property {string=} entry the runtime module, which its query is appended to; this package's copy by default — webpack-dev-server names its own `client/index.js`, which re-exports it
91+
* @property {(string | false)=} hotEntry what applies the updates the runtime announces, added to every compilation; `webpack/hot/dev-server`, or `webpack/hot/only-dev-server` for `hot: "only"`, by default, and `false` for nothing
7592
*/
7693

7794
/**
@@ -118,6 +135,15 @@
118135
* @typedef {{ action: string } & Record<string, EXPECTED_ANY>} CustomPayload
119136
*/
120137

138+
/**
139+
* A message in webpack-dev-server's protocol, which `hot.protocol` speaks and
140+
* a server speaking it publishes more of — a static file changing, a build's
141+
* progress.
142+
*
143+
* TODO in the next major release remove this, along with `hot.protocol`
144+
* @typedef {{ type: string, data?: EXPECTED_ANY, params?: EXPECTED_ANY }} DevServerMessage
145+
*/
146+
121147
// eslint-disable-next-line jsdoc/reject-any-type
122148
/** @typedef {any} EXPECTED_ANY */
123149

@@ -148,12 +174,13 @@
148174
* @property {((req: IncomingMessage, res: ServerResponse) => void)=} handler answer a request on the endpoint's path; without one a request there is answered `426 Upgrade Required`
149175
* @property {(() => boolean)=} hasClients true when at least one client is connected; without one a payload is built even if nobody is listening
150176
* @property {(fn: (client: TClient, req: IncomingMessage) => void) => void} onConnect called with each client once it has joined, and the request it joined with
151-
* @property {(payload: Payload | CustomPayload) => void} publish publish a payload to every client
152-
* @property {(client: TClient, payload: Payload | CustomPayload) => void} publishTo publish a payload to a single client
177+
* @property {(payload: Payload | CustomPayload | DevServerMessage) => void} publish publish a payload to every client
178+
* @property {(client: TClient, payload: Payload | CustomPayload | DevServerMessage) => void} publishTo publish a payload to a single client
153179
* @property {() => void} close end every client and stop the heartbeat
154180
* @property {((server: HttpServer) => void)=} attach answer upgrades on this server
155181
* @property {(() => void)=} detach stop answering upgrades
156182
* @property {((req: IncomingMessage, socket: Duplex, head: Buffer) => boolean)=} handleUpgrade answer one upgrade, for a caller that owns the server's `upgrade` event; returns false when the request is not this endpoint's
183+
* @property {EXPECTED_ANY=} implementation the server underneath, when there is one to hand out — the `ws` server behind the `"ws"` transport
157184
*/
158185

159186
/**
@@ -479,9 +506,10 @@ function publishBundles(bundles, previousBundles, eventStream) {
479506
* @property {(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean} handleUpgrade answer one WebSocket upgrade, for a caller that owns the server's `upgrade` event and wants to decide each one; returns false when the request is not the endpoint's, or the transport does not answer upgrades
480507
* @property {(fn: (client: EXPECTED_ANY, req: IncomingMessage) => void) => void} onConnect called with each client once it has joined, and the request it joined with, before anything is published to it
481508
* @property {(req: IncomingMessage, res: ServerResponse) => void} handle answer a request on the endpoint's path
482-
* @property {(payload: Payload | CustomPayload) => void} publish publish a payload to every client
483-
* @property {(client: EXPECTED_ANY, payload: Payload | CustomPayload) => void} publishTo publish a payload to one client, for answering a single connection
509+
* @property {(payload: Payload | CustomPayload | DevServerMessage) => void} publish publish a payload to every client
510+
* @property {(client: EXPECTED_ANY, payload: Payload | CustomPayload | DevServerMessage) => void} publishTo publish a payload to one client, for answering a single connection
484511
* @property {() => void} close end every client and detach the heartbeat
512+
* @property {EXPECTED_ANY=} implementation the server underneath the transport, when it has one: the `ws` server behind `"ws"`
485513
*/
486514

487515
/**
@@ -504,7 +532,18 @@ function createHot(compiler, userOptions, statsOption) {
504532
const token = resolveToken(
505533
options.inject === false ? (options.token ?? false) : options.token,
506534
);
507-
const logger = compiler.getInfrastructureLogger("webpack-dev-middleware");
535+
// webpack-dev-server's protocol is that server speaking, in the terminal as
536+
// well as on the wire.
537+
const logger = compiler.getInfrastructureLogger(
538+
options.protocol ? "webpack-dev-server" : "webpack-dev-middleware",
539+
);
540+
// TODO in the next major release remove this, along with `hot.protocol`
541+
const devServerProtocol = options.protocol
542+
? require("./webpack-dev-server.js").createProtocol(compiler, {
543+
protocol: options.protocol,
544+
client: options.client,
545+
})
546+
: undefined;
508547

509548
// TODO in the next major release remove `statsOptions` and this warning
510549
if (statsOptions) {
@@ -567,7 +606,17 @@ function createHot(compiler, userOptions, statsOption) {
567606
// A listener is arbitrary code, and closing the middleware from one is a
568607
// reasonable thing for it to do — there would be no stream left to catch
569608
// this client up on.
570-
if (closed || !valid || !latestBundles) {
609+
if (closed) {
610+
return;
611+
}
612+
613+
if (devServerProtocol) {
614+
devServerProtocol.connect(eventStream, client);
615+
616+
return;
617+
}
618+
619+
if (!valid || !latestBundles) {
571620
return;
572621
}
573622

@@ -626,6 +675,12 @@ function createHot(compiler, userOptions, statsOption) {
626675
valid = false;
627676
lastProgressPercent = -1;
628677

678+
if (devServerProtocol) {
679+
devServerProtocol.invalid(eventStream);
680+
681+
return;
682+
}
683+
629684
/** @type {{ action: string, name?: string, file?: string }} */
630685
const payload = { action: "building" };
631686

@@ -648,6 +703,13 @@ function createHot(compiler, userOptions, statsOption) {
648703
const onDone = (statsResult) => {
649704
if (closed) return;
650705

706+
if (devServerProtocol) {
707+
devServerProtocol.done(eventStream, statsResult);
708+
valid = true;
709+
710+
return;
711+
}
712+
651713
const bundles = toBundles(statsResult, statsOptions, statsOption);
652714

653715
publishBundles(bundles, latestBundles, eventStream);
@@ -668,6 +730,7 @@ function createHot(compiler, userOptions, statsOption) {
668730
path,
669731
transport,
670732
token,
733+
implementation: eventStream.implementation,
671734
attach(server) {
672735
if (closed || !eventStream.attach) {
673736
return;

‎src/index.js‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,13 @@ const noop = () => {};
195195

196196
/**
197197
* @callback Publish
198-
* @param {import("./hot").Payload | import("./hot").CustomPayload} payload the payload to publish to every client
198+
* @param {import("./hot").Payload | import("./hot").CustomPayload | import("./hot").DevServerMessage} payload the payload to publish to every client
199199
*/
200200

201201
/**
202202
* @callback PublishTo
203203
* @param {EXPECTED_ANY} client a client `onConnect` handed over
204-
* @param {import("./hot").Payload | import("./hot").CustomPayload} payload the payload to publish to it
204+
* @param {import("./hot").Payload | import("./hot").CustomPayload | import("./hot").DevServerMessage} payload the payload to publish to it
205205
*/
206206

207207
/**
@@ -688,8 +688,14 @@ function wdm(compiler, options = {}, isPlugin = false) {
688688
// The one `createHot` minted just above, so the client it injects and
689689
// the endpoint it serves agree.
690690
token: context.hot?.token,
691+
protocol: hotOptions.protocol,
691692
},
692-
/** @type {Logger} */ (context.logger),
693+
// webpack-dev-server's protocol is that server speaking, and what it
694+
// warned about it said under its own name.
695+
// TODO in the next major release remove this, along with `hot.protocol`
696+
hotOptions.protocol
697+
? compiler.getInfrastructureLogger("webpack-dev-server")
698+
: /** @type {Logger} */ (context.logger),
693699
);
694700
}
695701

‎src/options.check.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/options.json‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@
179179
"type": "boolean"
180180
},
181181
"reconnect": {
182-
"description": "How many times to reconnect before giving up. Unset, Server-Sent Events keep trying for as long as the page is open — a dev server is expected to come back — while a WebSocket gives up after 10. Setting it applies to both. Deprecated, and removed in the next major release: use `connect`.",
182+
"description": "How many times to reconnect before giving up. Unset, Server-Sent Events keep trying for as long as the page is open — a dev server is expected to come back — while a WebSocket gives up after 10. Setting it applies to both. Deprecated, and removed in the next major release: use `connect` — except with `hot.protocol`, whose runtime reads this one.",
183183
"type": "number",
184184
"minimum": 0
185185
},
@@ -573,6 +573,51 @@
573573
"$ref": "#/definitions/HotClient"
574574
}
575575
]
576+
},
577+
"protocol": {
578+
"description": "Speak webpack-dev-server 6's protocol and put its runtime in the page, instead of this package's own: what webpack-dev-server runs on until its next major release, when this option is removed. `hot` and `liveReload` are that server's options of the same names, and `hot.client` is read as its `client` option.",
579+
"link": "https://github.com/webpack/webpack-dev-middleware#hotprotocol",
580+
"type": "object",
581+
"additionalProperties": false,
582+
"required": ["type"],
583+
"properties": {
584+
"type": {
585+
"description": "The protocol.",
586+
"enum": ["webpack-dev-server"]
587+
},
588+
"hot": {
589+
"description": "Apply updates in place; `\"only\"` never falls back to a reload when one cannot be applied. `true` by default.",
590+
"anyOf": [
591+
{
592+
"type": "boolean"
593+
},
594+
{
595+
"enum": ["only"]
596+
}
597+
]
598+
},
599+
"liveReload": {
600+
"description": "Reload the page on a build whose updates are not applied in place. `true` by default.",
601+
"type": "boolean"
602+
},
603+
"entry": {
604+
"description": "The runtime module, which its query is appended to. This package's copy by default; webpack-dev-server names its own `client/index.js`, which re-exports it.",
605+
"type": "string",
606+
"minLength": 1
607+
},
608+
"hotEntry": {
609+
"description": "What applies the updates the runtime announces, added to every compilation: `webpack/hot/dev-server`, or `webpack/hot/only-dev-server` for `hot: \"only\"`, by default, and `false` for nothing.",
610+
"anyOf": [
611+
{
612+
"enum": [false]
613+
},
614+
{
615+
"type": "string",
616+
"minLength": 1
617+
}
618+
]
619+
}
620+
}
576621
}
577622
}
578623
}

‎src/servers/WebSocketServer.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,10 @@ function createWebSocketStream(
268268
};
269269

270270
return {
271+
// The `ws` server itself, for a server built on this one that hands it out
272+
// — webpack-dev-server's `webSocketServer.implementation` has always been
273+
// one.
274+
implementation,
271275
attach(server) {
272276
// Attaching twice would upgrade every request twice over, and an
273277
// endpoint on a server of its own answers nothing on this one.

‎src/utils.js‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1587,10 +1587,23 @@ function resolveClientTransport(request, context) {
15871587

15881588
/**
15891589
* @param {Compiler[]} compilers compilers to modify
1590-
* @param {{ path: string, transport: NonNullable<HotOptions["transport"]>, inject?: boolean, client?: HotClientOptions | false, token?: string | false }} options resolved hot options
1590+
* @param {{ path: string, transport: NonNullable<HotOptions["transport"]>, inject?: boolean, client?: HotClientOptions | false, token?: string | false, protocol?: HotOptions["protocol"] }} options resolved hot options
15911591
* @param {Logger} logger logger
15921592
*/
15931593
function injectHotClient(compilers, options, logger) {
1594+
// webpack-dev-server's runtime, put in the way that server put it.
1595+
// TODO in the next major release remove this, along with `hot.protocol`
1596+
if (options.protocol) {
1597+
// Loaded here rather than at the top: it loads this module.
1598+
require("./webpack-dev-server.js").injectRuntime(
1599+
/** @type {EXPECTED_ANY} */ (compilers),
1600+
/** @type {EXPECTED_ANY} */ (options),
1601+
logger,
1602+
);
1603+
1604+
return;
1605+
}
1606+
15941607
if (options.inject === false) {
15951608
return;
15961609
}
@@ -1812,6 +1825,7 @@ module.exports = {
18121825
pathMatch,
18131826
pipe,
18141827
removeResponseHeader,
1828+
resolveClientTransport,
18151829
resolveCors,
18161830
resolveToken,
18171831
send,

0 commit comments

Comments
 (0)