import { z } from 'zod'; import { type ChronologicalValidationActionReceipt, type ChronologicalValidationFinalizationInput, type ChronologicalValidationSelectionInput, type ChronologicalValidationSubmission, type ChronologicalValidationSummary, type ValidationResultEvidence, } from '@stock-bot/stock-config/chronological-validation'; import { invalidValidationResponse as invalid, parseValidationDetail, validationReceiptSchema as receipt, sameValidationInput as same, validationSummarySchema as summary, ValidationApiError, } from '@stock-bot/stock-config/research-responses'; import { API_BASE_URL, apiFetch } from '@/lib/api'; export { parseValidationDetail, ValidationApiError, validationEvidenceSchema, type ValidationDetailView, } from '@stock-bot/stock-config/research-responses'; export type { ValidationResultEvidence }; const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key]; async function request( path: string, init: RequestInit, status: number, parse: (body: unknown) => T ): Promise { let response: Response; try { response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init); } catch (cause) { if (init.signal?.aborted) { throw cause; } throw new ValidationApiError( 'The validation response was lost. Retry the same request to recover its receipt.', null ); } const body: unknown = await response.json().catch(() => null); if (!response.ok) { const error = z.object({ error: z.string() }).safeParse(body); throw new ValidationApiError( error.success ? error.data.error : `Validation request failed (${response.status})`, response.status ); } try { if (response.status !== status) { throw invalid(); } return parse(body); } catch { throw invalid(); } } const post = (body: unknown, key?: string): RequestInit => ({ method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) }, }); export const chronologicalValidationDurableApi = { list: (backtestId?: string, signal?: AbortSignal) => request( backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '', { signal }, 200, body => { const rows = z.array(summary).parse(envelope(body, 'validations')); if ( new Set(rows.map(row => row.id)).size !== rows.length || (backtestId && rows.some(row => row.backtestId !== backtestId)) ) { throw invalid(); } return rows as ChronologicalValidationSummary[]; } ), get: (id: string, signal?: AbortSignal) => request(`/${encodeURIComponent(id)}`, { signal }, 200, body => { const value = parseValidationDetail(envelope(body, 'validation')); if (value.id !== id) { throw invalid(); } return value; }), submit: (input: ChronologicalValidationSubmission, key: string) => request('', post(input, key), 202, body => { const value = parseValidationDetail(envelope(body, 'validation')); const { previewHash, ...original } = input; if (value.previewHash !== previewHash || !same(value.preview.input, original)) { throw invalid(); } return value; }), advance: ( id: string, operation: 'select' | 'finalize', input: ChronologicalValidationSelectionInput | ChronologicalValidationFinalizationInput, key: string ) => request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => { const accepted = receipt.parse(envelope(body, 'receipt')); const value = parseValidationDetail(envelope(body, 'validation')); const record = operation === 'select' ? value.selection : value.report; if ( accepted.validationId !== id || value.id !== id || accepted.previewHash !== input.previewHash || value.previewHash !== input.previewHash || accepted.operation !== (operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') || accepted.selectionHash !== value.selection?.selectionHash || !record || accepted.id !== record.id || accepted.createdAt !== record.createdAt || accepted.principal !== record.principal || (operation === 'finalize' && (!('selectionHash' in input) || accepted.selectionHash !== input.selectionHash || !value.report)) ) { throw invalid(); } return { receipt: accepted as ChronologicalValidationActionReceipt, validation: value }; }), cancel: (id: string) => request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => { const value = parseValidationDetail(envelope(body, 'validation')); if (value.id !== id || !value.cancelRequested) { throw invalid(); } return value; }), };