import { spawn } from 'node:child_process' import { createReadStream, existsSync } from 'node:fs' import type { IncomingMessage, ServerResponse } from 'node:http' import { basename, resolve } from 'node:path' 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) })) } } }) }, } } /** 올릴 곳. 로컬(이 Mac 백엔드)과 킹서버(운영). 비밀값은 이 서버에서만 쓰고 브라우저엔 안 나간다 */ type Target = { id: 'local' | 'king'; label: string; api: string; key?: string; site: string } const TARGETS: Target[] = [ { id: 'local', label: '로컬', api: process.env.VITE_API_BASE_URL ?? 'http://localhost:9810', key: process.env.ADMIN_API_KEY, site: process.env.LOCAL_SITE_URL ?? 'http://localhost:5174' }, { id: 'king', label: '킹서버', api: process.env.KING_API_BASE_URL ?? 'https://weather.o2o.kr', key: process.env.KING_ADMIN_API_KEY, site: process.env.KING_SITE_URL ?? 'https://weather.o2o.kr' }, ].filter((t) => !!t.key) as Target[] function targetOf(req: IncomingMessage) { const id = new URL(req.url ?? '/', 'http://x').searchParams.get('target') ?? TARGETS[0]?.id const t = TARGETS.find((x) => x.id === id) if (!t) throw new Error(id ? `'${id}' 에 올릴 비밀값이 없어요 (ADMIN_API_KEY / KING_ADMIN_API_KEY)` : 'ADMIN_API_KEY 가 없어요. 백엔드와 같은 값을 환경변수로 주고 관리자 서버를 다시 켜 주세요') return t } /** 날씨각 백엔드 카드뉴스 API 를 대신 부른다 (?target=local|king) * GET /api/targets · POST /api/post {…카드 묶음} → POST /v1/card · GET /api/cards → GET /v1/card · POST /api/cards//publish|reject|instagram */ function postApi(): Plugin { return { name: 'post-api', configureServer(server) { 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)}` })) } const headers = (t: Target) => ({ 'Content-Type': 'application/json', 'X-Admin-Key': t.key! }) server.middlewares.use('/api/targets', (_req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') res.end(JSON.stringify(TARGETS.map(({ id, label, site, api }) => ({ id, label, site, api })))) }) server.middlewares.use('/api/cards', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { const t = targetOf(req) const path = (req.url ?? '').split('?')[0] const m = path.match(/^\/(\d+)\/(publish|reject|instagram)$/) if (req.method === 'GET') return await relay(res, await fetch(`${t.api}/v1/card?limit=100`, { headers: headers(t) })) if (req.method === 'POST' && m) return await relay(res, await fetch(`${t.api}/v1/card/${m[1]}/${m[2]}`, { method: 'POST', headers: headers(t) })) throw new Error('GET /api/cards 또는 POST /api/cards//publish|reject|instagram') } 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) })) } }) // 릴스: GET /api/reel → 목록 · POST /api/reel {title, caption, hashtags, video, cover?} → 저장 · POST /api/reel//instagram → 인스타에 올리기 server.middlewares.use('/api/reel', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { const t = targetOf(req) const path = (req.url ?? '').split('?')[0] const m = path.match(/^\/(\d+)\/instagram$/) if (req.method === 'GET') return await relay(res, await fetch(`${t.api}/v1/reel?limit=100`, { headers: headers(t) })) if (req.method === 'POST' && m) return await relay(res, await fetch(`${t.api}/v1/reel/${m[1]}/instagram`, { method: 'POST', headers: headers(t) })) if (req.method === 'POST' && path === '/') return await relay(res, await fetch(`${t.api}/v1/reel`, { method: 'POST', headers: headers(t), body: JSON.stringify(await readJson(req)) })) throw new Error('GET /api/reel · POST /api/reel · POST /api/reel//instagram') } catch (e) { server.config.logger.error(`[reel-api] ${e instanceof Error ? e.message : String(e)}`) res.statusCode = 500 res.end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) })) } }) // 가입자: GET /api/users → GET /v1/admin/users server.middlewares.use('/api/users', async (req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8') try { if (req.method !== 'GET') throw new Error('GET /api/users') const t = targetOf(req) return await relay(res, await fetch(`${t.api}/v1/admin/users?limit=2000`, { headers: headers(t) })) } catch (e) { server.config.logger.error(`[users-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 t = targetOf(req) 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(`${t.api}/v1/card`, { method: 'POST', headers: headers(t), 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) })) } }) }, } } /** GET /daily/<날짜>-<사람>.webp → public/daily (scripts/daily-ootd.mjs 가 만든 그날 코디 그림). publicDir 는 프론트 아이콘용이라 따로 서빙 */ function dailyImages(): Plugin { return { name: 'daily-images', configureServer(server) { server.middlewares.use('/daily', (req, res, next) => { const name = basename((req.url ?? '').split('?')[0]) const file = resolve(import.meta.dirname, 'public/daily', name) if (!name.endsWith('.webp') || !existsSync(file)) return next() res.setHeader('Content-Type', 'image/webp') res.setHeader('Cache-Control', 'no-cache') createReadStream(file).pipe(res) }) }, } } // 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png) export default defineConfig({ plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi(), dailyImages()], publicDir: '../frontend/public', server: { port: 5175, strictPort: true }, })