import fs from 'node:fs'; import path from 'node:path'; export interface Config { botToken: string; clientId: string; clientSecret: string; /** 사이트 바깥 주소 (끝 / 없음). OAuth 돌아올 주소는 /callback */ publicUrl: string; host: string; port: number; dataDir: string; operatorName: string; /** 비어 있으면 봇이 들어간 모든 서버 */ allowedGuildIds: Set; /** 앱 연결 키를 만들어 녹음할 서버를 켜고 끌 수 있는 디스코드 아이디 */ adminIds: Set; channelNotice: boolean; /** 테스트에서 가짜 디스코드 API 로 바꿀 때만 */ discordApi: string; discordAuthorizeUrl: string; } /** KEY=VALUE 형식 .env (따옴표 · 주석 지원, 이미 있는 환경 변수는 덮어쓰지 않음) */ export function loadDotEnv(file: string): void { if (!fs.existsSync(file)) return; for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) { const m = /^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line); if (!m || line.trimStart().startsWith('#')) continue; let v = m[2]; if (/^(['"]).*\1$/.test(v)) v = v.slice(1, -1); if (process.env[m[1]] === undefined) process.env[m[1]] = v; } } export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true): Config { const req = (k: string) => { const v = env[k]?.trim(); if (!v) throw new Error(`환경 변수 ${k} 가 비어 있습니다 (.env.example 참고)`); return v; }; const publicUrl = req('PUBLIC_URL').replace(/\/+$/, ''); const u = new URL(publicUrl); if (u.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(u.hostname)) { throw new Error('PUBLIC_URL 은 https 여야 합니다 (localhost 만 예외)'); } return { botToken: needBot ? req('DISCORD_BOT_TOKEN') : env.DISCORD_BOT_TOKEN?.trim() ?? '', clientId: req('DISCORD_CLIENT_ID'), clientSecret: req('DISCORD_CLIENT_SECRET'), publicUrl, host: env.HOST?.trim() || '127.0.0.1', port: Number(env.PORT || 8787), dataDir: path.resolve(env.DATA_DIR?.trim() || './data'), operatorName: env.OPERATOR_NAME?.trim() || '사금향', allowedGuildIds: new Set((env.ALLOWED_GUILD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)), adminIds: new Set((env.ADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)), channelNotice: (env.CHANNEL_NOTICE ?? '1') !== '0', discordApi: env.DISCORD_API?.trim() || 'https://discord.com/api/v10', discordAuthorizeUrl: env.DISCORD_AUTHORIZE_URL?.trim() || 'https://discord.com/oauth2/authorize', }; }