feat: enrich internal match game analysis
This commit is contained in:
1 parent
9f698a8fec
commit
aa675199af
22 files changed
+3123
-241
No files matched your search
@@ -26,6 +26,8 @@ website/LICENSE
|
|||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
!AGENTS.md
|
!AGENTS.md
|
||||||
|
!docs/specs/internal-match-game-analysis.md
|
||||||
|
!docs/plans/internal-match-game-analysis-p0-p1.md
|
||||||
!agents/**/*.md
|
!agents/**/*.md
|
||||||
!skills/**/*.md
|
!skills/**/*.md
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('CommunityStatsService', () => {
|
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 communityId = new mongoose.Types.ObjectId();
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const match: InternalMatchCardView = {
|
const match: InternalMatchCardView = {
|
||||||
@@ -97,6 +97,20 @@ describe('CommunityStatsService', () => {
|
|||||||
seriesResults: [],
|
seriesResults: [],
|
||||||
};
|
};
|
||||||
const participant = record(matchId);
|
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 = {
|
const gameDetail: InternalGameDetail = {
|
||||||
gameNumber: 1,
|
gameNumber: 1,
|
||||||
riotMatchId: 'KR_1',
|
riotMatchId: 'KR_1',
|
||||||
@@ -125,38 +139,81 @@ describe('CommunityStatsService', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const staleCache = {
|
Object.assign(gameDetail, {
|
||||||
match,
|
timelineEvents: [
|
||||||
games: [
|
|
||||||
{
|
{
|
||||||
gameNumber: 1,
|
timestamp: 300,
|
||||||
riotMatchId: 'KR_1',
|
side: 'blue',
|
||||||
gameCreation: 1_000,
|
type: 'championKill',
|
||||||
gameDuration: 1_800,
|
killerParticipantId: 1,
|
||||||
teams: [
|
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,
|
summonerName: 'Cached Player',
|
||||||
side: 'blue',
|
tagLine: 'KR1',
|
||||||
win: true,
|
itemBuild: [],
|
||||||
objectives: { tower: 1, dragon: 0, baron: 0 },
|
skillBuild: [],
|
||||||
participants: [
|
|
||||||
{
|
|
||||||
summonerName: 'Player',
|
|
||||||
perks: {
|
|
||||||
primaryStyle: 8000,
|
|
||||||
subStyle: 8400,
|
|
||||||
keystone: 8010,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
};
|
||||||
|
const missingTimelineEventsCache = {
|
||||||
|
match,
|
||||||
|
games: [otherwiseCompleteCachedGame],
|
||||||
} as unknown as InternalMatchDetailResponse;
|
} 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 = {
|
const cacheService = {
|
||||||
get: jest.fn().mockResolvedValue(staleCache),
|
get: jest
|
||||||
setDetail: jest.fn().mockResolvedValue(undefined),
|
.fn()
|
||||||
|
.mockResolvedValueOnce(missingTimelineEventsCache)
|
||||||
|
.mockResolvedValueOnce(invalidCheckpointCache),
|
||||||
|
setDetail,
|
||||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
const matchStatsService = {
|
const matchStatsService = {
|
||||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
@@ -180,22 +237,245 @@ describe('CommunityStatsService', () => {
|
|||||||
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
|
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(missingEventsResponse.games[0].timeline).toHaveLength(1);
|
||||||
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength(
|
expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
|
||||||
1,
|
expect(invalidCheckpointResponse.games[0]).toMatchObject({
|
||||||
);
|
timelineEvents: [
|
||||||
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({
|
{
|
||||||
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
|
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(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
|
||||||
expect(cacheService.setDetail).toHaveBeenCalledWith(
|
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||||
expect.stringContaining(':r3:'),
|
expect(setDetail).toHaveBeenNthCalledWith(
|
||||||
response,
|
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 () => {
|
it('includes internal match route fields in user internal history matches', async () => {
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
const matchId = 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_LIST_LIMIT = 50;
|
||||||
const MAX_MATCH_SCAN = 300;
|
const MAX_MATCH_SCAN = 300;
|
||||||
const MIN_HIGHLIGHT_GAMES = 5;
|
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 {
|
interface CommunityStatsContext {
|
||||||
community: CommunityDocument;
|
community: CommunityDocument;
|
||||||
@@ -59,6 +60,10 @@ interface BaseDataset {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommunityStatsService {
|
export class CommunityStatsService {
|
||||||
private readonly logger = new Logger(CommunityStatsService.name);
|
private readonly logger = new Logger(CommunityStatsService.name);
|
||||||
|
private readonly matchDetailInFlight = new Map<
|
||||||
|
string,
|
||||||
|
Promise<InternalMatchDetailResponse>
|
||||||
|
>();
|
||||||
private readonly userInternalHistoryInFlight = new Map<
|
private readonly userInternalHistoryInFlight = new Map<
|
||||||
string,
|
string,
|
||||||
Promise<UserInternalHistoryResponse>
|
Promise<UserInternalHistoryResponse>
|
||||||
@@ -219,6 +224,27 @@ export class CommunityStatsService {
|
|||||||
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||||
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
|
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, {
|
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||||
seasonId: 'all',
|
seasonId: 'all',
|
||||||
});
|
});
|
||||||
@@ -246,6 +272,7 @@ export class CommunityStatsService {
|
|||||||
gameVersion: game.gameVersion,
|
gameVersion: game.gameVersion,
|
||||||
timeline: game.timeline ?? [],
|
timeline: game.timeline ?? [],
|
||||||
objectiveEvents: game.objectiveEvents ?? [],
|
objectiveEvents: game.objectiveEvents ?? [],
|
||||||
|
timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [],
|
||||||
teams: game.teams.map((team) => ({
|
teams: game.teams.map((team) => ({
|
||||||
teamIndex: team.teamIndex,
|
teamIndex: team.teamIndex,
|
||||||
side: team.side,
|
side: team.side,
|
||||||
@@ -253,6 +280,8 @@ export class CommunityStatsService {
|
|||||||
objectives: team.objectives,
|
objectives: team.objectives,
|
||||||
bans: team.bans ?? [],
|
bans: team.bans ?? [],
|
||||||
participants: team.participants.map((record) => ({
|
participants: team.participants.map((record) => ({
|
||||||
|
participantId: record.participantId,
|
||||||
|
checkpoints: record.checkpoints,
|
||||||
userId: record.userId,
|
userId: record.userId,
|
||||||
summonerName: record.summonerName,
|
summonerName: record.summonerName,
|
||||||
tagLine: record.tagLine,
|
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;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse(
|
|||||||
(game) =>
|
(game) =>
|
||||||
Array.isArray(game.timeline) &&
|
Array.isArray(game.timeline) &&
|
||||||
Array.isArray(game.objectiveEvents) &&
|
Array.isArray(game.objectiveEvents) &&
|
||||||
|
Array.isArray(game.timelineEvents) &&
|
||||||
game.teams.every(
|
game.teams.every(
|
||||||
(team) =>
|
(team) =>
|
||||||
Array.isArray(team.bans) &&
|
Array.isArray(team.bans) &&
|
||||||
@@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse(
|
|||||||
(participant) =>
|
(participant) =>
|
||||||
typeof participant.tagLine === 'string' &&
|
typeof participant.tagLine === 'string' &&
|
||||||
Array.isArray(participant.itemBuild) &&
|
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 {
|
import type {
|
||||||
|
MatchStatsParticipantCheckpoints,
|
||||||
MatchStatsItemBuildEvent,
|
MatchStatsItemBuildEvent,
|
||||||
MatchStatsRunePerks,
|
MatchStatsRunePerks,
|
||||||
MatchStatsSkillBuildEvent,
|
MatchStatsSkillBuildEvent,
|
||||||
|
MatchStatsTimelineEvent,
|
||||||
RiotLane,
|
RiotLane,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -128,6 +130,7 @@ export interface InternalMatchDetailResponse {
|
|||||||
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
||||||
monsterSubType?: string;
|
monsterSubType?: string;
|
||||||
}>;
|
}>;
|
||||||
|
timelineEvents: MatchStatsTimelineEvent[];
|
||||||
teams: Array<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -143,6 +146,8 @@ export interface InternalMatchDetailResponse {
|
|||||||
};
|
};
|
||||||
bans: Array<{ championId: number; pickTurn: number }>;
|
bans: Array<{ championId: number; pickTurn: number }>;
|
||||||
participants: Array<{
|
participants: Array<{
|
||||||
|
participantId?: number;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
userId: string | null;
|
userId: string | null;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
|
|||||||
@@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
it('builds rich set detail from raw Riot match data', () => {
|
it('builds rich set detail from raw Riot match data', () => {
|
||||||
const builder = new MatchStatsFragmentBuilder();
|
const builder = new MatchStatsFragmentBuilder();
|
||||||
const match = makeMatch();
|
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 = {
|
const raw = {
|
||||||
metadata: {
|
metadata: {
|
||||||
dataVersion: '2',
|
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 = {
|
const timeline = {
|
||||||
metadata: {
|
metadata: {
|
||||||
dataVersion: '2',
|
dataVersion: '2',
|
||||||
@@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
{
|
{
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
participantFrames: {
|
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: {
|
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,
|
timestamp: 0,
|
||||||
blue: { gold: 500, xp: 0 },
|
blue: { gold: 500, xp: 0 },
|
||||||
red: { gold: 0, xp: 0 },
|
red: { gold: 500, xp: 0 },
|
||||||
goldDiff: 500,
|
goldDiff: 0,
|
||||||
xpDiff: 0,
|
xpDiff: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
timestamp: 60,
|
timestamp: 60,
|
||||||
blue: { gold: 1_150, xp: 550 },
|
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 },
|
red: { gold: 0, xp: 0 },
|
||||||
goldDiff: 1_150,
|
goldDiff: 5_200,
|
||||||
xpDiff: 550,
|
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([
|
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
|
||||||
{ championId: 14, pickTurn: 1 },
|
{ championId: 14, pickTurn: 1 },
|
||||||
{ championId: 43, pickTurn: 2 },
|
{ championId: 43, pickTurn: 2 },
|
||||||
@@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
voidGrub: 1,
|
voidGrub: 1,
|
||||||
});
|
});
|
||||||
expect(fragment.records[0]).toMatchObject({
|
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,
|
championLevel: 15,
|
||||||
cs: 228,
|
cs: 228,
|
||||||
damageDealtToChampions: 18_765,
|
damageDealtToChampions: 18_765,
|
||||||
@@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
|
{ 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 {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
MatchGameResultParticipant,
|
MatchGameResultParticipant,
|
||||||
|
MatchStatsCheckpoint,
|
||||||
MatchStatsItemBuildEvent,
|
MatchStatsItemBuildEvent,
|
||||||
MatchStatsObjectiveEvent,
|
MatchStatsObjectiveEvent,
|
||||||
MatchStatsObjectiveSummary,
|
MatchStatsObjectiveSummary,
|
||||||
|
MatchStatsParticipantCheckpoints,
|
||||||
MatchStatsSkillBuildEvent,
|
MatchStatsSkillBuildEvent,
|
||||||
|
MatchStatsTimelineEvent,
|
||||||
MatchStatsTimelinePoint,
|
MatchStatsTimelinePoint,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -27,13 +30,17 @@ interface ParticipantBuildEvents {
|
|||||||
skills: MatchStatsSkillBuildEvent[];
|
skills: MatchStatsSkillBuildEvent[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TimelineProjection {
|
||||||
|
objectiveEvents: MatchStatsObjectiveEvent[];
|
||||||
|
timelineEvents: MatchStatsTimelineEvent[];
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MatchStatsFragmentBuilder {
|
export class MatchStatsFragmentBuilder {
|
||||||
public buildFragment(params: {
|
public buildFragment(params: {
|
||||||
match: MatchDocument;
|
match: MatchDocument;
|
||||||
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||||
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
|
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
|
||||||
timelineLoadAttempted?: boolean;
|
|
||||||
}): MatchStatsFragment {
|
}): MatchStatsFragment {
|
||||||
const games = [...(params.match.result?.games ?? [])].sort(
|
const games = [...(params.match.result?.games ?? [])].sort(
|
||||||
(left, right) => left.gameNumber - right.gameNumber,
|
(left, right) => left.gameNumber - right.gameNumber,
|
||||||
@@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
||||||
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
|
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
|
||||||
return raw
|
return raw
|
||||||
? this.toGameDetail(
|
? this.toGameDetail(params.match, game, raw, timeline)
|
||||||
params.match,
|
|
||||||
game,
|
|
||||||
raw,
|
|
||||||
timeline,
|
|
||||||
params.timelineLoadAttempted === true,
|
|
||||||
)
|
|
||||||
: this.toFallbackGameDetail(params.match, game);
|
: this.toFallbackGameDetail(params.match, game);
|
||||||
});
|
});
|
||||||
const records = gameDetails.flatMap((detail) =>
|
const records = gameDetails.flatMap((detail) =>
|
||||||
@@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder {
|
|||||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||||
raw: RiotMatchDto,
|
raw: RiotMatchDto,
|
||||||
timeline?: RiotMatchTimelineDto,
|
timeline?: RiotMatchTimelineDto,
|
||||||
timelineLoadAttempted = false,
|
|
||||||
): InternalGameDetail {
|
): InternalGameDetail {
|
||||||
|
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
|
||||||
|
? timeline
|
||||||
|
: undefined;
|
||||||
const puuidByUserId = new Map(
|
const puuidByUserId = new Map(
|
||||||
match.participants
|
match.participants
|
||||||
.filter((participant) => participant.puuid)
|
.filter((participant) => participant.puuid)
|
||||||
@@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder {
|
|||||||
raw,
|
raw,
|
||||||
rawTeamIdBySide,
|
rawTeamIdBySide,
|
||||||
);
|
);
|
||||||
const objectiveEvents = this.toObjectiveEvents(
|
const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
|
||||||
timeline,
|
usableTimeline,
|
||||||
rawTeamIdBySide,
|
rawTeamIdBySide,
|
||||||
sideByParticipantId,
|
sideByParticipantId,
|
||||||
);
|
);
|
||||||
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
|
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
|
||||||
const buildEventsByParticipantId =
|
const buildEventsByParticipantId =
|
||||||
this.toBuildEventsByParticipantId(timeline);
|
this.toBuildEventsByParticipantId(usableTimeline);
|
||||||
|
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
|
||||||
|
usableTimeline,
|
||||||
|
raw.info.gameDuration,
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
gameNumber: game.gameNumber,
|
gameNumber: game.gameNumber,
|
||||||
@@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder {
|
|||||||
gameDuration: game.gameDuration,
|
gameDuration: game.gameDuration,
|
||||||
gameVersion: raw.info.gameVersion,
|
gameVersion: raw.info.gameVersion,
|
||||||
winnerSide: game.winnerSide,
|
winnerSide: game.winnerSide,
|
||||||
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
|
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
|
||||||
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
|
timelineLoaded: Boolean(usableTimeline),
|
||||||
objectiveEvents,
|
objectiveEvents,
|
||||||
|
timelineEvents,
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||||
const teamIndex =
|
const teamIndex =
|
||||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||||
@@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder {
|
|||||||
objectives: this.toObjectiveSummary(
|
objectives: this.toObjectiveSummary(
|
||||||
rawTeam,
|
rawTeam,
|
||||||
timelineObjectives.get(side),
|
timelineObjectives.get(side),
|
||||||
Boolean(timeline),
|
|
||||||
),
|
),
|
||||||
bans: (rawTeam?.bans ?? []).map((ban) => ({
|
bans: (rawTeam?.bans ?? []).map((ban) => ({
|
||||||
championId: ban.championId,
|
championId: ban.championId,
|
||||||
@@ -224,6 +231,9 @@ export class MatchStatsFragmentBuilder {
|
|||||||
rawParticipant.participantId,
|
rawParticipant.participantId,
|
||||||
)
|
)
|
||||||
: undefined,
|
: undefined,
|
||||||
|
checkpoints: rawParticipant
|
||||||
|
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
||||||
|
: undefined,
|
||||||
teamKills,
|
teamKills,
|
||||||
teamDamage,
|
teamDamage,
|
||||||
});
|
});
|
||||||
@@ -246,6 +256,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
timeline: [],
|
timeline: [],
|
||||||
timelineLoaded: false,
|
timelineLoaded: false,
|
||||||
objectiveEvents: [],
|
objectiveEvents: [],
|
||||||
|
timelineEvents: [],
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||||
side,
|
side,
|
||||||
@@ -273,6 +284,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant: MatchGameResultParticipant;
|
participant: MatchGameResultParticipant;
|
||||||
rawParticipant?: RiotMatchParticipantDto;
|
rawParticipant?: RiotMatchParticipantDto;
|
||||||
buildEvents?: ParticipantBuildEvents;
|
buildEvents?: ParticipantBuildEvents;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
teamKills: number;
|
teamKills: number;
|
||||||
teamDamage: number;
|
teamDamage: number;
|
||||||
}): InternalRecord {
|
}): InternalRecord {
|
||||||
@@ -282,6 +294,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant,
|
participant,
|
||||||
rawParticipant,
|
rawParticipant,
|
||||||
buildEvents,
|
buildEvents,
|
||||||
|
checkpoints,
|
||||||
teamKills,
|
teamKills,
|
||||||
teamDamage,
|
teamDamage,
|
||||||
} = params;
|
} = params;
|
||||||
@@ -319,6 +332,8 @@ export class MatchStatsFragmentBuilder {
|
|||||||
riotMatchId: game.riotMatchId,
|
riotMatchId: game.riotMatchId,
|
||||||
gameCreation: game.gameCreation,
|
gameCreation: game.gameCreation,
|
||||||
gameDuration: game.gameDuration,
|
gameDuration: game.gameDuration,
|
||||||
|
participantId: rawParticipant?.participantId,
|
||||||
|
checkpoints,
|
||||||
userId: participant.userId.toString(),
|
userId: participant.userId.toString(),
|
||||||
summonerName:
|
summonerName:
|
||||||
snapshot?.gameName ??
|
snapshot?.gameName ??
|
||||||
@@ -455,6 +470,107 @@ export class MatchStatsFragmentBuilder {
|
|||||||
return buildEventsByParticipantId;
|
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(
|
private toTimeline(
|
||||||
raw: RiotMatchDto,
|
raw: RiotMatchDto,
|
||||||
rawTeamIdBySide: Map<TeamSide, number>,
|
rawTeamIdBySide: Map<TeamSide, number>,
|
||||||
@@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder {
|
|||||||
return sideByParticipantId;
|
return sideByParticipantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private toObjectiveEvents(
|
private toTimelineEvents(
|
||||||
timeline: RiotMatchTimelineDto | undefined,
|
timeline: RiotMatchTimelineDto | undefined,
|
||||||
rawTeamIdBySide: Map<TeamSide, number>,
|
rawTeamIdBySide: Map<TeamSide, number>,
|
||||||
sideByParticipantId: Map<number, TeamSide>,
|
sideByParticipantId: Map<number, TeamSide>,
|
||||||
): MatchStatsObjectiveEvent[] {
|
): TimelineProjection {
|
||||||
if (!timeline?.info.frames.length) return [];
|
if (!timeline?.info.frames.length) {
|
||||||
|
return { objectiveEvents: [], timelineEvents: [] };
|
||||||
|
}
|
||||||
|
|
||||||
const sideByTeamId = new Map<number, TeamSide>();
|
const sideByTeamId = new Map<number, TeamSide>();
|
||||||
for (const [side, teamId] of rawTeamIdBySide.entries()) {
|
for (const [side, teamId] of rawTeamIdBySide.entries()) {
|
||||||
sideByTeamId.set(teamId, side);
|
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 frame of timeline.info.frames) {
|
||||||
for (const event of frame.events ?? []) {
|
for (const event of frame.events ?? []) {
|
||||||
if (event.type !== 'ELITE_MONSTER_KILL') continue;
|
const currentSequence = sourceSequence;
|
||||||
const side =
|
sourceSequence += 1;
|
||||||
(typeof event.killerTeamId === 'number'
|
|
||||||
? sideByTeamId.get(event.killerTeamId)
|
|
||||||
: undefined) ??
|
|
||||||
(typeof event.killerId === 'number'
|
|
||||||
? sideByParticipantId.get(event.killerId)
|
|
||||||
: undefined);
|
|
||||||
if (!side) continue;
|
|
||||||
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
|
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
|
||||||
switch (event.monsterType) {
|
if (event.type === 'ELITE_MONSTER_KILL') {
|
||||||
case 'BARON_NASHOR':
|
const side =
|
||||||
objectiveEvents.push({ timestamp, side, type: 'baron' });
|
(typeof event.killerTeamId === 'number'
|
||||||
break;
|
? sideByTeamId.get(event.killerTeamId)
|
||||||
case 'RIFTHERALD':
|
: undefined) ??
|
||||||
objectiveEvents.push({ timestamp, side, type: 'riftHerald' });
|
(typeof event.killerId === 'number'
|
||||||
break;
|
? sideByParticipantId.get(event.killerId)
|
||||||
case 'HORDE':
|
: undefined);
|
||||||
objectiveEvents.push({ timestamp, side, type: 'voidGrub' });
|
if (!side) continue;
|
||||||
break;
|
const objectiveEvent = toObjectiveTimelineEvent({
|
||||||
case 'DRAGON':
|
timestamp,
|
||||||
if (event.monsterSubType === 'ELDER_DRAGON') {
|
side,
|
||||||
objectiveEvents.push({
|
monsterType: event.monsterType,
|
||||||
timestamp,
|
monsterSubType: event.monsterSubType,
|
||||||
side,
|
});
|
||||||
type: 'elderDragon',
|
if (objectiveEvent) {
|
||||||
monsterSubType: event.monsterSubType,
|
projected.push({
|
||||||
});
|
sourceSequence: currentSequence,
|
||||||
} else {
|
event: objectiveEvent,
|
||||||
objectiveEvents.push({
|
});
|
||||||
timestamp,
|
}
|
||||||
side,
|
continue;
|
||||||
type: 'dragon',
|
|
||||||
monsterSubType: event.monsterSubType,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
private toTimelineObjectives(
|
||||||
@@ -608,29 +783,29 @@ export class MatchStatsFragmentBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private toObjectiveSummary(
|
private toObjectiveSummary(
|
||||||
rawTeam:
|
rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
|
||||||
| RiotMatchDto['info']['teams'][number]
|
|
||||||
| undefined,
|
|
||||||
timelineObjectives: MatchStatsObjectiveSummary | undefined,
|
timelineObjectives: MatchStatsObjectiveSummary | undefined,
|
||||||
hasTimeline: boolean,
|
|
||||||
): MatchStatsObjectiveSummary {
|
): MatchStatsObjectiveSummary {
|
||||||
const rawObjectives = rawTeam?.objectives;
|
const rawObjectives = rawTeam?.objectives;
|
||||||
|
const timelineDragon = timelineObjectives?.dragon ?? 0;
|
||||||
|
const timelineElder = timelineObjectives?.elderDragon ?? 0;
|
||||||
|
const hasProjectedDragon = timelineDragon + timelineElder > 0;
|
||||||
return {
|
return {
|
||||||
tower: rawObjectives?.tower?.kills ?? 0,
|
tower: rawObjectives?.tower?.kills ?? 0,
|
||||||
dragon: hasTimeline
|
dragon: hasProjectedDragon
|
||||||
? (timelineObjectives?.dragon ?? 0)
|
? timelineDragon
|
||||||
: (rawObjectives?.dragon?.kills ?? 0),
|
: (rawObjectives?.dragon?.kills ?? 0),
|
||||||
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
||||||
baron: hasTimeline
|
baron: (timelineObjectives?.baron ?? 0) > 0
|
||||||
? (timelineObjectives?.baron ?? 0)
|
? (timelineObjectives?.baron ?? 0)
|
||||||
: (rawObjectives?.baron?.kills ?? 0),
|
: (rawObjectives?.baron?.kills ?? 0),
|
||||||
riftHerald: hasTimeline
|
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
|
||||||
? (timelineObjectives?.riftHerald ?? 0)
|
? (timelineObjectives?.riftHerald ?? 0)
|
||||||
: (rawObjectives?.riftHerald?.kills ?? 0),
|
: (rawObjectives?.riftHerald?.kills ?? 0),
|
||||||
voidGrub: hasTimeline
|
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
|
||||||
? (timelineObjectives?.voidGrub ?? 0)
|
? (timelineObjectives?.voidGrub ?? 0)
|
||||||
: (rawObjectives?.horde?.kills ?? 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 {
|
function round(value: number): number {
|
||||||
return Math.round(value * 10) / 10;
|
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 { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
import { MatchStatsRepository } from './match-stats.repository';
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
import { MatchStatsService } from './match-stats.service';
|
import { MatchStatsService } from './match-stats.service';
|
||||||
|
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||||
|
|
||||||
describe('MatchStatsService', () => {
|
describe('MatchStatsService', () => {
|
||||||
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
||||||
@@ -158,8 +159,10 @@ describe('MatchStatsService', () => {
|
|||||||
match,
|
match,
|
||||||
rawByRiotMatchId: expect.any(Map),
|
rawByRiotMatchId: expect.any(Map),
|
||||||
timelineByRiotMatchId: 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(repository.upsert).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
matchId,
|
matchId,
|
||||||
@@ -167,11 +170,169 @@ describe('MatchStatsService', () => {
|
|||||||
scheduledAt,
|
scheduledAt,
|
||||||
gameCreationMin: 1_000,
|
gameCreationMin: 1_000,
|
||||||
gameCreationMax: 2_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 () => {
|
it('builds from the Competition projection and records its source revision', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const communityId = 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);
|
query.lean.mockReturnValue(query);
|
||||||
return lean ? query : { exec: query.exec };
|
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>();
|
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
|
||||||
for (const doc of riotDocs) {
|
for (const doc of riotDocs) {
|
||||||
if (isRiotMatchTimelineDto(doc.timeline)) {
|
if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
|
||||||
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
|
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,6 +94,12 @@ export class MatchStatsService {
|
|||||||
doc.matchId,
|
doc.matchId,
|
||||||
{ region },
|
{ region },
|
||||||
);
|
);
|
||||||
|
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Ignored unusable match timeline for ${doc.matchId}.`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
await RiotMatchModel.updateOne(
|
await RiotMatchModel.updateOne(
|
||||||
{ matchId: doc.matchId },
|
{ matchId: doc.matchId },
|
||||||
{
|
{
|
||||||
@@ -118,7 +124,6 @@ export class MatchStatsService {
|
|||||||
match: sourceMatch,
|
match: sourceMatch,
|
||||||
rawByRiotMatchId,
|
rawByRiotMatchId,
|
||||||
timelineByRiotMatchId,
|
timelineByRiotMatchId,
|
||||||
timelineLoadAttempted: options.includeTimeline === true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.repository.upsert({
|
await this.repository.upsert({
|
||||||
@@ -253,9 +258,65 @@ export class MatchStatsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
|
function isUsableRiotMatchTimeline(
|
||||||
if (!isRecord(value) || !isRecord(value.info)) return false;
|
value: unknown,
|
||||||
return Array.isArray(value.info.frames);
|
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> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type {
|
|||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import type { InternalMatchCardView } from './community-stats.types';
|
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 InternalRecord = MatchStatsRecord;
|
||||||
export type InternalGameDetail = MatchStatsGameDetail;
|
export type InternalGameDetail = MatchStatsGameDetail;
|
||||||
|
|||||||
@@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent {
|
|||||||
levelUpType?: string;
|
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 {
|
export interface MatchStatsRecord {
|
||||||
matchId: string;
|
matchId: string;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -948,6 +963,8 @@ export interface MatchStatsRecord {
|
|||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
gameCreation: number;
|
gameCreation: number;
|
||||||
gameDuration: number;
|
gameDuration: number;
|
||||||
|
participantId?: number;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
userId: string;
|
userId: string;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
@@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail {
|
|||||||
timeline: MatchStatsTimelinePoint[];
|
timeline: MatchStatsTimelinePoint[];
|
||||||
timelineLoaded?: boolean;
|
timelineLoaded?: boolean;
|
||||||
objectiveEvents: MatchStatsObjectiveEvent[];
|
objectiveEvents: MatchStatsObjectiveEvent[];
|
||||||
|
timelineEvents?: MatchStatsTimelineEvent[];
|
||||||
teams: Array<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent {
|
|||||||
monsterSubType?: string;
|
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 {
|
export interface MatchStatsTimelinePoint {
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
blue: { gold: number; xp: number };
|
blue: { gold: number; xp: number };
|
||||||
|
|||||||
@@ -214,4 +214,52 @@ describe('RiotMatchService', () => {
|
|||||||
levelUpType: 'NORMAL',
|
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,
|
value.type,
|
||||||
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
|
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
|
||||||
),
|
),
|
||||||
|
victimId: optionalNumber(
|
||||||
|
value.victimId,
|
||||||
|
`timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`,
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
|
|||||||
skillSlot?: number;
|
skillSlot?: number;
|
||||||
teamId?: number;
|
teamId?: number;
|
||||||
towerType?: string;
|
towerType?: string;
|
||||||
|
victimId?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RiotMatchTimelineParticipantFrameDto
|
export interface RiotMatchTimelineParticipantFrameDto
|
||||||
|
|||||||
@@ -701,6 +701,24 @@ export interface ApiInternalMatchDetailResponse {
|
|||||||
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
||||||
monsterSubType?: string;
|
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<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -716,6 +734,27 @@ export interface ApiInternalMatchDetailResponse {
|
|||||||
};
|
};
|
||||||
bans: Array<{ championId: number; pickTurn: number }>;
|
bans: Array<{ championId: number; pickTurn: number }>;
|
||||||
participants: Array<{
|
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;
|
userId: string | null;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
|
|||||||
@@ -6,6 +6,14 @@ import {
|
|||||||
} from "../lib/ddragon";
|
} from "../lib/ddragon";
|
||||||
import { teamIndexLabel } from "../lib/league";
|
import { teamIndexLabel } from "../lib/league";
|
||||||
import { LANE_LABELS } from "../lib/riot-history";
|
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";
|
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
|
||||||
|
|
||||||
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
||||||
@@ -13,6 +21,7 @@ export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
|||||||
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
|
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
|
||||||
type InternalGameTeam = InternalGameDetail["teams"][number];
|
type InternalGameTeam = InternalGameDetail["teams"][number];
|
||||||
type InternalGameParticipant = InternalGameTeam["participants"][number];
|
type InternalGameParticipant = InternalGameTeam["participants"][number];
|
||||||
|
type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike;
|
||||||
type DdragonManifestData = DdragonManifest | null | undefined;
|
type DdragonManifestData = DdragonManifest | null | undefined;
|
||||||
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
|
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
|
||||||
|
|
||||||
@@ -44,8 +53,6 @@ const STAT_PERK_LABELS: Record<number, string> = {
|
|||||||
5011: "체력",
|
5011: "체력",
|
||||||
};
|
};
|
||||||
|
|
||||||
const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"];
|
|
||||||
|
|
||||||
function formatDuration(seconds: number) {
|
function formatDuration(seconds: number) {
|
||||||
const minutes = Math.floor(seconds / 60);
|
const minutes = Math.floor(seconds / 60);
|
||||||
const rest = seconds % 60;
|
const rest = seconds % 60;
|
||||||
@@ -56,6 +63,11 @@ function formatNumber(value: number) {
|
|||||||
return new Intl.NumberFormat("ko-KR").format(value);
|
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) {
|
function sideTone(side: TeamSide) {
|
||||||
return side === "blue"
|
return side === "blue"
|
||||||
? {
|
? {
|
||||||
@@ -111,11 +123,6 @@ function runeStyleSelection(
|
|||||||
return participant.perks.styles?.find((style) => style.styleId === styleId);
|
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({
|
function ChampionCell({
|
||||||
participant,
|
participant,
|
||||||
manifest,
|
manifest,
|
||||||
@@ -648,12 +655,14 @@ function SkillBuildPanel({
|
|||||||
|
|
||||||
function MatchupMetricRow({
|
function MatchupMetricRow({
|
||||||
label,
|
label,
|
||||||
|
difference,
|
||||||
blueLead,
|
blueLead,
|
||||||
redLead,
|
redLead,
|
||||||
blueText,
|
blueText,
|
||||||
redText,
|
redText,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
|
difference?: string;
|
||||||
blueLead: boolean;
|
blueLead: boolean;
|
||||||
redLead: boolean;
|
redLead: boolean;
|
||||||
blueText: string;
|
blueText: string;
|
||||||
@@ -668,8 +677,13 @@ function MatchupMetricRow({
|
|||||||
>
|
>
|
||||||
{blueText}
|
{blueText}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
<span className="min-w-16 text-center text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
||||||
{label}
|
<span className="block">{label}</span>
|
||||||
|
{difference ? (
|
||||||
|
<span className="mt-0.5 block normal-case text-base-content/50">
|
||||||
|
{difference}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={`tabular-nums ${
|
className={`tabular-nums ${
|
||||||
@@ -682,101 +696,172 @@ function MatchupMetricRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function LaneMatchupCard({
|
function checkpointKda(kills: number, deaths: number, assists: number) {
|
||||||
blue,
|
return deaths === 0 ? kills + assists : (kills + assists) / deaths;
|
||||||
red,
|
}
|
||||||
detail,
|
|
||||||
|
function LaneParticipantIdentity({
|
||||||
|
participant,
|
||||||
manifest,
|
manifest,
|
||||||
|
align,
|
||||||
|
ambiguous,
|
||||||
}: {
|
}: {
|
||||||
blue: InternalGameParticipant;
|
participant: CheckpointParticipant | null;
|
||||||
red: InternalGameParticipant;
|
|
||||||
detail: ApiInternalMatchDetailResponse;
|
|
||||||
manifest: DdragonManifestData;
|
manifest: DdragonManifestData;
|
||||||
|
align: "left" | "right";
|
||||||
|
ambiguous: boolean;
|
||||||
}) {
|
}) {
|
||||||
const laneLabel =
|
if (!participant) {
|
||||||
LANE_LABELS[blue.teamPosition] ??
|
return (
|
||||||
LANE_LABELS[red.teamPosition] ??
|
<div
|
||||||
blue.teamPosition ??
|
className={`min-w-0 text-[11px] font-bold text-base-content/30 ${
|
||||||
"-";
|
align === "right" ? "text-right" : "text-left"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{ambiguous ? "포지션 중복" : "선수 없음"}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const metrics = [
|
const championName =
|
||||||
{
|
|
||||||
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) =>
|
|
||||||
championDisplayName(manifest, participant.championId) ??
|
championDisplayName(manifest, participant.championId) ??
|
||||||
String(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 (
|
return (
|
||||||
<div className="overflow-hidden border border-base-content/10 bg-base-100">
|
<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="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">
|
<LaneParticipantIdentity
|
||||||
<div className="min-w-0 text-right">
|
participant={blue}
|
||||||
<div className="truncate text-xs font-bold text-base-content">
|
manifest={manifest}
|
||||||
{blue.summonerName}
|
align="right"
|
||||||
</div>
|
ambiguous={ambiguousBlue}
|
||||||
<div className="truncate text-[11px] text-base-content/40">
|
/>
|
||||||
{championName(blue)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<ChampionAvatar participant={blue} manifest={manifest} />
|
|
||||||
</div>
|
|
||||||
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
|
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
|
||||||
{laneLabel}
|
{laneLabel}
|
||||||
</span>
|
</span>
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<LaneParticipantIdentity
|
||||||
<ChampionAvatar participant={red} manifest={manifest} />
|
participant={red}
|
||||||
<div className="min-w-0">
|
manifest={manifest}
|
||||||
<div className="truncate text-xs font-bold text-base-content">
|
align="left"
|
||||||
{red.summonerName}
|
ambiguous={ambiguousRed}
|
||||||
</div>
|
/>
|
||||||
<div className="truncate text-[11px] text-base-content/40">
|
</div>
|
||||||
{championName(red)}
|
{comparison ? (
|
||||||
</div>
|
<>
|
||||||
|
<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>
|
||||||
|
<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>
|
)}
|
||||||
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -790,6 +875,8 @@ function LaneMatchupPanel({
|
|||||||
detail: ApiInternalMatchDetailResponse;
|
detail: ApiInternalMatchDetailResponse;
|
||||||
manifest: DdragonManifestData;
|
manifest: DdragonManifestData;
|
||||||
}) {
|
}) {
|
||||||
|
const [checkpointKey, setCheckpointKey] =
|
||||||
|
useState<LaneCheckpointKey>(DEFAULT_LANE_CHECKPOINT);
|
||||||
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||||
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||||
|
|
||||||
@@ -801,40 +888,64 @@ function LaneMatchupPanel({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const blueSorted = [...blueTeam.participants].sort(
|
const matchups = pairLaneParticipants(
|
||||||
(left, right) =>
|
blueTeam.participants as CheckpointParticipant[],
|
||||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
redTeam.participants as CheckpointParticipant[],
|
||||||
);
|
|
||||||
const redSorted = [...redTeam.participants].sort(
|
|
||||||
(left, right) =>
|
|
||||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
|
||||||
);
|
);
|
||||||
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
|
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
|
||||||
const redTeamName = getTeamName(detail, redTeam.teamIndex);
|
const redTeamName = getTeamName(detail, redTeam.teamIndex);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="overflow-hidden border border-base-content/10 bg-base-100">
|
<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">
|
<div className="border-b border-base-content/8 px-4 py-3">
|
||||||
<span className="truncate text-right text-blue-400">
|
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 text-xs font-bold">
|
||||||
{blueTeamName}
|
<span className="truncate text-right text-blue-400">
|
||||||
</span>
|
{blueTeamName}
|
||||||
<span className="text-base-content/20">VS</span>
|
</span>
|
||||||
<span className="truncate text-red-400">{redTeamName}</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>
|
||||||
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
||||||
{blueSorted.map((blue, index) => {
|
{matchups.length > 0 ? (
|
||||||
const red = redSorted[index];
|
matchups.map((matchup) => (
|
||||||
if (!red) return null;
|
|
||||||
return (
|
|
||||||
<LaneMatchupCard
|
<LaneMatchupCard
|
||||||
key={`matchup-${blue.teamPosition}-${blue.summonerName}`}
|
key={`matchup-${matchup.position}`}
|
||||||
blue={blue}
|
position={matchup.position}
|
||||||
red={red}
|
blue={matchup.blue}
|
||||||
detail={detail}
|
red={matchup.red}
|
||||||
|
ambiguousBlue={matchup.ambiguousBlue}
|
||||||
|
ambiguousRed={matchup.ambiguousRed}
|
||||||
|
checkpointKey={checkpointKey}
|
||||||
manifest={manifest}
|
manifest={manifest}
|
||||||
/>
|
/>
|
||||||
);
|
))
|
||||||
})}
|
) : (
|
||||||
|
<div className="py-10 text-center text-sm font-bold text-base-content/35 lg:col-span-2">
|
||||||
|
비교 가능한 포지션 정보가 없습니다
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
AreaChart,
|
AreaChart,
|
||||||
CartesianGrid,
|
CartesianGrid,
|
||||||
Line,
|
Line,
|
||||||
|
ReferenceDot,
|
||||||
ReferenceLine,
|
ReferenceLine,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@@ -28,6 +29,16 @@ import {
|
|||||||
internalMatchGamePath,
|
internalMatchGamePath,
|
||||||
} from "../lib/internal-match-routes";
|
} from "../lib/internal-match-routes";
|
||||||
import { LANE_LABELS } from "../lib/riot-history";
|
import { LANE_LABELS } from "../lib/riot-history";
|
||||||
|
import {
|
||||||
|
filterTimelineEvents,
|
||||||
|
normalizeObjectiveEvents,
|
||||||
|
normalizeTimelineEvents,
|
||||||
|
projectTimelineEventMarkers,
|
||||||
|
selectTimelineEventSource,
|
||||||
|
summarizeDragonTypes,
|
||||||
|
type NormalizedTimelineEvent,
|
||||||
|
type TimelineEventFilter,
|
||||||
|
} from "../lib/internal-match-timeline";
|
||||||
import {
|
import {
|
||||||
InternalGameAnalysisPanel,
|
InternalGameAnalysisPanel,
|
||||||
InternalGameDetailTabBar,
|
InternalGameDetailTabBar,
|
||||||
@@ -58,6 +69,16 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
|
|||||||
{ id: "xp", label: "경험치" },
|
{ 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> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null;
|
return typeof value === "object" && value !== null;
|
||||||
}
|
}
|
||||||
@@ -142,6 +163,16 @@ function formatPercent(value: number) {
|
|||||||
return `${value}%`;
|
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) {
|
function barWidth(value: number, max: number) {
|
||||||
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
|
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
|
||||||
}
|
}
|
||||||
@@ -411,13 +442,13 @@ function PlayerRow({
|
|||||||
{participant.assists}
|
{participant.assists}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs font-bold tabular-nums text-base-content/40">
|
<div className="text-xs font-bold tabular-nums text-base-content/40">
|
||||||
{formatKda(
|
KDA {formatKda(
|
||||||
participant.kills,
|
participant.kills,
|
||||||
participant.deaths,
|
participant.deaths,
|
||||||
participant.assists,
|
participant.assists,
|
||||||
)}
|
)}
|
||||||
<span className="ml-1 text-base-content/35">
|
<span className="ml-1 text-base-content/35">
|
||||||
({participant.killParticipation}%)
|
· KP {participant.killParticipation}%
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
@@ -451,6 +482,12 @@ function PlayerRow({
|
|||||||
<span className="block text-base-content/35">
|
<span className="block text-base-content/35">
|
||||||
{participant.csPerMin}/m
|
{participant.csPerMin}/m
|
||||||
</span>
|
</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>
|
||||||
<td className="px-3 py-2.5">
|
<td className="px-3 py-2.5">
|
||||||
<ItemStrip participant={participant} manifest={manifest} />
|
<ItemStrip participant={participant} manifest={manifest} />
|
||||||
@@ -486,13 +523,13 @@ function PlayerCard({
|
|||||||
{participant.assists}
|
{participant.assists}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
|
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
|
||||||
{formatKda(
|
KDA {formatKda(
|
||||||
participant.kills,
|
participant.kills,
|
||||||
participant.deaths,
|
participant.deaths,
|
||||||
participant.assists,
|
participant.assists,
|
||||||
)}
|
)}
|
||||||
<span className="ml-1 text-base-content/35">
|
<span className="ml-1 text-base-content/35">
|
||||||
({participant.killParticipation}%)
|
· KP {participant.killParticipation}%
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -527,13 +564,19 @@ function PlayerCard({
|
|||||||
</div>
|
</div>
|
||||||
<div className="border border-base-content/8 px-2 py-1.5">
|
<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">
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
||||||
CS
|
CS · 경제
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-0.5 font-black text-base-content/70">
|
<div className="mt-0.5 font-black text-base-content/70">
|
||||||
{participant.cs}
|
{participant.cs}
|
||||||
<span className="ml-1 font-bold text-base-content/35">
|
<span className="ml-1 font-bold text-base-content/35">
|
||||||
{participant.csPerMin}/m
|
{participant.csPerMin}/m
|
||||||
</span>
|
</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>
|
</div>
|
||||||
<div className="border border-base-content/8 px-2 py-1.5">
|
<div className="border border-base-content/8 px-2 py-1.5">
|
||||||
@@ -701,11 +744,125 @@ function PostgameBreakdown({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
<ObjectiveComparisonStrip selectedGame={selectedGame} />
|
||||||
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
|
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
|
||||||
</section>
|
</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({
|
function GoldComparisonStrip({
|
||||||
selectedGame,
|
selectedGame,
|
||||||
detail,
|
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({
|
function TimelineGraph({
|
||||||
selectedGame,
|
selectedGame,
|
||||||
detail,
|
detail,
|
||||||
|
manifest,
|
||||||
}: {
|
}: {
|
||||||
selectedGame: MatchGameDetail;
|
selectedGame: MatchGameDetail;
|
||||||
detail: ApiInternalMatchDetailResponse;
|
detail: ApiInternalMatchDetailResponse;
|
||||||
|
manifest: ReturnType<typeof useDdragonManifest>["data"];
|
||||||
}) {
|
}) {
|
||||||
const [metric, setMetric] = useState<TimelineMetric>("gold");
|
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 blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||||
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||||
const blueTeamName = blueTeam
|
const blueTeamName = blueTeam
|
||||||
@@ -883,6 +1100,41 @@ function TimelineGraph({
|
|||||||
...chartData.map((point) => Math.abs(point.value)),
|
...chartData.map((point) => Math.abs(point.value)),
|
||||||
);
|
);
|
||||||
const finalPoint = chartData[chartData.length - 1];
|
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 =
|
const finalLeader =
|
||||||
finalPoint?.leaderSide === "blue"
|
finalPoint?.leaderSide === "blue"
|
||||||
? blueTeamName
|
? blueTeamName
|
||||||
@@ -901,11 +1153,16 @@ function TimelineGraph({
|
|||||||
: "타임라인 대기"}
|
: "타임라인 대기"}
|
||||||
</div>
|
</div>
|
||||||
</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) => (
|
{TIMELINE_METRICS.map((item) => (
|
||||||
<button
|
<button
|
||||||
key={item.id}
|
key={item.id}
|
||||||
type="button"
|
type="button"
|
||||||
|
aria-pressed={metric === item.id}
|
||||||
onClick={() => setMetric(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 ${
|
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
|
metric === item.id
|
||||||
@@ -921,7 +1178,11 @@ function TimelineGraph({
|
|||||||
{chartData.length > 0 ? (
|
{chartData.length > 0 ? (
|
||||||
<div className="px-2 py-4 sm:px-4">
|
<div className="px-2 py-4 sm:px-4">
|
||||||
<div className="h-[260px] min-w-0 w-full">
|
<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
|
<AreaChart
|
||||||
data={chartData}
|
data={chartData}
|
||||||
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
|
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
|
||||||
@@ -933,6 +1194,8 @@ function TimelineGraph({
|
|||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="timestamp"
|
dataKey="timestamp"
|
||||||
|
type="number"
|
||||||
|
domain={[0, chartMaxTimestamp]}
|
||||||
minTickGap={28}
|
minTickGap={28}
|
||||||
tickFormatter={(value) =>
|
tickFormatter={(value) =>
|
||||||
`${Math.round(Number(value) / 60)}분`
|
`${Math.round(Number(value) / 60)}분`
|
||||||
@@ -965,6 +1228,14 @@ function TimelineGraph({
|
|||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
strokeOpacity={0.25}
|
strokeOpacity={0.25}
|
||||||
/>
|
/>
|
||||||
|
{selectedTimestamp !== null ? (
|
||||||
|
<ReferenceLine
|
||||||
|
x={selectedTimestamp}
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeDasharray="3 3"
|
||||||
|
strokeOpacity={0.35}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
<Area
|
<Area
|
||||||
type="monotone"
|
type="monotone"
|
||||||
dataKey="positive"
|
dataKey="positive"
|
||||||
@@ -994,6 +1265,44 @@ function TimelineGraph({
|
|||||||
}}
|
}}
|
||||||
isAnimationActive={false}
|
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>
|
</AreaChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
</div>
|
</div>
|
||||||
@@ -1008,6 +1317,106 @@ function TimelineGraph({
|
|||||||
타임라인 데이터가 아직 없습니다
|
타임라인 데이터가 아직 없습니다
|
||||||
</div>
|
</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>
|
</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-[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-[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>
|
<th className="w-[260px] px-3 py-2.5">아이템</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -1306,6 +1715,13 @@ export default function MatchGameDetailPage() {
|
|||||||
manifest={ddragon}
|
manifest={ddragon}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<TimelineGraph
|
||||||
|
key={selectedGame.riotMatchId}
|
||||||
|
selectedGame={selectedGame}
|
||||||
|
detail={detail}
|
||||||
|
manifest={ddragon}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="mt-5 space-y-4">
|
<div className="mt-5 space-y-4">
|
||||||
<InternalGameDetailTabBar
|
<InternalGameDetailTabBar
|
||||||
activeTab={activeTab}
|
activeTab={activeTab}
|
||||||
@@ -1325,8 +1741,6 @@ export default function MatchGameDetailPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<TimelineGraph selectedGame={selectedGame} detail={detail} />
|
|
||||||
</main>
|
</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],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Implementation Plan: Internal Match Game Analysis P0/P1
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deliver three independently verifiable slices: P0 existing-data UI, P1-A timeline
|
||||||
|
checkpoints and lane comparison, and P1-B unified notable events. Preserve the
|
||||||
|
existing detail endpoint and use builder/cache versioning to refresh old projections.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: P0 Existing Data
|
||||||
|
|
||||||
|
- [x] Add tested objective normalization, chart markers, an accessible event list,
|
||||||
|
and move game flow above the detail tabs.
|
||||||
|
- [x] Add a complete objective comparison strip with conservative dragon-type
|
||||||
|
fallback behavior.
|
||||||
|
- [x] Label KP and add participant gold/GPM to the combined CS/economy presentation.
|
||||||
|
|
||||||
|
### Checkpoint: P0
|
||||||
|
|
||||||
|
- [x] Web tests, lint, and production build pass.
|
||||||
|
- [x] Desktop and mobile layouts retain all existing scoreboard/build behavior.
|
||||||
|
|
||||||
|
### Phase 2: P1-A Lane Checkpoints
|
||||||
|
|
||||||
|
- [x] Parse the remaining participant event identifier fields and project tested
|
||||||
|
participant checkpoints at 10 and 15 minutes.
|
||||||
|
- [x] Persist and expose optional checkpoint fields, reject stale caches, and bump
|
||||||
|
the match-stats builder/detail-response versions.
|
||||||
|
- [x] Replace final-state lane comparisons with tested role-based 10/15-minute
|
||||||
|
GD/CSD/XPD and K/D/A comparisons.
|
||||||
|
|
||||||
|
### Checkpoint: P1-A
|
||||||
|
|
||||||
|
- [x] Focused API tests and builds pass.
|
||||||
|
- [x] Web tests and production build pass.
|
||||||
|
- [x] Short and missing-timeline games show unavailable states rather than zeros.
|
||||||
|
|
||||||
|
### Phase 3: P1-B Unified Events
|
||||||
|
|
||||||
|
- [x] Project objectives, champion kills, towers, and inhibitors into a deterministic
|
||||||
|
tested event stream.
|
||||||
|
- [x] Expose `timelineEvents` while retaining `objectiveEvents` compatibility and
|
||||||
|
bump persisted/cache versions as required.
|
||||||
|
- [x] Add accessible event filtering and chart selection with objective-only fallback.
|
||||||
|
- [x] Coalesce concurrent hydration and short-cache incomplete results so transient
|
||||||
|
failures retry without rebuilding on every sequential page request.
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] API and web focused suites pass without skipped tests.
|
||||||
|
- [x] API and web production builds pass.
|
||||||
|
- [x] Responsive runtime review passes at 320px, 390px, 768px, 1024px, and 1440px.
|
||||||
|
- [x] P0/P1 edits exclude unrelated Competition/bracket modifications already in
|
||||||
|
the shared worktree.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Missing or delayed Riot frames misrepresent @10/@15 | High | Use only a frame at/before the target within one frame interval and expose its actual timestamp. |
|
||||||
|
| Building events attribute the destroyed team's side as the scorer | High | Prefer killer participant side; otherwise invert the destroyed `teamId`; cover both paths in tests. |
|
||||||
|
| Old cached shapes hide new fields | High | Increment builder and response cache versions and strengthen completeness validation. |
|
||||||
|
| A kill-heavy game makes the page excessively long | Medium | Add event-category filters and a bounded scroll region. |
|
||||||
|
| Mobile chart remains hard to reach | Medium | Move flow directly below the summary before any participant cards. |
|
||||||
|
| Existing dirty work is accidentally included | High | Restrict edits and verification to the named game-analysis files and inspect the final diff by path. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
P0 event normalization -> P0 objective strip
|
||||||
|
P1 checkpoint projector -> response contract -> lane UI
|
||||||
|
P1 checkpoint identifiers -> event projector -> response contract -> event UI
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
# Spec: Internal Match Game Analysis P0/P1
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Make an internal-match game result explain both the final numbers and how the game
|
||||||
|
reached them. P0 exposes data already present in the detail response: objective
|
||||||
|
events, complete team objectives, participant gold/GPM, and explicitly labelled
|
||||||
|
kill participation. P1 projects Riot Match-V5 timeline frames into real 10- and
|
||||||
|
15-minute lane checkpoints and a unified event stream for kills and structures.
|
||||||
|
|
||||||
|
The primary user is a tournament participant or organizer reviewing a completed
|
||||||
|
game on desktop or mobile. Success means the user can identify the major objective
|
||||||
|
sequence before reading ten player cards, compare lane state at 10/15 minutes, and
|
||||||
|
trace kills and building events without mistaking unavailable data for zero.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Place game flow immediately after the game summary and before detail tabs.
|
||||||
|
- Render chart events as both visual markers and a keyboard-readable text list.
|
||||||
|
- Keep the existing gold/XP toggle and runes/build experience.
|
||||||
|
- Show tower, dragon, inhibitor, Baron, Rift Herald, Void Grub, and Elder Dragon
|
||||||
|
totals; derive dragon type labels only when objective events are available.
|
||||||
|
- Combine participant CS and economy instead of adding another wide table column.
|
||||||
|
- Label kill participation explicitly as `KP`.
|
||||||
|
- Replace final-state values in the lane tab with 10/15-minute checkpoints; default
|
||||||
|
to 15 minutes and pair players by `teamPosition`, never array position.
|
||||||
|
- Keep `objectiveEvents` for compatibility and add `timelineEvents` for the unified
|
||||||
|
P1 stream.
|
||||||
|
- Treat missing checkpoints and events as unavailable, not zero.
|
||||||
|
- Do not add an opaque MVP/rating or new external data feed in this scope.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19, TypeScript 6, Recharts 3, Tailwind CSS 4, and daisyUI under `apps/web`
|
||||||
|
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
|
||||||
|
- Riot Match-V5 match and timeline payloads already cached in `RiotMatchModel`
|
||||||
|
- Node's built-in test runner for pure web transformations
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web production build: `pnpm --filter web build:prod`
|
||||||
|
- Focused API tests: `pnpm --filter api test -- --runInBand riot-match.service.spec.ts match-stats-fragment.builder.spec.ts community-stats.service.spec.ts`
|
||||||
|
- API build: `pnpm --filter api build`
|
||||||
|
- Development web server: `pnpm --filter web start:dev`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/pages/MatchGameDetailPage.tsx` owns the result summary,
|
||||||
|
participant scoreboard, flow chart, and accessible event list.
|
||||||
|
- `apps/web/src/components/InternalGameAnalysisTabs.tsx` owns the lane and build
|
||||||
|
tabs.
|
||||||
|
- `apps/web/src/lib/internal-match-timeline.ts` owns pure event normalization,
|
||||||
|
labels, filtering, and chart projection.
|
||||||
|
- `apps/web/src/lib/internal-game-matchups.ts` owns pure role pairing and checkpoint
|
||||||
|
comparisons.
|
||||||
|
- `apps/web/test/` contains Node unit tests for the pure web transformations.
|
||||||
|
- `apps/api/src/modules/riot/` parses trusted fields from Riot match timelines.
|
||||||
|
- `apps/api/src/modules/community-stats/match-stats-fragment.builder.ts` projects
|
||||||
|
stored Riot payloads into cached internal-match records.
|
||||||
|
- `apps/api/src/modules/community-stats/community-stats.service.ts` maps persisted
|
||||||
|
records into the public detail response and versions response caches.
|
||||||
|
- `apps/api/src/modules/global/database/schema.ts` defines persisted TypeScript
|
||||||
|
shapes; nested `gameDetails` remains a Mongoose Mixed array.
|
||||||
|
|
||||||
|
## Data Contract
|
||||||
|
|
||||||
|
Participant checkpoint data is additive and optional for legacy/fallback games:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface MatchStatsCheckpoint {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchStatsParticipantCheckpoints {
|
||||||
|
at10?: MatchStatsCheckpoint;
|
||||||
|
at15?: MatchStatsCheckpoint;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each detailed participant gains optional `participantId` and `checkpoints`. Each
|
||||||
|
game gains optional `timelineEvents`, whose `type` is an existing objective type or
|
||||||
|
`championKill`, `tower`, or `inhibitor`. Actor IDs, assists, monster subtype, and
|
||||||
|
tower subtype are optional fields appropriate to the event type.
|
||||||
|
|
||||||
|
For a 10/15-minute target, use the latest frame at or before the target only when it
|
||||||
|
is less than one `frameInterval` old. Persist the actual selected timestamp. CS is
|
||||||
|
`minionsKilled + jungleMinionsKilled`; checkpoint K/D/A includes champion-kill
|
||||||
|
events through the selected timestamp. A game ending before a target has no value
|
||||||
|
for that checkpoint.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep timeline calculations independent from React and use discriminated event
|
||||||
|
types with conservative fallbacks:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const events = game.timelineEvents?.length
|
||||||
|
? game.timelineEvents
|
||||||
|
: game.objectiveEvents;
|
||||||
|
|
||||||
|
const checkpoint = participant.checkpoints?.at15;
|
||||||
|
if (!checkpoint) return { kind: "unavailable" };
|
||||||
|
```
|
||||||
|
|
||||||
|
Use existing semantic color tokens and square bordered panels. Dynamic chart
|
||||||
|
coordinates may use numeric props; spacing, colors, and typography remain in the
|
||||||
|
existing Tailwind/daisyUI system.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Develop pure event normalization, checkpoint selection, role pairing, and metric
|
||||||
|
comparison test-first.
|
||||||
|
- Builder tests cover exact and missing checkpoints, jungle CS, cumulative K/D/A,
|
||||||
|
executes, objective fallback, building ownership, and deterministic event order.
|
||||||
|
- Service tests reject stale cached response shapes and verify additive mapping.
|
||||||
|
- Browser verification covers 320px, 390px, 768px, 1024px, and 1440px; the event
|
||||||
|
text list is the accessible equivalent of decorative chart markers.
|
||||||
|
- Verify the supplied production-like game as well as a short game and a game with
|
||||||
|
no timeline.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Preserve existing `objectiveEvents`, runes/builds, and match-detail routes.
|
||||||
|
- Derive participant checkpoint values from stored Riot timeline frames.
|
||||||
|
- Pair lanes by normalized `teamPosition` and show unavailable states explicitly.
|
||||||
|
- Communicate team/event meaning with text as well as color.
|
||||||
|
- Increment the match-stats builder and detail-response cache versions whenever a
|
||||||
|
persisted or cached response shape changes.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Add a frontend or backend dependency.
|
||||||
|
- Change the public route or remove compatibility fields.
|
||||||
|
- Add a database migration or make a bulk external Riot API fetch.
|
||||||
|
- Deploy, push, or alter CI configuration.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Infer absent checkpoint data as zero.
|
||||||
|
- Pair opponents by array order.
|
||||||
|
- Claim that a nearby objective caused a gold swing.
|
||||||
|
- Expose unparsed arbitrary Riot event fields.
|
||||||
|
- Modify unrelated Competition/bracket work already present in the worktree.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- Game flow appears before player details and includes objective markers plus an
|
||||||
|
equivalent textual sequence on desktop and mobile.
|
||||||
|
- Summary shows all currently projected objective totals and available dragon types.
|
||||||
|
- Every participant shows labelled KP, gold, GPM, CS, and CS/min without breaking
|
||||||
|
the responsive scoreboard.
|
||||||
|
- The lane tab defaults to 15 minutes, can switch to 10 minutes, and presents
|
||||||
|
GD/CSD/XPD and checkpoint K/D/A for correctly paired roles.
|
||||||
|
- The unified timeline can filter and display objectives, champion kills, towers,
|
||||||
|
and inhibitors, while falling back to objective-only data during rolling updates.
|
||||||
|
- Focused API/web tests, lint, and production builds pass.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user reviewed the P0/P1 task plan and requested implementation.
|
||||||
Reference in new issue
Block a user