import { createBlockingErrorOverlay } from './feedback-dialog'; import { buildError, isNormalizedError, isOurError, isOurRejection, normalizeApiFetchFailure, normalizeException, normalizeWpErrorResponse, record, } from './error-core'; import type { ErrorOptions, NormalizedError, UnknownRecord } from './error-core'; interface ErrorActions { onRetry?: () => unknown | Promise; onExit?: () => void; retryLabel?: string; exitLabel?: string; } interface ErrorContext { i18n?: { __?: (value: string, domain?: string) => string }; restUrl?: unknown; restNonce?: unknown; state?: { currentStepKey?: unknown }; handleAuthExpired?: (error: NormalizedError) => void; handleErrorExit?: () => void; errorExitLabel?: unknown; } interface NormalizeContext extends ErrorOptions { endpoint?: unknown; method?: unknown; status?: unknown; } interface ErrorSystem { report: (error: NormalizedError, actions?: ErrorActions, endpoint?: unknown) => void; clear: () => void; isVisible: () => boolean; normalizeAndReport: (raw: unknown, context?: NormalizeContext, actions?: ErrorActions) => void; normalizeAndRecord: (raw: unknown, context?: NormalizeContext) => void; destroy: () => void; } interface ErrorNamespace { buildError: typeof buildError; createErrorSystem: (context?: ErrorContext) => ErrorSystem; } interface FotogenicWindow extends Window { FotogenicAI?: { Shared?: { core?: { error?: Partial }; }; }; } const RATE_LIMIT_MS = 5000; const AUTH_ERROR_CODES = new Set([ 'FOTOGENIC_AI_AUTH_SESSION_EXPIRED', 'FOTOGENIC_AI_MISSING_AUTH_SESSION', ]); let lastGlobalOverlayTime = 0; const text = (value: unknown): string => String(value ?? '').trim(); const isHandledAuthError = (error: NormalizedError): boolean => AUTH_ERROR_CODES.has(error.code.toUpperCase()); const createErrorSystem = (context: ErrorContext = {}): ErrorSystem => { const root = document.getElementById('fotogenic-ai-error-overlay-root'); if (!root) throw new Error('Fotogenic AI: blocking-error mount is unavailable.'); const overlay = createBlockingErrorOverlay(root, context.i18n); const loggedIds = new Set(); const restUrl = text(context.restUrl).replace(/\/$/, ''); const restNonce = text(context.restNonce); let destroyed = false; const logToServer = (error: NormalizedError): void => { if (!error.debugId || !restUrl || !restNonce) return; if (loggedIds.has(error.debugId)) return; loggedIds.add(error.debugId); if (loggedIds.size > 200) loggedIds.clear(); void fetch(`${restUrl}/logs/client-error`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': restNonce, }, body: JSON.stringify({ error: { supportId: error.debugId, errorCode: error.code || 'UNKNOWN_ERROR', httpStatus: Number.isInteger(error.httpStatus) ? error.httpStatus : 0, }, context: { step: text(context.state?.currentStepKey) }, }), }).then((response) => { if (!response.ok) loggedIds.delete(error.debugId); }).catch(() => { loggedIds.delete(error.debugId); }); }; const report = (error: NormalizedError, actions: ErrorActions = {}, endpoint: unknown = ''): void => { if (!error.debugId || destroyed) return; if (isHandledAuthError(error) && context.handleAuthExpired) { context.handleAuthExpired(error); return; } const endpointText = text(endpoint); const presented = endpointText && !error.endpoint ? { ...error, endpoint: endpointText } : error; const presentationActions: ErrorActions = { ...actions }; if (!presentationActions.onExit && context.handleErrorExit) presentationActions.onExit = context.handleErrorExit; if (!presentationActions.exitLabel && typeof context.errorExitLabel === 'string') { presentationActions.exitLabel = context.errorExitLabel; } overlay.show(presented, presentationActions); logToServer(presented); }; const normalize = ( raw: unknown, normalizeContext: NormalizeContext = {}, ): NormalizedError => { const options: ErrorOptions = { source: normalizeContext.source ?? 'network', requestId: normalizeContext.requestId, runId: normalizeContext.runId, httpStatus: normalizeContext.status, }; const rawRecord: UnknownRecord = record(raw); let normalized: NormalizedError; if (isNormalizedError(raw)) { normalized = raw; } else if (rawRecord.ok === false) { const data = record(rawRecord.data); normalized = normalizeApiFetchFailure({ ...options, message: rawRecord.message ?? data.message, code: data.code ?? rawRecord.code ?? rawRecord.errorCode, status: rawRecord.status ?? data.status, endpoint: normalizeContext.endpoint, method: normalizeContext.method, }); } else if (rawRecord.code || rawRecord.message) { normalized = normalizeWpErrorResponse(rawRecord, options); } else if (raw instanceof Error || typeof rawRecord.message === 'string') { normalized = normalizeException(raw, options); } else { normalized = buildError( 'UNKNOWN_ERROR', context.i18n?.__?.('Something went wrong.', 'fotogenic-ai') ?? 'Something went wrong.', options, ); } const endpoint = text(normalizeContext.endpoint); return endpoint && !normalized.endpoint ? { ...normalized, endpoint } : normalized; }; const normalizeAndReport = (raw: unknown, normalizeContext: NormalizeContext = {}, actions: ErrorActions = {}): void => { report(normalize(raw, normalizeContext), actions); }; const normalizeAndRecord = (raw: unknown, normalizeContext: NormalizeContext = {}): void => { if (!destroyed) logToServer(normalize(raw, normalizeContext)); }; const handleUnhandledRejection = (event: PromiseRejectionEvent): void => { if (!isOurRejection(event) || Date.now() - lastGlobalOverlayTime < RATE_LIMIT_MS) return; lastGlobalOverlayTime = Date.now(); report(normalizeException(event.reason, { source: 'global' })); }; const handleError = (event: ErrorEvent): void => { if (!isOurError(event) || Date.now() - lastGlobalOverlayTime < RATE_LIMIT_MS) return; lastGlobalOverlayTime = Date.now(); report(normalizeException(event.error ?? new Error(event.message || 'Script error'), { source: 'global' })); }; window.addEventListener('unhandledrejection', handleUnhandledRejection); window.addEventListener('error', handleError); return Object.freeze({ report, clear: (): void => overlay.hide(), isVisible: (): boolean => overlay.isVisible(), normalizeAndReport, normalizeAndRecord, destroy(): void { if (destroyed) return; destroyed = true; window.removeEventListener('unhandledrejection', handleUnhandledRejection); window.removeEventListener('error', handleError); loggedIds.clear(); overlay.destroy(); }, }); }; const globalWindow = window as FotogenicWindow; globalWindow.FotogenicAI = globalWindow.FotogenicAI ?? {}; globalWindow.FotogenicAI.Shared = globalWindow.FotogenicAI.Shared ?? {}; globalWindow.FotogenicAI.Shared.core = globalWindow.FotogenicAI.Shared.core ?? {}; globalWindow.FotogenicAI.Shared.core.error = Object.freeze({ buildError, createErrorSystem, }); export type { ErrorActions, ErrorContext, ErrorSystem, NormalizeContext }; export { createErrorSystem };