import { validateStructuredOutput, type FieldEvidence, type OutputFieldContract, type TextSource, type ValidationIssue } from './structured-output-validation'; export type ValidatedExport = | { status: 'ready'; mediaType: 'application/json' | 'text/csv'; content: string } | { status: 'needs_review'; issues: ValidationIssue[] }; /** * Serialize a single, flat record after rechecking its evidence against the * supplied source text. This is an internal serializer, not an authorization, * completeness, semantic-correctness or source-authenticity check. * CSV rejects formula-like text rather than silently changing customer data; * JSON preserves it exactly. CSV also rejects absent optional fields so that * absence is never silently converted into an empty string. */ export function exportValidatedOutput(input: { format: 'json' | 'csv'; fields: readonly OutputFieldContract[]; value: unknown; sources: readonly TextSource[]; evidence: readonly FieldEvidence[]; }): ValidatedExport { if (input.format !== 'json' && input.format !== 'csv') { return { status: 'needs_review', issues: [{ field: '', code: 'unsupported_export_format' }] }; } const validation = validateStructuredOutput(input); if (validation.status !== 'mechanically_validated') return validation; const value = input.value as Record; const ordered: Record = Object.create(null) as Record; for (const field of input.fields) { if (Object.prototype.hasOwnProperty.call(value, field.name)) ordered[field.name] = value[field.name]!; else if (input.format === 'csv') { return { status: 'needs_review', issues: [{ field: field.name, code: 'csv_missing_value' }] }; } } if (input.format === 'json') { return { status: 'ready', mediaType: 'application/json', content: `${JSON.stringify(ordered, null, 2)}\n` }; } // Spreadsheet applications may interpret these prefixes as formulas even // in quoted CSV cells. Treat leading control characters as unsafe as well. const unsafe = (cell: string): boolean => /^[\t\r\n]/u.test(cell) || /^\s*[=+@-]/u.test(cell); for (const field of input.fields) { if (unsafe(field.name) || (field.type === 'string' && unsafe(ordered[field.name] as string))) { return { status: 'needs_review', issues: [{ field: field.name, code: 'csv_unsafe_cell' }] }; } } const quote = (cell: string): string => `"${cell.replaceAll('"', '""')}"`; const header = input.fields.map((field) => quote(field.name)).join(','); const row = input.fields.map((field) => quote(String(ordered[field.name]))).join(','); return { status: 'ready', mediaType: 'text/csv', content: `${header}\r\n${row}\r\n` }; }