forked from vitejs/vite-plugin-basic-ssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
68 lines (60 loc) · 1.73 KB
/
index.ts
File metadata and controls
68 lines (60 loc) · 1.73 KB
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
import path from 'node:path'
import { promises as fsp } from 'node:fs'
import type { Plugin } from 'vite'
const defaultCacheDir = 'node_modules/.vite'
interface Options {
certDir: string
domains: string[]
name: string
ttlDays: number
}
function viteBasicSslPlugin(options?: Partial<Options>): Plugin {
return {
name: 'vite:basic-ssl',
async configResolved(config) {
const certificate = await getCertificate(
options?.certDir ?? (config.cacheDir ?? defaultCacheDir) + '/basic-ssl',
options?.name,
options?.domains,
options?.ttlDays,
)
const https = () => ({ cert: certificate, key: certificate })
if (config.server.https === undefined || !!config.server.https) {
config.server.https = Object.assign({}, config.server.https, https())
}
if (config.preview.https === undefined || !!config.preview.https) {
config.preview.https = Object.assign({}, config.preview.https, https())
}
},
}
}
export async function getCertificate(
cacheDir: string,
name?: string,
domains?: string[],
ttlDays?: number,
) {
const cachePath = path.join(cacheDir, '_cert.pem')
try {
const [stat, content] = await Promise.all([
fsp.stat(cachePath),
fsp.readFile(cachePath, 'utf8'),
])
if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
throw new Error('cache is outdated.')
}
return content
} catch {
const content = (await import('./certificate')).createCertificate(
name,
domains,
ttlDays,
)
fsp
.mkdir(cacheDir, { recursive: true })
.then(() => fsp.writeFile(cachePath, content))
.catch(() => {})
return content
}
}
export default viteBasicSslPlugin