import { spawn } from 'node:child_process' import type { IncomingMessage, ServerResponse } from 'node:http' import tailwindcss from '@tailwindcss/vite' import react from '@vitejs/plugin-react' import { defineConfig, type Plugin } from 'vite' async function readJson(req: IncomingMessage) { let body = '' for await (const chunk of req) body += chunk return body ? JSON.parse(body) : {} } /** POST /api/plan {template, topic?, feedback?, current?} → Claude가 기획한 칸별 문구. 화면과 npm run card --topic 이 같이 쓴다 */ function planApi(): Plugin { return { name: 'plan-api', configureServer(server) { server.middlewares.use('/api/plan', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { if (req.method !== 'POST') throw new Error('POST 로 보내 주세요') const body = await readJson(req) const { planContext } = await server.ssrLoadModule('/src/cards/context.ts') const ctx = await planContext(body.template, body.current) const { runPlan } = await import('./scripts/plan.mjs') res.end(JSON.stringify(await runPlan(ctx, body))) } catch (e) { server.config.logger.error(`[plan-api] ${e instanceof Error ? e.message : String(e)}`) res.statusCode = 500 res.end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) })) } }) }, } } type ImageJob = { status: 'idle' | 'running' | 'done' | 'failed'; total: number; done: number; current: string; log: string[] } const job: ImageJob = { status: 'idle', total: 0, done: 0, current: '', log: [] } /** 그림 한 종류(kind)의 id 들을 Codex로 하나씩 만든다 (scripts/gen-image.mjs). 사용량을 아끼려고 한 번에 한 장씩 */ function runGen(kind: string, ids: string[], force: boolean) { return new Promise((done) => { const p = spawn('node', ['scripts/gen-image.mjs', kind, ...ids, ...(force ? ['--force'] : [])], { cwd: import.meta.dirname }) let buf = '' const onLine = (chunk: Buffer) => { buf += chunk.toString() const lines = buf.split('\n') buf = lines.pop() ?? '' for (const line of lines.filter(Boolean)) { if (line.includes('그리는 중')) job.current = line.split(':')[0] if (/\.webp$/.test(line) || line.includes('이미 있어요')) job.done += 1 if (/: (\/|Codex|이미)/.test(line)) job.log.push(line) } } p.stdout.on('data', onLine) p.stderr.on('data', onLine) p.on('close', (code) => done(code === 0)) }) } /** POST /api/gen-image {template, copy, force?} → 이 카드에 없는 그림만 만들기 시작. GET 은 진행 상황 */ function imageApi(): Plugin { return { name: 'image-api', configureServer(server) { server.middlewares.use('/api/gen-image', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { if (req.method === 'GET') return res.end(JSON.stringify(job)) if (req.method !== 'POST') throw new Error('GET 또는 POST') if (job.status === 'running') return res.end(JSON.stringify(job)) const body = await readJson(req) const { missingImages } = await server.ssrLoadModule('/src/cards/context.ts') const missing: { kind: string; ids: string[] }[] = await missingImages(body.template, body.copy ?? {}, !!body.force) Object.assign(job, { status: missing.length ? 'running' : 'done', total: missing.reduce((n, m) => n + m.ids.length, 0), done: 0, current: '', log: [] }) res.end(JSON.stringify(job)) let ok = true for (const m of missing) ok = (await runGen(m.kind, m.ids, !!body.force)) && ok job.status = ok ? 'done' : 'failed' job.current = '' } catch (e) { server.config.logger.error(`[image-api] ${e instanceof Error ? e.message : String(e)}`) job.status = 'failed' if (!res.writableEnded) { res.statusCode = 500 res.end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) })) } } }) }, } } /** 날씨각 백엔드 카드뉴스 API 를 관리자 비밀값(ADMIN_API_KEY)을 붙여 대신 부른다. 비밀값은 이 서버에서만 쓰고 브라우저에 나가지 않는다 * POST /api/post {…카드 묶음} → POST /v1/card (저장·게시) · GET /api/cards → GET /v1/card (만든 카드 목록) · POST /api/cards//publish|reject */ function postApi(): Plugin { return { name: 'post-api', configureServer(server) { const api = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810' const headers = () => { const key = process.env.ADMIN_API_KEY if (!key) throw new Error('ADMIN_API_KEY 가 없어요. 백엔드와 같은 값을 환경변수로 주고 관리자 서버를 다시 켜 주세요') return { 'Content-Type': 'application/json', 'X-Admin-Key': key } } const relay = async (res: ServerResponse, r: Response) => { const text = await r.text() res.statusCode = r.ok ? 200 : r.status res.end(r.ok ? text : JSON.stringify({ error: `날씨각 API ${r.status}: ${text.slice(0, 200)}` })) } server.middlewares.use('/api/cards', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { const m = (req.url ?? '').match(/^\/(\d+)\/(publish|reject)$/) if (req.method === 'GET') return await relay(res, await fetch(`${api}/v1/card?limit=100`, { headers: headers() })) if (req.method === 'POST' && m) return await relay(res, await fetch(`${api}/v1/card/${m[1]}/${m[2]}`, { method: 'POST', headers: headers() })) throw new Error('GET /api/cards 또는 POST /api/cards//publish|reject') } catch (e) { server.config.logger.error(`[cards-api] ${e instanceof Error ? e.message : String(e)}`) res.statusCode = 500 res.end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) })) } }) server.middlewares.use('/api/post', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { if (req.method !== 'POST') throw new Error('POST 로 보내 주세요') const body = await readJson(req) if (!body.title) Object.assign(body, await (await server.ssrLoadModule('/src/cards/context.ts')).postText(body.template, body.texts)) await relay(res, await fetch(`${api}/v1/card`, { method: 'POST', headers: headers(), body: JSON.stringify(body) })) } catch (e) { server.config.logger.error(`[post-api] ${e instanceof Error ? e.message : String(e)}`) res.statusCode = 500 res.end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) })) } }) }, } } // 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png) export default defineConfig({ plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi()], publicDir: '../frontend/public', server: { port: 5175, strictPort: true }, })