-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.ts
175 lines (153 loc) Β· 4.34 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
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
import './shim'
import http from 'http'
import https from 'https'
import { promisify } from 'util'
import { promises as fs } from 'fs'
import { networkInterfaces } from 'os'
import { cyan, gray, underline, bold } from 'colorette'
import type { SelfsignedOptions } from 'selfsigned'
import { getPort, GetPortInput } from 'get-port-please'
import addShutdown from 'http-shutdown'
import defu from 'defu'
export interface Certificate {
key: string
cert: string
}
export interface CertificateInput {
key: string
cert: string
}
export interface ListenOptions {
name: string
port?: GetPortInput,
hostname?: string,
https?: boolean
selfsigned?: SelfsignedOptions
showURL: boolean
baseURL: string
open: boolean
certificate: Certificate
clipboard: boolean
isTest: Boolean
isProd: Boolean
autoClose: Boolean
autoCloseSignals: string[]
}
export interface Listener {
url: string,
server: http.Server | https.Server,
close: () => Promise<void>,
open: () => Promise<void>,
showURL: () => void
}
export async function listen (handle: http.RequestListener, opts: Partial<ListenOptions> = {}): Promise<Listener> {
opts = defu(opts, {
port: process.env.PORT || 3000,
hostname: process.env.HOST || '0.0.0.0',
showURL: true,
baseURL: '/',
open: false,
clipboard: false,
isTest: process.env.NODE_ENV === 'test',
isProd: process.env.NODE_ENV === 'production',
autoClose: true
})
if (opts.isTest) {
opts.showURL = false
}
if (opts.isProd || opts.isTest) {
opts.open = false
opts.clipboard = false
}
const port = await getPort(opts.port)
let server: http.Server | https.Server
let url: string
const isExternal = opts.hostname === '0.0.0.0'
const displayHost = isExternal ? 'localhost' : opts.hostname
if (opts.https) {
const { key, cert } = opts.certificate ? await resolveCert(opts.certificate) : await getSelfSignedCert(opts.selfsigned)
server = https.createServer({ key, cert }, handle)
addShutdown(server)
// @ts-ignore
await promisify(server.listen.bind(server))(port, opts.host)
url = `https://${displayHost}:${port}${opts.baseURL}`
} else {
server = http.createServer(handle)
addShutdown(server)
// @ts-ignore
await promisify(server.listen.bind(server))(port, opts.host)
url = `http://${displayHost}:${port}${opts.baseURL}`
}
let _closed = false
const close = () => {
if (_closed) {
return Promise.resolve()
}
_closed = true
return promisify((server as any).shutdown)()
}
if (opts.clipboard) {
const clipboardy = await import('clipboardy').then(r => r.default || r)
await clipboardy.write(url).catch(() => { opts.clipboard = false })
}
const showURL = () => {
const add = opts.clipboard ? gray('(copied to clipboard)') : ''
const lines = []
lines.push(` > Local: ${formatURL(url)} ${add}`)
if (isExternal) {
for (const ip of getExternalIps()) {
lines.push(` > Network: ${formatURL(url.replace('localhost', ip))}`)
}
}
// eslint-disable-next-line no-console
console.log('\n' + lines.join('\n') + '\n')
}
if (opts.showURL) {
showURL()
}
const _open = async () => {
const { default: open } = await import('open')
await open(url).catch(() => { })
}
if (opts.open) {
await _open()
}
if (opts.autoClose) {
process.on('exit', () => close())
}
return <Listener>{
url,
server,
open: _open,
showURL,
close
}
}
async function resolveCert (input: CertificateInput): Promise<Certificate> {
const key = await fs.readFile(input.key, 'utf-8')
const cert = await fs.readFile(input.cert, 'utf-8')
return { key, cert }
}
async function getSelfSignedCert (opts: SelfsignedOptions = {}): Promise<Certificate> {
// @ts-ignore
const { generate } = await import('selfsigned')
// @ts-ignore
const { private: key, cert } = await promisify(generate)(opts.attrs, opts)
return { key, cert }
}
function getExternalIps (): string[] {
const ips = new Set<string>()
for (const details of Object.values(networkInterfaces())) {
if (details) {
for (const d of details) {
if (d.family === 'IPv4' && !d.internal) {
ips.add(d.address)
}
}
}
}
return Array.from(ips)
}
function formatURL (url: string) {
return cyan(underline(decodeURI(url).replace(/:(\d+)\//g, `:${bold('$1')}/`)))
}