import { createSecureUuid } from '../identity/secure-uuid'; type ErrorSource = 'start' | 'active' | 'poll' | 'save' | 'resume' | 'network' | 'global' | 'picker' | 'settings'; interface NormalizedError { debugId: string; code: string; message: string; source: ErrorSource; requestId?: string; runId?: string; httpStatus?: number; details?: string[]; savedCount?: number; attachments?: unknown[]; timestamp: string; endpoint?: string; } interface ErrorOptions { source?: unknown; requestId?: unknown; runId?: unknown; httpStatus?: unknown; details?: unknown; savedCount?: unknown; attachments?: unknown; debugId?: unknown; } interface ApiFailure extends ErrorOptions { endpoint?: unknown; method?: unknown; status?: unknown; message?: unknown; code?: unknown; } type SafeErrorKind = 'network' | 'api' | 'unexpected' | 'unknown'; interface SafeErrorReport { category: string; code: string; reference: string; summary: string; text: string; } type UnknownRecord = Record; const SOURCES = new Set([ 'start', 'active', 'poll', 'save', 'resume', 'network', 'global', 'picker', 'settings', ]); const TRUNCATE_LENGTH = 200; const SCRIPT_MARKERS = ['fotogenic-ai', 'fotogenicai']; const IGNORE_PATTERNS = [ /ResizeObserver/i, /Script error\.?$/i, /Loading chunk \d+ failed/i, /ChunkLoadError/i, /Loading CSS chunk/i, /^Uncaught \(in promise\)\s*undefined$/i, /network error/i, /Failed to fetch dynamically imported module/i, /Importing a module script failed/i, /Stale element reference/i, /Take a new snapshot\./i, /CursorBrowser/i, /GUEST_VIEW_MANAGER_CALL/i, ]; const SAFE_ERROR_VARIANTS = Object.freeze({ network: Object.freeze({ category: 'Network', code: 'STUDIO_NETWORK_UNAVAILABLE', summary: 'Fotogenic AI did not receive a reply.', }), api: Object.freeze({ category: 'API response', code: 'STUDIO_API_RESPONSE', summary: 'Fotogenic AI could not read the reply.', }), unexpected: Object.freeze({ category: 'Interface', code: 'STUDIO_UI_RECOVERY', summary: 'Part of Fotogenic AI did not load correctly.', }), unknown: Object.freeze({ category: 'Studio', code: 'STUDIO_REQUEST_FAILED', summary: 'Fotogenic AI could not finish this action.', }), } satisfies Readonly>>>); const record = (value: unknown): UnknownRecord => ( value && typeof value === 'object' && !Array.isArray(value) ? value as UnknownRecord : {} ); const optionalText = (value: unknown): string | undefined => { if (value === null || value === undefined || value === '') return undefined; return String(value); }; const optionalInteger = (value: unknown): number | undefined => { const number = Number(value); return Number.isInteger(number) ? number : undefined; }; const normalizeSource = (value: unknown): ErrorSource => { const source = String(value ?? '') as ErrorSource; return SOURCES.has(source) ? source : 'global'; }; const buildError = (code: unknown, message: unknown, options: ErrorOptions = {}): NormalizedError => { const details = Array.isArray(options.details) ? options.details.map((detail) => String(detail)).slice(0, 8) : undefined; return { debugId: (optionalText(options.debugId) ?? createSecureUuid()) || 'UNAVAILABLE', code: optionalText(code) ?? 'UNKNOWN_ERROR', message: optionalText(message) ?? 'Something went wrong.', source: normalizeSource(options.source), requestId: optionalText(options.requestId), runId: optionalText(options.runId), httpStatus: optionalInteger(options.httpStatus), details, savedCount: optionalInteger(options.savedCount), attachments: Array.isArray(options.attachments) ? [...options.attachments] : undefined, timestamp: new Date().toISOString(), }; }; const truncate = (value: unknown): string => { if (typeof value !== 'string') return ''; const text = value.trim(); return text.length <= TRUNCATE_LENGTH ? text : `${text.slice(0, TRUNCATE_LENGTH)} [truncated]`; }; const normalizeWpErrorResponse = (value: unknown, options: ErrorOptions = {}): NormalizedError => { const payload = record(value); const data = record(payload.data); return buildError(payload.code ?? 'REST_ERROR', payload.message ?? 'Request failed.', { ...options, source: options.source ?? 'network', httpStatus: optionalInteger(data.status) ?? options.httpStatus, details: data.errorCode ? [String(data.errorCode)] : options.details, }); }; const normalizeApiFetchFailure = (params: ApiFailure): NormalizedError => { const status = optionalInteger(params.status); const code = params.code || (status === 403 ? 'FORBIDDEN' : status === 401 ? 'UNAUTHORIZED' : 'NETWORK_ERROR'); const endpoint = optionalText(params.endpoint); const method = optionalText(params.method); return buildError(code, params.message || 'Request failed. Please try again.', { ...params, source: params.source ?? 'network', httpStatus: status, details: endpoint ? [`${endpoint}${method ? ` ${method}` : ''}`] : params.details, }); }; const normalizeException = (value: unknown, options: ErrorOptions = {}): NormalizedError => { const error = record(value); const details: string[] = []; try { const stack = truncate(error.stack); if (stack) details.push(stack); } catch { // Hostile error objects may expose throwing accessors. The diagnostic allowlist stays empty. } return buildError(error.code ?? 'UNHANDLED_ERROR', truncate(error.message) || 'An unexpected error occurred.', { ...options, source: options.source ?? 'global', details: details.length > 0 ? details : options.details, }); }; const buildSafeErrorReport = (value: unknown): SafeErrorReport => { const error = record(value); const requested = String(error.kind ?? '').trim().toLowerCase(); const code = String(error.code ?? '').trim().toUpperCase(); const source = String(error.source ?? '').trim().toLowerCase(); const kind: SafeErrorKind = requested === 'network' || requested === 'api' || requested === 'unexpected' ? requested : ['REST_ERROR', 'NETWORK_ERROR', 'REQUEST_FAILED'].includes(code) ? 'network' : code === 'API_ERROR' ? 'api' : source === 'global' ? 'unexpected' : 'unknown'; const variant = SAFE_ERROR_VARIANTS[kind]; const reference = String(error.debugId ?? '').slice(0, 80).replace(/[^A-Za-z0-9._-]/g, '') || 'UNAVAILABLE'; return Object.freeze({ ...variant, reference, text: [ `Category: ${variant.category}`, `Code: ${variant.code}`, `Reference: ${reference}`, `Summary: ${variant.summary}`, ].join('\n'), }); }; const isOurScript = (value: unknown): boolean => { if (typeof value !== 'string' || !value) return false; const lower = value.toLowerCase(); return SCRIPT_MARKERS.some((marker) => lower.includes(marker)); }; const shouldIgnoreError = (message: unknown, filename: unknown = ''): boolean => { const combined = [message, filename].filter(Boolean).map(String).join(' '); return !combined || IGNORE_PATTERNS.some((pattern) => pattern.test(combined)); }; const isOurRejection = (event: PromiseRejectionEvent): boolean => { if (!event.reason) return false; const reason = record(event.reason); let message = ''; try { message = typeof reason.message === 'string' ? reason.message : String(event.reason); } catch { return false; } if (shouldIgnoreError(message)) return false; const target = record(event.target); const script = reason.filename ?? target.__fotogenic_script; if (isOurScript(script)) return true; try { return isOurScript(reason.stack); } catch { return false; } }; const isOurError = (event: ErrorEvent, scriptUrls: string[] = []): boolean => { if (shouldIgnoreError(event.message, event.filename)) return false; if (isOurScript(event.filename)) return true; return scriptUrls.some((url) => event.filename === url || event.filename.endsWith(url)); }; const isNormalizedError = (value: unknown): value is NormalizedError => { const error = record(value); return typeof error.debugId === 'string' && typeof error.code === 'string' && typeof error.message === 'string'; }; export type { ApiFailure, ErrorOptions, ErrorSource, NormalizedError, SafeErrorReport, UnknownRecord }; export { buildError, buildSafeErrorReport, isNormalizedError, isOurError, isOurRejection, normalizeApiFetchFailure, normalizeException, normalizeWpErrorResponse, record, shouldIgnoreError, truncate, };