import { FetchDoctorConfig, FetchDiagnosticIssue, NetworkRequestLog, DiagnosticSummary, generateRequestId, formatBytes, formatDuration, isUrlIgnored, } from '@fetch-doctor/shared'; declare const process: { env?: { NODE_ENV?: string } } | undefined; type DiagnosticListener = (logs: NetworkRequestLog[], summary: DiagnosticSummary) => void; const HTML_ESCAPES: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; function escapeHtml(value: unknown): string { return String(value).replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch]); } function mergeConfig(base: FetchDoctorConfig, override: FetchDoctorConfig): FetchDoctorConfig { const rules = base.rules || override.rules ? { ...base.rules, ...override.rules } : undefined; return { ...base, ...override, rules }; } // SEC-004: the overlay exposes request URLs in the DOM and must not appear in // production builds by accident. Explicit opt-in is required there. let productionOverlayOverride = false; function isProduction(): boolean { return ( typeof process !== 'undefined' && Boolean(process.env && process.env.NODE_ENV === 'production') ); } function overlayBlocked(): boolean { return isProduction() && !productionOverlayOverride; } class FetchDoctorEngine { private static instance: FetchDoctorEngine | null = null; private originalFetch: typeof window.fetch | null = null; private isInitialized = false; private config: FetchDoctorConfig = {}; private requestLogs: NetworkRequestLog[] = []; private activeRequests = new Map< string, { startTime: number; url: string; method: string; signal?: AbortSignal } >(); private activeScopes = new Map(); private requestScopes = new Map>(); private listeners: Set = new Set(); private overlayElement: HTMLElement | null = null; private shadowRoot: ShadowRoot | null = null; private constructor() {} public static getInstance(): FetchDoctorEngine { if (!FetchDoctorEngine.instance) { FetchDoctorEngine.instance = new FetchDoctorEngine(); } return FetchDoctorEngine.instance; } public init(config: FetchDoctorConfig = {}): void { if (typeof window === 'undefined') { console.warn('[fetch-doctor]: SSR environment detected. Interceptors disabled.'); return; } if (this.isInitialized) { this.updateConfig(config); return; } const isDev = typeof process !== 'undefined' && Boolean(process.env && process.env.NODE_ENV === 'development'); this.config = mergeConfig( { enableOverlay: isDev, overlayPosition: 'bottom-right', maxLogs: 100, rules: { zombieThresholdMs: 3000, slowThresholdMs: 2000, requireAbortSignal: true, }, }, config ); if (this.config.enableOverlay && overlayBlocked()) { console.warn( '[fetch-doctor]: Diagnostic overlay is disabled in production. Call allowProductionOverlay() only for controlled debugging sessions.' ); this.config.enableOverlay = false; } this.originalFetch = window.fetch; this.patchFetch(); this.isInitialized = true; if (this.config.enableOverlay) { this.mountOverlay(); } } public updateConfig(newConfig: FetchDoctorConfig): void { this.config = mergeConfig(this.config, newConfig); if (this.config.enableOverlay && overlayBlocked()) { this.config.enableOverlay = false; } if (this.config.enableOverlay && !this.overlayElement && typeof window !== 'undefined') { this.mountOverlay(); } else if (!this.config.enableOverlay && this.overlayElement) { this.unmountOverlay(); } } public registerScope(name = 'Component'): string { const id = `scope_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`; this.activeScopes.set(id, { id, name }); return id; } public unregisterScope(scopeId: string, cleanlyAbortedSignals?: Set): void { const scope = this.activeScopes.get(scopeId); if (!scope) return; this.activeRequests.forEach((reqInfo, reqId) => { const scopes = this.requestScopes.get(reqId); if (scopes && scopes.has(scopeId)) { const log = this.requestLogs.find((l) => l.id === reqId); // Per-request abort evaluation: a request is only "cleanly aborted" if // its OWN signal was aborted as part of the teardown. One aborted // request must not mask zombie detection for unrelated in-flight // requests registered under the same scope. const isCleanlyAborted = Boolean(reqInfo.signal?.aborted) || (cleanlyAbortedSignals ? Array.from(cleanlyAbortedSignals).some((s) => s === reqInfo.signal && s.aborted) : false); if (!isCleanlyAborted) { const issue: FetchDiagnosticIssue = { id: `${reqId}_zombie_unmount`, type: 'ZOMBIE_FETCH', severity: 'critical', message: `Zombie Fetch: ${reqInfo.method} ${reqInfo.url} continued in-flight after ${scope.name} unmounted.`, url: reqInfo.url, method: reqInfo.method, timestamp: Date.now(), recommendation: 'Pass an AbortSignal tied to component unmount via useTrackFetch() to prevent dangling promises.', }; if (log) { if (!log.issues.some((i) => i.type === 'ZOMBIE_FETCH')) { log.issues.push(issue); } } this.config.onIssueDetected?.(issue); } } }); this.activeScopes.delete(scopeId); this.notifyListeners(); this.renderOverlayContent(); } public restore(): void { if (typeof window === 'undefined' || !this.isInitialized) return; if (this.originalFetch) { window.fetch = this.originalFetch; this.originalFetch = null; } this.unmountOverlay(); this.isInitialized = false; this.requestLogs = []; this.activeRequests.clear(); this.activeScopes.clear(); this.requestScopes.clear(); this.listeners.clear(); } public getDiagnostics(): DiagnosticSummary { const issues: FetchDiagnosticIssue[] = []; let zombieFetches = 0; let missingAbortSignals = 0; let slowResponses = 0; let httpErrors = 0; for (const log of this.requestLogs) { for (const issue of log.issues) { issues.push(issue); if (issue.type === 'ZOMBIE_FETCH') zombieFetches++; if (issue.type === 'MISSING_ABORT_SIGNAL') missingAbortSignals++; if (issue.type === 'SLOW_RESPONSE') slowResponses++; if (issue.type === 'UNHANDLED_HTTP_ERROR') httpErrors++; } } const total = this.requestLogs.length; const penalty = zombieFetches * 25 + missingAbortSignals * 10 + slowResponses * 5 + httpErrors * 15; const score = Math.max(0, 100 - penalty); return { totalRequests: total, zombieFetches, missingAbortSignals, slowResponses, httpErrors, score, issues, }; } public getLogs(): NetworkRequestLog[] { return [...this.requestLogs]; } public clear(): void { this.requestLogs = []; this.activeRequests.clear(); this.notifyListeners(); this.renderOverlayContent(); } public subscribe(listener: DiagnosticListener): () => void { this.listeners.add(listener); listener(this.getLogs(), this.getDiagnostics()); return () => { this.listeners.delete(listener); }; } private patchFetch(): void { const self = this; const nativeFetch = this.originalFetch || window.fetch; window.fetch = async function ( input: RequestInfo | URL, init?: RequestInit ): Promise { const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; const method = (init?.method || (typeof input === 'object' && 'method' in input ? input.method : 'GET')).toUpperCase(); if (isUrlIgnored(url, self.config.ignoreUrls)) { return nativeFetch.apply(this, [input, init]); } const id = generateRequestId(); const startTime = performance.now(); const effectiveSignal: AbortSignal | undefined = init?.signal ?? (typeof input === 'object' && input !== null && 'signal' in input ? input.signal : undefined); const signalAttached = Boolean(effectiveSignal); const issues: FetchDiagnosticIssue[] = []; self.activeRequests.set(id, { startTime, url, method, signal: effectiveSignal }); self.requestScopes.set(id, new Set(self.activeScopes.keys())); if (!signalAttached && self.config.rules?.requireAbortSignal) { issues.push({ id: `${id}_no_signal`, type: 'MISSING_ABORT_SIGNAL', severity: 'warning', message: `Request to ${method} ${url} is missing an AbortSignal.`, url, method, timestamp: Date.now(), recommendation: 'Pass an AbortSignal via fetch options to allow cancellation upon unmount or timeout.', }); } let wasAborted = false; if (init?.signal) { if (init.signal.aborted) { wasAborted = true; } else { init.signal.addEventListener( 'abort', () => { wasAborted = true; }, { once: true } ); } } const logEntry: NetworkRequestLog = { id, url, method, startTime, aborted: wasAborted, signalAttached, issues, }; self.addLog(logEntry); try { const response = await nativeFetch.apply(this, [input, init]); const endTime = performance.now(); const duration = endTime - startTime; self.activeRequests.delete(id); self.requestScopes.delete(id); logEntry.endTime = endTime; logEntry.duration = duration; logEntry.status = response.status; logEntry.statusText = response.statusText; logEntry.aborted = wasAborted; const contentLength = response.headers.get('content-length'); if (contentLength) { logEntry.bytesReceived = parseInt(contentLength, 10); } if (wasAborted) { const issue: FetchDiagnosticIssue = { id: `${id}_zombie`, type: 'ZOMBIE_FETCH', severity: 'critical', message: `Zombie Fetch detected: Request to ${url} resolved after AbortSignal triggered.`, url, method, timestamp: Date.now(), duration, recommendation: 'Ensure component state updates are guarded or stream responses cancel immediately when aborted.', }; logEntry.issues.push(issue); self.config.onIssueDetected?.(issue); } if (self.config.rules?.slowThresholdMs && duration > self.config.rules.slowThresholdMs) { const issue: FetchDiagnosticIssue = { id: `${id}_slow`, type: 'SLOW_RESPONSE', severity: 'warning', message: `Slow Network Response (${formatDuration(duration)}) from ${url}.`, url, method, timestamp: Date.now(), duration, recommendation: 'Consider caching, payload optimization, or background fetching.', }; logEntry.issues.push(issue); self.config.onIssueDetected?.(issue); } if (response.status >= 400) { const issue: FetchDiagnosticIssue = { id: `${id}_http_err`, type: 'UNHANDLED_HTTP_ERROR', severity: 'error', message: `HTTP ${response.status} ${response.statusText} response for ${url}.`, url, method, timestamp: Date.now(), recommendation: 'Check response status code and add fallback error boundary handling.', }; logEntry.issues.push(issue); self.config.onIssueDetected?.(issue); } self.notifyListeners(); self.renderOverlayContent(); return response; } catch (error) { const endTime = performance.now(); const duration = endTime - startTime; self.activeRequests.delete(id); self.requestScopes.delete(id); logEntry.endTime = endTime; logEntry.duration = duration; logEntry.aborted = wasAborted || (error instanceof Error && error.name === 'AbortError'); if (!logEntry.aborted) { const issue: FetchDiagnosticIssue = { id: `${id}_net_err`, type: 'CORS_OR_NETWORK_ERROR', severity: 'error', message: error instanceof Error ? error.message : 'Network request failed.', url, method, timestamp: Date.now(), duration, recommendation: 'Verify CORS headers, server connectivity, and internet access.', }; logEntry.issues.push(issue); self.config.onIssueDetected?.(issue); } self.notifyListeners(); self.renderOverlayContent(); throw error; } }; } private addLog(log: NetworkRequestLog): void { const maxLogs = this.config.maxLogs || 100; this.requestLogs.unshift(log); if (this.requestLogs.length > maxLogs) { this.requestLogs.pop(); } this.notifyListeners(); this.renderOverlayContent(); } private notifyListeners(): void { const summary = this.getDiagnostics(); const logs = this.getLogs(); this.listeners.forEach((listener) => listener(logs, summary)); } private mountOverlay(): void { if (typeof document === 'undefined' || this.overlayElement) return; this.overlayElement = document.createElement('div'); this.overlayElement.id = 'fetch-doctor-root'; this.shadowRoot = this.overlayElement.attachShadow({ mode: 'open' }); document.body.appendChild(this.overlayElement); this.renderOverlayContent(); } private unmountOverlay(): void { if (this.overlayElement && this.overlayElement.parentNode) { this.overlayElement.parentNode.removeChild(this.overlayElement); this.overlayElement = null; this.shadowRoot = null; } } private isCollapsed = false; private renderOverlayContent(): void { if (!this.shadowRoot) return; const summary = this.getDiagnostics(); const logs = this.getLogs().slice(0, 10); const pos = this.config.overlayPosition || 'bottom-right'; let posStyle = 'bottom: 16px; right: 16px;'; if (pos === 'bottom-left') posStyle = 'bottom: 16px; left: 16px;'; if (pos === 'top-right') posStyle = 'top: 16px; right: 16px;'; if (pos === 'top-left') posStyle = 'top: 16px; left: 16px;'; const html = `
Fetch Doctor
Score: ${summary.score}
Total Requests: ${summary.totalRequests} Zombies: ${summary.zombieFetches}
Missing AbortSignal: ${summary.missingAbortSignals} Errors: ${summary.httpErrors}
Recent Logs:
${ logs.length === 0 ? '
No requests monitored yet.
' : logs .map( (l) => `
${escapeHtml(l.method)} ${escapeHtml(l.url.substring(0, 35))}...
${l.duration ? formatDuration(l.duration) : 'pending'} ${l.bytesReceived ? formatBytes(l.bytesReceived) : ''} ${l.status || 'ERR'}
${l.issues.map((i: FetchDiagnosticIssue) => `
[!] ${escapeHtml(i.message)}
`).join('')}
` ) .join('') }
`; this.shadowRoot.innerHTML = html; const btnToggle = this.shadowRoot.getElementById('btn-toggle'); if (btnToggle) { btnToggle.onclick = (e) => { e.stopPropagation(); this.isCollapsed = !this.isCollapsed; this.renderOverlayContent(); }; } const btnClear = this.shadowRoot.getElementById('btn-clear'); if (btnClear) { btnClear.onclick = (e) => { e.stopPropagation(); this.clear(); }; } } } export function initFetchDoctor(config?: FetchDoctorConfig): void { FetchDoctorEngine.getInstance().init(config); } export function restoreFetchDoctor(): void { FetchDoctorEngine.getInstance().restore(); } export function getDiagnostics(): DiagnosticSummary { return FetchDoctorEngine.getInstance().getDiagnostics(); } export function getNetworkLogs(): NetworkRequestLog[] { return FetchDoctorEngine.getInstance().getLogs(); } export function clearDiagnostics(): void { FetchDoctorEngine.getInstance().clear(); } export function subscribeDiagnostics( listener: (logs: NetworkRequestLog[], summary: DiagnosticSummary) => void ): () => void { return FetchDoctorEngine.getInstance().subscribe(listener); } /** * Explicitly allow the diagnostic overlay in production builds. This exposes * request URLs in the DOM; call it only for controlled debugging sessions. */ export function allowProductionOverlay(): void { productionOverlayOverride = true; } export function registerFetchScope(name?: string): string { return FetchDoctorEngine.getInstance().registerScope(name); } export function unregisterFetchScope(scopeId: string, cleanlyAbortedSignals?: Set): void { FetchDoctorEngine.getInstance().unregisterScope(scopeId, cleanlyAbortedSignals); } export * from '@fetch-doctor/shared'; export { FetchDoctorEngine };