Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / studio / route.ts

Raw 3.8 KB on f4d070c0cd6547ed6432bda0f7f1dc2cb2181b18
1import { hostedReadiness, studioDatabase } from '@/app/lib/studio-config';
2import { authOrigin, getCustomerUser } from '@/app/lib/lumen-auth';
3import { resolveImageModel } from '@/app/lib/image-models';
4import { cleanUpload, MAX_PIXELS, MAX_PROMPT, MAX_UPLOAD_BYTES, rawUpload, readStudioForm, StudioError } from '@/app/lib/studio-media';
5import { feedbackKey, studioFeedback, studioGenerate, studioModelKey } from '@/app/lib/studio-providers';
6import { reserveStudioCall, studioLimits } from '@/app/lib/studio-quota';
7
8export const runtime = 'nodejs';
9export const dynamic = 'force-dynamic';
10export const maxDuration = 75;
11
12const headers = { 'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff' };
13
14function unavailable() {
15 return new StudioError('studio_unavailable', 503, 'Hosted studio generation isn’t available right now. You can still work with your own image.');
16}
17
18function outputError(error: unknown) {
19 const safe = error instanceof StudioError ? error : unavailable();
20 return Response.json({ error: safe.message, code: safe.code }, { status: safe.status, headers });
21}
22
23export async function GET() {
24 const signedIn = Boolean(await getCustomerUser().catch(() => null));
25 return Response.json({ signedIn, ...await hostedReadiness(), maxUploadBytes: MAX_UPLOAD_BYTES, maxPixels: MAX_PIXELS, maxPromptLength: MAX_PROMPT }, { headers });
26}
27
28export async function POST(req: Request) {
29 try {
30 const canonical = authOrigin();
31 if (req.headers.get('origin') !== canonical || new URL(req.url).origin !== canonical) throw new StudioError('invalid_origin', 403, 'Open the studio directly to send this request.');
32 const user = await getCustomerUser().catch(() => null);
33 if (!user) throw new StudioError('sign_in', 401, 'Sign in to use the hosted image models.');
34 const limits = studioLimits();
35 if (!limits) throw unavailable();
36 const content = await readStudioForm(req);
37 const action = content.get('action');
38 if (action !== 'generate' && action !== 'revise' && action !== 'feedback') {
39 throw new StudioError('invalid_request', 400, 'Choose generate, revise, or feedback.');
40 }
41 const model = resolveImageModel(content.get('model'));
42 if (action !== 'feedback' && !model) throw new StudioError('invalid_model', 400, 'Choose one of the studio models.');
43 const key = action === 'feedback' ? feedbackKey() : model && studioModelKey(model);
44 if (!key) throw unavailable();
45 const promptEntry = content.get('prompt');
46 if (promptEntry !== null && typeof promptEntry !== 'string') {
47 throw new StudioError('invalid_prompt', 400, 'Enter a text prompt.');
48 }
49 const prompt = promptEntry?.trim() ?? '';
50 if (prompt.length > MAX_PROMPT || (!prompt && action !== 'feedback')) {
51 throw new StudioError('invalid_prompt', 400, 'Describe what you want in 1–1,200 characters.');
52 }
53 const source = content.get('image');
54 if (typeof source === 'string' || (action !== 'generate' && !source)) {
55 throw new StudioError('invalid_image', 400, 'Choose an uploaded image first.');
56 }
57 const raw = source ? await rawUpload(source) : undefined;
58 const db = studioDatabase();
59 if (!await reserveStudioCall(db, user.id, limits)) {
60 throw new StudioError('studio_limit', 429, 'The free studio’s usage limit has been reached. Your local image is still available.');
61 }
62
63 const image = raw ? await cleanUpload(raw) : undefined;
64 if (action === 'feedback' && image) return Response.json({ feedback: await studioFeedback(image, prompt, key) }, { headers });
65 if (!model) throw unavailable();
66 const result = await studioGenerate({ model, prompt, image }, key);
67 return new Response(new Uint8Array(result.bytes), { headers: { ...headers, 'content-type': result.mime } });
68 } catch (error) { return outputError(error); }
69}