2022-10-12 21:25:51 +00:00
|
|
|
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-10-12 21:25:51 +00:00
|
|
|
|
2022-11-07 15:06:51 +00:00
|
|
|
const preview: CreatePreviewServer = async function ({
|
|
|
|
client,
|
|
|
|
serverEntrypoint,
|
|
|
|
host,
|
|
|
|
port,
|
|
|
|
base,
|
|
|
|
}) {
|
2022-10-12 21:25:51 +00:00
|
|
|
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') {
|
2022-10-12 21:25:51 +00:00
|
|
|
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?`
|
|
|
|
);
|
2022-10-12 21:25:51 +00:00
|
|
|
}
|
2022-12-08 20:54:19 +00:00
|
|
|
} 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?`
|
2022-12-08 20:54:19 +00:00
|
|
|
);
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
2022-10-12 21:25:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
2022-11-07 15:05:12 +00:00
|
|
|
function removeBase(pathname: string): string {
|
2022-11-07 15:06:51 +00:00
|
|
|
if (pathname.startsWith(base)) {
|
2022-11-07 15:05:12 +00:00
|
|
|
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
|
|
|
|
);
|
2022-10-12 21:25:51 +00:00
|
|
|
|
|
|
|
// 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 };
|