forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.ts
180 lines (166 loc) · 4.78 KB
/
http.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import fs from 'fs'
import path from 'path'
import { Server as HttpServer } from 'http'
import { ServerOptions as HttpsServerOptions } from 'https'
import { isObject } from './utils'
import { ProxyOptions } from './server/middlewares/proxy'
import { Connect } from 'types/connect'
import { Logger } from './logger'
export interface CommonServerOptions {
/**
* Specify server port. Note if the port is already being used, Vite will
* automatically try the next available port so this may not be the actual
* port the server ends up listening on.
*/
port?: number
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean
/**
* Specify which IP addresses the server should listen on.
* Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
*/
host?: string | boolean
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | HttpsServerOptions
/**
* Open browser window on startup
*/
open?: boolean | string
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean
}
/**
* https://github.com/expressjs/cors#configuration-options
*/
export interface CorsOptions {
origin?:
| CorsOrigin
| ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void)
methods?: string | string[]
allowedHeaders?: string | string[]
exposedHeaders?: string | string[]
credentials?: boolean
maxAge?: number
preflightContinue?: boolean
optionsSuccessStatus?: number
}
export type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]
export async function resolveHttpServer(
{ proxy }: CommonServerOptions,
app: Connect.Server,
httpsOptions?: HttpsServerOptions
): Promise<HttpServer> {
if (!httpsOptions) {
return require('http').createServer(app)
}
if (proxy) {
// #484 fallback to http1 when proxy is needed.
return require('https').createServer(httpsOptions, app)
} else {
return require('http2').createSecureServer(
{
...httpsOptions,
allowHTTP1: true
},
app
)
}
}
export async function resolveHttpsConfig(
https?: boolean | HttpsServerOptions
): Promise<HttpsServerOptions | undefined> {
if (!https) return undefined
const httpsOption = isObject(https) ? https : {}
const { ca, cert, key, pfx } = httpsOption
Object.assign(httpsOption, {
ca: readFileIfExists(ca),
cert: readFileIfExists(cert),
key: readFileIfExists(key),
pfx: readFileIfExists(pfx)
})
if (!httpsOption.key || !httpsOption.cert) {
httpsOption.cert = httpsOption.key = getCertificate()
}
return httpsOption
}
function readFileIfExists(value?: string | Buffer | any[]) {
if (typeof value === 'string') {
try {
return fs.readFileSync(path.resolve(value as string))
} catch (e) {
return value
}
}
return value
}
function getCertificate() {
return fs.readFileSync(
path.join(__dirname, '..', '..', '..', 'dev-cert.pem'),
'utf-8'
)
}
export async function httpServerStart(
httpServer: HttpServer,
serverOptions: {
port: number
strictPort: boolean | undefined
host: string | undefined
logger: Logger
}
): Promise<number> {
return new Promise((resolve, reject) => {
let { port, strictPort, host, logger } = serverOptions
const onError = (e: Error & { code?: string }) => {
if (e.code === 'EADDRINUSE') {
if (strictPort) {
httpServer.removeListener('error', onError)
reject(new Error(`Port ${port} is already in use`))
} else {
logger.info(`Port ${port} is in use, trying another one...`)
httpServer.listen(++port, host)
}
} else {
httpServer.removeListener('error', onError)
reject(e)
}
}
httpServer.on('error', onError)
httpServer.listen(port, host, () => {
httpServer.removeListener('error', onError)
resolve(port)
})
})
}