-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal-api.ts
More file actions
322 lines (286 loc) · 9.23 KB
/
Copy pathexternal-api.ts
File metadata and controls
322 lines (286 loc) · 9.23 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { Hono } from "@hono/hono";
import { streamSSE } from "@hono/hono/streaming";
import type { Context, Next } from "@hono/hono";
import Anthropic from "@anthropic-ai/sdk";
import {
listApps,
getApp,
listEditRequests,
saveEditRequest,
logUsage,
isAppDisabled,
createAppPlaceholder,
getAppBuildStatus,
} from "./db.ts";
import {
generatePrd,
generateErd,
generateApp,
editApp,
backgroundGenerate,
type EditProgressEvent,
} from "./generate.ts";
const BASE_URL = "https://demo-generator.fly.dev";
function externalApiAuth(c: Context, next: Next) {
const apiKey = c.req.header("X-API-Key");
const expected = Deno.env.get("EXTERNAL_API_KEY");
if (!expected || apiKey !== expected) {
return c.json({ error: "Unauthorized" }, 401);
}
return next();
}
export function createExternalApiRoutes(anthropicClient: Anthropic): Hono {
const api = new Hono();
api.use("*", externalApiAuth);
// GET /api/external/apps — list all apps
api.get("/api/external/apps", (c) => {
const apps = listApps();
const result = apps.map((a) => {
const full = getApp(a.id);
return {
id: a.id,
title: a.title,
description: full?.description ?? "",
created_at: a.created_at,
disabled: full
? Boolean((full as Record<string, unknown>).disabled)
: false,
url: `${BASE_URL}/apps/${a.id}`,
};
});
return c.json(result);
});
// GET /api/external/apps/:appId — get app details
api.get("/api/external/apps/:appId", (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
const disabledStatus = isAppDisabled(appId);
return c.json({
id: record.id,
title: record.title,
description: record.description,
prd: record.prd,
erd: record.erd,
html: record.html,
disabled: disabledStatus.disabled,
created_at: record.created_at,
updated_at: record.updated_at,
url: `${BASE_URL}/apps/${appId}`,
});
});
// POST /api/external/apps — create a new app (SSE stream)
api.post("/api/external/apps", async (c) => {
let body: { title?: string; body?: string; context?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.body) {
return c.json({ error: "body (app description) is required" }, 400);
}
const title =
body.title ||
body.body
.split("\n")[0]
.replace(/^#+\s*/, "")
.slice(0, 100) ||
"Untitled App";
const description = body.body;
const context = body.context;
return streamSSE(c, async (stream) => {
try {
await stream.writeSSE({
event: "prd",
data: JSON.stringify({
step: "prd",
message: "Generating Product Requirements...",
}),
});
const prd = await generatePrd(description, title, anthropicClient, undefined, context);
await stream.writeSSE({
event: "prd_complete",
data: JSON.stringify({
step: "prd_complete",
message: "PRD complete",
}),
});
await stream.writeSSE({
event: "erd",
data: JSON.stringify({
step: "erd",
message: "Generating Engineering Requirements...",
}),
});
const erd = await generateErd(prd, title, anthropicClient, undefined, context);
await stream.writeSSE({
event: "erd_complete",
data: JSON.stringify({
step: "erd_complete",
message: "ERD complete",
}),
});
await stream.writeSSE({
event: "generating",
data: JSON.stringify({
step: "generating",
message: "Building app from requirements...",
}),
});
const result = await generateApp(
{ title, body: description, prd, erd, context },
anthropicClient
);
await stream.writeSSE({
event: "complete",
data: JSON.stringify({
step: "complete",
appId: result.appId,
credentials: result.credentials,
url: `${BASE_URL}/apps/${result.appId}`,
}),
});
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "App generation failed";
await stream.writeSSE({
event: "error",
data: JSON.stringify({ step: "error", message: msg }),
});
}
});
});
// POST /api/external/apps/:appId/edit — edit an existing app (SSE stream)
api.post("/api/external/apps/:appId/edit", async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
let body: { instruction?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.instruction) {
return c.json({ error: "instruction is required" }, 400);
}
saveEditRequest(appId, "external-api", body.instruction);
return streamSSE(c, async (stream) => {
try {
await editApp(
appId,
body.instruction!,
anthropicClient,
async (event: EditProgressEvent) => {
await stream.writeSSE({
event: event.step,
data: JSON.stringify(event),
});
}
);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Edit failed";
await stream.writeSSE({
event: "error",
data: JSON.stringify({ step: "error", message: msg }),
});
}
});
});
// GET /api/external/apps/:appId/edit-requests — list edit requests
api.get("/api/external/apps/:appId/edit-requests", (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
return c.json(listEditRequests(appId));
});
// POST /api/external/apps/:appId/edit-requests/summary — AI summary
api.post(
"/api/external/apps/:appId/edit-requests/summary",
async (c) => {
const appId = c.req.param("appId");
const record = getApp(appId);
if (!record) return c.json({ error: "App not found" }, 404);
const requests = listEditRequests(appId);
if (requests.length === 0) {
return c.json({ summary: "No edit requests to analyze." });
}
const requestList = requests
.map(
(r, i) =>
`${i + 1}. [${r.username}, ${r.created_at}] ${r.description}`
)
.join("\n");
try {
const message = await anthropicClient.messages.create({
model: "claude-sonnet-4-5-20250929",
max_tokens: 1024,
messages: [
{
role: "user",
content: `Summarize these edit requests from users of "${record.title}" demo app. Focus on: what features they want, what UX friction exists, and what it tells us about the prospect.\n\nEdit requests:\n${requestList}\n\nBe concise. Use bullet points.`,
},
],
});
logUsage(
appId,
"edit-summary",
"claude-sonnet-4-5-20250929",
message.usage.input_tokens,
message.usage.output_tokens
);
const summary =
message.content[0].type === "text"
? message.content[0].text
: "Unable to generate summary.";
return c.json({ summary });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : "Summary failed";
return c.json({ error: msg }, 500);
}
}
);
// POST /api/external/apps/async — create a new app (non-blocking, fire-and-forget)
api.post("/api/external/apps/async", async (c) => {
let body: { title?: string; body?: string; context?: string };
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
if (!body.body) {
return c.json({ error: "body (app description) is required" }, 400);
}
const title =
body.title ||
body.body
.split("\n")[0]
.replace(/^#+\s*/, "")
.slice(0, 100) ||
"Untitled App";
const description = body.body;
const context = body.context;
const appId = crypto.randomUUID();
createAppPlaceholder(appId, title, description);
backgroundGenerate(appId, title, description, anthropicClient, context);
return c.json({ appId, status: "building_prd" });
});
// GET /api/external/apps/:appId/status — check build status
api.get("/api/external/apps/:appId/status", (c) => {
const appId = c.req.param("appId");
const status = getAppBuildStatus(appId);
if (!status) return c.json({ error: "App not found" }, 404);
return c.json({
id: status.id,
title: status.title,
build_status: status.build_status || "ready",
failure_reason: status.failure_reason || "",
has_prd: status.has_prd,
has_erd: status.has_erd,
...(status.build_status === "ready" || !status.build_status
? { url: `${BASE_URL}/apps/${status.id}` }
: {}),
});
});
return api;
}