import { toVideos } from "./igdb-videos.js"; import { z } from "zod"; import { config } from "./config.js"; import { igdbLogger } from "./logger.js"; import { storage } from "./storage.js"; import { db } from "./db.js"; import { userSettings } from "./db/tables.js"; import { logger } from "./logger.js"; import { safeFetch } from "./ssrf.js"; import type { DownloadCategory } from "@shared/download-categorizer"; // Configuration constants for search limits const MAX_SEARCH_ATTEMPTS = 5; // IGDB status value for Early Access games export const IGDB_EARLY_ACCESS_STATUS = 4; // Shared field list for all IGDB game queries const IGDB_GAME_FIELDS = "name, summary, cover.url, first_release_date, rating, aggregated_rating, aggregated_rating_count, platforms.name, genres.name, themes.name, age_ratings.category, age_ratings.rating, screenshots.url, videos.name, videos.video_id, websites.url, websites.category, involved_companies.company.name, involved_companies.developer, involved_companies.publisher, status, game_type, category, version_parent.id, version_parent.name, expansions.name, expansions.cover.url, expansions.first_release_date, expansions.game_type, expansions.url, game_modes.name"; // IGDB theme name flagged as adult content (Erotic) const ADULT_THEME_NAMES = new Set(["Erotic"]); // IGDB AgeRating: category 1 = ESRB, 2 = PEGI; rating 12 = ESRB "Adults Only", 5 = PEGI "Eighteen" const ADULT_AGE_RATINGS = [ { category: 1, rating: 12 }, // ESRB Adults Only (AO) { category: 2, rating: 5 }, // PEGI 18 ]; type ContentFlagSource = { themes?: IGDBGame["themes"] | undefined; age_ratings?: IGDBGame["age_ratings"] | undefined; }; function hasEroticTheme(igdbGame: ContentFlagSource): boolean { return igdbGame.themes?.some((t) => ADULT_THEME_NAMES.has(t.name)) ?? false; } function mapIGDBGameType(gameType?: number): DownloadCategory { if (gameType === 14) return "update"; if ([1, 2, 4, 6, 7, 13].includes(gameType ?? -1)) return "dlc"; if ([5].includes(gameType ?? -1)) return "extra"; return "main"; } function hasAdultAgeRating(igdbGame: ContentFlagSource): boolean { return ( igdbGame.age_ratings?.some((r) => ADULT_AGE_RATINGS.some((a) => a.category === r.category && a.rating === r.rating) ) ?? false ); } export interface IGDBGame { id: number; name: string; summary?: string; cover?: { id: number; url: string; }; first_release_date?: number; rating?: number; aggregated_rating?: number; aggregated_rating_count?: number; platforms?: Array<{ id: number; name: string; }>; genres?: Array<{ id: number; name: string; }>; themes?: Array<{ id: number; name: string; }>; age_ratings?: Array<{ category: number; rating: number; }>; screenshots?: Array<{ id: number; url: string; }>; game_modes?: Array<{ id: number; name: string; }>; videos?: Array<{ name?: string; video_id?: string; }>; websites?: Array<{ category: number; url: string; }>; involved_companies?: Array<{ company: { name: string }; developer: boolean; publisher: boolean; }>; status?: number; game_type?: number; // IGDB's "category" field on the game entity itself (distinct from // download-categorizer's DownloadCategory): 0 = main game, 8 = remake, // 9 = remaster, etc. Not used for filtering today, just carried through. category?: number; // Present when this game entity is an edition/version of another game // (e.g. "Cyberpunk 2077: Ultimate Edition" -> version_parent points at // "Cyberpunk 2077"). Used by canonicalizeVersionedGames to collapse // editions into a single canonical search result. version_parent?: { id: number; name?: string }; expansions?: Array<{ id: number; name: string; cover?: { url: string }; first_release_date?: number; game_type?: number; url?: string; }>; } export interface TimeToBeat { hastily?: number | undefined; normally?: number | undefined; completely?: number | undefined; } export interface IGDBContentRef { id: number; name: string; cover?: { url: string }; first_release_date?: number; game_type?: number; themes?: IGDBGame["themes"] | undefined; age_ratings?: IGDBGame["age_ratings"] | undefined; } /** A game with the add-on content IGDB links to it (expansions, DLC, standalone expansions). */ export interface IGDBGameContent extends IGDBContentRef { summary?: string; expansions?: IGDBContentRef[]; dlcs?: IGDBContentRef[]; standalone_expansions?: IGDBContentRef[]; } export interface DiscoverFilters { query?: string | undefined; themes: number[]; gameModes: number[]; perspectives: number[]; genres: number[]; languages: number[]; excludeThemes: number[]; excludeGameModes: number[]; excludeGenres: number[]; minYear?: number | undefined; } export interface DiscoveredGame extends IGDBGame { game_modes?: Array<{ id: number; name: string }>; player_perspectives?: Array<{ id: number; name: string }>; } interface SearchGamesOptions { includeUndated?: boolean; undatedFirst?: boolean; platformId?: number; releaseYear?: number; } interface IGDBAuthResponse { access_token: string; expires_in: number; token_type: string; } const igdbWebsiteSchema = z.object({ category: z.number(), url: z.string().url(), }); /** * Sanitizes user input for use in IGDB API queries. * * IGDB uses a custom query language called Apicalypse. This function provides * defense-in-depth by removing characters that could be used for query injection, * complementing backend validation at the route level. * * Characters removed and rationale: * - Quotes (' "): String delimiters that could break out of string context * - Semicolons (;): Statement separators that could inject additional commands * - Ampersands (&) and Pipes (|): Logical operators for query conditions * - Asterisks (*): Wildcard operators (we control their placement in queries) * - Parentheses (()): Grouping operators for complex conditions * - Angle brackets (<>): Comparison operators * - Backslashes (\): Escape characters * - Square brackets ([]): Array/collection operators * - Backticks (`): Sometimes used for execution or string templating * * The 100-character limit prevents abuse through extremely long inputs that * could cause performance issues or circumvent other security measures. */ // ⚡ Bolt: Move regex compilation outside the function to avoid recompilation on every call. const SPECIAL_CHARS_REGEX = /['"`;|&*()<>[\]]/g; const WHITESPACE_REGEX = /\s+/g; /** * Value for an exact-equality match inside a double-quoted IGDB string literal. Unlike * `sanitizeIgdbInput` it keeps punctuation ("Role-playing (RPG)", "Hack and slash/Beat 'em up"), * which is harmless inside quotes; only what could end the literal or the query is removed. */ function exactIgdbStringValue(input: string): string { return [...input] .filter((ch) => ch !== '"' && ch !== "\\" && ch !== ";" && ch.charCodeAt(0) > 0x1f) .join("") .replace(WHITESPACE_REGEX, " ") .trim() .slice(0, 100); } function sanitizeIgdbInput(input: string): string { return input .replace(SPECIAL_CHARS_REGEX, "") // Remove special characters including square brackets .replace(WHITESPACE_REGEX, " ") // Normalize whitespace .trim() .slice(0, 100); // Limit length to prevent abuse } /** * Strip diacritics ("Pokémon" -> "Pokemon") so searches match regardless of accents. * Only used for matching; displayed IGDB titles are never altered. */ export function foldDiacritics(input: string): string { return input .normalize("NFD") .replace(/\p{M}+/gu, "") .normalize("NFC"); } // Retry configuration for rate-limited requests const MAX_RETRY_ATTEMPTS = 3; const BASE_RETRY_DELAY_MS = 1000; // Constants for query thresholds const MIN_RATING_THRESHOLD = 60; const MIN_RATING_COUNT = 3; const HIGH_RATING_THRESHOLD = 70; const HIGH_RATING_COUNT = 5; const MAX_LIMIT = 100; const MAX_OFFSET = 10000; const HOUR_IN_SECONDS = 3600; const FALLBACK_PLATFORMS: Array<{ id: number; name: string }> = [ { id: 6, name: "PC (Microsoft Windows)" }, { id: 48, name: "PlayStation 4" }, { id: 167, name: "PlayStation 5" }, { id: 49, name: "Xbox One" }, { id: 169, name: "Xbox Series X|S" }, { id: 130, name: "Nintendo Switch" }, { id: 41, name: "Wii U" }, { id: 19, name: "Super Nintendo Entertainment System" }, { id: 24, name: "Game Boy Advance" }, { id: 29, name: "Sega Mega Drive/Genesis" }, ]; // ⚡ Bolt: Define a cache entry interface for in-memory caching. interface CacheEntry { data: T; expiry: number; } class IGDBClient { private accessToken: string | null = null; private tokenExpiry: number = 0; // ⚡ Bolt: Use a Map for in-memory caching to store API responses and reduce redundant calls. // eslint-disable-next-line @typescript-eslint/no-explicit-any private cache = new Map>(); private async postProcessSearchResults( results: IGDBGame[], limit: number, options: SearchGamesOptions = {} ): Promise { // Canonicalize (collapse edition/version entries into their base game) // FIRST, before platformId/releaseYear filtering and date-based // ordering. An edition's platform list or first_release_date can // differ from its canonical parent's, so those filters/sort must be // evaluated against the actual game being returned to the caller, not // against the edition's own metadata. This is also why searchGames // deliberately omits platformId/releaseYear from the upstream IGDB // `where` clause: filtering upstream would let IGDB drop an edition // whose own metadata doesn't match before it ever reaches this // function, even when its canonical parent would. Truncation to // `limit` happens only once, at the very end, after filtering and // ordering are finalized. const canonicalResults = await this.canonicalizeVersionedGames(results); let yearRange: { start: number; end: number } | null = null; if (options.releaseYear) { yearRange = { start: Math.floor(Date.UTC(options.releaseYear, 0, 1) / 1000), end: Math.floor(Date.UTC(options.releaseYear + 1, 0, 1) / 1000), }; } const filteredResults = canonicalResults.filter((game) => { if (options.platformId && !game.platforms?.some((p) => p.id === options.platformId)) { return false; } if (yearRange) { if ( typeof game.first_release_date !== "number" || game.first_release_date < yearRange.start || game.first_release_date >= yearRange.end ) { return false; } } return true; }); const datedResults = filteredResults .filter((game) => typeof game.first_release_date === "number") .sort((left, right) => (right.first_release_date ?? 0) - (left.first_release_date ?? 0)); if (options.includeUndated === false) { return datedResults.slice(0, limit); } const undatedResults = filteredResults.filter( (game) => typeof game.first_release_date !== "number" ); const orderedResults = options.undatedFirst ? [...undatedResults, ...datedResults] : [...datedResults, ...undatedResults]; return orderedResults.slice(0, limit); } /** * IGDB models editions ("Gold Edition", "Deluxe Edition", ...) as separate * game entities linked to their base game via `version_parent`. Collapse * every edition in `results` down to its canonical (base) game, batch * fetching any canonical games not already present in `results`, then * dedupe by canonical id (first occurrence wins, so `results`' existing * order determines which edition's position each canonical game keeps). * * Does NOT filter, sort, or truncate to a limit -- callers apply * platform/year filtering and date-based ordering against the * canonicalized (parent) game metadata, then truncate to the requested * limit themselves, since an edition's platform list or release date can * differ from its canonical parent's. * * Never throws: if fetching parent games fails, this logs and falls back * to the original (uncanonicalized) entries. */ private async canonicalizeVersionedGames(results: IGDBGame[]): Promise { const resultById = new Map(results.map((game) => [game.id, game] as const)); const parentIdsToFetch = Array.from( new Set( results .map((game) => game.version_parent?.id) .filter((id): id is number => id != null && !resultById.has(id)) ) ); let fetchedParentsById = new Map(); if (parentIdsToFetch.length > 0) { try { // getGamesByIds does its own internal chunking/rate-limit pacing and // deliberately skips the shared per-request queue for that (see its // `skipQueue: true` makeRequest calls) so its batches aren't // serialized one-request-at-a-time like everything else. That's fine // for a single call, but two concurrent searchGames() calls can each // reach here at once and race on the shared lastRequestTime it reads // to pace itself, so their batches can overlap and jointly exceed // the configured rate limit. Route the whole call through the shared // queue so at most one canonicalization parent-fetch (and no other // queued IGDB request) runs at a time. const parents = await this.queueRequest(() => this.getGamesByIds(parentIdsToFetch)); fetchedParentsById = new Map(parents.map((game) => [game.id, game] as const)); } catch (error) { igdbLogger.warn( { error, parentIdsToFetch }, "failed to fetch version_parent games for canonicalization; falling back to uncanonicalized results" ); return results; } } const seenCanonicalIds = new Set(); const canonical: IGDBGame[] = []; for (const game of results) { const parentId = game.version_parent?.id; const canonicalGame = parentId != null ? (resultById.get(parentId) ?? fetchedParentsById.get(parentId) ?? game) : game; if (seenCanonicalIds.has(canonicalGame.id)) continue; seenCanonicalIds.add(canonicalGame.id); canonical.push(canonicalGame); } return canonical; } /** * Verifies a Client ID/Secret pair against Twitch/IGDB directly, without touching the * singleton's cached token or the stored/env credentials. Used by the "Test connection" * button in settings and the setup wizard, so a typo or expired secret is caught before * saving rather than surfacing later as a failed game search. */ async testCredentials( clientId: string, clientSecret: string ): Promise<{ success: true } | { success: false; error: string }> { let tokenResponse: Response; try { // Credentials go in the request body, not the URL: query strings are commonly retained // in server/proxy/monitoring logs, which would otherwise leak the client secret. tokenResponse = await safeFetch("https://id.twitch.tv/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: "client_credentials", }).toString(), // Pins the redirect chain to HTTPS/same-origin so a redirect can't downgrade the // request or forward the client secret to a different host. requireHttps: true, }); } catch (error) { igdbLogger.warn({ error }, "IGDB credential test: network error reaching Twitch"); return { success: false, error: "Could not reach Twitch — check your network connection." }; } if (!tokenResponse.ok) { if (tokenResponse.status === 400 || tokenResponse.status === 403) { return { success: false, error: "Invalid Client ID or Client Secret." }; } return { success: false, error: `Twitch returned an unexpected error (status ${tokenResponse.status}).`, }; } const tokenData: IGDBAuthResponse = await tokenResponse.json(); let igdbResponse: Response; try { igdbResponse = await safeFetch("https://api.igdb.com/v4/games", { method: "POST", headers: { Accept: "application/json", "Client-ID": clientId, Authorization: `Bearer ${tokenData.access_token}`, }, body: "fields id; limit 1;", requireHttps: true, }); } catch (error) { igdbLogger.warn({ error }, "IGDB credential test: network error reaching IGDB"); return { success: false, error: "Could not reach IGDB — check your network connection." }; } if (!igdbResponse.ok) { return { success: false, error: `IGDB rejected the request (status ${igdbResponse.status}).`, }; } return { success: true }; } private async getCredentials(): Promise<{ clientId: string | undefined; clientSecret: string | undefined; }> { const dbClientId = await storage.getSystemConfig("igdb.clientId"); const dbClientSecret = await storage.getSystemConfig("igdb.clientSecret"); if (dbClientId && dbClientSecret) { return { clientId: dbClientId, clientSecret: dbClientSecret }; } return { clientId: config.igdb.clientId, clientSecret: config.igdb.clientSecret, }; } private async ensureConfigured(): Promise { if (config.igdb.isConfigured) return true; const { clientId, clientSecret } = await this.getCredentials(); return !!(clientId && clientSecret); } // Request queueing properties private requestQueue: Promise = Promise.resolve(); private lastRequestTime: number = 0; // Disable throttling in test environment private readonly MIN_REQUEST_INTERVAL = config.server.nodeEnv === "test" ? 0 : 300; private async queueRequest(fn: () => Promise): Promise { return new Promise((resolve, reject) => { this.requestQueue = this.requestQueue.then(async () => { try { const now = Date.now(); const timeSinceLast = now - this.lastRequestTime; if (timeSinceLast < this.MIN_REQUEST_INTERVAL) { const delay = this.MIN_REQUEST_INTERVAL - timeSinceLast; await new Promise((r) => setTimeout(r, delay)); } this.lastRequestTime = Date.now(); const result = await fn(); resolve(result); } catch (error) { reject(error); } }); }); } private async authenticate(): Promise { if (this.accessToken && Date.now() < this.tokenExpiry) { return this.accessToken; } const { clientId, clientSecret } = await this.getCredentials(); if (!clientId || !clientSecret) { throw new Error("IGDB credentials not configured"); } // Credentials go in the request body, not the URL: query strings are commonly retained in // server/proxy/monitoring logs, which would otherwise leak the client secret. const response = await safeFetch("https://id.twitch.tv/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: "client_credentials", }).toString(), requireHttps: true, }); if (!response.ok) { throw new Error(`IGDB authentication failed: ${response.status}`); } const data: IGDBAuthResponse = await response.json(); this.accessToken = data.access_token; this.tokenExpiry = Date.now() + data.expires_in * 1000 - 60000; // Refresh 1 minute early return this.accessToken; } private async executeRequest( endpoint: string, query: string, ttl: number, cacheKey: string ): Promise { const token = await this.authenticate(); const { clientId } = await this.getCredentials(); this.lastRequestTime = Date.now(); let attempt = 0; while (true) { const response = await safeFetch(`https://api.igdb.com/v4/${endpoint}`, { method: "POST", headers: { Accept: "application/json", "Client-ID": clientId!, Authorization: `Bearer ${token}`, }, body: query, }); if (response.status === 429 && attempt < MAX_RETRY_ATTEMPTS) { const retryAfterHeader = response.headers.get("Retry-After"); const delay = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : BASE_RETRY_DELAY_MS * Math.pow(2, attempt); igdbLogger.warn( { endpoint, attempt: attempt + 1, delayMs: delay }, "IGDB rate limited (429), retrying after delay" ); await new Promise((r) => setTimeout(r, delay)); attempt++; continue; } if (!response.ok) { throw new Error(`IGDB API error: ${response.status}`); } const data = await response.json(); // ⚡ Bolt: If a TTL is specified, store the response in the cache. if (ttl > 0) { const expiry = Date.now() + ttl; this.cache.set(cacheKey, { data, expiry }); igdbLogger.debug({ cacheKey, ttl }, "cached response"); } return data as T; } } // IGDB API returns dynamic JSON structures private async makeRequest( endpoint: string, query: string, ttl: number = 0, skipQueue: boolean = false ): Promise { // ⚡ Bolt: Generate a unique cache key based on the endpoint and a normalized query. // Normalizing whitespace ensures that semantically identical queries // with different formatting hit the same cache entry. const cacheKey = `${endpoint}:${query.replace(/\s+/g, " ").trim()}`; // ⚡ Bolt: Check for a valid, non-expired cache entry first. if (this.cache.has(cacheKey)) { const entry = this.cache.get(cacheKey)!; if (Date.now() < entry.expiry) { igdbLogger.debug({ cacheKey }, "cache hit"); return entry.data as T; } igdbLogger.debug({ cacheKey }, "cache expired"); this.cache.delete(cacheKey); } igdbLogger.debug({ cacheKey }, "cache miss"); if (skipQueue) { return this.executeRequest(endpoint, query, ttl, cacheKey); } // Queue the API request to respect rate limits return this.queueRequest(async () => { return this.executeRequest(endpoint, query, ttl, cacheKey); }); } async searchGames( query: string, limit: number = 20, options: SearchGamesOptions = {} ): Promise { if (!(await this.ensureConfigured())) { igdbLogger.warn("IGDB credentials not configured, skipping search"); return []; } // Sanitize the search query to prevent query injection const sanitizedQuery = sanitizeIgdbInput(query); if (!sanitizedQuery) return []; let attemptCount = 0; // NOTE: platformId/releaseYear are intentionally NOT turned into `where` // clauses here. An edition (e.g. "Game: Gold Edition") can carry its own // platform list / first_release_date that differs from its canonical // version_parent's -- if we filtered upstream, IGDB would exclude such // editions from the response before canonicalizeVersionedGames ever gets // a chance to resolve them to a parent that DOES match. Instead, the // upstream query is left unfiltered on these fields and // postProcessSearchResults applies platformId/releaseYear filtering // locally, after canonicalization, against the resolved parent's // metadata. const withFilters = (conditions: string[] = []) => conditions.length > 0 ? `where ${conditions.join(" & ")}; ` : ""; // Request more raw results from IGDB than `limit` so there's enough // headroom left after canonicalizeVersionedGames collapses editions down // to their canonical parent (which can shrink the result count even for // an unfiltered search) and, when platformId/releaseYear are set, after // local filtering against the resolved parent's metadata. A local filter // discards a much larger share of the raw rows than edition dedupe // alone, so ask for more headroom when one is set. Still capped at // MAX_LIMIT (IGDB's own relevance ranking keeps this tractable without // needing an even larger multiplier). const hasLocalFilter = options.platformId != null || options.releaseYear != null; const headroomMultiplier = hasLocalFilter ? 5 : 2; const requestLimit = Math.min(limit * headroomMultiplier, MAX_LIMIT); // Search on the accent-folded query so "pokémon" and "pokemon" behave identically; // IGDB name matching (~) is case-insensitive but not accent-insensitive. const foldedQuery = foldDiacritics(sanitizedQuery) || sanitizedQuery; const hasAccents = foldedQuery !== sanitizedQuery; const exactNameCondition = `name ~= "${foldedQuery}"`; // When the user typed accents, also match the accented spelling verbatim, since IGDB // titles such as "Pokémon" only match `~` with the accent present. Folded into the // existing partial approach so the attempt budget (and word fallback) is unchanged. const partialNameCondition = hasAccents ? `(name ~ *"${foldedQuery}"* | name ~ *"${sanitizedQuery}"*)` : `name ~ *"${foldedQuery}"*`; // Try multiple search approaches to maximize results const searchApproaches = [ // Approach 1: Full text search without category filter `search "${foldedQuery}"; fields ${IGDB_GAME_FIELDS}; ${withFilters()}limit ${requestLimit};`, // Approach 2: Full text search with category filter `search "${foldedQuery}"; fields ${IGDB_GAME_FIELDS}; ${withFilters(["category = 0"])}limit ${requestLimit};`, // Approach 3: Case-insensitive name matching without category `fields ${IGDB_GAME_FIELDS}; ${withFilters([exactNameCondition])}limit ${requestLimit};`, // Approach 4: Partial name matching without category `fields ${IGDB_GAME_FIELDS}; ${withFilters([partialNameCondition])}sort rating desc; limit ${requestLimit};`, ]; for (let i = 0; i < searchApproaches.length && attemptCount < MAX_SEARCH_ATTEMPTS; i++) { const approach = searchApproaches[i]; if (approach === undefined) continue; try { attemptCount++; igdbLogger.debug( { approach: i + 1, query: sanitizedQuery, attempt: attemptCount, maxAttempts: MAX_SEARCH_ATTEMPTS, }, `trying approach ${i + 1}` ); // Cache search results for 15 minutes to reduce redundant API calls const results = await this.makeRequest("games", approach, 15 * 60 * 1000); if (results.length > 0) { igdbLogger.info( { approach: i + 1, query: sanitizedQuery, resultCount: results.length }, `search approach ${i + 1} found ${results.length} results` ); // postProcessSearchResults can legitimately return an empty array // even though the raw response wasn't empty -- canonicalization // can collapse this approach's rows onto parents that don't match // a platformId/releaseYear filter, or dedupe collapses everything // onto ids already excluded. Only return here if there's something // to show; otherwise fall through to the next search approach // instead of returning an empty result out from under a query // that a later, less-targeted approach might still satisfy. const processedResults = await this.postProcessSearchResults(results, limit, options); if (processedResults.length > 0) { return processedResults; } } } catch { igdbLogger.warn( { approach: i + 1, query: sanitizedQuery }, `search approach ${i + 1} failed` ); } } // Check if we've reached the max attempts before trying word search if (attemptCount >= MAX_SEARCH_ATTEMPTS) { igdbLogger.info( { query: sanitizedQuery, maxAttempts: MAX_SEARCH_ATTEMPTS }, `search reached max attempts` ); return []; } // If no full-phrase results, try individual words without category filter const words = foldedQuery .toLowerCase() .split(" ") .filter((word) => word.length > 2); // ⚡ Bolt: Sequential word search fallback was slow. Replaced with parallel execution // to improve response time for fallback queries. // We strictly respect the global attempt limit to prevent excessive API usage. const remainingAttempts = MAX_SEARCH_ATTEMPTS - attemptCount; if (words.length > 0 && remainingAttempts > 0) { // Only take as many words as we have remaining attempts const wordsToSearch = words.slice(0, remainingAttempts); const wordPromises = wordsToSearch.map(async (word) => { try { const sanitizedWord = sanitizeIgdbInput(word); if (!sanitizedWord) return []; const wordCondition = `name ~ *"${sanitizedWord}"*`; const wordQuery = `fields ${IGDB_GAME_FIELDS}; ${withFilters([wordCondition])}sort rating desc; limit ${requestLimit};`; // Cache word search results for 15 minutes return await this.makeRequest("games", wordQuery, 15 * 60 * 1000); } catch (error) { igdbLogger.warn({ word, error }, `word search failed`); return []; } }); const allWordResults = await Promise.all(wordPromises); // Flatten and process results const wordResults = allWordResults.flat(); if (wordResults.length > 0) { igdbLogger.info( { wordCount: wordsToSearch.length, resultCount: wordResults.length }, `parallel word search found results` ); // Filter to prefer games containing multiple query words const filteredResults = wordResults.filter( (game: IGDBGame) => words.filter((w) => foldDiacritics(game.name).toLowerCase().includes(w)).length >= Math.min(2, words.length) ); // Remove duplicates after merging const uniqueResults = (filteredResults.length > 0 ? filteredResults : wordResults).filter( (game: IGDBGame, index: number, self: IGDBGame[]) => index === self.findIndex((g) => g.id === game.id) ); // This fallback path sits outside the try/catch that wraps the // primary search approaches above, so guard the post-processing // call explicitly -- a rejection here must not escape as an // unhandled crash; fall back to the uncanonicalized/unfiltered // word-search results instead. try { return await this.postProcessSearchResults(uniqueResults, limit, options); } catch (error) { igdbLogger.warn( { error, query: sanitizedQuery }, "post-processing failed for word search fallback results; returning uncanonicalized results" ); return uniqueResults.slice(0, limit); } } } igdbLogger.info({ query: sanitizedQuery }, `search found no results`); return []; } /** * Search for multiple game titles efficiently using the multiquery endpoint. * Returns a map of QueryString -> IGDBGame | null */ async batchSearchGames(queries: string[]): Promise> { if (!(await this.ensureConfigured()) || queries.length === 0) { return new Map(); } const uniqueQueries = Array.from(new Set(queries)); // Multiquery limit is usually 10 sub-queries per request const BATCH_SIZE = 10; const results = new Map(); for (let i = 0; i < uniqueQueries.length; i += BATCH_SIZE) { const batch = uniqueQueries.slice(i, i + BATCH_SIZE); const multiqueryBody = batch .map((q, idx) => { const sanitized = sanitizeIgdbInput(q); if (!sanitized) return null; // Split into words, remove common short words to improve match robustness // (e.g. "the", "and", "of", "a") const words = sanitized .toLowerCase() .split(/\s+/) .filter((word) => word.length >= 3 || /\d/.test(word)); // Keep words >= 3 chars or containing digits if (words.length === 0) return null; // Join with & logic: all words must be present in the name const intersection = words.map((w) => `name ~ *"${w}"*`).join(" & "); // Alias the result with the index `q${idx}` to map back return `query games "q${idx}" { fields name, cover.url, first_release_date, platforms.name, genres.name, involved_companies.company.name; where ${intersection}; limit 1; };`; }) .filter(Boolean) .join("\n"); if (!multiqueryBody) continue; try { const responseData = await this.makeRequest>( "multiquery", multiqueryBody, HOUR_IN_SECONDS * 1000 ); // Cache for 1 hour logger.debug(`[DEBUG] Multiquery response length: ${responseData.length}`); logger.debug(`[DEBUG] Multiquery response: ${JSON.stringify(responseData)}`); // Verbose // Map results back to queries batch.forEach((originalQuery, idx) => { const alias = `q${idx}`; const match = responseData.find((r) => r.name === alias); if (match && match.result && match.result.length > 0) { results.set(originalQuery, match.result[0] ?? null); } else { results.set(originalQuery, null); } }); } catch (error) { igdbLogger.error({ error }, "Multiquery batch failed"); // Fallback: Set all in this batch to null batch.forEach((q) => results.set(q, null)); } } return results; } async getGameById(id: number): Promise { if (!(await this.ensureConfigured())) return null; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where id = ${id}; `; // ⚡ Bolt: Cache game data for 24 hours as it's unlikely to change frequently. const results = await this.makeRequest("games", igdbQuery, 24 * 60 * 60 * 1000); return results[0] ?? null; } /** The adult-content flags the account's content filters act on. */ contentFlags(game: ContentFlagSource): { isAdultContent: boolean; isAgeRestricted: boolean } { return { isAdultContent: hasEroticTheme(game), isAgeRestricted: hasAdultAgeRating(game) }; } /** The base game with its linked add-ons, and the editions that name it as `version_parent`. */ async getGameEditions( id: number ): Promise<{ base: IGDBGameContent | null; editions: IGDBGameContent[] }> { if (!(await this.ensureConfigured())) return { base: null, editions: [] }; const refFields = (field: string) => [ "name", "cover.url", "first_release_date", "game_type", "themes.name", "age_ratings.category", "age_ratings.rating", ] .map((name) => `${field}.${name}`) .join(", "); const fields = [ "name, summary, first_release_date, game_type, themes.name, age_ratings.category, age_ratings.rating", refFields("expansions"), refFields("dlcs"), refFields("standalone_expansions"), ].join(", "); const ttl = 24 * 60 * 60 * 1000; const [bases, editions] = await Promise.all([ this.makeRequest("games", `fields ${fields}; where id = ${id};`, ttl), this.makeRequest( "games", `fields ${fields}; where version_parent = ${id}; sort first_release_date asc; limit 30;`, ttl ), ]); return { base: bases[0] ?? null, editions }; } /** * Games matching IGDB theme, mode, perspective, genre and language ids. Included ids match any * of the listed values, excluded ids drop a game carrying any of them. All ids are integers * validated by the caller. */ async discoverGames( filters: DiscoverFilters, limit: number, offset: number ): Promise { if (!(await this.ensureConfigured())) return []; const conditions = ["game_type = (0,8,9,10,11)", "cover != null"]; const includeAny = (field: string, ids: number[]) => { if (ids.length > 0) conditions.push(`${field} = (${ids.join(",")})`); }; const excludeAny = (field: string, ids: number[]) => { if (ids.length > 0) conditions.push(`${field} = !(${ids.join(",")})`); }; includeAny("themes", filters.themes); includeAny("game_modes", filters.gameModes); includeAny("player_perspectives", filters.perspectives); includeAny("genres", filters.genres); includeAny("language_supports.language", filters.languages); excludeAny("themes", filters.excludeThemes); excludeAny("game_modes", filters.excludeGameModes); excludeAny("genres", filters.excludeGenres); if (filters.minYear) { conditions.push(`first_release_date >= ${Date.UTC(filters.minYear, 0, 1) / 1000}`); } const text = filters.query ? sanitizeIgdbInput(filters.query) : ""; const search = text ? `search "${text}";` : ""; // Relevance ordering applies to searches; otherwise the better rated games come first. const sort = text ? "" : "sort aggregated_rating_count desc;"; const igdbQuery = ` ${search} fields ${IGDB_GAME_FIELDS}, themes.id, game_modes.name, player_perspectives.name; where ${conditions.join(" & ")}; ${sort} limit ${limit}; offset ${offset}; `; return this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } async getGameIdBySteamAppId(steamAppId: number): Promise { if (!(await this.ensureConfigured())) return null; // source 1 = Steam const igdbQuery = ` fields game; where uid = "${steamAppId}" & external_game_source = 1; limit 1; `; try { // Cache external game lookups for 24 hours const results = await this.makeRequest<{ id: number; game: number }[]>( "external_games", igdbQuery, 24 * 60 * 60 * 1000 ); return results[0]?.game ?? null; } catch (error) { igdbLogger.warn({ steamAppId, error }, "Failed to lookup IGDB ID from Steam App ID"); return null; } } /** Map exact Steam IDs in bounded batches; strict mode propagates outages instead of misses. */ async getGameIdsBySteamAppIds( steamAppIds: number[], options: { strict?: boolean } = {} ): Promise> { if (steamAppIds.length === 0) return new Map(); if (!(await this.ensureConfigured())) { if (options.strict) throw new Error("IGDB is not configured"); return new Map(); } const idMap = new Map(); const CHUNK_SIZE = 100; // IGDB might have a limit on URL length or number of IDs for (let i = 0; i < steamAppIds.length; i += CHUNK_SIZE) { const chunk = steamAppIds.slice(i, i + CHUNK_SIZE); // uid is string in IGDB external_games const igdbQuery = ` fields game, uid; where uid = (${chunk.map((id) => `"${id}"`).join(",")}) & external_game_source = 1; limit ${chunk.length}; `; try { const results = await this.makeRequest<{ uid: string; game: number }[]>( "external_games", igdbQuery, 24 * 60 * 60 * 1000 ); for (const result of results) { idMap.set(parseInt(result.uid, 10), result.game); } } catch (error) { // Imports must distinguish an unavailable provider from a genuine missing mapping. if (options.strict) throw new Error("IGDB Steam mapping lookup failed", { cause: error }); igdbLogger.warn( { steamAppIds: chunk, error }, "Failed to lookup a chunk of IGDB IDs from Steam App IDs" ); } } return idMap; } /** * Whether IGDB lists a remake of this game as a game of its own. `undefined` when it cannot * be told (not configured, request failed): callers then keep their default behavior. */ async hasRemake(igdbId: number): Promise { if (!Number.isInteger(igdbId) || igdbId <= 0) return undefined; try { if (!(await this.ensureConfigured())) return undefined; const rows = await this.makeRequest>( "games", `fields remakes; where id = ${igdbId};`, 24 * 60 * 60 * 1000 ); const row = rows[0]; if (!row) return undefined; return (row.remakes?.length ?? 0) > 0; } catch (error) { igdbLogger.warn({ igdbId, error }, "Failed to look up IGDB remake relations"); return undefined; } } /** * Fetch community-submitted completion-time estimates from IGDB's own * `game_time_to_beats` endpoint (hastily/normally/completely, in hours). * Coverage is best-effort: a game with no IGDB submissions is simply * absent from the returned map, never a zero/placeholder entry. */ async getTimeToBeats(igdbIds: number[]): Promise> { const result = new Map(); if (!(await this.ensureConfigured()) || igdbIds.length === 0) { return result; } const CHUNK_SIZE = 100; for (let i = 0; i < igdbIds.length; i += CHUNK_SIZE) { const chunk = igdbIds.slice(i, i + CHUNK_SIZE); const igdbQuery = ` fields game_id, hastily, normally, completely; where game_id = (${chunk.join(",")}); limit ${chunk.length}; `; try { const rows = await this.makeRequest< Array<{ game_id: number; hastily?: number; normally?: number; completely?: number }> >("game_time_to_beats", igdbQuery, 24 * 60 * 60 * 1000); for (const row of rows) { result.set(row.game_id, { hastily: row.hastily != null ? row.hastily / HOUR_IN_SECONDS : undefined, normally: row.normally != null ? row.normally / HOUR_IN_SECONDS : undefined, completely: row.completely != null ? row.completely / HOUR_IN_SECONDS : undefined, }); } } catch (error) { igdbLogger.warn({ igdbIds: chunk, error }, "Failed to fetch a chunk of time-to-beat data"); } } return result; } /** Fetch paced metadata batches; strict callers must distinguish provider failure from no match. */ async getGamesByIds(ids: number[], options: { strict?: boolean } = {}): Promise { if (ids.length === 0) return []; if (!(await this.ensureConfigured())) { if (options.strict) throw new Error("IGDB is not configured"); return []; } // Get rate limit from settings let rateLimit = 3; try { const [settings] = await db.select().from(userSettings).limit(1); if (settings?.igdbRateLimitPerSecond) { rateLimit = settings.igdbRateLimitPerSecond; } } catch { igdbLogger.warn("Failed to fetch user settings for rate limit, defaulting to 3"); } // Split into chunks of 100 to avoid query length limits const chunks = []; for (let i = 0; i < ids.length; i += 100) { chunks.push(ids.slice(i, i + 100)); } const allResults: IGDBGame[] = []; // Process chunks in batches respecting rate limit for (let i = 0; i < chunks.length; i += rateLimit) { const batchStartTime = Date.now(); const startLastRequestTime = this.lastRequestTime; const batch = chunks.slice(i, i + rateLimit); const promises = batch.map((chunk) => { const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where id = (${chunk.join(",")}); limit 100; `; // Cache batch requests for 1 hour, skip queue for manual batching return this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000, true); }); const results = await Promise.all(promises); results.forEach((r) => allResults.push(...r)); // If we made actual requests (cache miss), enforce rate limit if (this.lastRequestTime > startLastRequestTime && i + rateLimit < chunks.length) { const elapsed = Date.now() - batchStartTime; // Ensure at least 1 second passes per batch to respect X req/s const delay = Math.max(0, 1000 - elapsed); if (delay > 0) { await new Promise((resolve) => setTimeout(resolve, delay)); } } } return allResults; } /** Returns the current Unix timestamp (seconds) floored to the nearest hour. */ private currentHourTimestamp(): number { return Math.floor(Date.now() / (HOUR_IN_SECONDS * 1000)) * HOUR_IN_SECONDS; } async getPopularGames(limit: number = 20): Promise { if (!(await this.ensureConfigured())) return []; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where rating > 80 & rating_count > 10; sort rating desc; limit ${limit}; `; // ⚡ Bolt: Cache popular games for 1 hour to reduce load during high traffic. return this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } async getRecentReleases(limit: number = 20): Promise { if (!(await this.ensureConfigured())) return []; // Round timestamps to the nearest hour so the query string (and thus the cache key) // stays identical for all calls within the same hour, enabling effective caching. const nowHour = this.currentHourTimestamp(); const thirtyDaysAgo = nowHour - 30 * 24 * HOUR_IN_SECONDS; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where first_release_date >= ${thirtyDaysAgo} & first_release_date <= ${nowHour}; sort first_release_date desc; limit ${limit}; `; return this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } async getUpcomingReleases(limit: number = 20): Promise { if (!(await this.ensureConfigured())) return []; // Round timestamps to the nearest hour for stable cache keys. const nowHour = this.currentHourTimestamp(); const sixMonthsFromNow = nowHour + 6 * 30 * 24 * HOUR_IN_SECONDS; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where first_release_date >= ${nowHour} & first_release_date <= ${sixMonthsFromNow}; sort first_release_date asc; limit ${limit}; `; return this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } async getGamesByGenres( genres: string[], excludeIds: number[] = [], limit: number = 20 ): Promise { if (!(await this.ensureConfigured())) return []; if (genres.length === 0) return []; // Convert genre names to a query format - use regex matching for better results const genreConditions = genres .slice(0, 3) .map((genre) => { // Sanitize genre names to prevent query injection const cleanGenre = sanitizeIgdbInput(genre); return cleanGenre ? `genres.name ~ *"${cleanGenre}"*` : null; }) .filter((condition): condition is string => Boolean(condition)); if (genreConditions.length === 0) return []; // ⚡ Bolt: Sort conditions alphabetically to ensure a consistent cache key // regardless of the original order of genres. const genreCondition = genreConditions.sort((a, b) => a.localeCompare(b)).join(" | "); const excludeCondition = excludeIds.length > 0 ? ` & id != (${excludeIds.join(",")})` : ""; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where (${genreCondition}) & rating > ${HIGH_RATING_THRESHOLD} & rating_count > ${HIGH_RATING_COUNT}${excludeCondition}; sort rating desc; limit ${limit}; `; try { // ⚡ Bolt: Cache genre-based searches for 1 hour. return await this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } catch { igdbLogger.warn({ genres }, `genre search failed`); return []; } } async getGamesByPlatforms( platforms: string[], excludeIds: number[] = [], limit: number = 20 ): Promise { if (!(await this.ensureConfigured())) return []; if (platforms.length === 0) return []; // Use common platform names for better matching const platformMap: { [key: string]: string } = { "PC (Microsoft Windows)": "PC", "PlayStation 5": "PlayStation", "PlayStation 4": "PlayStation", "Xbox Series X|S": "Xbox", "Xbox One": "Xbox", "Nintendo Switch": "Nintendo", }; const mappedPlatforms = platforms.slice(0, 3).map( (platform) => platformMap[platform] || (platform.split(" ")[0] ?? platform) // Use first word if no mapping ); const uniquePlatforms = Array.from(new Set(mappedPlatforms)); const platformConditions = uniquePlatforms .map((platform) => { // Sanitize platform names to prevent query injection const cleanPlatform = sanitizeIgdbInput(platform); return cleanPlatform ? `platforms.name ~ *"${cleanPlatform}"*` : null; }) .filter((condition): condition is string => Boolean(condition)); if (platformConditions.length === 0) return []; // ⚡ Bolt: Sort conditions alphabetically to ensure a consistent cache key // regardless of the original order of platforms. const platformCondition = platformConditions.sort((a, b) => a.localeCompare(b)).join(" | "); const excludeCondition = excludeIds.length > 0 ? ` & id != (${excludeIds.join(",")})` : ""; const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where (${platformCondition}) & rating > ${HIGH_RATING_THRESHOLD} & rating_count > ${HIGH_RATING_COUNT}${excludeCondition}; sort rating desc; limit ${limit}; `; try { // ⚡ Bolt: Cache platform-based searches for 1 hour. return await this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } catch (error) { igdbLogger.warn({ platforms, error }, `platform search failed`); return []; } } async getRecommendations( userGames: Array<{ genres?: string[] | undefined; platforms?: string[] | undefined; igdbId?: number | undefined; }>, limit: number = 20 ): Promise { if (!(await this.ensureConfigured())) return []; if (userGames.length === 0) { // If user has no games, show popular games return this.getPopularGames(limit); } // Extract genres and platforms from user's games const userGenres = Array.from(new Set(userGames.flatMap((game) => game.genres || []))); const userPlatforms = Array.from(new Set(userGames.flatMap((game) => game.platforms || []))); const userIgdbIds = userGames .filter((game) => game.igdbId !== undefined) .map((game) => game.igdbId!); igdbLogger.debug( { genreCount: userGenres.length, platformCount: userPlatforms.length, excludeCount: userIgdbIds.length, }, `generating recommendations` ); const recommendations: IGDBGame[] = []; try { // Get games by favorite genres (60% of results) if (userGenres.length > 0) { const topGenres = userGenres.slice(0, 5); // Use top 5 genres const genreGames = await this.getGamesByGenres( topGenres, userIgdbIds, Math.ceil(limit * 0.6) ); recommendations.push(...genreGames); } // Get games by platforms (40% of results) if (userPlatforms.length > 0 && recommendations.length < limit) { const remaining = limit - recommendations.length; const platformGames = await this.getGamesByPlatforms(userPlatforms, userIgdbIds, remaining); recommendations.push(...platformGames); } // Fill remaining with popular games if needed if (recommendations.length < limit) { const remaining = limit - recommendations.length; const popularGames = await this.getPopularGames(remaining + 10); // Get extra to filter duplicates const filteredPopular = popularGames.filter( (game) => !userIgdbIds.includes(game.id) && !recommendations.some((rec) => rec.id === game.id) ); recommendations.push(...filteredPopular.slice(0, remaining)); } // Remove duplicates and return const uniqueRecommendations = recommendations.filter( (game, index, self) => index === self.findIndex((g) => g.id === game.id) ); igdbLogger.info( { count: uniqueRecommendations.length }, `generated ${uniqueRecommendations.length} unique recommendations` ); return uniqueRecommendations.slice(0, limit); } catch (error) { igdbLogger.error({ error }, `error generating recommendations`); // Fallback to popular games return this.getPopularGames(limit); } } /** * Candidate pool for library-driven recommendations: games IGDB lists as similar to the * user's favourite games, plus well-rated games sharing their genres, themes or developers. * Each source fails on its own (an IGDB error just shrinks the pool). The caller scores and * filters the candidates; `similarTo` says which anchor games listed a candidate as similar. */ async getRecommendationCandidates(seed: { anchorIgdbIds: number[]; genres: string[]; themes: string[]; developers: string[]; excludeIgdbIds: number[]; }): Promise> { if (!(await this.ensureConfigured())) return []; const names = (list: string[]) => list .slice(0, 4) .map((n) => exactIgdbStringValue(n)) .filter(Boolean) .sort((a, b) => a.localeCompare(b)) .map((n) => `"${n}"`) .join(","); const anchors = [...new Set(seed.anchorIgdbIds.filter((id) => Number.isInteger(id)))] .sort((a, b) => a - b) .slice(0, 10); const exclude = [...new Set(seed.excludeIgdbIds.filter((id) => Number.isInteger(id)))].sort( (a, b) => a - b ); const excludeCondition = exclude.length > 0 ? ` & id != (${exclude.join(",")})` : ""; const quality = `rating > ${HIGH_RATING_THRESHOLD} & rating_count > ${HIGH_RATING_COUNT}`; const ttl = HOUR_IN_SECONDS * 1000; const byName = async (field: string, list: string[]): Promise => { const values = names(list); if (!values) return []; try { return await this.makeRequest( "games", `fields ${IGDB_GAME_FIELDS}; where ${field} = (${values}) & ${quality}${excludeCondition}; sort rating desc; limit 40;`, ttl ); } catch { igdbLogger.warn({ field }, "recommendation candidate query failed"); return []; } }; const similarFields = IGDB_GAME_FIELDS.split(", ") .map((f) => `similar_games.${f}`) .join(", "); const similarSource = async (): Promise> => { if (anchors.length === 0) return []; try { const rows = await this.makeRequest>( "games", `fields ${similarFields}; where id = (${anchors.join(",")}); limit ${anchors.length};`, ttl ); return rows.flatMap((row) => (row.similar_games ?? []).map((game) => ({ game, similarTo: [row.id] })) ); } catch { igdbLogger.warn("similar games query failed"); return []; } }; const [similar, byGenre, byTheme, byDeveloper] = await Promise.all([ similarSource(), byName("genres.name", seed.genres), byName("themes.name", seed.themes), byName("involved_companies.company.name", seed.developers), ]); // Merge duplicates across sources, remembering every anchor that listed the game as similar. const merged = new Map }>(); const add = (game: IGDBGame, similarTo: number[]) => { const entry = merged.get(game.id) ?? { game, similarTo: new Set() }; for (const id of similarTo) entry.similarTo.add(id); merged.set(game.id, entry); }; for (const { game, similarTo } of similar) add(game, similarTo); for (const game of [...byGenre, ...byTheme, ...byDeveloper]) add(game, []); return [...merged.values()].map(({ game, similarTo }) => ({ game, similarTo: [...similarTo], })); } async getGamesByGenre( genre: string, limit: number = 20, offset: number = 0 ): Promise { if (!(await this.ensureConfigured())) return []; // Sanitize the genre name to prevent query injection const cleanGenre = sanitizeIgdbInput(genre); if (!cleanGenre) return []; // Validate pagination parameters const validLimit = Math.min(Math.max(1, limit), MAX_LIMIT); const validOffset = Math.min(Math.max(0, offset), MAX_OFFSET); const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where genres.name ~ *"${cleanGenre}"* & rating > ${MIN_RATING_THRESHOLD} & rating_count > ${MIN_RATING_COUNT}; sort rating desc; limit ${validLimit}; offset ${validOffset}; `; try { // ⚡ Bolt: Cache genre search results for 1 hour. return await this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } catch (error) { console.warn(`IGDB genre search failed for genre: ${genre}`, error); return []; } } async getGamesByPlatform( platform: string, limit: number = 20, offset: number = 0 ): Promise { if (!(await this.ensureConfigured())) return []; // Sanitize the platform name to prevent query injection const cleanPlatform = sanitizeIgdbInput(platform); if (!cleanPlatform) return []; // Validate pagination parameters const validLimit = Math.min(Math.max(1, limit), MAX_LIMIT); const validOffset = Math.min(Math.max(0, offset), MAX_OFFSET); const igdbQuery = ` fields ${IGDB_GAME_FIELDS}; where platforms.name ~ *"${cleanPlatform}"* & rating > ${MIN_RATING_THRESHOLD} & rating_count > ${MIN_RATING_COUNT}; sort rating desc; limit ${validLimit}; offset ${validOffset}; `; try { // ⚡ Bolt: Cache platform search results for 1 hour. return await this.makeRequest("games", igdbQuery, HOUR_IN_SECONDS * 1000); } catch (error) { console.warn(`IGDB platform search failed for platform: ${platform}`, error); return []; } } async getGenres(): Promise> { if (!(await this.ensureConfigured())) return []; const igdbQuery = ` fields id, name; sort name asc; limit 50; `; try { // ⚡ Bolt: Cache genres for 24 hours as they are static. return await this.makeRequest<{ id: number; name: string }[]>( "genres", igdbQuery, 24 * 60 * 60 * 1000 ); } catch (error) { console.warn("IGDB genres fetch failed:", error); return []; } } async getPlatforms(): Promise> { if (!(await this.ensureConfigured())) return []; const fetchAllPlatforms = async ( whereClause: string ): Promise> => { const pageSize = 100; const all: Array<{ id: number; name: string }> = []; for (let offset = 0; offset <= MAX_OFFSET; offset += pageSize) { const pagedQuery = ` fields id, name; where ${whereClause}; sort name asc; limit ${pageSize}; offset ${offset}; `; const batch = await this.makeRequest<{ id: number; name: string }[]>( "platforms", pagedQuery, 24 * 60 * 60 * 1000 ); if (batch.length === 0) break; all.push(...batch); if (batch.length < pageSize) break; } return all; }; const processPlatforms = (platforms: Array<{ id: number; name: string }>) => Array.from(new Map(platforms.map((p) => [p.id, p])).values()).sort((a, b) => a.name.localeCompare(b.name) ); try { // Only get major gaming platforms, but fetch all pages. IGDB replaced the deprecated // `category` field with `platform_type`: 1 console, 4 operating system (PC, Mac, Linux), // 5 portable console, 6 computer. const primary = await fetchAllPlatforms("platform_type = (1, 4, 5, 6)"); if (primary.length > 0) { return processPlatforms(primary); } // Fallback query without category filter in case upstream schema/filter behavior changed. const broadFallback = await fetchAllPlatforms("name != null"); if (broadFallback.length > 0) { return processPlatforms(broadFallback); } return FALLBACK_PLATFORMS; } catch (error) { console.warn("IGDB platforms fetch failed, using fallback list:", error); return FALLBACK_PLATFORMS; } } formatGameData(igdbGame: IGDBGame): Record { const releaseDate = igdbGame.first_release_date ? new Date(igdbGame.first_release_date * 1000) : null; const now = new Date(); const isReleased = releaseDate ? releaseDate <= now : false; return { id: `igdb-${igdbGame.id}`, igdbId: igdbGame.id, title: igdbGame.name, summary: igdbGame.summary || "", coverUrl: igdbGame.cover?.url ? `https:${igdbGame.cover.url.replace("t_thumb", "t_cover_big")}` : "", releaseDate: releaseDate ? releaseDate.toISOString().split("T")[0] : "", rating: igdbGame.rating ? Math.round(igdbGame.rating) / 10 : null, platforms: igdbGame.platforms?.map((p) => p.name) || [], platformOptions: igdbGame.platforms?.map(({ id, name }) => ({ id, name })) || [], genres: igdbGame.genres?.map((g) => g.name) || [], themes: igdbGame.themes?.map((t) => t.name) || [], isAdultContent: hasEroticTheme(igdbGame), isAgeRestricted: hasAdultAgeRating(igdbGame), publishers: igdbGame.involved_companies?.filter((c) => c.publisher).map((c) => c.company.name) || [], developers: igdbGame.involved_companies?.filter((c) => c.developer).map((c) => c.company.name) || [], screenshots: igdbGame.screenshots?.map((s) => `https:${s.url.replace("t_thumb", "t_screenshot_big")}`) || [], gameModes: igdbGame.game_modes?.map((m) => m.name) || [], videos: toVideos(igdbGame.videos), igdbWebsites: igdbWebsiteSchema .array() .catch([]) .parse(igdbGame.websites ?? []), aggregatedRating: igdbGame.aggregated_rating ? Math.round(igdbGame.aggregated_rating) / 10 : undefined, // For Discovery games, don't set a status since they're not in collection yet status: null, isReleased, releaseYear: releaseDate ? releaseDate.getFullYear() : null, earlyAccess: igdbGame.status === 4, category: mapIGDBGameType(igdbGame.game_type), gameType: igdbGame.game_type, expansions: igdbGame.expansions?.map((expansion) => ({ id: expansion.id, name: expansion.name, coverUrl: expansion.cover?.url ? `https:${expansion.cover.url.replace("t_thumb", "t_cover_big")}` : "", releaseDate: expansion.first_release_date ? new Date(expansion.first_release_date * 1000).toISOString().split("T")[0] : "", category: mapIGDBGameType(expansion.game_type), gameType: expansion.game_type, igdbUrl: expansion.url, })) ?? [], }; } } export const igdbClient = new IGDBClient();