/** FonFin AI Sohbet API v1 — sunucu tarafı Node.js örneği, bağımsız paket/SDK değildir. */ export class FonFinError extends Error { constructor(status, code, requestId) { super(`FonFin HTTP ${status}: ${code}`); this.status = status; this.code = code; this.requestId = requestId; } } export class FonFin { #apiKey; constructor(apiKey, { sandbox = false, timeoutMs = 150000 } = {}) { if (!/^ffk_chat_[a-z2-7]{8}_[A-Za-z0-9_-]{43}$/.test(apiKey)) throw new Error('Geçerli Sohbet API anahtarı (ffk_chat_…) gerekli.'); this.#apiKey = apiKey; this.base = `https://api.fonfin.ai${sandbox ? '/sandbox' : ''}/v1`; this.timeoutMs = timeoutMs; } async request(path, body) { const response = await fetch(this.base + path, { method: 'POST', redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(this.timeoutMs), headers: {Authorization: `Bearer ${this.#apiKey}`, Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify(body), }); // Büyük yanıtlar için uygulamanızda akış kullanın; örnekte 1 MB sınırı var. const reader = response.body?.getReader(); const decoder = new TextDecoder(); let text = '', size = 0; try { if (reader) while (true) { const {value, done} = await reader.read(); if (done) break; size += value.byteLength; if (size > 1048576) { await reader.cancel(); throw new Error('Yanıt 1 MB sınırını aştı.'); } text += decoder.decode(value, {stream:true}); } text += decoder.decode(); } finally { reader?.releaseLock(); } let data; try { data = JSON.parse(text); } catch { throw new FonFinError(response.status, 'gecersiz_yanit', response.headers.get('x-request-id')); } if (!response.ok) { const code = /^[a-z_]{1,80}$/.test(data?.hata?.kod || '') ? data.hata.kod : 'api_hatasi'; throw new FonFinError(response.status, code, response.headers.get('x-request-id')); } return {data, requestId:response.headers.get('x-request-id'), sandbox:response.headers.get('x-fonfin-sandbox') === 'true'}; } /** onceki_yanit_id ile sohbet sürdürülür (Sandbox desteklemez). */ chat(prompt, {oncekiYanitId} = {}) { return this.request('/chat', {prompt, ...(oncekiYanitId ? {onceki_yanit_id: oncekiYanitId} : {})}); } } // const client = new FonFin(process.env.FONFIN_API_KEY, {sandbox:true}); // const {data, requestId} = await client.chat('Sandbox bağlantı testi'); // Ücretli POST otomatik tekrarlanmaz; timeout sunucunun işlemi bitirmediğini kanıtlamaz.