/**
* Title Utilities
*
* Shared logic for normalizing, cleaning, and matching game titles
* and release names (from xREL, Indexers, etc.)
*/
/**
* Normalizes a title by removing special characters, multiple spaces, and converting to lowercase.
*/
export function normalizeTitle(title: string): string {
return title
.toLowerCase()
.replaceAll(/[^a-z0-9\s]/g, " ") // Replace non-alphanumeric with space
.replaceAll(/\s+/g, " ") // Multiple spaces to single space
.trim();
}
/**
* Collapses every run of whitespace (newlines, tabs, repeated spaces) in a release title
* into a single space and trims it. Some indexer definitions scrape a whole results-table
* row into the title, which otherwise blows past the 500-character download title limit.
*/
export function normalizeReleaseTitle(title: unknown): string {
if (typeof title === "string" || typeof title === "number") {
return String(title).replaceAll(/\s+/g, " ").trim();
}
// fast-xml-parser yields { "#text": ... } for a
element that carries attributes
if (title !== null && typeof title === "object" && "#text" in title) {
return normalizeReleaseTitle(title["#text"]);
}
return "";
}
/**
* Common scene release tags and patterns to remove from release names.
*/
const RELEASE_TAGS = [
/\b(1080p|720p|2160p|4k|uhd|bluray|h264|x264|h265|x265|hevc)\b/gi,
/\b(multi\d*|multilingual|language|languages|german|english|french|italian|spanish|nordic|pal|ntsc|russian|japanese)\b/gi,
/\b(iso|rip|repack|re-repack|proper|internal|readnfo|nfo|re-nfo|crackfix|fix|fixed|hotfix|update|dlc|unlocker)\b/gi,
/\b(?:nintendo\s*)?switch\s*2\b/gi,
/\b(?:nintendo\s*64|n64)\b/gi,
/\b(ps3|ps4|ps5|xbox|xbox360|x360|switch|nsw|nsp|xci|wii|wiiu|nds|3ds|gba|psp|psvita|vita)\b/gi,
/\b(mac|linux|osx|os\.x|macos)\b/gi,
/\b(gog|steam|epic|uplay|origin|drm[ -]?free)\b/gi,
/\b(goty|deluxe|complete|gold|ultimate|collectors|definitive|remastered|remake|remaster)\b/gi,
];
const VERSION_REGEX = /\b(v\d+([.\s-]\d+)*|build[.\s-]\d+)\b/i;
const SWITCH_TITLE_ID_REGEX = /\b01[0-9a-f]{14}\b/gi;
const SWITCH_REGION_TAG_REGEX = /[([]\s*(?:US|EU|JP|UK|KR|CN|HK|TW|AU|WORLD|ASIA)\s*[)\]]/gi;
export type SwitchTitleKind = "base" | "update" | "dlc";
export interface SwitchTitleInfo {
titleId: string;
kind: SwitchTitleKind;
/** Shared by a base game, its updates and its DLC: the base title id's first 13 hex digits. */
family: string;
}
/**
* Reads a Nintendo Switch title id (16 hex digits starting with 01) from a file or folder name.
* A base game id ends in 000 with an even 13th digit, its update sets bit 0x800, and DLC ids use
* the next 13-digit prefix, so all three of a game's files resolve to the same family.
*/
export function parseSwitchTitleId(name: string): SwitchTitleInfo | null {
const match = /(?= 1975 && Number(year) <= 2040) hints.year = Number(year);
return hints;
}
/**
* Cleans a release name (e.g. from a torrent or NZB) to attempt to extract the base game title.
*/
export function cleanReleaseName(releaseName: string): string {
// 1. Convert underscores and dots (but not dashes) to spaces early to help regex word boundaries
// We keep dashes for now to detect -GROUP suffixes. Switch title ids ([0100F2C0115B6000]) are
// hex, so the bracket cleanup below would keep them in the title.
let cleaned = releaseName.replace(ID_TAG_REGEX, " ").replace(/[._]/g, " ");
// `upd` and `nsz`/`xcz` are only release tags on Switch dumps ("NSZ Edition" can be a title),
// so they go only when a title id or a compressed-dump extension identifies one.
const switchDump = parseSwitchTitleId(releaseName) !== null || /\.(nsz|xcz)$/i.test(releaseName);
cleaned = cleaned.replace(SWITCH_TITLE_ID_REGEX, " ");
if (switchDump) {
cleaned = cleaned.replace(/[([]\s*(?:upd|nsz|xcz)\s*[)\]]|\b(?:upd|nsz|xcz)\b/gi, " ");
cleaned = cleaned.replace(SWITCH_REGION_TAG_REGEX, " ");
}
// 2. Remove common release group suffixes (usually -GROUP at the end)
// Handle simple -GROUP at end
cleaned = cleaned.replace(/-[a-zA-Z0-9]+$/, "");
// 2. Handle content in brackets or parentheses that often contains metadata
// Three separate regexes ensure only matched bracket pairs are consumed (e.g. `(foo]` is not matched).
const bracketCallback = (match: string) => {
const inner = match.slice(1, -1).toLowerCase();
// Reset lastIndex before each .test() — g-flag regexes are stateful and lastIndex
// advances after a match, causing intermittent misses on reuse.
const hasTag =
RELEASE_TAGS.some((tag) => {
tag.lastIndex = 0;
return tag.test(inner);
}) || VERSION_REGEX.test(inner);
const isNumeric = /^\d+$/.test(inner.replace(/\s/g, ""));
if (hasTag || isNumeric) return " ";
return match; // Keep it if it might be part of the title (e.g. "Game (Special Edition)")
};
cleaned = cleaned.replace(/\([^)]*\)/g, bracketCallback);
cleaned = cleaned.replace(/\[[^\]]*\]/g, bracketCallback);
cleaned = cleaned.replace(/\{[^}]*\}/g, bracketCallback);
// 3. Remove version patterns explicitly
cleaned = cleaned.replace(VERSION_REGEX, " ");
// 4. Replace dots, underscores, dashes with space
cleaned = cleaned.replace(/[._-]/g, " ");
// Normalize " and " to " & " to improve matching (e.g. Tales And Tactics -> Tales & Tactics)
cleaned = cleaned.replace(/\s+and\s+/gi, " & ");
// 5. Remove all known release tags
for (const tag of RELEASE_TAGS) {
cleaned = cleaned.replace(tag, " ");
}
// 6. Remove years (only if they are between 1975 and 2040)
cleaned = cleaned.replace(/\b\d{4}\b/g, (match) => {
const year = parseInt(match);
if (year >= 1975 && year <= 2040) {
return " ";
}
return match;
});
// Final cleanup of extra symbols and spaces
return cleaned.replaceAll(/[[\]]/g, " ").replaceAll(/\s+/g, " ").trim();
}
export const TITLE_STOP_WORDS: ReadonlySet = new Set([
"the",
"of",
"and",
"in",
"on",
"at",
"to",
"a",
"an",
"is",
"by",
"or",
"for",
"with",
]);
/** Drops stopwords from an already normalized title ("the witcher 3" -> "witcher 3"). */
export function withoutStopWords(normalized: string): string {
return normalized
.split(" ")
.filter((w) => !TITLE_STOP_WORDS.has(w))
.join(" ");
}
// "2"-"99" or a roman numeral from II to XXXIX ("I" alone is too often a word).
const SEQUEL_NUMBER_REGEX = /^([2-9]|[1-9]\d)$/;
const SEQUEL_ROMAN_REGEX = /^(?!i$)x{0,3}(ix|iv|v?i{0,3})$/;
/** True for a word that reads as a sequel number: "2" to "99", or a roman numeral from II. */
function isSequelMarker(token: string | undefined): boolean {
if (!token) return false;
return SEQUEL_NUMBER_REGEX.test(token) || SEQUEL_ROMAN_REGEX.test(token);
}
/**
* True when `longer` contains `shorter` (both normalized) and the word right after it is a
* sequel number: "dishonored 2" for "dishonored", "hades ii" for "hades". Word containment
* alone would accept those, and auto-search downloads a lone match on its own.
* A number followed by another number ("game 2 0") reads as a version, not a sequel.
*/
export function isSequelOf(longer: string, shorter: string): boolean {
if (!longer || !shorter || longer === shorter) return false;
const longWords = longer.split(" ");
const shortWords = shorter.split(" ");
for (let i = 0; i + shortWords.length <= longWords.length; i++) {
if (!shortWords.every((word, j) => longWords[i + j] === word)) continue;
const next = longWords[i + shortWords.length];
const afterNext = longWords[i + shortWords.length + 1];
if (!isSequelMarker(next)) continue;
// "game 2 0" is a version; "hades ii 2 0" is still the sequel at version 2.0, and a year
// ("game 2 2017") is not a version component
const isVersion =
/^\d+$/.test(next ?? "") && afterNext !== undefined && /^\d{1,3}$/.test(afterNext);
if (!isVersion) return true;
}
return false;
}
/**
* Checks if two titles match loosely.
* Can be used to match a known game title against an xREL title or a cleaned release name.
*/
export function titleMatches(a: string, b: string): boolean {
const normA = normalizeTitle(a);
const normB = normalizeTitle(b);
if (!normA || !normB) return false;
if (normA === normB) return true;
// For very short titles, require exact match after normalization
if (normA.length < 5 || normB.length < 5) return normA === normB;
// "Dishonored 2" contains "Dishonored" but is another game
if (isSequelOf(normA, normB) || isSequelOf(normB, normA)) return false;
// Check if one contains the other (e.g. "The Witcher 3" vs "The Witcher 3: Wild Hunt")
// We check for word boundaries to avoid matching "Fable" with "Fabletown"
const regexA = new RegExp(`\\b${normA.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
const regexB = new RegExp(`\\b${normB.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i");
return regexA.test(normB) || regexB.test(normA);
}
/**
* Checks if a release name (dirty) matches a specific game title.
*/
export function releaseMatchesGame(releaseName: string, gameTitle: string): boolean {
// First try matching against the cleaned release name
const cleaned = cleanReleaseName(releaseName);
// A sequel of the wanted game must not get through the word-based fallback below either.
// This reads the raw name: cleanup drops tags that sit between the title and a number
// ("Dishonored.Update.2" would read as "Dishonored 2") and can drop the number itself
// ("Dishonored-2" looks like a group suffix). Stopword-free forms are checked too, since
// indexers often drop the "The".
const normRelease = normalizeTitle(releaseName);
const normGame = normalizeTitle(gameTitle);
if (
isSequelOf(normRelease, normGame) ||
isSequelOf(withoutStopWords(normRelease), withoutStopWords(normGame))
) {
return false;
}
if (titleMatches(cleaned, gameTitle)) return true;
// Fallback: Check if the normalized game title words are all present in the release name
// IMPROVED LOGIC:
// 1. Include numbers (for "Witcher 3" vs "Witcher 2")
// 2. Filter common stopwords
// 3. Require at least one "meaningful" word (> 2 chars or specific) to avoid matching "Stalker 2" against "Witcher 2" (via "2")
const gameWords = normalizeTitle(gameTitle)
.split(" ")
.filter((w) => {
// Keep if it's a number (length 1 allowed) OR length > 1
if (w.length < 2 && isNaN(Number(w))) return false;
// Filter stopwords
if (TITLE_STOP_WORDS.has(w)) return false;
return true;
});
// Calculate meaningful words (longer than 2 chars)
// If we have NO meaningful words (e.g. "Stalker 2" -> ["2"] where stalker is lost due to spaces, or "It"),
// disable fallback to prevent false positives.
const meaningfulWords = gameWords.filter((w) => w.length > 2);
if (meaningfulWords.length === 0) return false;
const normalizedRelease = releaseName.toLowerCase().replace(/[._-]/g, " ");
return gameWords.every((word) => normalizedRelease.includes(word));
}
// Trailing edition words an indexer rarely carries in the release name ("... Game of the Year
// Edition", "... Remastered"). Only stripped at the end of the title.
const EDITION_SUFFIX_REGEX = new RegExp(
// a separator is required, so "HeartGold" or "Superedition" keep their last word
String.raw`(?:\s+|\s*[:\-\u2013\u2014]\s*)(?:the\s+)?` +
// adjectives that can be part of a title ("Persona 5 Royal", "Pokemon Gold") only count
// as edition metadata when followed by "edition"
String.raw`(?:(?:game\s+of\s+the\s+year|goty)(?:\s+edition)?|` +
String.raw`(?:deluxe|definitive|complete|ultimate|gold|enhanced|special|collector'?s|` +
String.raw`anniversary|standard|digital|premium|legendary|royal)\s+edition|` +
String.raw`remastered|remaster|director'?s\s+cut|edition)\s*$`,
"i"
);
// "Clive Barker's Hellraiser", "Sid Meier's Civilization VI": a possessive publisher or author
// prefix of two to four words in front of the actual title. A single possessive word is left
// alone: "Baldur's Gate" and "Assassin's Creed" are the title itself.
const POSSESSIVE_PREFIX_REGEX = /^(?:[\p{L}\p{N}.&]+\s+){1,3}[\p{L}\p{N}.&]+['\u2019]s\s+(?=\S)/u;
function stripEditionWords(title: string): string {
let current = title.trim();
// "Foo: Deluxe Edition" -> "Foo"; repeated for "Foo Remastered Deluxe Edition"
for (let i = 0; i < 3; i++) {
const next = current.replace(EDITION_SUFFIX_REGEX, "").trim();
if (next === current || next.length < 3) break;
current = next;
}
return current;
}
function stripPossessivePrefix(title: string): string {
const stripped = title.replace(POSSESSIVE_PREFIX_REGEX, "").trim();
// A prefix cannot be told from the title's own words ("Little King's Story" is not "Story"),
// so a one-word remainder is not trusted: the full title stays the identity.
return stripped.length >= 3 && stripped.split(/\s+/).length >= 2 ? stripped : title;
}
function dropSubtitle(title: string): string {
const match = /^(.{3,}?)\s*(?::|\s[-\u2013\u2014]\s)/.exec(title);
return match?.[1]?.trim() ?? title;
}
function stripPunctuation(title: string): string {
return title
.replaceAll(/['\u2019]/g, "")
.replaceAll(/[^\p{L}\p{N}\s]/gu, " ")
.replaceAll(/\s+/g, " ")
.trim();
}
/**
* The title releases found through a fallback query are matched against: the full title minus
* only the parts indexers commonly leave out (a possessive publisher prefix, edition words).
* The subtitle stays, so a release of another game of the series ("Hellraiser.Inferno" for
* "Hellraiser: Revival") found through the subtitle-less query is not taken for the wanted one.
*/
export function strictMatchTitle(title: string): string {
return stripEditionWords(stripPossessivePrefix(title.trim()));
}
/**
* Fallback search queries for a game title whose full form returned nothing, from the least to
* the most lossy: without a possessive publisher prefix ("Clive Barker's Hellraiser: Revival" ->
* "Hellraiser: Revival"), without edition words, without punctuation, and finally without the
* subtitle after ":" or " - ". The original title is never part of the list and every variant
* is distinct and at least 4 characters long. Callers must still filter the results with
* releaseMatchesGame: a short variant ("Hellraiser") finds releases of a sequel as well.
*/
export function buildQueryVariants(title: string): string[] {
const original = title.trim();
if (!original) return [];
const noPossessive = stripPossessivePrefix(original);
const noEdition = stripEditionWords(original);
const noPossessiveNoEdition = stripEditionWords(noPossessive);
const bases = [noPossessive, noEdition, noPossessiveNoEdition];
const ordered: string[] = [
...bases,
// only of the most simplified base: punctuation of the longer forms would use up the
// fallback budget before the subtitle variants
stripPunctuation(noPossessiveNoEdition),
...[noPossessiveNoEdition, noPossessive, noEdition, original].map(dropSubtitle),
...[noPossessiveNoEdition, noPossessive, noEdition, original].map((t) =>
stripPunctuation(dropSubtitle(t))
),
];
// compared as typed (case and spacing aside): a variant that only drops punctuation is wanted
const keyOf = (t: string) => t.toLowerCase().replaceAll(/\s+/g, " ").trim();
const seen = new Set([keyOf(original)]);
const variants: string[] = [];
for (const candidate of ordered) {
const key = keyOf(candidate);
if (key.length < 4 || seen.has(key)) continue;
seen.add(key);
variants.push(candidate);
}
return variants;
}
export interface ReleaseMetadata {
gameTitle: string;
version?: string | undefined;
languages?: string[] | undefined;
group?: string | undefined;
platform?: string | undefined;
drm?: string | undefined;
isScene: boolean;
}
/**
* Parses a release name to extract as much metadata as possible.
*/
export function parseReleaseMetadata(releaseName: string): ReleaseMetadata {
const cleaned = releaseName.replace(/[._-]/g, " ");
// 1. Extract Group (usually after the last dash)
// More robust group detection: some releases use [Group] at start or end, or -Group at end
let group: string | undefined;
const dashGroupMatch = releaseName.match(/-(\w+)(?:\[\w+\])?$/);
if (dashGroupMatch) {
group = dashGroupMatch[1];
} else {
const bracketMatch = releaseName.match(/^\[(\w+)\]/);
if (bracketMatch) group = bracketMatch[1];
}
// 2. Extract Version
// Handles v1.0, v1 0, v1-0, build.123, etc.
const versionMatch = cleaned.match(/\b(v\d+([.\s-]\d+)*|build[.\s-]\d+)\b/i);
const version = versionMatch ? versionMatch[0].replace(/[\s-]/g, ".") : undefined;
// 3. Extract Languages
const languages: string[] = [];
if (/\b(multi\d*|multilingual)\b/i.test(cleaned)) languages.push("Multi");
if (/\bgerman\b/i.test(cleaned)) languages.push("German");
if (/\bfrench\b/i.test(cleaned)) languages.push("French");
if (/\bspanish\b/i.test(cleaned)) languages.push("Spanish");
if (/\bitalian\b/i.test(cleaned)) languages.push("Italian");
if (/\brussian\b/i.test(cleaned)) languages.push("Russian");
if (/\bjapanese\b/i.test(cleaned)) languages.push("Japanese");
if (/\benglish\b/i.test(cleaned)) languages.push("English");
// 4. Extract Platform using the shared target-platform catalog.
const platform = PLATFORM_CATALOG.find(({ releasePattern }) =>
releasePattern.test(cleaned)
)?.canonical;
// 5. DRM / Source
let drm: string | undefined;
if (/\bgog\b/i.test(cleaned)) drm = "GOG";
else if (/\bsteam\b/i.test(cleaned)) drm = "Steam";
else if (/\bepic\b/i.test(cleaned)) drm = "Epic";
else if (/\bdrm[ -]?free\b/i.test(cleaned)) drm = "DRM-Free";
// 6. Base Game Title (using existing cleanReleaseName logic)
const gameTitle = cleanReleaseName(releaseName);
return {
gameTitle,
version,
languages: languages.length > 0 ? languages : undefined,
group,
platform,
drm,
isScene: !!group && !["p2p", "gls", "initial", "rarbg", "crack"].includes(group.toLowerCase()),
};
}
/**
* Canonical release labels and their stable IGDB identities. Keep parsing aliases here so
* discovery selection and automation use the same cross-generation vocabulary.
*/
export const PLATFORM_CATALOG = [
{
canonical: "PS5",
igdbIds: [167],
igdbNames: ["PlayStation 5"],
releasePattern: /(?:^|[^a-z0-9])(ps5|playstation\s*5)(?=$|[^a-z0-9])/i,
},
{
canonical: "PS4",
igdbIds: [48],
igdbNames: ["PlayStation 4"],
releasePattern: /(?:^|[^a-z0-9])(ps4|playstation\s*4)(?=$|[^a-z0-9])/i,
},
{
canonical: "PS3",
igdbIds: [9],
igdbNames: ["PlayStation 3"],
releasePattern: /(?:^|[^a-z0-9])(ps3|playstation\s*3)(?=$|[^a-z0-9])/i,
},
{
canonical: "PS2",
igdbIds: [8],
igdbNames: ["PlayStation 2"],
releasePattern: /(?:^|[^a-z0-9])(ps2|playstation\s*2)(?=$|[^a-z0-9])/i,
},
{
canonical: "PS1",
igdbIds: [7],
igdbNames: ["PlayStation"],
releasePattern: /(?:^|[^a-z0-9])(psx|ps1|playstation\s*1)(?=$|[^a-z0-9])/i,
},
{
canonical: "PSP",
igdbIds: [38],
igdbNames: ["PlayStation Portable"],
releasePattern: /(?:^|[^a-z0-9])(psp|playstation\s*portable)(?=$|[^a-z0-9])/i,
},
{
canonical: "PSVita",
igdbIds: [46],
igdbNames: ["PlayStation Vita"],
releasePattern: /(?:^|[^a-z0-9])(ps\s?vita|vita)(?=$|[^a-z0-9])/i,
},
{
canonical: "Xbox Series",
igdbIds: [169],
igdbNames: ["Xbox Series X|S"],
releasePattern: /(?:^|[^a-z0-9])(xbox\s*series(?:\s*[xs])?|xbsx|xss)(?=$|[^a-z0-9])/i,
},
{
canonical: "Xbox One",
igdbIds: [49],
igdbNames: ["Xbox One"],
releasePattern: /(?:^|[^a-z0-9])(xbox\s*one|xbone)(?=$|[^a-z0-9])/i,
},
{
canonical: "Xbox 360",
igdbIds: [12],
igdbNames: ["Xbox 360"],
releasePattern: /(?:^|[^a-z0-9])(xbox\s*360|xbox360|x360)(?=$|[^a-z0-9])/i,
},
{
canonical: "Xbox Classic",
igdbIds: [11],
igdbNames: ["Xbox"],
releasePattern: /(?:^|[^a-z0-9])(xbox(?:\s*(?:classic|original))?|xb)(?=$|[^a-z0-9])/i,
},
{
canonical: "Switch 2",
igdbIds: [508],
igdbNames: ["Nintendo Switch 2"],
// Listed before Switch: the first matching entry wins, and NSP/XCI tags on a
// "Switch 2" release must not read as Switch.
releasePattern: /(?:^|[^a-z0-9])(nintendo\s*switch\s*2|switch\s*2)(?=$|[^a-z0-9])/i,
},
{
canonical: "Switch",
igdbIds: [130],
igdbNames: ["Nintendo Switch"],
// "Switch 2" releases are matched by the Switch 2 entry above, which comes first.
releasePattern: /(?:^|[^a-z0-9])(nintendo\s*switch|switch|nsw|nsp|xci)(?=$|[^a-z0-9])/i,
},
{
canonical: "GameCube",
igdbIds: [21],
igdbNames: ["Nintendo GameCube"],
releasePattern: /(?:^|[^a-z0-9])(game\s?cube|ngc|gc)(?=$|[^a-z0-9])/i,
},
{
canonical: "Wii U",
igdbIds: [41],
igdbNames: ["Wii U"],
releasePattern: /(?:^|[^a-z0-9])(wii\s*u|wiiu)(?=$|[^a-z0-9])/i,
},
{
canonical: "Wii",
igdbIds: [5],
igdbNames: ["Wii"],
releasePattern: /(?:^|[^a-z0-9])(wii)(?=$|[^a-z0-9])/i,
},
{
canonical: "3DS",
igdbIds: [37],
igdbNames: ["Nintendo 3DS"],
releasePattern: /(?:^|[^a-z0-9])(3ds)(?=$|[^a-z0-9])/i,
},
{
canonical: "NDS",
igdbIds: [20],
igdbNames: ["Nintendo DS"],
releasePattern: /(?:^|[^a-z0-9])(nds|nintendo\s*ds|ds)(?=$|[^a-z0-9])/i,
},
{
canonical: "N64",
igdbIds: [4],
igdbNames: ["Nintendo 64"],
releasePattern: /(?:^|[^a-z0-9])(n64|nintendo\s*64)(?=$|[^a-z0-9])/i,
},
{
canonical: "SNES",
igdbIds: [19],
igdbNames: ["Super Nintendo Entertainment System"],
releasePattern:
/(?:^|[^a-z0-9])(snes|super\s*nintendo|super\s*nes|super\s*famicom)(?=$|[^a-z0-9])/i,
},
{
canonical: "NES",
igdbIds: [18],
igdbNames: ["Nintendo Entertainment System"],
releasePattern: /(?:^|[^a-z0-9])(nes|famicom)(?=$|[^a-z0-9])/i,
},
{
canonical: "GBA",
igdbIds: [24],
igdbNames: ["Game Boy Advance"],
releasePattern: /(?:^|[^a-z0-9])(gba|game\s*boy\s*advance)(?=$|[^a-z0-9])/i,
},
{
canonical: "GBC",
igdbIds: [22],
igdbNames: ["Game Boy Color"],
releasePattern: /(?:^|[^a-z0-9])(gbc|game\s*boy\s*color)(?=$|[^a-z0-9])/i,
},
{
canonical: "GB",
igdbIds: [33],
igdbNames: ["Game Boy"],
releasePattern: /(?:^|[^a-z0-9])(game\s*boy|gb)(?=$|[^a-z0-9])/i,
},
{
canonical: "Dreamcast",
igdbIds: [23],
igdbNames: ["Dreamcast"],
releasePattern: /(?:^|[^a-z0-9])(dreamcast|dc)(?=$|[^a-z0-9])/i,
},
{
canonical: "Mega Drive",
igdbIds: [29],
igdbNames: ["Sega Mega Drive/Genesis"],
releasePattern: /(?:^|[^a-z0-9])(megadrive|mega\s*drive|genesis)(?=$|[^a-z0-9])/i,
},
{
canonical: "Game Gear",
igdbIds: [35],
igdbNames: ["Sega Game Gear"],
releasePattern: /(?:^|[^a-z0-9])(game\s*gear)(?=$|[^a-z0-9])/i,
},
{
canonical: "Master System",
igdbIds: [64],
igdbNames: ["Sega Master System/Mark III"],
releasePattern: /(?:^|[^a-z0-9])(master\s*system|sms)(?=$|[^a-z0-9])/i,
},
{
canonical: "Neo Geo",
igdbIds: [80],
igdbNames: ["Neo Geo AES"],
releasePattern: /(?:^|[^a-z0-9])(neo\s*geo|neogeo)(?=$|[^a-z0-9])/i,
},
{
canonical: "Atari 2600",
igdbIds: [59],
igdbNames: ["Atari 2600"],
releasePattern: /(?:^|[^a-z0-9])(atari\s*2600|a2600)(?=$|[^a-z0-9])/i,
},
{
canonical: "PC",
igdbIds: [6],
igdbNames: ["PC (Microsoft Windows)"],
releasePattern: /(?:^|[^a-z0-9])(pc|windows|win64|win32)(?=$|[^a-z0-9])/i,
},
{
canonical: "Linux",
igdbIds: [3],
igdbNames: ["Linux"],
releasePattern: /(?:^|[^a-z0-9])(linux)(?=$|[^a-z0-9])/i,
},
{
canonical: "Mac",
igdbIds: [14],
igdbNames: ["Mac"],
releasePattern: /(?:^|[^a-z0-9])(mac|macos|osx)(?=$|[^a-z0-9])/i,
},
] as const;
export type CanonicalPlatform = (typeof PLATFORM_CATALOG)[number]["canonical"];
// Keep the legacy account-wide Xbox umbrella selectable while explicit game targets use
// generation-specific catalog entries.
export const CANONICAL_PLATFORMS: readonly string[] = [
"Xbox",
...PLATFORM_CATALOG.map(({ canonical }) => canonical),
];
const normalizePlatformName = (value: string) => value.toLowerCase().replace(/[^a-z0-9]+/g, "");
/** Resolves a stored IGDB platform pair to the release label used by automation. */
export function resolveTargetPlatform(
targetPlatformId: number | null | undefined,
targetPlatformName: string | null | undefined
): CanonicalPlatform | null {
if (targetPlatformId == null || !targetPlatformName) return null;
const normalizedName = normalizePlatformName(targetPlatformName);
return (
PLATFORM_CATALOG.find(
({ igdbIds, igdbNames }) =>
(igdbIds as readonly number[]).includes(targetPlatformId) &&
igdbNames.some((name) => normalizePlatformName(name) === normalizedName)
)?.canonical ?? null
);
}
export const UNSUPPORTED_TARGET_PLATFORM = "__unsupported_target_platform__";
/** Resolve a game's explicit target or preserve the account-wide fallback for legacy rows. */
export function resolveGamePlatformPreference(
game: { targetPlatformId?: number | null; targetPlatformName?: string | null },
fallback: string | null
): string | null {
const hasTargetId = game.targetPlatformId != null;
const hasTargetName = game.targetPlatformName != null;
if (!hasTargetId && !hasTargetName) return fallback;
if (!hasTargetId || !hasTargetName) return UNSUPPORTED_TARGET_PLATFORM;
return (
resolveTargetPlatform(game.targetPlatformId, game.targetPlatformName) ??
UNSUPPORTED_TARGET_PLATFORM
);
}
/**
* Returns true if a release's detected platform matches the preferred platform filter.
*
* PC is special: many PC releases omit any platform marker in their title, so "PC"
* matches both releases explicitly detected as "PC" and releases with no detected platform.
* All non-PC platforms require an explicit detected platform match.
*/
export function matchesPlatformFilter(
releasePlatform: string | undefined,
preferredPlatform: string
): boolean {
if (preferredPlatform === "PC") {
return !releasePlatform || releasePlatform === "PC";
}
// Preserve the legacy account-wide "Xbox" setting as a cross-generation umbrella.
if (preferredPlatform === "Xbox") {
return ["Xbox", "Xbox Classic", "Xbox 360", "Xbox One", "Xbox Series"].includes(
releasePlatform ?? ""
);
}
return releasePlatform === preferredPlatform;
}
/**
* Safely parses a JSON-encoded string array.
* Returns an empty array if the value is null/undefined, not valid JSON, or not an array.
*/
export function parseJsonStringArray(value: string | null | undefined): string[] {
if (!value) return [];
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) && parsed.every((entry) => typeof entry === "string")
? (parsed as string[])
: [];
} catch {
return [];
}
}