0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00
astro/packages/integrations/node/src/preview.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

55 lines
1.4 KiB
TypeScript
Raw Normal View History

import type { CreatePreviewServer } from 'astro';
import http from 'http';
import { fileURLToPath } from 'url';
import { createServer } from './http-server.js';
2022-10-12 16:27:56 -05:00
import type { createExports } from './server';
2022-10-12 16:27:56 -05:00
const preview: CreatePreviewServer = async function ({ client, serverEntrypoint, host, port }) {
type ServerModule = ReturnType<typeof createExports>;
type MaybeServerModule = Partial<ServerModule>;
let ssrHandler: ServerModule['handler'];
try {
process.env.ASTRO_NODE_AUTOSTART = 'disabled';
const ssrModule: MaybeServerModule = await import(serverEntrypoint.toString());
2022-10-12 16:27:56 -05:00
if (typeof ssrModule.handler === 'function') {
ssrHandler = ssrModule.handler;
} else {
2022-10-12 16:27:56 -05:00
throw new Error(
`The server entrypoint doesn't have a handler. Are you sure this is the right file?`
);
}
2022-10-12 16:27:56 -05:00
} catch (_err) {
throw new Error(
`The server entrypoint ${fileURLToPath} does not exist. Have you ran a build yet?`
);
}
const handler: http.RequestListener = (req, res) => {
ssrHandler(req, res, (ssrErr: any) => {
if (ssrErr) {
res.writeHead(500);
res.end(ssrErr.toString());
} else {
res.writeHead(404);
res.end();
}
});
};
2022-10-12 16:27:56 -05:00
const server = createServer(
{
client,
port,
host,
},
handler
);
// eslint-disable-next-line no-console
console.log(`Preview server listening on http://${host}:${port}`);
return server;
};
2022-10-12 16:27:56 -05:00
export { preview as default };