diff --git a/.changeset/big-yaks-invite.md b/.changeset/big-yaks-invite.md new file mode 100644 index 000000000..bbedfd0f1 --- /dev/null +++ b/.changeset/big-yaks-invite.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix bug causing `astro preview` server to close immediately diff --git a/packages/astro/src/cli/index.ts b/packages/astro/src/cli/index.ts index 50ef47531..df2d2c2a8 100644 --- a/packages/astro/src/cli/index.ts +++ b/packages/astro/src/cli/index.ts @@ -138,7 +138,8 @@ export async function cli(args: string[]) { case 'preview': { try { - return await preview(config, { logging }); // this will keep running + const server = await preview(config, { logging }); + return await server.closed(); // keep alive until the server is closed } catch (err) { return throwAndExit(err); } diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index 1d68bd0f1..9040e6581 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -18,6 +18,7 @@ export interface PreviewServer { host?: string; port: number; server: http.Server; + closed(): Promise; stop(): Promise; } @@ -133,9 +134,18 @@ export default async function preview( // Start listening on `hostname:port`. await startServer(startServerTime); + // Resolves once the server is closed + function closed() { + return new Promise((resolve, reject) => { + httpServer!.addListener('close', resolve); + httpServer!.addListener('error', reject); + }) + } + return { host, port, + closed, server: httpServer!, stop: async () => { await new Promise((resolve, reject) => {