diff --git a/apps/api/src/modules/competition/competition.presenter.spec.ts b/apps/api/src/modules/competition/competition.presenter.spec.ts new file mode 100644 index 00000000..958046bf --- /dev/null +++ b/apps/api/src/modules/competition/competition.presenter.spec.ts @@ -0,0 +1,97 @@ +import { presentCompetitionDetail } from './competition.presenter'; + +describe('presentCompetitionDetail', () => { + it('returns the explicit public contract without persistence-only fields', () => { + const response = presentCompetitionDetail({ + _id: objectId('competition-1'), + matchId: objectId('match-1'), + communityId: objectId('community-1'), + schemaVersion: 1, + projectorVersion: 3, + revision: 7, + phase: 'running', + teams: [ + { + teamId: objectId('team-8'), + legacyTeamIndex: 8, + displayOrder: 2, + seedNumber: 2, + name: '똥칼라파워', + captainUserId: objectId('captain-8'), + members: [ + { + userId: objectId('user-8'), + displayName: 'player 8', + gameName: '칼라', + tagLine: 'KR1', + assignedPosition: 'MID', + cost: 42, + secretPuuid: 'must-not-leak', + }, + ], + }, + ], + format: { + type: 'paired-series', + rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' }, + }, + seriesGraph: [{ internal: true }], + projection: { + sourceRevision: 7, + projectorVersion: 3, + phase: 'running', + formatType: 'paired-series', + series: [], + games: [], + gameSlots: [], + rounds: [], + connectors: [], + }, + internalCommandReceipts: [{ idempotencyKey: 'secret' }], + createdAt: new Date('2026-07-11T00:00:00.000Z'), + updatedAt: new Date('2026-07-12T00:00:00.000Z'), + }); + + expect(response).toMatchObject({ + id: 'competition-1', + matchId: 'match-1', + communityId: 'community-1', + schemaVersion: 1, + revision: 7, + phase: 'running', + createdAt: '2026-07-11T00:00:00.000Z', + updatedAt: '2026-07-12T00:00:00.000Z', + teams: [ + { + teamId: 'team-8', + displayOrder: 2, + name: '똥칼라파워', + captainUserId: 'captain-8', + members: [ + { + userId: 'user-8', + displayName: 'player 8', + gameName: '칼라', + tagLine: 'KR1', + assignedPosition: 'MID', + cost: 42, + }, + ], + }, + ], + projection: { + sourceRevision: 7, + projectorVersion: 3, + }, + }); + expect(response).not.toHaveProperty('seriesGraph'); + expect(response).not.toHaveProperty('internalCommandReceipts'); + expect(response.teams[0]).not.toHaveProperty('legacyTeamIndex'); + expect(response.teams[0]).not.toHaveProperty('seedNumber'); + expect(response.teams[0].members[0]).not.toHaveProperty('secretPuuid'); + }); +}); + +function objectId(value: string) { + return { toString: () => value }; +} diff --git a/apps/api/src/modules/competition/competition.presenter.ts b/apps/api/src/modules/competition/competition.presenter.ts new file mode 100644 index 00000000..925a38c7 --- /dev/null +++ b/apps/api/src/modules/competition/competition.presenter.ts @@ -0,0 +1,115 @@ +import type { + CommunityId, + CompetitionDetailResponse, + CompetitionFormat, + CompetitionId, + CompetitionPhase, + CompetitionProjection, + MatchId, + PlayerPosition, + TeamId, + UserId, +} from '@lolympus/contracts'; + +type IdLike = string | { toString(): string }; + +interface CompetitionMemberSource { + userId: IdLike; + displayName: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + assignedPosition?: string; + cost?: number; + [key: string]: unknown; +} + +interface CompetitionTeamSource { + teamId: IdLike; + displayOrder: number; + name: string; + captainUserId?: IdLike; + members: CompetitionMemberSource[]; + [key: string]: unknown; +} + +export interface CompetitionDetailSource { + _id: IdLike; + matchId: IdLike; + communityId: IdLike; + schemaVersion: number; + revision: number; + phase: CompetitionPhase; + teams: CompetitionTeamSource[]; + format: Record; + projection: Record; + createdAt: Date | string; + updatedAt: Date | string; + [key: string]: unknown; +} + +/** Build the public wire DTO without ever spreading a persistence document. */ +export function presentCompetitionDetail( + source: CompetitionDetailSource, +): CompetitionDetailResponse { + return { + id: asId(source._id), + matchId: asId(source.matchId), + communityId: asId(source.communityId), + schemaVersion: source.schemaVersion, + revision: source.revision, + phase: source.phase, + teams: source.teams.map((team) => ({ + teamId: asId(team.teamId), + displayOrder: team.displayOrder, + name: team.name, + ...(team.captainUserId + ? { captainUserId: asId(team.captainUserId) } + : {}), + members: team.members.map((member) => ({ + userId: asId(member.userId), + displayName: member.displayName, + ...(member.gameName ? { gameName: member.gameName } : {}), + ...(member.tagLine ? { tagLine: member.tagLine } : {}), + ...(member.profileIconId !== undefined + ? { profileIconId: member.profileIconId } + : {}), + ...(member.assignedPosition + ? { assignedPosition: member.assignedPosition as PlayerPosition } + : {}), + ...(member.cost !== undefined ? { cost: member.cost } : {}), + })), + })), + format: toWireValue(source.format) as CompetitionFormat, + projection: toWireValue(source.projection) as CompetitionProjection, + createdAt: asIsoDateTime(source.createdAt), + updatedAt: asIsoDateTime(source.updatedAt), + }; +} + +function asId(value: IdLike): T { + return value.toString() as T; +} + +function asIsoDateTime(value: Date | string): string { + return value instanceof Date ? value.toISOString() : value; +} + +function toWireValue(value: unknown): unknown { + if (value instanceof Date) return value.toISOString(); + if (Array.isArray(value)) return value.map(toWireValue); + if (isPlainRecord(value)) { + return Object.fromEntries( + Object.entries(value).map(([key, entry]) => [key, toWireValue(entry)]), + ); + } + return value; +} + +function isPlainRecord(value: unknown): value is Record { + return ( + typeof value === 'object' && + value !== null && + Object.getPrototypeOf(value) === Object.prototype + ); +} diff --git a/apps/api/src/modules/competition/domain/competition-projector.spec.ts b/apps/api/src/modules/competition/domain/competition-projector.spec.ts new file mode 100644 index 00000000..509d62d9 --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-projector.spec.ts @@ -0,0 +1,399 @@ +import { projectCompetition } from './competition-projector'; +import { generateSeriesGraph } from './series-graph'; + +describe('projectCompetition', () => { + it('keeps a three-way round-robin cycle on a shared rank', () => { + const competitionId = 'competition-round-robin-tie'; + const teams = ['team-1', 'team-2', 'team-3'].map((teamId, index) => ({ + teamId, + displayOrder: index + 1, + seedNumber: index + 1, + })); + const format = { + type: 'round-robin' as const, + rule: fixedGames(1), + tieBreakers: ['series-wins', 'game-diff', 'head-to-head'] as const, + }; + const seriesGraph = generateSeriesGraph({ + competitionId, + teams, + format, + }); + const accept = acceptedGameFactory(competitionId); + const oneVersusTwo = requireRoundRobinSeries( + seriesGraph, + 'team-1', + 'team-2', + ); + const oneVersusThree = requireRoundRobinSeries( + seriesGraph, + 'team-1', + 'team-3', + ); + const twoVersusThree = requireRoundRobinSeries( + seriesGraph, + 'team-2', + 'team-3', + ); + const facts = [ + accept(oneVersusTwo, 1, 'team-1', 'team-2', 'team-1'), + accept(twoVersusThree, 1, 'team-2', 'team-3', 'team-2'), + accept(oneVersusThree, 1, 'team-3', 'team-1', 'team-3'), + ]; + + const projection = projectCompetition({ + competitionId, + revision: facts.length, + projectorVersion: 1, + teams, + format, + seriesGraph, + facts, + }); + + expect(projection.outcome).toEqual({ + type: 'round-robin', + leaderTeamIds: ['team-1', 'team-2', 'team-3'], + standings: [ + standing('team-1', 1), + standing('team-2', 1), + standing('team-3', 1), + ], + completedAt: '2026-07-12T00:00:03.000Z', + }); + expect(projection.games).toHaveLength(3); + expect(projection.gameSlots).toHaveLength(3); + expect(projection.rounds).toEqual( + expect.arrayContaining([ + expect.objectContaining({ stage: 'round-robin', roundNumber: 1 }), + ]), + ); + }); + + it('attributes WB_R2_M2 wins to team ids when series and bracket slot orders differ', () => { + const competitionId = 'competition-wb-r2-m2-regression'; + const teams = [ + seededTeam('team-1', 1), + seededTeam('team-8', 2), + seededTeam('team-3', 3), + seededTeam('team-4', 4), + seededTeam('team-5', 5), + seededTeam('team-6', 6), + seededTeam('team-7', 7), + seededTeam('team-2', 8), + ]; + const format = doubleEliminationFormat({ upperWinsRequired: 2 }); + const seriesGraph = generateSeriesGraph({ + competitionId, + teams, + format, + }); + const wbRoundOneMatchThree = requireSeries(seriesGraph, 'WB_R1_M3'); + const wbRoundOneMatchFour = requireSeries(seriesGraph, 'WB_R1_M4'); + const wbRoundTwoMatchTwo = requireSeries(seriesGraph, 'WB_R2_M2'); + const accept = acceptedGameFactory(competitionId); + const facts = [ + accept(wbRoundOneMatchThree, 1, 'team-8', 'team-7', 'team-8'), + accept(wbRoundOneMatchThree, 2, 'team-7', 'team-8', 'team-8'), + accept(wbRoundOneMatchFour, 1, 'team-3', 'team-6', 'team-3'), + accept(wbRoundOneMatchFour, 2, 'team-6', 'team-3', 'team-3'), + accept(wbRoundTwoMatchTwo, 1, 'team-3', 'team-8', 'team-8'), + accept(wbRoundTwoMatchTwo, 2, 'team-8', 'team-3', 'team-3'), + accept(wbRoundTwoMatchTwo, 3, 'team-3', 'team-8', 'team-8'), + ]; + + const projection = projectCompetition({ + competitionId, + revision: facts.length, + projectorVersion: 1, + teams, + format, + seriesGraph, + facts, + }); + + expect(projectedSeries(projection, 'WB_R2_M2')).toMatchObject({ + status: 'completed', + entries: [ + { slot: 'A', teamId: 'team-8', gameWins: 2 }, + { slot: 'B', teamId: 'team-3', gameWins: 1 }, + ], + outcome: { + type: 'played', + winnerTeamId: 'team-8', + loserTeamId: 'team-3', + }, + }); + expect(projectedSeries(projection, 'WB_FINAL')).toMatchObject({ + entries: expect.arrayContaining([ + { slot: 'B', teamId: 'team-8', gameWins: 0 }, + ]), + }); + expect(projectedSeries(projection, 'LB_R2_M1')).toMatchObject({ + entries: expect.arrayContaining([ + { slot: 'B', teamId: 'team-3', gameWins: 0 }, + ]), + }); + expect(projection.games).toHaveLength(7); + expect( + projection.games.filter( + (game) => game.seriesId === wbRoundTwoMatchTwo.id, + ), + ).toEqual([ + expect.objectContaining({ winnerTeamId: 'team-8', ordinal: 1 }), + expect.objectContaining({ winnerTeamId: 'team-3', ordinal: 2 }), + expect.objectContaining({ winnerTeamId: 'team-8', ordinal: 3 }), + ]); + expect( + projection.connectors.some( + (connector) => + connector.from.seriesId === wbRoundTwoMatchTwo.id && + connector.from.select === 'winner' && + connector.to.slot === 'B', + ), + ).toBe(true); + }); + + it('activates the predefined reset final only when the lower-bracket finalist wins GF', () => { + const competitionId = 'competition-grand-final-reset'; + const teams = Array.from({ length: 4 }, (_, index) => + seededTeam(`team-${index + 1}`, index + 1), + ); + const format = doubleEliminationFormat({ upperWinsRequired: 1 }); + const seriesGraph = generateSeriesGraph({ + competitionId, + teams, + format, + }); + const resetDefinition = requireSeries(seriesGraph, 'GF_RESET'); + + const initial = projectCompetition({ + competitionId, + revision: 0, + projectorVersion: 1, + teams, + format, + seriesGraph, + facts: [], + }); + expect(projectedSeries(initial, 'GF_RESET')).toMatchObject({ + seriesId: resetDefinition.id, + status: 'inactive', + }); + + const accept = acceptedGameFactory(competitionId); + const facts = [ + accept( + requireSeries(seriesGraph, 'WB_R1_M1'), + 1, + 'team-1', + 'team-4', + 'team-1', + ), + accept( + requireSeries(seriesGraph, 'WB_R1_M2'), + 1, + 'team-2', + 'team-3', + 'team-2', + ), + accept( + requireSeries(seriesGraph, 'WB_FINAL'), + 1, + 'team-1', + 'team-2', + 'team-1', + ), + accept( + requireSeries(seriesGraph, 'LB_R1_M1'), + 1, + 'team-3', + 'team-4', + 'team-3', + ), + accept( + requireSeries(seriesGraph, 'LB_FINAL'), + 1, + 'team-3', + 'team-2', + 'team-2', + ), + accept(requireSeries(seriesGraph, 'GF'), 1, 'team-2', 'team-1', 'team-2'), + ]; + + const afterGrandFinal = projectCompetition({ + competitionId, + revision: facts.length, + projectorVersion: 1, + teams, + format, + seriesGraph, + facts, + }); + + expect(projectedSeries(afterGrandFinal, 'GF_RESET')).toMatchObject({ + seriesId: resetDefinition.id, + status: 'ready', + entries: [ + { slot: 'A', teamId: 'team-1', gameWins: 0 }, + { slot: 'B', teamId: 'team-2', gameWins: 0 }, + ], + }); + expect(afterGrandFinal).not.toHaveProperty('outcome'); + expect(afterGrandFinal.gameSlots).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + seriesId: resetDefinition.id, + status: 'ready', + entries: [ + { slot: 'A', teamId: 'team-1' }, + { slot: 'B', teamId: 'team-2' }, + ], + }), + ]), + ); + }); +}); + +function fixedGames(gameCount: number) { + return { + type: 'fixed-games' as const, + gameCount, + drawPolicy: 'allow' as const, + }; +} + +function seededTeam(teamId: string, seedNumber: number) { + return { teamId, displayOrder: seedNumber, seedNumber }; +} + +function doubleEliminationFormat(params: { upperWinsRequired: 1 | 2 }) { + const upper = + params.upperWinsRequired === 1 + ? { type: 'first-to' as const, winsRequired: 1, maxGames: 1 } + : { type: 'first-to' as const, winsRequired: 2, maxGames: 3 }; + const singleGame = { + type: 'first-to' as const, + winsRequired: 1, + maxGames: 1, + }; + return { + type: 'double-elimination' as const, + resetFinalEnabled: true, + rules: { + upper, + lower: singleGame, + grandFinal: singleGame, + resetFinal: singleGame, + }, + }; +} + +function requireSeries< + T extends { code?: string; id: string; gameSlots: Array }, +>(graph: T[], code: string): T { + const definition = graph.find((series) => series.code === code); + if (!definition) throw new Error(`Missing series ${code}`); + return definition; +} + +function requireRoundRobinSeries< + T extends { + id: string; + gameSlots: Array; + slots: Array<{ source: { type: string; teamId?: string } }>; + }, +>(graph: T[], leftTeamId: string, rightTeamId: string): T { + const expected = new Set([leftTeamId, rightTeamId]); + const definition = graph.find((series) => { + const actual = series.slots + .filter((slot) => slot.source.type === 'team') + .map((slot) => slot.source.teamId); + return ( + actual.length === 2 && actual.every((teamId) => expected.has(teamId!)) + ); + }); + if (!definition) { + throw new Error(`Missing round-robin series ${leftTeamId}/${rightTeamId}`); + } + return definition; +} + +function acceptedGameFactory(competitionId: string) { + let revision = 0; + return }>( + definition: T, + ordinal: number, + blueTeamId: string, + redTeamId: string, + winnerTeamId: string, + ) => { + revision += 1; + const gameSlot = definition.gameSlots.find( + (candidate) => candidate.ordinal === ordinal, + ); + if (!gameSlot) { + throw new Error(`Missing game slot ${definition.id}/${ordinal}`); + } + return { + id: `fact-${revision}`, + type: 'game-accepted' as const, + competitionId, + revision, + ordinalWithinRevision: 1, + commandId: `command-${revision}`, + schemaVersion: 1, + actor: { type: 'system' as const }, + occurredAt: new Date( + `2026-07-12T00:00:${String(revision).padStart(2, '0')}.000Z`, + ), + recordedAt: new Date( + `2026-07-12T00:01:${String(revision).padStart(2, '0')}.000Z`, + ), + gameId: `game-${revision}`, + seriesId: definition.id, + gameSlotId: gameSlot.id, + ordinal, + evidence: { + type: 'riot' as const, + riotMatchId: `KR_${competitionId}_${revision}`, + payloadHash: `sha256:${competitionId}:${revision}`, + }, + mapping: { + mappingVersion: 1, + confidence: 1, + blueTeamId, + redTeamId, + winnerTeamId, + participantAssignments: [], + }, + }; + }; +} + +function projectedSeries< + T extends { series: Array<{ code?: string; seriesId: string }> }, +>(projection: T, code: string) { + const series = projection.series.find((candidate) => candidate.code === code); + if (!series) throw new Error(`Missing projected series ${code}`); + return series; +} + +function standing(teamId: string, rank: number) { + return { + teamId, + rank, + seriesPlayed: 2, + seriesWins: 1, + seriesLosses: 1, + seriesDraws: 0, + gameWins: 1, + gameLosses: 1, + gameDiff: 0, + }; +} + +interface GameSlotLike { + id: string; + ordinal: number; +} diff --git a/apps/api/src/modules/competition/domain/competition-projector.ts b/apps/api/src/modules/competition/domain/competition-projector.ts new file mode 100644 index 00000000..d0a0b54e --- /dev/null +++ b/apps/api/src/modules/competition/domain/competition-projector.ts @@ -0,0 +1,936 @@ +import type { + CompetitionGraphFormat, + CompetitionGraphTeam, + ParticipantSource, + SeriesDefinition, +} from './series-graph'; +import { + projectSeries, + type SeriesDefinitionLike, + type SeriesProjection, + type SeriesProjectionOutcome, +} from './series-projector'; + +export interface ProjectCompetitionInput { + competitionId: string; + revision: number; + projectorVersion: number; + teams: readonly CompetitionGraphTeam[]; + format: CompetitionGraphFormat; + seriesGraph: readonly SeriesDefinition[]; + facts: readonly unknown[]; +} + +export interface RoundRobinStanding { + teamId: string; + rank: number; + seriesPlayed: number; + seriesWins: number; + seriesLosses: number; + seriesDraws: number; + gameWins: number; + gameLosses: number; + gameDiff: number; +} + +export interface CompetitionPlacement { + teamId: string; + rank: number; +} + +export interface CompetitionGameProjection { + id: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + displayNumber: number; + evidence: + | { type: 'riot'; riotMatchId: string } + | { type: 'legacy'; legacyReference: string }; + teams: { + blue: { side: 'blue'; teamId: string }; + red: { side: 'red'; teamId: string }; + }; + winnerTeamId: string; + startedAt: string; + durationSeconds: number; + participants: unknown[]; +} + +export interface GameSlotProjection { + id: string; + seriesId: string; + ordinal: number; + displayNumber: number; + status: 'inactive' | 'waiting' | 'ready' | 'completed' | 'voided'; + entries: [ + { slot: 'A'; teamId: string | null }, + { slot: 'B'; teamId: string | null }, + ]; + gameId?: string; +} + +export interface BracketRoundProjection { + stage: SeriesDefinition['stage']['type']; + roundNumber?: number; + displayOrder: number; + label: string; + seriesIds: string[]; +} + +export interface SeriesConnectorProjection { + from: { + seriesId: string; + select: 'winner' | 'loser' | 'slot-a' | 'slot-b'; + }; + to: { seriesId: string; slot: 'A' | 'B' }; +} + +export type CompetitionProjectionOutcome = + | { + type: 'paired-series'; + completedSeriesIds: string[]; + drawnSeriesIds: string[]; + completedAt: string; + } + | { + type: 'round-robin'; + leaderTeamIds: string[]; + standings: RoundRobinStanding[]; + completedAt: string; + } + | { + type: 'double-elimination'; + championTeamId: string; + placements: CompetitionPlacement[]; + completedAt: string; + }; + +export interface CompetitionProjection { + competitionId: string; + sourceRevision: number; + projectorVersion: number; + formatType: CompetitionGraphFormat['type']; + phase: 'ready' | 'running' | 'completed'; + series: SeriesProjection[]; + games: CompetitionGameProjection[]; + gameSlots: GameSlotProjection[]; + rounds: BracketRoundProjection[]; + connectors: SeriesConnectorProjection[]; + standings?: RoundRobinStanding[]; + placements?: CompetitionPlacement[]; + outcome?: CompetitionProjectionOutcome; +} + +/** + * Rebuilds all official Competition state from the immutable graph and fact + * ledger. Participant identity is always resolved through explicit sources; + * display codes and slot/array order are never used as team identity. + */ +export function projectCompetition( + input: ProjectCompetitionInput, +): CompetitionProjection { + const teamBySeed = new Map(); + const knownTeams = new Set(); + for (const team of input.teams) { + knownTeams.add(team.teamId); + if (team.seedNumber !== undefined) { + teamBySeed.set(team.seedNumber, team.teamId); + } + } + + const definitionsById = new Map( + input.seriesGraph.map((definition) => [definition.id, definition]), + ); + const projectedById = new Map(); + const remaining = new Set(input.seriesGraph.map(({ id }) => id)); + + // A graph can be stored in any display order. Resolve it as a DAG rather + // than relying on that order or parsing diagnostic codes such as WB_R2_M2. + let madeProgress = true; + while (remaining.size > 0 && madeProgress) { + madeProgress = false; + + for (const seriesId of [...remaining]) { + const definition = definitionsById.get(seriesId)!; + const activation = resolveActivation(definition, projectedById); + if (activation === 'pending') continue; + + if (activation === 'inactive') { + projectedById.set( + definition.id, + projectSeries({ + definition: asProjectorDefinition(definition), + participants: resolveAvailableParticipants( + definition, + knownTeams, + teamBySeed, + projectedById, + ), + facts: input.facts, + active: false, + }), + ); + remaining.delete(seriesId); + madeProgress = true; + continue; + } + + const participants = definition.slots.map(({ source }) => + resolveParticipant(source, knownTeams, teamBySeed, projectedById), + ); + if (participants.some((teamId) => teamId === undefined)) continue; + + projectedById.set( + definition.id, + projectSeries({ + definition: asProjectorDefinition(definition), + participants, + facts: input.facts, + }), + ); + remaining.delete(seriesId); + madeProgress = true; + } + } + + // An unresolved outcome source is a normal waiting bracket node. Conditional + // reset nodes remain inactive until their grand-final condition is known. + for (const seriesId of remaining) { + const definition = definitionsById.get(seriesId)!; + const participants = resolveAvailableParticipants( + definition, + knownTeams, + teamBySeed, + projectedById, + ); + projectedById.set( + definition.id, + projectSeries({ + definition: asProjectorDefinition(definition), + participants, + facts: input.facts, + ...(definition.activation ? { active: false } : {}), + }), + ); + } + + const series = input.seriesGraph.map(({ id }) => projectedById.get(id)!); + const gameProjection = projectGamesAndSlots( + input.seriesGraph, + series, + input.facts, + ); + const common = { + competitionId: input.competitionId, + sourceRevision: input.revision, + projectorVersion: input.projectorVersion, + formatType: input.format.type, + series, + games: gameProjection.games, + gameSlots: gameProjection.gameSlots, + rounds: projectRounds(input.seriesGraph), + connectors: projectConnectors(input.seriesGraph), + }; + + switch (input.format.type) { + case 'paired-series': { + const outcome = pairedSeriesOutcome(series); + return { + ...common, + phase: phaseFor(series, outcome), + ...(outcome ? { outcome } : {}), + }; + } + case 'round-robin': { + const standings = roundRobinStandings(input.teams, series); + const outcome = + series.length > 0 && + series.every(({ status }) => status === 'completed') + ? { + type: 'round-robin' as const, + leaderTeamIds: standings + .filter(({ rank }) => rank === 1) + .map(({ teamId }) => teamId), + standings, + completedAt: competitionCompletedAt(series), + } + : undefined; + return { + ...common, + phase: phaseFor(series, outcome), + standings, + ...(outcome ? { outcome } : {}), + }; + } + case 'double-elimination': { + const outcome = doubleEliminationOutcome( + input.teams, + input.format.resetFinalEnabled, + series, + ); + return { + ...common, + phase: phaseFor(series, outcome), + placements: outcome?.placements ?? [], + ...(outcome ? { outcome } : {}), + }; + } + } +} + +function asProjectorDefinition( + definition: SeriesDefinition, +): SeriesDefinitionLike { + return definition as unknown as SeriesDefinitionLike; +} + +function resolveActivation( + definition: SeriesDefinition, + projections: ReadonlyMap, +): 'active' | 'inactive' | 'pending' { + if (!definition.activation) return 'active'; + + const grandFinal = projections.get(definition.activation.grandFinalSeriesId); + if (!grandFinal || grandFinal.status !== 'completed') return 'pending'; + if (grandFinal.outcome.type === 'draw') return 'inactive'; + + const lowerBracketFinalist = grandFinal.entries.find( + ({ slot }) => slot === 'B', + )?.teamId; + return grandFinal.outcome.winnerTeamId === lowerBracketFinalist + ? 'active' + : 'inactive'; +} + +function resolveAvailableParticipants( + definition: SeriesDefinition, + knownTeams: ReadonlySet, + teamBySeed: ReadonlyMap, + projections: ReadonlyMap, +): Array { + return definition.slots.map( + ({ source }) => + resolveParticipant(source, knownTeams, teamBySeed, projections) ?? null, + ); +} + +function resolveParticipant( + source: ParticipantSource, + knownTeams: ReadonlySet, + teamBySeed: ReadonlyMap, + projections: ReadonlyMap, +): string | undefined { + switch (source.type) { + case 'team': + return knownTeams.has(source.teamId) ? source.teamId : undefined; + case 'seed': + return teamBySeed.get(source.seedNumber); + case 'series-outcome': { + const sourceSeries = projections.get(source.seriesId); + if (!sourceSeries || sourceSeries.status !== 'completed') { + return undefined; + } + if (sourceSeries.outcome.type === 'draw') return undefined; + return source.select === 'winner' + ? sourceSeries.outcome.winnerTeamId + : sourceSeries.outcome.loserTeamId; + } + case 'series-slot': { + const sourceSeries = projections.get(source.seriesId); + return ( + sourceSeries?.entries.find(({ slot }) => slot === source.slot) + ?.teamId ?? undefined + ); + } + } +} + +function pairedSeriesOutcome( + series: readonly SeriesProjection[], +): + | Extract + | undefined { + if ( + series.length === 0 || + !series.every(({ status }) => status === 'completed') + ) { + return undefined; + } + return { + type: 'paired-series', + completedSeriesIds: series + .filter( + (candidate) => + candidate.status === 'completed' && candidate.outcome.type !== 'draw', + ) + .map(({ seriesId }) => seriesId), + completedAt: competitionCompletedAt(series), + drawnSeriesIds: series + .filter( + (candidate) => + candidate.status === 'completed' && candidate.outcome.type === 'draw', + ) + .map(({ seriesId }) => seriesId), + }; +} + +function roundRobinStandings( + teams: readonly CompetitionGraphTeam[], + series: readonly SeriesProjection[], +): RoundRobinStanding[] { + const standingByTeam = new Map( + teams.map((team) => [team.teamId, emptyStanding(team.teamId)]), + ); + const completed = series.filter( + (candidate): candidate is SeriesProjection & { status: 'completed' } => + candidate.status === 'completed', + ); + + for (const projected of completed) { + addSeriesToStandings(standingByTeam, projected); + } + + const displayOrderByTeam = new Map( + teams.map(({ teamId, displayOrder }) => [teamId, displayOrder]), + ); + const base = [...standingByTeam.values()].sort( + (left, right) => + right.seriesWins - left.seriesWins || + right.gameDiff - left.gameDiff || + stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam), + ); + + const ranked: RoundRobinStanding[] = []; + let start = 0; + while (start < base.length) { + let end = start + 1; + while ( + end < base.length && + base[end].seriesWins === base[start].seriesWins && + base[end].gameDiff === base[start].gameDiff + ) { + end += 1; + } + + const tiedGroup = base.slice(start, end); + const teamIds = new Set(tiedGroup.map(({ teamId }) => teamId)); + const miniTable = new Map( + tiedGroup.map(({ teamId }) => [teamId, emptyMiniTableRow()]), + ); + for (const projected of completed) { + const participants = projected.entries.map(({ teamId }) => teamId); + if ( + participants.length === 2 && + participants.every( + (teamId): teamId is string => teamId !== null && teamIds.has(teamId), + ) + ) { + addSeriesToMiniTable(miniTable, projected); + } + } + + tiedGroup.sort((left, right) => { + const leftMini = miniTable.get(left.teamId)!; + const rightMini = miniTable.get(right.teamId)!; + return ( + rightMini.seriesWins - leftMini.seriesWins || + rightMini.gameDiff - leftMini.gameDiff || + stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam) + ); + }); + + let tiedStart = 0; + while (tiedStart < tiedGroup.length) { + const reference = miniTable.get(tiedGroup[tiedStart].teamId)!; + let tiedEnd = tiedStart + 1; + while (tiedEnd < tiedGroup.length) { + const candidate = miniTable.get(tiedGroup[tiedEnd].teamId)!; + if ( + candidate.seriesWins !== reference.seriesWins || + candidate.gameDiff !== reference.gameDiff + ) { + break; + } + tiedEnd += 1; + } + + const rank = start + tiedStart + 1; + for (const standing of tiedGroup.slice(tiedStart, tiedEnd)) { + ranked.push({ ...standing, rank }); + } + tiedStart = tiedEnd; + } + start = end; + } + + return ranked; +} + +function emptyStanding(teamId: string): RoundRobinStanding { + return { + teamId, + rank: 0, + seriesWins: 0, + seriesLosses: 0, + seriesDraws: 0, + seriesPlayed: 0, + gameWins: 0, + gameLosses: 0, + gameDiff: 0, + }; +} + +function addSeriesToStandings( + rows: Map, + projected: SeriesProjection & { status: 'completed' }, +): void { + const [entryA, entryB] = projected.entries; + if (entryA.teamId === null || entryB.teamId === null) return; + const rowA = rows.get(entryA.teamId); + const rowB = rows.get(entryB.teamId); + if (!rowA || !rowB) return; + + rowA.gameWins += entryA.gameWins; + rowA.gameLosses += entryB.gameWins; + rowB.gameWins += entryB.gameWins; + rowB.gameLosses += entryA.gameWins; + rowA.gameDiff = rowA.gameWins - rowA.gameLosses; + rowB.gameDiff = rowB.gameWins - rowB.gameLosses; + rowA.seriesPlayed += 1; + rowB.seriesPlayed += 1; + + if (projected.outcome.type === 'draw') { + rowA.seriesDraws += 1; + rowB.seriesDraws += 1; + return; + } + rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1; + rows.get(projected.outcome.loserTeamId)!.seriesLosses += 1; +} + +interface MiniTableRow { + seriesWins: number; + gameWins: number; + gameLosses: number; + gameDiff: number; +} + +function emptyMiniTableRow(): MiniTableRow { + return { seriesWins: 0, gameWins: 0, gameLosses: 0, gameDiff: 0 }; +} + +function addSeriesToMiniTable( + rows: Map, + projected: SeriesProjection & { status: 'completed' }, +): void { + const [entryA, entryB] = projected.entries; + if (entryA.teamId === null || entryB.teamId === null) return; + const rowA = rows.get(entryA.teamId)!; + const rowB = rows.get(entryB.teamId)!; + rowA.gameWins += entryA.gameWins; + rowA.gameLosses += entryB.gameWins; + rowB.gameWins += entryB.gameWins; + rowB.gameLosses += entryA.gameWins; + rowA.gameDiff = rowA.gameWins - rowA.gameLosses; + rowB.gameDiff = rowB.gameWins - rowB.gameLosses; + if (projected.outcome.type !== 'draw') { + rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1; + } +} + +function doubleEliminationOutcome( + teams: readonly CompetitionGraphTeam[], + resetFinalEnabled: boolean, + series: readonly SeriesProjection[], +): + | Extract + | undefined { + const grandFinal = series.find(({ stage }) => stage.type === 'grand-final'); + if (!grandFinal || grandFinal.status !== 'completed') return undefined; + if (grandFinal.outcome.type === 'draw') return undefined; + + let decisiveOutcome: Exclude = + grandFinal.outcome; + const lowerFinalist = grandFinal.entries.find( + ({ slot }) => slot === 'B', + )?.teamId; + if (resetFinalEnabled && grandFinal.outcome.winnerTeamId === lowerFinalist) { + const resetFinal = series.find(({ stage }) => stage.type === 'reset-final'); + if (!resetFinal || resetFinal.status !== 'completed') return undefined; + if (resetFinal.outcome.type === 'draw') return undefined; + decisiveOutcome = resetFinal.outcome; + } + + const championTeamId = decisiveOutcome.winnerTeamId; + const runnerUpTeamId = decisiveOutcome.loserTeamId; + const placements: CompetitionPlacement[] = [ + { teamId: championTeamId, rank: 1 }, + { teamId: runnerUpTeamId, rank: 2 }, + ]; + const alreadyPlaced = new Set([championTeamId, runnerUpTeamId]); + const eliminatedByRound = new Map(); + + for (const projected of series) { + if ( + projected.stage.type !== 'lower' || + projected.status !== 'completed' || + projected.outcome.type === 'draw' + ) { + continue; + } + const key = projected.stage.roundNumber ?? projected.stage.displayOrder; + const eliminated = eliminatedByRound.get(key) ?? []; + if (!alreadyPlaced.has(projected.outcome.loserTeamId)) { + eliminated.push(projected.outcome.loserTeamId); + } + eliminatedByRound.set(key, eliminated); + } + + let nextRank = 3; + for (const [, eliminated] of [...eliminatedByRound].sort( + ([left], [right]) => right - left, + )) { + const unique = [...new Set(eliminated)].filter( + (teamId) => !alreadyPlaced.has(teamId), + ); + unique.sort( + (left, right) => + teamDisplayOrder(left, teams) - teamDisplayOrder(right, teams), + ); + for (const teamId of unique) { + placements.push({ teamId, rank: nextRank }); + alreadyPlaced.add(teamId); + } + nextRank += unique.length; + } + + // With a valid 4/8-team graph every team is accounted for by the decisive + // final or a lower-bracket elimination. Keep replay deterministic if an old + // migrated graph omitted placement metadata. + const unplaced = teams + .filter(({ teamId }) => !alreadyPlaced.has(teamId)) + .sort((left, right) => left.displayOrder - right.displayOrder); + for (const { teamId } of unplaced) { + placements.push({ teamId, rank: nextRank }); + nextRank += 1; + } + + return { + type: 'double-elimination', + championTeamId, + placements, + completedAt: decisiveOutcome.completedAt, + }; +} + +interface AcceptedGameProjectionFact { + id: string; + type: 'game-accepted'; + revision: number; + ordinalWithinRevision: number; + gameId: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + occurredAt: Date | string; + startedAt?: Date | string; + durationSeconds?: number; + participants?: unknown[]; + evidence?: { + type?: string; + riotMatchId?: string; + legacyReference?: string; + }; + mapping: { + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; + }; +} + +interface VoidedGameProjectionFact { + type: 'game-voided'; + revision: number; + ordinalWithinRevision: number; + gameAcceptedFactId: string; +} + +function projectGamesAndSlots( + graph: readonly SeriesDefinition[], + series: readonly SeriesProjection[], + facts: readonly unknown[], +): { + games: CompetitionGameProjection[]; + gameSlots: GameSlotProjection[]; +} { + const acceptedByFactId = new Map(); + const activeBySlotId = new Map(); + const voidedSlotIds = new Set(); + + for (const fact of projectionGameFacts(facts)) { + if (fact.type === 'game-accepted') { + acceptedByFactId.set(fact.id, fact); + activeBySlotId.set(fact.gameSlotId, fact); + voidedSlotIds.delete(fact.gameSlotId); + continue; + } + const accepted = acceptedByFactId.get(fact.gameAcceptedFactId); + if (!accepted) continue; + if (activeBySlotId.get(accepted.gameSlotId)?.id === accepted.id) { + activeBySlotId.delete(accepted.gameSlotId); + voidedSlotIds.add(accepted.gameSlotId); + } + } + + const displayNumberBySlotId = new Map(); + let displayNumber = 0; + for (const definition of graph) { + for (const slot of [...definition.gameSlots].sort( + (left, right) => left.ordinal - right.ordinal, + )) { + displayNumber += 1; + displayNumberBySlotId.set(slot.id, displayNumber); + } + } + + const games = [...activeBySlotId.values()] + .sort( + (left, right) => + (displayNumberBySlotId.get(left.gameSlotId) ?? 0) - + (displayNumberBySlotId.get(right.gameSlotId) ?? 0), + ) + .map((fact) => ({ + id: fact.gameId, + seriesId: fact.seriesId, + gameSlotId: fact.gameSlotId, + ordinal: fact.ordinal, + displayNumber: displayNumberBySlotId.get(fact.gameSlotId) ?? 0, + evidence: + fact.evidence?.type === 'riot' && fact.evidence.riotMatchId + ? { + type: 'riot' as const, + riotMatchId: fact.evidence.riotMatchId, + } + : { + type: 'legacy' as const, + legacyReference: + fact.evidence?.legacyReference ?? `fact:${fact.id}`, + }, + teams: { + blue: { + side: 'blue' as const, + teamId: fact.mapping.blueTeamId, + }, + red: { side: 'red' as const, teamId: fact.mapping.redTeamId }, + }, + winnerTeamId: fact.mapping.winnerTeamId, + startedAt: toIsoString(fact.startedAt ?? fact.occurredAt), + durationSeconds: + typeof fact.durationSeconds === 'number' ? fact.durationSeconds : 0, + participants: Array.isArray(fact.participants) + ? [...fact.participants] + : [], + })); + + const projectedBySeriesId = new Map( + series.map((projection) => [projection.seriesId, projection]), + ); + const gameSlots = graph.flatMap((definition) => { + const projected = projectedBySeriesId.get(definition.id)!; + const entries: GameSlotProjection['entries'] = [ + { + slot: 'A', + teamId: + projected.entries.find(({ slot }) => slot === 'A')?.teamId ?? null, + }, + { + slot: 'B', + teamId: + projected.entries.find(({ slot }) => slot === 'B')?.teamId ?? null, + }, + ]; + return [...definition.gameSlots] + .sort((left, right) => left.ordinal - right.ordinal) + .map((slot) => { + const game = activeBySlotId.get(slot.id); + const status = game + ? ('completed' as const) + : voidedSlotIds.has(slot.id) + ? ('voided' as const) + : gameSlotStatus(projected.status); + return { + id: slot.id, + seriesId: definition.id, + ordinal: slot.ordinal, + displayNumber: displayNumberBySlotId.get(slot.id) ?? 0, + status, + entries, + ...(game ? { gameId: game.gameId } : {}), + }; + }); + }); + + return { games, gameSlots }; +} + +function projectionGameFacts( + facts: readonly unknown[], +): Array { + return facts + .filter( + (fact): fact is AcceptedGameProjectionFact | VoidedGameProjectionFact => + isRecord(fact) && + (fact.type === 'game-accepted' || fact.type === 'game-voided'), + ) + .sort( + (left, right) => + left.revision - right.revision || + left.ordinalWithinRevision - right.ordinalWithinRevision, + ); +} + +function gameSlotStatus( + status: SeriesProjection['status'], +): GameSlotProjection['status'] { + switch (status) { + case 'inactive': + return 'inactive'; + case 'waiting': + return 'waiting'; + case 'ready': + case 'in-progress': + return 'ready'; + case 'completed': + return 'inactive'; + } +} + +function projectRounds( + graph: readonly SeriesDefinition[], +): BracketRoundProjection[] { + const rounds = new Map(); + for (const definition of graph) { + const { type: stage, roundNumber, displayOrder } = definition.stage; + const key = `${stage}:${roundNumber ?? 'none'}`; + const existing = rounds.get(key); + if (existing) { + existing.seriesIds.push(definition.id); + existing.displayOrder = Math.min(existing.displayOrder, displayOrder); + continue; + } + rounds.set(key, { + stage, + ...(roundNumber !== undefined ? { roundNumber } : {}), + displayOrder, + label: roundLabel(stage, roundNumber), + seriesIds: [definition.id], + }); + } + return [...rounds.values()].sort( + (left, right) => left.displayOrder - right.displayOrder, + ); +} + +function roundLabel( + stage: SeriesDefinition['stage']['type'], + roundNumber?: number, +): string { + switch (stage) { + case 'pair': + return 'Pair'; + case 'round-robin': + return `Round ${roundNumber ?? 1}`; + case 'upper': + return `Upper ${roundNumber ?? 1}`; + case 'lower': + return `Lower ${roundNumber ?? 1}`; + case 'grand-final': + return 'Grand Final'; + case 'reset-final': + return 'Reset Final'; + } +} + +function projectConnectors( + graph: readonly SeriesDefinition[], +): SeriesConnectorProjection[] { + const connectors: SeriesConnectorProjection[] = []; + for (const definition of graph) { + for (const { position, source } of definition.slots) { + if (source.type === 'series-outcome') { + connectors.push({ + from: { + seriesId: source.seriesId, + select: source.select, + }, + to: { seriesId: definition.id, slot: position }, + }); + continue; + } + if (source.type === 'series-slot') { + connectors.push({ + from: { + seriesId: source.seriesId, + select: source.slot === 'A' ? 'slot-a' : 'slot-b', + }, + to: { seriesId: definition.id, slot: position }, + }); + } + } + } + return connectors; +} + +function competitionCompletedAt(series: readonly SeriesProjection[]): string { + return series + .filter( + (projection): projection is SeriesProjection & { status: 'completed' } => + projection.status === 'completed', + ) + .map(({ outcome }) => outcome.completedAt) + .sort() + .at(-1)!; +} + +function toIsoString(value: Date | string): string { + return value instanceof Date ? value.toISOString() : value; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function phaseFor( + series: readonly SeriesProjection[], + outcome: CompetitionProjectionOutcome | undefined, +): CompetitionProjection['phase'] { + if (outcome) return 'completed'; + return series.some( + ({ status }) => status === 'in-progress' || status === 'completed', + ) + ? 'running' + : 'ready'; +} + +function stableTeamOrder( + left: string, + right: string, + displayOrderByTeam: ReadonlyMap, +): number { + return ( + (displayOrderByTeam.get(left) ?? Number.MAX_SAFE_INTEGER) - + (displayOrderByTeam.get(right) ?? Number.MAX_SAFE_INTEGER) || + left.localeCompare(right) + ); +} + +function teamDisplayOrder( + teamId: string, + teams: readonly CompetitionGraphTeam[], +): number { + return ( + teams.find((candidate) => candidate.teamId === teamId)?.displayOrder ?? + Number.MAX_SAFE_INTEGER + ); +} diff --git a/apps/api/src/modules/competition/domain/domain-error.ts b/apps/api/src/modules/competition/domain/domain-error.ts new file mode 100644 index 00000000..62eb3578 --- /dev/null +++ b/apps/api/src/modules/competition/domain/domain-error.ts @@ -0,0 +1,48 @@ +export type CompetitionDomainErrorCode = + | 'DUPLICATE_FACT_ID' + | 'DUPLICATE_GAME_ID' + | 'DUPLICATE_RIOT_MATCH_ID' + | 'DUPLICATE_GAME_SLOT' + | 'DUPLICATE_GAME_ORDINAL' + | 'DUPLICATE_ADJUDICATION' + | 'FACT_REFERENCE_NOT_FOUND' + | 'FACT_ALREADY_REVERSED' + | 'FACT_TYPE_INVALID' + | 'GAME_SLOT_INVALID' + | 'GAME_ORDINAL_INVALID' + | 'GAME_SERIES_MISMATCH' + | 'GAME_TEAM_MISMATCH' + | 'GAME_WINNER_INVALID' + | 'SERIES_ALREADY_COMPLETED' + | 'SERIES_DEFINITION_INVALID' + | 'SERIES_PARTICIPANTS_INVALID' + | 'ADJUDICATION_INVALID' + | 'ADJUDICATION_DRAW_NOT_ALLOWED' + | 'WALKOVER_HAS_ACTIVE_GAMES'; + +/** + * A deterministic domain-invariant failure. Command handlers translate these + * errors to the appropriate HTTP conflict/validation response; projectors do + * not depend on NestJS or transport concerns. + */ +export class CompetitionDomainError extends Error { + constructor( + public readonly code: CompetitionDomainErrorCode, + message: string, + public readonly details?: Readonly>, + ) { + super(message); + this.name = 'CompetitionDomainError'; + } +} + +export function assertCompetitionInvariant( + condition: unknown, + code: CompetitionDomainErrorCode, + message: string, + details?: Readonly>, +): asserts condition { + if (!condition) { + throw new CompetitionDomainError(code, message, details); + } +} diff --git a/apps/api/src/modules/competition/domain/series-graph.spec.ts b/apps/api/src/modules/competition/domain/series-graph.spec.ts new file mode 100644 index 00000000..6a4d929e --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-graph.spec.ts @@ -0,0 +1,93 @@ +import { generateSeriesGraph } from './series-graph'; + +describe('generateSeriesGraph', () => { + it('generates a deterministic graph with stable opaque ids', () => { + const input = { + competitionId: 'competition-deterministic', + teams: Array.from({ length: 8 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: index + 1, + seedNumber: index + 1, + })), + format: { + type: 'double-elimination' as const, + resetFinalEnabled: true, + rules: { + upper: firstTo(2, 3), + lower: firstTo(1, 1), + grandFinal: firstTo(1, 1), + resetFinal: firstTo(1, 1), + }, + }, + }; + + const first = generateSeriesGraph(input); + const second = generateSeriesGraph(input); + + expect(second).toEqual(first); + expect(first.map((series) => series.id)).toHaveLength(15); + expect(new Set(first.map((series) => series.id))).toHaveProperty( + 'size', + 15, + ); + expect(first.every((series) => series.id.length > 0)).toBe(true); + }); + + it('predefines a conditional grand-final reset node using only slot sources', () => { + const graph = generateSeriesGraph({ + competitionId: 'competition-reset-node', + teams: Array.from({ length: 4 }, (_, index) => ({ + teamId: `team-${index + 1}`, + displayOrder: index + 1, + seedNumber: index + 1, + })), + format: { + type: 'double-elimination' as const, + resetFinalEnabled: true, + rules: { + upper: firstTo(2, 3), + lower: firstTo(1, 1), + grandFinal: firstTo(1, 1), + resetFinal: firstTo(1, 1), + }, + }, + }); + const grandFinal = graph.find((series) => series.code === 'GF'); + const resetFinal = graph.find((series) => series.code === 'GF_RESET'); + + expect(grandFinal).toBeDefined(); + expect(resetFinal).toMatchObject({ + stage: { type: 'reset-final' }, + activation: { + type: 'grand-final-reset-required', + grandFinalSeriesId: grandFinal!.id, + }, + slots: [ + { + position: 'A', + source: { + type: 'series-slot', + seriesId: grandFinal!.id, + slot: 'A', + }, + }, + { + position: 'B', + source: { + type: 'series-slot', + seriesId: grandFinal!.id, + slot: 'B', + }, + }, + ], + }); + for (const series of graph) { + expect(series).not.toHaveProperty('winnerAdvancesTo'); + expect(series).not.toHaveProperty('loserAdvancesTo'); + } + }); +}); + +function firstTo(winsRequired: number, maxGames: number) { + return { type: 'first-to' as const, winsRequired, maxGames }; +} diff --git a/apps/api/src/modules/competition/domain/series-graph.ts b/apps/api/src/modules/competition/domain/series-graph.ts new file mode 100644 index 00000000..1be252a8 --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-graph.ts @@ -0,0 +1,647 @@ +import { createHash } from 'node:crypto'; + +export type SeriesSlot = 'A' | 'B'; + +export type FirstToSeriesRule = { + type: 'first-to'; + winsRequired: number; + maxGames: number; +}; + +export type FixedGamesSeriesRule = { + type: 'fixed-games'; + gameCount: number; + drawPolicy: 'allow' | 'tiebreak-required'; +}; + +export type SeriesRule = FirstToSeriesRule | FixedGamesSeriesRule; + +export type ParticipantSource = + | { type: 'team'; teamId: string } + | { type: 'seed'; seedNumber: number } + | { + type: 'series-outcome'; + seriesId: string; + select: 'winner' | 'loser'; + } + | { + type: 'series-slot'; + seriesId: string; + slot: SeriesSlot; + }; + +export type SeriesStageType = + | 'pair' + | 'round-robin' + | 'upper' + | 'lower' + | 'grand-final' + | 'reset-final'; + +export interface SeriesDefinition { + id: string; + code?: string; + stage: { + type: SeriesStageType; + roundNumber?: number; + displayOrder: number; + }; + slots: [ + { position: 'A'; source: ParticipantSource }, + { position: 'B'; source: ParticipantSource }, + ]; + rule: SeriesRule; + activation?: { + type: 'grand-final-reset-required'; + grandFinalSeriesId: string; + }; + gameSlots: Array<{ + id: string; + seriesId: string; + ordinal: number; + }>; +} + +export interface CompetitionGraphTeam { + teamId: string; + displayOrder: number; + seedNumber?: number; +} + +export type CompetitionGraphFormat = + | { + type: 'paired-series'; + rule: FixedGamesSeriesRule; + } + | { + type: 'round-robin'; + rule: FixedGamesSeriesRule; + maxRounds?: number; + tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head']; + } + | { + type: 'double-elimination'; + teamCount?: 4 | 8; + resetFinalEnabled: boolean; + rules: { + upper: FirstToSeriesRule; + lower: FirstToSeriesRule; + grandFinal: FirstToSeriesRule; + resetFinal: FirstToSeriesRule; + }; + }; + +export interface GenerateSeriesGraphInput { + competitionId: string; + teams: readonly CompetitionGraphTeam[]; + format: CompetitionGraphFormat; +} + +interface DoubleEliminationTemplate { + code: string; + stage: Extract< + SeriesStageType, + 'upper' | 'lower' | 'grand-final' | 'reset-final' + >; + roundNumber: number; + sources: [TemplateParticipantSource, TemplateParticipantSource]; +} + +type TemplateParticipantSource = + | { type: 'seed'; seedNumber: number } + | { + type: 'series-outcome'; + seriesCode: string; + select: 'winner' | 'loser'; + } + | { type: 'series-slot'; seriesCode: string; slot: SeriesSlot }; + +interface RoundRobinPairing { + roundNumber: number; + teamAIndex: number; + teamBIndex: number; +} + +/** + * Builds the immutable Series graph. Identifiers depend only on the Competition + * identity and the logical node/slot key, never on array position or a display + * number supplied by a client. + */ +export function generateSeriesGraph( + input: GenerateSeriesGraphInput, +): SeriesDefinition[] { + assertCompetitionId(input.competitionId); + const teams = normalizeTeams(input.teams); + + let graph: SeriesDefinition[]; + switch (input.format.type) { + case 'paired-series': + graph = generatePairedSeriesGraph( + input.competitionId, + teams, + input.format.rule, + ); + break; + case 'round-robin': + graph = generateRoundRobinGraph( + input.competitionId, + teams, + input.format.rule, + input.format.maxRounds, + ); + break; + case 'double-elimination': + graph = generateDoubleEliminationGraph( + input.competitionId, + teams, + input.format, + ); + break; + } + + assertValidGraph(graph); + return graph; +} + +function generatePairedSeriesGraph( + competitionId: string, + teams: CompetitionGraphTeam[], + rule: FixedGamesSeriesRule, +): SeriesDefinition[] { + assertFixedGamesRule(rule); + if (teams.length < 2 || teams.length % 2 !== 0) { + throw graphError( + 'INVALID_PAIRED_TEAM_COUNT', + 'Paired Series requires a positive, even number of teams.', + ); + } + + const definitions: SeriesDefinition[] = []; + for (let teamIndex = 0; teamIndex < teams.length; teamIndex += 2) { + const code = `PAIR_M${teamIndex / 2 + 1}`; + definitions.push( + createSeriesDefinition({ + competitionId, + code, + stage: 'pair', + roundNumber: 1, + displayOrder: definitions.length + 1, + sources: [ + { type: 'team', teamId: teams[teamIndex].teamId }, + { type: 'team', teamId: teams[teamIndex + 1].teamId }, + ], + rule, + }), + ); + } + return definitions; +} + +function generateRoundRobinGraph( + competitionId: string, + teams: CompetitionGraphTeam[], + rule: FixedGamesSeriesRule, + maxRounds?: number, +): SeriesDefinition[] { + assertFixedGamesRule(rule); + if (teams.length < 2) { + throw graphError( + 'INVALID_ROUND_ROBIN_TEAM_COUNT', + 'Round robin requires at least two teams.', + ); + } + + const pairings = roundRobinPairings(teams.length, maxRounds); + const matchNumberByRound = new Map(); + + return pairings.map((pairing, index) => { + const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1; + matchNumberByRound.set(pairing.roundNumber, matchNumber); + const code = `RR_R${pairing.roundNumber}_M${matchNumber}`; + return createSeriesDefinition({ + competitionId, + code, + stage: 'round-robin', + roundNumber: pairing.roundNumber, + displayOrder: index + 1, + sources: [ + { type: 'team', teamId: teams[pairing.teamAIndex].teamId }, + { type: 'team', teamId: teams[pairing.teamBIndex].teamId }, + ], + rule, + }); + }); +} + +function generateDoubleEliminationGraph( + competitionId: string, + teams: CompetitionGraphTeam[], + format: Extract, +): SeriesDefinition[] { + if (teams.length !== 4 && teams.length !== 8) { + throw graphError( + 'INVALID_DOUBLE_ELIMINATION_TEAM_COUNT', + 'Double elimination supports only four or eight teams.', + ); + } + if (format.teamCount !== undefined && format.teamCount !== teams.length) { + throw graphError( + 'DOUBLE_ELIMINATION_TEAM_COUNT_MISMATCH', + 'The configured team count does not match the team snapshots.', + ); + } + assertContiguousSeeds(teams); + assertFirstToRule(format.rules.upper); + assertFirstToRule(format.rules.lower); + assertFirstToRule(format.rules.grandFinal); + assertFirstToRule(format.rules.resetFinal); + + const templates = + teams.length === 4 + ? fourTeamDoubleEliminationTemplate() + : eightTeamDoubleEliminationTemplate(); + if (format.resetFinalEnabled) templates.push(resetFinalTemplate()); + + return templates.map((template, index) => { + const rule = ruleForStage(template.stage, format.rules); + const grandFinalSeriesId = stableSeriesId(competitionId, 'GF'); + return createSeriesDefinition({ + competitionId, + code: template.code, + stage: template.stage, + roundNumber: template.roundNumber, + displayOrder: index + 1, + sources: template.sources.map((source) => + resolveTemplateSource(competitionId, source), + ) as [ParticipantSource, ParticipantSource], + rule, + activation: + template.stage === 'reset-final' + ? { + type: 'grand-final-reset-required', + grandFinalSeriesId, + } + : undefined, + }); + }); +} + +function createSeriesDefinition(params: { + competitionId: string; + code: string; + stage: SeriesStageType; + roundNumber: number; + displayOrder: number; + sources: [ParticipantSource, ParticipantSource]; + rule: SeriesRule; + activation?: SeriesDefinition['activation']; +}): SeriesDefinition { + const id = stableSeriesId(params.competitionId, params.code); + const rule = cloneRule(params.rule); + const gameCount = + rule.type === 'fixed-games' ? rule.gameCount : rule.maxGames; + + return { + id, + code: params.code, + stage: { + type: params.stage, + roundNumber: params.roundNumber, + displayOrder: params.displayOrder, + }, + slots: [ + { position: 'A', source: { ...params.sources[0] } }, + { position: 'B', source: { ...params.sources[1] } }, + ], + rule, + ...(params.activation ? { activation: { ...params.activation } } : {}), + gameSlots: Array.from({ length: gameCount }, (_, index) => ({ + id: stableGameSlotId(params.competitionId, params.code, index + 1), + seriesId: id, + ordinal: index + 1, + })), + }; +} + +function fourTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] { + return [ + deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(4)), + deSeries('WB_R1_M2', 'upper', 1, seed(2), seed(3)), + deSeries('WB_FINAL', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')), + deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')), + deSeries('LB_FINAL', 'lower', 2, winner('LB_R1_M1'), loser('WB_FINAL')), + deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')), + ]; +} + +function eightTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] { + return [ + deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(8)), + deSeries('WB_R1_M2', 'upper', 1, seed(4), seed(5)), + deSeries('WB_R1_M3', 'upper', 1, seed(2), seed(7)), + deSeries('WB_R1_M4', 'upper', 1, seed(3), seed(6)), + deSeries('WB_R2_M1', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')), + deSeries('WB_R2_M2', 'upper', 2, winner('WB_R1_M3'), winner('WB_R1_M4')), + deSeries('WB_FINAL', 'upper', 3, winner('WB_R2_M1'), winner('WB_R2_M2')), + deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')), + deSeries('LB_R1_M2', 'lower', 1, loser('WB_R1_M3'), loser('WB_R1_M4')), + deSeries('LB_R2_M1', 'lower', 2, winner('LB_R1_M1'), loser('WB_R2_M2')), + deSeries('LB_R2_M2', 'lower', 2, winner('LB_R1_M2'), loser('WB_R2_M1')), + deSeries('LB_R3_M1', 'lower', 3, winner('LB_R2_M1'), winner('LB_R2_M2')), + deSeries('LB_FINAL', 'lower', 4, winner('LB_R3_M1'), loser('WB_FINAL')), + deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')), + ]; +} + +function resetFinalTemplate(): DoubleEliminationTemplate { + return deSeries( + 'GF_RESET', + 'reset-final', + 1, + seriesSlot('GF', 'A'), + seriesSlot('GF', 'B'), + ); +} + +function deSeries( + code: string, + stage: DoubleEliminationTemplate['stage'], + roundNumber: number, + sourceA: TemplateParticipantSource, + sourceB: TemplateParticipantSource, +): DoubleEliminationTemplate { + return { code, stage, roundNumber, sources: [sourceA, sourceB] }; +} + +function seed(seedNumber: number): TemplateParticipantSource { + return { type: 'seed', seedNumber }; +} + +function winner(seriesCode: string): TemplateParticipantSource { + return { type: 'series-outcome', seriesCode, select: 'winner' }; +} + +function loser(seriesCode: string): TemplateParticipantSource { + return { type: 'series-outcome', seriesCode, select: 'loser' }; +} + +function seriesSlot( + seriesCode: string, + slot: SeriesSlot, +): TemplateParticipantSource { + return { type: 'series-slot', seriesCode, slot }; +} + +function resolveTemplateSource( + competitionId: string, + source: TemplateParticipantSource, +): ParticipantSource { + switch (source.type) { + case 'seed': + return { ...source }; + case 'series-outcome': + return { + type: 'series-outcome', + seriesId: stableSeriesId(competitionId, source.seriesCode), + select: source.select, + }; + case 'series-slot': + return { + type: 'series-slot', + seriesId: stableSeriesId(competitionId, source.seriesCode), + slot: source.slot, + }; + } +} + +function ruleForStage( + stage: DoubleEliminationTemplate['stage'], + rules: Extract< + CompetitionGraphFormat, + { type: 'double-elimination' } + >['rules'], +): FirstToSeriesRule { + switch (stage) { + case 'upper': + return rules.upper; + case 'lower': + return rules.lower; + case 'grand-final': + return rules.grandFinal; + case 'reset-final': + return rules.resetFinal; + } +} + +function roundRobinPairings( + teamCount: number, + maxRounds?: number, +): RoundRobinPairing[] { + const bye = -1; + const rotating = Array.from({ length: teamCount }, (_, index) => index); + if (rotating.length % 2 === 1) rotating.push(bye); + + const fullRoundCount = rotating.length - 1; + const requestedRounds = + maxRounds === undefined + ? fullRoundCount + : Number.isFinite(maxRounds) + ? Math.floor(maxRounds) + : fullRoundCount; + const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds)); + const pairings: RoundRobinPairing[] = []; + + for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) { + for (let index = 0; index < rotating.length / 2; index += 1) { + const left = rotating[index]; + const right = rotating[rotating.length - 1 - index]; + if (left === bye || right === bye) continue; + pairings.push({ + roundNumber: roundIndex + 1, + teamAIndex: Math.min(left, right), + teamBIndex: Math.max(left, right), + }); + } + + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop() as number); + rotating.splice(0, rotating.length, fixed, ...tail); + } + + return pairings; +} + +function normalizeTeams( + teams: readonly CompetitionGraphTeam[], +): CompetitionGraphTeam[] { + const normalized = teams.map((team) => ({ ...team })); + const teamIds = new Set(); + const displayOrders = new Set(); + + for (const team of normalized) { + if (typeof team.teamId !== 'string' || team.teamId.trim().length === 0) { + throw graphError('INVALID_TEAM_ID', 'Every team needs an opaque ID.'); + } + if (teamIds.has(team.teamId)) { + throw graphError( + 'DUPLICATE_TEAM_ID', + `Duplicate team ID: ${team.teamId}`, + ); + } + if (!Number.isInteger(team.displayOrder) || team.displayOrder < 1) { + throw graphError( + 'INVALID_TEAM_DISPLAY_ORDER', + 'Team display order must be a positive integer.', + ); + } + if (displayOrders.has(team.displayOrder)) { + throw graphError( + 'DUPLICATE_TEAM_DISPLAY_ORDER', + `Duplicate team display order: ${team.displayOrder}`, + ); + } + teamIds.add(team.teamId); + displayOrders.add(team.displayOrder); + } + + return normalized.sort( + (left, right) => + left.displayOrder - right.displayOrder || + left.teamId.localeCompare(right.teamId), + ); +} + +function assertContiguousSeeds(teams: CompetitionGraphTeam[]): void { + const seeds = teams.map((team) => team.seedNumber); + if ( + seeds.some((seedNumber) => !Number.isInteger(seedNumber)) || + new Set(seeds).size !== teams.length + ) { + throw graphError( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds must be unique integers.', + ); + } + const sorted = [...(seeds as number[])].sort((left, right) => left - right); + if (sorted.some((seedNumber, index) => seedNumber !== index + 1)) { + throw graphError( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds must be contiguous from one to the team count.', + ); + } +} + +function assertCompetitionId(competitionId: string): void { + if (typeof competitionId !== 'string' || competitionId.trim().length === 0) { + throw graphError( + 'INVALID_COMPETITION_ID', + 'Competition ID must be a non-empty string.', + ); + } +} + +function assertFixedGamesRule(rule: FixedGamesSeriesRule): void { + if (!Number.isInteger(rule.gameCount) || rule.gameCount < 1) { + throw graphError( + 'INVALID_FIXED_GAMES_RULE', + 'Fixed-game Series need a positive game count.', + ); + } + if (rule.drawPolicy !== 'allow' && rule.drawPolicy !== 'tiebreak-required') { + throw graphError( + 'INVALID_FIXED_GAMES_RULE', + 'Fixed-game Series need a supported draw policy.', + ); + } +} + +function assertFirstToRule(rule: FirstToSeriesRule): void { + if ( + !Number.isInteger(rule.winsRequired) || + rule.winsRequired < 1 || + !Number.isInteger(rule.maxGames) || + rule.maxGames < rule.winsRequired + ) { + throw graphError( + 'INVALID_FIRST_TO_RULE', + 'First-to Series need positive, achievable win and game limits.', + ); + } +} + +function cloneRule(rule: SeriesRule): SeriesRule { + return rule.type === 'fixed-games' ? { ...rule } : { ...rule }; +} + +function assertValidGraph(graph: SeriesDefinition[]): void { + const seriesIndexById = new Map(); + const gameSlotIds = new Set(); + + graph.forEach((series, index) => { + if (seriesIndexById.has(series.id)) { + throw graphError('DUPLICATE_SERIES_ID', 'Series IDs must be unique.'); + } + seriesIndexById.set(series.id, index); + for (const gameSlot of series.gameSlots) { + if (gameSlotIds.has(gameSlot.id)) { + throw graphError( + 'DUPLICATE_GAME_SLOT_ID', + 'GameSlot IDs must be unique.', + ); + } + gameSlotIds.add(gameSlot.id); + } + }); + + graph.forEach((series, index) => { + for (const slot of series.slots) { + if ( + slot.source.type !== 'series-outcome' && + slot.source.type !== 'series-slot' + ) { + continue; + } + const sourceIndex = seriesIndexById.get(slot.source.seriesId); + if (sourceIndex === undefined) { + throw graphError( + 'UNKNOWN_SERIES_SOURCE', + `Series ${series.id} references an unknown source.`, + ); + } + if (sourceIndex >= index) { + throw graphError( + 'CYCLIC_SERIES_GRAPH', + `Series ${series.id} does not follow its source in topological order.`, + ); + } + } + }); +} + +function stableSeriesId(competitionId: string, code: string): string { + return stableOpaqueId(competitionId, 'series', code); +} + +function stableGameSlotId( + competitionId: string, + seriesCode: string, + ordinal: number, +): string { + return stableOpaqueId(competitionId, 'game-slot', seriesCode, ordinal); +} + +function stableOpaqueId( + competitionId: string, + entityKind: string, + ...logicalKey: Array +): string { + return createHash('sha256') + .update(JSON.stringify([competitionId, entityKind, ...logicalKey])) + .digest('hex') + .slice(0, 24); +} + +function graphError(code: string, message: string): Error & { code: string } { + return Object.assign(new Error(message), { code }); +} diff --git a/apps/api/src/modules/competition/domain/series-projector.spec.ts b/apps/api/src/modules/competition/domain/series-projector.spec.ts new file mode 100644 index 00000000..c1be3de8 --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-projector.spec.ts @@ -0,0 +1,296 @@ +import { projectSeries } from './series-projector'; + +describe('projectSeries', () => { + it('keeps a fixed-games pair in progress until every game slot is filled', () => { + const definition = seriesDefinition({ + id: 'series-pair', + stage: 'pair', + rule: { + type: 'fixed-games', + gameCount: 3, + drawPolicy: 'allow', + }, + }); + const firstTwoGames = [ + acceptedGame({ + definition, + ordinal: 1, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-8', + }), + acceptedGame({ + definition, + ordinal: 2, + blueTeamId: 'team-3', + redTeamId: 'team-8', + winnerTeamId: 'team-8', + }), + ]; + + const inProgress = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: firstTwoGames, + }); + + expect(inProgress).toMatchObject({ + status: 'in-progress', + leaderTeamId: 'team-8', + entries: [ + { slot: 'A', teamId: 'team-8', gameWins: 2 }, + { slot: 'B', teamId: 'team-3', gameWins: 0 }, + ], + }); + expect(inProgress).not.toHaveProperty('outcome'); + + const completed = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [ + ...firstTwoGames, + acceptedGame({ + definition, + ordinal: 3, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-3', + }), + ], + }); + + expect(completed).toMatchObject({ + status: 'completed', + entries: [ + { slot: 'A', teamId: 'team-8', gameWins: 2 }, + { slot: 'B', teamId: 'team-3', gameWins: 1 }, + ], + outcome: { + type: 'played', + winnerTeamId: 'team-8', + loserTeamId: 'team-3', + }, + }); + expect(completed).not.toHaveProperty('leaderTeamId'); + }); + + it('reports a leader during first-to play and a winner only after the threshold', () => { + const definition = seriesDefinition({ + id: 'series-first-to', + stage: 'upper', + rule: { type: 'first-to', winsRequired: 2, maxGames: 3 }, + }); + const firstGame = acceptedGame({ + definition, + ordinal: 1, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-8', + }); + + const oneToZero = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [firstGame], + }); + + expect(oneToZero).toMatchObject({ + status: 'in-progress', + leaderTeamId: 'team-8', + }); + expect(oneToZero).not.toHaveProperty('outcome'); + + const twoToOne = projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [ + firstGame, + acceptedGame({ + definition, + ordinal: 2, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-3', + }), + acceptedGame({ + definition, + ordinal: 3, + blueTeamId: 'team-3', + redTeamId: 'team-8', + winnerTeamId: 'team-8', + }), + ], + }); + + expect(twoToOne).toMatchObject({ + status: 'completed', + outcome: { + type: 'played', + winnerTeamId: 'team-8', + loserTeamId: 'team-3', + decidedByGameIds: [ + 'game-series-first-to-1', + 'game-series-first-to-2', + 'game-series-first-to-3', + ], + }, + }); + expect(twoToOne).not.toHaveProperty('leaderTeamId'); + }); + + it('rejects accepted evidence whose teams do not match the series participants', () => { + const definition = seriesDefinition({ + id: 'series-invalid-team', + stage: 'upper', + rule: { type: 'first-to', winsRequired: 2, maxGames: 3 }, + }); + + expectInvariant( + () => + projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [ + acceptedGame({ + definition, + ordinal: 1, + blueTeamId: 'team-8', + redTeamId: 'team-9', + winnerTeamId: 'team-8', + }), + ], + }), + 'GAME_TEAM_MISMATCH', + ); + }); + + it('rejects a game accepted after a first-to series was already complete', () => { + const definition = seriesDefinition({ + id: 'series-extra-game', + stage: 'upper', + rule: { type: 'first-to', winsRequired: 2, maxGames: 3 }, + }); + + expectInvariant( + () => + projectSeries({ + definition, + participants: ['team-8', 'team-3'], + facts: [ + acceptedGame({ + definition, + ordinal: 1, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-8', + }), + acceptedGame({ + definition, + ordinal: 2, + blueTeamId: 'team-3', + redTeamId: 'team-8', + winnerTeamId: 'team-8', + }), + acceptedGame({ + definition, + ordinal: 3, + blueTeamId: 'team-8', + redTeamId: 'team-3', + winnerTeamId: 'team-3', + }), + ], + }), + 'SERIES_ALREADY_COMPLETED', + ); + }); +}); + +function seriesDefinition(params: { + id: string; + stage: 'pair' | 'upper'; + rule: + | { + type: 'fixed-games'; + gameCount: number; + drawPolicy: 'allow'; + } + | { type: 'first-to'; winsRequired: number; maxGames: number }; +}) { + const gameCount = + params.rule.type === 'fixed-games' + ? params.rule.gameCount + : params.rule.maxGames; + return { + id: params.id, + code: params.id, + stage: { type: params.stage, displayOrder: 1 }, + slots: [ + { + position: 'A' as const, + source: { type: 'team' as const, teamId: 'team-8' }, + }, + { + position: 'B' as const, + source: { type: 'team' as const, teamId: 'team-3' }, + }, + ], + rule: params.rule, + gameSlots: Array.from({ length: gameCount }, (_, index) => ({ + id: `${params.id}-slot-${index + 1}`, + seriesId: params.id, + ordinal: index + 1, + })), + }; +} + +function acceptedGame(params: { + definition: ReturnType; + ordinal: number; + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; +}) { + const gameSlot = params.definition.gameSlots.find( + (slot) => slot.ordinal === params.ordinal, + ); + if (!gameSlot) throw new Error(`Missing game slot ${params.ordinal}`); + + return { + id: `fact-${params.definition.id}-${params.ordinal}`, + type: 'game-accepted' as const, + competitionId: 'competition-series-projector', + revision: params.ordinal, + ordinalWithinRevision: 1, + commandId: `command-${params.definition.id}-${params.ordinal}`, + schemaVersion: 1, + actor: { type: 'system' as const }, + occurredAt: new Date(`2026-07-12T00:0${params.ordinal}:00.000Z`), + recordedAt: new Date(`2026-07-12T00:0${params.ordinal}:01.000Z`), + gameId: `game-${params.definition.id}-${params.ordinal}`, + seriesId: params.definition.id, + gameSlotId: gameSlot.id, + ordinal: params.ordinal, + evidence: { + type: 'riot' as const, + riotMatchId: `KR_${params.definition.id}_${params.ordinal}`, + payloadHash: `sha256:${params.definition.id}:${params.ordinal}`, + }, + mapping: { + mappingVersion: 1, + confidence: 1, + blueTeamId: params.blueTeamId, + redTeamId: params.redTeamId, + winnerTeamId: params.winnerTeamId, + participantAssignments: [], + }, + }; +} + +function expectInvariant(action: () => unknown, code: string) { + try { + action(); + throw new Error(`Expected invariant ${code}`); + } catch (error) { + expect(error).toMatchObject({ code }); + } +} diff --git a/apps/api/src/modules/competition/domain/series-projector.ts b/apps/api/src/modules/competition/domain/series-projector.ts new file mode 100644 index 00000000..329c7dda --- /dev/null +++ b/apps/api/src/modules/competition/domain/series-projector.ts @@ -0,0 +1,777 @@ +import { + assertCompetitionInvariant, + CompetitionDomainError, +} from './domain-error'; + +export type SeriesSlot = 'A' | 'B'; + +export type SeriesRule = + | { type: 'first-to'; winsRequired: number; maxGames: number } + | { + type: 'fixed-games'; + gameCount: number; + drawPolicy: 'allow' | 'tiebreak-required'; + }; + +export interface SeriesDefinitionLike { + id: string; + code?: string; + stage: { + type: string; + roundNumber?: number; + displayOrder: number; + }; + slots: ReadonlyArray<{ + position: SeriesSlot; + source: Readonly>; + }>; + rule: SeriesRule; + gameSlots: ReadonlyArray<{ + id: string; + seriesId: string; + ordinal: number; + }>; +} + +export interface ProjectSeriesInput { + definition: SeriesDefinitionLike; + participants: readonly (string | null | undefined)[]; + facts: readonly unknown[]; + /** A stable conditional node can exist before it is eligible for play. */ + active?: boolean; +} + +export interface SeriesProjectionEntry { + slot: SeriesSlot; + teamId: string | null; + gameWins: number; +} + +export type SeriesProjectionOutcome = + | { + type: 'played'; + winnerTeamId: string; + loserTeamId: string; + decidedByGameIds: string[]; + completedAt: string; + } + | { + type: 'draw'; + basis: + | { type: 'played'; decidedByGameIds: string[] } + | { type: 'administrative'; decisionFactId: string }; + completedAt: string; + } + | { + type: 'walkover' | 'forfeit' | 'administrative'; + winnerTeamId: string; + loserTeamId: string; + decisionFactId: string; + completedAt: string; + }; + +interface SeriesProjectionBase { + seriesId: string; + code?: string; + stage: SeriesDefinitionLike['stage']; + rule: SeriesRule; + entries: [SeriesProjectionEntry, SeriesProjectionEntry]; +} + +export type SeriesProjection = SeriesProjectionBase & + ( + | { status: 'inactive' | 'waiting' | 'ready' } + | { status: 'in-progress'; leaderTeamId?: string } + | { status: 'completed'; outcome: SeriesProjectionOutcome } + ); + +interface FactBase { + id: string; + type: string; + revision: number; + ordinalWithinRevision: number; + occurredAt: Date | string; + recordedAt?: Date | string; +} + +interface GameAcceptedFact extends FactBase { + type: 'game-accepted'; + gameId: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + evidence?: { + type?: string; + riotMatchId?: string; + }; + mapping: { + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; + }; +} + +interface GameVoidedFact extends FactBase { + type: 'game-voided'; + gameAcceptedFactId: string; + reason?: string; +} + +interface SeriesAdjudicatedFact extends FactBase { + type: 'series-adjudicated'; + seriesId: string; + decision: + | { type: 'walkover' | 'forfeit' | 'administrative'; winnerTeamId: string } + | { type: 'administrative-draw' }; + reason: string; +} + +interface AdjudicationReversedFact extends FactBase { + type: 'adjudication-reversed'; + adjudicationFactId: string; + reason?: string; +} + +type CompetitionFact = + | GameAcceptedFact + | GameVoidedFact + | SeriesAdjudicatedFact + | AdjudicationReversedFact; + +interface PlayedState { + activeGames: GameAcceptedFact[]; + winsByTeam: Map; + completed: boolean; +} + +/** Project one Series exclusively from its definition, resolved participants and fact ledger. */ +export function projectSeries(input: ProjectSeriesInput): SeriesProjection { + validateDefinition(input.definition); + const participants = normalizeParticipants(input.participants); + const facts = normalizeFacts(input.facts); + const base = projectionBase(input.definition, participants); + + if (input.active === false) { + assertNoSeriesActivity(input.definition.id, facts); + return { ...base, status: 'inactive' }; + } + + if (participants.some((teamId) => teamId === null)) { + assertNoSeriesActivity(input.definition.id, facts); + return { ...base, status: 'waiting' }; + } + + const resolvedParticipants = participants as [string, string]; + const relevantFacts = selectRelevantFacts(input.definition.id, facts); + const activeGames = new Map(); + const voidedGameFacts = new Set(); + const adjudications = new Map(); + const reversedAdjudications = new Set(); + let activeAdjudication: SeriesAdjudicatedFact | undefined; + + for (const fact of relevantFacts) { + switch (fact.type) { + case 'game-accepted': { + assertCompetitionInvariant( + activeAdjudication === undefined && + !derivePlayedState( + input.definition.rule, + [...activeGames.values()], + resolvedParticipants, + ).completed, + 'SERIES_ALREADY_COMPLETED', + `Series ${input.definition.id} was already completed before game ${fact.gameId}`, + { seriesId: input.definition.id, factId: fact.id }, + ); + validateAcceptedGame(input.definition, resolvedParticipants, fact); + validateActiveGameUniqueness(activeGames.values(), fact); + activeGames.set(fact.id, fact); + break; + } + case 'game-voided': { + const accepted = facts.find( + (candidate): candidate is GameAcceptedFact => + candidate.type === 'game-accepted' && + candidate.id === fact.gameAcceptedFactId, + ); + assertCompetitionInvariant( + accepted !== undefined, + 'FACT_REFERENCE_NOT_FOUND', + `Voided game fact ${fact.gameAcceptedFactId} does not exist`, + { factId: fact.id, referencedFactId: fact.gameAcceptedFactId }, + ); + assertCompetitionInvariant( + activeGames.has(accepted.id) && !voidedGameFacts.has(accepted.id), + 'FACT_ALREADY_REVERSED', + `Game fact ${accepted.id} is already voided`, + { factId: fact.id, referencedFactId: accepted.id }, + ); + activeGames.delete(accepted.id); + voidedGameFacts.add(accepted.id); + break; + } + case 'series-adjudicated': { + const played = derivePlayedState( + input.definition.rule, + [...activeGames.values()], + resolvedParticipants, + ); + assertCompetitionInvariant( + !played.completed && activeAdjudication === undefined, + activeAdjudication + ? 'DUPLICATE_ADJUDICATION' + : 'SERIES_ALREADY_COMPLETED', + `Series ${input.definition.id} already has an official outcome`, + { seriesId: input.definition.id, factId: fact.id }, + ); + validateAdjudication( + input.definition, + resolvedParticipants, + played.activeGames, + fact, + ); + adjudications.set(fact.id, fact); + activeAdjudication = fact; + break; + } + case 'adjudication-reversed': { + const adjudication = adjudications.get(fact.adjudicationFactId); + assertCompetitionInvariant( + adjudication !== undefined, + 'FACT_REFERENCE_NOT_FOUND', + `Adjudication fact ${fact.adjudicationFactId} does not exist or is not active in this Series`, + { factId: fact.id, referencedFactId: fact.adjudicationFactId }, + ); + assertCompetitionInvariant( + !reversedAdjudications.has(adjudication.id) && + activeAdjudication?.id === adjudication.id, + 'FACT_ALREADY_REVERSED', + `Adjudication fact ${adjudication.id} is already reversed`, + { factId: fact.id, referencedFactId: adjudication.id }, + ); + reversedAdjudications.add(adjudication.id); + activeAdjudication = undefined; + break; + } + } + } + + const played = derivePlayedState( + input.definition.rule, + [...activeGames.values()], + resolvedParticipants, + ); + const entries = entriesFor(resolvedParticipants, played.winsByTeam); + const projectedBase = { ...base, entries }; + + if (activeAdjudication) { + return { + ...projectedBase, + status: 'completed', + outcome: adjudicatedOutcome(activeAdjudication, resolvedParticipants), + }; + } + + if (played.completed) { + return { + ...projectedBase, + status: 'completed', + outcome: playedOutcome( + input.definition.rule, + played.activeGames, + resolvedParticipants, + played.winsByTeam, + ), + }; + } + + if (played.activeGames.length === 0) { + return { ...projectedBase, status: 'ready' }; + } + + const leaderTeamId = deriveLeader(resolvedParticipants, played.winsByTeam); + return { + ...projectedBase, + status: 'in-progress', + ...(leaderTeamId ? { leaderTeamId } : {}), + }; +} + +function validateDefinition(definition: SeriesDefinitionLike): void { + assertCompetitionInvariant( + typeof definition.id === 'string' && definition.id.length > 0, + 'SERIES_DEFINITION_INVALID', + 'A Series must have an opaque id', + ); + assertCompetitionInvariant( + definition.slots.length === 2 && + definition.slots[0]?.position === 'A' && + definition.slots[1]?.position === 'B', + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} must define exactly the local A and B slots`, + ); + + const requiredSlots = + definition.rule.type === 'fixed-games' + ? definition.rule.gameCount + : definition.rule.maxGames; + assertCompetitionInvariant( + Number.isInteger(requiredSlots) && requiredSlots > 0, + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} has an invalid game count`, + ); + if (definition.rule.type === 'first-to') { + assertCompetitionInvariant( + Number.isInteger(definition.rule.winsRequired) && + definition.rule.winsRequired > 0 && + definition.rule.winsRequired <= definition.rule.maxGames, + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} has an invalid first-to threshold`, + ); + } + assertCompetitionInvariant( + definition.gameSlots.length === requiredSlots, + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} must predefine every GameSlot`, + ); + + const ids = new Set(); + const ordinals = new Set(); + for (const slot of definition.gameSlots) { + assertCompetitionInvariant( + slot.seriesId === definition.id && + typeof slot.id === 'string' && + slot.id.length > 0, + 'SERIES_DEFINITION_INVALID', + `GameSlot ${slot.id} does not belong to Series ${definition.id}`, + ); + assertCompetitionInvariant( + Number.isInteger(slot.ordinal) && + slot.ordinal >= 1 && + slot.ordinal <= requiredSlots, + 'SERIES_DEFINITION_INVALID', + `GameSlot ${slot.id} has an invalid ordinal`, + ); + assertCompetitionInvariant( + !ids.has(slot.id) && !ordinals.has(slot.ordinal), + 'SERIES_DEFINITION_INVALID', + `Series ${definition.id} has duplicate GameSlot identity or ordinal`, + ); + ids.add(slot.id); + ordinals.add(slot.ordinal); + } +} + +function normalizeParticipants( + participants: readonly (string | null | undefined)[], +): [string | null, string | null] { + assertCompetitionInvariant( + participants.length === 2, + 'SERIES_PARTICIPANTS_INVALID', + 'A Series projection requires exactly two participant slots', + ); + const normalized = participants.map((teamId) => teamId ?? null) as [ + string | null, + string | null, + ]; + for (const teamId of normalized) { + assertCompetitionInvariant( + teamId === null || (typeof teamId === 'string' && teamId.length > 0), + 'SERIES_PARTICIPANTS_INVALID', + 'Resolved participant ids must be opaque non-empty strings', + ); + } + assertCompetitionInvariant( + normalized[0] === null || + normalized[1] === null || + normalized[0] !== normalized[1], + 'SERIES_PARTICIPANTS_INVALID', + 'A team cannot occupy both Series slots', + ); + return normalized; +} + +function normalizeFacts(facts: readonly unknown[]): CompetitionFact[] { + const normalized = facts.map(normalizeFact).sort(compareFacts); + const factIds = new Set(); + const gameIds = new Set(); + const riotMatchIds = new Set(); + + for (const fact of normalized) { + assertCompetitionInvariant( + !factIds.has(fact.id), + 'DUPLICATE_FACT_ID', + `Duplicate fact id ${fact.id}`, + { factId: fact.id }, + ); + factIds.add(fact.id); + + if (fact.type === 'game-accepted') { + assertCompetitionInvariant( + !gameIds.has(fact.gameId), + 'DUPLICATE_GAME_ID', + `Duplicate game id ${fact.gameId}`, + { gameId: fact.gameId }, + ); + gameIds.add(fact.gameId); + const riotMatchId = fact.evidence?.riotMatchId; + if (fact.evidence?.type === 'riot' && riotMatchId) { + assertCompetitionInvariant( + !riotMatchIds.has(riotMatchId), + 'DUPLICATE_RIOT_MATCH_ID', + `Riot match ${riotMatchId} was accepted more than once`, + { riotMatchId }, + ); + riotMatchIds.add(riotMatchId); + } + } + } + return normalized; +} + +function normalizeFact(value: unknown): CompetitionFact { + assertCompetitionInvariant( + isRecord(value) && + typeof value.id === 'string' && + typeof value.type === 'string' && + Number.isFinite(value.revision) && + Number.isFinite(value.ordinalWithinRevision), + 'FACT_TYPE_INVALID', + 'Competition facts require identity and ledger ordering fields', + ); + + switch (value.type) { + case 'game-accepted': + case 'game-voided': + case 'series-adjudicated': + case 'adjudication-reversed': + return value as unknown as CompetitionFact; + default: + throw new CompetitionDomainError( + 'FACT_TYPE_INVALID', + `Unsupported Competition fact type ${value.type}`, + { factType: value.type }, + ); + } +} + +function selectRelevantFacts( + seriesId: string, + facts: CompetitionFact[], +): CompetitionFact[] { + const acceptedSeriesById = new Map( + facts + .filter((fact): fact is GameAcceptedFact => fact.type === 'game-accepted') + .map((fact) => [fact.id, fact.seriesId]), + ); + const adjudicationSeriesById = new Map( + facts + .filter( + (fact): fact is SeriesAdjudicatedFact => + fact.type === 'series-adjudicated', + ) + .map((fact) => [fact.id, fact.seriesId]), + ); + + return facts.filter((fact) => { + switch (fact.type) { + case 'game-accepted': + case 'series-adjudicated': + return fact.seriesId === seriesId; + case 'game-voided': { + const targetSeriesId = acceptedSeriesById.get(fact.gameAcceptedFactId); + assertCompetitionInvariant( + targetSeriesId !== undefined, + 'FACT_REFERENCE_NOT_FOUND', + `Voided game fact ${fact.gameAcceptedFactId} does not exist`, + { factId: fact.id, referencedFactId: fact.gameAcceptedFactId }, + ); + return targetSeriesId === seriesId; + } + case 'adjudication-reversed': { + const targetSeriesId = adjudicationSeriesById.get( + fact.adjudicationFactId, + ); + assertCompetitionInvariant( + targetSeriesId !== undefined, + 'FACT_REFERENCE_NOT_FOUND', + `Adjudication fact ${fact.adjudicationFactId} does not exist`, + { factId: fact.id, referencedFactId: fact.adjudicationFactId }, + ); + return targetSeriesId === seriesId; + } + } + }); +} + +function assertNoSeriesActivity( + seriesId: string, + facts: CompetitionFact[], +): void { + const hasActivity = facts.some( + (fact) => + (fact.type === 'game-accepted' || fact.type === 'series-adjudicated') && + fact.seriesId === seriesId, + ); + assertCompetitionInvariant( + !hasActivity, + 'SERIES_PARTICIPANTS_INVALID', + `Series ${seriesId} cannot contain facts before both participants are active`, + { seriesId }, + ); +} + +function validateAcceptedGame( + definition: SeriesDefinitionLike, + participants: [string, string], + fact: GameAcceptedFact, +): void { + assertCompetitionInvariant( + fact.seriesId === definition.id, + 'GAME_SERIES_MISMATCH', + `Game ${fact.gameId} targets a different Series`, + ); + const slot = definition.gameSlots.find( + (candidate) => candidate.id === fact.gameSlotId, + ); + assertCompetitionInvariant( + slot !== undefined, + 'GAME_SLOT_INVALID', + `Game ${fact.gameId} targets an unknown GameSlot`, + { gameId: fact.gameId, gameSlotId: fact.gameSlotId }, + ); + assertCompetitionInvariant( + slot.ordinal === fact.ordinal, + 'GAME_ORDINAL_INVALID', + `Game ${fact.gameId} ordinal does not match its GameSlot`, + { gameId: fact.gameId, ordinal: fact.ordinal }, + ); + + const { blueTeamId, redTeamId, winnerTeamId } = fact.mapping; + const expectedTeams = new Set(participants); + const actualTeams = new Set([blueTeamId, redTeamId]); + assertCompetitionInvariant( + actualTeams.size === 2 && + expectedTeams.size === actualTeams.size && + [...expectedTeams].every((teamId) => actualTeams.has(teamId)), + 'GAME_TEAM_MISMATCH', + `Game ${fact.gameId} teams do not match Series ${definition.id}`, + { + gameId: fact.gameId, + expectedTeamIds: participants, + actualTeamIds: [blueTeamId, redTeamId], + }, + ); + assertCompetitionInvariant( + winnerTeamId === blueTeamId || winnerTeamId === redTeamId, + 'GAME_WINNER_INVALID', + `Game ${fact.gameId} winner is not a participant`, + { gameId: fact.gameId, winnerTeamId }, + ); +} + +function validateActiveGameUniqueness( + activeGames: Iterable, + fact: GameAcceptedFact, +): void { + for (const active of activeGames) { + assertCompetitionInvariant( + active.gameSlotId !== fact.gameSlotId, + 'DUPLICATE_GAME_SLOT', + `GameSlot ${fact.gameSlotId} already has an accepted game`, + { gameSlotId: fact.gameSlotId }, + ); + assertCompetitionInvariant( + active.ordinal !== fact.ordinal, + 'DUPLICATE_GAME_ORDINAL', + `Series ordinal ${fact.ordinal} already has an accepted game`, + { ordinal: fact.ordinal }, + ); + } +} + +function validateAdjudication( + definition: SeriesDefinitionLike, + participants: [string, string], + activeGames: GameAcceptedFact[], + fact: SeriesAdjudicatedFact, +): void { + assertCompetitionInvariant( + typeof fact.reason === 'string' && fact.reason.trim().length > 0, + 'ADJUDICATION_INVALID', + `Adjudication ${fact.id} requires a reason`, + ); + if (fact.decision.type === 'administrative-draw') { + assertCompetitionInvariant( + definition.rule.type === 'fixed-games' && + definition.rule.drawPolicy === 'allow', + 'ADJUDICATION_DRAW_NOT_ALLOWED', + `Series ${definition.id} cannot be adjudicated as a draw`, + ); + return; + } + assertCompetitionInvariant( + participants.includes(fact.decision.winnerTeamId), + 'ADJUDICATION_INVALID', + `Adjudication winner is not a Series participant`, + ); + if (fact.decision.type === 'walkover') { + assertCompetitionInvariant( + activeGames.length === 0, + 'WALKOVER_HAS_ACTIVE_GAMES', + `Walkover Series ${definition.id} cannot retain played games`, + ); + } +} + +function derivePlayedState( + rule: SeriesRule, + games: GameAcceptedFact[], + participants: [string, string], +): PlayedState { + const activeGames = [...games].sort(compareGames); + const winsByTeam = new Map(participants.map((teamId) => [teamId, 0])); + for (const game of activeGames) { + const winnerTeamId = game.mapping.winnerTeamId; + winsByTeam.set(winnerTeamId, (winsByTeam.get(winnerTeamId) ?? 0) + 1); + } + const completed = + rule.type === 'fixed-games' + ? activeGames.length === rule.gameCount + : participants.some( + (teamId) => (winsByTeam.get(teamId) ?? 0) >= rule.winsRequired, + ); + return { activeGames, winsByTeam, completed }; +} + +function playedOutcome( + rule: SeriesRule, + activeGames: GameAcceptedFact[], + participants: [string, string], + winsByTeam: Map, +): SeriesProjectionOutcome { + const decidedByGameIds = activeGames.map((game) => game.gameId); + const completedAt = toIsoString(activeGames.at(-1)!.occurredAt); + const [teamAId, teamBId] = participants; + const teamAWins = winsByTeam.get(teamAId) ?? 0; + const teamBWins = winsByTeam.get(teamBId) ?? 0; + + if (teamAWins === teamBWins) { + assertCompetitionInvariant( + rule.type === 'fixed-games' && rule.drawPolicy === 'allow', + 'SERIES_DEFINITION_INVALID', + 'This Series completed tied but its rule requires a winner', + ); + return { + type: 'draw', + basis: { type: 'played', decidedByGameIds }, + completedAt, + }; + } + + const winnerTeamId = teamAWins > teamBWins ? teamAId : teamBId; + return { + type: 'played', + winnerTeamId, + loserTeamId: winnerTeamId === teamAId ? teamBId : teamAId, + decidedByGameIds, + completedAt, + }; +} + +function adjudicatedOutcome( + fact: SeriesAdjudicatedFact, + participants: [string, string], +): SeriesProjectionOutcome { + const completedAt = toIsoString(fact.occurredAt); + if (fact.decision.type === 'administrative-draw') { + return { + type: 'draw', + basis: { type: 'administrative', decisionFactId: fact.id }, + completedAt, + }; + } + const winnerTeamId = fact.decision.winnerTeamId; + return { + type: fact.decision.type, + winnerTeamId, + loserTeamId: + participants[0] === winnerTeamId ? participants[1] : participants[0], + decisionFactId: fact.id, + completedAt, + }; +} + +function projectionBase( + definition: SeriesDefinitionLike, + participants: [string | null, string | null], +): SeriesProjectionBase { + return { + seriesId: definition.id, + ...(definition.code ? { code: definition.code } : {}), + stage: definition.stage, + rule: definition.rule, + entries: [ + { slot: 'A', teamId: participants[0], gameWins: 0 }, + { slot: 'B', teamId: participants[1], gameWins: 0 }, + ], + }; +} + +function entriesFor( + participants: [string, string], + winsByTeam: Map, +): [SeriesProjectionEntry, SeriesProjectionEntry] { + return [ + { + slot: 'A', + teamId: participants[0], + gameWins: winsByTeam.get(participants[0]) ?? 0, + }, + { + slot: 'B', + teamId: participants[1], + gameWins: winsByTeam.get(participants[1]) ?? 0, + }, + ]; +} + +function deriveLeader( + participants: [string, string], + winsByTeam: Map, +): string | undefined { + const firstWins = winsByTeam.get(participants[0]) ?? 0; + const secondWins = winsByTeam.get(participants[1]) ?? 0; + if (firstWins === secondWins) return undefined; + return firstWins > secondWins ? participants[0] : participants[1]; +} + +function compareFacts(left: CompetitionFact, right: CompetitionFact): number { + return ( + left.revision - right.revision || + left.ordinalWithinRevision - right.ordinalWithinRevision || + left.id.localeCompare(right.id) + ); +} + +function compareGames(left: GameAcceptedFact, right: GameAcceptedFact): number { + return ( + left.ordinal - right.ordinal || + left.revision - right.revision || + left.id.localeCompare(right.id) + ); +} + +function toIsoString(value: Date | string): string { + const date = value instanceof Date ? value : new Date(value); + assertCompetitionInvariant( + !Number.isNaN(date.getTime()), + 'FACT_TYPE_INVALID', + 'Fact timestamps must be valid dates', + ); + return date.toISOString(); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +}