import { VOICE_ITEM_MAX_LENGTH, VOICE_MAX_ITEMS } from '@superlist/shared' /** * Trims every item, drops empty ones and caps the result: at most `VOICE_MAX_ITEMS` * items of at most `VOICE_ITEM_MAX_LENGTH` characters each. */ export function cleanItems(items: string[]): string[] { return items .map((item) => item.trim().slice(0, VOICE_ITEM_MAX_LENGTH).trim()) .filter(Boolean) .slice(0, VOICE_MAX_ITEMS) } /** * Plan B when the model cannot be used: splits on commas, semicolons, " y " and " e ". * A comma between digits is a decimal ("1,5 kg") and stays. */ export function fallbackSplit(text: string): string[] { return cleanItems(text.split(/\s*[;\n]\s*|\s*,\s*(?!\d)|\s+[ye]\s+/i)) } /** Removes a Markdown code fence around the answer (```json … ```), if any. */ function stripCodeFences(text: string): string { const fenced = /```(?:json|JSON)?\s*([\s\S]*?)```/.exec(text) return (fenced?.[1] ?? text).trim() } /** * The first balanced JSON array or object in `text`, skipping brackets inside strings. * Returns `null` when there is none. */ function firstJsonValue(text: string): string | null { const start = text.search(/[[{]/) if (start === -1) return null let depth = 0 let inString = false let escaped = false for (let index = start; index < text.length; index++) { const char = text[index] if (inString) { if (escaped) escaped = false else if (char === '\\') escaped = true else if (char === '"') inString = false continue } if (char === '"') inString = true else if (char === '[' || char === '{') depth++ else if (char === ']' || char === '}') { depth-- if (depth === 0) return text.slice(start, index + 1) } } return null } function tryParse(text: string): unknown { try { return JSON.parse(text) } catch { return undefined } } /** * Reads the model's answer: a JSON array of strings, possibly inside a code fence, * surrounded by prose or wrapped as `{ "items": [...] }`. Returns the cleaned items, * or `null` when the answer is not an array of strings. */ export function parseModelItems(answer: string): string[] | null { const unfenced = stripCodeFences(answer) let value = tryParse(unfenced) if (value === undefined) { const json = firstJsonValue(unfenced) value = json ? tryParse(json) : undefined } if (value && typeof value === 'object' && !Array.isArray(value) && 'items' in value) { value = value.items } if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) return null return cleanItems(value) }