UNPKG

somali-exchange-rates

Version:

πŸ‡ΈπŸ‡΄ Comprehensive Somali Exchange Rates platform with real-time rates, transfer fees, alerts, multi-language support, and advanced financial tools

1,505 lines (1,491 loc) β€’ 43 kB
import { ExchangerateHostProvider, analyzeMarket, getRateHistory, nice, tryReadJSON, tryWriteJSON } from "./chunk-GBQMRN7V.mjs"; // src/index.ts import os3 from "os"; import path3 from "path"; // src/data/seed.json var seed_default = { USD: 175e-5, EUR: 16e-4, GBP: 135e-5, KES: 0.225, ETB: 0.102, AED: 64e-4, SAR: 66e-4, TRY: 0.056, CNY: 0.012 }; // src/cache.ts var memoryCache = null; function getMemoryCache() { return memoryCache; } function setMemoryCache(c) { memoryCache = c; } // src/alerts.ts import * as cron from "node-cron"; import * as nodemailer from "nodemailer"; import path from "path"; import os from "os"; var AlertManager = class { alertsPath; webhookConfigs = []; emailTransporter; monitoringTask; constructor() { this.alertsPath = path.join(os.homedir(), ".sosx", "alerts.json"); } async createAlert(alert) { const newAlert = { ...alert, id: this.generateId(), createdAt: /* @__PURE__ */ new Date(), active: true }; const alerts = await this.getAlerts(); alerts.push(newAlert); await this.saveAlerts(alerts); console.log(`Created alert: ${newAlert.from}/${newAlert.to} ${newAlert.direction} ${newAlert.threshold}`); this.startMonitoring(); return newAlert.id; } async updateAlert(id, updates) { const alerts = await this.getAlerts(); const index = alerts.findIndex((alert) => alert.id === id); if (index === -1) { throw new Error(`Alert with id ${id} not found`); } alerts[index] = { ...alerts[index], ...updates }; await this.saveAlerts(alerts); } async deleteAlert(id) { const alerts = await this.getAlerts(); const filtered = alerts.filter((alert) => alert.id !== id); if (filtered.length === alerts.length) { throw new Error(`Alert with id ${id} not found`); } await this.saveAlerts(filtered); console.log(`Deleted alert ${id}`); } async getAlerts() { const alerts = await tryReadJSON(this.alertsPath); return alerts || []; } async checkAlerts() { const alerts = await this.getAlerts(); const activeAlerts = alerts.filter((alert) => alert.active); if (activeAlerts.length === 0) return; try { const rates = await getRates(); for (const alert of activeAlerts) { const currentRate = rates[alert.to] / rates[alert.from]; const shouldTrigger = this.shouldTriggerAlert(alert, currentRate); if (shouldTrigger) { await this.triggerAlert(alert, currentRate); } } } catch (error) { console.error("Error checking alerts:", error); } } shouldTriggerAlert(alert, currentRate) { if (alert.direction === "above") { return currentRate > alert.threshold; } else { return currentRate < alert.threshold; } } async triggerAlert(alert, currentRate) { const message = `Alert triggered: ${alert.from}/${alert.to} is ${currentRate.toFixed(6)} (${alert.direction} ${alert.threshold})`; console.log(message); if (alert.webhook) { await this.sendWebhook(alert.webhook, { type: "alert-triggered", alert, currentRate, message, timestamp: (/* @__PURE__ */ new Date()).toISOString() }); } if (alert.email && this.emailTransporter) { await this.sendEmail(alert.email, "Rate Alert Triggered", message); } for (const config of this.webhookConfigs) { if (config.events.includes("alert-triggered") && config.currencies.includes(alert.from) && config.currencies.includes(alert.to)) { await this.sendWebhook(config.url, { type: "alert-triggered", alert, currentRate, message, timestamp: (/* @__PURE__ */ new Date()).toISOString() }); } } } async sendWebhook(url, payload) { try { const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "Somali-Exchange-Rates/1.0" }, body: JSON.stringify(payload) }); if (!response.ok) { console.warn(`Webhook failed: ${response.status} ${response.statusText}`); } } catch (error) { console.error("Webhook error:", error); } } async sendEmail(to, subject, text) { if (!this.emailTransporter) return; try { await this.emailTransporter.sendMail({ from: process.env.SMTP_FROM || "alerts@sosx.com", to, subject, text }); } catch (error) { console.error("Email error:", error); } } setupEmailTransporter(config) { this.emailTransporter = nodemailer.createTransporter(config); } addWebhookConfig(config) { this.webhookConfigs.push(config); } startMonitoring(interval = "*/5 * * * *") { if (this.monitoringTask) { this.monitoringTask.stop(); } this.monitoringTask = cron.schedule(interval, async () => { await this.checkAlerts(); }, { scheduled: false }); this.monitoringTask.start(); console.log(`Started alert monitoring with interval: ${interval}`); } stopMonitoring() { if (this.monitoringTask) { this.monitoringTask.stop(); this.monitoringTask = void 0; console.log("Stopped alert monitoring"); } } async saveAlerts(alerts) { await tryWriteJSON(this.alertsPath, alerts); } generateId() { return Math.random().toString(36).substr(2, 9); } }; var alertManager; function getAlertManager() { if (!alertManager) { alertManager = new AlertManager(); } return alertManager; } async function setRateAlert(from, to, threshold, direction, options = {}) { const manager = getAlertManager(); return manager.createAlert({ from, to, threshold, direction, webhook: options.webhook, email: options.email }); } async function removeRateAlert(id) { const manager = getAlertManager(); return manager.deleteAlert(id); } async function listRateAlerts() { const manager = getAlertManager(); return manager.getAlerts(); } function startAlertMonitoring(interval) { const manager = getAlertManager(); manager.startMonitoring(interval); } function stopAlertMonitoring() { const manager = getAlertManager(); manager.stopMonitoring(); } // src/transfer-fees.ts var PROVIDER_FEES = { "western-union": { "bank-transfer": { fixedFee: 5, percentageFee: 0.015, // 1.5% exchangeRateMargin: 0.02, // 2% margin on exchange rate estimatedTime: "1-3 business days", minimumFee: 5, maximumFee: 50 }, "cash-pickup": { fixedFee: 8, percentageFee: 0.02, // 2% exchangeRateMargin: 0.025, // 2.5% margin estimatedTime: "Within minutes", minimumFee: 8, maximumFee: 75 }, "mobile-money": { fixedFee: 3, percentageFee: 0.01, // 1% exchangeRateMargin: 0.015, // 1.5% margin estimatedTime: "Within minutes", minimumFee: 3, maximumFee: 25 } }, "remitly": { "bank-transfer": { fixedFee: 3.99, percentageFee: 0.01, // 1% exchangeRateMargin: 0.015, // 1.5% margin estimatedTime: "1-2 business days", minimumFee: 3.99, maximumFee: 30 }, "cash-pickup": { fixedFee: 4.99, percentageFee: 0.015, // 1.5% exchangeRateMargin: 0.02, // 2% margin estimatedTime: "Within minutes", minimumFee: 4.99, maximumFee: 40 }, "mobile-money": { fixedFee: 1.99, percentageFee: 5e-3, // 0.5% exchangeRateMargin: 0.01, // 1% margin estimatedTime: "Within minutes", minimumFee: 1.99, maximumFee: 15 } }, "worldremit": { "bank-transfer": { fixedFee: 2.99, percentageFee: 0.012, // 1.2% exchangeRateMargin: 0.018, // 1.8% margin estimatedTime: "1-2 business days", minimumFee: 2.99, maximumFee: 35 }, "cash-pickup": { fixedFee: 5.99, percentageFee: 0.018, // 1.8% exchangeRateMargin: 0.022, // 2.2% margin estimatedTime: "Within minutes", minimumFee: 5.99, maximumFee: 45 }, "mobile-money": { fixedFee: 2.49, percentageFee: 8e-3, // 0.8% exchangeRateMargin: 0.012, // 1.2% margin estimatedTime: "Within minutes", minimumFee: 2.49, maximumFee: 20 } }, "wise": { "bank-transfer": { fixedFee: 1.5, percentageFee: 5e-3, // 0.5% exchangeRateMargin: 5e-3, // 0.5% margin (Wise uses mid-market rate) estimatedTime: "1-2 business days", minimumFee: 1.5, maximumFee: 15 }, "cash-pickup": { fixedFee: 0, // Not available percentageFee: 0, exchangeRateMargin: 0, estimatedTime: "Not available", minimumFee: 0, maximumFee: 0 }, "mobile-money": { fixedFee: 2, percentageFee: 7e-3, // 0.7% exchangeRateMargin: 8e-3, // 0.8% margin estimatedTime: "Within hours", minimumFee: 2, maximumFee: 12 } } }; async function calculateTransferFee(options) { const { amount, from, to, provider, method } = options; const providerFees = PROVIDER_FEES[provider]; if (!providerFees) { throw new Error(`Unsupported provider: ${provider}`); } const feeStructure = providerFees[method]; if (!feeStructure) { throw new Error(`Method ${method} not available for ${provider}`); } if (feeStructure.fixedFee === 0 && feeStructure.percentageFee === 0) { throw new Error(`${method} is not available for ${provider}`); } const midMarketRate = await convert(1, from, to); const providerRate = midMarketRate * (1 - feeStructure.exchangeRateMargin); const percentageFee = amount * feeStructure.percentageFee; let totalFee = feeStructure.fixedFee + percentageFee; if (feeStructure.minimumFee && totalFee < feeStructure.minimumFee) { totalFee = feeStructure.minimumFee; } if (feeStructure.maximumFee && totalFee > feeStructure.maximumFee) { totalFee = feeStructure.maximumFee; } const totalCost = amount + totalFee; const recipientAmount = amount * providerRate; return { fee: totalFee, exchangeRate: providerRate, totalCost, recipientAmount, provider, estimatedTime: feeStructure.estimatedTime }; } async function compareTransferOptions(amount, from, to, method) { const providers = ["western-union", "remitly", "worldremit", "wise"]; const results = []; for (const provider of providers) { try { const result = await calculateTransferFee({ amount, from, to, provider, method }); results.push(result); } catch (error) { console.warn(`Failed to calculate fees for ${provider}:`, error); } } return results.sort((a, b) => a.totalCost - b.totalCost); } async function getBestTransferOption(amount, from, to) { const methods = ["bank-transfer", "cash-pickup", "mobile-money"]; let bestOption = null; for (const method of methods) { try { const options = await compareTransferOptions(amount, from, to, method); if (options.length > 0) { const best = options[0]; if (!bestOption || best.totalCost < bestOption.result.totalCost) { bestOption = { method, result: best }; } } } catch (error) { console.warn(`Failed to compare options for ${method}:`, error); } } if (!bestOption) { throw new Error("No transfer options available"); } return bestOption; } function formatTransferResult(result) { return ` Provider: ${result.provider} Fee: $${result.fee.toFixed(2)} Exchange Rate: ${result.exchangeRate.toFixed(6)} Total Cost: $${result.totalCost.toFixed(2)} Recipient Gets: ${result.recipientAmount.toFixed(2)} Estimated Time: ${result.estimatedTime} `.trim(); } // src/localization.ts var LOCALIZED_STRINGS = { // Currency names "currency.SOS": { en: "Somali Shilling", so: "Shilin Soomaali", ar: "\u0634\u0644\u0646 \u0635\u0648\u0645\u0627\u0644\u064A" }, "currency.USD": { en: "US Dollar", so: "Doolar Maraykan", ar: "\u062F\u0648\u0644\u0627\u0631 \u0623\u0645\u0631\u064A\u0643\u064A" }, "currency.EUR": { en: "Euro", so: "Yuuroo", ar: "\u064A\u0648\u0631\u0648" }, "currency.GBP": { en: "British Pound", so: "Bownd Biritish", ar: "\u062C\u0646\u064A\u0647 \u0625\u0633\u062A\u0631\u0644\u064A\u0646\u064A" }, "currency.KES": { en: "Kenyan Shilling", so: "Shilin Kiiniya", ar: "\u0634\u0644\u0646 \u0643\u064A\u0646\u064A" }, "currency.ETB": { en: "Ethiopian Birr", so: "Bir Itoobiya", ar: "\u0628\u064A\u0631 \u0625\u062B\u064A\u0648\u0628\u064A" }, "currency.AED": { en: "UAE Dirham", so: "Dirham Imaaraadka", ar: "\u062F\u0631\u0647\u0645 \u0625\u0645\u0627\u0631\u0627\u062A\u064A" }, "currency.SAR": { en: "Saudi Riyal", so: "Riyaal Sacuudi", ar: "\u0631\u064A\u0627\u0644 \u0633\u0639\u0648\u062F\u064A" }, "currency.TRY": { en: "Turkish Lira", so: "Lira Turki", ar: "\u0644\u064A\u0631\u0629 \u062A\u0631\u0643\u064A\u0629" }, "currency.CNY": { en: "Chinese Yuan", so: "Yuan Shiinaha", ar: "\u064A\u0648\u0627\u0646 \u0635\u064A\u0646\u064A" }, // Currency symbols "symbol.SOS": { en: "Sh", so: "Sh", ar: "\u0634.\u0635" }, // Common phrases "exchange_rate": { en: "Exchange Rate", so: "Qiimaha Sarifka", ar: "\u0633\u0639\u0631 \u0627\u0644\u0635\u0631\u0641" }, "conversion": { en: "Conversion", so: "Beddelka", ar: "\u0627\u0644\u062A\u062D\u0648\u064A\u0644" }, "amount": { en: "Amount", so: "Qadarka", ar: "\u0627\u0644\u0645\u0628\u0644\u063A" }, "from": { en: "From", so: "Ka", ar: "\u0645\u0646" }, "to": { en: "To", so: "Ilaa", ar: "\u0625\u0644\u0649" }, "equals": { en: "equals", so: "le'eg yahay", ar: "\u064A\u0633\u0627\u0648\u064A" }, "rate_updated": { en: "Rate updated", so: "Qiimaha waa la cusbooneysiiyay", ar: "\u062A\u0645 \u062A\u062D\u062F\u064A\u062B \u0627\u0644\u0633\u0639\u0631" }, "offline_mode": { en: "Offline mode", so: "Hab aan internetka lahayn", ar: "\u0648\u0636\u0639 \u0639\u062F\u0645 \u0627\u0644\u0627\u062A\u0635\u0627\u0644" }, "cache_used": { en: "Using cached data", so: "Isticmaalka xogta kaydsan", ar: "\u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u0627\u0644\u0628\u064A\u0627\u0646\u0627\u062A \u0627\u0644\u0645\u062E\u0632\u0646\u0629" }, // Time periods "daily": { en: "Daily", so: "Maalin kasta", ar: "\u064A\u0648\u0645\u064A" }, "weekly": { en: "Weekly", so: "Toddobaad kasta", ar: "\u0623\u0633\u0628\u0648\u0639\u064A" }, "monthly": { en: "Monthly", so: "Bil kasta", ar: "\u0634\u0647\u0631\u064A" }, // Market analysis "trend.bullish": { en: "Bullish", so: "Kor u socda", ar: "\u0635\u0627\u0639\u062F" }, "trend.bearish": { en: "Bearish", so: "Hoos u socda", ar: "\u0647\u0627\u0628\u0637" }, "trend.neutral": { en: "Neutral", so: "Dhexdhexaad", ar: "\u0645\u062D\u0627\u064A\u062F" }, "volatility": { en: "Volatility", so: "Doorsooma", ar: "\u0627\u0644\u062A\u0642\u0644\u0628" }, "support": { en: "Support", so: "Taageero", ar: "\u0627\u0644\u062F\u0639\u0645" }, "resistance": { en: "Resistance", so: "Iska caabin", ar: "\u0627\u0644\u0645\u0642\u0627\u0648\u0645\u0629" } }; var LocalizationService = class { currentLanguage = "en"; currentLocale = "en-US"; setLanguage(language) { this.currentLanguage = language; } setLocale(locale) { this.currentLocale = locale; if (locale.startsWith("so")) { this.currentLanguage = "so"; } else if (locale.startsWith("ar")) { this.currentLanguage = "ar"; } else { this.currentLanguage = "en"; } } translate(key, language) { const lang = language || this.currentLanguage; const strings = LOCALIZED_STRINGS[key]; if (!strings) { console.warn(`Translation key not found: ${key}`); return key; } return strings[lang] || strings.en || key; } getCurrencyName(currency, language) { return this.translate(`currency.${currency}`, language); } getCurrencySymbol(currency, language) { const symbol = this.translate(`symbol.${currency}`, language); return symbol !== `symbol.${currency}` ? symbol : this.getDefaultSymbol(currency); } formatCurrency(amount, currency, options = {}) { const lang = options.language || this.currentLanguage; const locale = this.getLocaleForLanguage(lang); try { let formatted = new Intl.NumberFormat(locale, { style: "decimal", minimumFractionDigits: currency === "SOS" ? 0 : 2, maximumFractionDigits: currency === "SOS" ? 0 : 6 }).format(amount); if (options.showSymbol !== false) { const symbol = this.getCurrencySymbol(currency, lang); formatted = `${symbol} ${formatted}`; } if (options.showCode) { formatted = `${formatted} ${currency}`; } return formatted; } catch (error) { const symbol = options.showSymbol !== false ? this.getCurrencySymbol(currency, lang) : ""; const code = options.showCode ? ` ${currency}` : ""; return `${symbol} ${amount.toLocaleString()}${code}`.trim(); } } formatQuote(amount, fromCurrency, toCurrency, convertedAmount, options = {}) { const lang = options.language || this.currentLanguage; const fromFormatted = this.formatCurrency(amount, fromCurrency, { language: lang }); const toFormatted = this.formatCurrency(convertedAmount, toCurrency, { language: lang }); const equals = this.translate("equals", lang); return `${fromFormatted} ${equals} ${toFormatted}`; } formatTrend(trend, language) { return this.translate(`trend.${trend}`, language); } getAvailableLanguages() { return [ { code: "en", name: "English", nativeName: "English" }, { code: "so", name: "Somali", nativeName: "Soomaali" }, { code: "ar", name: "Arabic", nativeName: "\u0627\u0644\u0639\u0631\u0628\u064A\u0629" } ]; } getLocaleForLanguage(language) { switch (language) { case "so": return "so-SO"; case "ar": return "ar-SA"; default: return "en-US"; } } getDefaultSymbol(currency) { const symbols = { SOS: "Sh", USD: "$", EUR: "\u20AC", GBP: "\xA3", KES: "KSh", ETB: "Br", AED: "\u062F.\u0625", SAR: "\uFDFC", TRY: "\u20BA", CNY: "\xA5" }; return symbols[currency] || currency; } }; var localizationService; function getLocalizationService() { if (!localizationService) { localizationService = new LocalizationService(); } return localizationService; } function setLanguage(language) { getLocalizationService().setLanguage(language); } function setLocale(locale) { getLocalizationService().setLocale(locale); } function translate(key, language) { return getLocalizationService().translate(key, language); } function formatLocalizedCurrency(amount, currency, options) { return getLocalizationService().formatCurrency(amount, currency, options); } function formatLocalizedQuote(amount, fromCurrency, toCurrency, convertedAmount, options) { return getLocalizationService().formatQuote(amount, fromCurrency, toCurrency, convertedAmount, options); } // src/export.ts import * as XLSX from "xlsx"; import { createObjectCsvWriter } from "csv-writer"; import { promises as fs } from "fs"; var ExportService = class { async exportRates(options) { const { format, period, currencies, output } = options; const days = parseInt(period.replace(/[^\d]/g, "")); const endDate = /* @__PURE__ */ new Date(); const startDate = /* @__PURE__ */ new Date(); startDate.setDate(startDate.getDate() - days); const data = []; for (const currency of currencies) { if (currency === "SOS") continue; try { const history = await getRateHistory( currency, startDate.toISOString().split("T")[0], endDate.toISOString().split("T")[0] ); history.forEach((record) => { data.push({ date: record.date, currency, rate: record.rate, baseCurrency: "SOS" }); }); } catch (error) { console.warn(`Failed to get history for ${currency}:`, error); } } data.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()); const filename = output || this.generateFilename(format, period, currencies); switch (format) { case "csv": return this.exportToCSV(data, filename); case "xlsx": return this.exportToXLSX(data, filename); case "json": return this.exportToJSON(data, filename); case "pdf": return this.exportToPDF(data, filename); default: throw new Error(`Unsupported export format: ${format}`); } } async exportAnalysisReport(currencies, period, output) { const analysisData = []; for (const currency of currencies) { if (currency === "SOS") continue; try { const analysis = await analyzeMarket("SOS", currency, period); analysisData.push({ currency, baseCurrency: "SOS", period, volatility: analysis.volatility, trend: analysis.trend, support: analysis.support, resistance: analysis.resistance, rsi: analysis.rsi, sma7: analysis.sma[0], sma14: analysis.sma[1], sma30: analysis.sma[2], ema7: analysis.ema[0], ema14: analysis.ema[1], ema30: analysis.ema[2], generatedAt: (/* @__PURE__ */ new Date()).toISOString() }); } catch (error) { console.warn(`Failed to analyze ${currency}:`, error); } } const filename = output || `analysis-report-${period}-${Date.now()}.xlsx`; return this.exportToXLSX(analysisData, filename); } async exportToCSV(data, filename) { if (data.length === 0) { throw new Error("No data to export"); } const csvWriter = createObjectCsvWriter({ path: filename, header: Object.keys(data[0]).map((key) => ({ id: key, title: key })) }); await csvWriter.writeRecords(data); console.log(`Exported ${data.length} records to ${filename}`); return filename; } async exportToXLSX(data, filename) { if (data.length === 0) { throw new Error("No data to export"); } const worksheet = XLSX.utils.json_to_sheet(data); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Exchange Rates"); const range = XLSX.utils.decode_range(worksheet["!ref"] || "A1"); const colWidths = []; for (let col = range.s.c; col <= range.e.c; col++) { let maxWidth = 10; for (let row = range.s.r; row <= range.e.r; row++) { const cellAddress = XLSX.utils.encode_cell({ r: row, c: col }); const cell = worksheet[cellAddress]; if (cell && cell.v) { const cellLength = cell.v.toString().length; maxWidth = Math.max(maxWidth, cellLength); } } colWidths.push({ wch: Math.min(maxWidth + 2, 50) }); } worksheet["!cols"] = colWidths; XLSX.writeFile(workbook, filename); console.log(`Exported ${data.length} records to ${filename}`); return filename; } async exportToJSON(data, filename) { const jsonData = { exportedAt: (/* @__PURE__ */ new Date()).toISOString(), recordCount: data.length, data }; await fs.writeFile(filename, JSON.stringify(jsonData, null, 2)); console.log(`Exported ${data.length} records to ${filename}`); return filename; } async exportToPDF(data, filename) { const html = this.generateHTMLReport(data); const htmlFilename = filename.replace(".pdf", ".html"); await fs.writeFile(htmlFilename, html); console.log(`Exported HTML report to ${htmlFilename} (PDF conversion requires additional library)`); return htmlFilename; } generateHTMLReport(data) { const headers = data.length > 0 ? Object.keys(data[0]) : []; return ` <!DOCTYPE html> <html> <head> <title>Somali Exchange Rates Report</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .header { margin-bottom: 20px; } .summary { margin-bottom: 20px; padding: 10px; background-color: #f9f9f9; } </style> </head> <body> <div class="header"> <h1>Somali Exchange Rates Report</h1> <p>Generated on: ${(/* @__PURE__ */ new Date()).toLocaleString()}</p> </div> <div class="summary"> <h2>Summary</h2> <p>Total Records: ${data.length}</p> <p>Currencies: ${[...new Set(data.map((d) => d.currency))].join(", ")}</p> <p>Date Range: ${data.length > 0 ? `${data[0].date} to ${data[data.length - 1].date}` : "N/A"}</p> </div> <table> <thead> <tr> ${headers.map((header) => `<th>${header}</th>`).join("")} </tr> </thead> <tbody> ${data.map((row) => ` <tr> ${headers.map((header) => `<td>${row[header] || ""}</td>`).join("")} </tr> `).join("")} </tbody> </table> </body> </html>`; } generateFilename(format, period, currencies) { const timestamp = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]; const currencyList = currencies.slice(0, 3).join("-"); return `exchange-rates-${currencyList}-${period}-${timestamp}.${format}`; } }; var exportService; async function exportRates(options) { if (!exportService) { exportService = new ExportService(); } return exportService.exportRates(options); } async function exportAnalysisReport(currencies, period, output) { if (!exportService) { exportService = new ExportService(); } return exportService.exportAnalysisReport(currencies, period, output); } async function exportToCSV(currencies, period, output) { return exportRates({ format: "csv", currencies, period, output }); } async function exportToExcel(currencies, period, output) { return exportRates({ format: "xlsx", currencies, period, output }); } // src/config.ts import path2 from "path"; import os2 from "os"; var DEFAULT_CONFIG = { defaultCurrencies: ["USD", "EUR", "GBP", "KES", "ETB"], language: "en", locale: "en-US", notifications: {}, providers: { primary: "exchangerate-host", fallbacks: ["fixer", "currencyapi"] } }; var ConfigManager = class { configPath; config; constructor() { this.configPath = path2.join(os2.homedir(), ".sosx", "config.json"); this.config = { ...DEFAULT_CONFIG }; } async loadConfig() { try { const savedConfig = await tryReadJSON(this.configPath); if (savedConfig) { this.config = { ...DEFAULT_CONFIG, ...savedConfig }; } } catch (error) { console.warn("Failed to load config, using defaults:", error); } return this.config; } async saveConfig() { await tryWriteJSON(this.configPath, this.config); console.log(`Configuration saved to ${this.configPath}`); } getConfig() { return { ...this.config }; } // Language and Locale setLanguage(language) { this.config.language = language; switch (language) { case "so": this.config.locale = "so-SO"; break; case "ar": this.config.locale = "ar-SA"; break; default: this.config.locale = "en-US"; } } setLocale(locale) { this.config.locale = locale; } getLanguage() { return this.config.language; } getLocale() { return this.config.locale; } // Default Currencies setDefaultCurrencies(currencies) { this.config.defaultCurrencies = currencies; } addDefaultCurrency(currency) { if (!this.config.defaultCurrencies.includes(currency)) { this.config.defaultCurrencies.push(currency); } } removeDefaultCurrency(currency) { this.config.defaultCurrencies = this.config.defaultCurrencies.filter((c) => c !== currency); } getDefaultCurrencies() { return [...this.config.defaultCurrencies]; } // Notifications setEmailNotification(email) { this.config.notifications.email = email; } setWebhookNotification(webhook) { this.config.notifications.webhook = webhook; } removeEmailNotification() { delete this.config.notifications.email; } removeWebhookNotification() { delete this.config.notifications.webhook; } getNotificationSettings() { return { ...this.config.notifications }; } // Providers setPrimaryProvider(provider) { this.config.providers.primary = provider; } setFallbackProviders(providers) { this.config.providers.fallbacks = providers; } addFallbackProvider(provider) { if (!this.config.providers.fallbacks.includes(provider)) { this.config.providers.fallbacks.push(provider); } } removeFallbackProvider(provider) { this.config.providers.fallbacks = this.config.providers.fallbacks.filter((p) => p !== provider); } getProviderSettings() { return { ...this.config.providers }; } // Database setDatabaseConfig(config) { this.config.database = config; } removeDatabaseConfig() { delete this.config.database; } getDatabaseConfig() { return this.config.database ? { ...this.config.database } : void 0; } // Validation validateConfig() { const errors = []; const validCurrencies = ["SOS", "USD", "EUR", "GBP", "KES", "ETB", "AED", "SAR", "TRY", "CNY"]; for (const currency of this.config.defaultCurrencies) { if (!validCurrencies.includes(currency)) { errors.push(`Invalid currency: ${currency}`); } } const validLanguages = ["en", "so", "ar"]; if (!validLanguages.includes(this.config.language)) { errors.push(`Invalid language: ${this.config.language}`); } const validLocales = ["en-US", "so-SO", "ar-SA"]; if (!validLocales.includes(this.config.locale)) { errors.push(`Invalid locale: ${this.config.locale}`); } if (this.config.notifications.email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(this.config.notifications.email)) { errors.push(`Invalid email format: ${this.config.notifications.email}`); } } if (this.config.notifications.webhook) { try { new URL(this.config.notifications.webhook); } catch { errors.push(`Invalid webhook URL: ${this.config.notifications.webhook}`); } } return { valid: errors.length === 0, errors }; } // Reset to defaults resetToDefaults() { this.config = { ...DEFAULT_CONFIG }; } // Export/Import exportConfig() { return JSON.stringify(this.config, null, 2); } importConfig(configJson) { try { const importedConfig = JSON.parse(configJson); this.config = { ...DEFAULT_CONFIG, ...importedConfig }; const validation = this.validateConfig(); if (!validation.valid) { throw new Error(`Invalid configuration: ${validation.errors.join(", ")}`); } } catch (error) { throw new Error(`Failed to import configuration: ${error}`); } } }; var configManager; function getConfigManager() { if (!configManager) { configManager = new ConfigManager(); } return configManager; } async function loadUserConfig() { return getConfigManager().loadConfig(); } async function saveUserConfig() { return getConfigManager().saveConfig(); } function getUserConfig() { return getConfigManager().getConfig(); } function setUserLanguage(language) { getConfigManager().setLanguage(language); } function setUserDefaultCurrencies(currencies) { getConfigManager().setDefaultCurrencies(currencies); } function setUserNotifications(email, webhook) { const manager = getConfigManager(); if (email) manager.setEmailNotification(email); if (webhook) manager.setWebhookNotification(webhook); } async function runConfigWizard() { const manager = getConfigManager(); console.log("\u{1F527} Somali Exchange Rates Configuration Wizard"); console.log("This will help you set up your preferences.\n"); manager.setLanguage("en"); manager.setDefaultCurrencies(["USD", "EUR", "GBP", "KES", "ETB"]); manager.setPrimaryProvider("exchangerate-host"); manager.setFallbackProviders(["fixer", "currencyapi"]); await manager.saveConfig(); console.log("\u2705 Configuration saved successfully!"); console.log(`Configuration file: ${manager["configPath"]}`); } // src/realtime.ts import { WebSocket, WebSocketServer } from "ws"; import { EventEmitter } from "events"; import * as cron2 from "node-cron"; var RateStreamServer = class extends EventEmitter { server; clients = /* @__PURE__ */ new Set(); updateTask; lastRates = {}; constructor(port = 8080) { super(); this.server = new WebSocketServer({ port }); this.setupServer(); } setupServer() { this.server.on("connection", (ws) => { console.log("New WebSocket client connected"); this.clients.add(ws); this.sendCurrentRates(ws); ws.on("message", (message) => { try { const data = JSON.parse(message); this.handleClientMessage(ws, data); } catch (error) { console.error("Invalid message from client:", error); } }); ws.on("close", () => { console.log("WebSocket client disconnected"); this.clients.delete(ws); }); ws.on("error", (error) => { console.error("WebSocket error:", error); this.clients.delete(ws); }); }); console.log(`Rate stream server started on port ${this.server.options.port}`); } handleClientMessage(ws, data) { switch (data.type) { case "subscribe": if (data.currencies && Array.isArray(data.currencies)) { ws.send(JSON.stringify({ type: "subscription_confirmed", currencies: data.currencies, timestamp: (/* @__PURE__ */ new Date()).toISOString() })); } break; case "ping": ws.send(JSON.stringify({ type: "pong", timestamp: (/* @__PURE__ */ new Date()).toISOString() })); break; } } async sendCurrentRates(ws) { try { const rates = await getRates(); ws.send(JSON.stringify({ type: "current_rates", rates, timestamp: (/* @__PURE__ */ new Date()).toISOString() })); } catch (error) { console.error("Failed to send current rates:", error); } } startUpdates(interval = "*/1 * * * *") { if (this.updateTask) { this.updateTask.stop(); } this.updateTask = cron2.schedule(interval, async () => { await this.checkForUpdates(); }, { scheduled: false }); this.updateTask.start(); console.log(`Started rate updates with interval: ${interval}`); } stopUpdates() { if (this.updateTask) { this.updateTask.stop(); this.updateTask = void 0; console.log("Stopped rate updates"); } } async checkForUpdates() { try { const newRates = await getRates(); const updates = []; for (const [currency, rate] of Object.entries(newRates)) { const previousRate = this.lastRates[currency]; if (previousRate && previousRate !== rate) { const change = rate - previousRate; const changePercent = change / previousRate * 100; updates.push({ from: "SOS", to: currency, rate, previousRate, change, changePercent, timestamp: (/* @__PURE__ */ new Date()).toISOString() }); } } if (updates.length > 0) { this.broadcastUpdates(updates); this.emit("rate-updates", updates); } this.lastRates = newRates; } catch (error) { console.error("Failed to check for rate updates:", error); } } broadcastUpdates(updates) { const message = JSON.stringify({ type: "rate_updates", updates, timestamp: (/* @__PURE__ */ new Date()).toISOString() }); this.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); console.log(`Broadcasted ${updates.length} rate updates to ${this.clients.size} clients`); } getConnectedClients() { return this.clients.size; } close() { this.stopUpdates(); this.clients.forEach((client) => client.close()); this.server.close(); console.log("Rate stream server closed"); } }; var RateStreamClient = class extends EventEmitter { ws; url; reconnectAttempts = 0; maxReconnectAttempts = 5; reconnectDelay = 1e3; constructor(url = "ws://localhost:8080") { super(); this.url = url; } connect() { try { this.ws = new WebSocket(this.url); this.ws.on("open", () => { console.log("Connected to rate stream server"); this.reconnectAttempts = 0; this.emit("connected"); }); this.ws.on("message", (data) => { try { const message = JSON.parse(data); this.handleMessage(message); } catch (error) { console.error("Failed to parse message:", error); } }); this.ws.on("close", () => { console.log("Disconnected from rate stream server"); this.emit("disconnected"); this.attemptReconnect(); }); this.ws.on("error", (error) => { console.error("WebSocket error:", error); this.emit("error", error); }); } catch (error) { console.error("Failed to connect to rate stream server:", error); this.attemptReconnect(); } } handleMessage(message) { switch (message.type) { case "current_rates": this.emit("current-rates", message.rates); break; case "rate_updates": this.emit("rate-updates", message.updates); break; case "subscription_confirmed": this.emit("subscription-confirmed", message.currencies); break; case "pong": this.emit("pong"); break; } } subscribe(currencies) { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "subscribe", currencies })); } } ping() { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "ping" })); } } attemptReconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1); console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`); setTimeout(() => { this.connect(); }, delay); } else { console.error("Max reconnection attempts reached"); this.emit("max-reconnect-attempts"); } } disconnect() { if (this.ws) { this.ws.close(); this.ws = void 0; } } }; function createRateStream(currencies) { const client = new RateStreamClient(); client.on("connected", () => { if (currencies) { client.subscribe(currencies); } }); client.connect(); return client; } // src/index.ts function defaultPersistPath() { return path3.join(os3.homedir(), ".sosx", "cache.json"); } async function readCache(persistPath) { const mem = getMemoryCache(); if (mem) return mem; if (persistPath) return await tryReadJSON(persistPath); return null; } async function writeCache(c, persistPath) { setMemoryCache(c); if (persistPath) await tryWriteJSON(persistPath, c); } async function getRates(options = {}) { const { provider = new ExchangerateHostProvider(), ttlMs = 1e3 * 60 * 60 * 6, // 6 hours persistPath = defaultPersistPath(), offline = false } = options; const cached = await readCache(persistPath); const fresh = cached && Date.now() - cached.at < ttlMs; if (fresh) return cached.rates; if (offline) { if (cached) return cached.rates; return seed_default; } try { const live = await provider.fetchRatesSOS(); const c = { at: Date.now(), rates: live }; await writeCache(c, persistPath); return live; } catch { if (cached) return cached.rates; return seed_default; } } async function getRate(target, options) { const table = await getRates(options); return table[target]; } async function convert(amount, from, to, options) { if (from === to) return amount; const table = await getRates(options); if (from === "SOS") { return amount * table[to]; } if (to === "SOS") { return amount * (1 / table[from]); } const inSOS = amount * (1 / table[from]); return inSOS * table[to]; } function formatSOS(value) { return new Intl.NumberFormat("so-SO", { style: "currency", currency: "SOS", currencyDisplay: "symbol" }).format(value); } function formatCurrency(value, currency) { return new Intl.NumberFormat("so-SO", { style: "currency", currency, currencyDisplay: "symbol" }).format(value); } async function quote(from, to, amount = 1, options) { const out = await convert(amount, from, to, options); const left = formatCurrency(amount, from); const right = to === "SOS" ? formatSOS(nice(out)) : formatCurrency(nice(out), to); return `${left} = ${right}`; } export { AlertManager, getAlertManager, setRateAlert, removeRateAlert, listRateAlerts, startAlertMonitoring, stopAlertMonitoring, calculateTransferFee, compareTransferOptions, getBestTransferOption, formatTransferResult, LocalizationService, getLocalizationService, setLanguage, setLocale, translate, formatLocalizedCurrency, formatLocalizedQuote, ExportService, exportRates, exportAnalysisReport, exportToCSV, exportToExcel, ConfigManager, getConfigManager, loadUserConfig, saveUserConfig, getUserConfig, setUserLanguage, setUserDefaultCurrencies, setUserNotifications, runConfigWizard, RateStreamServer, RateStreamClient, createRateStream, getRates, getRate, convert, formatSOS, formatCurrency, quote };