Files
sweet/packages/fresh/src/dev/middlewares/live_reload.ts
T
Marvin Hagemeister 815b1940e3 chore: restructure repository into packages/ folder (#3197)
We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
2025-08-06 15:52:45 +02:00

40 lines
1.0 KiB
TypeScript

import type { Middleware } from "../../middlewares/mod.ts";
import { ALIVE_URL } from "../../constants.ts";
// Live reload: Send updates to browser
export function liveReload<T>(): Middleware<T> {
const revision = Date.now();
return (ctx) => {
const { config, req, url } = ctx;
const aliveUrl = config.basePath + ALIVE_URL;
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision,
}),
);
});
return response;
}
return ctx.next();
};
}