0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/packages/integrations/node/src/standalone.ts

57 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { NodeApp } from 'astro/app/node';
import path from 'path';
import { fileURLToPath } from 'url';
import { createServer } from './http-server.js';
2022-10-12 16:27:56 -05:00
import middleware from './middleware.js';
import type { Options } from './types';
function resolvePaths(options: Options) {
const clientURLRaw = new URL(options.client);
const serverURLRaw = new URL(options.server);
const rel = path.relative(fileURLToPath(serverURLRaw), fileURLToPath(clientURLRaw));
2022-10-12 16:27:56 -05:00
const serverEntryURL = new URL(import.meta.url);
const clientURL = new URL(appendForwardSlash(rel), serverEntryURL);
return {
client: clientURL,
};
}
function appendForwardSlash(pth: string) {
return pth.endsWith('/') ? pth : pth + '/';
}
export function getResolvedHostForHttpServer(host: string | boolean) {
if (host === false) {
// Use a secure default
return '127.0.0.1';
} else if (host === true) {
// If passed --host in the CLI without arguments
return undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
} else {
return host;
}
}
export default function startServer(app: NodeApp, options: Options) {
2022-10-12 16:27:56 -05:00
const port = process.env.PORT ? Number(process.env.port) : options.port ?? 8080;
const { client } = resolvePaths(options);
const handler = middleware(app);
const host = getResolvedHostForHttpServer(options.host);
2022-10-12 16:27:56 -05:00
const server = createServer(
{
client,
port,
host,
},
handler
);
// eslint-disable-next-line no-console
console.log(`Server listening on http://${host}:${port}`);
return server.closed();
}