feat: enrich internal match game analysis

This commit is contained in:
dahyeon committed 2026-07-13 09:35:25 +00:00
1 parent 9f698a8fec
commit aa675199af
22 files changed
+3123 -241

No files matched your search

@@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
}
describe('CommunityStatsService', () => {
it('ignores stale detail cache entries missing timeline build fields', async () => {
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
@@ -97,6 +97,20 @@ describe('CommunityStatsService', () => {
seriesResults: [],
};
const participant = record(matchId);
Object.assign(participant, {
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
});
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
@@ -125,38 +139,81 @@ describe('CommunityStatsService', () => {
},
],
};
const staleCache = {
match,
games: [
Object.assign(gameDetail, {
timelineEvents: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
teams: [
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [],
},
],
});
const otherwiseCompleteCachedGame = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
timeline: [],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: { tower: 1, dragon: 0, baron: 0 },
participants: [
{
summonerName: 'Player',
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
},
},
],
summonerName: 'Cached Player',
tagLine: 'KR1',
itemBuild: [],
skillBuild: [],
},
],
},
],
};
const missingTimelineEventsCache = {
match,
games: [otherwiseCompleteCachedGame],
} as unknown as InternalMatchDetailResponse;
const invalidCheckpointCache = {
match,
games: [
{
...otherwiseCompleteCachedGame,
timelineEvents: [],
teams: otherwiseCompleteCachedGame.teams.map((team) => ({
...team,
participants: team.participants.map((cachedParticipant) => ({
...cachedParticipant,
participantId: 1,
checkpoints: {
at10: {
timestamp: '590',
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
})),
})),
},
],
} as unknown as InternalMatchDetailResponse;
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(staleCache),
setDetail: jest.fn().mockResolvedValue(undefined),
get: jest
.fn()
.mockResolvedValueOnce(missingTimelineEventsCache)
.mockResolvedValueOnce(invalidCheckpointCache),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
@@ -180,22 +237,245 @@ describe('CommunityStatsService', () => {
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
});
const response = await service.getMatchDetail({ communityId, matchId });
const missingEventsResponse = await service.getMatchDetail({
communityId,
matchId,
});
const invalidCheckpointResponse = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games[0].timeline).toHaveLength(1);
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength(
1,
);
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
expect(missingEventsResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0]).toMatchObject({
timelineEvents: [
{
timestamp: 300,
side: 'blue',
type: 'championKill',
},
],
});
expect(
invalidCheckpointResponse.games[0].teams[0].participants[0],
).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
perks: {
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
},
});
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
expect(cacheService.setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r3:'),
response,
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.stringContaining(':r4:'),
invalidCheckpointResponse,
);
});
it('backs off failed timeline hydration and retries after the short cache expires', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
const dataset = (timelineLoaded: boolean) => ({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[matchId.toString(), [{ ...gameDetail, timelineLoaded }]],
]),
});
let cachedResponse: InternalMatchDetailResponse | null = null;
const set = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const setDetail = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const cacheService = {
get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)),
set,
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest
.fn()
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(true));
const fallback = await service.getMatchDetail({ communityId, matchId });
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(set).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
fallback,
60,
);
expect(setDetail).not.toHaveBeenCalled();
cachedResponse = null;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
recovered,
);
});
it('coalesces concurrent internal match detail cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const dataset = {
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue' as const,
timelineLoaded: true,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
},
],
],
]),
};
let resolveDataset: ((value: typeof dataset) => void) | undefined;
const datasetPromise = new Promise<typeof dataset>((resolve) => {
resolveDataset = resolve;
});
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(null),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
);
const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
buildBaseDataset;
const first = service.getMatchDetail({ communityId, matchId });
const second = service.getMatchDetail({ communityId, matchId });
await Promise.resolve();
resolveDataset?.(dataset);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(buildBaseDataset).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledTimes(1);
});
it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -40,7 +40,8 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
community: CommunityDocument;
@@ -59,6 +60,10 @@ interface BaseDataset {
@Injectable()
export class CommunityStatsService {
private readonly logger = new Logger(CommunityStatsService.name);
private readonly matchDetailInFlight = new Map<
string,
Promise<InternalMatchDetailResponse>
>();
private readonly userInternalHistoryInFlight = new Map<
string,
Promise<UserInternalHistoryResponse>
@@ -219,6 +224,27 @@ export class CommunityStatsService {
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const inFlight = this.matchDetailInFlight.get(key);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key) === promise) {
this.matchDetailInFlight.delete(key);
}
}
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
},
key: string,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
@@ -246,6 +272,7 @@ export class CommunityStatsService {
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
@@ -253,6 +280,8 @@ export class CommunityStatsService {
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
participantId: record.participantId,
checkpoints: record.checkpoints,
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
@@ -289,7 +318,15 @@ export class CommunityStatsService {
})),
})),
};
await this.cacheService.setDetail(key, response);
if (gameDetails.every((game) => game.timelineLoaded === true)) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
key,
response,
INCOMPLETE_MATCH_DETAIL_TTL_SECONDS,
);
}
return response;
}
@@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse(
(game) =>
Array.isArray(game.timeline) &&
Array.isArray(game.objectiveEvents) &&
Array.isArray(game.timelineEvents) &&
game.teams.every(
(team) =>
Array.isArray(team.bans) &&
@@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse(
(participant) =>
typeof participant.tagLine === 'string' &&
Array.isArray(participant.itemBuild) &&
Array.isArray(participant.skillBuild),
Array.isArray(participant.skillBuild) &&
isOptionalFiniteNumber(participant.participantId) &&
isCompleteParticipantCheckpoints(participant.checkpoints),
),
),
);
}
function isCompleteParticipantCheckpoints(value: unknown): boolean {
if (value === undefined) return true;
if (!isRecord(value)) return false;
return ['at10', 'at15'].every((key) => {
const checkpoint = value[key];
if (checkpoint === undefined) return true;
if (!isRecord(checkpoint)) return false;
return [
'timestamp',
'gold',
'cs',
'xp',
'kills',
'deaths',
'assists',
].every((field) => isFiniteNumber(checkpoint[field]));
});
}
function isOptionalFiniteNumber(value: unknown): boolean {
return value === undefined || isFiniteNumber(value);
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -1,7 +1,9 @@
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
MatchStatsRunePerks,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
RiotLane,
TeamSide,
} from '../global/database/schema';
@@ -128,6 +130,7 @@ export interface InternalMatchDetailResponse {
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
timelineEvents: MatchStatsTimelineEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -143,6 +146,8 @@ export interface InternalMatchDetailResponse {
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string | null;
summonerName: string;
tagLine: string;
@@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => {
it('builds rich set detail from raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const redUserId = new mongoose.Types.ObjectId();
match.participants.push({
userId: redUserId,
puuid: 'puuid-2',
gameName: 'Opponent',
profileIconId: 8,
});
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
match.result?.games[0].participants.push({
userId: redUserId,
teamIndex: 2,
side: 'red',
championId: 24,
kills: 1,
deaths: 3,
assists: 0,
win: false,
});
const raw = {
metadata: {
dataVersion: '2',
@@ -206,6 +224,51 @@ describe('MatchStatsFragmentBuilder', () => {
],
},
};
raw.info.participants.push(
{
...raw.info.participants[0],
assists: 0,
championId: 24,
championName: 'Jax',
deaths: 3,
kills: 1,
participantId: 2,
puuid: 'puuid-2',
riotIdGameName: 'Opponent',
summonerId: 'summoner-2',
summonerName: 'Opponent',
teamId: 200,
win: false,
},
{
...raw.info.participants[0],
assists: 2,
championId: 64,
championName: 'LeeSin',
deaths: 0,
kills: 1,
participantId: 3,
puuid: 'puuid-3',
riotIdGameName: 'Jungler',
summonerId: 'summoner-3',
summonerName: 'Jungler',
teamId: 100,
},
);
raw.info.teams.push({
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 3 },
dragon: { first: false, kills: 0 },
horde: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 200,
win: false,
});
const timeline = {
metadata: {
dataVersion: '2',
@@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => {
{
timestamp: 0,
participantFrames: {
'1': { participantId: 1, totalGold: 500, xp: 0 },
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
'2': {
participantId: 2,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
},
{
@@ -291,7 +367,137 @@ describe('MatchStatsFragmentBuilder', () => {
},
],
participantFrames: {
'1': { participantId: 1, totalGold: 1_150, xp: 550 },
'1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
minionsKilled: 5,
jungleMinionsKilled: 1,
},
'2': {
participantId: 2,
totalGold: 1_050,
xp: 500,
minionsKilled: 4,
jungleMinionsKilled: 0,
},
},
},
{
timestamp: 540_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 300_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
{
type: 'CHAMPION_KILL',
timestamp: 400_000,
killerId: 0,
victimId: 1,
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 0,
teamId: 200,
buildingType: 'TOWER_BUILDING',
towerType: 'OUTER_TURRET',
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 1,
teamId: 200,
buildingType: 'INHIBITOR_BUILDING',
},
{
type: 'CHAMPION_KILL',
timestamp: 500_000,
killerId: 3,
victimId: 2,
assistingParticipantIds: [1],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 4_900,
xp: 3_900,
minionsKilled: 72,
jungleMinionsKilled: 8,
},
'2': {
participantId: 2,
totalGold: 4_300,
xp: 3_500,
minionsKilled: 68,
jungleMinionsKilled: 2,
},
},
},
{
timestamp: 590_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 5_200,
xp: 4_200,
minionsKilled: 80,
jungleMinionsKilled: 10,
},
},
},
{
timestamp: 900_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 900_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 8_100,
xp: 7_300,
minionsKilled: 130,
jungleMinionsKilled: 15,
},
'2': {
participantId: 2,
totalGold: 6_700,
xp: 6_100,
minionsKilled: 115,
jungleMinionsKilled: 5,
},
},
},
{
timestamp: 1_800_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 12_500,
xp: 14_000,
minionsKilled: 205,
jungleMinionsKilled: 23,
},
'2': {
participantId: 2,
totalGold: 10_200,
xp: 12_700,
minionsKilled: 190,
jungleMinionsKilled: 10,
},
},
},
],
@@ -329,19 +535,105 @@ describe('MatchStatsFragmentBuilder', () => {
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 0, xp: 0 },
goldDiff: 500,
red: { gold: 500, xp: 0 },
goldDiff: 0,
xpDiff: 0,
},
{
timestamp: 60,
blue: { gold: 1_150, xp: 550 },
red: { gold: 1_050, xp: 500 },
goldDiff: 100,
xpDiff: 50,
},
{
timestamp: 540,
blue: { gold: 4_900, xp: 3_900 },
red: { gold: 4_300, xp: 3_500 },
goldDiff: 600,
xpDiff: 400,
},
{
timestamp: 590,
blue: { gold: 5_200, xp: 4_200 },
red: { gold: 0, xp: 0 },
goldDiff: 1_150,
xpDiff: 550,
goldDiff: 5_200,
xpDiff: 4_200,
},
{
timestamp: 900,
blue: { gold: 8_100, xp: 7_300 },
red: { gold: 6_700, xp: 6_100 },
goldDiff: 1_400,
xpDiff: 1_200,
},
{
timestamp: 1_800,
blue: { gold: 12_500, xp: 14_000 },
red: { gold: 10_200, xp: 12_700 },
goldDiff: 2_300,
xpDiff: 1_300,
},
],
});
expect(fragment.gameDetails[0].timelineEvents).toEqual([
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
{
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
{
timestamp: 400,
type: 'championKill',
victimParticipantId: 1,
},
{
timestamp: 450,
side: 'blue',
type: 'tower',
towerType: 'OUTER_TURRET',
},
{
timestamp: 450,
side: 'blue',
type: 'inhibitor',
killerParticipantId: 1,
},
{
timestamp: 500,
side: 'blue',
type: 'championKill',
killerParticipantId: 3,
victimParticipantId: 2,
assistingParticipantIds: [1],
},
{
timestamp: 900,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
]);
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
@@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => {
voidGrub: 1,
});
expect(fragment.records[0]).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
at15: {
timestamp: 900,
gold: 8_100,
cs: 145,
xp: 7_300,
kills: 2,
deaths: 1,
assists: 1,
},
},
championLevel: 15,
cs: 228,
damageDealtToChampions: 18_765,
@@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => {
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
],
});
expect(fragment.records[1]).toMatchObject({
participantId: 2,
checkpoints: {
at15: {
timestamp: 900,
gold: 6_700,
cs: 120,
xp: 6_100,
kills: 0,
deaths: 3,
assists: 0,
},
},
});
expect(fragment.records[1].checkpoints).not.toHaveProperty('at10');
const timelineWithoutEvents = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: [],
})),
},
} as RiotMatchTimelineDto;
const objectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]),
});
expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 2,
elderDragon: 0,
riftHerald: 0,
voidGrub: 3,
});
const dragonOnlyTimeline = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: (frame.events ?? []).filter(
(event) =>
event.type !== 'ELITE_MONSTER_KILL' ||
event.monsterType === 'DRAGON',
),
})),
},
} as RiotMatchTimelineDto;
const partialObjectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]),
});
expect(
partialObjectiveFallback.gameDetails[0].teams[0].objectives,
).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
riftHerald: 0,
voidGrub: 3,
});
const shortMatch = {
...match,
result: {
...match.result!,
games: match.result!.games.map((game) => ({
...game,
gameDuration: 599,
})),
},
} as MatchDocument;
const shortFragment = builder.buildFragment({
match: shortMatch,
rawByRiotMatchId: new Map([
[
'KR_1',
{
...raw,
info: { ...raw.info, gameDuration: 599 },
} as RiotMatchDto,
],
]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
});
expect(
shortFragment.records.every((record) => record.checkpoints === undefined),
).toBe(true);
const invalidIntervalTimeline = {
...timeline,
info: { ...timeline.info, frameInterval: Number.NaN },
} as RiotMatchTimelineDto;
const invalidIntervalFragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]),
});
expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false);
expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]);
expect(
invalidIntervalFragment.records.every(
(record) => record.checkpoints === undefined,
),
).toBe(true);
});
});
@@ -3,10 +3,13 @@ import mongoose from 'mongoose';
import type {
MatchDocument,
MatchGameResultParticipant,
MatchStatsCheckpoint,
MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary,
MatchStatsParticipantCheckpoints,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
MatchStatsTimelinePoint,
TeamSide,
} from '../global/database/schema';
@@ -27,13 +30,17 @@ interface ParticipantBuildEvents {
skills: MatchStatsSkillBuildEvent[];
}
interface TimelineProjection {
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents: MatchStatsTimelineEvent[];
}
@Injectable()
export class MatchStatsFragmentBuilder {
public buildFragment(params: {
match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
timelineLoadAttempted?: boolean;
}): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
@@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder {
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw
? this.toGameDetail(
params.match,
game,
raw,
timeline,
params.timelineLoadAttempted === true,
)
? this.toGameDetail(params.match, game, raw, timeline)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
@@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto,
timelineLoadAttempted = false,
): InternalGameDetail {
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
? timeline
: undefined;
const puuidByUserId = new Map(
match.participants
.filter((participant) => participant.puuid)
@@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder {
raw,
rawTeamIdBySide,
);
const objectiveEvents = this.toObjectiveEvents(
timeline,
const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
usableTimeline,
rawTeamIdBySide,
sideByParticipantId,
);
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
const buildEventsByParticipantId =
this.toBuildEventsByParticipantId(timeline);
this.toBuildEventsByParticipantId(usableTimeline);
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
usableTimeline,
raw.info.gameDuration,
);
return {
gameNumber: game.gameNumber,
@@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder {
gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline),
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder {
objectives: this.toObjectiveSummary(
rawTeam,
timelineObjectives.get(side),
Boolean(timeline),
),
bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId,
@@ -224,6 +231,9 @@ export class MatchStatsFragmentBuilder {
rawParticipant.participantId,
)
: undefined,
checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
: undefined,
teamKills,
teamDamage,
});
@@ -246,6 +256,7 @@ export class MatchStatsFragmentBuilder {
timeline: [],
timelineLoaded: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
@@ -273,6 +284,7 @@ export class MatchStatsFragmentBuilder {
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
checkpoints?: MatchStatsParticipantCheckpoints;
teamKills: number;
teamDamage: number;
}): InternalRecord {
@@ -282,6 +294,7 @@ export class MatchStatsFragmentBuilder {
participant,
rawParticipant,
buildEvents,
checkpoints,
teamKills,
teamDamage,
} = params;
@@ -319,6 +332,8 @@ export class MatchStatsFragmentBuilder {
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
participantId: rawParticipant?.participantId,
checkpoints,
userId: participant.userId.toString(),
summonerName:
snapshot?.gameName ??
@@ -455,6 +470,107 @@ export class MatchStatsFragmentBuilder {
return buildEventsByParticipantId;
}
private toCheckpointsByParticipantId(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): Map<number, MatchStatsParticipantCheckpoints> {
const checkpointsByParticipantId = new Map<
number,
MatchStatsParticipantCheckpoints
>();
if (
!timeline?.info.frames.length ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0
) {
return checkpointsByParticipantId;
}
const participantIds = new Set<number>();
const championKillEvents = timeline.info.frames.flatMap((frame) =>
(frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'),
);
for (const frame of timeline.info.frames) {
for (const participantFrame of Object.values(frame.participantFrames)) {
participantIds.add(participantFrame.participantId);
}
}
const targets = [
['at10', 600_000],
['at15', 900_000],
] as const;
for (const participantId of participantIds) {
const checkpoints: MatchStatsParticipantCheckpoints = {};
for (const [key, targetTimestamp] of targets) {
if (gameDurationSeconds * 1_000 < targetTimestamp) continue;
const selectedFrame = timeline.info.frames.reduce<
RiotMatchTimelineDto['info']['frames'][number] | undefined
>((latest, frame) => {
if (
frame.timestamp > targetTimestamp ||
!Object.values(frame.participantFrames).some(
(participantFrame) =>
participantFrame.participantId === participantId,
)
) {
return latest;
}
return !latest || frame.timestamp > latest.timestamp ? frame : latest;
}, undefined);
if (
!selectedFrame ||
targetTimestamp - selectedFrame.timestamp >=
timeline.info.frameInterval
) {
continue;
}
const participantFrame = Object.values(
selectedFrame.participantFrames,
).find((frame) => frame.participantId === participantId);
if (
!participantFrame ||
typeof participantFrame.minionsKilled !== 'number' ||
!Number.isFinite(participantFrame.minionsKilled) ||
typeof participantFrame.jungleMinionsKilled !== 'number' ||
!Number.isFinite(participantFrame.jungleMinionsKilled)
) {
continue;
}
const checkpoint: MatchStatsCheckpoint = {
timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)),
gold: participantFrame.totalGold,
cs:
participantFrame.minionsKilled +
participantFrame.jungleMinionsKilled,
xp: participantFrame.xp,
kills: 0,
deaths: 0,
assists: 0,
};
for (const event of championKillEvents) {
if (event.timestamp > selectedFrame.timestamp) continue;
if (event.killerId === participantId && event.killerId > 0) {
checkpoint.kills += 1;
}
if (event.victimId === participantId) checkpoint.deaths += 1;
if (event.assistingParticipantIds?.includes(participantId)) {
checkpoint.assists += 1;
}
}
checkpoints[key] = checkpoint;
}
if (checkpoints.at10 || checkpoints.at15) {
checkpointsByParticipantId.set(participantId, checkpoints);
}
}
return checkpointsByParticipantId;
}
private toTimeline(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
@@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder {
return sideByParticipantId;
}
private toObjectiveEvents(
private toTimelineEvents(
timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>,
): MatchStatsObjectiveEvent[] {
if (!timeline?.info.frames.length) return [];
): TimelineProjection {
if (!timeline?.info.frames.length) {
return { objectiveEvents: [], timelineEvents: [] };
}
const sideByTeamId = new Map<number, TeamSide>();
for (const [side, teamId] of rawTeamIdBySide.entries()) {
sideByTeamId.set(teamId, side);
}
const objectiveEvents: MatchStatsObjectiveEvent[] = [];
const projected: Array<{
sourceSequence: number;
event: MatchStatsTimelineEvent;
}> = [];
let sourceSequence = 0;
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
if (event.type !== 'ELITE_MONSTER_KILL') continue;
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const currentSequence = sourceSequence;
sourceSequence += 1;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
switch (event.monsterType) {
case 'BARON_NASHOR':
objectiveEvents.push({ timestamp, side, type: 'baron' });
break;
case 'RIFTHERALD':
objectiveEvents.push({ timestamp, side, type: 'riftHerald' });
break;
case 'HORDE':
objectiveEvents.push({ timestamp, side, type: 'voidGrub' });
break;
case 'DRAGON':
if (event.monsterSubType === 'ELDER_DRAGON') {
objectiveEvents.push({
timestamp,
side,
type: 'elderDragon',
monsterSubType: event.monsterSubType,
});
} else {
objectiveEvents.push({
timestamp,
side,
type: 'dragon',
monsterSubType: event.monsterSubType,
});
}
break;
default:
break;
if (event.type === 'ELITE_MONSTER_KILL') {
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const objectiveEvent = toObjectiveTimelineEvent({
timestamp,
side,
monsterType: event.monsterType,
monsterSubType: event.monsterSubType,
});
if (objectiveEvent) {
projected.push({
sourceSequence: currentSequence,
event: objectiveEvent,
});
}
continue;
}
if (event.type === 'CHAMPION_KILL') {
const side =
typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
type: 'championKill',
...(side ? { side } : {}),
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(typeof event.victimId === 'number' && event.victimId > 0
? { victimParticipantId: event.victimId }
: {}),
...(event.assistingParticipantIds
? { assistingParticipantIds: event.assistingParticipantIds }
: {}),
},
});
continue;
}
if (event.type !== 'BUILDING_KILL') continue;
const destroyedSide =
typeof event.teamId === 'number'
? sideByTeamId.get(event.teamId)
: undefined;
const side =
(typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined) ??
(destroyedSide ? oppositeSide(destroyedSide) : undefined);
const type =
event.buildingType === 'TOWER_BUILDING'
? 'tower'
: event.buildingType === 'INHIBITOR_BUILDING'
? 'inhibitor'
: undefined;
if (!side || !type) continue;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
side,
type,
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(type === 'tower' && event.towerType
? { towerType: event.towerType }
: {}),
},
});
}
}
return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp);
const timelineEvents = projected
.sort(
(left, right) =>
left.event.timestamp - right.event.timestamp ||
left.sourceSequence - right.sourceSequence,
)
.map(({ event }) => event);
return {
timelineEvents,
objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent),
};
}
private toTimelineObjectives(
@@ -608,29 +783,29 @@ export class MatchStatsFragmentBuilder {
}
private toObjectiveSummary(
rawTeam:
| RiotMatchDto['info']['teams'][number]
| undefined,
rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
timelineObjectives: MatchStatsObjectiveSummary | undefined,
hasTimeline: boolean,
): MatchStatsObjectiveSummary {
const rawObjectives = rawTeam?.objectives;
const timelineDragon = timelineObjectives?.dragon ?? 0;
const timelineElder = timelineObjectives?.elderDragon ?? 0;
const hasProjectedDragon = timelineDragon + timelineElder > 0;
return {
tower: rawObjectives?.tower?.kills ?? 0,
dragon: hasTimeline
? (timelineObjectives?.dragon ?? 0)
dragon: hasProjectedDragon
? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: hasTimeline
baron: (timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald: hasTimeline
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub: hasTimeline
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: timelineObjectives?.elderDragon ?? 0,
elderDragon: hasProjectedDragon ? timelineElder : 0,
};
}
@@ -687,6 +862,79 @@ function toItemBuildType(
}
}
function toObjectiveTimelineEvent(params: {
timestamp: number;
side: TeamSide;
monsterType?: string;
monsterSubType?: string;
}): MatchStatsObjectiveEvent | null {
switch (params.monsterType) {
case 'BARON_NASHOR':
return { timestamp: params.timestamp, side: params.side, type: 'baron' };
case 'RIFTHERALD':
return {
timestamp: params.timestamp,
side: params.side,
type: 'riftHerald',
};
case 'HORDE':
return {
timestamp: params.timestamp,
side: params.side,
type: 'voidGrub',
};
case 'DRAGON':
return {
timestamp: params.timestamp,
side: params.side,
type:
params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon',
monsterSubType: params.monsterSubType,
};
default:
return null;
}
}
function isObjectiveTimelineEvent(
event: MatchStatsTimelineEvent,
): event is MatchStatsObjectiveEvent {
return (
event.type === 'dragon' ||
event.type === 'elderDragon' ||
event.type === 'baron' ||
event.type === 'riftHerald' ||
event.type === 'voidGrub'
);
}
function oppositeSide(side: TeamSide): TeamSide {
return side === 'blue' ? 'red' : 'blue';
}
function isUsableTimeline(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): timeline is RiotMatchTimelineDto {
if (
!timeline ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0 ||
!Array.isArray(timeline.info.frames) ||
timeline.info.frames.length === 0
) {
return false;
}
const finalTimestamp = Math.max(
...timeline.info.frames.map((frame) => frame.timestamp),
);
return (
Number.isFinite(finalTimestamp) &&
Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) <
timeline.info.frameInterval
);
}
function round(value: number): number {
return Math.round(value * 10) / 10;
}
@@ -3,6 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
describe('MatchStatsService', () => {
it('deletes an existing fragment when the match is no longer eligible', async () => {
@@ -158,8 +159,10 @@ describe('MatchStatsService', () => {
match,
rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
timelineLoadAttempted: false,
});
expect(
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
).toHaveProperty('size', 0);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
@@ -167,11 +170,169 @@ describe('MatchStatsService', () => {
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
builderVersion: 9,
builderVersion: MATCH_STATS_BUILDER_VERSION,
}),
);
});
it('retries unusable timeline caches and stores a later usable fetch', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const emptyTimeline = {
info: { frameInterval: 60_000, frames: [] },
};
const partialTimeline = {
info: {
frameInterval: 60_000,
frames: [{ timestamp: 0, events: [] }],
},
};
const nonPositiveTimeline = {
info: {
frameInterval: 0,
frames: [timelineFrame(120_000)],
},
};
const truncatedTimeline = {
info: {
frameInterval: 60_000,
frames: [timelineFrame()],
},
};
const usableTimeline = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [timelineFrame(120_000)],
},
};
const cachedTimelines = [
emptyTimeline,
partialTimeline,
nonPositiveTimeline,
truncatedTimeline,
];
let buildIndex = 0;
const riotFind = jest.fn().mockImplementation(() => ({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: { info: { gameDuration: 120 } },
timeline: cachedTimelines[Math.min(buildIndex++, 3)],
},
]),
}),
}));
const updateExec = jest.fn().mockResolvedValue(undefined);
let storedUpdate:
| {
filter: unknown;
update: { $set: { timeline: unknown; timelineFetchedAt: Date } };
}
| undefined;
const updateOne = jest.fn(
(
filter: unknown,
update: { $set: { timeline: unknown; timelineFetchedAt: Date } },
) => {
storedUpdate = { filter, update };
return { exec: updateExec };
},
);
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({ findById: () => queryResult(match, false) });
}
if (name === 'competition') {
return Promise.resolve({ findOne: () => queryResult(null) });
}
if (name === 'riotMatch') {
return Promise.resolve({ find: riotFind, updateOne });
}
if (name === 'community') {
return Promise.resolve({
findById: () => ({
select: () => queryResult({ riotRegion: 'asia' }),
}),
});
}
return Promise.reject(new Error(`Unexpected model: ${name}`));
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
type BuildParams = Parameters<
MatchStatsFragmentBuilder['buildFragment']
>[0];
const buildCalls: BuildParams[] = [];
const builtFragment = {
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
});
const builder = {
buildFragment,
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const getMatchTimeline = jest
.fn()
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockResolvedValueOnce(usableTimeline);
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline } as never,
);
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
expect(getMatchTimeline).toHaveBeenCalledTimes(4);
expect(buildFragment).toHaveBeenCalledTimes(4);
expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined();
expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe(
usableTimeline,
);
for (const call of buildCalls) {
expect(call).not.toHaveProperty('timelineLoadAttempted');
}
expect(updateOne).toHaveBeenCalledTimes(1);
expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' });
expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline);
expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date);
expect(updateExec).toHaveBeenCalledTimes(1);
});
it('builds from the Competition projection and records its source revision', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -451,3 +612,19 @@ function queryResult<T>(value: T, lean = true) {
query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec };
}
function timelineFrame(timestamp = 0) {
return {
timestamp,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
};
}
@@ -77,7 +77,7 @@ export class MatchStatsService {
);
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
for (const doc of riotDocs) {
if (isRiotMatchTimelineDto(doc.timeline)) {
if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
}
}
@@ -94,6 +94,12 @@ export class MatchStatsService {
doc.matchId,
{ region },
);
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
this.logger.warn(
`Ignored unusable match timeline for ${doc.matchId}.`,
);
continue;
}
await RiotMatchModel.updateOne(
{ matchId: doc.matchId },
{
@@ -118,7 +124,6 @@ export class MatchStatsService {
match: sourceMatch,
rawByRiotMatchId,
timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true,
});
await this.repository.upsert({
@@ -253,9 +258,65 @@ export class MatchStatsService {
}
}
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
if (!isRecord(value) || !isRecord(value.info)) return false;
return Array.isArray(value.info.frames);
function isUsableRiotMatchTimeline(
value: unknown,
rawMatch: unknown,
): value is RiotMatchTimelineDto {
if (
!isRecord(value) ||
!isRecord(value.info) ||
!isRecord(rawMatch) ||
!isRecord(rawMatch.info)
) {
return false;
}
const frameInterval = finiteNumber(value.info.frameInterval);
const gameDuration = finiteNumber(rawMatch.info.gameDuration);
const frames = value.info.frames;
if (
frameInterval === undefined ||
frameInterval <= 0 ||
gameDuration === undefined ||
gameDuration < 0 ||
!Array.isArray(frames) ||
frames.length === 0 ||
!frames.every(isUsableTimelineFrame)
) {
return false;
}
const lastTimestamp = Math.max(
...frames.map((frame) => (frame as { timestamp: number }).timestamp),
);
return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval;
}
function isUsableTimelineFrame(value: unknown): boolean {
if (
!isRecord(value) ||
finiteNumber(value.timestamp) === undefined ||
!Array.isArray(value.events) ||
!value.events.every(
(event) =>
isRecord(event) &&
typeof event.type === 'string' &&
finiteNumber(event.timestamp) !== undefined,
) ||
!isRecord(value.participantFrames)
) {
return false;
}
const participantFrames = Object.values(value.participantFrames);
return (
participantFrames.length > 0 &&
participantFrames.every(
(participantFrame) =>
isRecord(participantFrame) &&
finiteNumber(participantFrame.participantId) !== undefined &&
finiteNumber(participantFrame.totalGold) !== undefined &&
finiteNumber(participantFrame.xp) !== undefined,
)
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 9;
export const MATCH_STATS_BUILDER_VERSION = 10;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
@@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent {
levelUpType?: string;
}
export interface MatchStatsCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
export interface MatchStatsParticipantCheckpoints {
at10?: MatchStatsCheckpoint;
at15?: MatchStatsCheckpoint;
}
export interface MatchStatsRecord {
matchId: string;
title: string;
@@ -948,6 +963,8 @@ export interface MatchStatsRecord {
riotMatchId: string;
gameCreation: number;
gameDuration: number;
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string;
summonerName: string;
tagLine: string;
@@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail {
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents?: MatchStatsTimelineEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent {
monsterSubType?: string;
}
export interface MatchStatsChampionKillEvent {
timestamp: number;
side?: TeamSide;
type: 'championKill';
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
}
export interface MatchStatsBuildingEvent {
timestamp: number;
side: TeamSide;
type: 'tower' | 'inhibitor';
killerParticipantId?: number;
towerType?: string;
}
export type MatchStatsTimelineEvent =
| MatchStatsObjectiveEvent
| MatchStatsChampionKillEvent
| MatchStatsBuildingEvent;
export interface MatchStatsTimelinePoint {
timestamp: number;
blue: { gold: number; xp: number };
@@ -214,4 +214,52 @@ describe('RiotMatchService', () => {
levelUpType: 'NORMAL',
});
});
it('rejects non-numeric champion kill victim ids', async () => {
const payload = {
metadata: {
dataVersion: '2',
matchId: 'KR_8188913502',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [
{
timestamp: 60_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 30_000,
killerId: 1,
victimId: '2',
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
},
},
},
],
},
};
const riotClientService = {
get: jest.fn(
<T>(_path: string, _options: unknown, parser?: RiotResponseParser<T>) =>
Promise.resolve().then(() =>
parser ? parser(payload) : (payload as T),
),
),
} as unknown as RiotClientService;
const service = new RiotMatchService(riotClientService);
await expect(
service.getMatchTimeline('KR_8188913502', { region: 'asia' }),
).rejects.toThrow(
'timeline.info.frames[0].events[0].victimId must be a finite number when present.',
);
});
});
@@ -415,6 +415,10 @@ function parseTimelineEvent(
value.type,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
),
victimId: optionalNumber(
value.victimId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`,
),
};
}
+1
View File
@@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
skillSlot?: number;
teamId?: number;
towerType?: string;
victimId?: number;
}
export interface RiotMatchTimelineParticipantFrameDto
+39
View File
@@ -701,6 +701,24 @@ export interface ApiInternalMatchDetailResponse {
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
timelineEvents?: Array<{
timestamp: number;
side?: TeamSide;
type:
| 'dragon'
| 'elderDragon'
| 'baron'
| 'riftHerald'
| 'voidGrub'
| 'championKill'
| 'tower'
| 'inhibitor';
monsterSubType?: string;
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
towerType?: string;
}>;
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -716,6 +734,27 @@ export interface ApiInternalMatchDetailResponse {
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
participantId?: number;
checkpoints?: {
at10?: {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
};
at15?: {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
};
};
userId: string | null;
summonerName: string;
tagLine: string;
@@ -6,6 +6,14 @@ import {
} from "../lib/ddragon";
import { teamIndexLabel } from "../lib/league";
import { LANE_LABELS } from "../lib/riot-history";
import {
DEFAULT_LANE_CHECKPOINT,
pairLaneParticipants,
resolveCheckpointComparison,
type LaneCheckpointKey,
type LaneParticipantLike,
type NormalizedLanePosition,
} from "../lib/internal-game-matchups";
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
@@ -13,6 +21,7 @@ export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
type InternalGameTeam = InternalGameDetail["teams"][number];
type InternalGameParticipant = InternalGameTeam["participants"][number];
type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike;
type DdragonManifestData = DdragonManifest | null | undefined;
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
@@ -44,8 +53,6 @@ const STAT_PERK_LABELS: Record<number, string> = {
5011: "체력",
};
const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"];
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
@@ -56,6 +63,11 @@ function formatNumber(value: number) {
return new Intl.NumberFormat("ko-KR").format(value);
}
function formatSignedNumber(value: number) {
if (value === 0) return "0";
return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`;
}
function sideTone(side: TeamSide) {
return side === "blue"
? {
@@ -111,11 +123,6 @@ function runeStyleSelection(
return participant.perks.styles?.find((style) => style.styleId === styleId);
}
function laneSortValue(position: string) {
const index = LANE_SORT_ORDER.indexOf(position);
return index === -1 ? 99 : index;
}
function ChampionCell({
participant,
manifest,
@@ -648,12 +655,14 @@ function SkillBuildPanel({
function MatchupMetricRow({
label,
difference,
blueLead,
redLead,
blueText,
redText,
}: {
label: string;
difference?: string;
blueLead: boolean;
redLead: boolean;
blueText: string;
@@ -668,8 +677,13 @@ function MatchupMetricRow({
>
{blueText}
</span>
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
{label}
<span className="min-w-16 text-center text-[10px] font-bold uppercase tracking-wider text-base-content/30">
<span className="block">{label}</span>
{difference ? (
<span className="mt-0.5 block normal-case text-base-content/50">
{difference}
</span>
) : null}
</span>
<span
className={`tabular-nums ${
@@ -682,101 +696,172 @@ function MatchupMetricRow({
);
}
function LaneMatchupCard({
blue,
red,
detail,
function checkpointKda(kills: number, deaths: number, assists: number) {
return deaths === 0 ? kills + assists : (kills + assists) / deaths;
}
function LaneParticipantIdentity({
participant,
manifest,
align,
ambiguous,
}: {
blue: InternalGameParticipant;
red: InternalGameParticipant;
detail: ApiInternalMatchDetailResponse;
participant: CheckpointParticipant | null;
manifest: DdragonManifestData;
align: "left" | "right";
ambiguous: boolean;
}) {
const laneLabel =
LANE_LABELS[blue.teamPosition] ??
LANE_LABELS[red.teamPosition] ??
blue.teamPosition ??
"-";
if (!participant) {
return (
<div
className={`min-w-0 text-[11px] font-bold text-base-content/30 ${
align === "right" ? "text-right" : "text-left"
}`}
>
{ambiguous ? "포지션 중복" : "선수 없음"}
</div>
);
}
const metrics = [
{
key: "kda",
label: "KDA",
blueValue:
blue.deaths === 0
? blue.kills + blue.assists
: (blue.kills + blue.assists) / blue.deaths,
redValue:
red.deaths === 0
? red.kills + red.assists
: (red.kills + red.assists) / red.deaths,
blueText: `${blue.kills}/${blue.deaths}/${blue.assists}`,
redText: `${red.kills}/${red.deaths}/${red.assists}`,
},
{
key: "gold",
label: "골드",
blueValue: blue.gold,
redValue: red.gold,
blueText: formatNumber(blue.gold),
redText: formatNumber(red.gold),
},
{
key: "cs",
label: "CS",
blueValue: blue.cs,
redValue: red.cs,
blueText: `${blue.cs} (${blue.csPerMin}/m)`,
redText: `${red.cs} (${red.csPerMin}/m)`,
},
];
const championName = (participant: InternalGameParticipant) =>
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
const details = (
<div className={`min-w-0 ${align === "right" ? "text-right" : ""}`}>
<div className="truncate text-xs font-bold text-base-content">
{participant.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName}
</div>
</div>
);
return (
<div
className={`flex min-w-0 items-center gap-2 ${
align === "right" ? "justify-end" : ""
}`}
>
{align === "right" ? details : null}
<ChampionAvatar participant={participant} manifest={manifest} />
{align === "left" ? details : null}
</div>
);
}
function LaneMatchupCard({
position,
blue,
red,
ambiguousBlue,
ambiguousRed,
checkpointKey,
manifest,
}: {
position: NormalizedLanePosition;
blue: CheckpointParticipant | null;
red: CheckpointParticipant | null;
ambiguousBlue: boolean;
ambiguousRed: boolean;
checkpointKey: LaneCheckpointKey;
manifest: DdragonManifestData;
}) {
const laneLabel = LANE_LABELS[position] ?? position;
const comparison = resolveCheckpointComparison(blue, red, checkpointKey);
const metrics = comparison
? [
{
key: "gold",
label: "골드",
difference: `GD ${formatSignedNumber(comparison.goldDiff)}`,
blueValue: comparison.blue.gold,
redValue: comparison.red.gold,
blueText: formatNumber(comparison.blue.gold),
redText: formatNumber(comparison.red.gold),
},
{
key: "cs",
label: "CS",
difference: `CSD ${formatSignedNumber(comparison.csDiff)}`,
blueValue: comparison.blue.cs,
redValue: comparison.red.cs,
blueText: formatNumber(comparison.blue.cs),
redText: formatNumber(comparison.red.cs),
},
{
key: "xp",
label: "경험치",
difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`,
blueValue: comparison.blue.xp,
redValue: comparison.red.xp,
blueText: formatNumber(comparison.blue.xp),
redText: formatNumber(comparison.red.xp),
},
{
key: "kda",
label: "K / D / A",
blueValue: checkpointKda(
comparison.blue.kills,
comparison.blue.deaths,
comparison.blue.assists,
),
redValue: checkpointKda(
comparison.red.kills,
comparison.red.deaths,
comparison.red.assists,
),
blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`,
redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`,
},
]
: [];
return (
<div className="overflow-hidden border border-base-content/10 bg-base-100">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 border-b border-base-content/8 bg-base-content/[0.015] px-3 py-2">
<div className="flex min-w-0 items-center justify-end gap-2">
<div className="min-w-0 text-right">
<div className="truncate text-xs font-bold text-base-content">
{blue.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName(blue)}
</div>
</div>
<ChampionAvatar participant={blue} manifest={manifest} />
</div>
<LaneParticipantIdentity
participant={blue}
manifest={manifest}
align="right"
ambiguous={ambiguousBlue}
/>
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
{laneLabel}
</span>
<div className="flex min-w-0 items-center gap-2">
<ChampionAvatar participant={red} manifest={manifest} />
<div className="min-w-0">
<div className="truncate text-xs font-bold text-base-content">
{red.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName(red)}
</div>
<LaneParticipantIdentity
participant={red}
manifest={manifest}
align="left"
ambiguous={ambiguousRed}
/>
</div>
{comparison ? (
<>
<div className="divide-y divide-base-content/5">
{metrics.map((metric) => (
<MatchupMetricRow
key={`${position}-${checkpointKey}-${metric.key}`}
label={metric.label}
difference={metric.difference}
blueLead={metric.blueValue > metric.redValue}
redLead={metric.redValue > metric.blueValue}
blueText={metric.blueText}
redText={metric.redText}
/>
))}
</div>
<div className="border-t border-base-content/5 px-3 py-1.5 text-center text-[10px] font-bold text-base-content/30">
실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)}
</div>
</>
) : (
<div className="px-3 py-7 text-center text-xs font-bold text-base-content/35">
{ambiguousBlue || ambiguousRed
? "포지션이 중복되어 상대를 확정할 수 없습니다"
: "선택한 시점의 라인전 데이터가 없습니다"}
</div>
</div>
<div className="divide-y divide-base-content/5">
{metrics.map((metric) => (
<MatchupMetricRow
key={`${detail.match.matchId}-${blue.teamPosition}-${metric.key}`}
label={metric.label}
blueLead={metric.blueValue > metric.redValue}
redLead={metric.redValue > metric.blueValue}
blueText={metric.blueText}
redText={metric.redText}
/>
))}
</div>
)}
</div>
);
}
@@ -790,6 +875,8 @@ function LaneMatchupPanel({
detail: ApiInternalMatchDetailResponse;
manifest: DdragonManifestData;
}) {
const [checkpointKey, setCheckpointKey] =
useState<LaneCheckpointKey>(DEFAULT_LANE_CHECKPOINT);
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
@@ -801,40 +888,64 @@ function LaneMatchupPanel({
);
}
const blueSorted = [...blueTeam.participants].sort(
(left, right) =>
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
);
const redSorted = [...redTeam.participants].sort(
(left, right) =>
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
const matchups = pairLaneParticipants(
blueTeam.participants as CheckpointParticipant[],
redTeam.participants as CheckpointParticipant[],
);
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
const redTeamName = getTeamName(detail, redTeam.teamIndex);
return (
<section className="overflow-hidden border border-base-content/10 bg-base-100">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-base-content/8 px-4 py-3 text-xs font-bold">
<span className="truncate text-right text-blue-400">
{blueTeamName}
</span>
<span className="text-base-content/20">VS</span>
<span className="truncate text-red-400">{redTeamName}</span>
<div className="border-b border-base-content/8 px-4 py-3">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 text-xs font-bold">
<span className="truncate text-right text-blue-400">
{blueTeamName}
</span>
<span className="text-base-content/20">VS</span>
<span className="truncate text-red-400">{redTeamName}</span>
</div>
<div
className="mx-auto mt-3 flex w-fit border border-base-content/10"
role="group"
aria-label="라인전 비교 시점"
>
{(["at10", "at15"] as const).map((key) => (
<button
key={key}
type="button"
aria-pressed={checkpointKey === key}
onClick={() => setCheckpointKey(key)}
className={`border-r border-base-content/8 px-4 py-1.5 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
checkpointKey === key
? "bg-primary text-primary-content"
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
}`}
>
{key === "at10" ? "10분" : "15분"}
</button>
))}
</div>
</div>
<div className="grid gap-3 p-4 lg:grid-cols-2">
{blueSorted.map((blue, index) => {
const red = redSorted[index];
if (!red) return null;
return (
{matchups.length > 0 ? (
matchups.map((matchup) => (
<LaneMatchupCard
key={`matchup-${blue.teamPosition}-${blue.summonerName}`}
blue={blue}
red={red}
detail={detail}
key={`matchup-${matchup.position}`}
position={matchup.position}
blue={matchup.blue}
red={matchup.red}
ambiguousBlue={matchup.ambiguousBlue}
ambiguousRed={matchup.ambiguousRed}
checkpointKey={checkpointKey}
manifest={manifest}
/>
);
})}
))
) : (
<div className="py-10 text-center text-sm font-bold text-base-content/35 lg:col-span-2">
비교 가능한 포지션 정보가 없습니다
</div>
)}
</div>
</section>
);
+127
View File
@@ -0,0 +1,127 @@
export type LaneCheckpointKey = "at10" | "at15";
export const DEFAULT_LANE_CHECKPOINT: LaneCheckpointKey = "at15";
export type NormalizedLanePosition =
| "TOP"
| "JUNGLE"
| "MIDDLE"
| "BOTTOM"
| "UTILITY";
export interface LaneCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
export interface LaneParticipantLike {
teamPosition: string;
checkpoints?: Partial<Record<LaneCheckpointKey, LaneCheckpoint>>;
}
export interface LanePair<TParticipant extends LaneParticipantLike> {
position: NormalizedLanePosition;
blue: TParticipant | null;
red: TParticipant | null;
ambiguousBlue: boolean;
ambiguousRed: boolean;
}
export interface LaneCheckpointComparison {
blue: LaneCheckpoint;
red: LaneCheckpoint;
goldDiff: number;
csDiff: number;
xpDiff: number;
}
const LANE_ORDER: readonly NormalizedLanePosition[] = [
"TOP",
"JUNGLE",
"MIDDLE",
"BOTTOM",
"UTILITY",
];
const LANE_ALIASES: Readonly<Record<string, NormalizedLanePosition>> = {
TOP: "TOP",
JUNGLE: "JUNGLE",
JGL: "JUNGLE",
MIDDLE: "MIDDLE",
MID: "MIDDLE",
BOTTOM: "BOTTOM",
ADC: "BOTTOM",
UTILITY: "UTILITY",
SUPPORT: "UTILITY",
SUP: "UTILITY",
};
export function normalizeLanePosition(
value: string | undefined,
): NormalizedLanePosition | null {
if (!value) return null;
return LANE_ALIASES[value.toUpperCase()] ?? null;
}
export function pairLaneParticipants<TParticipant extends LaneParticipantLike>(
blueParticipants: readonly TParticipant[],
redParticipants: readonly TParticipant[],
): Array<LanePair<TParticipant>> {
const blueByPosition = groupByPosition(blueParticipants);
const redByPosition = groupByPosition(redParticipants);
return LANE_ORDER.flatMap((position) => {
const blue = blueByPosition.get(position) ?? [];
const red = redByPosition.get(position) ?? [];
if (blue.length === 0 && red.length === 0) return [];
return [
{
position,
blue: blue.length === 1 ? blue[0] : null,
red: red.length === 1 ? red[0] : null,
ambiguousBlue: blue.length > 1,
ambiguousRed: red.length > 1,
},
];
});
}
export function resolveCheckpointComparison<
TParticipant extends LaneParticipantLike,
>(
blueParticipant: TParticipant | null,
redParticipant: TParticipant | null,
checkpointKey: LaneCheckpointKey,
): LaneCheckpointComparison | null {
const blue = blueParticipant?.checkpoints?.[checkpointKey];
const red = redParticipant?.checkpoints?.[checkpointKey];
if (!blue || !red) return null;
return {
blue,
red,
goldDiff: blue.gold - red.gold,
csDiff: blue.cs - red.cs,
xpDiff: blue.xp - red.xp,
};
}
function groupByPosition<TParticipant extends LaneParticipantLike>(
participants: readonly TParticipant[],
) {
const grouped = new Map<NormalizedLanePosition, TParticipant[]>();
for (const participant of participants) {
const position = normalizeLanePosition(participant.teamPosition);
if (!position) continue;
const values = grouped.get(position) ?? [];
values.push(participant);
grouped.set(position, values);
}
return grouped;
}
+218
View File
@@ -0,0 +1,218 @@
export type InternalMatchTeamSide = "blue" | "red";
export type InternalMatchObjectiveType =
| "dragon"
| "elderDragon"
| "baron"
| "riftHerald"
| "voidGrub";
export type InternalMatchTimelineEventType =
| InternalMatchObjectiveType
| "championKill"
| "tower"
| "inhibitor";
export type TimelineEventCategory = "objective" | "kill" | "structure";
export type TimelineEventFilter = "all" | TimelineEventCategory;
export interface InternalMatchTimelineEvent {
timestamp: number;
side?: InternalMatchTeamSide;
type: InternalMatchTimelineEventType;
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
monsterSubType?: string;
towerType?: string;
}
export interface InternalMatchObjectiveEvent {
timestamp: number;
side: InternalMatchTeamSide;
type: InternalMatchObjectiveType;
monsterSubType?: string;
}
export interface NormalizedObjectiveEvent extends InternalMatchObjectiveEvent {
label: string;
markerLabel: string;
}
export interface NormalizedTimelineEvent extends InternalMatchTimelineEvent {
category: TimelineEventCategory;
label: string;
markerLabel: string;
}
const DRAGON_TYPE_LABELS: Readonly<Record<string, string>> = {
AIR_DRAGON: "바람",
EARTH_DRAGON: "대지",
WATER_DRAGON: "바다",
FIRE_DRAGON: "화염",
HEXTECH_DRAGON: "마법공학",
CHEMTECH_DRAGON: "화학공학",
ELDER_DRAGON: "장로",
};
const OBJECTIVE_LABELS: Readonly<
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
> = {
elderDragon: "장로 드래곤",
baron: "바론",
riftHerald: "협곡의 전령",
voidGrub: "공허 유충",
};
const OBJECTIVE_MARKER_LABELS: Readonly<
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
> = {
elderDragon: "장로",
baron: "바론",
riftHerald: "전령",
voidGrub: "유충",
};
export function dragonTypeLabel(
monsterSubType: string | undefined,
): string | null {
if (!monsterSubType) return null;
return DRAGON_TYPE_LABELS[monsterSubType] ?? null;
}
export function normalizeObjectiveEvents(
events: readonly InternalMatchObjectiveEvent[],
): NormalizedObjectiveEvent[] {
return events
.map((event) => {
if (event.type === "dragon") {
const dragonLabel = dragonTypeLabel(event.monsterSubType);
return {
...event,
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
markerLabel: dragonLabel ?? "용",
};
}
return {
...event,
label: OBJECTIVE_LABELS[event.type],
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
};
})
.sort((left, right) => left.timestamp - right.timestamp);
}
export function normalizeTimelineEvents(
events: readonly InternalMatchTimelineEvent[],
): NormalizedTimelineEvent[] {
return events
.map((event): NormalizedTimelineEvent => {
if (event.type === "championKill") {
return {
...event,
category: "kill",
label: "챔피언 처치",
markerLabel: "킬",
};
}
if (event.type === "tower") {
return {
...event,
category: "structure",
label: "포탑 파괴",
markerLabel: "포탑",
};
}
if (event.type === "inhibitor") {
return {
...event,
category: "structure",
label: "억제기 파괴",
markerLabel: "억제기",
};
}
if (event.type === "dragon") {
const dragonLabel = dragonTypeLabel(event.monsterSubType);
return {
...event,
category: "objective",
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
markerLabel: dragonLabel ?? "용",
};
}
return {
...event,
category: "objective",
label: OBJECTIVE_LABELS[event.type],
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
};
})
.sort((left, right) => left.timestamp - right.timestamp);
}
export function selectTimelineEventSource<
TTimeline extends InternalMatchTimelineEvent,
TObjective extends InternalMatchObjectiveEvent,
>(
timelineEvents: readonly TTimeline[] | undefined,
objectiveEvents: readonly TObjective[],
): readonly (TTimeline | TObjective)[] {
return timelineEvents && timelineEvents.length > 0
? timelineEvents
: objectiveEvents;
}
export function filterTimelineEvents<TEvent extends NormalizedTimelineEvent>(
events: readonly TEvent[],
filter: TimelineEventFilter,
): TEvent[] {
return filter === "all"
? [...events]
: events.filter((event) => event.category === filter);
}
export function summarizeDragonTypes(
events: readonly NormalizedObjectiveEvent[],
side: InternalMatchTeamSide,
): Array<{ label: string; count: number }> {
const counts = new Map<string, number>();
for (const event of events) {
if (event.side !== side || event.type !== "dragon") continue;
const label = dragonTypeLabel(event.monsterSubType);
if (!label) continue;
counts.set(label, (counts.get(label) ?? 0) + 1);
}
return [...counts.entries()].map(([label, count]) => ({ label, count }));
}
export function projectObjectiveMarkers<
TEvent extends NormalizedObjectiveEvent,
>(
events: readonly TEvent[],
points: readonly { timestamp: number; value: number }[],
): Array<TEvent & { value: number }> {
return projectTimelineEventMarkers(events, points);
}
export function projectTimelineEventMarkers<TEvent extends { timestamp: number }>(
events: readonly TEvent[],
points: readonly { timestamp: number; value: number }[],
): Array<TEvent & { value: number }> {
if (points.length === 0) return [];
const orderedPoints = [...points].sort(
(left, right) => left.timestamp - right.timestamp,
);
return events.map((event) => {
let selected = orderedPoints[0];
for (const point of orderedPoints) {
if (point.timestamp > event.timestamp) break;
selected = point;
}
return { ...event, value: selected.value };
});
}
+424 -10
View File
@@ -5,6 +5,7 @@ import {
AreaChart,
CartesianGrid,
Line,
ReferenceDot,
ReferenceLine,
ResponsiveContainer,
Tooltip,
@@ -28,6 +29,16 @@ import {
internalMatchGamePath,
} from "../lib/internal-match-routes";
import { LANE_LABELS } from "../lib/riot-history";
import {
filterTimelineEvents,
normalizeObjectiveEvents,
normalizeTimelineEvents,
projectTimelineEventMarkers,
selectTimelineEventSource,
summarizeDragonTypes,
type NormalizedTimelineEvent,
type TimelineEventFilter,
} from "../lib/internal-match-timeline";
import {
InternalGameAnalysisPanel,
InternalGameDetailTabBar,
@@ -58,6 +69,16 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
{ id: "xp", label: "경험치" },
];
const TIMELINE_EVENT_FILTERS: Array<{
id: TimelineEventFilter;
label: string;
}> = [
{ id: "all", label: "전체" },
{ id: "objective", label: "오브젝트" },
{ id: "kill", label: "킬" },
{ id: "structure", label: "구조물" },
];
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
@@ -142,6 +163,16 @@ function formatPercent(value: number) {
return `${value}%`;
}
function formatDragonTypeSummary(
values: Array<{ label: string; count: number }>,
total: number,
) {
if (values.length === 0) return total > 0 ? "유형 정보 없음" : "-";
return values
.map(({ label, count }) => (count > 1 ? `${label}×${count}` : label))
.join(" · ");
}
function barWidth(value: number, max: number) {
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
}
@@ -411,13 +442,13 @@ function PlayerRow({
{participant.assists}
</div>
<div className="text-xs font-bold tabular-nums text-base-content/40">
{formatKda(
KDA {formatKda(
participant.kills,
participant.deaths,
participant.assists,
)}
<span className="ml-1 text-base-content/35">
({participant.killParticipation}%)
· KP {participant.killParticipation}%
</span>
</div>
</td>
@@ -451,6 +482,12 @@ function PlayerRow({
<span className="block text-base-content/35">
{participant.csPerMin}/m
</span>
<span className="mt-1 block font-bold text-base-content/55">
{formatCompactNumber(participant.gold)}
<span className="ml-1 font-normal text-base-content/30">
{formatNumber(participant.gpm)} GPM
</span>
</span>
</td>
<td className="px-3 py-2.5">
<ItemStrip participant={participant} manifest={manifest} />
@@ -486,13 +523,13 @@ function PlayerCard({
{participant.assists}
</div>
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
{formatKda(
KDA {formatKda(
participant.kills,
participant.deaths,
participant.assists,
)}
<span className="ml-1 text-base-content/35">
({participant.killParticipation}%)
· KP {participant.killParticipation}%
</span>
</div>
</div>
@@ -527,13 +564,19 @@ function PlayerCard({
</div>
<div className="border border-base-content/8 px-2 py-1.5">
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
CS
CS · 경제
</div>
<div className="mt-0.5 font-black text-base-content/70">
{participant.cs}
<span className="ml-1 font-bold text-base-content/35">
{participant.csPerMin}/m
</span>
<span className="mt-1 block text-base-content/60">
{formatCompactNumber(participant.gold)}
<span className="ml-1 font-bold text-base-content/35">
{formatNumber(participant.gpm)} GPM
</span>
</span>
</div>
</div>
<div className="border border-base-content/8 px-2 py-1.5">
@@ -701,11 +744,125 @@ function PostgameBreakdown({
);
})}
</div>
<ObjectiveComparisonStrip selectedGame={selectedGame} />
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
</section>
);
}
function ObjectiveComparisonStrip({
selectedGame,
}: {
selectedGame: MatchGameDetail;
}) {
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
if (!blueTeam || !redTeam) return null;
const events = normalizeObjectiveEvents(selectedGame.objectiveEvents ?? []);
const blueDragonTypes = formatDragonTypeSummary(
summarizeDragonTypes(events, "blue"),
blueTeam.objectives.dragon,
);
const redDragonTypes = formatDragonTypeSummary(
summarizeDragonTypes(events, "red"),
redTeam.objectives.dragon,
);
const objectives = [
{
key: "tower",
label: "포탑",
blue: blueTeam.objectives.tower,
red: redTeam.objectives.tower,
},
{
key: "dragon",
label: "드래곤",
blue: blueTeam.objectives.dragon,
red: redTeam.objectives.dragon,
blueDetail: blueDragonTypes,
redDetail: redDragonTypes,
},
{
key: "inhibitor",
label: "억제기",
blue: blueTeam.objectives.inhibitor,
red: redTeam.objectives.inhibitor,
},
{
key: "baron",
label: "바론",
blue: blueTeam.objectives.baron,
red: redTeam.objectives.baron,
},
{
key: "riftHerald",
label: "전령",
blue: blueTeam.objectives.riftHerald,
red: redTeam.objectives.riftHerald,
},
{
key: "voidGrub",
label: "공허 유충",
blue: blueTeam.objectives.voidGrub,
red: redTeam.objectives.voidGrub,
},
{
key: "elderDragon",
label: "장로",
blue: blueTeam.objectives.elderDragon,
red: redTeam.objectives.elderDragon,
},
];
return (
<div className="border-t border-base-content/8 bg-base-content/[0.01]">
<h3 className="sr-only">오브젝트 비교</h3>
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7">
{objectives.map((objective) => (
<div
key={objective.key}
className="border-b border-r border-base-content/8 px-3 py-2.5 last:border-r-0 lg:border-b-0"
aria-label={`${objective.label}: 블루 ${objective.blue}, 레드 ${objective.red}`}
>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 text-xs tabular-nums">
<span
className={`text-right font-black ${
objective.blue > objective.red
? "text-blue-400"
: "text-base-content/50"
}`}
>
{objective.blue}
</span>
<span className="text-[10px] font-bold text-base-content/35">
{objective.label}
</span>
<span
className={`font-black ${
objective.red > objective.blue
? "text-red-400"
: "text-base-content/50"
}`}
>
{objective.red}
</span>
</div>
{objective.key === "dragon" ? (
<div className="mt-1 grid grid-cols-2 gap-2 text-[9px] font-bold leading-tight">
<span className="text-right text-blue-400/70">
{objective.blueDetail}
</span>
<span className="text-red-400/70">{objective.redDetail}</span>
</div>
) : null}
</div>
))}
</div>
</div>
);
}
function GoldComparisonStrip({
selectedGame,
detail,
@@ -848,14 +1005,74 @@ function TimelineTooltip({
);
}
function timelineEventKey(event: NormalizedTimelineEvent, index: number) {
return [
event.timestamp,
event.side ?? "unknown",
event.type,
event.killerParticipantId ?? "none",
event.victimParticipantId ?? "none",
index,
].join(":");
}
function timelineParticipantLabel(
participant: MatchGameParticipant | undefined,
manifest: ReturnType<typeof useDdragonManifest>["data"],
) {
if (!participant) return null;
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
return `${participant.summonerName} (${championName})`;
}
function timelineEventActors(
event: NormalizedTimelineEvent,
participantById: ReadonlyMap<number, MatchGameParticipant>,
manifest: ReturnType<typeof useDdragonManifest>["data"],
) {
const killer = timelineParticipantLabel(
event.killerParticipantId === undefined
? undefined
: participantById.get(event.killerParticipantId),
manifest,
);
const victim = timelineParticipantLabel(
event.victimParticipantId === undefined
? undefined
: participantById.get(event.victimParticipantId),
manifest,
);
const assistants = (event.assistingParticipantIds ?? [])
.map((participantId) =>
timelineParticipantLabel(participantById.get(participantId), manifest),
)
.filter((label): label is string => Boolean(label));
const assistLabel =
assistants.length > 0 ? ` · 도움 ${assistants.join(", ")}` : "";
if (event.type === "championKill") {
if (killer && victim) return `${killer} → ${victim}${assistLabel}`;
if (killer) return `${killer} 처치${assistLabel}`;
if (victim) return `${victim} 사망`;
}
if (killer) return `${killer} 기여${assistLabel}`;
return null;
}
function TimelineGraph({
selectedGame,
detail,
manifest,
}: {
selectedGame: MatchGameDetail;
detail: ApiInternalMatchDetailResponse;
manifest: ReturnType<typeof useDdragonManifest>["data"];
}) {
const [metric, setMetric] = useState<TimelineMetric>("gold");
const [eventFilter, setEventFilter] = useState<TimelineEventFilter>("all");
const [selectedEventKey, setSelectedEventKey] = useState<string | null>(null);
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
const blueTeamName = blueTeam
@@ -883,6 +1100,41 @@ function TimelineGraph({
...chartData.map((point) => Math.abs(point.value)),
);
const finalPoint = chartData[chartData.length - 1];
const timelineEvents = normalizeTimelineEvents(
selectTimelineEventSource(
selectedGame.timelineEvents,
selectedGame.objectiveEvents ?? [],
),
);
const visibleEvents = filterTimelineEvents(timelineEvents, eventFilter);
const visibleEventEntries = visibleEvents.map((event) => {
const index = timelineEvents.indexOf(event);
return {
event,
key: timelineEventKey(event, index),
};
});
const selectedEvent = visibleEventEntries.find(
(entry) => entry.key === selectedEventKey,
);
const selectedTimestamp = selectedEvent?.event.timestamp ?? null;
const timelineMarkers = projectTimelineEventMarkers(
visibleEventEntries.map(({ event, key }) => ({ ...event, eventKey: key })),
chartData,
);
const participantById = new Map<number, MatchGameParticipant>();
for (const team of selectedGame.teams) {
for (const participant of team.participants) {
if (participant.participantId !== undefined) {
participantById.set(participant.participantId, participant);
}
}
}
const chartMaxTimestamp = Math.max(
selectedGame.gameDuration,
finalPoint?.timestamp ?? 0,
timelineEvents[timelineEvents.length - 1]?.timestamp ?? 0,
);
const finalLeader =
finalPoint?.leaderSide === "blue"
? blueTeamName
@@ -901,11 +1153,16 @@ function TimelineGraph({
: "타임라인 대기"}
</div>
</div>
<div className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto">
<div
className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto"
role="group"
aria-label="경기 흐름 지표"
>
{TIMELINE_METRICS.map((item) => (
<button
key={item.id}
type="button"
aria-pressed={metric === item.id}
onClick={() => setMetric(item.id)}
className={`min-w-24 flex-1 border-r border-base-content/8 px-4 py-2 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
metric === item.id
@@ -921,7 +1178,11 @@ function TimelineGraph({
{chartData.length > 0 ? (
<div className="px-2 py-4 sm:px-4">
<div className="h-[260px] min-w-0 w-full">
<ResponsiveContainer width="100%" height="100%">
<ResponsiveContainer
width="100%"
height="100%"
initialDimension={{ width: 800, height: 260 }}
>
<AreaChart
data={chartData}
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
@@ -933,6 +1194,8 @@ function TimelineGraph({
/>
<XAxis
dataKey="timestamp"
type="number"
domain={[0, chartMaxTimestamp]}
minTickGap={28}
tickFormatter={(value) =>
`${Math.round(Number(value) / 60)}분`
@@ -965,6 +1228,14 @@ function TimelineGraph({
stroke="currentColor"
strokeOpacity={0.25}
/>
{selectedTimestamp !== null ? (
<ReferenceLine
x={selectedTimestamp}
stroke="currentColor"
strokeDasharray="3 3"
strokeOpacity={0.35}
/>
) : null}
<Area
type="monotone"
dataKey="positive"
@@ -994,6 +1265,44 @@ function TimelineGraph({
}}
isAnimationActive={false}
/>
{timelineMarkers.map((event) => {
const selected = event.eventKey === selectedEventKey;
const markerRadius =
event.category === "objective"
? 4
: event.category === "structure"
? 3.5
: 2.5;
return (
<ReferenceDot
key={event.eventKey}
x={event.timestamp}
y={event.value}
r={selected ? 5.5 : markerRadius}
fill={
event.side === "blue"
? "#3b82f6"
: event.side === "red"
? "#ef4444"
: "currentColor"
}
stroke="currentColor"
strokeWidth={selected ? 2 : 1}
ifOverflow="extendDomain"
label={
selected
? {
value: event.markerLabel,
position: "top",
fontSize: 10,
fontWeight: 800,
fill: "currentColor",
}
: undefined
}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
</div>
@@ -1008,6 +1317,106 @@ function TimelineGraph({
타임라인 데이터가 아직 없습니다
</div>
)}
{timelineEvents.length > 0 ? (
<div className="border-t border-base-content/8 px-4 py-3">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 className="text-xs font-black text-base-content">주요 사건</h3>
<p className="text-[11px] font-bold text-base-content/30">
항목을 선택하면 그래프의 해당 시점을 강조합니다
</p>
</div>
<div
className="mt-3 flex w-full overflow-x-auto border border-base-content/10 bg-base-content/[0.02] sm:w-fit"
role="group"
aria-label="사건 유형 필터"
>
{TIMELINE_EVENT_FILTERS.map((filter) => (
<button
key={filter.id}
type="button"
aria-pressed={eventFilter === filter.id}
onClick={() => setEventFilter(filter.id)}
className={`min-w-20 flex-1 border-r border-base-content/8 px-3 py-2 text-[11px] font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
eventFilter === filter.id
? "bg-primary text-primary-content"
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
}`}
>
{filter.label}
</button>
))}
</div>
<ul
className="m-0 mt-3 grid max-h-64 list-none gap-1.5 overflow-y-auto p-0 sm:grid-cols-2 lg:grid-cols-3"
aria-label="시간순 주요 사건"
>
{visibleEventEntries.map(({ event, key }) => {
const selected = key === selectedEventKey;
const teamName =
event.side === "blue"
? blueTeamName
: event.side === "red"
? redTeamName
: null;
const actorLabel = timelineEventActors(
event,
participantById,
manifest,
);
return (
<li key={key} className="min-w-0">
<button
type="button"
aria-pressed={selected}
onClick={() => setSelectedEventKey(selected ? null : key)}
className={`grid h-full w-full grid-cols-[3.25rem_3.25rem_minmax(0,1fr)] items-start gap-2 border px-2.5 py-2 text-left text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
selected
? "border-primary bg-primary/8"
: "border-base-content/8 hover:bg-base-content/[0.03]"
}`}
>
<span className="font-mono font-black tabular-nums text-base-content/55">
{formatDuration(event.timestamp)}
</span>
<span
className={`text-[10px] font-black uppercase tracking-wider ${
event.side === "blue"
? "text-blue-400"
: event.side === "red"
? "text-red-400"
: "text-base-content/35"
}`}
>
{event.side ? sideLabel(event.side) : "-"}
</span>
<span className="min-w-0">
<span className="block truncate font-bold text-base-content/75">
{teamName ? (
<span className="sr-only">{teamName} </span>
) : null}
{event.label}
</span>
{actorLabel ? (
<span
className="mt-0.5 block truncate text-[10px] font-bold text-base-content/35"
title={actorLabel}
>
{actorLabel}
</span>
) : null}
</span>
</button>
</li>
);
})}
</ul>
{visibleEventEntries.length === 0 ? (
<p className="py-6 text-center text-xs font-bold text-base-content/35">
이 유형의 사건이 없습니다
</p>
) : null}
</div>
) : null}
</section>
);
}
@@ -1045,7 +1454,7 @@ function TeamTable({
<th className="w-[120px] px-3 py-2.5 text-center">가한 피해량</th>
<th className="w-[120px] px-3 py-2.5 text-center">받은 피해량</th>
<th className="w-[80px] px-3 py-2.5 text-center">시야</th>
<th className="w-[76px] px-3 py-2.5 text-center">CS</th>
<th className="w-[96px] px-3 py-2.5 text-center">CS · 경제</th>
<th className="w-[260px] px-3 py-2.5">아이템</th>
</tr>
</thead>
@@ -1306,6 +1715,13 @@ export default function MatchGameDetailPage() {
manifest={ddragon}
/>
<TimelineGraph
key={selectedGame.riotMatchId}
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
/>
<div className="mt-5 space-y-4">
<InternalGameDetailTabBar
activeTab={activeTab}
@@ -1325,8 +1741,6 @@ export default function MatchGameDetailPage() {
}
/>
</div>
<TimelineGraph selectedGame={selectedGame} detail={detail} />
</main>
);
}
@@ -0,0 +1,134 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
DEFAULT_LANE_CHECKPOINT,
pairLaneParticipants,
resolveCheckpointComparison,
} from "../src/lib/internal-game-matchups.ts";
function participant(
name: string,
side: "blue" | "red",
teamPosition: string,
gold: number,
cs: number,
xp: number,
) {
return {
name,
side,
teamPosition,
checkpoints: {
at15: {
timestamp: 900,
gold,
cs,
xp,
kills: side === "blue" ? 2 : 1,
deaths: side === "blue" ? 1 : 2,
assists: 3,
},
},
};
}
test("pairLaneParticipants matches shuffled players by normalized team position", () => {
const blue = [
participant("Blue ADC", "blue", "BOTTOM", 6_000, 120, 7_000),
participant("Blue Top", "blue", "TOP", 5_500, 110, 6_800),
participant("Blue Mid", "blue", "MID", 6_200, 115, 7_100),
];
const red = [
participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900),
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
participant("Red ADC", "red", "ADC", 5_800, 116, 6_850),
];
const pairs = pairLaneParticipants(blue, red);
assert.deepEqual(
pairs.map((pair) => [pair.position, pair.blue?.name, pair.red?.name]),
[
["TOP", "Blue Top", "Red Top"],
["MIDDLE", "Blue Mid", "Red Mid"],
["BOTTOM", "Blue ADC", "Red ADC"],
],
);
});
test("pairLaneParticipants leaves a duplicated role ambiguous instead of pairing by index", () => {
const blue = [
participant("Blue Top A", "blue", "TOP", 5_500, 110, 6_800),
participant("Blue Top B", "blue", "TOP", 5_000, 100, 6_200),
];
const red = [
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
];
assert.deepEqual(pairLaneParticipants(blue, red), [
{
position: "TOP",
blue: null,
red: red[0],
ambiguousBlue: true,
ambiguousRed: false,
},
]);
});
test("resolveCheckpointComparison calculates blue-side GD, CSD, and XPD", () => {
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
const comparison = resolveCheckpointComparison(blue, red, "at15");
assert.deepEqual(comparison, {
blue: blue.checkpoints.at15,
red: red.checkpoints.at15,
goldDiff: 300,
csDiff: 6,
xpDiff: 200,
});
});
test("resolveCheckpointComparison returns null when either checkpoint is unavailable", () => {
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
assert.equal(resolveCheckpointComparison(blue, red, "at10"), null);
assert.equal(resolveCheckpointComparison(blue, null, "at15"), null);
});
test("the lane panel defaults to 15 minutes and supports an available 10-minute comparison", () => {
assert.equal(DEFAULT_LANE_CHECKPOINT, "at15");
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
blue.checkpoints.at10 = {
timestamp: 590,
gold: 4_000,
cs: 75,
xp: 4_600,
kills: 1,
deaths: 0,
assists: 2,
};
red.checkpoints.at10 = {
timestamp: 590,
gold: 3_700,
cs: 69,
xp: 4_450,
kills: 0,
deaths: 1,
assists: 1,
};
assert.deepEqual(resolveCheckpointComparison(blue, red, "at10"), {
blue: blue.checkpoints.at10,
red: red.checkpoints.at10,
goldDiff: 300,
csDiff: 6,
xpDiff: 150,
});
});
@@ -0,0 +1,228 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
dragonTypeLabel,
filterTimelineEvents,
normalizeObjectiveEvents,
normalizeTimelineEvents,
projectObjectiveMarkers,
selectTimelineEventSource,
summarizeDragonTypes,
} from "../src/lib/internal-match-timeline.ts";
test("dragonTypeLabel maps Riot dragon subtypes to Korean labels", () => {
assert.deepEqual(
[
"AIR_DRAGON",
"EARTH_DRAGON",
"WATER_DRAGON",
"FIRE_DRAGON",
"HEXTECH_DRAGON",
"CHEMTECH_DRAGON",
"ELDER_DRAGON",
].map(dragonTypeLabel),
["바람", "대지", "바다", "화염", "마법공학", "화학공학", "장로"],
);
assert.equal(dragonTypeLabel("UNKNOWN_DRAGON"), null);
assert.equal(dragonTypeLabel(undefined), null);
});
test("normalizeObjectiveEvents sorts events and adds conservative Korean labels", () => {
const events = normalizeObjectiveEvents([
{ timestamp: 1_443, side: "blue", type: "baron" },
{
timestamp: 339,
side: "blue",
type: "dragon",
monsterSubType: "EARTH_DRAGON",
},
{ timestamp: 963, side: "red", type: "riftHerald" },
{
timestamp: 1_356,
side: "red",
type: "dragon",
monsterSubType: "UNKNOWN_DRAGON",
},
{ timestamp: 530, side: "blue", type: "voidGrub" },
{ timestamp: 1_600, side: "red", type: "elderDragon" },
]);
assert.deepEqual(
events.map(({ timestamp, label, markerLabel }) => ({
timestamp,
label,
markerLabel,
})),
[
{ timestamp: 339, label: "대지 드래곤", markerLabel: "대지" },
{ timestamp: 530, label: "공허 유충", markerLabel: "유충" },
{ timestamp: 963, label: "협곡의 전령", markerLabel: "전령" },
{ timestamp: 1_356, label: "드래곤", markerLabel: "용" },
{ timestamp: 1_443, label: "바론", markerLabel: "바론" },
{ timestamp: 1_600, label: "장로 드래곤", markerLabel: "장로" },
],
);
});
test("summarizeDragonTypes groups repeated dragon types per side in event order", () => {
const events = normalizeObjectiveEvents([
{
timestamp: 300,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{
timestamp: 600,
side: "red",
type: "dragon",
monsterSubType: "WATER_DRAGON",
},
{
timestamp: 900,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{
timestamp: 1_200,
side: "blue",
type: "dragon",
monsterSubType: "HEXTECH_DRAGON",
},
{
timestamp: 1_500,
side: "red",
type: "dragon",
monsterSubType: "UNKNOWN_DRAGON",
},
]);
assert.deepEqual(summarizeDragonTypes(events, "blue"), [
{ label: "화염", count: 2 },
{ label: "마법공학", count: 1 },
]);
assert.deepEqual(summarizeDragonTypes(events, "red"), [
{ label: "바다", count: 1 },
]);
});
test("projectObjectiveMarkers anchors events to the latest available chart value", () => {
const events = normalizeObjectiveEvents([
{ timestamp: 10, side: "blue", type: "voidGrub" },
{ timestamp: 90, side: "red", type: "riftHerald" },
{ timestamp: 180, side: "blue", type: "baron" },
]);
assert.deepEqual(
projectObjectiveMarkers(events, [
{ timestamp: 0, value: 0 },
{ timestamp: 60, value: 100 },
{ timestamp: 120, value: 80 },
]).map(({ timestamp, value }) => ({ timestamp, value })),
[
{ timestamp: 10, value: 0 },
{ timestamp: 90, value: 100 },
{ timestamp: 180, value: 80 },
],
);
});
test("normalizeTimelineEvents labels and sorts objectives, kills, and structures", () => {
const events = normalizeTimelineEvents([
{
timestamp: 700,
side: "blue",
type: "tower",
killerParticipantId: 1,
towerType: "OUTER_TURRET",
},
{
timestamp: 500,
side: "red",
type: "championKill",
killerParticipantId: 6,
victimParticipantId: 1,
assistingParticipantIds: [7, 8],
},
{
timestamp: 300,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{ timestamp: 800, side: "red", type: "inhibitor" },
]);
assert.deepEqual(
events.map(({ timestamp, category, label, markerLabel }) => ({
timestamp,
category,
label,
markerLabel,
})),
[
{
timestamp: 300,
category: "objective",
label: "화염 드래곤",
markerLabel: "화염",
},
{
timestamp: 500,
category: "kill",
label: "챔피언 처치",
markerLabel: "킬",
},
{
timestamp: 700,
category: "structure",
label: "포탑 파괴",
markerLabel: "포탑",
},
{
timestamp: 800,
category: "structure",
label: "억제기 파괴",
markerLabel: "억제기",
},
],
);
assert.equal(events[1].killerParticipantId, 6);
assert.equal(events[1].victimParticipantId, 1);
});
test("selectTimelineEventSource falls back to objective events during rolling updates", () => {
const objectives = [
{ timestamp: 300, side: "blue" as const, type: "voidGrub" as const },
];
const timeline = [
{ timestamp: 400, side: "red" as const, type: "championKill" as const },
];
assert.equal(selectTimelineEventSource(timeline, objectives), timeline);
assert.equal(selectTimelineEventSource([], objectives), objectives);
assert.equal(selectTimelineEventSource(undefined, objectives), objectives);
});
test("filterTimelineEvents filters event categories without changing order", () => {
const events = normalizeTimelineEvents([
{ timestamp: 300, side: "blue", type: "dragon" },
{ timestamp: 500, side: "red", type: "championKill" },
{ timestamp: 700, side: "blue", type: "tower" },
]);
assert.deepEqual(
filterTimelineEvents(events, "all").map((event) => event.timestamp),
[300, 500, 700],
);
assert.deepEqual(
filterTimelineEvents(events, "kill").map((event) => event.timestamp),
[500],
);
assert.deepEqual(
filterTimelineEvents(events, "structure").map((event) => event.timestamp),
[700],
);
});