server.ts
10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFileSync, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio';
import type { JobStore } from './jobStore';
import type { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { configView, loadServerModelConfig, resolveServerOptions } from './config';
import type { GenerateRequest, Job, ServerConfigView } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_INDEX = path.join(__dirname, '..', 'public', 'index.html');
// Phase 2 前端工程构建产物:apps/web/dist。存在时优先托管它(支持 SPA 路由)。
const WEB_DIST = path.join(__dirname, '..', '..', 'web', 'dist');
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.map': 'application/json',
};
function serveStaticFile(res: ServerResponse, filePath: string): void {
try {
const data = readFileSync(filePath);
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
'Content-Type': MIME[ext] ?? 'application/octet-stream',
'Cache-Control': 'no-cache',
});
res.end(data);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
}
}
function resolveIndexHtml(): string {
if (WEB_DIST && existsSync(path.join(WEB_DIST, 'index.html'))) {
return path.join(WEB_DIST, 'index.html');
}
return PUBLIC_INDEX;
}
export interface ServerDeps {
store: JobStore;
queue: JobQueue;
preview: PreviewManager;
}
export interface AppHandle {
server: ReturnType<typeof createServer>;
/** Broadcast an SSE event to all connected clients. */
broadcast: (event: string, data: unknown) => void;
}
export function createApp(deps: ServerDeps): AppHandle {
const { store, queue, preview } = deps;
const sseClients = new Set<ServerResponse>();
const opts = resolveServerOptions();
const model = loadServerModelConfig();
const broadcast = (event: string, data: unknown): void => {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of sseClients) {
try {
res.write(payload);
} catch {
sseClients.delete(res);
}
}
};
// Forward engine logs to every connected SSE client.
subscribeLogs((entry: LogEntry) => broadcast('log', entry));
const sendJson = (res: ServerResponse, code: number, obj: unknown): void => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(obj));
};
const readBody = (req: IncomingMessage): Promise<string> =>
new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
if (data.length > 5 * 1024 * 1024) req.destroy();
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);
// ---- Built web static assets (apps/web/dist) ----
if (req.method === 'GET' && WEB_DIST && url.pathname.startsWith('/assets/')) {
const fp = path.join(WEB_DIST, decodeURIComponent(url.pathname));
if (existsSync(fp) && statSync(fp).isFile()) {
serveStaticFile(res, fp);
return;
}
}
// ---- SPA root / index ----
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
return;
}
// ---- SPA fallback (client-side routing, non-asset GET) ----
if (
req.method === 'GET' &&
!url.pathname.startsWith('/api') &&
!path.extname(url.pathname)
) {
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
return;
}
}
// ---- SSE stream ----
if (req.method === 'GET' && url.pathname === '/api/stream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
sseClients.add(res);
broadcast('jobs', store.list()); // replay current jobs snapshot
res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`);
const ping = setInterval(() => {
try {
res.write(': ping\n\n');
} catch {
/* ignore */
}
}, 15000);
req.on('close', () => {
clearInterval(ping);
sseClients.delete(res);
});
return;
}
// ---- GET /api/config ----
if (req.method === 'GET' && url.pathname === '/api/config') {
const view: ServerConfigView = configView(model, opts.maxConcurrent);
sendJson(res, 200, view);
return;
}
// ---- POST /api/generate ----
if (req.method === 'POST' && url.pathname === '/api/generate') {
const raw = await readBody(req);
let body: GenerateRequest;
try {
body = JSON.parse(raw || '{}');
} catch {
sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const figmaUrl = (body.figmaUrl || '').trim();
if (!figmaUrl) {
sendJson(res, 400, { error: 'figmaUrl 为必填项' });
return;
}
try {
parseFigmaUrl(figmaUrl);
} catch {
sendJson(res, 400, {
error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
});
return;
}
const mode =
body.mode && ['full', 'code', 'with-report'].includes(body.mode)
? body.mode
: 'full';
const job: Job = {
id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
status: 'queued',
figmaUrl,
mode,
outputDir: body.outputDir
? path.resolve(body.outputDir)
: opts.outputDir,
appName: body.appName || 'my-app',
resultDir: null,
reportPath: null,
error: null,
pid: null,
createdAt: new Date().toISOString(),
startedAt: null,
finishedAt: null,
};
queue.submit(job);
const position = queue.position(job.id);
sendJson(res, 200, {
jobId: job.id,
position,
message:
position > 0
? `已加入队列,前方还有 ${position} 个任务`
: '开始生成',
});
return;
}
// ---- GET /api/jobs ----
if (req.method === 'GET' && url.pathname === '/api/jobs') {
sendJson(res, 200, { jobs: store.list() });
return;
}
// ---- GET /api/job/:id ----
if (req.method === 'GET' && url.pathname.startsWith('/api/job/')) {
const id = url.pathname.slice('/api/job/'.length);
const job = store.get(id);
sendJson(res, job ? 200 : 404, job ?? { error: 'not found' });
return;
}
// ---- GET /api/preview ----
if (req.method === 'GET' && url.pathname === '/api/preview') {
sendJson(res, 200, preview.state);
return;
}
// ---- POST /api/preview (start) ----
if (req.method === 'POST' && url.pathname === '/api/preview') {
const raw = await readBody(req);
let body: { appPath?: string } = {};
try {
body = JSON.parse(raw || '{}');
} catch {
/* ignore */
}
const latestDone = store
.list()
.find((j) => j.status === 'done' && j.resultDir);
const appPath =
body.appPath ||
PreviewManager.defaultAppPath(latestDone?.resultDir ?? null);
const r = preview.start(appPath);
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- POST /api/preview/stop ----
if (req.method === 'POST' && url.pathname === '/api/preview/stop') {
preview.stop();
sendJson(res, 200, { ok: true });
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
} catch (err) {
sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
}
});
return { server, broadcast };
}