const fs = require('node:fs'); const path = require('node:path'); const development = require('./development.json'); function internal(value, dev) { const url = new URL(value); const p = url.hostname.split('.').map(Number); const ipv4 = p.length === 4 && p.every(v => Number.isInteger(v) && v >= 0 && v <= 255); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || !(ipv4 && (p[0] === 10 || p[0] === 192 && p[1] === 168 || p[0] === 172 && p[1] >= 16 && p[1] <= 31) || dev && ['localhost', '127.0.0.1'].includes(url.hostname))) throw Error('App 地址必须是内网 IPv4 地址;开发环境也可用 localhost。'); return url.toString().replace(/\/$/, ''); } function environment(env = process.env) { const variant = env.APP_ENV || 'dev'; if (!['dev', 'prod'].includes(variant)) throw Error('APP_ENV 只能是 dev 或 prod'); const dev = variant === 'dev'; const apiUrl = internal(env.APP_API_URL || (dev ? development.apiUrl : ''), dev); // Installed development apps reach the development PC, not the phone or production server. // API selection remains independent and editable from the development app. const updateOrigin = internal(env.APP_UPDATE_ORIGIN || (dev ? development.updateOrigin : ''), dev); if (new URL(updateOrigin).pathname !== '/') throw Error('APP_UPDATE_ORIGIN 只能包含协议、内网地址和端口。'); const certificate = path.resolve(__dirname, '../certs', `${variant}.pem`); if (!dev && !fs.existsSync(certificate)) throw Error('正式构建必须先配置 certs/prod.pem 更新签名证书。'); return { variant, apiUrl, updateOrigin, certificate, updatesEnabled: fs.existsSync(certificate) }; } module.exports = { environment, internal };