|
| 1 | +import { spawnSync } from 'node:child_process'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | + |
| 6 | +const CERT_DIR = path.resolve('.cert'); |
| 7 | +const CERT_FILE = path.join(CERT_DIR, 'cert.pem'); |
| 8 | +const KEY_FILE = path.join(CERT_DIR, 'key.pem'); |
| 9 | +const MKCERT_HELP = `mkcert failed. |
| 10 | +
|
| 11 | +Install mkcert, run: |
| 12 | + mkcert -install |
| 13 | +
|
| 14 | +Then re-run: |
| 15 | + npm run cert`; |
| 16 | + |
| 17 | +export const ALLOWED_HOSTS = ['localhost', '.local']; |
| 18 | + |
| 19 | +/** |
| 20 | + * @returns {{ cert: Buffer, key: Buffer } | undefined} vite https config. |
| 21 | + */ |
| 22 | +export const httpsConfig = () => { |
| 23 | + if (process.env.EXAMPLES_HTTPS !== '1') { |
| 24 | + return undefined; |
| 25 | + } |
| 26 | + |
| 27 | + if (!fs.existsSync(CERT_FILE) || !fs.existsSync(KEY_FILE)) { |
| 28 | + throw new Error( |
| 29 | + `HTTPS dev requested but certs not found in ${CERT_DIR}. ` + |
| 30 | + 'Run "npm run cert" to generate them.' |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + return { |
| 35 | + cert: fs.readFileSync(CERT_FILE), |
| 36 | + key: fs.readFileSync(KEY_FILE) |
| 37 | + }; |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * @param {string[]} hosts - extra host names or lan ips. |
| 42 | + * @returns {boolean} true if certs were generated. |
| 43 | + */ |
| 44 | +export const generateCertificates = (hosts) => { |
| 45 | + fs.mkdirSync(CERT_DIR, { recursive: true }); |
| 46 | + |
| 47 | + const local = process.platform === 'darwin' ? |
| 48 | + spawnSync('scutil', ['--get', 'LocalHostName'], { encoding: 'utf8' }) : null; |
| 49 | + const host = local?.status === 0 && local.stdout.trim() ? |
| 50 | + local.stdout.trim() : os.hostname().replace(/\.local$/, ''); |
| 51 | + const sans = [...new Set([ |
| 52 | + 'localhost', |
| 53 | + '127.0.0.1', |
| 54 | + '::1', |
| 55 | + `${host}.local`, |
| 56 | + ...hosts.map(value => value.trim()).filter(Boolean) |
| 57 | + ])]; |
| 58 | + |
| 59 | + console.log(`Generating dev cert for: ${sans.join(', ')}`); |
| 60 | + |
| 61 | + const result = spawnSync('mkcert', ['-cert-file', CERT_FILE, '-key-file', KEY_FILE, ...sans], { |
| 62 | + stdio: 'inherit' |
| 63 | + }); |
| 64 | + if (result.status !== 0) { |
| 65 | + console.error(MKCERT_HELP); |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + console.log(`Wrote ${path.relative(process.cwd(), CERT_FILE)} |
| 70 | +Wrote ${path.relative(process.cwd(), KEY_FILE)} |
| 71 | +
|
| 72 | +Start the HTTPS dev server with: |
| 73 | + npm run dev:https |
| 74 | +
|
| 75 | +Or without automatic reloads: |
| 76 | + npm run develop:https |
| 77 | +
|
| 78 | +Then open on this machine: |
| 79 | + https://${host}.local:${process.env.EXAMPLES_PORT ?? 5555} |
| 80 | + https://localhost:${process.env.EXAMPLES_PORT ?? 5555}`); |
| 81 | + |
| 82 | + return true; |
| 83 | +}; |
0 commit comments