const { fail, requireProductWrite } = require('./workspace.cjs'); function sendJson(response, status, value) { if (response.destroyed || response.writableEnded) return; const body = JSON.stringify(value); response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Length': Buffer.byteLength(body) }); response.end(body); } function readJson(request, maxBytes) { const contentType = String(request.headers['content-type'] || '').split(';')[0].trim().toLowerCase(); if (contentType !== 'application/json') throw fail(415, 'JSON_REQUIRED', 'JSON request প্রয়োজন।'); if (Number(request.headers['content-length']) > maxBytes) throw fail(413, 'REQUEST_TOO_LARGE', 'Request অতিরিক্ত বড়।'); return new Promise((resolve, reject) => { const chunks = []; let bytes = 0, done = false; function cleanup() { request.off('data', data); request.off('end', end); request.off('error', error); request.off('aborted', aborted); } function finish(problem, value) { if (done) return; done = true; cleanup(); if (problem) { request.resume(); reject(problem); } else resolve(value); } function data(chunk) { bytes += chunk.length; if (bytes > maxBytes) return finish(fail(413, 'REQUEST_TOO_LARGE', 'Request অতিরিক্ত বড়।')); chunks.push(chunk); } function end() { let value; try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return finish(fail(400, 'INVALID_JSON', 'Request-এর JSON সঠিক নয়।')); } if (!value || typeof value !== 'object' || Array.isArray(value)) return finish(fail(400, 'INVALID_JSON', 'JSON object প্রয়োজন।')); finish(null, value); } function error() { finish(fail(400, 'INCOMPLETE_REQUEST', 'Request সম্পূর্ণ আসেনি।')); } function aborted() { error(); } request.on('data', data); request.on('end', end); request.on('error', error); request.on('aborted', aborted); }); } function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) { const configured = new URL(publicOrigin); if (!['http:', 'https:'].includes(configured.protocol) || configured.pathname !== '/' || configured.search || configured.hash || configured.username || configured.password) { throw new Error('A public Studio origin without path or credentials is required'); } if (![maxBodyBytes, maxConcurrentImports, maxImportsPerMinute].every(n => Number.isInteger(n) && n > 0)) throw new Error('Invalid API limits'); const origin = configured.origin, attempts = new Map(); let runningImports = 0; function browserStore(record, workspace) { return { ...record, products: record.products.map(product => ({ ...product, image: product.image ? '/api/catalog-image?' + new URLSearchParams({ storeId: record.id, productId: String(product.id), tenant: workspace.tenant }).toString() : '' })) }; } function writeOrigin(request) { if (request.headers.origin !== origin || (request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin')) { throw fail(403, 'ORIGIN_REJECTED', 'এই request Studio page থেকে পাঠান।'); } } function rateLimit(workspace) { const now = Date.now(), key = workspace.namespace + ':' + workspace.userId; for (const [id, item] of attempts) if (item.until <= now) attempts.delete(id); const item = attempts.get(key) || { count: 0, until: now + 60000 }; if (item.count >= maxImportsPerMinute) throw fail(429, 'IMPORT_RATE_LIMIT', 'অল্প পরে আবার import করুন।'); item.count++; attempts.set(key, item); if (attempts.size > 10000) attempts.delete(attempts.keys().next().value); } return async function api(request, response) { try { const pathname = new URL(request.url, origin).pathname; const routes = { '/api/workspace': 'GET', '/api/catalog-image': 'GET', '/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST' }; if (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' }); if (request.method !== routes[pathname]) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' }); if (request.method === 'POST') writeOrigin(request); const workspace = await resolveWorkspace(request); const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts }; if (pathname === '/api/workspace') return sendJson(response, 200, { success: true, workspace: publicWorkspace }); if (pathname === '/api/catalog-image') { if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।'); return await imageHandler(request, response, workspace); } if (request.method === 'GET') { const records = await store.read(workspace); if (getConnected) records.unshift(await getConnected(workspace)); return sendJson(response, 200, { success: true, stores: records.map(record => browserStore(record, workspace)), workspace: publicWorkspace }); } requireProductWrite(workspace); const body = await readJson(request, maxBodyBytes); if (pathname === '/api/delete-synced-store') { if (typeof body.storeId === 'string' && body.storeId.startsWith('connected:')) throw fail(403, 'CONNECTED_CATALOG_READ_ONLY', 'Connected catalog মূল Client dashboard থেকে পরিচালনা করুন।'); if (typeof body.storeId !== 'string' || !body.storeId || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।'); return sendJson(response, 200, { success: true, stores: (await store.remove(workspace, body.storeId)).map(record => browserStore(record, workspace)) }); } if (runningImports >= maxConcurrentImports) throw fail(503, 'IMPORT_BUSY', 'আরেকটি import চলছে; অল্প পরে আবার চেষ্টা করুন।'); rateLimit(workspace); const controller = new AbortController(); const disconnected = () => { if (!response.writableEnded) controller.abort(); }; response.on('close', disconnected); runningImports++; try { const imported = await scrape({ url: body.url, storeName: body.storeName, category: body.category }, { signal: controller.signal }); if (controller.signal.aborted) throw fail(499, 'REQUEST_CANCELLED', 'Request বাতিল হয়েছে।'); await store.upsert(workspace, imported); return sendJson(response, 200, { success: true, store: browserStore(imported, workspace) }); } finally { runningImports--; response.off('close', disconnected); } } catch (error) { const status = Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 ? error.status : 500; if (status === 413) { response.setHeader('Connection', 'close'); request.resume(); } return sendJson(response, status, { success: false, code: status === 500 ? 'INTERNAL_ERROR' : (error.code || 'REQUEST_FAILED'), error: status === 500 ? 'কাজটি সম্পন্ন হয়নি; আগের data মুছে দেওয়া হয়নি।' : error.message }); } }; } module.exports = { createApiHandler };