Harden menu import: tolerate truncated JSON + reject oversized files

Bug 1 (malformed/truncated JSON crashed the route with SyntaxError):
- Raise extraction max_tokens 4000 -> 8000 and ask the model for compact, complete JSON
- Parse tolerantly: extractJson() for fences/prose, plus a repair pass that closes
  open strings/brackets and drops a trailing partial entry for token-truncated output
- Wrap JSON.parse; on failure return a friendly code (parse_failed, or output_truncated
  when stop_reason was max_tokens) instead of a raw 500

Bug 2 (40MB PDF -> Anthropic 413):
- Validate visual file size BEFORE calling the API (max 4.5MB raw; base64 inflates ~33%)
- Return 413 {error:file_too_large, maxMb} so the UI shows 'max X MB, compress or use text/link'

i18n: file_too_large (with {mb}), parse_failed, output_truncated (es/en); ImportModal
interpolates the size limit.

Verified: build passes; repair recovers mid-string/mid-property/fenced/prose JSON;
oversized upload returns 413 with the limit; text path fails gracefully (no crash).
This commit is contained in:
Jorem Juárez committed 2026-06-14 02:14:40 -06:00
1 parent 9a40a988e0
commit 9fad1d43aa
5 files changed
+112 -13

No files matched your search

+21 -7
View File
@@ -1,6 +1,6 @@
import { NextResponse } from 'next/server';
import { requireEditor } from '@/lib/guard';
import { resolveSource, extractMenu, type ImportMethod } from '@/lib/import';
import { resolveSource, extractMenu, FileTooLargeError, type ImportMethod } from '@/lib/import';
import type { Locale } from '@/i18n/config';
export const dynamic = 'force-dynamic';
@@ -34,12 +34,26 @@ export async function POST(req: Request, { params }: { params: { slug: string }
}
return NextResponse.json(result);
} catch (err) {
const code = err instanceof Error ? err.message : 'import_failed';
const known = ['empty_text', 'invalid_link', 'fetch_failed', 'no_file'];
console.error('import extract error', err);
return NextResponse.json(
{ error: known.includes(code) ? code : 'import_failed' },
{ status: known.includes(code) ? 400 : 502 },
);
// File too large: tell the user the limit so they can act.
if (err instanceof FileTooLargeError) {
return NextResponse.json(
{ error: 'file_too_large', maxMb: err.maxMb },
{ status: 413 },
);
}
const code = err instanceof Error ? err.message : 'import_failed';
// 400 = user-fixable input; 502 = upstream/model issue.
const userErrors = ['empty_text', 'invalid_link', 'fetch_failed', 'no_file'];
const modelErrors = ['parse_failed', 'output_truncated'];
if (userErrors.includes(code)) {
return NextResponse.json({ error: code }, { status: 400 });
}
if (modelErrors.includes(code)) {
return NextResponse.json({ error: code }, { status: 422 });
}
return NextResponse.json({ error: 'import_failed' }, { status: 502 });
}
}