import { createRouter, type Router } from '@rareindex/connectors'; import { env, logger } from '@rareindex/shared'; import { recordCost } from './costs.ts'; let cached: Router | null = null; /** Shared engine router wired to the cost ledger. Keys come from env only (ยง194). */ export function getRouter(connectorId?: string): Router { if (cached && !connectorId) return cached; const r = createRouter({ firecrawlApiKey: env().FIRECRAWL_API_KEY, scrapflyApiKey: env().SCRAPFLY_API_KEY, log: logger.child({ component: 'router', connector: connectorId }), onAttempt: (info) => { if (info.engine === 'firecrawl' || info.engine === 'scrapfly') { recordCost({ kind: info.engine, provider: info.engine, connectorId, credits: info.credits, units: 1, metadata: { success: info.success, quality: info.quality, ms: info.ms } }); } }, }); if (!connectorId) cached = r; return r; }