-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.ts
146 lines (130 loc) · 4.05 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import type { AstroConfig } from '../../@types/astro';
import type { LogOptions } from '../logger/core';
import type { AddressInfo } from 'net';
import http from 'http';
import sirv from 'sirv';
import { performance } from 'perf_hooks';
import { fileURLToPath } from 'url';
import * as msg from '../messages.js';
import { error, info } from '../logger/core.js';
import { subpathNotUsedTemplate, notFoundTemplate } from '../../template/4xx.js';
import { getResolvedHostForHttpServer } from './util.js';
interface PreviewOptions {
logging: LogOptions;
}
export interface PreviewServer {
host?: string;
port: number;
server: http.Server;
stop(): Promise<void>;
}
const HAS_FILE_EXTENSION_REGEXP = /^.*\.[^\\]+$/;
/** The primary dev action */
export default async function preview(
config: AstroConfig,
{ logging }: PreviewOptions
): Promise<PreviewServer> {
const startServerTime = performance.now();
const defaultOrigin = 'http://localhost';
const trailingSlash = config.trailingSlash;
/** Base request URL. */
let baseURL = new URL(config.base, new URL(config.site || '/', defaultOrigin));
const staticFileServer = sirv(fileURLToPath(config.outDir), {
dev: true,
etag: true,
maxAge: 0,
});
// Create the preview server, send static files out of the `dist/` directory.
const server = http.createServer((req, res) => {
const requestURL = new URL(req.url as string, defaultOrigin);
// respond 404 to requests outside the base request directory
if (!requestURL.pathname.startsWith(baseURL.pathname)) {
res.statusCode = 404;
res.end(subpathNotUsedTemplate(baseURL.pathname, requestURL.pathname));
return;
}
/** Relative request path. */
const pathname = requestURL.pathname.slice(baseURL.pathname.length - 1);
const isRoot = pathname === '/';
const hasTrailingSlash = isRoot || pathname.endsWith('/');
function sendError(message: string) {
res.statusCode = 404;
res.end(notFoundTemplate(pathname, message));
}
switch (true) {
case hasTrailingSlash && trailingSlash == 'never' && !isRoot:
sendError('Not Found (trailingSlash is set to "never")');
return;
case !hasTrailingSlash &&
trailingSlash == 'always' &&
!isRoot &&
!HAS_FILE_EXTENSION_REGEXP.test(pathname):
sendError('Not Found (trailingSlash is set to "always")');
return;
default: {
// HACK: rewrite req.url so that sirv finds the file
req.url = '/' + req.url?.replace(baseURL.pathname, '');
staticFileServer(req, res, () => sendError('Not Found'));
return;
}
}
});
let { port } = config.server;
const host = getResolvedHostForHttpServer(config.server.host);
let httpServer: http.Server;
/** Expose dev server to `port` */
function startServer(timerStart: number): Promise<void> {
let showedPortTakenMsg = false;
let showedListenMsg = false;
return new Promise<void>((resolve, reject) => {
const listen = () => {
httpServer = server.listen(port, host, async () => {
if (!showedListenMsg) {
const devServerAddressInfo = server.address() as AddressInfo;
info(
logging,
null,
msg.devStart({
startupTime: performance.now() - timerStart,
config,
devServerAddressInfo,
https: false,
site: baseURL,
})
);
}
showedListenMsg = true;
resolve();
});
httpServer?.on('error', onError);
};
const onError = (err: NodeJS.ErrnoException) => {
if (err.code && err.code === 'EADDRINUSE') {
if (!showedPortTakenMsg) {
info(logging, 'astro', msg.portInUse({ port }));
showedPortTakenMsg = true; // only print this once
}
port++;
return listen(); // retry
} else {
error(logging, 'astro', err.stack);
httpServer?.removeListener('error', onError);
reject(err); // reject
}
};
listen();
});
}
// Start listening on `hostname:port`.
await startServer(startServerTime);
return {
host,
port,
server: httpServer!,
stop: async () => {
await new Promise((resolve, reject) => {
httpServer.close((err) => (err ? reject(err) : resolve(undefined)));
});
},
};
}