import { SSE_EVENT_TYPES } from "./realtime/refreshPlan"; export type HealthStatus = | "healthy" | "degraded" | "down" | "unknown" | "unmonitored" | "recovering" | "maintenance"; export type ServiceKind = "http" | "tcp" | "dns" | "tls"; export type Criticality = "low" | "medium" | "high" | "critical"; export type DiscoveryCategory = | "application" | "database" | "cache" | "proxy" | "monitoring" | "development" | "storage" | "infrastructure" | "background_worker" | "system" | "unknown"; export type ComponentRole = | "frontend" | "api" | "database" | "cache" | "proxy" | "worker" | "storage" | "monitoring" | "agent" | "scheduler" | "auxiliary" | "unknown"; export type DiscoveryVisibility = "visible" | "hidden" | "ignored"; export type DiscoveryLifecycle = "active" | "missing" | "stale" | "ignored" | "retired"; export type DiscoveryConfidence = "confirmed" | "high" | "medium" | "low"; export type RelationType = "depends_on" | "routes_to" | "uses_storage" | "communicates_with"; export type MonitoringState = | "active_probe" | "docker_health" | "appops_observation" | "observed" | "unmonitored" | "disabled"; export type ProbeEndpointSource = | "manual" | "explicit_label" | "known_url" | "appops" | "reverse_proxy" | "published_port" | "docker_healthcheck" | "container_internal" | "discovered_environment"; export type ProbeReachability = "verified" | "reachable" | "unverified" | "internal_only" | "not_configured"; export type Service = { id: string; name: string; kind: ServiceKind; url: string | null; host: string | null; port: number | null; depends_on: string[]; description: string | null; tags: string[]; group: string | null; environment: string | null; owner: string | null; enabled: boolean; monitoring_enabled: boolean; monitoring_state: MonitoringState; probe_source: ProbeEndpointSource; probe_reachability: ProbeReachability; probe_confidence: DiscoveryConfidence; runtime_state: string | null; runtime_health: string | null; application: string | null; domain: string | null; component_role: ComponentRole; application_locked: boolean; domain_locked: boolean; component_role_locked: boolean; criticality: Criticality; category: DiscoveryCategory; visibility: DiscoveryVisibility; lifecycle: DiscoveryLifecycle; source_type: string | null; source_ref: string | null; first_seen_at: string | null; last_seen_at: string | null; last_discovery_status: string | null; container_image: string | null; compose_project: string | null; layout_x: number | null; layout_y: number | null; layout_pinned: boolean; interval_seconds: number | null; timeout_seconds: number | null; retries: number | null; failure_threshold: number; recovery_threshold: number; expected_status_min: number | null; expected_status_max: number | null; availability_target: number | null; maintenance_enabled: boolean; maintenance_reason: string | null; state: HealthStatus; failure_streak: number; recovery_streak: number; flapping: boolean; flap_count: number; last_state_change_at: string | null; created_at: string; updated_at: string; }; export type ProbeResult = { id: string; service_id: string; status: HealthStatus; latency_ms: number | null; detail: string; checked_at: string; trigger: string; metadata: Record; }; export type EvidenceProvider = "active_probe" | "docker" | "appops" | "runtime" | "manual"; export type EvidenceScope = "component" | "application"; export type EvidenceFreshness = "fresh" | "stale" | "expired"; export type HealthResolutionReason = | "selected_component_evidence" | "application_scoped_only" | "no_current_component_evidence" | "stale_evidence" | "expired_evidence" | "selected_application_evidence" | "component_failure" | "component_dependency_impact" | "component_coverage" | "no_application_evidence"; export type HealthEvidence = { id: string; subject_type: string; subject_id: string; service_id: string | null; provider: EvidenceProvider; provider_ref: string | null; status: HealthStatus; scope: EvidenceScope; confidence: number; observed_at: string; valid_until: string; received_at: string; summary: string; metadata: Record; active: boolean; superseded_by: string | null; freshness: EvidenceFreshness; }; export type HealthResolution = { status: HealthStatus; selected_evidence_id: string | null; selected_provider: EvidenceProvider | null; confidence: number | null; reason_code: HealthResolutionReason; explanation: string; conflict: boolean; evidence: HealthEvidence[]; }; export type ProviderStatus = { provider: EvidenceProvider; status: "healthy" | "degraded" | "unavailable" | "unknown"; observed_at: string; valid_until: string; detail: string; metadata: Record; }; export type ServiceSnapshot = { service: Service; latest_probe: ProbeResult | null; availability_24h: AvailabilitySummary | null; dependency_status: HealthStatus; effective_status: HealthStatus; direct_status: HealthStatus; flapping: boolean; flap_count: number; next_probe_at: string | null; dependents: string[]; sources: ServiceSource[]; evidence: RelationEvidence[]; health_evidence: HealthEvidence[]; health_resolution: HealthResolution; maintenance_until?: string | null; }; export type ServiceSource = { id: string; source_type: string; source_id: string; source_name: string | null; first_seen_at: string; last_seen_at: string; lifecycle: DiscoveryLifecycle; managed: boolean; metadata: Record; }; export type RelationEvidence = { id: string; source_service_id: string; target_service_id: string | null; target_ref: string | null; relation_type: RelationType; evidence_type: string; confidence: DiscoveryConfidence; explanation: string; source_ref: string | null; locked: boolean; active: boolean; first_seen_at: string; last_seen_at: string; }; export type LogicalRelation = { id: string; source_service_id: string; target_service_id: string | null; target_ref: string | null; relation_type: RelationType; confidence: DiscoveryConfidence; active: boolean; locked: boolean; first_seen_at: string; last_seen_at: string; evidence: RelationEvidence[]; }; export type TopologySnapshot = { id: string; run_id: string | null; created_at: string; revision: string; service_count: number; relationship_count: number; summary: Record; }; export type TopologyChange = { change_type: "added" | "removed" | "changed"; entity_type: "service" | "relationship"; entity_id: string; name: string; before: Record | null; after: Record | null; }; export type TopologyDiff = { before_snapshot_id: string | null; after_snapshot_id: string; added: TopologyChange[]; removed: TopologyChange[]; changed: TopologyChange[]; summary: Record; }; export type SemanticComponent = { service_id: string; name: string; kind: ServiceKind; application_id: string; domain_id: string; role: ComponentRole; direct_status: HealthStatus; effective_status: HealthStatus; unknown_reason: HealthResolutionReason | null; runtime_state: string | null; runtime_health: string | null; monitoring_state: MonitoringState; latest_latency_ms: number | null; dependency_ids: string[]; dependent_ids: string[]; root_cause: boolean; affected: boolean; }; export type SemanticApplication = { id: string; name: string; domain_id: string; component_ids: string[]; component_count: number; roles: ComponentRole[]; status: HealthStatus; status_explanation: string; health_resolution: { status: HealthStatus; confidence: number | null; explanation: string; reason_code: HealthResolutionReason; selected_evidence_id: string | null; selected_provider: EvidenceProvider | null; evidence_freshness: EvidenceFreshness | null; conflict: boolean; resolved_components: number; unresolved_components: number; component_coverage_percent: number; }; dependency_application_ids: string[]; dependent_application_ids: string[]; monitored_components: number; unmonitored_components: number; resolved_components: number; unresolved_components: number; component_coverage_percent: number; root_cause: boolean; affected: boolean; }; export type SemanticDomain = { id: string; name: string; application_ids: string[]; application_count: number; status: HealthStatus; resolved_application_count: number; unresolved_application_count: number; application_coverage_percent: number; incident_count: number; root_cause: boolean; affected: boolean; }; export type SemanticTopology = { generated_at: string; domains: SemanticDomain[]; applications: SemanticApplication[]; components: SemanticComponent[]; relations: LogicalRelation[]; monitoring_coverage: Record; }; export type AvailabilitySummary = { hours: number; total_checks: number; healthy_checks: number; degraded_checks: number; down_checks: number; uptime_percent: number | null; average_latency_ms: number | null; last_checked_at: string | null; target_percent: number | null; meets_target: boolean | null; }; export type ServiceInput = { name: string; kind: ServiceKind; url?: string; host?: string; port?: number; depends_on?: string[]; description?: string; tags?: string[]; group?: string; environment?: string; owner?: string; enabled?: boolean; monitoring_enabled?: boolean; monitoring_state?: MonitoringState; probe_source?: ProbeEndpointSource; probe_reachability?: ProbeReachability; probe_confidence?: DiscoveryConfidence; runtime_state?: string; runtime_health?: string; application?: string; domain?: string; component_role?: ComponentRole; application_locked?: boolean; domain_locked?: boolean; component_role_locked?: boolean; criticality?: Criticality; category?: DiscoveryCategory; visibility?: DiscoveryVisibility; lifecycle?: DiscoveryLifecycle; layout_x?: number; layout_y?: number; layout_pinned?: boolean; interval_seconds?: number; timeout_seconds?: number; retries?: number; failure_threshold?: number; recovery_threshold?: number; expected_status_min?: number; expected_status_max?: number; availability_target?: number; source_type?: string; source_ref?: string; first_seen_at?: string; last_seen_at?: string; last_discovery_status?: string; container_image?: string; compose_project?: string; maintenance_enabled?: boolean; maintenance_reason?: string; }; export type IncidentCandidate = { service_id: string; service_name: string; status: HealthStatus; reason: string; affected_service_ids: string[]; affected_service_names: string[]; }; export type IncidentStatus = "open" | "acknowledged" | "resolved"; export type IncidentRecord = { id: string; status: IncidentStatus; root_service_id: string; root_service_name: string; started_at: string; detected_at: string; acknowledged_at: string | null; resolved_at: string | null; title: string; root_cause_reason: string; affected_service_ids: string[]; affected_service_names: string[]; severity: Criticality; latest_update_at: string; }; export type IncidentTimelineEvent = { id: string; incident_id: string; event_type: string; message: string; created_at: string; service_id: string | null; }; export type IncidentDetail = { incident: IncidentRecord; timeline: IncidentTimelineEvent[]; }; export type IncidentOverview = { generated_at: string; active: boolean; candidates: IncidentCandidate[]; degraded_service_ids: string[]; down_service_ids: string[]; incidents: IncidentRecord[]; }; export type EventRecord = { id: string; event_type: string; service_id: string | null; incident_id: string | null; from_status: HealthStatus | null; to_status: HealthStatus | null; message: string; metadata: Record; created_at: string; }; export type OverviewSummary = { generated_at: string; total_services: number; health_counts: Record; active_incidents: number; likely_root_causes: string[]; flapping_services: string[]; recent_events: EventRecord[]; monitoring_coverage: Record; }; export type DemoState = { active: boolean; enabled: boolean; synthetic: boolean; scenario_name: string | null; service_count: number; root_cause_service_id: string | null; root_cause_service_name: string | null; affected_service_ids: string[]; affected_service_names: string[]; affected_count: number; }; export type DemoMutationResult = DemoState & { created: number; updated: number; total: number; restored: boolean; }; export type DockerPort = { container_port: string; host_ip: string | null; host_port: number | null; }; export type DockerSuggestion = { name: string; kind: ServiceKind; host: string | null; port: number | null; url: string | null; group: string | null; evidence: string[]; confidence: string; depends_on_names: string[]; source_type: string | null; source_ref: string | null; stable_source_ref: string | null; category: DiscoveryCategory; visibility: DiscoveryVisibility; relation_type: RelationType; }; export type DockerCandidate = { container_id: string; name: string; image: string; state: string; health: string | null; networks: string[]; ports: DockerPort[]; labels: Record; import_state: string; suggestions: DockerSuggestion[]; dependency_suggestions: string[]; stable_source_ref: string | null; compose_project: string | null; compose_service: string | null; category: DiscoveryCategory; visibility: DiscoveryVisibility; lifecycle: DiscoveryLifecycle; healthcheck_present: boolean; environment_evidence: string[]; proxy_route_evidence: string[]; appops_app_id: string | null; appops_category: string | null; appops_criticality: string | null; appops_health: string | null; probe_candidates: ProbeEndpointCandidate[]; }; export type ProbeEndpointCandidate = { source: ProbeEndpointSource; kind: ServiceKind; url: string | null; host: string | null; port: number | null; reachability: ProbeReachability; confidence: DiscoveryConfidence; primary: boolean; evidence: string; preflight_detail: string | null; preflight_latency_ms: number | null; }; export type ProbeRepairChange = { service_id: string; service_name: string; previous_monitoring_state: MonitoringState; next_monitoring_state: MonitoringState; previous_endpoint: string | null; next_endpoint: string | null; next_probe_source: ProbeEndpointSource | null; next_probe_confidence: DiscoveryConfidence | null; reason: string; }; export type ProbeRepairReport = { run_id: string | null; dry_run: boolean; inspected: number; changed: number; disabled_unsafe: number; enabled_published: number; docker_health_observed: number; appops_observed: number; runtime_observed: number; unmonitored: number; resolved_incidents: number; changes: ProbeRepairChange[]; }; export type DockerDiscoveryResult = { docker_host: string; candidates: DockerCandidate[]; proxy_routes?: number; }; export type DiscoveryObservation = { id: string; run_id: string; source_id: string; source_type: string; source_name: string; lifecycle: DiscoveryLifecycle; change_type: string; observed_at: string; metadata: Record; }; export type TopologySuggestion = { id: string; run_id: string; suggestion_type: string; status: "open" | "accepted" | "rejected" | "superseded"; source_ref: string | null; source_service_id: string | null; target_ref: string | null; target_service_id: string | null; proposed_name: string | null; proposed_kind: ServiceKind | null; proposed_url: string | null; proposed_host: string | null; proposed_port: number | null; proposed_category: DiscoveryCategory; proposed_group: string | null; relation_type: RelationType | null; confidence: DiscoveryConfidence; evidence: string[]; created_at: string; updated_at: string; }; export type DiscoveryDiff = { new: number; changed: number; missing: number; unchanged: number; stale: number; new_suggestions: number; }; export type DiscoveryRun = { id: string; status: "idle" | "discovering" | "reconciling" | "completed" | "failed"; started_at: string; completed_at: string | null; source_counts: Record; diff: DiscoveryDiff; error: string | null; }; export type DiscoveryResult = DockerDiscoveryResult & { run: DiscoveryRun; suggestions: TopologySuggestion[]; observations: DiscoveryObservation[]; appops_available: boolean; appops_mappings: number; proxy_routes: number; }; export type DiscoveryStatus = { current: DiscoveryRun | null; last_completed: DiscoveryRun | null; active: boolean; }; export type ReconcileResult = { run: DiscoveryRun; created: number; updated: number; unchanged: number; missing: number; retired: number; accepted_relations: number; open_suggestions: number; service_ids: string[]; }; // The admin token is kept per browser tab (sessionStorage): it survives a // reload but not closing the tab, and never reaches topology config. const TOKEN_KEY = "servicemap.adminToken"; export const AUTH_REQUIRED_EVENT = "servicemap:auth-required"; function readStoredToken(): string | null { try { return window.sessionStorage.getItem(TOKEN_KEY); } catch { return null; } } let accessToken: string | null = typeof window === "undefined" ? null : readStoredToken(); export function setApiAccessToken(token: string | null): void { accessToken = token?.trim() || null; try { if (accessToken) window.sessionStorage.setItem(TOKEN_KEY, accessToken); else window.sessionStorage.removeItem(TOKEN_KEY); } catch { // Storage may be unavailable (private mode); the token stays in memory. } } export function hasApiAccessToken(): boolean { return accessToken !== null; } /** An API failure that keeps the HTTP status, e.g. 401 for a locked editor. */ export class ApiError extends Error { readonly status: number; constructor(message: string, status: number) { super(message); this.name = "ApiError"; this.status = status; } } function errorMessage(detail: unknown, status: number): string { if (typeof detail === "string" && detail) return detail; if (Array.isArray(detail)) { // FastAPI validation errors: [{loc: [...], msg: "..."}] const parts = detail .map((item) => { const entry = item as { loc?: unknown[]; msg?: string }; const field = Array.isArray(entry.loc) ? entry.loc.filter((part) => part !== "body").join(".") : ""; return entry.msg ? (field ? `${field}: ${entry.msg}` : entry.msg) : ""; }) .filter(Boolean); if (parts.length) return parts.join("; "); } return `Verzoek mislukt (${status})`; } function requestHeaders(init?: RequestInit, token: string | null = accessToken): Headers { const headers = new Headers(init?.headers); if (init?.body !== undefined && !headers.has("Content-Type")) { headers.set("Content-Type", "application/json"); } if (token && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${token}`); return headers; } async function request(url: string, init?: RequestInit, token: string | null = accessToken): Promise { // Spread init first: a caller's headers are merged above, never dropped. const response = await fetch(url, { ...init, headers: requestHeaders(init, token) }); if (!response.ok) { const payload = await response.json().catch(() => null); if (response.status === 401 && token === accessToken && typeof window !== "undefined") { // The tab's token is missing or no longer valid: forget it and let the // UI ask for it. Explicit candidate tokens (verifyWriteAccess) don't. if (accessToken) setApiAccessToken(null); window.dispatchEvent(new Event(AUTH_REQUIRED_EVENT)); } throw new ApiError(errorMessage(payload?.detail, response.status), response.status); } if (response.status === 204) return undefined as T; return response.json() as Promise; } export type AlertSettings = { enabled: boolean; ntfy_server: string; ntfy_topic: string; min_severity: Criticality; delay_seconds: number; notify_resolved: boolean; reminder_minutes: number; public_url: string; ntfy_token_set?: boolean; }; export type BackupInfo = { name: string; kind: "backup" | "pre-restore"; created_at: string; size_bytes: number; }; /** Download a backup with the tab's token (a plain link carries none). */ export async function downloadBackupFile(name: string): Promise { const response = await fetch(`/api/v1/backups/${encodeURIComponent(name)}`, { headers: requestHeaders(), }); if (!response.ok) { const payload = await response.json().catch(() => null); throw new ApiError(errorMessage(payload?.detail, response.status), response.status); } return response.blob(); } export type ServiceMapMeta = { version: string; auth_mode: string; write_auth?: "none" | "admin_token" | "oidc"; }; export const api = { alertSettings: () => request("/api/v1/settings/alerts"), /** ``ntfyToken``: undefined keeps the stored token, "" removes it. */ saveAlertSettings: (settings: AlertSettings, ntfyToken?: string) => request("/api/v1/settings/alerts", { method: "PUT", body: JSON.stringify({ ...settings, ntfy_token_set: undefined, ntfy_token: ntfyToken }), }), backups: () => request("/api/v1/backups"), createBackup: () => request("/api/v1/backups", { method: "POST" }), restoreBackup: (name: string) => request(`/api/v1/backups/${encodeURIComponent(name)}/restore`, { method: "POST" }), testAlert: () => request<{ ok: boolean; detail: string }>("/api/v1/settings/alerts/test", { method: "POST" }), meta: () => request("/api/v1/meta"), /** Resolves only when ``token`` may change ServiceMap. */ verifyWriteAccess: (token: string) => request<{ ok: boolean }>("/api/v1/auth/verify", { method: "POST" }, token.trim()), listServices: (includeHidden = false) => request( `/api/v1/services?include_hidden=${includeHidden}`, ), createService: (payload: ServiceInput) => request("/api/v1/services", { method: "POST", body: JSON.stringify(payload), }), updateService: (serviceId: string, payload: ServiceInput) => request(`/api/v1/services/${serviceId}`, { method: "PUT", body: JSON.stringify(payload), }), probeService: (serviceId: string) => request(`/api/v1/services/${serviceId}/probe`, { method: "POST", }), probeAll: () => request<{ requested: number; completed: number; results: ProbeResult[] }>( "/api/v1/probe-all", { method: "POST" }, ), deleteService: (serviceId: string) => request(`/api/v1/services/${serviceId}`, { method: "DELETE" }), history: (serviceId: string, limit = 24) => request( `/api/v1/services/${serviceId}/history?limit=${limit}`, ), availability: (serviceId: string, hours = 24) => request( `/api/v1/services/${serviceId}/availability?hours=${hours}`, ), serviceEvidence: (serviceId: string) => request(`/api/v1/services/${serviceId}/evidence`), providers: () => request("/api/v1/providers"), incidents: () => request("/api/v1/incidents"), incident: (incidentId: string) => request(`/api/v1/incidents/${incidentId}`), acknowledgeIncident: (incidentId: string) => request(`/api/v1/incidents/${incidentId}/acknowledge`, { method: "POST", }), events: (limit = 50, options: { eventType?: string; before?: string } = {}) => { const params = new URLSearchParams({ limit: String(limit) }); if (options.eventType) params.set("event_type", options.eventType); if (options.before) params.set("before", options.before); return request(`/api/v1/events?${params.toString()}`); }, resolveIncident: (incidentId: string, note?: string) => request(`/api/v1/incidents/${encodeURIComponent(incidentId)}/resolve`, { method: "POST", body: JSON.stringify({ note: note || null }), }), addIncidentNote: (incidentId: string, text: string) => request(`/api/v1/incidents/${encodeURIComponent(incidentId)}/notes`, { method: "POST", body: JSON.stringify({ text }), }), overview: () => request("/api/v1/overview"), maintenance: (serviceId: string, enabled: boolean, reason?: string, until?: string | null) => request(`/api/v1/services/${serviceId}/maintenance`, { method: "POST", body: JSON.stringify({ enabled, reason, until: until ?? null }), }), demoState: () => request("/api/v1/demo"), loadDemo: () => request("/api/v1/demo", { method: "POST" }), resetDemo: () => request("/api/v1/demo/reset", { method: "POST" }), exitDemo: () => request("/api/v1/demo/exit", { method: "POST" }), importConfig: ( content: string, format: "yaml" | "json", mode: "merge" | "replace", ) => request<{ created: number; updated: number; total: number }>( "/api/v1/config/import", { method: "POST", body: JSON.stringify({ content, format, mode }) }, ), exportConfig: async (format: "yaml" | "json") => { const response = await fetch(`/api/v1/config?format=${format}`, { headers: requestHeaders() }); if (!response.ok) throw new Error(`Exporteren mislukt (${response.status})`); return response.text(); }, discoverDocker: (dockerHost: string) => request("/api/v1/docker/discover", { method: "POST", body: JSON.stringify({ docker_host: dockerHost }), }), runDiscovery: ( dockerHost?: string, appopsUrl?: string, includeStopped = false, ) => request("/api/v1/discovery/run", { method: "POST", body: JSON.stringify({ docker_host: dockerHost || undefined, appops_url: appopsUrl || undefined, include_stopped: includeStopped, }), }), discoveryStatus: () => request("/api/v1/discovery/status"), discoveryItems: (runId?: string) => request( `/api/v1/discovery/items${runId ? `?run_id=${encodeURIComponent(runId)}` : ""}`, ), discoverySuggestions: (status = "open") => request( `/api/v1/discovery/suggestions?status=${status}`, ), acceptSuggestion: (suggestionId: string) => request( `/api/v1/discovery/suggestions/${suggestionId}/accept`, { method: "POST" }, ), rejectSuggestion: (suggestionId: string) => request( `/api/v1/discovery/suggestions/${suggestionId}/reject`, { method: "POST" }, ), reconcileDiscovery: (runId?: string, applyHighConfidence = false) => request("/api/v1/discovery/reconcile", { method: "POST", body: JSON.stringify({ run_id: runId, apply_high_confidence: applyHighConfidence, }), }), repairDiscoveredProbes: (dryRun = true, runId?: string) => request( `/api/v1/discovery/probes/repair?dry_run=${dryRun}${runId ? `&run_id=${encodeURIComponent(runId)}` : ""}`, { method: "POST" }, ), topologyEdges: () => request("/api/v1/topology/edges"), topologyRelations: () => request("/api/v1/topology/relations"), topologySnapshots: (limit = 30) => request(`/api/v1/topology/snapshots?limit=${limit}`), topologyDiff: (afterSnapshotId: string, beforeSnapshotId?: string) => request( `/api/v1/topology/diff?after_snapshot_id=${encodeURIComponent(afterSnapshotId)}${beforeSnapshotId ? `&before_snapshot_id=${encodeURIComponent(beforeSnapshotId)}` : ""}`, ), semanticTopology: () => request("/api/v1/topology/semantic"), createEdge: (payload: { source_service_id: string; target_service_id: string; relation_type?: RelationType; lock?: boolean; explanation?: string; }) => request("/api/v1/topology/edges", { method: "POST", body: JSON.stringify(payload), }), edgeAction: ( evidenceId: string, action: "confirm" | "reject" | "lock" | "remove", ) => request(`/api/v1/topology/edges/${evidenceId}/action`, { method: "POST", body: JSON.stringify({ action }), }), }; export function subscribeToEvents( onEvent: (event: EventRecord | Record) => void, onError?: () => void, onOpen?: () => void, ): () => void { if (accessToken) { const controller = new AbortController(); void (async () => { try { const response = await fetch("/api/v1/events/stream", { headers: { Authorization: `Bearer ${accessToken}`, Accept: "text/event-stream" }, signal: controller.signal, }); if (!response.ok || !response.body) throw new Error(`SSE failed (${response.status})`); onOpen?.(); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (!controller.signal.aborted) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const frames = buffer.split("\n\n"); buffer = frames.pop() ?? ""; for (const frame of frames) { const data = frame .split("\n") .filter((line) => line.startsWith("data:")) .map((line) => line.slice(5).trim()) .join("\n"); if (!data) continue; try { onEvent(JSON.parse(data) as EventRecord); } catch { // Ignore a malformed event and retain the durable polling fallback. } } } if (!controller.signal.aborted) onError?.(); } catch { if (!controller.signal.aborted) onError?.(); } })(); return () => controller.abort(); } const source = new EventSource("/api/v1/events/stream"); const emit = (message: MessageEvent) => { try { onEvent(JSON.parse(message.data) as EventRecord); } catch { /* reconnect/poll remains the fallback */ } }; source.onmessage = emit; // Named SSE events are only delivered to explicit listeners; a type missing // here is silently dropped by EventSource. for (const eventType of SSE_EVENT_TYPES) { source.addEventListener(eventType, emit); } source.onerror = () => onError?.(); source.onopen = () => onOpen?.(); return () => source.close(); }