export const RATE_SOURCE = 'https://www.tcmb.gov.tr/kurlar/today.xml'; export function parseRates(xml) { const bulletinDate = /]*\bTarih="([^"]+)"/.exec(xml)?.[1]; if (!bulletinDate) throw new Error('TCMB bülten tarihi okunamadı.'); const rates={}; for (const code of ['USD','EUR']) { const block=new RegExp(`]*CurrencyCode="${code}"[^>]*>([\\s\\S]*?)`).exec(xml)?.[1]; const unit=Number(/([^<]+)<\/Unit>/.exec(block || '')?.[1]); const selling=Number(/([^<]+)<\/ForexSelling>/.exec(block || '')?.[1]); if (!(unit>0) || !(selling>0)) throw new Error(`${code} döviz satış kuru okunamadı.`); rates[code]=selling/unit; } return {bulletinDate,rates,type:'Döviz satış',source:RATE_SOURCE}; } let cache; export async function exchangeRates() { if (cache && Date.now()-cache.at<15*60*1000) return {...cache.value,cached:true}; try { const response=await fetch(RATE_SOURCE,{signal:AbortSignal.timeout(10000)}); if (!response.ok) throw new Error('TCMB kaynağına ulaşılamadı.'); const value={...parseRates(await response.text()),fetchedAt:new Date().toISOString()}; cache={at:Date.now(),value};return {...value,cached:false}; } catch(error) { if(cache) return {...cache.value,cached:true,refreshError:'Güncelleme alınamadı; gösterilen bülten tarihini kontrol edin.'}; throw new Error('Kur alınamadı. Daha sonra yeniden deneyin.'); } }