From e40ae7888a1058183a887744264b2cc0762190d8 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Thu, 30 Jul 2026 03:38:16 +0530 Subject: [PATCH] refactor(serve): resolve once the server is listening Collapse the duplicated listen branches and await the listening event; serve() now also rejects on listen errors like EADDRINUSE instead of crashing in the callback. Co-Authored-By: Claude Fable 5 --- src/node/serve/serve.ts | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/node/serve/serve.ts b/src/node/serve/serve.ts index e46e5522..dc70f683 100644 --- a/src/node/serve/serve.ts +++ b/src/node/serve/serve.ts @@ -1,4 +1,5 @@ import compression from '@polka/compression' +import { once } from 'node:events' import path from 'node:path' import polka, { type IOptions } from 'polka' import sirv from 'sirv' @@ -42,19 +43,15 @@ export async function serve(options: ServeOptions = {}) { } }) - if (base) { - return polka({ onNoMatch }) - .use(base, compress, serve) - .listen(port, () => { - config.logger.info( - `Built site served at http://localhost:${port}/${base}/` - ) - }) - } + const app = base + ? polka({ onNoMatch }).use(base, compress, serve) + : polka({ onNoMatch }).use(compress, serve) + + app.listen(port) + await once(app.server, 'listening') + config.logger.info( + `Built site served at http://localhost:${port}/${base ? `${base}/` : ''}` + ) - return polka({ onNoMatch }) - .use(compress, serve) - .listen(port, () => { - config.logger.info(`Built site served at http://localhost:${port}/`) - }) + return app }