import { isRecord, isUuid } from '@d3ro/core/guards' import type { RealtimeChannel } from '@supabase/supabase-js' import type { DictationTemplateField, MeetingDocument, TemplateKind, UserTemplate, UserTemplateSelection, } from '@d3ro/api-client' import { SUPABASE_URL } from '@d3ro/core/supabase-config' import { supabase } from '../../lib/supabase' import { createLabeledUuidAssert, extractSupabaseErrorInfo, getTypedSupabaseClient, isSupabaseAuthFailure, isSupabaseNetworkFailure, } from '../shared/service-guards' import { asyncStorageGenerationKeyStore, type GenerationKeyStore, } from './generation-idempotency' import { generationKeyDisposition, type GenerationAttemptOutcome, } from './generation-key-policy' import type { GenerateMeetingDocumentOptions, GeneratedMeetingDocument, TemplateDraft, TemplateLibrary, } from './types' export type TemplateServiceErrorCode = | 'auth' | 'builtin' | 'conflict' | 'forbidden' | 'in-progress' | 'network' | 'not-found' | 'provider' | 'quota' | 'server' | 'validation' /** The HTTP answer the server gave, when an error came from a server response. */ export interface TemplateServiceResponseInfo { status: number errorCode: string | null } export class TemplateServiceError extends Error { constructor( public readonly code: TemplateServiceErrorCode, message: string, public readonly retryable = false, public readonly response: TemplateServiceResponseInfo | null = null, ) { super(message) this.name = 'TemplateServiceError' } } export interface TemplateSubscription { unsubscribe: () => Promise } const FIELD_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]*$/ const TEMPLATE_COLUMNS = 'id,user_id,template_kind,builtin_key,name,description,fields,output_format,template_type,system_prompt,is_builtin,revision,created_at,updated_at' const SELECTION_COLUMNS = 'user_id,template_kind,template_id,revision,updated_at' const requireUuid = createLabeledUuidAssert( (label) => new TemplateServiceError('auth', `A valid ${label} is required`), ) function normalizeSingleLine(value: string): string { return value.trim().replace(/\s+/g, ' ') } export function sanitizeTemplateSearch(value: string): string { return value .trim() .slice(0, 100) .replace(/[\\%_,().'";]/g, ' ') .replace(/\s+/g, ' ') .trim() } export function normalizeTemplateField( field: DictationTemplateField, index: number, ): DictationTemplateField { const id = normalizeSingleLine(field.id) const name = normalizeSingleLine(field.name) const label = normalizeSingleLine(field.label) const promptText = normalizeSingleLine(field.promptText) if ( !FIELD_ID_PATTERN.test(id) || id.length > 80 || name.length < 1 || name.length > 80 || label.length < 1 || label.length > 120 || promptText.length < 1 || promptText.length > 500 || typeof field.required !== 'boolean' || !Number.isSafeInteger(field.maxDurationSec) || field.maxDurationSec < 1 || field.maxDurationSec > 1800 ) { throw new TemplateServiceError('validation', `Template field ${index + 1} is invalid`) } return { id, name, label, promptText, required: field.required, maxDurationSec: field.maxDurationSec, } } export function normalizeTemplateDraft( kind: TemplateKind, draft: TemplateDraft, ): Required> & Omit { const name = normalizeSingleLine(draft.name) const description = draft.description === null || draft.description === undefined ? null : normalizeSingleLine(draft.description) || null if (name.length < 1 || name.length > 120 || (description?.length ?? 0) > 1000) { throw new TemplateServiceError('validation', 'Template name or description is invalid') } if (kind === 'dictation') { const fields = (draft.fields ?? []).map(normalizeTemplateField) const fieldIds = new Set(fields.map((field) => field.id.toLocaleLowerCase('en-US'))) const fieldNames = new Set(fields.map((field) => field.name.toLocaleLowerCase('en-US'))) const outputFormat = draft.outputFormat?.trim() ?? '' if ( fields.length < 1 || fields.length > 50 || fieldIds.size !== fields.length || fieldNames.size !== fields.length || outputFormat.length < 1 || outputFormat.length > 20000 ) { throw new TemplateServiceError('validation', 'Dictation template fields or output are invalid') } return { name, description, fields, outputFormat, systemPrompt: null } } const systemPrompt = draft.systemPrompt?.trim() ?? '' if (systemPrompt.length < 1 || systemPrompt.length > 12000) { throw new TemplateServiceError('validation', 'Meeting document prompt is invalid') } return { name, description, fields: [], outputFormat: null, systemPrompt } } function toServiceError(error: unknown): TemplateServiceError { if (error instanceof TemplateServiceError) return error const info = extractSupabaseErrorInfo(error, 'Template request failed') if (isSupabaseNetworkFailure(error, info) || info.lower.includes('abort')) { return new TemplateServiceError('network', info.message, true) } if (info.code === 'PT409' || info.lower.includes('revision_conflict')) { return new TemplateServiceError('conflict', info.message, true) } if (info.lower.includes('builtin_template_immutable')) { return new TemplateServiceError('builtin', info.message) } if (info.code === '42501') return new TemplateServiceError('forbidden', info.message) if (info.code === 'P0002') return new TemplateServiceError('not-found', info.message) if (isSupabaseAuthFailure(info)) { return new TemplateServiceError('auth', info.message) } if (info.code.startsWith('22')) return new TemplateServiceError('validation', info.message) return new TemplateServiceError('server', info.message, true) } function assertTemplate(value: UserTemplate | null, userId: string): UserTemplate { if ( value === null || !isUuid(value.id) || value.user_id !== userId || !['dictation', 'meeting_document'].includes(value.template_kind) || !Number.isSafeInteger(value.revision) || value.revision < 1 || !Array.isArray(value.fields) ) throw new TemplateServiceError('server', 'Server returned an invalid template') return value } async function rpc(name: string, params: Record = {}): Promise { const { data, error } = await supabase.rpc(name as never, params as never) if (error !== null) throw toServiceError(error) return data as T } export async function loadTemplateLibrary( userId: string, kind?: TemplateKind, searchValue = '', ): Promise { requireUuid(userId, 'authenticated user') const search = sanitizeTemplateSearch(searchValue) try { await rpc('bootstrap_user_templates_v1') let templateQuery = getTypedSupabaseClient() .from('user_templates') .select(TEMPLATE_COLUMNS) .eq('user_id', userId) .order('is_builtin', { ascending: false }) .order('created_at', { ascending: true }) .order('id', { ascending: true }) if (kind !== undefined) templateQuery = templateQuery.eq('template_kind', kind) if (search.length > 0) { templateQuery = templateQuery.or(`name.ilike.%${search}%,description.ilike.%${search}%`) } const [templateResult, selectionResult] = await Promise.all([ templateQuery, getTypedSupabaseClient() .from('user_template_selections') .select(SELECTION_COLUMNS) .eq('user_id', userId), ]) if (templateResult.error !== null) throw templateResult.error if (selectionResult.error !== null) throw selectionResult.error const templates = (templateResult.data ?? []) .map((row) => assertTemplate(row as UserTemplate, userId)) const selections: TemplateLibrary['selections'] = {} for (const selection of selectionResult.data ?? []) { if (selection.user_id !== userId || !isUuid(selection.template_id)) { throw new TemplateServiceError('server', 'Server returned an invalid template selection') } selections[selection.template_kind] = selection } return { templates, selections } } catch (error) { throw toServiceError(error) } } export async function createTemplate( userId: string, kind: TemplateKind, draft: TemplateDraft, ): Promise { requireUuid(userId, 'authenticated user') const normalized = normalizeTemplateDraft(kind, draft) try { const created = await rpc('create_user_template_v1', { p_template_kind: kind, p_name: normalized.name, p_description: normalized.description ?? null, p_fields: normalized.fields ?? [], p_output_format: normalized.outputFormat ?? null, p_system_prompt: normalized.systemPrompt ?? null, }) return assertTemplate(created, userId) } catch (error) { throw toServiceError(error) } } export async function updateTemplate( userId: string, current: UserTemplate, draft: TemplateDraft, ): Promise { requireUuid(userId, 'authenticated user') if (current.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch') if (current.is_builtin) throw new TemplateServiceError('builtin', 'Builtin templates are immutable') const normalized = normalizeTemplateDraft(current.template_kind, draft) try { const updated = await rpc('update_user_template_v1', { p_template_id: current.id, p_expected_revision: current.revision, p_name: normalized.name, p_description: normalized.description ?? null, p_fields: normalized.fields ?? [], p_output_format: normalized.outputFormat ?? null, p_system_prompt: normalized.systemPrompt ?? null, }) return assertTemplate(updated, userId) } catch (error) { throw toServiceError(error) } } export async function deleteTemplate( userId: string, current: UserTemplate, ): Promise { requireUuid(userId, 'authenticated user') if (current.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch') if (current.is_builtin) throw new TemplateServiceError('builtin', 'Builtin templates are immutable') try { const deleted = await rpc('delete_user_template_v1', { p_template_id: current.id, p_expected_revision: current.revision, }) if (deleted !== true) throw new TemplateServiceError('server', 'Template was not deleted') } catch (error) { throw toServiceError(error) } } export async function selectTemplate( userId: string, template: UserTemplate, currentSelection: UserTemplateSelection | undefined, ): Promise { requireUuid(userId, 'authenticated user') if (template.user_id !== userId) throw new TemplateServiceError('auth', 'Template owner mismatch') if ( currentSelection !== undefined && (currentSelection.user_id !== userId || currentSelection.template_kind !== template.template_kind) ) throw new TemplateServiceError('auth', 'Template selection owner mismatch') try { const selected = await rpc('select_user_template_v1', { p_template_id: template.id, p_expected_revision: currentSelection?.revision ?? null, }) if ( selected.user_id !== userId || selected.template_id !== template.id || selected.template_kind !== template.template_kind || !Number.isSafeInteger(selected.revision) ) throw new TemplateServiceError('server', 'Server returned an invalid selection') return selected } catch (error) { throw toServiceError(error) } } export function renderDictationTemplate( template: UserTemplate, fieldValues: Record, ): string { if (template.template_kind !== 'dictation' || template.output_format === null) { throw new TemplateServiceError('validation', 'A dictation template is required') } for (const field of template.fields) { const value = fieldValues[field.id]?.trim() ?? '' if (field.required && value.length === 0) { throw new TemplateServiceError('validation', `Required field is missing: ${field.label}`) } } let output = template.output_format for (const field of template.fields) { const escapedName = field.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') output = output.replace( new RegExp(`\\{\\{${escapedName}\\}\\}`, 'g'), fieldValues[field.id]?.trim() ?? '', ) } return output.replace(/\{\{[^}]+\}\}/g, '').trim() } function generationError(status: number, body: unknown): TemplateServiceError { const code = isRecord(body) && typeof body.error === 'string' ? body.error : '' const response: TemplateServiceResponseInfo = { status, errorCode: code || null } if (status === 401) return new TemplateServiceError('auth', code, false, response) if (status === 403) return new TemplateServiceError('forbidden', code, false, response) if (status === 404) return new TemplateServiceError('not-found', code, false, response) if (status === 409 && code === 'generation_failed') { // The previous attempt with this key failed for good; a new attempt can succeed. return new TemplateServiceError('server', code, true, response) } if (status === 409) return new TemplateServiceError('in-progress', code, true, response) if (status === 429) return new TemplateServiceError('quota', code, true, response) if ([502, 503, 504].includes(status)) { return new TemplateServiceError('provider', code, true, response) } if (status === 400) return new TemplateServiceError('validation', code, false, response) return new TemplateServiceError('server', code || 'Document generation failed', true, response) } export async function generateMeetingDocument( options: GenerateMeetingDocumentOptions, ): Promise { requireUuid(options.meetingId, 'meeting id') requireUuid(options.templateId, 'template id') requireUuid(options.idempotencyKey, 'idempotency key') if (options.accessToken.trim().length < 20) { throw new TemplateServiceError('auth', 'An authenticated session is required') } const title = normalizeSingleLine(options.title) if (title.length < 1 || title.length > 160) { throw new TemplateServiceError('validation', 'Document title is invalid') } try { const response = await fetch(`${SUPABASE_URL}/functions/v1/generate-meeting-document`, { method: 'POST', headers: { Authorization: `Bearer ${options.accessToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ meetingId: options.meetingId, templateId: options.templateId, idempotencyKey: options.idempotencyKey, title, ...(options.model === undefined ? {} : { model: options.model }), }), signal: options.signal, }) const body: unknown = await response.json().catch(() => null) if (!response.ok) throw generationError(response.status, body) if (!isRecord(body) || !isRecord(body.document) || typeof body.idempotent !== 'boolean') { throw new TemplateServiceError('server', 'Server returned an invalid generated document') } const document = body.document as MeetingDocument if (document.meeting_id !== options.meetingId || document.template_id !== options.templateId) { throw new TemplateServiceError('server', 'Generated document linkage is invalid') } return { document, idempotent: body.idempotent } } catch (error) { throw toServiceError(error) } } export interface GenerateMeetingDocumentOnceOptions extends Omit { userId: string } export interface GenerateMeetingDocumentOnceDeps { keyStore: GenerationKeyStore generate: (options: GenerateMeetingDocumentOptions) => Promise } const DEFAULT_GENERATE_ONCE_DEPS: GenerateMeetingDocumentOnceDeps = { keyStore: asyncStorageGenerationKeyStore, generate: generateMeetingDocument, } /** Maps a failed attempt to what the client actually learned from the server. */ export function generationAttemptOutcome(error: unknown): GenerationAttemptOutcome { if (error instanceof TemplateServiceError && error.response !== null) { return { kind: 'server-response', status: error.response.status, errorCode: error.response.errorCode, } } return { kind: 'no-response' } } /** * Generates one meeting document and owns its idempotency key's lifecycle: * the key for (user, meeting, template) is reused across ambiguous retries and * discarded once the server has given a final answer for it, success or not. */ export async function generateMeetingDocumentOnce( options: GenerateMeetingDocumentOnceOptions, deps: GenerateMeetingDocumentOnceDeps = DEFAULT_GENERATE_ONCE_DEPS, ): Promise { const { userId, ...request } = options let idempotencyKey: string try { idempotencyKey = await deps.keyStore.getOrCreate(userId, request.meetingId, request.templateId) } catch (error) { throw toServiceError(error) } let outcome: GenerationAttemptOutcome let generated: GeneratedMeetingDocument | null = null let failure: unknown = null try { generated = await deps.generate({ ...request, idempotencyKey }) outcome = { kind: 'succeeded' } } catch (error) { failure = error outcome = generationAttemptOutcome(error) } if (generationKeyDisposition(outcome) === 'discard') { // A failed cleanup only costs one extra replay of the final answer. await deps.keyStore .clear(userId, request.meetingId, request.templateId) .catch(() => undefined) } if (generated === null) throw toServiceError(failure) return generated } export function subscribeToTemplates( userId: string, onRemoteChange: () => void, onStatus: (status: string) => void, ): TemplateSubscription { requireUuid(userId, 'authenticated user') let channel: RealtimeChannel | null = supabase .channel(`mobile-templates-${userId}`) .on( 'postgres_changes', { event: '*', schema: 'public', table: 'user_templates', filter: `user_id=eq.${userId}` }, onRemoteChange, ) .on( 'postgres_changes', { event: '*', schema: 'public', table: 'user_template_selections', filter: `user_id=eq.${userId}` }, onRemoteChange, ) .subscribe(onStatus) return { unsubscribe: async (): Promise => { if (channel === null) return const active = channel channel = null await supabase.removeChannel(active) }, } }