astro/packages/integrations/node/src/preview.ts

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

78 lines
1.8 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 21:27:56 +00:00
import type { createExports } from './server';
2022-11-07 15:06:51 +00:00
const preview: CreatePreviewServer = async function ({
client,
serverEntrypoint,
host,
port,
base,
}) {
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 21:27:56 +00:00
if (typeof ssrModule.handler === 'function') {
ssrHandler = ssrModule.handler;
} else {
2022-10-12 21:27:56 +00:00
throw new Error(
`The server entrypoint doesn't have a handler. Are you sure this is the right file?`
);
}
} catch (err) {
if ((err as any).code === 'ERR_MODULE_NOT_FOUND') {
throw new Error(
2022-12-08 20:56:38 +00:00
`The server entrypoint ${fileURLToPath(
serverEntrypoint
)} does not exist. Have you ran a build yet?`
);
} else {
throw err;
}
}
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-11-07 15:06:51 +00:00
const baseWithoutTrailingSlash: string = base.endsWith('/')
? base.slice(0, base.length - 1)
: base;
function removeBase(pathname: string): string {
2022-11-07 15:06:51 +00:00
if (pathname.startsWith(base)) {
return pathname.slice(baseWithoutTrailingSlash.length);
}
return pathname;
}
2022-10-12 21:27:56 +00:00
const server = createServer(
{
client,
port,
host,
2022-11-07 15:06:51 +00:00
removeBase,
2022-10-12 21:27:56 +00:00
},
handler
);
// eslint-disable-next-line no-console
console.log(`Preview server listening on http://${host}:${port}`);
return server;
};
2022-10-12 21:27:56 +00:00
export { preview as default };