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

+4 -1
View File
@@ -143,7 +143,10 @@
"invalid_link": "That link isn't valid.",
"fetch_failed": "We couldn't open that link.",
"empty_text": "Paste some text first.",
"no_file": "Choose a file first."
"no_file": "Choose a file first.",
"file_too_large": "The file is too large (max {mb} MB). Compress it or use the text or link method.",
"parse_failed": "We couldn't read the menu cleanly. Try less text or load it by sections.",
"output_truncated": "The menu is very long and got cut off. Load it in parts (e.g. one section at a time)."
}
},
"auth": {
+4 -1
View File
@@ -143,7 +143,10 @@
"invalid_link": "El link no es válido.",
"fetch_failed": "No pudimos abrir ese link.",
"empty_text": "Pega algo de texto primero.",
"no_file": "Elige un archivo primero."
"no_file": "Elige un archivo primero.",
"file_too_large": "El archivo es muy grande (máx {mb} MB). Comprímelo o usa el método de texto o link.",
"parse_failed": "No pudimos leer bien el menú. Intenta con menos texto o cárgalo por secciones.",
"output_truncated": "El menú es muy extenso y se cortó. Cárgalo por partes (por ejemplo, una sección a la vez)."
}
},
"auth": {
+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 });
}
}
+7 -1
View File
@@ -58,7 +58,13 @@ export default function ImportModal({
const res = await fetch(`/api/${slug}/import`, { method: 'POST', body: form });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(t.has(`errors.${data.error}`) ? t(`errors.${data.error}`) : t('errors.import_failed'));
if (data.error === 'file_too_large') {
setError(t('errors.file_too_large', { mb: data.maxMb ?? 4.5 }));
} else if (data.error && t.has(`errors.${data.error}`)) {
setError(t(`errors.${data.error}`));
} else {
setError(t('errors.import_failed'));
}
return;
}
const data = await res.json();
+76 -3
View File
@@ -32,6 +32,20 @@ const XLSX_MIMES = [
'application/vnd.ms-excel',
];
// Visual files (image/PDF) are base64-encoded into the request, which inflates
// size ~33%. Keep the raw file well under Anthropic's request ceiling so a big
// upload fails fast with a clear message instead of a 413 from the API.
export const MAX_VISUAL_FILE_MB = 4.5;
const MAX_VISUAL_FILE_BYTES = Math.round(MAX_VISUAL_FILE_MB * 1024 * 1024);
// Raised by resolveSource; carries the limit so the UI can show "máx X MB".
export class FileTooLargeError extends Error {
constructor(public readonly maxMb: number) {
super('file_too_large');
this.name = 'FileTooLargeError';
}
}
// Prompt that drives structured extraction. Both ES and EN are requested so the
// imported menu is bilingual from the start; inferred macros/allergens are flagged.
function systemPrompt(defaultLocale: Locale): string {
@@ -55,6 +69,8 @@ function systemPrompt(defaultLocale: Locale): string {
'"macros":{"protein":0,"carbs":0,"sugar":0,"fat":0,"fiber":0,"kcal":0},',
'"aiEstimated":{"macros":true,"allergens":true}}]}]}',
'Do not invent dishes that are not in the source. No prose, no code fences.',
'Output COMPACT JSON with no extra whitespace. Keep descriptions short (one sentence).',
'Return only the JSON object and make sure it is complete and valid (all braces closed).',
].join(' ');
}
@@ -115,6 +131,11 @@ export async function resolveSource(input: {
const mime = file.type;
const buffer = Buffer.from(await file.arrayBuffer());
const isVisual = (IMAGE_MIMES as readonly string[]).includes(mime) || mime === PDF_MIME;
if (isVisual && buffer.length > MAX_VISUAL_FILE_BYTES) {
throw new FileTooLargeError(MAX_VISUAL_FILE_MB);
}
if ((IMAGE_MIMES as readonly string[]).includes(mime)) {
return { kind: 'image', data: buffer.toString('base64'), mediaType: mime, visual: true };
}
@@ -154,14 +175,66 @@ export async function extractMenu(
const msg = await client.messages.create({
model: source.visual ? SONNET_MODEL : HAIKU_MODEL,
max_tokens: 4000,
max_tokens: 8000,
system: systemPrompt(defaultLocale),
messages: [{ role: 'user', content }],
});
const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
const parsed = JSON.parse(extractJson(text));
return { sections: normalizeSections(parsed?.sections) };
const parsed = parseMenuJson(text);
if (!parsed) {
// Truncation (hit the token ceiling) vs other malformed output.
throw new Error(msg.stop_reason === 'max_tokens' ? 'output_truncated' : 'parse_failed');
}
return { sections: normalizeSections(parsed.sections) };
}
// Parse the model's JSON tolerantly: handle fences/surrounding prose via
// extractJson, and attempt to repair JSON truncated by the token limit by
// closing any open strings/brackets and dropping a trailing partial entry.
// Returns null if it still can't be parsed (caller maps to a friendly error).
function parseMenuJson(text: string): { sections?: unknown } | null {
const candidate = extractJson(text);
const attempts = [candidate, repairTruncatedJson(candidate)];
for (const a of attempts) {
try {
const obj = JSON.parse(a);
if (obj && typeof obj === 'object') return obj as { sections?: unknown };
} catch {
/* try next */
}
}
return null;
}
// Best-effort repair of JSON cut off mid-output: close an open string, drop a
// dangling trailing fragment, then balance the remaining open { and [.
function repairTruncatedJson(input: string): string {
let inStr = false;
let esc = false;
const stack: string[] = [];
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (inStr) {
if (esc) esc = false;
else if (ch === '\\') esc = true;
else if (ch === '"') inStr = false;
continue;
}
if (ch === '"') inStr = true;
else if (ch === '{' || ch === '[') stack.push(ch);
else if (ch === '}' || ch === ']') stack.pop();
}
let out = input;
if (inStr) out += '"';
// Drop a trailing incomplete property like `"price":` or a dangling comma.
out = out.replace(/[\s,]*("[^"]*"\s*:\s*)?$/u, '');
out = out.replace(/[\s,]+$/u, '');
for (let i = stack.length - 1; i >= 0; i--) {
out += stack[i] === '{' ? '}' : ']';
}
return out;
}
// Defensive normalization so a partially-malformed model reply can't crash apply.