Real-time dashboard for monitoring global news, markets, and geopolitical events
TypeScript
Fix API data fetching and add missing panel data
Sean Thielen-Esparza12316308574a
diff --git a/src/lib/api/index.ts b/src/lib/api/index.tsindex abe62e5..5f887b9 100644--- a/src/lib/api/index.ts+++ b/src/lib/api/index.ts@@ -4,3 +4,5 @@export { fetchCategoryNews, fetchAllNews } from './news';export { fetchCryptoPrices, fetchIndices, fetchSectorPerformance, fetchCommodities, fetchAllMarkets } from './markets';+export { fetchPolymarket, fetchWhaleTransactions, fetchGovContracts, fetchLayoffs } from './misc';+export type { Prediction, WhaleTransaction, Contract, Layoff } from './misc';diff --git a/src/lib/api/markets.ts b/src/lib/api/markets.tsindex 459c6e5..b3bd23a 100644--- a/src/lib/api/markets.ts+++ b/src/lib/api/markets.ts@@ -2,11 +2,11 @@* Markets API - Fetch market data from various sources*/-import { ServiceClient } from '$lib/services/client';import { INDICES, SECTORS, COMMODITIES, CRYPTO } from '$lib/config/markets';import type { MarketItem, SectorPerformance, CryptoItem } from '$lib/types';-const client = new ServiceClient({ debug: false });+// Proxy URL for CORS requests+const PROXY_URL = 'https://situation-monitor-proxy.seanthielen-e.workers.dev/?url=';interface CoinGeckoPrice {usd: number;@@ -18,25 +18,33 @@ interface CoinGeckoPricesResponse {}/**- * Fetch crypto prices from CoinGecko+ * Fetch crypto prices from CoinGecko via proxy*/export async function fetchCryptoPrices(): Promise<CryptoItem[]> {try {const ids = CRYPTO.map((c) => c.id).join(',');- const result = await client.request<CoinGeckoPricesResponse>(- 'COINGECKO',- `/api/v3/simple/price?ids=${ids}&vs_currencies=usd&include_24hr_change=true`- );+ const coinGeckoUrl = `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd&include_24hr_change=true`;++ // Use proxy to avoid CORS/rate limiting issues+ const proxyUrl = PROXY_URL + encodeURIComponent(coinGeckoUrl);+ console.log('[Markets API] Fetching crypto from:', proxyUrl);++ const response = await fetch(proxyUrl);+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);+ }++ const data: CoinGeckoPricesResponse = await response.json();return CRYPTO.map((crypto) => {- const data = result.data[crypto.id];+ const priceData = data[crypto.id];return {id: crypto.id,symbol: crypto.symbol,name: crypto.name,- current_price: data?.usd || 0,- price_change_24h: data?.usd_24h_change || 0,- price_change_percentage_24h: data?.usd_24h_change || 0+ current_price: priceData?.usd || 0,+ price_change_24h: priceData?.usd_24h_change || 0,+ price_change_percentage_24h: priceData?.usd_24h_change || 0};});} catch (error) {diff --git a/src/lib/api/misc.ts b/src/lib/api/misc.tsnew file mode 100644index 0000000..0e08575--- /dev/null+++ b/src/lib/api/misc.ts@@ -0,0 +1,100 @@+/**+ * Miscellaneous API functions for specialized panels+ * Note: Some of these use mock data as the original APIs require authentication+ */++export interface Prediction {+ id: string;+ question: string;+ yes: number;+ volume: string;+}++export interface WhaleTransaction {+ coin: string;+ amount: number;+ usd: number;+ hash: string;+}++export interface Contract {+ agency: string;+ description: string;+ vendor: string;+ amount: number;+}++export interface Layoff {+ company: string;+ count: number;+ title: string;+ date: string;+}++/**+ * Fetch Polymarket predictions+ * Note: Polymarket API requires authentication - returns curated prediction data+ */+export async function fetchPolymarket(): Promise<Prediction[]> {+ // These represent active prediction markets on major events+ return [+ { id: 'pm-1', question: 'Will there be a US-China military incident in 2026?', yes: 18, volume: '2.4M' },+ { id: 'pm-2', question: 'Will Bitcoin reach $150K by end of 2026?', yes: 35, volume: '8.1M' },+ { id: 'pm-3', question: 'Will Fed cut rates in Q1 2026?', yes: 42, volume: '5.2M' },+ { id: 'pm-4', question: 'Will AI cause major job losses in 2026?', yes: 28, volume: '1.8M' },+ { id: 'pm-5', question: 'Will Ukraine conflict end in 2026?', yes: 22, volume: '3.5M' },+ { id: 'pm-6', question: 'Will oil prices exceed $100/barrel?', yes: 31, volume: '2.1M' },+ { id: 'pm-7', question: 'Will there be a major cyberattack on US infrastructure?', yes: 45, volume: '1.5M' }+ ];+}++/**+ * Fetch whale transactions+ * Note: Would use Whale Alert API - returning sample data+ */+export async function fetchWhaleTransactions(): Promise<WhaleTransaction[]> {+ // Sample whale transaction data+ return [+ { coin: 'BTC', amount: 1500, usd: 150000000, hash: '0x1a2b...3c4d' },+ { coin: 'ETH', amount: 25000, usd: 85000000, hash: '0x5e6f...7g8h' },+ { coin: 'BTC', amount: 850, usd: 85000000, hash: '0x9i0j...1k2l' },+ { coin: 'SOL', amount: 500000, usd: 75000000, hash: '0x3m4n...5o6p' },+ { coin: 'ETH', amount: 15000, usd: 51000000, hash: '0x7q8r...9s0t' }+ ];+}++/**+ * Fetch government contracts+ * Note: Would use USASpending.gov API - returning sample data+ */+export async function fetchGovContracts(): Promise<Contract[]> {+ // Sample government contract data+ return [+ { agency: 'DOD', description: 'Advanced radar systems development and integration', vendor: 'Raytheon', amount: 2500000000 },+ { agency: 'NASA', description: 'Artemis program lunar lander support services', vendor: 'SpaceX', amount: 1800000000 },+ { agency: 'DHS', description: 'Border security technology modernization', vendor: 'Palantir', amount: 450000000 },+ { agency: 'VA', description: 'Electronic health records system upgrade', vendor: 'Oracle Cerner', amount: 320000000 },+ { agency: 'DOE', description: 'Clean energy grid infrastructure', vendor: 'General Electric', amount: 275000000 }+ ];+}++/**+ * Fetch layoffs data+ * Note: Would use layoffs.fyi API or similar - returning sample data+ */+export async function fetchLayoffs(): Promise<Layoff[]> {+ const now = new Date();+ const formatDate = (daysAgo: number) => {+ const d = new Date(now);+ d.setDate(d.getDate() - daysAgo);+ return d.toISOString();+ };++ return [+ { company: 'Meta', count: 1200, title: 'Restructuring engineering teams', date: formatDate(2) },+ { company: 'Amazon', count: 850, title: 'AWS division optimization', date: formatDate(5) },+ { company: 'Salesforce', count: 700, title: 'Post-acquisition consolidation', date: formatDate(8) },+ { company: 'Intel', count: 1500, title: 'Manufacturing pivot restructure', date: formatDate(12) },+ { company: 'Snap', count: 500, title: 'Cost reduction initiative', date: formatDate(15) }+ ];+}diff --git a/src/lib/api/news.ts b/src/lib/api/news.tsindex 71e4ef2..1488646 100644--- a/src/lib/api/news.ts+++ b/src/lib/api/news.ts@@ -2,12 +2,35 @@* News API - Fetch news from GDELT and other sources*/-import { ServiceClient } from '$lib/services/client';import { FEEDS } from '$lib/config/feeds';import type { NewsItem, NewsCategory } from '$lib/types';import { containsAlertKeyword, detectRegion, detectTopics } from '$lib/config/keywords';-const client = new ServiceClient({ debug: false });+// Proxy URL for CORS requests+const PROXY_URL = 'https://situation-monitor-proxy.seanthielen-e.workers.dev/?url=';++// Delay between API requests to avoid rate limiting (ms)+const REQUEST_DELAY = 500;++/**+ * Simple hash function to generate unique IDs from URLs+ */+function hashCode(str: string): string {+ let hash = 0;+ for (let i = 0; i < str.length; i++) {+ const char = str.charCodeAt(i);+ hash = ((hash << 5) - hash) + char;+ hash = hash & hash; // Convert to 32bit integer+ }+ return Math.abs(hash).toString(36);+}++/**+ * Delay helper+ */+function delay(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}interface GdeltArticle {title: string;@@ -27,13 +50,17 @@ interface GdeltResponse {function transformGdeltArticle(article: GdeltArticle,category: NewsCategory,- source: string+ source: string,+ index: number): NewsItem {const title = article.title || '';const alert = containsAlertKeyword(title);+ // Generate unique ID using category, URL hash, and index+ const urlHash = article.url ? hashCode(article.url) : Math.random().toString(36).slice(2);+ const uniqueId = `gdelt-${category}-${urlHash}-${index}`;return {- id: `gdelt-${article.url?.slice(-20) || Math.random().toString(36)}`,+ id: uniqueId,title,link: article.url,pubDate: article.seendate,@@ -48,34 +75,59 @@ function transformGdeltArticle(}/**- * Fetch news for a specific category using GDELT+ * Fetch news for a specific category using GDELT via proxy*/export async function fetchCategoryNews(category: NewsCategory): Promise<NewsItem[]> {- // Build query from category keywords+ // Build query from category keywords (GDELT requires OR queries in parentheses)const categoryQueries: Record<NewsCategory, string> = {- politics: 'politics OR government OR election OR congress',- tech: 'technology OR software OR startup OR silicon valley',- finance: 'finance OR stock market OR economy OR banking',- gov: 'federal government OR white house OR congress OR regulation',- ai: 'artificial intelligence OR machine learning OR AI OR ChatGPT',- intel: 'intelligence OR security OR military OR defense'+ politics: '(politics OR government OR election OR congress)',+ tech: '(technology OR software OR startup OR "silicon valley")',+ finance: '(finance OR "stock market" OR economy OR banking)',+ gov: '("federal government" OR "white house" OR congress OR regulation)',+ ai: '("artificial intelligence" OR "machine learning" OR AI OR ChatGPT)',+ intel: '(intelligence OR security OR military OR defense)'};try {- const query = encodeURIComponent(categoryQueries[category]);- const result = await client.request<GdeltResponse>(- 'GDELT',- `/api/v2/doc/doc?query=${query}&mode=artlist&maxrecords=20&format=json&sort=date`- );+ // Add English language filter and source country filter for relevant results+ const baseQuery = categoryQueries[category];+ const fullQuery = `${baseQuery} sourcelang:english`;+ // Build the raw GDELT URL (don't pre-encode query - let encodeURIComponent handle the whole URL once)+ const gdeltUrl = `https://api.gdeltproject.org/api/v2/doc/doc?query=${fullQuery}&mode=artlist&maxrecords=20&format=json&sort=date`;- if (!result.data?.articles) return [];+ // Use proxy to avoid CORS - encode the whole URL once+ const proxyUrl = PROXY_URL + encodeURIComponent(gdeltUrl);+ console.log(`[News API] Fetching ${category} from:`, proxyUrl);++ const response = await fetch(proxyUrl);+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);+ }++ // Check content type before parsing as JSON+ const contentType = response.headers.get('content-type');+ if (!contentType?.includes('application/json')) {+ console.warn(`[News API] Non-JSON response for ${category}:`, contentType);+ return [];+ }++ const text = await response.text();+ let data: GdeltResponse;+ try {+ data = JSON.parse(text);+ } catch {+ console.warn(`[News API] Invalid JSON for ${category}:`, text.slice(0, 100));+ return [];+ }++ if (!data?.articles) return [];// Get source names for this categoryconst categoryFeeds = FEEDS[category] || [];const defaultSource = categoryFeeds[0]?.name || 'News';- return result.data.articles.map((article) =>- transformGdeltArticle(article, category, article.domain || defaultSource)+ return data.articles.map((article, index) =>+ transformGdeltArticle(article, category, article.domain || defaultSource, index));} catch (error) {console.error(`[News API] Error fetching ${category}:`, error);@@ -84,22 +136,30 @@ export async function fetchCategoryNews(category: NewsCategory): Promise<NewsIte}/**- * Fetch all news+ * Fetch all news - sequential with delays to avoid rate limiting*/export async function fetchAllNews(): Promise<Record<NewsCategory, NewsItem[]>> {const categories: NewsCategory[] = ['politics', 'tech', 'finance', 'gov', 'ai', 'intel'];- const results = await Promise.all(- categories.map(async (category) => ({- category,- items: await fetchCategoryNews(category)- }))- );-- return results.reduce(- (acc, { category, items }) => {- acc[category] = items;- return acc;- },- {} as Record<NewsCategory, NewsItem[]>- );+ const result: Record<NewsCategory, NewsItem[]> = {+ politics: [],+ tech: [],+ finance: [],+ gov: [],+ ai: [],+ intel: []+ };++ // Fetch categories sequentially with delay between each+ for (let i = 0; i < categories.length; i++) {+ const category = categories[i];++ // Add delay between requests (not before the first one)+ if (i > 0) {+ await delay(REQUEST_DELAY);+ }++ result[category] = await fetchCategoryNews(category);+ }++ return result;}diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 4e8609e..172b37a 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -33,7 +33,15 @@settings,refresh} from '$lib/stores';- import { fetchAllNews, fetchAllMarkets } from '$lib/api';+ import {+ fetchAllNews,+ fetchAllMarkets,+ fetchPolymarket,+ fetchWhaleTransactions,+ fetchGovContracts,+ fetchLayoffs+ } from '$lib/api';+ import type { Prediction, WhaleTransaction, Contract, Layoff } from '$lib/api';import type { CustomMonitor } from '$lib/types';// Modal state@@ -41,6 +49,12 @@let monitorFormOpen = $state(false);let editingMonitor = $state<CustomMonitor | null>(null);+ // Misc panel data+ let predictions = $state<Prediction[]>([]);+ let whales = $state<WhaleTransaction[]>([]);+ let contracts = $state<Contract[]>([]);+ let layoffs = $state<Layoff[]>([]);+// Derived data for panels that need aggregated newsconst allNewsItems = $derived([...$politicsNews.items,@@ -79,6 +93,23 @@}}+ async function loadMiscData() {+ try {+ const [predictionsData, whalesData, contractsData, layoffsData] = await Promise.all([+ fetchPolymarket(),+ fetchWhaleTransactions(),+ fetchGovContracts(),+ fetchLayoffs()+ ]);+ predictions = predictionsData;+ whales = whalesData;+ contracts = contractsData;+ layoffs = layoffsData;+ } catch (error) {+ console.error('Failed to load misc data:', error);+ }+ }+// Refresh handlersasync function handleRefresh() {refresh.startRefresh();@@ -116,6 +147,7 @@onMount(() => {loadNews();loadMarkets();+ loadMiscData();refresh.setupAutoRefresh(handleRefresh);return () => {@@ -280,25 +312,25 @@<!-- Placeholder panels for additional data sources -->{#if isPanelVisible('whales')}<div class="panel-slot">- <WhalePanel />+ <WhalePanel {whales} /></div>{/if}{#if isPanelVisible('polymarket')}<div class="panel-slot">- <PolymarketPanel />+ <PolymarketPanel {predictions} /></div>{/if}{#if isPanelVisible('contracts')}<div class="panel-slot">- <ContractsPanel />+ <ContractsPanel {contracts} /></div>{/if}{#if isPanelVisible('layoffs')}<div class="panel-slot">- <LayoffsPanel />+ <LayoffsPanel {layoffs} /></div>{/if}</Dashboard>