@umituz/web-ai-groq-provider 1.1.13 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +154 -72
  2. package/dist/domains/chat/index.cjs +539 -0
  3. package/dist/domains/chat/index.cjs.map +1 -0
  4. package/dist/domains/chat/index.d.cts +322 -0
  5. package/dist/domains/chat/index.d.ts +322 -0
  6. package/dist/domains/chat/index.js +531 -0
  7. package/dist/domains/chat/index.js.map +1 -0
  8. package/dist/domains/groq/index.cjs +1499 -0
  9. package/dist/domains/groq/index.cjs.map +1 -0
  10. package/dist/domains/groq/index.d.cts +561 -0
  11. package/dist/domains/groq/index.d.ts +561 -0
  12. package/dist/domains/groq/index.js +1453 -0
  13. package/dist/domains/groq/index.js.map +1 -0
  14. package/dist/index.cjs +1993 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +53 -0
  17. package/dist/index.d.ts +53 -0
  18. package/dist/index.js +1937 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/text-generation.service-BP4Q_SH0.d.cts +252 -0
  21. package/dist/text-generation.service-BP4Q_SH0.d.ts +252 -0
  22. package/package.json +25 -11
  23. package/src/domains/chat/entities/chat.entities.ts +0 -113
  24. package/src/domains/chat/entities/index.ts +0 -14
  25. package/src/domains/chat/hooks/index.ts +0 -5
  26. package/src/domains/chat/hooks/use-chat.hook.ts +0 -259
  27. package/src/domains/chat/index.ts +0 -32
  28. package/src/domains/chat/interfaces/chat.interface.ts +0 -80
  29. package/src/domains/chat/interfaces/index.ts +0 -10
  30. package/src/domains/chat/services/chat.service.ts +0 -195
  31. package/src/domains/chat/services/index.ts +0 -5
  32. package/src/domains/chat/utils/message-formatter.ts +0 -49
  33. package/src/domains/groq/constants/error.constants.ts +0 -46
  34. package/src/domains/groq/constants/groq.constants.ts +0 -68
  35. package/src/domains/groq/constants/index.ts +0 -20
  36. package/src/domains/groq/entities/groq.entities.ts +0 -196
  37. package/src/domains/groq/entities/index.ts +0 -20
  38. package/src/domains/groq/hooks/index.ts +0 -7
  39. package/src/domains/groq/hooks/use-groq.hook.ts +0 -232
  40. package/src/domains/groq/index.ts +0 -72
  41. package/src/domains/groq/interfaces/groq.interface.ts +0 -77
  42. package/src/domains/groq/interfaces/index.ts +0 -22
  43. package/src/domains/groq/services/http-client.service.ts +0 -265
  44. package/src/domains/groq/services/index.ts +0 -9
  45. package/src/domains/groq/services/text-generation.service.ts +0 -238
  46. package/src/domains/groq/utils/cache-manager.util.ts +0 -215
  47. package/src/domains/groq/utils/debounce.util.ts +0 -268
  48. package/src/domains/groq/utils/error.util.ts +0 -57
  49. package/src/domains/groq/utils/groq-error.util.ts +0 -18
  50. package/src/domains/groq/utils/index.ts +0 -37
  51. package/src/domains/groq/utils/message.util.ts +0 -57
  52. package/src/domains/groq/utils/request-deduplicator.util.ts +0 -123
  53. package/src/domains/groq/utils/request-queue.util.ts +0 -178
  54. package/src/domains/groq/utils/retry.util.ts +0 -207
  55. package/src/index.ts +0 -15
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/domains/groq/utils/groq-error.ts","../../../src/domains/groq/constants/error-types.ts","../../../src/domains/groq/constants/groq.constants.ts","../../../src/domains/groq/constants/identifier.constants.ts","../../../src/domains/groq/calculations/lru-key-selector.ts","../../../src/domains/groq/calculations/cache-hit-rate.ts","../../../src/domains/groq/builders/cache-key-builder.ts","../../../src/domains/groq/utils/cache-manager.ts","../../../src/domains/groq/builders/groq-request.builder.ts","../../../src/domains/groq/builders/structured-prompt.builder.ts","../../../src/domains/groq/constants/protocol.constants.ts","../../../src/domains/groq/parsers/sse-line-extractor.ts","../../../src/domains/groq/parsers/streaming-response.parser.ts","../../../src/domains/groq/parsers/json-content-extractor.ts","../../../src/domains/groq/parsers/json-response.parser.ts","../../../src/domains/groq/utils/message.util.ts","../../../src/domains/groq/services/text-generation.service.ts","../../../src/domains/groq/validators/api-key-validator.ts","../../../src/domains/groq/clients/groq-config-store.ts","../../../src/domains/groq/validators/http-status-classifier.ts","../../../src/domains/groq/extractors/response-error-message-extractor.ts","../../../src/domains/groq/clients/groq-http-transport.ts","../../../src/domains/groq/utils/request-deduplicator.util.ts","../../../src/domains/groq/utils/request-queue.util.ts","../../../src/domains/groq/calculations/exponential-backoff.ts","../../../src/domains/groq/validators/error-classifier.ts","../../../src/domains/groq/utils/retry.ts","../../../src/domains/groq/strategies/retry-executor.strategy.ts","../../../src/domains/groq/strategies/queue-executor.strategy.ts","../../../src/domains/groq/strategies/dedupe-executor.strategy.ts","../../../src/domains/groq/strategies/composite-executor.strategy.ts","../../../src/domains/groq/clients/groq-http-client.ts","../../../src/domains/groq/resolvers/user-friendly-error-resolver.ts","../../../src/domains/groq/utils/error-resolver.ts","../../../src/domains/groq/hooks/use-groq.hook.ts","../../../src/domains/groq/hooks/use-cache-stats.hook.ts","../../../src/domains/groq/calculations/timing-window.ts","../../../src/domains/groq/utils/debounce.ts"],"names":["GroqErrorType","retryManager","useState","useRef","useMemo","useEffect","useCallback"],"mappings":";;;;;AAaO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnB,IAAA;AAAA,EACA,KAAA;AAAA,EACA,QAAA;AAAA,EAEhB,YACE,IAAA,EACA,OAAA,EACA,KAAA,EACA,QAAA,GAA8B,EAAC,EAC/B;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AACb,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AAAA,EAES,QAAA,GAAmB;AAC1B,IAAA,MAAM,UAAA,GACJ,OAAO,IAAA,CAAK,QAAA,CAAS,MAAA,KAAW,WAAW,CAAA,OAAA,EAAU,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,CAAA,CAAA,GAAM,EAAA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AAA;AAC9B,UAAA,MAAM,SAAA,GAAY,WAAW,MAAM;AACjC,YAAA,IAAA,CAAK,MAAA,CAAO,OAAO,GAAG,CAAA;AAAA,UACxB,GAAG,QAAQ,CAAA;AACX,UAAA,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,SAAS,CAAA;AAAA,QAChC;AAAA,MACF,GAAG,QAAQ,CAAA;AAEX,MAAA,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AAAA,IAC5B,CAAA;AAAA,EACF;AAAA,EAEA,eAAe,GAAA,EAAmB;AAChC,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AACjC,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,IAAA,CAAK,MAAA,CAAO,OAAO,GAAG,CAAA;AAAA,IACxB;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,OAAO,GAAG,CAAA;AAAA,EAC1B;AAAA,EAEA,YAAY,GAAA,EAAsB;AAChC,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAAA,EAC5B;AACF,CAAA;AAEO,IAAM,eAAA,GAAkB,IAAI,eAAA;AAC5B,IAAM,eAAA,GAAkB,IAAI,eAAA;AAE5B,SAAS,QAAA,CACd,IACA,KAAA,EACG;AACH,EAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,EAAA,EAAI,EAAE,OAAO,CAAA;AAC/C;AAEO,SAAS,QAAA,CACd,IACA,QAAA,EACG;AACH,EAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,EAAA,EAAI,EAAE,UAAU,CAAA;AAClD","file":"index.cjs","sourcesContent":["/**\n * Groq Error\n * @description Custom error class for Groq API operations.\n */\n\nimport { GroqErrorType } from \"../constants/error-types\";\n\nexport interface GroqErrorMetadata {\n readonly status?: number;\n readonly url?: string;\n readonly [key: string]: unknown;\n}\n\nexport class GroqError extends Error {\n public readonly type: GroqErrorType;\n public readonly cause?: Error;\n public readonly metadata: GroqErrorMetadata;\n\n constructor(\n type: GroqErrorType,\n message: string,\n cause?: Error,\n metadata: GroqErrorMetadata = {},\n ) {\n super(message);\n this.name = \"GroqError\";\n this.type = type;\n this.cause = cause;\n this.metadata = metadata;\n }\n\n override toString(): string {\n const statusPart =\n typeof this.metadata.status === \"number\" ? ` (HTTP ${this.metadata.status})` : \"\";\n return `${this.name} [${this.type}]: ${this.message}${statusPart}`;\n }\n\n toJSON(): {\n name: string;\n type: GroqErrorType;\n message: string;\n metadata: GroqErrorMetadata;\n } {\n return {\n name: this.name,\n type: this.type,\n message: this.message,\n metadata: this.metadata,\n };\n }\n}\n","/**\n * Error Types\n * @description Error type enum and user-friendly message table.\n * The classification logic (status → type, type → retryable, ...)\n * lives in the validators/ and resolvers/ folders; this file\n * only contains the enum and the message table.\n */\n\nexport enum GroqErrorType {\n INVALID_API_KEY = \"INVALID_API_KEY\",\n MISSING_CONFIG = \"MISSING_CONFIG\",\n NETWORK_ERROR = \"NETWORK_ERROR\",\n ABORT_ERROR = \"ABORT_ERROR\",\n RATE_LIMIT_ERROR = \"RATE_LIMIT_ERROR\",\n SERVER_ERROR = \"SERVER_ERROR\",\n CLIENT_ERROR = \"CLIENT_ERROR\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nexport const USER_FRIENDLY_ERROR_MESSAGES: Readonly<Record<GroqErrorType, string>> = {\n [GroqErrorType.INVALID_API_KEY]: \"Please check your Groq API key and try again.\",\n [GroqErrorType.MISSING_CONFIG]: \"The provider is not configured. Please call configureProvider first.\",\n [GroqErrorType.NETWORK_ERROR]: \"Network error. Please check your connection and try again.\",\n [GroqErrorType.ABORT_ERROR]: \"Request was cancelled.\",\n [GroqErrorType.RATE_LIMIT_ERROR]: \"You've reached the rate limit. Please wait a moment and try again.\",\n [GroqErrorType.SERVER_ERROR]: \"Groq service is temporarily unavailable. Please try again later.\",\n [GroqErrorType.CLIENT_ERROR]: \"The request was invalid. Please check your input and try again.\",\n [GroqErrorType.UNKNOWN_ERROR]: \"An unexpected error occurred. Please try again.\",\n};\n","/**\n * Groq Constants\n * @description Available models and default configurations\n */\n\n/**\n * Available Groq models\n */\nexport const GROQ_MODELS = {\n /** Llama 3.1 8B - Fast and efficient (560 T/s) */\n LLAMA_3_1_8B_INSTANT: \"llama-3.1-8b-instant\",\n /** Llama 3.3 70B - Versatile and powerful (280 T/s) */\n LLAMA_3_3_70B_VERSATILE: \"llama-3.3-70b-versatile\",\n /** Llama 3.1 70B - Versatile (280 T/s) */\n LLAMA_3_1_70B_VERSATILE: \"llama-3.1-70b-versatile\",\n /** GPT-OSS 20B - Experimental (1000 T/s) */\n GPT_OSS_20B: \"openai/gpt-oss-20b\",\n /** GPT-OSS 120B - Large experimental model */\n GPT_OSS_120B: \"openai/gpt-oss-120b\",\n /** Mixtral 8x7b - MoE model */\n MIXTRAL_8X7B: \"mixtral-8x7b-32768\",\n /** Gemma 2 9B - Google's model */\n GEMMA_2_9B: \"gemma2-9b-it\",\n /** Llama 4 Scout 17B - New model (30K T/s) */\n LLAMA_4_SCOUT_17B: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n /** Kimi K2 - Moonshot AI model */\n KIMI_K2_INSTRUCT: \"moonshotai/kimi-k2-instruct\",\n /** Qwen 3 32B - Alibaba's model */\n QWEN3_32B: \"qwen/qwen3-32b\",\n} as const;\n\n/**\n * Default models for different use cases\n */\nexport const DEFAULT_MODELS = {\n TEXT: GROQ_MODELS.LLAMA_3_1_8B_INSTANT,\n FAST: GROQ_MODELS.LLAMA_3_1_8B_INSTANT,\n EXPERIMENTAL: GROQ_MODELS.GPT_OSS_20B,\n} as const;\n\n/**\n * Default generation configuration\n */\nexport const DEFAULT_GENERATION_CONFIG = {\n temperature: 0.7,\n maxTokens: 1024,\n topP: 1.0,\n} as const;\n\n/**\n * API endpoints\n */\nexport const API_ENDPOINTS = {\n CHAT: \"/chat/completions\",\n} as const;\n\n/**\n * Default base URL\n */\nexport const DEFAULT_BASE_URL = \"https://api.groq.com/openai/v1\" as const;\n\n/**\n * Default timeouts\n */\nexport const TIMEOUTS = {\n DEFAULT: 30000, // 30 seconds\n STREAMING: 60000, // 60 seconds\n} as const;\n","/**\n * Identifier Constants\n * @description Prefixes and identifiers used across the package\n */\n\nexport const MESSAGE_ID_PREFIX = \"msg-\" as const;\nexport const CHAT_MESSAGE_ID_SUFFIX_LENGTH = 9;\nexport const CACHE_KEY_TYPE_COMPLETION = \"completion\" as const;\nexport const CACHE_KEY_TYPE_CHAT = \"chat\" as const;\nexport const CACHE_KEY_TYPE_RESPONSE = \"response\" as const;\nexport const SYSTEM_PROMPT_CACHE_PREFIX = \"system-prompt\" as const;\n\nexport const USER_ROLE = \"user\" as const;\nexport const ASSISTANT_ROLE = \"assistant\" as const;\nexport const SYSTEM_ROLE = \"system\" as const;\n\nexport const QUEUE_PRIORITY_USER_REQUEST = 10;\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_INITIAL_DELAY_MS = 1000;\nexport const DEFAULT_RETRY_MAX_DELAY_MS = 10000;\nexport const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2;\nexport const DEFAULT_RETRY_JITTER_FACTOR = 0.1;\n","/**\n * LRU Key Selector\n * @description Pure function: selects the least recently used key from\n * a collection of timestamped entries. Used by LRU caches\n * to choose which entry to evict when at capacity.\n *\n * @example\n * ```typescript\n * const entries = new Map([\n * [\"a\", { lastAccess: 100 }],\n * [\"b\", { lastAccess: 50 }],\n * [\"c\", { lastAccess: 200 }],\n * ]);\n * selectLeastRecentlyUsedKey(entries); // \"b\"\n * ```\n */\n\nexport interface AccessTimestamped {\n readonly lastAccess: number;\n}\n\nexport function selectLeastRecentlyUsedKey<K, V extends AccessTimestamped>(\n entries: ReadonlyMap<K, V>,\n): K | null {\n let oldestKey: K | null = null;\n let oldestAccess = Number.POSITIVE_INFINITY;\n\n for (const [key, entry] of entries.entries()) {\n if (entry.lastAccess < oldestAccess) {\n oldestAccess = entry.lastAccess;\n oldestKey = key;\n }\n }\n\n return oldestKey;\n}\n","/**\n * Cache Hit Rate Calculator\n * @description Pure function: computes the average access count\n * per cache entry, used to surface cache effectiveness\n * in dynamic statistics displays.\n *\n * @example\n * ```typescript\n * calculateCacheHitRate([\n * { accessCount: 5 },\n * { accessCount: 3 },\n * { accessCount: 0 },\n * ]); // 2.67\n *\n * calculateCacheHitRate([]); // 0\n * ```\n */\n\nexport interface AccessCounted {\n readonly accessCount: number;\n}\n\nexport function calculateCacheHitRate(\n entries: ReadonlyArray<AccessCounted>,\n): number {\n if (entries.length === 0) return 0;\n const totalAccess = entries.reduce((sum, e) => sum + e.accessCount, 0);\n return totalAccess / entries.length;\n}\n","/**\n * Cache Key Builder\n * @description Pure function: builds a stable cache key from a\n * parameter object by sorting its keys and JSON-stringifying.\n * No hardcoded values.\n *\n * @example\n * ```typescript\n * buildCacheKey({ b: 1, a: 2 }); // '{\"a\":2,\"b\":1}'\n * buildCacheKey({ model: \"x\", prompt: \"hi\" });\n * ```\n */\n\nexport function buildCacheKey(params: Readonly<Record<string, unknown>>): string {\n const sortedKeys = Object.keys(params).sort();\n const sortedParams: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n sortedParams[key] = params[key];\n }\n return JSON.stringify(sortedParams);\n}\n","/**\n * Cache Manager\n * @description LRU cache for API responses with TTL. Delegates:\n * - LRU key selection → calculations/lru-key-selector\n * - Cache key construction → builders/cache-key-builder\n * - Hit rate calculation → calculations/cache-hit-rate\n */\n\nimport { selectLeastRecentlyUsedKey } from \"../calculations/lru-key-selector\";\nimport { calculateCacheHitRate } from \"../calculations/cache-hit-rate\";\nimport { buildCacheKey } from \"../builders/cache-key-builder\";\n\ninterface CacheEntry<T> {\n readonly value: T;\n readonly timestamp: number;\n accessCount: number;\n lastAccess: number;\n}\n\nexport interface CacheOptions {\n /** Maximum number of entries. Default 100. */\n readonly maxSize?: number;\n /** Time-to-live in milliseconds. Default 5 minutes. */\n readonly ttl?: number;\n}\n\nconst DEFAULT_CACHE_MAX_SIZE = 100;\nconst DEFAULT_CACHE_TTL_MS = 300_000;\n\nexport class CacheManager {\n private readonly cache = new Map<string, CacheEntry<unknown>>();\n private readonly maxSize: number;\n private readonly ttl: number;\n\n constructor(options: CacheOptions = {}) {\n this.maxSize = options.maxSize ?? DEFAULT_CACHE_MAX_SIZE;\n this.ttl = options.ttl ?? DEFAULT_CACHE_TTL_MS;\n }\n\n get<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n if (this.isExpired(entry)) {\n this.cache.delete(key);\n return null;\n }\n entry.accessCount += 1;\n entry.lastAccess = Date.now();\n return entry.value as T;\n }\n\n set<T>(key: string, value: T): void {\n if (this.cache.size >= this.maxSize && !this.cache.has(key)) {\n const lruKey = selectLeastRecentlyUsedKey(this.cache);\n if (lruKey !== null) this.cache.delete(lruKey);\n }\n this.cache.set(key, {\n value,\n timestamp: Date.now(),\n accessCount: 1,\n lastAccess: Date.now(),\n });\n }\n\n has(key: string): boolean {\n const entry = this.cache.get(key);\n return entry !== undefined && !this.isExpired(entry);\n }\n\n delete(key: string): boolean {\n return this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n /** Build a stable cache key from a parameter object. */\n generateKey(params: Readonly<Record<string, unknown>>): string {\n return buildCacheKey(params);\n }\n\n /**\n * Dynamic cache statistics. All numbers are computed at call time\n * from the current state; nothing is hardcoded.\n */\n getStats(): CacheStats {\n const now = Date.now();\n const entries = Array.from(this.cache.entries()).map(([key, entry]) => ({\n key,\n accessCount: entry.accessCount,\n ageMs: now - entry.timestamp,\n }));\n const hitRate = calculateCacheHitRate(\n Array.from(this.cache.values()).map((e) => ({ accessCount: e.accessCount })),\n );\n return {\n size: this.cache.size,\n maxSize: this.maxSize,\n hitRate,\n entries,\n };\n }\n\n private isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() - entry.timestamp > this.ttl;\n }\n}\n\nexport interface CacheStats {\n readonly size: number;\n readonly maxSize: number;\n readonly hitRate: number;\n readonly entries: ReadonlyArray<{\n readonly key: string;\n readonly accessCount: number;\n readonly ageMs: number;\n }>;\n}\n\nexport const cacheManager = new CacheManager();\n","/**\n * Groq Request Builder\n * @description Builder for constructing GroqChatRequest instances\n * from a domain intent (model + messages + generation config).\n * Implements the Builder pattern; each method is fluent.\n */\n\nimport type { GroqChatRequest, GroqMessage, GroqGenerationConfig } from \"../entities\";\nimport { DEFAULT_GENERATION_CONFIG } from \"../constants/groq.constants\";\n\ninterface MutableRequest {\n model: string;\n messages: GroqMessage[];\n temperature?: number;\n max_tokens?: number;\n top_p?: number;\n n?: number;\n stop?: string[];\n frequency_penalty?: number;\n presence_penalty?: number;\n stream?: boolean;\n}\n\nexport class GroqChatRequestBuilder {\n private readonly model: string;\n private messages: GroqMessage[] = [];\n private generationConfig: GroqGenerationConfig = {};\n private streamEnabled = false;\n\n constructor(model: string) {\n this.model = model;\n }\n\n static for(model: string): GroqChatRequestBuilder {\n return new GroqChatRequestBuilder(model);\n }\n\n withMessages(messages: ReadonlyArray<GroqMessage>): this {\n this.messages = [...messages];\n return this;\n }\n\n withConfig(config: GroqGenerationConfig | undefined): this {\n this.generationConfig = config ? { ...config } : {};\n return this;\n }\n\n withStream(stream: boolean): this {\n this.streamEnabled = stream;\n return this;\n }\n\n build(): GroqChatRequest {\n const cfg = this.generationConfig;\n const request: MutableRequest = {\n model: this.model,\n messages: this.messages,\n temperature: cfg.temperature ?? DEFAULT_GENERATION_CONFIG.temperature,\n max_tokens: cfg.maxTokens ?? DEFAULT_GENERATION_CONFIG.maxTokens,\n top_p: cfg.topP ?? DEFAULT_GENERATION_CONFIG.topP,\n };\n\n if (cfg.n !== undefined) request.n = cfg.n;\n if (cfg.stop !== undefined) request.stop = cfg.stop;\n if (cfg.frequencyPenalty !== undefined) request.frequency_penalty = cfg.frequencyPenalty;\n if (cfg.presencePenalty !== undefined) request.presence_penalty = cfg.presencePenalty;\n if (this.streamEnabled) request.stream = true;\n\n return request as GroqChatRequest;\n }\n}\n","/**\n * Structured Prompt Builder\n * @description Builds user prompts that ask the model to emit JSON,\n * optionally constrained to a JSON Schema.\n */\n\nexport class StructuredPromptBuilder {\n private schema: Record<string, unknown> | undefined;\n private request: string;\n\n constructor(request: string) {\n this.request = request;\n }\n\n static for(request: string): StructuredPromptBuilder {\n return new StructuredPromptBuilder(request);\n }\n\n withSchema(schema: Record<string, unknown> | undefined): this {\n this.schema = schema;\n return this;\n }\n\n build(): string {\n const schemaSection = this.schema\n ? `Expected JSON schema:\\n${JSON.stringify(this.schema, null, 2)}\\n\\n`\n : \"\";\n\n return (\n \"Please generate a JSON response for the following request.\\n\\n\" +\n schemaSection +\n `Request:\\n${this.request}\\n\\n` +\n \"Respond only with valid JSON, formatted as:\\n```json\\n{...}\\n```\"\n );\n }\n}\n","/**\n * Protocol Constants\n * @description Network and protocol-level constants\n */\n\nexport const HTTP_HEADERS = {\n CONTENT_TYPE: \"Content-Type\",\n AUTHORIZATION: \"Authorization\",\n APPLICATION_JSON: \"application/json\",\n BEARER_PREFIX: \"Bearer \",\n} as const;\n\nexport const SSE_PREFIX = \"data: \" as const;\nexport const SSE_DONE_MARKER = \"[DONE]\" as const;\n\nexport const JSON_CODE_BLOCK_PATTERN = /```json\\n([\\s\\S]*?)\\n```/;\nexport const JSON_OBJECT_PATTERN = /\\{[\\s\\S]*\\}/;\n\nexport const CHAT_COMPLETIONS_PATH = \"/chat/completions\" as const;\n","/**\n * SSE Line Extractor\n * @description Pure functions for parsing Server-Sent Events (SSE)\n * lines as emitted by Groq's streaming endpoint. Handles\n * prefix detection, done-marker detection, and JSON\n * content extraction.\n *\n * @example\n * ```typescript\n * isSseDataLine(\"data: {...}\"); // true\n * extractSseDataPayload(\"data: {...}\"); // \"{...}\"\n * isSseDoneMarker(\"data: [DONE]\"); // true\n * extractContentFromSsePayload('{\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}');\n * // \"hi\"\n * ```\n */\n\nimport { SSE_DONE_MARKER, SSE_PREFIX } from \"../constants/protocol.constants\";\n\nexport interface SseChunkDelta {\n readonly choices?: ReadonlyArray<{\n readonly delta?: { readonly content?: string };\n }>;\n}\n\nexport function isSseDataLine(line: string): boolean {\n return line.startsWith(SSE_PREFIX);\n}\n\nexport function extractSseDataPayload(line: string): string {\n return line.slice(SSE_PREFIX.length);\n}\n\nexport function isSseDoneMarker(payload: string): boolean {\n return payload === SSE_DONE_MARKER;\n}\n\nexport function splitSseLines(rawChunk: string): ReadonlyArray<string> {\n return rawChunk.split(\"\\n\").map((l) => l.trim()).filter((l) => l.length > 0);\n}\n\nexport function extractContentFromSsePayload(payload: string): string | null {\n try {\n const parsed = JSON.parse(payload) as SseChunkDelta;\n return parsed.choices?.[0]?.delta?.content ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface NormalizedSseChunk {\n readonly payload: string;\n readonly isDone: boolean;\n}\n\n/**\n * Normalize a raw chunk into one or more `NormalizedSseChunk`s,\n * filtering out non-data lines and done markers.\n */\nexport function normalizeSseChunk(rawChunk: string): ReadonlyArray<NormalizedSseChunk> {\n const lines = splitSseLines(rawChunk);\n const result: NormalizedSseChunk[] = [];\n for (const line of lines) {\n if (!isSseDataLine(line)) continue;\n const payload = extractSseDataPayload(line);\n result.push({ payload, isDone: isSseDoneMarker(payload) });\n }\n return result;\n}\n","/**\n * Streaming Response Parser\n * @description Parses Server-Sent Events (SSE) from Groq streaming responses.\n * Delegates the line-level logic → parsers/sse-line-extractor.\n */\n\nimport { GroqError } from \"../utils/groq-error\";\nimport { GroqErrorType } from \"../constants/error-types\";\nimport {\n normalizeSseChunk,\n extractContentFromSsePayload,\n} from \"./sse-line-extractor\";\n\nexport interface StreamingParserCallbacks {\n readonly onChunk: (content: string) => void;\n}\n\nexport class StreamingResponseParser {\n private readonly decoder = new TextDecoder();\n\n constructor(private readonly callbacks: StreamingParserCallbacks) {}\n\n async parse(stream: ReadableStream<Uint8Array>): Promise<string> {\n const reader = stream.getReader();\n const contentChunks: string[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = this.decoder.decode(value, { stream: true });\n const normalized = normalizeSseChunk(chunk);\n\n for (const item of normalized) {\n if (item.isDone) continue;\n const content = extractContentFromSsePayload(item.payload);\n if (content !== null) {\n contentChunks.push(content);\n this.callbacks.onChunk(content);\n }\n }\n }\n } catch (error) {\n if (error instanceof GroqError) throw error;\n throw new GroqError(\n GroqErrorType.NETWORK_ERROR,\n \"Stream was interrupted\",\n error instanceof Error ? error : undefined,\n );\n } finally {\n reader.releaseLock();\n }\n\n return contentChunks.join(\"\");\n }\n}\n","/**\n * JSON Content Extractor\n * @description Pure functions for extracting a JSON payload from\n * model output that may wrap it in a markdown code fence.\n *\n * @example\n * ```typescript\n * extractJsonCandidate('```json\\n{\"a\":1}\\n```'); // '{\"a\":1}'\n * extractJsonCandidate('prefix {\"a\":1} suffix'); // '{\"a\":1}'\n * extractJsonCandidate('no json here'); // 'no json here'\n * ```\n */\n\nimport { JSON_CODE_BLOCK_PATTERN, JSON_OBJECT_PATTERN } from \"../constants/protocol.constants\";\n\nexport function extractJsonFromCodeFence(content: string): string | null {\n const match = content.match(JSON_CODE_BLOCK_PATTERN);\n if (match && match[1]) return match[1];\n return null;\n}\n\nexport function extractJsonObject(content: string): string | null {\n const match = content.match(JSON_OBJECT_PATTERN);\n if (match && match[0]) return match[0];\n return null;\n}\n\nexport function extractJsonCandidate(content: string): string {\n return (\n extractJsonFromCodeFence(content) ??\n extractJsonObject(content) ??\n content\n );\n}\n","/**\n * JSON Response Parser\n * @description Parses JSON payloads extracted by parsers/json-content-extractor.\n */\n\nimport { GroqError } from \"../utils/groq-error\";\nimport { GroqErrorType } from \"../constants/error-types\";\nimport { extractJsonCandidate } from \"./json-content-extractor\";\n\nexport class JsonResponseParser {\n parse<T>(rawContent: string): T {\n const candidate = extractJsonCandidate(rawContent);\n try {\n return JSON.parse(candidate) as T;\n } catch (error) {\n throw new GroqError(\n GroqErrorType.UNKNOWN_ERROR,\n \"Failed to parse structured response as JSON\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n}\n","/**\n * Message Factory and Transformer\n * @description Builders and converters for Groq messages\n */\n\nimport type { GroqMessage, GroqMessageRole } from \"../entities\";\n\nexport const createUserMessage = (content: string): GroqMessage => ({\n role: \"user\",\n content,\n});\n\nexport const createAssistantMessage = (content: string): GroqMessage => ({\n role: \"assistant\",\n content,\n});\n\nexport const createSystemMessage = (content: string): GroqMessage => ({\n role: \"system\",\n content,\n});\n\nexport const createMessage = (role: GroqMessageRole, content: string): GroqMessage => ({\n role,\n content,\n});\n\nexport const promptToMessages = (prompt: string): GroqMessage[] => [\n createUserMessage(prompt),\n];\n\nexport const extractTextFromMessages = (messages: ReadonlyArray<GroqMessage>): string =>\n messages.map((m) => m.content).join(\"\\n\\n\");\n\nexport const formatMessagesForDisplay = (\n messages: ReadonlyArray<GroqMessage>,\n): string =>\n messages\n .map((m) => `[${m.role.toUpperCase()}]: ${m.content}`)\n .join(\"\\n\\n---\\n\\n\");\n","/**\n * Text Generation Service\n * @description High-level text generation orchestrator. Coordinates:\n * - cache lookup/store\n * - request building\n * - HTTP transport\n * - response parsing (text / structured / streaming)\n *\n * No longer owns prompt construction (delegated to builder)\n * or JSON parsing (delegated to JsonResponseParser).\n */\n\nimport type {\n TextGenerationOptions,\n StreamingCallbacks,\n StructuredGenerationOptions,\n IGroqChatService,\n} from \"../interfaces\";\nimport type { GroqMessage } from \"../entities\";\nimport type { IGroqHttpClient } from \"../interfaces\";\nimport { GroqError } from \"../utils/groq-error\";\nimport { GroqErrorType } from \"../constants/error-types\";\nimport { DEFAULT_MODELS } from \"../constants/groq.constants\";\nimport {\n CACHE_KEY_TYPE_COMPLETION,\n CACHE_KEY_TYPE_CHAT,\n} from \"../constants/identifier.constants\";\nimport { CacheManager } from \"../utils/cache-manager\";\nimport { GroqChatRequestBuilder, StructuredPromptBuilder } from \"../builders\";\nimport { JsonResponseParser, StreamingResponseParser } from \"../parsers\";\nimport { createUserMessage } from \"../utils/message.util\";\n\nconst STRUCTURED_OUTPUT_TEMPERATURE = 0.1;\n\nexport class TextGenerationService implements IGroqChatService {\n private readonly jsonParser = new JsonResponseParser();\n\n constructor(\n private readonly httpClient: IGroqHttpClient,\n private readonly cache: CacheManager = new CacheManager(),\n ) {}\n\n generateCompletion(\n prompt: string,\n options: TextGenerationOptions = {},\n ): Promise<string> {\n const model = options.model ?? DEFAULT_MODELS.TEXT;\n\n return this.executeWithCache(\n {\n type: CACHE_KEY_TYPE_COMPLETION,\n model,\n prompt,\n config: options.generationConfig,\n },\n async () => {\n const request = GroqChatRequestBuilder.for(model)\n .withMessages([createUserMessage(prompt)])\n .withConfig(options.generationConfig)\n .build();\n const response = await this.httpClient.postChatCompletion(request);\n return this.extractContent(response.choices[0]?.message?.content);\n },\n );\n }\n\n generateChatCompletion(\n messages: ReadonlyArray<GroqMessage>,\n options: TextGenerationOptions = {},\n ): Promise<string> {\n const model = options.model ?? DEFAULT_MODELS.TEXT;\n\n return this.executeWithCache(\n {\n type: CACHE_KEY_TYPE_CHAT,\n model,\n messages: [...messages],\n config: options.generationConfig,\n },\n async () => {\n const request = GroqChatRequestBuilder.for(model)\n .withMessages(messages)\n .withConfig(options.generationConfig)\n .build();\n const response = await this.httpClient.postChatCompletion(request);\n return this.extractContent(response.choices[0]?.message?.content);\n },\n );\n }\n\n generateStructured<T>(\n prompt: string,\n options: StructuredGenerationOptions = {},\n ): Promise<T> {\n const model = options.model ?? DEFAULT_MODELS.TEXT;\n const jsonPrompt = StructuredPromptBuilder.for(prompt)\n .withSchema(options.schema)\n .build();\n\n const request = GroqChatRequestBuilder.for(model)\n .withMessages([createUserMessage(jsonPrompt)])\n .withConfig({\n ...options.generationConfig,\n temperature: STRUCTURED_OUTPUT_TEMPERATURE,\n })\n .build();\n\n return this.httpClient.postChatCompletion(request).then((response) => {\n const content = this.extractContent(response.choices[0]?.message?.content);\n return this.jsonParser.parse<T>(content);\n });\n }\n\n streamCompletion(\n prompt: string,\n callbacks: StreamingCallbacks,\n options: TextGenerationOptions = {},\n ): Promise<string> {\n return this.streamChatCompletion([createUserMessage(prompt)], callbacks, options);\n }\n\n /**\n * Stream a chat completion given an existing message history.\n * Resolves with the accumulated full text once the stream completes.\n *\n * @param messages - The full conversation history.\n * @param callbacks - Streaming callbacks (`onChunk`, `onComplete`, `onError`).\n * @param options - Generation options.\n * @returns The full accumulated text.\n */\n async streamChatCompletion(\n messages: ReadonlyArray<GroqMessage>,\n callbacks: StreamingCallbacks,\n options: TextGenerationOptions = {},\n ): Promise<string> {\n const model = options.model ?? DEFAULT_MODELS.TEXT;\n const request = GroqChatRequestBuilder.for(model)\n .withMessages(messages)\n .withConfig(options.generationConfig)\n .withStream(true)\n .build();\n\n const parser = new StreamingResponseParser({\n onChunk: (chunk) => callbacks.onChunk?.(chunk),\n });\n\n try {\n const stream = await this.httpClient.streamChatCompletion(request);\n const fullText = await parser.parse(stream);\n callbacks.onComplete?.(fullText);\n return fullText;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n callbacks.onError?.(err);\n throw err;\n }\n }\n\n /**\n * Clear the response cache (used by long-running services to free memory).\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n private async executeWithCache(\n params: Record<string, unknown>,\n factory: () => Promise<string>,\n ): Promise<string> {\n const key = this.cache.generateKey(params);\n const cached = this.cache.get<string>(key);\n if (cached !== null) {\n return cached;\n }\n const result = await factory();\n this.cache.set(key, result);\n return result;\n }\n\n private extractContent(content: string | undefined): string {\n if (!content) {\n throw new GroqError(\n GroqErrorType.UNKNOWN_ERROR,\n \"No content generated from Groq API\",\n );\n }\n return content;\n }\n}\n","/**\n * API Key Validator\n * @description Pure function: validates a Groq API key by length and\n * non-emptiness. No I/O, no hardcoded values.\n *\n * @example\n * ```typescript\n * isValidApiKey(\"gsk_abcdefghijklmnop\"); // true\n * isValidApiKey(\"short\"); // false\n * isValidApiKey(\"\"); // false\n * isValidApiKey(undefined); // false\n * ```\n */\n\nexport interface ApiKeyValidationRule {\n /** Minimum accepted length after trimming whitespace. */\n readonly minLength: number;\n}\n\nexport const DEFAULT_API_KEY_RULE: ApiKeyValidationRule = {\n minLength: 10,\n};\n\nexport function isValidApiKey(\n apiKey: string | undefined | null,\n rule: ApiKeyValidationRule = DEFAULT_API_KEY_RULE,\n): apiKey is string {\n if (!apiKey) return false;\n return apiKey.trim().length >= rule.minLength;\n}\n\nexport function validateApiKey(\n apiKey: string | undefined | null,\n rule: ApiKeyValidationRule = DEFAULT_API_KEY_RULE,\n): { valid: boolean; reason?: string } {\n if (!apiKey) {\n return { valid: false, reason: \"API key is required\" };\n }\n const trimmed = apiKey.trim();\n if (trimmed.length === 0) {\n return { valid: false, reason: \"API key cannot be empty\" };\n }\n if (trimmed.length < rule.minLength) {\n return {\n valid: false,\n reason: `API key must be at least ${rule.minLength} characters`,\n };\n }\n return { valid: true };\n}\n","/**\n * Groq Config Store\n * @description Single source of truth for the active GroqConfig.\n * Delegates key validation → validators/api-key-validator.\n */\n\nimport type { GroqConfig } from \"../entities\";\nimport { GroqError } from \"../utils/groq-error\";\nimport { GroqErrorType } from \"../constants/error-types\";\nimport { DEFAULT_BASE_URL, TIMEOUTS } from \"../constants/groq.constants\";\nimport { validateApiKey } from \"../validators/api-key-validator\";\n\nexport class GroqConfigStore {\n private config: GroqConfig | null = null;\n\n /**\n * Validate and persist the given config. Cancels any prior state\n * by overwriting (callers that need atomicity should use `reset()` first).\n *\n * @throws GroqError with type `INVALID_API_KEY` if validation fails.\n */\n initialize(config: GroqConfig): GroqConfig {\n const validation = validateApiKey(config.apiKey);\n if (!validation.valid) {\n throw new GroqError(GroqErrorType.INVALID_API_KEY, validation.reason ?? \"Invalid API key\");\n }\n\n const normalized: GroqConfig = {\n apiKey: config.apiKey.trim(),\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n timeoutMs: config.timeoutMs ?? TIMEOUTS.DEFAULT,\n ...(config.textModel !== undefined ? { textModel: config.textModel } : {}),\n };\n\n this.config = normalized;\n return normalized;\n }\n\n /**\n * Returns the active config or throws if not initialized.\n *\n * @throws GroqError with type `MISSING_CONFIG` when not initialized.\n */\n get(): GroqConfig {\n if (!this.config) {\n throw new GroqError(\n GroqErrorType.MISSING_CONFIG,\n \"Client not initialized. Call configureProvider first.\",\n );\n }\n return this.config;\n }\n\n getOrNull(): GroqConfig | null {\n return this.config;\n }\n\n isInitialized(): boolean {\n return this.config !== null;\n }\n\n /**\n * Replace the API key.\n *\n * @throws GroqError with type `MISSING_CONFIG` if not initialized,\n * or `INVALID_API_KEY` if the new key fails validation.\n */\n setApiKey(apiKey: string): void {\n const current = this.get();\n const validation = validateApiKey(apiKey);\n if (!validation.valid) {\n throw new GroqError(GroqErrorType.INVALID_API_KEY, validation.reason ?? \"Invalid API key\");\n }\n this.config = { ...current, apiKey: apiKey.trim() };\n }\n\n reset(): void {\n this.config = null;\n }\n}\n","/**\n * HTTP Status Classifier\n * @description Pure function: maps an HTTP status code to a\n * {@link GroqErrorType}. No hardcoded HTTP status codes\n * in the call sites; thresholds are explicit parameters.\n *\n * @example\n * ```typescript\n * classifyHttpStatus(401); // GroqErrorType.INVALID_API_KEY\n * classifyHttpStatus(429); // GroqErrorType.RATE_LIMIT_ERROR\n * classifyHttpStatus(500); // GroqErrorType.SERVER_ERROR\n * classifyHttpStatus(404); // GroqErrorType.CLIENT_ERROR\n * classifyHttpStatus(200); // GroqErrorType.UNKNOWN_ERROR\n * ```\n */\n\nimport { GroqErrorType } from \"../constants/error-types\";\n\nexport interface HttpStatusClassificationRule {\n readonly unauthorizedStatuses: ReadonlySet<number>;\n readonly rateLimitedStatus: number;\n readonly serverErrorThreshold: number;\n readonly clientErrorThreshold: number;\n}\n\nexport const DEFAULT_HTTP_STATUS_RULE: HttpStatusClassificationRule = {\n unauthorizedStatuses: new Set([401, 403]),\n rateLimitedStatus: 429,\n serverErrorThreshold: 500,\n clientErrorThreshold: 400,\n};\n\nexport function classifyHttpStatus(\n status: number,\n rule: HttpStatusClassificationRule = DEFAULT_HTTP_STATUS_RULE,\n): GroqErrorType {\n if (rule.unauthorizedStatuses.has(status)) return GroqErrorType.INVALID_API_KEY;\n if (status === rule.rateLimitedStatus) return GroqErrorType.RATE_LIMIT_ERROR;\n if (status >= rule.serverErrorThreshold) return GroqErrorType.SERVER_ERROR;\n if (status >= rule.clientErrorThreshold) return GroqErrorType.CLIENT_ERROR;\n return GroqErrorType.UNKNOWN_ERROR;\n}\n","/**\n * Response Error Message Extractor\n * @description Extracts the user-facing error message from a Groq\n * error response body. Returns a sensible fallback\n * when the body is missing or not JSON.\n *\n * @example\n * ```typescript\n * const msg = await extractErrorMessageFromResponse(response);\n * // \"Rate limit exceeded\" or \"HTTP 429: Too Many Requests\"\n * ```\n */\n\nimport { GroqErrorType } from \"../constants/error-types\";\n\nexport interface GroqErrorBody {\n readonly error?: { readonly message?: string };\n}\n\nexport function extractErrorMessageFromJsonBody(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const candidate = body as GroqErrorBody;\n const message = candidate.error?.message;\n if (typeof message === \"string\" && message.length > 0) return message;\n return null;\n}\n\nexport function buildHttpStatusFallback(status: number, statusText: string): string {\n const trimmedStatusText = statusText.trim();\n if (trimmedStatusText.length > 0) {\n return `HTTP ${status}: ${trimmedStatusText}`;\n }\n return `HTTP ${status}`;\n}\n\nexport async function extractErrorMessageFromResponse(response: Response): Promise<string> {\n try {\n const body = (await response.json()) as unknown;\n const fromBody = extractErrorMessageFromJsonBody(body);\n if (fromBody) return fromBody;\n } catch {\n // Body wasn't JSON; fall through.\n }\n return buildHttpStatusFallback(response.status, response.statusText);\n}\n\n/**\n * Lightweight helper for logging: returns a stable string for any\n * error type without throwing.\n */\nexport function describeGroqErrorType(type: GroqErrorType): string {\n return `GroqError[${type}]`;\n}\n","/**\n * Groq HTTP Transport\n * @description Low-level transport. Delegates:\n * - error body parsing → extractors/response-error-message-extractor\n * - status classification → validators/http-status-classifier\n */\n\nimport type { GroqChatRequest, GroqChatResponse } from \"../entities\";\nimport { GroqError, GroqErrorMetadata } from \"../utils/groq-error\";\nimport { GroqErrorType } from \"../constants/error-types\";\nimport { TIMEOUTS } from \"../constants/groq.constants\";\nimport { classifyHttpStatus } from \"../validators/http-status-classifier\";\nimport {\n extractErrorMessageFromResponse,\n} from \"../extractors/response-error-message-extractor\";\nimport { HTTP_HEADERS, CHAT_COMPLETIONS_PATH } from \"../constants/protocol.constants\";\nimport type { GroqConfigStore } from \"./groq-config-store\";\n\nexport class GroqHttpTransport {\n private readonly pendingAbortControllers = new Set<AbortController>();\n\n constructor(private readonly configStore: GroqConfigStore) {}\n\n cancelPendingRequests(): void {\n for (const controller of this.pendingAbortControllers) {\n controller.abort();\n }\n this.pendingAbortControllers.clear();\n }\n\n async postChatCompletion(request: GroqChatRequest): Promise<GroqChatResponse> {\n return this.request<GroqChatResponse>(CHAT_COMPLETIONS_PATH, {\n ...request,\n stream: false,\n });\n }\n\n async streamChatCompletion(request: GroqChatRequest): Promise<ReadableStream<Uint8Array>> {\n const config = this.configStore.get();\n const url = `${config.baseUrl}${CHAT_COMPLETIONS_PATH}`;\n const timeout = config.timeoutMs ?? TIMEOUTS.STREAMING;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n this.pendingAbortControllers.add(controller);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: this.buildHeaders(config.apiKey),\n body: JSON.stringify({ ...request, stream: true }),\n signal: controller.signal,\n });\n\n if (!response.ok) await this.throwFromErrorResponse(response);\n\n if (!response.body) {\n throw new GroqError(GroqErrorType.NETWORK_ERROR, \"Response body is null\");\n }\n\n return response.body;\n } catch (error) {\n throw this.normalizeError(error);\n } finally {\n clearTimeout(timeoutId);\n this.pendingAbortControllers.delete(controller);\n }\n }\n\n private async request<T>(endpoint: string, body: unknown): Promise<T> {\n const config = this.configStore.get();\n const url = `${config.baseUrl}${endpoint}`;\n const timeout = config.timeoutMs ?? TIMEOUTS.DEFAULT;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n this.pendingAbortControllers.add(controller);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: this.buildHeaders(config.apiKey),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) await this.throwFromErrorResponse(response);\n\n return (await response.json()) as T;\n } catch (error) {\n throw this.normalizeError(error);\n } finally {\n clearTimeout(timeoutId);\n this.pendingAbortControllers.delete(controller);\n }\n }\n\n private buildHeaders(apiKey: string): HeadersInit {\n return {\n [HTTP_HEADERS.CONTENT_TYPE]: HTTP_HEADERS.APPLICATION_JSON,\n [HTTP_HEADERS.AUTHORIZATION]: `${HTTP_HEADERS.BEARER_PREFIX}${apiKey}`,\n };\n }\n\n private async throwFromErrorResponse(response: Response): Promise<never> {\n const errorMessage = await extractErrorMessageFromResponse(response);\n const metadata: GroqErrorMetadata = {\n status: response.status,\n url: response.url,\n };\n throw new GroqError(\n classifyHttpStatus(response.status),\n errorMessage,\n undefined,\n metadata,\n );\n }\n\n private normalizeError(error: unknown): GroqError {\n if (error instanceof GroqError) return error;\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n return new GroqError(\n GroqErrorType.ABORT_ERROR,\n \"Request was aborted by the client\",\n error,\n );\n }\n if (error.name === \"TypeError\" && error.message.toLowerCase().includes(\"network\")) {\n return new GroqError(\n GroqErrorType.NETWORK_ERROR,\n \"Network error: Unable to connect to Groq API\",\n error,\n );\n }\n }\n\n return new GroqError(\n GroqErrorType.UNKNOWN_ERROR,\n error instanceof Error ? error.message : \"Unknown error occurred\",\n error instanceof Error ? error : undefined,\n );\n }\n}\n","/**\n * Request Deduplicator Utility\n * @description Prevents duplicate in-flight API calls for the same request\n */\n\ninterface PendingRequest<T> {\n readonly promise: Promise<T>;\n readonly timestamp: number;\n}\n\nconst DEFAULT_DEDUPE_TTL_MS = 30_000;\n\nexport class RequestDeduplicator {\n private readonly pendingRequests = new Map<string, PendingRequest<unknown>>();\n private readonly ttl: number;\n\n constructor(ttl: number = DEFAULT_DEDUPE_TTL_MS) {\n this.ttl = ttl;\n }\n\n execute<T>(key: string, requestFn: () => Promise<T>): Promise<T> {\n this.cleanup();\n\n const existing = this.pendingRequests.get(key);\n if (existing) {\n return existing.promise as Promise<T>;\n }\n\n const promise = requestFn();\n this.pendingRequests.set(key, {\n promise,\n timestamp: Date.now(),\n });\n\n promise.finally(() => {\n this.pendingRequests.delete(key);\n });\n\n return promise;\n }\n\n cancelAll(): void {\n this.pendingRequests.clear();\n }\n\n private cleanup(): void {\n const now = Date.now();\n for (const [key, request] of this.pendingRequests.entries()) {\n if (now - request.timestamp > this.ttl) {\n this.pendingRequests.delete(key);\n }\n }\n }\n}\n\nexport const requestDeduplicator = new RequestDeduplicator();\n","/**\n * Request Queue Manager Utility\n * @description Manages concurrent requests with priority and limits\n */\n\ninterface QueuedRequest<T> {\n readonly id: string;\n readonly priority: number;\n readonly requestFn: () => Promise<T>;\n readonly resolve: (value: T) => void;\n readonly reject: (reason: unknown) => void;\n readonly timestamp: number;\n}\n\nexport interface QueueOptions {\n readonly maxConcurrent?: number;\n readonly defaultPriority?: number;\n readonly requestTimeout?: number;\n}\n\nconst DEFAULT_MAX_CONCURRENT = 3;\nconst DEFAULT_PRIORITY = 0;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\nexport class RequestQueue {\n private queue: QueuedRequest<unknown>[] = [];\n private readonly activeRequests = new Set<string>();\n private readonly maxConcurrent: number;\n private readonly defaultPriority: number;\n private readonly requestTimeout: number;\n private requestIdCounter = 0;\n\n constructor(options: QueueOptions = {}) {\n this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;\n this.defaultPriority = options.defaultPriority ?? DEFAULT_PRIORITY;\n this.requestTimeout = options.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS;\n }\n\n add<T>(requestFn: () => Promise<T>, priority?: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = `req-${++this.requestIdCounter}`;\n const queuedRequest: QueuedRequest<T> = {\n id,\n priority: priority ?? this.defaultPriority,\n requestFn,\n resolve: resolve as (value: unknown) => void,\n reject,\n timestamp: Date.now(),\n };\n\n this.queue.push(queuedRequest as QueuedRequest<unknown>);\n this.sortQueue();\n this.process();\n });\n }\n\n cancelAll(): void {\n for (const request of this.queue) {\n request.reject(new Error(\"Request was cancelled\"));\n }\n this.queue = [];\n }\n\n private sortQueue(): void {\n this.queue.sort((a, b) => {\n if (a.priority !== b.priority) {\n return b.priority - a.priority;\n }\n return a.timestamp - b.timestamp;\n });\n }\n\n private process(): void {\n while (this.queue.length > 0 && this.activeRequests.size < this.maxConcurrent) {\n const request = this.queue.shift();\n if (!request) break;\n this.executeRequest(request);\n }\n }\n\n private executeRequest<T>(request: QueuedRequest<T>): void {\n this.activeRequests.add(request.id);\n\n const timeoutId = setTimeout(() => {\n this.activeRequests.delete(request.id);\n request.reject(new Error(`Request ${request.id} timed out`));\n this.process();\n }, this.requestTimeout);\n\n request.requestFn()\n .then((result) => {\n clearTimeout(timeoutId);\n request.resolve(result);\n })\n .catch((error: unknown) => {\n clearTimeout(timeoutId);\n request.reject(error);\n })\n .finally(() => {\n this.activeRequests.delete(request.id);\n this.process();\n });\n }\n}\n\nexport const requestQueue = new RequestQueue();\n","/**\n * Exponential Backoff Calculator\n * @description Pure function: computes a retry delay using\n * exponential backoff with optional jitter.\n * No hardcoded values: all parameters are explicit.\n *\n * Formula:\n * base = initialDelay * (backoffMultiplier ^ (attempt - 1))\n * capped = min(base, maxDelay)\n * jitter = capped * jitterFactor * (random * 2 - 1)\n * final = max(0, capped + jitter)\n *\n * @example\n * ```typescript\n * calculateExponentialBackoff({\n * attempt: 1,\n * initialDelay: 1000,\n * maxDelay: 10_000,\n * backoffMultiplier: 2,\n * jitterFactor: 0.1,\n * }); // ~1000ms (with small jitter)\n * ```\n */\n\nexport interface ExponentialBackoffParams {\n /** 1-based attempt number. */\n readonly attempt: number;\n /** Initial delay in milliseconds. */\n readonly initialDelay: number;\n /** Maximum delay cap in milliseconds. */\n readonly maxDelay: number;\n /** Multiplier applied per attempt (commonly 2). */\n readonly backoffMultiplier: number;\n /** Jitter factor (0 = no jitter, 0.5 = ±50%). */\n readonly jitterFactor: number;\n /** Random source in [0, 1). Defaults to Math.random. */\n readonly random?: () => number;\n}\n\nexport function calculateExponentialBackoff(params: ExponentialBackoffParams): number {\n const {\n attempt,\n initialDelay,\n maxDelay,\n backoffMultiplier,\n jitterFactor,\n random = Math.random,\n } = params;\n\n const base = initialDelay * Math.pow(backoffMultiplier, Math.max(0, attempt - 1));\n const capped = Math.min(base, maxDelay);\n const jitterMultiplier = random() * 2 - 1;\n const jitter = capped * jitterFactor * jitterMultiplier;\n\n return Math.max(0, capped + jitter);\n}\n","/**\n * Error Classifier\n * @description Pure functions: classify a GroqErrorType into actionable\n * categories (retryable, auth-related, etc.).\n * No hardcoded error types in the call sites; the sets\n * are explicit and configurable.\n *\n * @example\n * ```typescript\n * isRetryableErrorType(GroqErrorType.RATE_LIMIT_ERROR); // true\n * isRetryableErrorType(GroqErrorType.INVALID_API_KEY); // false\n * isAuthErrorType(GroqErrorType.INVALID_API_KEY); // true\n * ```\n */\n\nimport { GroqErrorType } from \"../constants/error-types\";\n\nconst DEFAULT_RETRYABLE_TYPES: ReadonlySet<GroqErrorType> = new Set([\n GroqErrorType.NETWORK_ERROR,\n GroqErrorType.RATE_LIMIT_ERROR,\n GroqErrorType.SERVER_ERROR,\n]);\n\nconst DEFAULT_AUTH_TYPES: ReadonlySet<GroqErrorType> = new Set([\n GroqErrorType.INVALID_API_KEY,\n]);\n\nexport interface ErrorClassificationRule {\n readonly retryable: ReadonlySet<GroqErrorType>;\n readonly auth: ReadonlySet<GroqErrorType>;\n}\n\nexport const DEFAULT_ERROR_CLASSIFICATION_RULE: ErrorClassificationRule = {\n retryable: DEFAULT_RETRYABLE_TYPES,\n auth: DEFAULT_AUTH_TYPES,\n};\n\nexport function isRetryableErrorType(\n type: GroqErrorType,\n rule: ErrorClassificationRule = DEFAULT_ERROR_CLASSIFICATION_RULE,\n): boolean {\n return rule.retryable.has(type);\n}\n\nexport function isAuthErrorType(\n type: GroqErrorType,\n rule: ErrorClassificationRule = DEFAULT_ERROR_CLASSIFICATION_RULE,\n): boolean {\n return rule.auth.has(type);\n}\n","/**\n * Retry Manager\n * @description Orchestrates retry logic for failed requests. Delegates\n * the actual delay math → calculations/exponential-backoff\n * and the error classification → validators/error-classifier.\n * No hardcoded values; all rules are explicit parameters.\n */\n\nimport { GroqError } from \"./groq-error\";\nimport { calculateExponentialBackoff } from \"../calculations/exponential-backoff\";\nimport {\n isRetryableErrorType,\n DEFAULT_ERROR_CLASSIFICATION_RULE,\n} from \"../validators/error-classifier\";\nimport {\n DEFAULT_RETRY_MAX_ATTEMPTS,\n DEFAULT_RETRY_INITIAL_DELAY_MS,\n DEFAULT_RETRY_MAX_DELAY_MS,\n DEFAULT_RETRY_BACKOFF_MULTIPLIER,\n DEFAULT_RETRY_JITTER_FACTOR,\n} from \"../constants/identifier.constants\";\n\nexport interface RetryOptions {\n readonly maxAttempts?: number;\n readonly initialDelay?: number;\n readonly maxDelay?: number;\n readonly backoffMultiplier?: number;\n readonly jitterFactor?: number;\n /** Custom retry predicate; bypasses the default error-type classifier. */\n readonly shouldRetry?: (error: Error) => boolean;\n}\n\nconst RETRYABLE_MESSAGE_KEYWORDS: ReadonlyArray<string> = [\n \"network\",\n \"timeout\",\n \"econnrefused\",\n \"enotfound\",\n \"etimedout\",\n];\n\nexport class RetryManager {\n private readonly defaults: Required<\n Pick<RetryOptions, \"maxAttempts\" | \"initialDelay\" | \"maxDelay\" | \"backoffMultiplier\" | \"jitterFactor\">\n >;\n\n constructor() {\n this.defaults = {\n maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,\n initialDelay: DEFAULT_RETRY_INITIAL_DELAY_MS,\n maxDelay: DEFAULT_RETRY_MAX_DELAY_MS,\n backoffMultiplier: DEFAULT_RETRY_BACKOFF_MULTIPLIER,\n jitterFactor: DEFAULT_RETRY_JITTER_FACTOR,\n };\n }\n\n async execute<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const maxAttempts = options.maxAttempts ?? this.defaults.maxAttempts;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n if (attempt >= maxAttempts || !this.shouldRetry(lastError, options)) {\n throw lastError;\n }\n\n const delay = calculateExponentialBackoff({\n attempt,\n initialDelay: options.initialDelay ?? this.defaults.initialDelay,\n maxDelay: options.maxDelay ?? this.defaults.maxDelay,\n backoffMultiplier: options.backoffMultiplier ?? this.defaults.backoffMultiplier,\n jitterFactor: options.jitterFactor ?? this.defaults.jitterFactor,\n });\n await this.delay(delay);\n }\n }\n\n throw lastError ?? new Error(\"Retry loop exited without result\");\n }\n\n private shouldRetry(error: Error, options: RetryOptions): boolean {\n if (options.shouldRetry) return options.shouldRetry(error);\n\n if (error instanceof GroqError) {\n return isRetryableErrorType(error.type, DEFAULT_ERROR_CLASSIFICATION_RULE);\n }\n\n const lower = error.message.toLowerCase();\n return RETRYABLE_MESSAGE_KEYWORDS.some((kw) => lower.includes(kw));\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\nexport const retryManager = new RetryManager();\n\n/** Convenience function: execute `fn` with the default retry manager. */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return retryManager.execute(fn, options);\n}\n","/**\n * Retry Executor Strategy\n * @description Wraps a request function with retry logic.\n *\n * @example\n * ```typescript\n * const executor = new RetryExecutor(retryManager, { maxAttempts: 5 });\n * await executor.execute(unreliableRequest, payload);\n * ```\n */\n\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport { RetryManager, RetryOptions } from \"../utils/retry\";\n\nexport class RetryExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly retryManager: RetryManager,\n private readonly options?: RetryOptions,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n return this.retryManager.execute(() => fn(...args), this.options);\n }\n}\n","/**\n * Queue Executor Strategy\n * @description Wraps a request function with a concurrency-limiting queue.\n *\n * @example\n * ```typescript\n * const executor = new QueueExecutor(queue, 10); // priority 10\n * await executor.execute(someRequest, payload);\n * ```\n */\n\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport { RequestQueue } from \"../utils/request-queue.util\";\n\nexport class QueueExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly queue: RequestQueue,\n private readonly priority: number,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n return this.queue.add(() => fn(...args), this.priority);\n }\n}\n","/**\n * Dedupe Executor Strategy\n * @description Coalesces in-flight requests with the same key\n */\n\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\nimport type { RequestDeduplicator } from \"../utils/request-deduplicator.util\";\n\nexport type KeyGenerator<TArgs extends unknown[]> = (...args: TArgs) => string;\n\nexport interface DedupeExecutorOptions<TArgs extends unknown[]> {\n readonly generateKey: KeyGenerator<TArgs>;\n}\n\nexport class DedupeExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n constructor(\n private readonly deduplicator: RequestDeduplicator,\n private readonly options: DedupeExecutorOptions<TArgs>,\n ) {}\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n const key = this.options.generateKey(...args);\n return this.deduplicator.execute(key, () => fn(...args));\n }\n}\n","/**\n * Composite Executor Strategy\n * @description Chains multiple IRequestExecutor instances.\n * Order matters: the OUTERMOST executor wraps the others.\n * Execution flows top-to-bottom on the way in,\n * bottom-to-top on the way out.\n *\n * Example with [Dedupe, Retry, Queue]:\n * Dedupe -> Retry -> Queue -> fn\n */\n\nimport type { IRequestExecutor } from \"./request-executor.strategy\";\n\ntype AnyExecutor = IRequestExecutor<unknown[], unknown>;\n\nexport class CompositeExecutor<TArgs extends unknown[], TResult>\n implements IRequestExecutor<TArgs, TResult>\n{\n private readonly executors: ReadonlyArray<AnyExecutor>;\n\n constructor(executors: ReadonlyArray<IRequestExecutor<TArgs, TResult>>) {\n this.executors = executors as unknown as ReadonlyArray<AnyExecutor>;\n }\n\n execute(fn: (...args: TArgs) => Promise<TResult>, ...args: TArgs): Promise<TResult> {\n const composed = this.compress(fn as unknown as (...a: unknown[]) => Promise<unknown>);\n return composed(...args) as Promise<TResult>;\n }\n\n private compress(fn: (...args: unknown[]) => Promise<unknown>): (...args: unknown[]) => Promise<unknown> {\n return this.executors.reduceRight(\n (innerFn, executor) => (...a: unknown[]) => executor.execute(innerFn, ...a),\n fn,\n );\n }\n}\n","/**\n * Groq HTTP Client\n * @description Facade that wires the transport together with the\n * request executor strategies (retry, queue, deduplication).\n */\n\nimport type { GroqChatRequest, GroqChatResponse, GroqConfig } from \"../entities\";\nimport type { IGroqHttpClient } from \"../interfaces\";\nimport type { IRequestExecutor } from \"../strategies/request-executor.strategy\";\nimport { GroqConfigStore } from \"./groq-config-store\";\nimport { GroqHttpTransport } from \"./groq-http-transport\";\nimport { RequestDeduplicator } from \"../utils/request-deduplicator.util\";\nimport { RequestQueue } from \"../utils/request-queue.util\";\nimport { RetryManager } from \"../utils/retry\";\nimport { CompositeExecutor, DedupeExecutor, QueueExecutor, RetryExecutor } from \"../strategies\";\nimport { QUEUE_PRIORITY_USER_REQUEST } from \"../constants/identifier.constants\";\n\nexport interface GroqHttpClientDeps {\n readonly configStore?: GroqConfigStore;\n readonly transport?: GroqHttpTransport;\n readonly retryManager?: RetryManager;\n readonly queue?: RequestQueue;\n readonly deduplicator?: RequestDeduplicator;\n}\n\nexport class GroqHttpClient implements IGroqHttpClient {\n private readonly configStore: GroqConfigStore;\n private readonly transport: GroqHttpTransport;\n private readonly executor: IRequestExecutor<[GroqChatRequest], GroqChatResponse>;\n\n constructor(deps: GroqHttpClientDeps = {}) {\n this.configStore = deps.configStore ?? new GroqConfigStore();\n this.transport =\n deps.transport ?? new GroqHttpTransport(this.configStore);\n\n const retryManager = deps.retryManager ?? new RetryManager();\n const queue = deps.queue ?? new RequestQueue();\n const deduplicator = deps.deduplicator ?? new RequestDeduplicator();\n\n this.executor = new CompositeExecutor<[GroqChatRequest], GroqChatResponse>([\n new DedupeExecutor<[GroqChatRequest], GroqChatResponse>(deduplicator, {\n generateKey: (request) =>\n deduplicatorKey(\n request as unknown as GroqChatRequest,\n this.configStore.get().apiKey,\n ),\n }),\n new RetryExecutor<[GroqChatRequest], GroqChatResponse>(retryManager),\n new QueueExecutor<[GroqChatRequest], GroqChatResponse>(\n queue,\n QUEUE_PRIORITY_USER_REQUEST,\n ),\n ]);\n }\n\n initialize(config: GroqConfig): void {\n this.configStore.initialize(config);\n }\n\n cancelPendingRequests(): void {\n this.transport.cancelPendingRequests();\n }\n\n isInitialized(): boolean {\n return this.configStore.isInitialized();\n }\n\n getApiKey(): string {\n return this.configStore.get().apiKey;\n }\n\n setApiKey(apiKey: string): void {\n this.configStore.setApiKey(apiKey);\n }\n\n postChatCompletion(request: GroqChatRequest): Promise<GroqChatResponse> {\n return this.executor.execute(\n (req) => this.transport.postChatCompletion(req),\n request,\n );\n }\n\n streamChatCompletion(request: GroqChatRequest): Promise<ReadableStream<Uint8Array>> {\n return this.transport.streamChatCompletion(request);\n }\n\n reset(): void {\n this.transport.cancelPendingRequests();\n this.configStore.reset();\n }\n}\n\nfunction deduplicatorKey(request: GroqChatRequest, apiKey: string): string {\n const { model, messages, stream: _stream, ...rest } = request;\n const stable = JSON.stringify({\n apiKey,\n model,\n messages: messages.map((m) => ({ role: m.role, content: m.content })),\n ...rest,\n });\n return stable;\n}\n","/**\n * User-Friendly Error Resolver\n * @description Maps any thrown value (Error, GroqError, string, etc.)\n * to a user-facing string suitable for display. No I/O,\n * no hardcoded user-facing strings: the mapping table\n * is explicit and overridable.\n *\n * @example\n * ```typescript\n * resolveUserFriendlyErrorMessage(new GroqError(GroqErrorType.RATE_LIMIT_ERROR, \"x\"));\n * // \"You've reached the rate limit. Please wait a moment and try again.\"\n * ```\n */\n\nimport { GroqError } from \"../utils/groq-error\";\nimport { GroqErrorType, USER_FRIENDLY_ERROR_MESSAGES } from \"../constants/error-types\";\n\n/**\n * Keyword-based fallback messages. Used when the error is not a\n * {@link GroqError} and we want to do best-effort classification\n * by string matching.\n */\nconst KEYWORD_FALLBACK_RULES: ReadonlyArray<{ keywords: ReadonlyArray<string>; type: GroqErrorType }> = [\n { keywords: [\"api key\", \"unauthorized\"], type: GroqErrorType.INVALID_API_KEY },\n { keywords: [\"rate limit\"], type: GroqErrorType.RATE_LIMIT_ERROR },\n { keywords: [\"network\", \"fetch\"], type: GroqErrorType.NETWORK_ERROR },\n { keywords: [\"abort\"], type: GroqErrorType.ABORT_ERROR },\n];\n\nexport function resolveUserFriendlyErrorMessage(error: unknown): string {\n if (error instanceof GroqError) {\n return USER_FRIENDLY_ERROR_MESSAGES[error.type];\n }\n\n if (error instanceof Error) {\n const lower = error.message.toLowerCase();\n for (const rule of KEYWORD_FALLBACK_RULES) {\n if (rule.keywords.some((kw) => lower.includes(kw))) {\n return USER_FRIENDLY_ERROR_MESSAGES[rule.type];\n }\n }\n if (error.message.length > 0) return error.message;\n }\n\n return USER_FRIENDLY_ERROR_MESSAGES[GroqErrorType.UNKNOWN_ERROR];\n}\n","/**\n * Error Resolver\n * @description Resolves any thrown value to a user-friendly message.\n * Delegates the actual classification → resolvers/user-friendly-error-resolver.\n */\n\nimport { resolveUserFriendlyErrorMessage } from \"../resolvers/user-friendly-error-resolver\";\nimport { GroqError } from \"./groq-error\";\nimport { GroqErrorType, USER_FRIENDLY_ERROR_MESSAGES } from \"../constants/error-types\";\nimport type { GroqErrorMetadata } from \"./groq-error\";\n\nexport const resolveUserFriendlyMessage = resolveUserFriendlyErrorMessage;\n\nexport interface LoggedError {\n readonly message: string;\n readonly type: string;\n readonly stack?: string;\n readonly metadata?: GroqErrorMetadata;\n}\n\nexport function formatErrorForLogging(error: unknown): LoggedError {\n if (error instanceof GroqError) {\n return {\n message: error.message,\n type: error.type,\n stack: error.stack,\n metadata: error.metadata,\n };\n }\n if (error instanceof Error) {\n return { message: error.message, type: error.name, stack: error.stack };\n }\n return { message: String(error), type: typeof error };\n}\n\nexport { GroqErrorType, USER_FRIENDLY_ERROR_MESSAGES };\n","/**\n * useGroq Hook\n * @description React hook for Groq text generation.\n * Each component instance owns its own AbortController\n * so unmounting one component does NOT cancel requests\n * issued by other consumers. Use `cancel()` to abort\n * an in-flight request from the same component.\n *\n * @example\n * ```tsx\n * import { useGroq, getProvider } from \"@umituz/web-ai-groq-provider\";\n *\n * function MyComponent() {\n * const { generate, isLoading, error, result, cancel } = useGroq(\n * { model: \"llama-3.3-70b-versatile\" },\n * { textGeneration: getProvider()!.textGeneration },\n * );\n * // ...\n * }\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { GroqGenerationConfig } from \"../entities\";\nimport type { StreamingCallbacks } from \"../interfaces\";\nimport type { TextGenerationService } from \"../services\";\nimport { resolveUserFriendlyMessage } from \"../utils/error-resolver\";\n\nexport interface UseGroqOptions {\n readonly model?: string;\n readonly generationConfig?: GroqGenerationConfig;\n readonly onStart?: () => void;\n readonly onSuccess?: (result: string) => void;\n readonly onError?: (error: string) => void;\n}\n\nexport interface UseGroqReturn {\n readonly isLoading: boolean;\n readonly error: string | null;\n readonly result: string | null;\n /** Generate a completion from a single prompt. */\n generate: (prompt: string, options?: GroqGenerationConfig) => Promise<string | null>;\n /** Generate a structured JSON completion. */\n generateJSON: <T = Record<string, unknown>>(\n prompt: string,\n options?: GroqGenerationConfig & { schema?: Record<string, unknown> },\n ) => Promise<T | null>;\n /** Stream a completion. Returns the full text. */\n stream: (\n prompt: string,\n onChunk: (chunk: string) => void,\n options?: GroqGenerationConfig,\n ) => Promise<string | null>;\n /** Cancel any in-flight request issued by this hook instance. */\n cancel: () => void;\n /** Reset the hook state to its initial values. Does not clear the cache. */\n reset: () => void;\n /** Clear the error state. */\n clearError: () => void;\n}\n\nexport interface UseGroqDeps {\n readonly textGeneration: TextGenerationService;\n}\n\nexport function useGroq(\n options: UseGroqOptions = {},\n deps?: UseGroqDeps,\n): UseGroqReturn {\n const textGeneration = deps?.textGeneration;\n\n if (!textGeneration) {\n throw new Error(\n \"useGroq requires a TextGenerationService dependency. \" +\n \"Provide it via the second argument or wire it through the app container.\",\n );\n }\n\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [result, setResult] = useState<string | null>(null);\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n // Component-scoped abort controller: only this component's requests are cancelled.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stableConfig = useMemo(\n () => ({\n model: options.model,\n generationConfig: options.generationConfig,\n }),\n [\n options.model,\n options.generationConfig?.temperature,\n options.generationConfig?.maxTokens,\n options.generationConfig?.topP,\n ],\n );\n\n useEffect(() => {\n const controller = new AbortController();\n abortControllerRef.current = controller;\n return () => {\n controller.abort();\n abortControllerRef.current = null;\n };\n }, []);\n\n const runWithState = useCallback(\n async <T>(task: (signal: AbortSignal) => Promise<T>): Promise<T | null> => {\n const controller = abortControllerRef.current;\n if (!controller) {\n // Already unmounted.\n return null;\n }\n const { signal } = controller;\n if (signal.aborted) return null;\n\n setIsLoading(true);\n setError(null);\n setResult(null);\n const currentOptions = optionsRef.current;\n currentOptions.onStart?.();\n try {\n const value = await task(signal);\n return value;\n } catch (err) {\n if (signal.aborted) {\n // Caller chose to cancel; suppress error propagation.\n return null;\n }\n const message = resolveUserFriendlyMessage(err);\n setError(message);\n currentOptions.onError?.(message);\n throw err;\n } finally {\n if (!signal.aborted) {\n setIsLoading(false);\n }\n }\n },\n [],\n );\n\n const generate = useCallback(\n (prompt: string, config?: GroqGenerationConfig) =>\n runWithState(async () => {\n const response = await textGeneration.generateCompletion(prompt, {\n model: stableConfig.model,\n generationConfig: {\n ...stableConfig.generationConfig,\n ...config,\n },\n });\n setResult(response);\n optionsRef.current.onSuccess?.(response);\n return response;\n }),\n [runWithState, textGeneration, stableConfig],\n );\n\n const generateJSON = useCallback(\n <T = Record<string, unknown>,>(\n prompt: string,\n config?: GroqGenerationConfig & { schema?: Record<string, unknown> },\n ) =>\n runWithState(async () => {\n const response = await textGeneration.generateStructured<T>(prompt, {\n model: stableConfig.model,\n generationConfig: {\n ...stableConfig.generationConfig,\n ...config,\n },\n ...(config?.schema !== undefined ? { schema: config.schema } : {}),\n });\n const json = JSON.stringify(response, null, 2);\n setResult(json);\n optionsRef.current.onSuccess?.(json);\n return response;\n }),\n [runWithState, textGeneration, stableConfig],\n );\n\n const stream = useCallback(\n (\n prompt: string,\n onChunk: (chunk: string) => void,\n config?: GroqGenerationConfig,\n ) =>\n runWithState(async () => {\n const callbacks: StreamingCallbacks = {\n onChunk,\n onComplete: (text) => {\n setResult(text);\n optionsRef.current.onSuccess?.(text);\n },\n };\n return textGeneration.streamCompletion(\n prompt,\n callbacks,\n {\n model: stableConfig.model,\n generationConfig: {\n ...stableConfig.generationConfig,\n ...config,\n },\n },\n );\n }),\n [runWithState, textGeneration, stableConfig],\n );\n\n const cancel = useCallback(() => {\n abortControllerRef.current?.abort();\n setIsLoading(false);\n }, []);\n\n const reset = useCallback(() => {\n cancel();\n setError(null);\n setResult(null);\n }, [cancel]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return {\n isLoading,\n error,\n result,\n generate,\n generateJSON,\n stream,\n cancel,\n reset,\n clearError,\n };\n}\n","/**\n * useCacheStats Hook\n * @description React hook that exposes dynamic, real-time statistics\n * of the active CacheManager. The numbers are computed\n * on every interval tick — no value is hardcoded.\n *\n * @example\n * ```tsx\n * function CacheDebug() {\n * const stats = useCacheStats({ pollIntervalMs: 2000 });\n * return <pre>{JSON.stringify(stats, null, 2)}</pre>;\n * }\n * ```\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { CacheManager, CacheStats } from \"../utils/cache-manager\";\n\nexport interface UseCacheStatsOptions {\n /** Polling interval in milliseconds. Default 1000. */\n readonly pollIntervalMs?: number;\n /** When false, polling is paused and the last snapshot is returned. */\n readonly enabled?: boolean;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1000;\n\nexport function useCacheStats(\n cache: CacheManager,\n options: UseCacheStatsOptions = {},\n): CacheStats {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const enabled = options.enabled ?? true;\n\n const [snapshot, setSnapshot] = useState<CacheStats>(() => cache.getStats());\n\n useEffect(() => {\n if (!enabled) return;\n setSnapshot(cache.getStats());\n const intervalId = setInterval(() => {\n setSnapshot(cache.getStats());\n }, pollIntervalMs);\n return () => clearInterval(intervalId);\n }, [cache, pollIntervalMs, enabled]);\n\n return snapshot;\n}\n","/**\n * Timing Window Calculator\n * @description Pure function: computes time-based decisions for\n * debounce and throttle logic. No hardcoded values.\n *\n * @example\n * ```typescript\n * shouldCallOnLeadingEdge({\n * now: Date.now(),\n * lastCallTime: 0,\n * interval: 1000,\n * leadingEnabled: true,\n * isThrottled: false,\n * }); // true\n * ```\n */\n\nexport interface LeadingEdgeParams {\n readonly now: number;\n readonly lastCallTime: number;\n readonly interval: number;\n readonly leadingEnabled: boolean;\n readonly isThrottled: boolean;\n}\n\nexport function shouldCallOnLeadingEdge(params: LeadingEdgeParams): boolean {\n const { now, lastCallTime, interval, leadingEnabled, isThrottled } = params;\n if (!leadingEnabled) return false;\n if (isThrottled) return false;\n return now - lastCallTime >= interval;\n}\n\nexport interface TrailingDelayParams {\n readonly interval: number;\n readonly timeSinceLastCall: number;\n}\n\nexport function calculateTrailingDelay(params: TrailingDelayParams): number {\n return Math.max(0, params.interval - params.timeSinceLastCall);\n}\n\nexport function isWithinWindow(now: number, lastCallTime: number, interval: number): boolean {\n return now - lastCallTime < interval;\n}\n","/**\n * Debounce and Throttle\n * @description Rate limiting utilities. Delegates timing math\n * → calculations/timing-window.\n */\n\nimport {\n shouldCallOnLeadingEdge,\n calculateTrailingDelay,\n} from \"../calculations/timing-window\";\n\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\nexport interface DebounceOptions {\n readonly delay?: number;\n readonly leading?: boolean;\n readonly trailing?: boolean;\n}\n\nexport interface ThrottleOptions {\n readonly interval?: number;\n readonly leading?: boolean;\n readonly trailing?: boolean;\n}\n\nconst DEFAULT_DEBOUNCE_DELAY_MS = 300;\nconst DEFAULT_THROTTLE_INTERVAL_MS = 1000;\n\nexport class DebounceManager {\n private readonly timers = new Map<string, TimerHandle>();\n private readonly lastArgs = new Map<string, readonly unknown[]>();\n\n debounce<T extends (...args: never[]) => unknown>(\n fn: T,\n options: DebounceOptions = {},\n ): T {\n const delay = options.delay ?? DEFAULT_DEBOUNCE_DELAY_MS;\n const leading = options.leading ?? false;\n const trailing = options.trailing ?? true;\n\n let timer: TimerHandle | null = null;\n let lastCallTime = 0;\n let lastResult: unknown;\n\n return ((...args: never[]) => {\n const now = Date.now();\n const shouldCallLeading = shouldCallOnLeadingEdge({\n now,\n lastCallTime,\n interval: delay,\n leadingEnabled: leading,\n isThrottled: timer !== null,\n });\n\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n\n if (shouldCallLeading) {\n lastCallTime = now;\n lastResult = fn(...args);\n return lastResult;\n }\n\n if (trailing) {\n timer = setTimeout(() => {\n timer = null;\n lastCallTime = Date.now();\n lastResult = fn(...args);\n }, delay);\n }\n\n return lastResult;\n }) as T;\n }\n\n debounceByKey<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n delay: number = DEFAULT_DEBOUNCE_DELAY_MS,\n ): T {\n return ((...args: never[]) => {\n this.lastArgs.set(key, args);\n const existingTimer = this.timers.get(key);\n if (existingTimer) clearTimeout(existingTimer);\n\n const timer = setTimeout(() => {\n this.timers.delete(key);\n const pendingArgs = this.lastArgs.get(key);\n this.lastArgs.delete(key);\n if (pendingArgs) fn(...(pendingArgs as never[]));\n }, delay);\n\n this.timers.set(key, timer);\n }) as T;\n }\n\n cancelDebounce(key: string): void {\n const timer = this.timers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n this.lastArgs.delete(key);\n }\n\n flushDebounce<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n ): void {\n this.cancelDebounce(key);\n const args = this.lastArgs.get(key);\n if (args) {\n fn(...(args as never[]));\n this.lastArgs.delete(key);\n }\n }\n}\n\nexport class ThrottleManager {\n private readonly timers = new Map<string, TimerHandle>();\n private readonly lastArgs = new Map<string, readonly unknown[]>();\n\n throttle<T extends (...args: never[]) => unknown>(\n fn: T,\n options: ThrottleOptions = {},\n ): T {\n const interval = options.interval ?? DEFAULT_THROTTLE_INTERVAL_MS;\n const leading = options.leading ?? true;\n const trailing = options.trailing ?? false;\n\n let timer: TimerHandle | null = null;\n let lastCallTime = 0;\n let lastResult: unknown;\n let pendingArgs: readonly unknown[] | null = null;\n\n return ((...args: never[]) => {\n const now = Date.now();\n const timeSinceLastCall = now - lastCallTime;\n const shouldCall = shouldCallOnLeadingEdge({\n now,\n lastCallTime,\n interval,\n leadingEnabled: leading,\n isThrottled: timer !== null,\n });\n pendingArgs = args;\n\n if (shouldCall) {\n lastCallTime = now;\n lastResult = fn(...args);\n return lastResult;\n }\n\n if (trailing && !timer) {\n const delay = calculateTrailingDelay({ interval, timeSinceLastCall });\n timer = setTimeout(() => {\n timer = null;\n lastCallTime = Date.now();\n if (pendingArgs) {\n lastResult = fn(...(pendingArgs as never[]));\n pendingArgs = null;\n }\n }, delay);\n }\n\n return lastResult;\n }) as T;\n }\n\n throttleByKey<T extends (...args: never[]) => unknown>(\n key: string,\n fn: T,\n interval: number = DEFAULT_THROTTLE_INTERVAL_MS,\n ): T {\n return ((...args: never[]) => {\n const existingTimer = this.timers.get(key);\n if (existingTimer) {\n this.lastArgs.set(key, args);\n return;\n }\n\n fn(...args);\n\n const timer = setTimeout(() => {\n this.timers.delete(key);\n const pendingArgs = this.lastArgs.get(key);\n if (pendingArgs) {\n this.lastArgs.delete(key);\n fn(...(pendingArgs as never[]));\n const nextTimer = setTimeout(() => {\n this.timers.delete(key);\n }, interval);\n this.timers.set(key, nextTimer);\n }\n }, interval);\n\n this.timers.set(key, timer);\n }) as T;\n }\n\n cancelThrottle(key: string): void {\n const timer = this.timers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n this.lastArgs.delete(key);\n }\n\n isThrottled(key: string): boolean {\n return this.timers.has(key);\n }\n}\n\nexport const debounceManager = new DebounceManager();\nexport const throttleManager = new ThrottleManager();\n\nexport function debounce<T extends (...args: never[]) => unknown>(\n fn: T,\n delay?: number,\n): T {\n return debounceManager.debounce(fn, { delay });\n}\n\nexport function throttle<T extends (...args: never[]) => unknown>(\n fn: T,\n interval?: number,\n): T {\n return throttleManager.throttle(fn, { interval });\n}\n"]}