Skip to content

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

TypeScript

Simplify and refactor code for clarity

Sean Thielen-Esparza066eba7978e6
diff --git a/js/data.js b/js/data.js
index 8526909..60b9f0b 100644
--- a/js/data.js
+++ b/js/data.js
@@ -48,7 +48,7 @@ export function hasAlertKeyword(title) {
export async function fetchFeed(source) {
// Try Worker RSS-to-JSON first
const jsonResult = await fetchFeedViaJson(source);
- if (jsonResult !== null && jsonResult.length > 0) {
+ if (jsonResult?.length > 0) {
return jsonResult;
}
@@ -228,7 +228,7 @@ export async function fetchMarkets() {
};
const stockResults = await Promise.all(symbols.map(fetchStock));
- stockResults.forEach(r => { if (r) markets.push(r); });
+ markets.push(...stockResults.filter(Boolean));
// Crypto - now uses ServiceClient with caching and circuit breaker
try {
@@ -330,30 +330,29 @@ export async function fetchGovContracts() {
// Fetch AI news from major AI companies - using Cloudflare Worker
export async function fetchAINews() {
- const results = await Promise.all(AI_FEEDS.map(async (source) => {
- // Use Cloudflare Worker with RSS-to-JSON parsing
- try {
- const proxyUrl = `${WORKER_URL}/?url=${encodeURIComponent(source.url)}&format=json`;
- const response = await fetch(proxyUrl);
-
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
-
- const data = await response.json();
- if (data.status === 'ok' && data.items) {
- return data.items.slice(0, 3).map(item => ({
- source: source.name,
- title: (item.title || 'No title').trim(),
- link: item.link || '',
- date: item.pubDate || ''
- }));
- }
- } catch (e) {
- console.log(`Failed to fetch ${source.name}`);
- return [];
- }
- }));
+ const fetchAIFeed = async (source) => {
+ const proxyUrl = `${WORKER_URL}/?url=${encodeURIComponent(source.url)}&format=json`;
+ const response = await fetch(proxyUrl);
+
+ if (!response.ok) return [];
+
+ const data = await response.json();
+ if (data.status !== 'ok' || !data.items) return [];
- return results.flat().sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 15);
+ return data.items.slice(0, 3).map(item => ({
+ source: source.name,
+ title: (item.title || 'No title').trim(),
+ link: item.link || '',
+ date: item.pubDate || ''
+ }));
+ };
+
+ const results = await Promise.allSettled(AI_FEEDS.map(fetchAIFeed));
+ const items = results
+ .filter(r => r.status === 'fulfilled')
+ .flatMap(r => r.value);
+
+ return items.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 15);
}
// Fetch Fed balance sheet from FRED - routed through CORS proxy
@@ -479,30 +478,22 @@ export async function fetchGDELTNews() {
'(military OR defense OR security)'
];
- try {
- const results = await Promise.allSettled(
- queries.map(query => fetchGDELTQuery(query, 10))
- );
-
- const items = [];
- results.forEach(result => {
- if (result.status === 'fulfilled' && result.value) {
- items.push(...result.value);
- }
- });
-
- // Remove duplicates
- const seen = new Set();
- return items.filter(item => {
- const key = item.title.toLowerCase().substring(0, 50);
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- }).slice(0, 50);
- } catch (error) {
- console.error('Error fetching GDELT news:', error);
- return [];
- }
+ const results = await Promise.allSettled(
+ queries.map(query => fetchGDELTQuery(query, 10))
+ );
+
+ const items = results
+ .filter(r => r.status === 'fulfilled' && r.value)
+ .flatMap(r => r.value);
+
+ // Remove duplicates by title prefix
+ const seen = new Set();
+ return items.filter(item => {
+ const key = item.title.toLowerCase().substring(0, 50);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ }).slice(0, 50);
}
// Fetch situation-specific news using GDELT - now with ServiceClient
@@ -517,9 +508,7 @@ export async function fetchSituationNews(keywords, limit = 10) {
// Fetch Intel feed using GDELT API - now with ServiceClient
export async function fetchIntelFeed() {
- const items = [];
-
- // GDELT queries for intelligence-related news (parentheses only around OR terms)
+ // GDELT queries for intelligence-related news
const queries = [
{ query: '(military OR defense OR pentagon)', topics: ['DEFENSE'], regions: ['US'] },
{ query: '(intelligence OR espionage OR CIA)', topics: ['INTEL'], regions: ['US'] },
@@ -530,65 +519,49 @@ export async function fetchIntelFeed() {
{ query: '"north korea" (missile OR nuclear)', topics: ['NUCLEAR'], regions: ['APAC'] }
];
- try {
- // Fetch from multiple GDELT queries in parallel
- const results = await Promise.allSettled(
- queries.map(async ({ query, topics, regions }) => {
- try {
- const result = await serviceClient.request('GDELT', '/api/v2/doc/doc', {
- params: {
- query: query,
- mode: 'artlist',
- maxrecords: 5,
- format: 'json',
- sort: 'date'
- }
- });
-
- return (result.data.articles || []).map(article => ({
- source: article.domain || 'Unknown',
- sourceType: article.domain?.includes('.gov') ? 'govt' :
- article.domain?.includes('bellingcat') ? 'osint' : 'news',
- title: article.title || '',
- link: article.url || '',
- pubDate: article.seendate || '',
- isAlert: ALERT_KEYWORDS.some(kw => (article.title || '').toLowerCase().includes(kw)),
- regions: regions,
- topics: topics
- }));
- } catch (e) {
- return [];
- }
- })
- );
-
- results.forEach(result => {
- if (result.status === 'fulfilled' && result.value) {
- items.push(...result.value);
- }
+ const fetchIntelQuery = async ({ query, topics, regions }) => {
+ const result = await serviceClient.request('GDELT', '/api/v2/doc/doc', {
+ params: { query, mode: 'artlist', maxrecords: 5, format: 'json', sort: 'date' }
});
- // Remove duplicates by title
- const seen = new Set();
- const unique = items.filter(item => {
- const key = item.title.toLowerCase().substring(0, 50);
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
+ return (result.data.articles || []).map(article => {
+ const domain = article.domain || '';
+ const sourceType = domain.includes('.gov') ? 'govt' :
+ domain.includes('bellingcat') ? 'osint' : 'news';
+ return {
+ source: domain || 'Unknown',
+ sourceType,
+ title: article.title || '',
+ link: article.url || '',
+ pubDate: article.seendate || '',
+ isAlert: ALERT_KEYWORDS.some(kw => (article.title || '').toLowerCase().includes(kw)),
+ regions,
+ topics
+ };
});
+ };
- // Sort by date and alert status
- unique.sort((a, b) => {
- if (a.isAlert && !b.isAlert) return -1;
- if (!a.isAlert && b.isAlert) return 1;
- return new Date(b.pubDate) - new Date(a.pubDate);
- });
+ const results = await Promise.allSettled(queries.map(fetchIntelQuery));
+ const items = results
+ .filter(r => r.status === 'fulfilled')
+ .flatMap(r => r.value);
+
+ // Remove duplicates by title prefix
+ const seen = new Set();
+ const unique = items.filter(item => {
+ const key = item.title.toLowerCase().substring(0, 50);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
- return unique.slice(0, 30);
- } catch (error) {
- console.error('Error fetching intel feed:', error);
- return [];
- }
+ // Sort by alert status then date
+ unique.sort((a, b) => {
+ if (a.isAlert !== b.isAlert) return a.isAlert ? -1 : 1;
+ return new Date(b.pubDate) - new Date(a.pubDate);
+ });
+
+ return unique.slice(0, 30);
}
// Export serviceClient health status for debugging
diff --git a/js/renderers.js b/js/renderers.js
index 09791fe..2f1f42d 100644
--- a/js/renderers.js
+++ b/js/renderers.js
@@ -69,25 +69,23 @@ export function renderHeatmap(sectors) {
return;
}
- panel.innerHTML = '<div class="heatmap">' + sectors.map(s => {
- let colorClass = 'up-0';
- const c = s.change;
- if (c >= 2) colorClass = 'up-3';
- else if (c >= 1) colorClass = 'up-2';
- else if (c >= 0.5) colorClass = 'up-1';
- else if (c >= 0) colorClass = 'up-0';
- else if (c >= -0.5) colorClass = 'down-0';
- else if (c >= -1) colorClass = 'down-1';
- else if (c >= -2) colorClass = 'down-2';
- else colorClass = 'down-3';
+ const getColorClass = (change) => {
+ if (change >= 2) return 'up-3';
+ if (change >= 1) return 'up-2';
+ if (change >= 0.5) return 'up-1';
+ if (change >= 0) return 'up-0';
+ if (change >= -0.5) return 'down-0';
+ if (change >= -1) return 'down-1';
+ if (change >= -2) return 'down-2';
+ return 'down-3';
+ };
- return `
- <div class="heatmap-cell ${colorClass}">
- <div class="sector-name">${s.name}</div>
- <div class="sector-change">${s.change >= 0 ? '+' : ''}${s.change.toFixed(2)}%</div>
- </div>
- `;
- }).join('') + '</div>';
+ panel.innerHTML = '<div class="heatmap">' + sectors.map(s => `
+ <div class="heatmap-cell ${getColorClass(s.change)}">
+ <div class="sector-name">${s.name}</div>
+ <div class="sector-change">${s.change >= 0 ? '+' : ''}${s.change.toFixed(2)}%</div>
+ </div>
+ `).join('') + '</div>';
}
// Render commodities
@@ -131,12 +129,11 @@ export function renderPolymarket(markets) {
}
const formatVolume = (v) => {
- // Handle pre-formatted strings (e.g., '2.4M')
if (typeof v === 'string') return '$' + v;
- // Handle numeric values
- if (v >= 1000000) return '$' + (v / 1000000).toFixed(1) + 'M';
- if (v >= 1000) return '$' + (v / 1000).toFixed(0) + 'K';
- return '$' + (v || 0).toFixed(0);
+ if (!v) return '$0';
+ if (v >= 1e6) return '$' + (v / 1e6).toFixed(1) + 'M';
+ if (v >= 1e3) return '$' + (v / 1e3).toFixed(0) + 'K';
+ return '$' + v.toFixed(0);
};
panel.innerHTML = markets.map(m => `
@@ -360,30 +357,22 @@ export function renderIntelFeed(items) {
count.textContent = items.length;
- panel.innerHTML = items.map(item => {
- let tagsHTML = '';
-
- if (item.sourceType === 'osint') {
- tagsHTML += '<span class="intel-tag osint">OSINT</span>';
- } else if (item.sourceType === 'govt') {
- tagsHTML += '<span class="intel-tag govt">GOVT</span>';
- }
-
- item.regions.slice(0, 2).forEach(r => {
- tagsHTML += `<span class="intel-tag region">${r}</span>`;
- });
-
- item.topics.slice(0, 2).forEach(t => {
- tagsHTML += `<span class="intel-tag topic">${t}</span>`;
- });
+ const buildTags = (item) => {
+ const tags = [];
+ if (item.sourceType === 'osint') tags.push('<span class="intel-tag osint">OSINT</span>');
+ else if (item.sourceType === 'govt') tags.push('<span class="intel-tag govt">GOVT</span>');
+ tags.push(...item.regions.slice(0, 2).map(r => `<span class="intel-tag region">${r}</span>`));
+ tags.push(...item.topics.slice(0, 2).map(t => `<span class="intel-tag topic">${t}</span>`));
+ return tags.join('');
+ };
+ panel.innerHTML = items.map(item => {
const timeAgoStr = item.pubDate ? getRelativeTime(new Date(item.pubDate)) : '';
-
return `
<div class="intel-item ${item.isPriority ? 'priority' : ''}">
<div class="intel-header">
<span class="intel-source">${item.source}</span>
- <div class="intel-tags">${tagsHTML}</div>
+ <div class="intel-tags">${buildTags(item)}</div>
</div>
<a href="${item.link}" target="_blank" class="intel-title">${item.title}</a>
<div class="intel-meta">
diff --git a/js/services/ServiceRegistry.js b/js/services/ServiceRegistry.js
index 1be7c64..45bd9ba 100644
--- a/js/services/ServiceRegistry.js
+++ b/js/services/ServiceRegistry.js
@@ -122,7 +122,7 @@ export class ServiceRegistry {
* Check if a service is registered
*/
static has(serviceId) {
- return serviceId in SERVICE_CONFIG;
+ return Object.hasOwn(SERVICE_CONFIG, serviceId);
}
/**
diff --git a/workers/proxy/index.js b/workers/proxy/index.js
index 70e5b0b..18b4559 100644
--- a/workers/proxy/index.js
+++ b/workers/proxy/index.js
@@ -153,10 +153,7 @@ function extractTag(xml, tagName) {
function extractAtomLink(entry) {
// Look for link with rel="alternate" or no rel (default)
const linkMatch = entry.match(/<link[^>]*href=["']([^"']+)["'][^>]*>/i);
- if (linkMatch) {
- return linkMatch[1];
- }
- return extractTag(entry, 'link');
+ return linkMatch ? linkMatch[1] : extractTag(entry, 'link');
}
// Decode common HTML entities
@@ -179,10 +176,7 @@ function isRssFeed(contentType, body) {
return true;
}
// Check body for RSS/Atom markers
- if (body && (body.includes('<rss') || body.includes('<feed') || body.includes('<channel'))) {
- return true;
- }
- return false;
+ return body && (body.includes('<rss') || body.includes('<feed') || body.includes('<channel'));
}
// Add CORS headers to response
@@ -210,7 +204,7 @@ function isAllowedOrigin(targetUrl) {
}
export default {
- async fetch(request, env, ctx) {
+ async fetch(request, _env, ctx) {
const url = new URL(request.url);
const origin = request.headers.get('Origin') || '*';