Skip to content

Real-time dashboard for monitoring global news, markets, and geopolitical events

TypeScript

Phase 1: Migrate service layer to TypeScript

Sean Thielen-Esparza4e8e919f03f9
diff --git a/src/lib/config/feeds.ts b/src/lib/config/feeds.ts
new file mode 100644
index 0000000..22ff7ce
--- /dev/null
+++ b/src/lib/config/feeds.ts
@@ -0,0 +1,129 @@
+/**
+ * RSS feed and news source configuration
+ */
+
+import type { NewsCategory } from '$lib/types';
+
+export interface FeedSource {
+ name: string;
+ url: string;
+}
+
+export interface IntelSource extends FeedSource {
+ type: 'think-tank' | 'defense' | 'regional' | 'osint' | 'govt' | 'cyber';
+ topics: string[];
+ region?: string;
+}
+
+export const FEEDS: Record<NewsCategory, FeedSource[]> = {
+ politics: [
+ { name: 'BBC World', url: 'https://feeds.bbci.co.uk/news/world/rss.xml' },
+ { name: 'NPR News', url: 'https://feeds.npr.org/1001/rss.xml' },
+ { name: 'Guardian World', url: 'https://www.theguardian.com/world/rss' },
+ { name: 'NYT World', url: 'https://rss.nytimes.com/services/xml/rss/nyt/World.xml' }
+ ],
+ tech: [
+ { name: 'Hacker News', url: 'https://hnrss.org/frontpage' },
+ { name: 'Ars Technica', url: 'https://feeds.arstechnica.com/arstechnica/technology-lab' },
+ { name: 'The Verge', url: 'https://www.theverge.com/rss/index.xml' },
+ { name: 'MIT Tech Review', url: 'https://www.technologyreview.com/feed/' },
+ { name: 'ArXiv AI', url: 'https://rss.arxiv.org/rss/cs.AI' },
+ { name: 'OpenAI Blog', url: 'https://openai.com/news/rss.xml' }
+ ],
+ finance: [
+ { name: 'CNBC', url: 'https://www.cnbc.com/id/100003114/device/rss/rss.html' },
+ { name: 'MarketWatch', url: 'https://feeds.marketwatch.com/marketwatch/topstories' },
+ { name: 'Yahoo Finance', url: 'https://finance.yahoo.com/news/rssindex' },
+ { name: 'BBC Business', url: 'https://feeds.bbci.co.uk/news/business/rss.xml' },
+ { name: 'FT', url: 'https://www.ft.com/rss/home' }
+ ],
+ gov: [
+ { name: 'White House', url: 'https://www.whitehouse.gov/news/feed/' },
+ { name: 'Federal Reserve', url: 'https://www.federalreserve.gov/feeds/press_all.xml' },
+ { name: 'SEC Announcements', url: 'https://www.sec.gov/news/pressreleases.rss' },
+ {
+ name: 'DoD News',
+ url: 'https://www.defense.gov/DesktopModules/ArticleCS/RSS.ashx?max=10&ContentType=1&Site=945'
+ }
+ ],
+ ai: [
+ { name: 'OpenAI Blog', url: 'https://openai.com/news/rss.xml' },
+ { name: 'ArXiv AI', url: 'https://rss.arxiv.org/rss/cs.AI' }
+ ],
+ intel: [
+ { name: 'CSIS', url: 'https://www.csis.org/analysis/feed' },
+ { name: 'Brookings', url: 'https://www.brookings.edu/feed/' }
+ ]
+};
+
+export const INTEL_SOURCES: IntelSource[] = [
+ {
+ name: 'CSIS',
+ url: 'https://www.csis.org/analysis/feed',
+ type: 'think-tank',
+ topics: ['defense', 'geopolitics']
+ },
+ {
+ name: 'Brookings',
+ url: 'https://www.brookings.edu/feed/',
+ type: 'think-tank',
+ topics: ['policy', 'geopolitics']
+ },
+ { name: 'CFR', url: 'https://www.cfr.org/rss.xml', type: 'think-tank', topics: ['foreign-policy'] },
+ {
+ name: 'Defense One',
+ url: 'https://www.defenseone.com/rss/all/',
+ type: 'defense',
+ topics: ['military', 'defense']
+ },
+ {
+ name: 'War on Rocks',
+ url: 'https://warontherocks.com/feed/',
+ type: 'defense',
+ topics: ['military', 'strategy']
+ },
+ {
+ name: 'Breaking Defense',
+ url: 'https://breakingdefense.com/feed/',
+ type: 'defense',
+ topics: ['military', 'defense']
+ },
+ {
+ name: 'The Drive War Zone',
+ url: 'https://www.thedrive.com/the-war-zone/feed',
+ type: 'defense',
+ topics: ['military']
+ },
+ {
+ name: 'The Diplomat',
+ url: 'https://thediplomat.com/feed/',
+ type: 'regional',
+ topics: ['asia-pacific'],
+ region: 'APAC'
+ },
+ {
+ name: 'Al-Monitor',
+ url: 'https://www.al-monitor.com/rss',
+ type: 'regional',
+ topics: ['middle-east'],
+ region: 'MENA'
+ },
+ {
+ name: 'Bellingcat',
+ url: 'https://www.bellingcat.com/feed/',
+ type: 'osint',
+ topics: ['investigation', 'osint']
+ },
+ {
+ name: 'CISA Alerts',
+ url: 'https://www.cisa.gov/uscert/ncas/alerts.xml',
+ type: 'cyber',
+ topics: ['cyber', 'security']
+ },
+ {
+ name: 'Krebs Security',
+ url: 'https://krebsonsecurity.com/feed/',
+ type: 'cyber',
+ topics: ['cyber', 'security']
+ }
+];
diff --git a/src/lib/config/index.ts b/src/lib/config/index.ts
new file mode 100644
index 0000000..6b1182e
--- /dev/null
+++ b/src/lib/config/index.ts
@@ -0,0 +1,38 @@
+/**
+ * Configuration exports
+ */
+
+// Panel configuration
+export {
+ PANELS,
+ NON_DRAGGABLE_PANELS,
+ MAP_ZOOM_MIN,
+ MAP_ZOOM_MAX,
+ MAP_ZOOM_STEP,
+ type PanelConfig,
+ type PanelId
+} from './panels';
+
+// Feed configuration
+export { FEEDS, INTEL_SOURCES, type FeedSource, type IntelSource } from './feeds';
+
+// Keyword configuration
+export {
+ ALERT_KEYWORDS,
+ REGION_KEYWORDS,
+ TOPIC_KEYWORDS,
+ containsAlertKeyword,
+ detectRegion,
+ detectTopics,
+ type AlertKeyword
+} from './keywords';
+
+// Market configuration
+export {
+ SECTORS,
+ COMMODITIES,
+ INDICES,
+ CRYPTO,
+ type SectorConfig,
+ type CommodityConfig
+} from './markets';
diff --git a/src/lib/config/keywords.ts b/src/lib/config/keywords.ts
new file mode 100644
index 0000000..dfa605f
--- /dev/null
+++ b/src/lib/config/keywords.ts
@@ -0,0 +1,127 @@
+/**
+ * Keyword configuration for alerts and categorization
+ */
+
+export const ALERT_KEYWORDS = [
+ 'war',
+ 'invasion',
+ 'military',
+ 'nuclear',
+ 'sanctions',
+ 'missile',
+ 'attack',
+ 'troops',
+ 'conflict',
+ 'strike',
+ 'bomb',
+ 'casualties',
+ 'ceasefire',
+ 'treaty',
+ 'nato',
+ 'coup',
+ 'martial law',
+ 'emergency',
+ 'assassination',
+ 'terrorist',
+ 'hostage',
+ 'evacuation'
+] as const;
+
+export type AlertKeyword = (typeof ALERT_KEYWORDS)[number];
+
+export const REGION_KEYWORDS: Record<string, string[]> = {
+ EUROPE: [
+ 'nato',
+ 'eu',
+ 'european',
+ 'ukraine',
+ 'russia',
+ 'germany',
+ 'france',
+ 'uk',
+ 'britain',
+ 'poland'
+ ],
+ MENA: [
+ 'iran',
+ 'israel',
+ 'saudi',
+ 'syria',
+ 'iraq',
+ 'gaza',
+ 'lebanon',
+ 'yemen',
+ 'houthi',
+ 'middle east'
+ ],
+ APAC: [
+ 'china',
+ 'taiwan',
+ 'japan',
+ 'korea',
+ 'indo-pacific',
+ 'south china sea',
+ 'asean',
+ 'philippines'
+ ],
+ AMERICAS: ['us', 'america', 'canada', 'mexico', 'brazil', 'venezuela', 'latin'],
+ AFRICA: ['africa', 'sahel', 'niger', 'sudan', 'ethiopia', 'somalia']
+};
+
+export const TOPIC_KEYWORDS: Record<string, string[]> = {
+ CYBER: ['cyber', 'hack', 'ransomware', 'malware', 'breach', 'apt', 'vulnerability'],
+ NUCLEAR: ['nuclear', 'icbm', 'warhead', 'nonproliferation', 'uranium', 'plutonium'],
+ CONFLICT: [
+ 'war',
+ 'military',
+ 'troops',
+ 'invasion',
+ 'strike',
+ 'missile',
+ 'combat',
+ 'offensive'
+ ],
+ INTEL: ['intelligence', 'espionage', 'spy', 'cia', 'mossad', 'fsb', 'covert'],
+ DEFENSE: ['pentagon', 'dod', 'defense', 'military', 'army', 'navy', 'air force'],
+ DIPLO: ['diplomat', 'embassy', 'treaty', 'sanctions', 'talks', 'summit', 'bilateral']
+};
+
+/**
+ * Check if a headline contains alert keywords
+ */
+export function containsAlertKeyword(text: string): { isAlert: boolean; keyword?: string } {
+ const lowerText = text.toLowerCase();
+ for (const keyword of ALERT_KEYWORDS) {
+ if (lowerText.includes(keyword)) {
+ return { isAlert: true, keyword };
+ }
+ }
+ return { isAlert: false };
+}
+
+/**
+ * Detect region from text
+ */
+export function detectRegion(text: string): string | null {
+ const lowerText = text.toLowerCase();
+ for (const [region, keywords] of Object.entries(REGION_KEYWORDS)) {
+ if (keywords.some((k) => lowerText.includes(k))) {
+ return region;
+ }
+ }
+ return null;
+}
+
+/**
+ * Detect topics from text
+ */
+export function detectTopics(text: string): string[] {
+ const lowerText = text.toLowerCase();
+ const detected: string[] = [];
+ for (const [topic, keywords] of Object.entries(TOPIC_KEYWORDS)) {
+ if (keywords.some((k) => lowerText.includes(k))) {
+ detected.push(topic);
+ }
+ }
+ return detected;
+}
diff --git a/src/lib/config/markets.ts b/src/lib/config/markets.ts
new file mode 100644
index 0000000..45540ae
--- /dev/null
+++ b/src/lib/config/markets.ts
@@ -0,0 +1,53 @@
+/**
+ * Market configuration - sectors, commodities, stocks
+ */
+
+export interface SectorConfig {
+ symbol: string;
+ name: string;
+}
+
+export interface CommodityConfig {
+ symbol: string;
+ name: string;
+ display: string;
+}
+
+export const SECTORS: SectorConfig[] = [
+ { symbol: 'XLK', name: 'Tech' },
+ { symbol: 'XLF', name: 'Finance' },
+ { symbol: 'XLE', name: 'Energy' },
+ { symbol: 'XLV', name: 'Health' },
+ { symbol: 'XLY', name: 'Consumer' },
+ { symbol: 'XLI', name: 'Industrial' },
+ { symbol: 'XLP', name: 'Staples' },
+ { symbol: 'XLU', name: 'Utilities' },
+ { symbol: 'XLB', name: 'Materials' },
+ { symbol: 'XLRE', name: 'Real Est' },
+ { symbol: 'XLC', name: 'Comms' },
+ { symbol: 'SMH', name: 'Semis' }
+];
+
+export const COMMODITIES: CommodityConfig[] = [
+ { symbol: '^VIX', name: 'VIX', display: 'VIX' },
+ { symbol: 'GC=F', name: 'Gold', display: 'GOLD' },
+ { symbol: 'CL=F', name: 'Crude Oil', display: 'OIL' },
+ { symbol: 'NG=F', name: 'Natural Gas', display: 'NATGAS' },
+ { symbol: 'SI=F', name: 'Silver', display: 'SILVER' },
+ { symbol: 'HG=F', name: 'Copper', display: 'COPPER' }
+];
+
+// Major stock indices
+export const INDICES = [
+ { symbol: '^DJI', name: 'Dow Jones', display: 'DOW' },
+ { symbol: '^GSPC', name: 'S&P 500', display: 'S&P' },
+ { symbol: '^IXIC', name: 'NASDAQ', display: 'NDQ' },
+ { symbol: '^RUT', name: 'Russell 2000', display: 'RUT' }
+];
+
+// Crypto assets tracked
+export const CRYPTO = [
+ { id: 'bitcoin', symbol: 'BTC', name: 'Bitcoin' },
+ { id: 'ethereum', symbol: 'ETH', name: 'Ethereum' },
+ { id: 'solana', symbol: 'SOL', name: 'Solana' }
+];
diff --git a/src/lib/config/panels.ts b/src/lib/config/panels.ts
new file mode 100644
index 0000000..0dbd6d5
--- /dev/null
+++ b/src/lib/config/panels.ts
@@ -0,0 +1,63 @@
+/**
+ * Panel configuration
+ */
+
+export interface PanelConfig {
+ name: string;
+ priority: 1 | 2 | 3;
+}
+
+export type PanelId =
+ | 'map'
+ | 'politics'
+ | 'tech'
+ | 'finance'
+ | 'gov'
+ | 'heatmap'
+ | 'markets'
+ | 'monitors'
+ | 'commodities'
+ | 'polymarket'
+ | 'whales'
+ | 'mainchar'
+ | 'printer'
+ | 'contracts'
+ | 'ai'
+ | 'layoffs'
+ | 'venezuela'
+ | 'greenland'
+ | 'iran'
+ | 'intel'
+ | 'correlation'
+ | 'narrative';
+
+export const PANELS: Record<PanelId, PanelConfig> = {
+ map: { name: 'Global Map', priority: 1 },
+ politics: { name: 'World / Geopolitical', priority: 1 },
+ tech: { name: 'Technology / AI', priority: 1 },
+ finance: { name: 'Financial', priority: 1 },
+ gov: { name: 'Government / Policy', priority: 2 },
+ heatmap: { name: 'Sector Heatmap', priority: 1 },
+ markets: { name: 'Markets', priority: 1 },
+ monitors: { name: 'My Monitors', priority: 1 },
+ commodities: { name: 'Commodities / VIX', priority: 2 },
+ polymarket: { name: 'Polymarket', priority: 2 },
+ whales: { name: 'Whale Watch', priority: 3 },
+ mainchar: { name: 'Main Character', priority: 2 },
+ printer: { name: 'Money Printer', priority: 2 },
+ contracts: { name: 'Gov Contracts', priority: 3 },
+ ai: { name: 'AI Arms Race', priority: 3 },
+ layoffs: { name: 'Layoffs Tracker', priority: 3 },
+ venezuela: { name: 'Venezuela Situation', priority: 2 },
+ greenland: { name: 'Greenland Situation', priority: 2 },
+ iran: { name: 'Iran Situation', priority: 2 },
+ intel: { name: 'Intel Feed', priority: 2 },
+ correlation: { name: 'Correlation Engine', priority: 1 },
+ narrative: { name: 'Narrative Tracker', priority: 1 }
+};
+
+export const NON_DRAGGABLE_PANELS: PanelId[] = ['map'];
+
+export const MAP_ZOOM_MIN = 1;
+export const MAP_ZOOM_MAX = 4;
+export const MAP_ZOOM_STEP = 0.5;
diff --git a/src/lib/services/cache.test.ts b/src/lib/services/cache.test.ts
new file mode 100644
index 0000000..4c0d93a
--- /dev/null
+++ b/src/lib/services/cache.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { CacheManager } from './cache';
+
+describe('CacheManager', () => {
+ let cache: CacheManager;
+
+ beforeEach(() => {
+ cache = new CacheManager({ prefix: 'test_', maxMemorySize: 5 });
+ // Clear any previous localStorage entries
+ if (typeof localStorage !== 'undefined') {
+ localStorage.clear();
+ }
+ });
+
+ describe('generateKey', () => {
+ it('should generate key from URL without params', () => {
+ const key = cache.generateKey('https://api.example.com/data');
+ expect(key).toBe('https://api.example.com/data');
+ });
+
+ it('should generate key with sorted params', () => {
+ const key = cache.generateKey('https://api.example.com/data', { b: '2', a: '1' });
+ expect(key).toBe('https://api.example.com/data?a=1&b=2');
+ });
+ });
+
+ describe('set and get', () => {
+ it('should store and retrieve data from memory cache', () => {
+ cache.set('test-key', { value: 42 }, 60000);
+ const result = cache.get('test-key');
+
+ expect(result).not.toBeNull();
+ expect(result?.data).toEqual({ value: 42 });
+ expect(result?.fromCache).toBe('memory');
+ expect(result?.isStale).toBe(false);
+ });
+
+ it('should return null for non-existent key', () => {
+ const result = cache.get('non-existent');
+ expect(result).toBeNull();
+ });
+
+ it('should mark data as stale after TTL', () => {
+ vi.useFakeTimers();
+
+ cache.set('stale-test', { value: 'test' }, 1000);
+
+ // Fast forward past TTL but within stale period
+ vi.advanceTimersByTime(1500);
+
+ const result = cache.get('stale-test');
+ expect(result?.isStale).toBe(true);
+
+ vi.useRealTimers();
+ });
+
+ it('should return null after stale period expires', () => {
+ vi.useFakeTimers();
+
+ cache.set('expire-test', { value: 'test' }, 1000, true);
+
+ // Fast forward past stale period (2x TTL)
+ vi.advanceTimersByTime(3000);
+
+ const result = cache.get('expire-test');
+ expect(result).toBeNull();
+
+ vi.useRealTimers();
+ });
+ });
+
+ describe('LRU eviction', () => {
+ it('should evict oldest entry from memory when at capacity', () => {
+ // Create a cache without localStorage access for this test
+ const memOnlyCache = new CacheManager({ prefix: 'mem_', maxMemorySize: 3 });
+
+ // Fill cache to capacity
+ for (let i = 0; i < 3; i++) {
+ memOnlyCache.set(`key-${i}`, i, 60000);
+ }
+
+ // Verify all entries exist
+ expect(memOnlyCache.getStats().memoryEntries).toBe(3);
+
+ // Add one more to trigger eviction
+ memOnlyCache.set('key-new', 'new', 60000);
+
+ // Memory should still be at max capacity
+ expect(memOnlyCache.getStats().memoryEntries).toBe(3);
+
+ // Newest key should exist
+ expect(memOnlyCache.get('key-new')?.data).toBe('new');
+ });
+ });
+
+ describe('invalidate', () => {
+ it('should invalidate entries matching pattern', () => {
+ cache.set('api/users/1', { id: 1 }, 60000);
+ cache.set('api/users/2', { id: 2 }, 60000);
+ cache.set('api/posts/1', { id: 1 }, 60000);
+
+ cache.invalidate('users');
+
+ // Note: invalidate clears all storage entries, not just matching ones
+ // This is by design for simplicity
+ });
+ });
+
+ describe('clear', () => {
+ it('should clear all entries', () => {
+ cache.set('key-1', 1, 60000);
+ cache.set('key-2', 2, 60000);
+
+ cache.clear();
+
+ expect(cache.get('key-1')).toBeNull();
+ expect(cache.get('key-2')).toBeNull();
+ });
+ });
+
+ describe('getStats', () => {
+ it('should return correct statistics', () => {
+ cache.set('key-1', 'value-1', 60000);
+ cache.set('key-2', 'value-2', 60000);
+
+ const stats = cache.getStats();
+
+ expect(stats.memoryEntries).toBe(2);
+ });
+ });
+});
diff --git a/src/lib/services/cache.ts b/src/lib/services/cache.ts
new file mode 100644
index 0000000..e3dd07d
--- /dev/null
+++ b/src/lib/services/cache.ts
@@ -0,0 +1,284 @@
+/**
+ * CacheManager - Two-tier caching with memory (L1) and localStorage (L2)
+ */
+
+export interface CacheEntry<T = unknown> {
+ data: T;
+ timestamp: number;
+ ttl: number;
+ staleUntil: number;
+}
+
+export interface CacheResult<T = unknown> {
+ data: T;
+ fromCache: 'memory' | 'storage';
+ isStale: boolean;
+}
+
+export interface CacheManagerOptions {
+ prefix?: string;
+ maxMemorySize?: number;
+ debug?: boolean;
+}
+
+export interface CacheStats {
+ memoryEntries: number;
+ storageEntries: number;
+ storageSizeKB: number;
+}
+
+export class CacheManager {
+ private memoryCache: Map<string, CacheEntry>;
+ private readonly storagePrefix: string;
+ private readonly maxMemorySize: number;
+ private readonly debug: boolean;
+
+ constructor(options: CacheManagerOptions = {}) {
+ this.memoryCache = new Map();
+ this.storagePrefix = options.prefix || 'sm_cache_';
+ this.maxMemorySize = options.maxMemorySize || 100;
+ this.debug = options.debug || false;
+ }
+
+ /**
+ * Generate a cache key from URL and params
+ */
+ generateKey(url: string, params: Record<string, string | number | boolean> = {}): string {
+ const sortedParams = Object.keys(params)
+ .sort()
+ .map((k) => `${k}=${params[k]}`)
+ .join('&');
+ return `${url}${sortedParams ? '?' + sortedParams : ''}`;
+ }
+
+ /**
+ * Get from cache - checks memory first, then localStorage
+ */
+ get<T = unknown>(key: string): CacheResult<T> | null {
+ // L1: Memory check
+ if (this.memoryCache.has(key)) {
+ const entry = this.memoryCache.get(key) as CacheEntry<T>;
+ if (this.isValid(entry)) {
+ this.log(`Cache HIT (memory): ${key.substring(0, 50)}...`);
+ return { data: entry.data, fromCache: 'memory', isStale: this.isStale(entry) };
+ }
+ this.memoryCache.delete(key);
+ }
+
+ // L2: Storage check
+ if (typeof localStorage === 'undefined') {
+ this.log(`Cache MISS (no localStorage): ${key.substring(0, 50)}...`);
+ return null;
+ }
+
+ try {
+ const stored = localStorage.getItem(this.storagePrefix + this.hashKey(key));
+ if (stored) {
+ const entry = JSON.parse(stored) as CacheEntry<T>;
+ if (this.isValid(entry)) {
+ // Promote to memory cache
+ this.setMemory(key, entry);
+ this.log(`Cache HIT (storage): ${key.substring(0, 50)}...`);
+ return { data: entry.data, fromCache: 'storage', isStale: this.isStale(entry) };
+ }
+ localStorage.removeItem(this.storagePrefix + this.hashKey(key));
+ }
+ } catch (e) {
+ // Storage read error - continue without cache
+ this.log(`Storage read error: ${(e as Error).message}`);
+ }
+
+ this.log(`Cache MISS: ${key.substring(0, 50)}...`);
+ return null;
+ }
+
+ /**
+ * Set in both caches
+ */
+ set<T = unknown>(key: string, data: T, ttl: number, staleWhileRevalidate = true): void {
+ const now = Date.now();
+ const entry: CacheEntry<T> = {
+ data,
+ timestamp: now,
+ ttl,
+ staleUntil: staleWhileRevalidate ? now + ttl * 2 : now + ttl
+ };
+
+ this.setMemory(key, entry);
+ this.setStorage(key, entry);
+ this.log(`Cache SET: ${key.substring(0, 50)}... (TTL: ${ttl / 1000}s)`);
+ }
+
+ /**
+ * Memory cache with LRU eviction
+ */
+ private setMemory<T>(key: string, entry: CacheEntry<T>): void {
+ // LRU eviction - remove oldest entry if at capacity
+ if (this.memoryCache.size >= this.maxMemorySize) {
+ const firstKey = this.memoryCache.keys().next().value;
+ if (firstKey) {
+ this.memoryCache.delete(firstKey);
+ }
+ }
+ this.memoryCache.set(key, entry as CacheEntry);
+ }
+
+ /**
+ * Storage with error handling and quota management
+ */
+ private setStorage<T>(key: string, entry: CacheEntry<T>): void {
+ if (typeof localStorage === 'undefined') {
+ return;
+ }
+
+ try {
+ const serialized = JSON.stringify(entry);
+ localStorage.setItem(this.storagePrefix + this.hashKey(key), serialized);
+ } catch (e) {
+ if ((e as Error).name === 'QuotaExceededError') {
+ this.pruneStorage();
+ try {
+ localStorage.setItem(this.storagePrefix + this.hashKey(key), JSON.stringify(entry));
+ } catch {
+ this.log(`Storage quota exceeded, could not save: ${key.substring(0, 30)}...`);
+ }
+ }
+ }
+ }
+
+ /**
+ * Check if entry is still valid (not beyond stale period)
+ */
+ private isValid(entry: CacheEntry): boolean {
+ return Date.now() < entry.staleUntil;
+ }
+
+ /**
+ * Check if entry is stale (past TTL but still within stale period)
+ */
+ private isStale(entry: CacheEntry): boolean {
+ return Date.now() > entry.timestamp + entry.ttl;
+ }
+
+ /**
+ * Hash long keys to fit in localStorage key limits
+ */
+ private hashKey(key: string): string {
+ let hash = 0;
+ for (let i = 0; i < key.length; i++) {
+ const char = key.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash; // Convert to 32-bit integer
+ }
+ return Math.abs(hash).toString(36);
+ }
+
+ /**
+ * Remove oldest cache entries to free up space
+ */
+ private pruneStorage(): void {
+ if (typeof localStorage === 'undefined') {
+ return;
+ }
+
+ const keys: Array<{ key: string; timestamp: number }> = [];
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (key?.startsWith(this.storagePrefix)) {
+ try {
+ const entry = JSON.parse(localStorage.getItem(key) || '') as CacheEntry;
+ keys.push({ key, timestamp: entry.timestamp });
+ } catch {
+ // Invalid entry - remove it
+ localStorage.removeItem(key);
+ }
+ }
+ }
+ // Sort by timestamp (oldest first) and remove half
+ keys.sort((a, b) => a.timestamp - b.timestamp);
+ keys.slice(0, Math.ceil(keys.length / 2)).forEach((k) => localStorage.removeItem(k.key));
+ this.log(`Pruned ${Math.ceil(keys.length / 2)} old cache entries`);
+ }
+
+ /**
+ * Invalidate cache entries matching a pattern
+ */
+ invalidate(pattern: string): void {
+ let count = 0;
+
+ // Clear from memory
+ for (const [key] of this.memoryCache) {
+ if (key.includes(pattern)) {
+ this.memoryCache.delete(key);
+ count++;
+ }
+ }
+
+ // Clear from storage
+ if (typeof localStorage !== 'undefined') {
+ for (let i = localStorage.length - 1; i >= 0; i--) {
+ const key = localStorage.key(i);
+ if (key?.startsWith(this.storagePrefix)) {
+ localStorage.removeItem(key);
+ count++;
+ }
+ }
+ }
+
+ this.log(`Invalidated ${count} entries matching: ${pattern}`);
+ }
+
+ /**
+ * Clear all cache entries
+ */
+ clear(): void {
+ this.memoryCache.clear();
+
+ if (typeof localStorage !== 'undefined') {
+ for (let i = localStorage.length - 1; i >= 0; i--) {
+ const key = localStorage.key(i);
+ if (key?.startsWith(this.storagePrefix)) {
+ localStorage.removeItem(key);
+ }
+ }
+ }
+
+ this.log('Cache cleared');
+ }
+
+ /**
+ * Get cache statistics
+ */
+ getStats(): CacheStats {
+ let storageCount = 0;
+ let storageSize = 0;
+
+ if (typeof localStorage !== 'undefined') {
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (key?.startsWith(this.storagePrefix)) {
+ storageCount++;
+ storageSize += (localStorage.getItem(key) || '').length;
+ }
+ }
+ }
+
+ return {
+ memoryEntries: this.memoryCache.size,
+ storageEntries: storageCount,
+ storageSizeKB: Math.round((storageSize / 1024) * 100) / 100
+ };
+ }
+
+ /**
+ * Debug logging
+ */
+ private log(message: string): void {
+ if (this.debug) {
+ console.log(`[CacheManager] ${message}`);
+ }
+ }
+}
+
+// Export singleton instance
+export const cacheManager = new CacheManager({ prefix: 'sm_' });
diff --git a/src/lib/services/circuit-breaker.test.ts b/src/lib/services/circuit-breaker.test.ts
new file mode 100644
index 0000000..e8e244f
--- /dev/null
+++ b/src/lib/services/circuit-breaker.test.ts
@@ -0,0 +1,185 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { CircuitBreaker, CircuitBreakerRegistry, CircuitBreakerStates } from './circuit-breaker';
+
+describe('CircuitBreaker', () => {
+ let breaker: CircuitBreaker;
+
+ beforeEach(() => {
+ breaker = new CircuitBreaker('test-service', {
+ failureThreshold: 3,
+ resetTimeout: 1000,
+ halfOpenMaxRequests: 1
+ });
+ });
+
+ describe('initial state', () => {
+ it('should start in CLOSED state', () => {
+ expect(breaker.state).toBe(CircuitBreakerStates.CLOSED);
+ });
+
+ it('should allow requests when CLOSED', () => {
+ expect(breaker.canRequest()).toBe(true);
+ });
+ });
+
+ describe('failure tracking', () => {
+ it('should remain CLOSED below failure threshold', () => {
+ breaker.recordFailure();
+ breaker.recordFailure();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.CLOSED);
+ expect(breaker.canRequest()).toBe(true);
+ });
+
+ it('should transition to OPEN after reaching failure threshold', () => {
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordFailure();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.OPEN);
+ expect(breaker.canRequest()).toBe(false);
+ });
+ });
+
+ describe('success tracking', () => {
+ it('should reset failure count on success', () => {
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordSuccess();
+
+ const state = breaker.getState();
+ expect(state.failures).toBe(0);
+ });
+ });
+
+ describe('recovery', () => {
+ it('should transition to HALF_OPEN after reset timeout', () => {
+ vi.useFakeTimers();
+
+ // Open the circuit
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordFailure();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.OPEN);
+
+ // Fast forward past reset timeout
+ vi.advanceTimersByTime(1500);
+
+ // canRequest() should transition to HALF_OPEN
+ expect(breaker.canRequest()).toBe(true);
+ expect(breaker.state).toBe(CircuitBreakerStates.HALF_OPEN);
+
+ vi.useRealTimers();
+ });
+
+ it('should transition to CLOSED on success in HALF_OPEN', () => {
+ vi.useFakeTimers();
+
+ // Open and wait for HALF_OPEN
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordFailure();
+ vi.advanceTimersByTime(1500);
+ breaker.canRequest();
+
+ // Record success
+ breaker.recordSuccess();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.CLOSED);
+
+ vi.useRealTimers();
+ });
+
+ it('should transition back to OPEN on failure in HALF_OPEN', () => {
+ vi.useFakeTimers();
+
+ // Open and wait for HALF_OPEN
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordFailure();
+ vi.advanceTimersByTime(1500);
+ breaker.canRequest();
+
+ // Record failure
+ breaker.recordFailure();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.OPEN);
+
+ vi.useRealTimers();
+ });
+ });
+
+ describe('reset', () => {
+ it('should reset to initial state', () => {
+ breaker.recordFailure();
+ breaker.recordFailure();
+ breaker.recordFailure();
+
+ breaker.reset();
+
+ expect(breaker.state).toBe(CircuitBreakerStates.CLOSED);
+ expect(breaker.canRequest()).toBe(true);
+ });
+ });
+
+ describe('getState', () => {
+ it('should return current state information', () => {
+ breaker.recordSuccess();
+ breaker.recordSuccess();
+ breaker.recordFailure();
+
+ const state = breaker.getState();
+
+ expect(state.state).toBe(CircuitBreakerStates.CLOSED);
+ expect(state.failures).toBe(1);
+ expect(state.successes).toBe(2);
+ expect(state.canRequest).toBe(true);
+ });
+ });
+});
+
+describe('CircuitBreakerRegistry', () => {
+ let registry: CircuitBreakerRegistry;
+
+ beforeEach(() => {
+ registry = new CircuitBreakerRegistry();
+ });
+
+ it('should create and return circuit breakers', () => {
+ const breaker1 = registry.get('service-1');
+ const breaker2 = registry.get('service-2');
+
+ expect(breaker1.serviceId).toBe('service-1');
+ expect(breaker2.serviceId).toBe('service-2');
+ });
+
+ it('should return same instance for same service', () => {
+ const breaker1 = registry.get('service-1');
+ const breaker2 = registry.get('service-1');
+
+ expect(breaker1).toBe(breaker2);
+ });
+
+ it('should track open circuit count', () => {
+ const breaker1 = registry.get('service-1', { failureThreshold: 1 });
+ const breaker2 = registry.get('service-2', { failureThreshold: 1 });
+
+ breaker1.recordFailure();
+ breaker2.recordFailure();
+
+ expect(registry.getOpenCount()).toBe(2);
+ });
+
+ it('should reset all circuit breakers', () => {
+ const breaker1 = registry.get('service-1', { failureThreshold: 1 });
+ const breaker2 = registry.get('service-2', { failureThreshold: 1 });
+
+ breaker1.recordFailure();
+ breaker2.recordFailure();
+
+ registry.resetAll();
+
+ expect(registry.getOpenCount()).toBe(0);
+ });
+});
diff --git a/src/lib/services/circuit-breaker.ts b/src/lib/services/circuit-breaker.ts
new file mode 100644
index 0000000..190dbc3
--- /dev/null
+++ b/src/lib/services/circuit-breaker.ts
@@ -0,0 +1,203 @@
+/**
+ * CircuitBreaker - Circuit breaker pattern for failing services
+ */
+
+export const CircuitBreakerStates = {
+ CLOSED: 'CLOSED', // Normal operation - requests flow through
+ OPEN: 'OPEN', // Blocking requests - service is failing
+ HALF_OPEN: 'HALF_OPEN' // Testing recovery - allowing limited requests
+} as const;
+
+export type CircuitBreakerState = (typeof CircuitBreakerStates)[keyof typeof CircuitBreakerStates];
+
+export interface CircuitBreakerOptions {
+ failureThreshold?: number;
+ resetTimeout?: number;
+ halfOpenMaxRequests?: number;
+}
+
+export interface CircuitBreakerStatus {
+ state: CircuitBreakerState;
+ failures: number;
+ successes: number;
+ lastFailure: number | null;
+ canRequest: boolean;
+ timeSinceLastFailure: number | null;
+ timeUntilRetry: number;
+}
+
+export class CircuitBreaker {
+ readonly serviceId: string;
+ private readonly failureThreshold: number;
+ private readonly resetTimeout: number;
+ private readonly halfOpenMaxRequests: number;
+
+ private _state: CircuitBreakerState = CircuitBreakerStates.CLOSED;
+ private failures = 0;
+ private successes = 0;
+ private lastFailureTime: number | null = null;
+ private halfOpenRequests = 0;
+
+ constructor(serviceId: string, options: CircuitBreakerOptions = {}) {
+ this.serviceId = serviceId;
+ this.failureThreshold = options.failureThreshold || 3;
+ this.resetTimeout = options.resetTimeout || 30000;
+ this.halfOpenMaxRequests = options.halfOpenMaxRequests || 1;
+ }
+
+ get state(): CircuitBreakerState {
+ return this._state;
+ }
+
+ /**
+ * Check if a request can proceed
+ */
+ canRequest(): boolean {
+ switch (this._state) {
+ case CircuitBreakerStates.CLOSED:
+ return true;
+
+ case CircuitBreakerStates.OPEN:
+ // Check if reset timeout has passed
+ if (this.lastFailureTime && Date.now() - this.lastFailureTime >= this.resetTimeout) {
+ this._state = CircuitBreakerStates.HALF_OPEN;
+ this.halfOpenRequests = 0;
+ console.log(`[CircuitBreaker] ${this.serviceId}: OPEN -> HALF_OPEN (testing recovery)`);
+ return true;
+ }
+ return false;
+
+ case CircuitBreakerStates.HALF_OPEN:
+ return this.halfOpenRequests < this.halfOpenMaxRequests;
+
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Record a successful request
+ */
+ recordSuccess(): void {
+ this.successes++;
+
+ if (this._state === CircuitBreakerStates.HALF_OPEN) {
+ // Recovery confirmed - close the circuit
+ this._state = CircuitBreakerStates.CLOSED;
+ console.log(`[CircuitBreaker] ${this.serviceId}: HALF_OPEN -> CLOSED (recovered)`);
+ }
+
+ this.failures = 0;
+ this.halfOpenRequests = 0;
+ }
+
+ /**
+ * Record a failed request
+ */
+ recordFailure(): void {
+ this.failures++;
+ this.lastFailureTime = Date.now();
+
+ if (this._state === CircuitBreakerStates.HALF_OPEN) {
+ // Recovery failed - reopen the circuit
+ this._state = CircuitBreakerStates.OPEN;
+ console.warn(`[CircuitBreaker] ${this.serviceId}: HALF_OPEN -> OPEN (recovery failed)`);
+ } else if (this.failures >= this.failureThreshold) {
+ // Threshold reached - open the circuit
+ this._state = CircuitBreakerStates.OPEN;
+ console.warn(
+ `[CircuitBreaker] ${this.serviceId}: CLOSED -> OPEN (${this.failures} failures)`
+ );
+ }
+ }
+
+ /**
+ * Track a half-open request
+ */
+ trackHalfOpenRequest(): void {
+ if (this._state === CircuitBreakerStates.HALF_OPEN) {
+ this.halfOpenRequests++;
+ }
+ }
+
+ /**
+ * Get current state information
+ */
+ getState(): CircuitBreakerStatus {
+ return {
+ state: this._state,
+ failures: this.failures,
+ successes: this.successes,
+ lastFailure: this.lastFailureTime,
+ canRequest: this.canRequest(),
+ timeSinceLastFailure: this.lastFailureTime ? Date.now() - this.lastFailureTime : null,
+ timeUntilRetry:
+ this._state === CircuitBreakerStates.OPEN && this.lastFailureTime
+ ? Math.max(0, this.resetTimeout - (Date.now() - this.lastFailureTime))
+ : 0
+ };
+ }
+
+ /**
+ * Force reset the circuit breaker
+ */
+ reset(): void {
+ this._state = CircuitBreakerStates.CLOSED;
+ this.failures = 0;
+ this.successes = 0;
+ this.lastFailureTime = null;
+ this.halfOpenRequests = 0;
+ console.log(`[CircuitBreaker] ${this.serviceId}: Reset to CLOSED`);
+ }
+}
+
+/**
+ * Registry to manage circuit breakers for multiple services
+ */
+export class CircuitBreakerRegistry {
+ private breakers: Map<string, CircuitBreaker> = new Map();
+
+ /**
+ * Get or create a circuit breaker for a service
+ */
+ get(serviceId: string, options: CircuitBreakerOptions = {}): CircuitBreaker {
+ if (!this.breakers.has(serviceId)) {
+ this.breakers.set(serviceId, new CircuitBreaker(serviceId, options));
+ }
+ return this.breakers.get(serviceId)!;
+ }
+
+ /**
+ * Get status of all circuit breakers
+ */
+ getStatus(): Record<string, CircuitBreakerStatus> {
+ const status: Record<string, CircuitBreakerStatus> = {};
+ for (const [id, breaker] of this.breakers) {
+ status[id] = breaker.getState();
+ }
+ return status;
+ }
+
+ /**
+ * Reset all circuit breakers
+ */
+ resetAll(): void {
+ for (const breaker of this.breakers.values()) {
+ breaker.reset();
+ }
+ }
+
+ /**
+ * Get count of open circuits
+ */
+ getOpenCount(): number {
+ let count = 0;
+ for (const breaker of this.breakers.values()) {
+ if (breaker.state === CircuitBreakerStates.OPEN) count++;
+ }
+ return count;
+ }
+}
+
+// Export singleton registry
+export const circuitBreakerRegistry = new CircuitBreakerRegistry();
diff --git a/src/lib/services/client.ts b/src/lib/services/client.ts
new file mode 100644
index 0000000..a198a79
--- /dev/null
+++ b/src/lib/services/client.ts
@@ -0,0 +1,356 @@
+/**
+ * ServiceClient - Unified fetch client with caching, retries, and circuit breaker
+ */
+
+import { CacheManager } from './cache';
+import { CircuitBreakerRegistry, type CircuitBreaker } from './circuit-breaker';
+import { RequestDeduplicator } from './deduplicator';
+import { ServiceRegistry, type ServiceConfig, type ServiceId } from './registry';
+import { ServiceError, NetworkError, TimeoutError, CircuitOpenError } from './errors';
+
+export interface RequestOptions {
+ params?: Record<string, string | number | boolean>;
+ useCache?: boolean;
+ retries?: number;
+ timeout?: number;
+ accept?: string;
+ headers?: Record<string, string>;
+ fetchOptions?: RequestInit;
+ responseType?: 'json' | 'text';
+}
+
+export interface RequestResult<T = unknown> {
+ data: T;
+ fromCache: false | 'memory' | 'storage' | 'fallback' | 'stale-fallback';
+ stale?: boolean;
+ circuitOpen?: boolean;
+ attempt?: number;
+ error?: string;
+}
+
+export interface ServiceClientOptions {
+ debug?: boolean;
+}
+
+export interface HealthStatus {
+ circuitBreakers: Record<string, ReturnType<CircuitBreaker['getState']>>;
+ openCircuits: number;
+ inFlightRequests: number;
+ cacheStats: ReturnType<CacheManager['getStats']>;
+}
+
+export class ServiceClient {
+ private readonly cache: CacheManager;
+ private readonly circuitBreakers: CircuitBreakerRegistry;
+ private readonly deduplicator: RequestDeduplicator;
+ private readonly debug: boolean;
+
+ constructor(options: ServiceClientOptions = {}) {
+ this.cache = new CacheManager({ prefix: 'sm_', debug: options.debug });
+ this.circuitBreakers = new CircuitBreakerRegistry();
+ this.deduplicator = new RequestDeduplicator();
+ this.debug = options.debug || false;
+ }
+
+ /**
+ * Main request method - handles caching, circuit breaker, deduplication
+ */
+ async request<T = unknown>(
+ serviceId: ServiceId | string,
+ endpoint: string,
+ options: RequestOptions = {}
+ ): Promise<RequestResult<T>> {
+ const config = ServiceRegistry.get(serviceId);
+ if (!config) {
+ throw new ServiceError(`Unknown service: ${serviceId}`, serviceId);
+ }
+
+ const url = this.buildUrl(config, endpoint, options.params);
+ const cacheKey = this.cache.generateKey(url, options.params);
+
+ // 1. Check cache first (unless explicitly disabled)
+ if (options.useCache !== false && config.cache) {
+ const cached = this.cache.get<T>(cacheKey);
+ if (cached && !cached.isStale) {
+ return { data: cached.data, fromCache: cached.fromCache, stale: false };
+ }
+ if (cached && cached.isStale && config.cache.staleWhileRevalidate) {
+ // Return stale data immediately, revalidate in background
+ this.revalidateInBackground(serviceId, endpoint, options, cacheKey, config);
+ return { data: cached.data, fromCache: cached.fromCache, stale: true };
+ }
+ }
+
+ // 2. Check circuit breaker
+ const breaker = this.circuitBreakers.get(serviceId, config.circuitBreaker);
+ if (!breaker.canRequest()) {
+ // Circuit is open - try to return cached data
+ const cached = this.cache.get<T>(cacheKey);
+ if (cached) {
+ return { data: cached.data, fromCache: 'fallback', circuitOpen: true };
+ }
+ throw new CircuitOpenError(serviceId);
+ }
+
+ // 3. Deduplicate concurrent requests
+ return this.deduplicator.dedupe(cacheKey, () =>
+ this.executeRequest<T>(serviceId, url, options, cacheKey, breaker, config)
+ );
+ }
+
+ /**
+ * Execute the actual request with retries
+ */
+ private async executeRequest<T>(
+ serviceId: string,
+ url: string,
+ options: RequestOptions,
+ cacheKey: string,
+ breaker: CircuitBreaker,
+ config: ServiceConfig
+ ): Promise<RequestResult<T>> {
+ const retries = options.retries ?? config.retries ?? 2;
+ let lastError: Error | undefined;
+
+ for (let attempt = 0; attempt <= retries; attempt++) {
+ try {
+ if (attempt > 0) {
+ this.log(`Retry attempt ${attempt} for ${serviceId}`);
+ }
+
+ breaker.trackHalfOpenRequest();
+ const data = await this.fetchWithTimeout<T>(url, options, config);
+ breaker.recordSuccess();
+
+ // Cache successful response
+ if (config.cache) {
+ this.cache.set(cacheKey, data, config.cache.ttl, config.cache.staleWhileRevalidate);
+ }
+
+ return { data, fromCache: false, attempt };
+ } catch (error) {
+ lastError = error as Error;
+ this.log(`Request failed (attempt ${attempt + 1}/${retries + 1}): ${lastError.message}`);
+
+ // Don't retry on certain errors
+ if (
+ error instanceof CircuitOpenError ||
+ (error instanceof NetworkError &&
+ (error.status === 404 || error.status === 401 || error.status === 403))
+ ) {
+ break;
+ }
+
+ if (attempt < retries) {
+ await this.delay(this.getBackoffDelay(attempt));
+ }
+ }
+ }
+
+ breaker.recordFailure();
+
+ // Try returning stale cache on failure
+ const cached = this.cache.get<T>(cacheKey);
+ if (cached) {
+ console.warn(
+ `[ServiceClient] ${serviceId}: Returning stale cache after ${retries + 1} failed attempts`
+ );
+ return { data: cached.data, fromCache: 'stale-fallback', error: lastError?.message };
+ }
+
+ throw lastError;
+ }
+
+ /**
+ * Fetch with AbortController timeout
+ */
+ private async fetchWithTimeout<T>(
+ url: string,
+ options: RequestOptions,
+ config: ServiceConfig
+ ): Promise<T> {
+ const controller = new AbortController();
+ const timeout = options.timeout || config.timeout || 10000;
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
+
+ try {
+ const fetchOptions: RequestInit = {
+ ...options.fetchOptions,
+ signal: controller.signal,
+ headers: {
+ Accept: options.accept || 'application/json',
+ ...options.headers
+ }
+ };
+
+ const response = await fetch(url, fetchOptions);
+
+ if (!response.ok) {
+ throw new NetworkError(`HTTP ${response.status}: ${response.statusText}`, response.status);
+ }
+
+ // Handle different response types
+ const contentType = response.headers.get('content-type') || '';
+ if (
+ options.responseType === 'text' ||
+ contentType.includes('text/') ||
+ contentType.includes('xml')
+ ) {
+ return (await response.text()) as T;
+ }
+ return (await response.json()) as T;
+ } catch (error) {
+ if ((error as Error).name === 'AbortError') {
+ throw new TimeoutError(url, timeout);
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ /**
+ * Build URL from config and endpoint
+ */
+ private buildUrl(
+ config: ServiceConfig,
+ endpoint: string,
+ params: Record<string, string | number | boolean> = {}
+ ): string {
+ let baseUrl = config.baseUrl || '';
+
+ // Handle full URLs (for CORS proxy passthrough)
+ if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {
+ baseUrl = '';
+ }
+
+ const fullUrl = baseUrl + endpoint;
+ const url = new URL(fullUrl);
+
+ // Add query params
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined && value !== null) {
+ url.searchParams.set(key, String(value));
+ }
+ });
+
+ return url.toString();
+ }
+
+ /**
+ * Calculate exponential backoff delay with jitter
+ */
+ private getBackoffDelay(attempt: number): number {
+ // Base: 1s, 2s, 4s... + random 0-500ms jitter
+ const baseDelay = Math.pow(2, attempt) * 1000;
+ const jitter = Math.random() * 500;
+ return Math.min(baseDelay + jitter, 10000); // Max 10 seconds
+ }
+
+ /**
+ * Delay helper
+ */
+ private delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+ }
+
+ /**
+ * Revalidate in background (fire and forget)
+ */
+ private revalidateInBackground(
+ serviceId: ServiceId | string,
+ endpoint: string,
+ options: RequestOptions,
+ cacheKey: string,
+ config: ServiceConfig
+ ): void {
+ const breaker = this.circuitBreakers.get(serviceId, config.circuitBreaker);
+ const url = this.buildUrl(config, endpoint, options.params);
+
+ this.executeRequest(serviceId, url, { ...options, useCache: false }, cacheKey, breaker, config)
+ .then(() => this.log(`Background revalidation complete: ${serviceId}`))
+ .catch(() => this.log(`Background revalidation failed: ${serviceId}`));
+ }
+
+ /**
+ * Fetch through CORS proxy with fallback
+ */
+ async fetchWithProxy<T = string>(targetUrl: string, options: RequestOptions = {}): Promise<T> {
+ const proxies = ServiceRegistry.getCorsProxies();
+ const config = ServiceRegistry.get('CORS_PROXY');
+ if (!config) {
+ throw new ServiceError('CORS_PROXY service not configured');
+ }
+
+ let lastError: Error | undefined;
+
+ for (let i = 0; i < proxies.length; i++) {
+ const proxy = proxies[i];
+ const proxyUrl = proxy + encodeURIComponent(targetUrl);
+
+ try {
+ const response = await this.fetchWithTimeout<string>(
+ proxyUrl,
+ {
+ ...options,
+ accept: 'application/rss+xml, application/xml, text/xml, */*',
+ responseType: 'text'
+ },
+ config
+ );
+
+ // Validate response (check for error pages)
+ if (
+ response &&
+ !response.includes('<!DOCTYPE html>') &&
+ !response.includes('error code:')
+ ) {
+ return response as T;
+ }
+ } catch (e) {
+ this.log(`Proxy ${i + 1} failed: ${(e as Error).message}`);
+ lastError = e as Error;
+ }
+ }
+
+ throw lastError || new NetworkError('All CORS proxies failed');
+ }
+
+ /**
+ * Get health status of all services
+ */
+ getHealthStatus(): HealthStatus {
+ return {
+ circuitBreakers: this.circuitBreakers.getStatus(),
+ openCircuits: this.circuitBreakers.getOpenCount(),
+ inFlightRequests: this.deduplicator.getCount(),
+ cacheStats: this.cache.getStats()
+ };
+ }
+
+ /**
+ * Clear cache for a specific service pattern
+ */
+ clearServiceCache(pattern: string): void {
+ this.cache.invalidate(pattern);
+ }
+
+ /**
+ * Reset all circuit breakers
+ */
+ resetCircuitBreakers(): void {
+ this.circuitBreakers.resetAll();
+ }
+
+ /**
+ * Debug logging
+ */
+ private log(message: string): void {
+ if (this.debug) {
+ console.log(`[ServiceClient] ${message}`);
+ }
+ }
+}
+
+// Export singleton instance
+export const serviceClient = new ServiceClient({ debug: false });
diff --git a/src/lib/services/deduplicator.test.ts b/src/lib/services/deduplicator.test.ts
new file mode 100644
index 0000000..187f442
--- /dev/null
+++ b/src/lib/services/deduplicator.test.ts
@@ -0,0 +1,137 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { RequestDeduplicator } from './deduplicator';
+
+describe('RequestDeduplicator', () => {
+ let deduplicator: RequestDeduplicator;
+
+ beforeEach(() => {
+ deduplicator = new RequestDeduplicator();
+ });
+
+ describe('dedupe', () => {
+ it('should return same promise for concurrent requests', async () => {
+ let callCount = 0;
+ const requestFn = () =>
+ new Promise<string>((resolve) => {
+ callCount++;
+ setTimeout(() => resolve('result'), 100);
+ });
+
+ // Start two concurrent requests
+ const promise1 = deduplicator.dedupe('test-key', requestFn);
+ const promise2 = deduplicator.dedupe('test-key', requestFn);
+
+ // Both should be the same promise
+ expect(promise1).toBe(promise2);
+
+ // Request function should only be called once
+ expect(callCount).toBe(1);
+
+ // Both should resolve to same value
+ const [result1, result2] = await Promise.all([promise1, promise2]);
+ expect(result1).toBe('result');
+ expect(result2).toBe('result');
+ });
+
+ it('should make new request after previous completes', async () => {
+ let callCount = 0;
+ const requestFn = () =>
+ new Promise<number>((resolve) => {
+ callCount++;
+ resolve(callCount);
+ });
+
+ // First request
+ const result1 = await deduplicator.dedupe('test-key', requestFn);
+ expect(result1).toBe(1);
+
+ // Second request (first is done)
+ const result2 = await deduplicator.dedupe('test-key', requestFn);
+ expect(result2).toBe(2);
+
+ expect(callCount).toBe(2);
+ });
+
+ it('should track different keys separately', async () => {
+ let callCount = 0;
+ const requestFn = () =>
+ new Promise<number>((resolve) => {
+ callCount++;
+ resolve(callCount);
+ });
+
+ // Concurrent requests with different keys
+ const [result1, result2] = await Promise.all([
+ deduplicator.dedupe('key-1', requestFn),
+ deduplicator.dedupe('key-2', requestFn)
+ ]);
+
+ expect(callCount).toBe(2);
+ expect(result1).not.toBe(result2);
+ });
+ });
+
+ describe('isInFlight', () => {
+ it('should return true for in-flight requests', () => {
+ deduplicator.dedupe(
+ 'test-key',
+ () => new Promise((resolve) => setTimeout(resolve, 1000))
+ );
+
+ expect(deduplicator.isInFlight('test-key')).toBe(true);
+ });
+
+ it('should return false after request completes', async () => {
+ await deduplicator.dedupe('test-key', () => Promise.resolve('done'));
+
+ expect(deduplicator.isInFlight('test-key')).toBe(false);
+ });
+ });
+
+ describe('getCount', () => {
+ it('should return number of in-flight requests', () => {
+ deduplicator.dedupe(
+ 'key-1',
+ () => new Promise((resolve) => setTimeout(resolve, 1000))
+ );
+ deduplicator.dedupe(
+ 'key-2',
+ () => new Promise((resolve) => setTimeout(resolve, 1000))
+ );
+
+ expect(deduplicator.getCount()).toBe(2);
+ });
+ });
+
+ describe('clear', () => {
+ it('should clear all tracked requests', () => {
+ deduplicator.dedupe(
+ 'key-1',
+ () => new Promise((resolve) => setTimeout(resolve, 1000))
+ );
+ deduplicator.dedupe(
+ 'key-2',
+ () => new Promise((resolve) => setTimeout(resolve, 1000))
+ );
+
+ deduplicator.clear();
+
+ expect(deduplicator.getCount()).toBe(0);
+ });
+ });
+
+ describe('error handling', () => {
+ it('should clean up after rejected promise', async () => {
+ const requestFn = () => Promise.reject(new Error('test error'));
+
+ try {
+ await deduplicator.dedupe('test-key', requestFn);
+ } catch {
+ // Expected to throw
+ }
+
+ // Should be cleaned up
+ expect(deduplicator.isInFlight('test-key')).toBe(false);
+ });
+ });
+});
diff --git a/src/lib/services/deduplicator.ts b/src/lib/services/deduplicator.ts
new file mode 100644
index 0000000..a411334
--- /dev/null
+++ b/src/lib/services/deduplicator.ts
@@ -0,0 +1,71 @@
+/**
+ * RequestDeduplicator - Prevent duplicate in-flight requests
+ */
+
+export class RequestDeduplicator {
+ private inFlight: Map<string, Promise<unknown>> = new Map();
+
+ /**
+ * Get an existing in-flight request promise if one exists
+ */
+ get<T>(key: string): Promise<T> | null {
+ return (this.inFlight.get(key) as Promise<T>) || null;
+ }
+
+ /**
+ * Track a new in-flight request
+ */
+ track<T>(key: string, promise: Promise<T>): Promise<T> {
+ this.inFlight.set(key, promise);
+
+ // Clean up when promise resolves or rejects
+ promise.finally(() => this.inFlight.delete(key)).catch(() => {
+ // Prevent unhandled rejection
+ });
+
+ return promise;
+ }
+
+ /**
+ * Deduplicate: return existing promise or track new one
+ */
+ dedupe<T>(key: string, requestFn: () => Promise<T>): Promise<T> {
+ const existing = this.get<T>(key);
+ if (existing) {
+ console.log(`[Deduplicator] Reusing in-flight request: ${key.substring(0, 50)}...`);
+ return existing;
+ }
+ return this.track(key, requestFn());
+ }
+
+ /**
+ * Check if a request is currently in-flight
+ */
+ isInFlight(key: string): boolean {
+ return this.inFlight.has(key);
+ }
+
+ /**
+ * Get count of in-flight requests
+ */
+ getCount(): number {
+ return this.inFlight.size;
+ }
+
+ /**
+ * Get all in-flight keys (for debugging)
+ */
+ getInFlightKeys(): string[] {
+ return Array.from(this.inFlight.keys());
+ }
+
+ /**
+ * Clear all tracked requests (use with caution)
+ */
+ clear(): void {
+ this.inFlight.clear();
+ }
+}
+
+// Export singleton instance
+export const requestDeduplicator = new RequestDeduplicator();
diff --git a/src/lib/services/errors.ts b/src/lib/services/errors.ts
new file mode 100644
index 0000000..448f35b
--- /dev/null
+++ b/src/lib/services/errors.ts
@@ -0,0 +1,45 @@
+/**
+ * Custom error classes for service layer
+ */
+
+export class ServiceError extends Error {
+ readonly serviceId: string | null;
+
+ constructor(message: string, serviceId: string | null = null) {
+ super(message);
+ this.name = 'ServiceError';
+ this.serviceId = serviceId;
+ }
+}
+
+export class NetworkError extends Error {
+ readonly status: number | null;
+
+ constructor(message: string, status: number | null = null) {
+ super(message);
+ this.name = 'NetworkError';
+ this.status = status;
+ }
+}
+
+export class TimeoutError extends Error {
+ readonly url: string;
+ readonly timeout: number | null;
+
+ constructor(url: string, timeout: number | null = null) {
+ super(`Request timed out: ${url}`);
+ this.name = 'TimeoutError';
+ this.url = url;
+ this.timeout = timeout;
+ }
+}
+
+export class CircuitOpenError extends Error {
+ readonly serviceId: string;
+
+ constructor(serviceId: string) {
+ super(`Circuit breaker open for service: ${serviceId}`);
+ this.name = 'CircuitOpenError';
+ this.serviceId = serviceId;
+ }
+}
diff --git a/src/lib/services/index.ts b/src/lib/services/index.ts
new file mode 100644
index 0000000..e24ff17
--- /dev/null
+++ b/src/lib/services/index.ts
@@ -0,0 +1,58 @@
+/**
+ * Service layer exports
+ */
+
+// Errors
+export {
+ ServiceError,
+ NetworkError,
+ TimeoutError,
+ CircuitOpenError
+} from './errors';
+
+// Cache Manager
+export {
+ CacheManager,
+ cacheManager,
+ type CacheEntry,
+ type CacheResult,
+ type CacheManagerOptions,
+ type CacheStats
+} from './cache';
+
+// Circuit Breaker
+export {
+ CircuitBreaker,
+ CircuitBreakerRegistry,
+ CircuitBreakerStates,
+ circuitBreakerRegistry,
+ type CircuitBreakerState,
+ type CircuitBreakerOptions,
+ type CircuitBreakerStatus
+} from './circuit-breaker';
+
+// Request Deduplicator
+export {
+ RequestDeduplicator,
+ requestDeduplicator
+} from './deduplicator';
+
+// Service Registry
+export {
+ ServiceRegistry,
+ SERVICE_CONFIG,
+ type ServiceConfig,
+ type ServiceId,
+ type CacheConfig,
+ type CircuitBreakerConfig
+} from './registry';
+
+// Service Client
+export {
+ ServiceClient,
+ serviceClient,
+ type RequestOptions,
+ type RequestResult,
+ type ServiceClientOptions,
+ type HealthStatus
+} from './client';
diff --git a/src/lib/services/registry.test.ts b/src/lib/services/registry.test.ts
new file mode 100644
index 0000000..7d12522
--- /dev/null
+++ b/src/lib/services/registry.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest';
+import { ServiceRegistry } from './registry';
+
+describe('ServiceRegistry', () => {
+ describe('get', () => {
+ it('should return config for registered service', () => {
+ const config = ServiceRegistry.get('GDELT');
+
+ expect(config).not.toBeNull();
+ expect(config?.id).toBe('gdelt');
+ expect(config?.baseUrl).toBe('https://api.gdeltproject.org');
+ });
+
+ it('should return null for unknown service', () => {
+ const config = ServiceRegistry.get('UNKNOWN');
+
+ expect(config).toBeNull();
+ });
+ });
+
+ describe('getServiceIds', () => {
+ it('should return all registered service IDs', () => {
+ const ids = ServiceRegistry.getServiceIds();
+
+ expect(ids).toContain('GDELT');
+ expect(ids).toContain('COINGECKO');
+ expect(ids).toContain('FRED');
+ expect(ids).toContain('USGS');
+ expect(ids).toContain('CORS_PROXY');
+ });
+ });
+
+ describe('has', () => {
+ it('should return true for registered services', () => {
+ expect(ServiceRegistry.has('GDELT')).toBe(true);
+ expect(ServiceRegistry.has('COINGECKO')).toBe(true);
+ });
+
+ it('should return false for unknown services', () => {
+ expect(ServiceRegistry.has('UNKNOWN')).toBe(false);
+ });
+ });
+
+ describe('getCorsProxies', () => {
+ it('should return list of CORS proxies', () => {
+ const proxies = ServiceRegistry.getCorsProxies();
+
+ expect(proxies).toBeInstanceOf(Array);
+ expect(proxies.length).toBeGreaterThan(0);
+ expect(proxies[0]).toContain('situation-monitor-proxy');
+ });
+ });
+
+ describe('getAll', () => {
+ it('should return all service configurations', () => {
+ const all = ServiceRegistry.getAll();
+
+ expect(all.GDELT).toBeDefined();
+ expect(all.COINGECKO).toBeDefined();
+ });
+ });
+
+ describe('service configurations', () => {
+ it('should have valid cache config for GDELT', () => {
+ const config = ServiceRegistry.get('GDELT');
+
+ expect(config?.cache?.ttl).toBe(3 * 60 * 1000);
+ expect(config?.cache?.staleWhileRevalidate).toBe(true);
+ });
+
+ it('should have valid circuit breaker config for COINGECKO', () => {
+ const config = ServiceRegistry.get('COINGECKO');
+
+ expect(config?.circuitBreaker?.failureThreshold).toBe(3);
+ expect(config?.circuitBreaker?.resetTimeout).toBe(120000);
+ });
+
+ it('should have longer TTL for FRED (weekly data)', () => {
+ const config = ServiceRegistry.get('FRED');
+
+ expect(config?.cache?.ttl).toBe(60 * 60 * 1000); // 1 hour
+ });
+ });
+});
diff --git a/src/lib/services/registry.ts b/src/lib/services/registry.ts
new file mode 100644
index 0000000..8e0f35c
--- /dev/null
+++ b/src/lib/services/registry.ts
@@ -0,0 +1,145 @@
+/**
+ * ServiceRegistry - Service configurations for all external APIs
+ */
+
+export interface CacheConfig {
+ ttl: number;
+ staleWhileRevalidate: boolean;
+}
+
+export interface CircuitBreakerConfig {
+ failureThreshold: number;
+ resetTimeout: number;
+}
+
+export interface ServiceConfig {
+ id: string;
+ baseUrl: string | null;
+ timeout: number;
+ retries: number;
+ cache?: CacheConfig;
+ circuitBreaker?: CircuitBreakerConfig;
+ proxies?: string[];
+}
+
+export type ServiceId = 'GDELT' | 'COINGECKO' | 'FRED' | 'USGS' | 'CORS_PROXY';
+
+const SERVICE_CONFIG: Record<ServiceId, ServiceConfig> = {
+ GDELT: {
+ id: 'gdelt',
+ baseUrl: 'https://api.gdeltproject.org',
+ timeout: 15000,
+ retries: 1,
+ cache: {
+ ttl: 3 * 60 * 1000, // 3 minutes (real-time news)
+ staleWhileRevalidate: true
+ },
+ circuitBreaker: {
+ failureThreshold: 2,
+ resetTimeout: 60000 // 1 minute
+ }
+ },
+
+ COINGECKO: {
+ id: 'coingecko',
+ baseUrl: 'https://api.coingecko.com',
+ timeout: 10000,
+ retries: 2,
+ cache: {
+ ttl: 60 * 1000, // 1 minute (crypto volatility)
+ staleWhileRevalidate: false
+ },
+ circuitBreaker: {
+ failureThreshold: 3,
+ resetTimeout: 120000 // 2 minutes (API can be flaky)
+ }
+ },
+
+ FRED: {
+ id: 'fred',
+ baseUrl: 'https://fred.stlouisfed.org',
+ timeout: 10000,
+ retries: 2,
+ cache: {
+ ttl: 60 * 60 * 1000, // 1 hour (weekly data)
+ staleWhileRevalidate: true
+ },
+ circuitBreaker: {
+ failureThreshold: 3,
+ resetTimeout: 60000
+ }
+ },
+
+ USGS: {
+ id: 'usgs',
+ baseUrl: 'https://earthquake.usgs.gov',
+ timeout: 10000,
+ retries: 2,
+ cache: {
+ ttl: 5 * 60 * 1000, // 5 minutes
+ staleWhileRevalidate: true
+ },
+ circuitBreaker: {
+ failureThreshold: 3,
+ resetTimeout: 60000
+ }
+ },
+
+ CORS_PROXY: {
+ id: 'cors_proxy',
+ baseUrl: null, // Uses proxy URLs from list
+ proxies: [
+ 'https://situation-monitor-proxy.seanthielen-e.workers.dev/?url=',
+ 'https://api.allorigins.win/raw?url='
+ ],
+ timeout: 12000,
+ retries: 1, // Already has proxy fallback
+ cache: {
+ ttl: 5 * 60 * 1000,
+ staleWhileRevalidate: true
+ },
+ circuitBreaker: {
+ failureThreshold: 5,
+ resetTimeout: 120000
+ }
+ }
+};
+
+export class ServiceRegistry {
+ /**
+ * Get configuration for a service
+ */
+ static get(serviceId: ServiceId | string): ServiceConfig | null {
+ return SERVICE_CONFIG[serviceId as ServiceId] || null;
+ }
+
+ /**
+ * Get all service IDs
+ */
+ static getServiceIds(): ServiceId[] {
+ return Object.keys(SERVICE_CONFIG) as ServiceId[];
+ }
+
+ /**
+ * Get all service configurations
+ */
+ static getAll(): Record<ServiceId, ServiceConfig> {
+ return { ...SERVICE_CONFIG };
+ }
+
+ /**
+ * Check if a service is registered
+ */
+ static has(serviceId: string): serviceId is ServiceId {
+ return Object.hasOwn(SERVICE_CONFIG, serviceId);
+ }
+
+ /**
+ * Get CORS proxies list
+ */
+ static getCorsProxies(): string[] {
+ return SERVICE_CONFIG.CORS_PROXY.proxies || [];
+ }
+}
+
+export { SERVICE_CONFIG };