-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
standalone.ts
57 lines (48 loc) · 1.55 KB
/
standalone.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { NodeApp } from 'astro/app/node';
import path from 'path';
import { fileURLToPath } from 'url';
import { createServer } from './http-server.js';
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));
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) {
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);
const server = createServer(
{
client,
port,
host,
removeBase: app.removeBase.bind(app),
},
handler
);
// eslint-disable-next-line no-console
console.log(`Server listening on http:https://${host}:${port}`);
return server.closed();
}