code-server/src/node/wsRouter.ts
renovate[bot] 91589fd106
chore(deps): update dependency @types/node to v16 (#5170)
* Update Node types to 16

* Update Express core types

Fixes a number of conflicts it has with Node 16.

* Fix websocket router types

It seems req was `any` before so now we have to handle the types.  Also
it seems the socket is of type `stream.Duplex`, not `net.Socket`.

The ws types had to be updated to support the new type.

Unfortunately Code still uses the old type so cast for now.

In the web socket router just use a cast for the extra properties we
add.  We could add the types to the Express namespace but I am not sure
we really want these commonly accessible so keep with the casts for now.
Likely we should use Express's `locals` or something instead.

* Add missing return

Not sure why it only just now started complaining though.

Co-authored-by: Asher <ash@coder.com>
2022-08-10 16:15:52 -05:00

55 lines
1.6 KiB
TypeScript

import * as express from "express"
import * as expressCore from "express-serve-static-core"
import * as http from "http"
import Websocket from "ws"
import * as pluginapi from "../../typings/pluginapi"
export const handleUpgrade = (app: express.Express, server: http.Server): void => {
server.on("upgrade", (req, socket, head) => {
socket.pause()
const wreq = req as InternalWebsocketRequest
wreq.ws = socket
wreq.head = head
wreq._ws_handled = false
// Send the request off to be handled by Express.
;(app as any).handle(wreq, new http.ServerResponse(wreq), () => {
if (!wreq._ws_handled) {
socket.end("HTTP/1.1 404 Not Found\r\n\r\n")
}
})
})
}
interface InternalWebsocketRequest extends pluginapi.WebsocketRequest {
_ws_handled: boolean
}
export class WebsocketRouter {
public readonly router = express.Router()
/**
* Handle a websocket at this route. Note that websockets are immediately
* paused when they come in.
*/
public ws(route: expressCore.PathParams, ...handlers: pluginapi.WebSocketHandler[]): void {
this.router.get(
route,
...handlers.map((handler) => {
const wrapped: express.Handler = (req, res, next) => {
;(req as InternalWebsocketRequest)._ws_handled = true
return handler(req as pluginapi.WebsocketRequest, res, next)
}
return wrapped
}),
)
}
}
export function Router(): WebsocketRouter {
return new WebsocketRouter()
}
// eslint-disable-next-line import/no-named-as-default-member -- the typings are not updated correctly
export const wss = new Websocket.Server({ noServer: true })