/** 9단계 수집 확장: chart parsers on saved pages, chart saving, Melon details, heatmap highlights, level calculation. */ import { describe, expect, test } from 'bun:test'; import { join } from 'node:path'; import { openDb } from '../db'; import { tempDbPath } from '../test-utils'; import { Catalog } from './catalog'; import { parseBugs, parseGenie, parseMelon, parseMelonDetail, parseTj, saveChart } from './charts'; import { collectHeatmaps, parseHeatmap, pickHighlight } from './heatmap'; import { computeLevels, levelsByShare, LEVEL_CUTS, popularity } from './levels'; const fx = (f: string) => Bun.file(join(import.meta.dir, 'fixtures', f)).text(); describe('chart parsers (saved pages, 2026-10-18)', () => { test('멜론 연도별: song id, rank, title, artists with Melon artist ids', async () => { const rows = parseMelon(await fx('melon-chart.html')); expect(rows.length).toBe(3); expect(rows[0]).toEqual({ rank: 1, ref: '711627', title: '죄와벌', artists: [{ ref: '108363', name: 'SG 워너비' }] }); expect(rows[1]).toMatchObject({ rank: 2, title: '겁쟁이', artists: [{ name: '버즈' }] }); }); test('지니 연도별 / 벅스 실시간 / TJ', async () => { expect(parseGenie(await fx('genie-chart.html'))[0]).toEqual({ rank: 1, ref: '16188070', title: '죄와 벌 (罪와 罰)', artists: [{ name: 'SG워너비' }] }); expect(parseBugs(await fx('bugs-chart.html'))[0]).toMatchObject({ rank: 1, ref: '6511885', title: 'NEON', artists: [{ name: 'A2O' }] }); expect(parseTj({ resultData: { items: [{ rank: '1', pro: 86291, indexTitle: 'HAPPY', indexSong: '데이식스' }] } })).toEqual([{ rank: 1, ref: '86291', title: 'HAPPY', artists: [{ name: '데이식스' }] }]); }); test('멜론 곡 상세: release date, genre mapping, lyrics with line breaks', async () => { expect(parseMelonDetail(await fx('melon-song.html'))).toEqual({ releaseDate: '2005-03-03', genres: ['rock'], lyrics: '첫째 줄 가사\n둘째 줄 & 가사\n\n셋째 줄' }); }); }); describe('saving charts', () => { test('Melon rows create songs with Melon ids; Genie rows only link existing songs (same song, other spelling)', () => { const db = openDb(tempDbPath()); const melon = [ { rank: 1, ref: '711627', title: '죄와벌', artists: [{ ref: '108363', name: 'SG 워너비' }] }, { rank: 2, ref: '732512', title: '겁쟁이', artists: [{ ref: '160091', name: '버즈' }] }, ]; expect(saveChart(db, { source: 'melon', chart: 'year-kpop', period: '2005', create: 'kpop', year: 2005 }, melon)).toEqual({ created: 2, linked: 2, rows: 2 }); const s = db.query<{ id: number; melon_id: number; year: number }, []>("SELECT id, melon_id, year FROM songs WHERE title = '죄와벌'").get()!; expect(s).toMatchObject({ melon_id: 711627, year: 2005 }); const genie = [ { rank: 1, ref: '16188070', title: '죄와 벌 (罪와 罰)', artists: [{ name: 'SG워너비' }] }, { rank: 2, ref: '1', title: '모르는곡', artists: [{ name: '누군가' }] }, ]; expect(saveChart(db, { source: 'genie', chart: 'year', period: '2005', year: 2005 }, genie)).toEqual({ created: 0, linked: 1, rows: 2 }); expect(db.query<{ song_id: number | null }, []>("SELECT song_id FROM chart_entries WHERE source = 'genie' ORDER BY rank").all().map((r) => r.song_id)).toEqual([s.id, null]); // saving again replaces rows, never duplicates songs saveChart(db, { source: 'melon', chart: 'year-kpop', period: '2005', create: 'kpop', year: 2005 }, melon); expect(db.query<{ n: number }, []>('SELECT COUNT(*) n FROM songs').get()!.n).toBe(2); expect(db.query<{ n: number }, []>('SELECT COUNT(*) n FROM chart_entries').get()!.n).toBe(4); }); }); describe('heatmap highlight', () => { test('real page markers → 광 (狂) peak around the chorus, the opening spike is ignored', async () => { const m = parseHeatmap(await fx('youtube-heatmap.txt')); expect(m.length).toBe(100); const sec = pickHighlight(m)!; expect(sec).toBeGreaterThan(65); expect(sec).toBeLessThan(80); }); test('sets heatmap highlights, never touches an admin one, remembers tries', async () => { const db = openDb(tempDbPath()); const c = new Catalog(db); const ids = ['a', 'b'].map((t) => c.upsert({ title: t, artists: [{ name: 'x' }], source: 't', ref: t })[0]); db.query("UPDATE songs SET youtube_status = 'matched', youtube_id = 'VO88htcm09E'").run(); db.query("UPDATE songs SET highlight_sec = 12, highlight_source = 'admin' WHERE id = ?").run(ids[1]!); const page = await fx('youtube-heatmap.txt'); const r = await collectHeatmaps(db, { delayMs: 0, fetchPage: async () => page }); expect(r).toEqual({ set: 1, none: 0, failed: 0 }); expect(db.query<{ highlight_sec: number; highlight_source: string }, []>('SELECT highlight_sec, highlight_source FROM songs ORDER BY id').all()).toEqual([ { highlight_sec: pickHighlight(parseHeatmap(page))!, highlight_source: 'heatmap' }, { highlight_sec: 12, highlight_source: 'admin' }, ]); expect((await collectHeatmaps(db, { delayMs: 0, fetchPage: async () => page })).set).toBe(0); }); }); describe('level calculation (docs/07 난이도 분류)', () => { const base = { yearBest: null, chartYears: 0, realtimeBest: null, norabosePeak: null, noraboseLevel: null, tjBest: null, quizSources: [] as string[], artistHits: 0 }; test('a yearly #1 karaoke hit beats a song that only charted low', () => { const hit = popularity({ ...base, yearBest: 1, chartYears: 2, tjBest: 3, noraboseLevel: 1, quizSources: ['sta', 'norabose'], artistHits: 12 }); const low = popularity({ ...base, yearBest: 90, noraboseLevel: 4 }); expect(hit).toBeGreaterThan(90); expect(low).toBeLessThan(25); expect(popularity(base)).toBe(0); }); test('levels by share: top 3% = 1 … last 5% = 10, equal scores share a level', () => { const scores = new Map(Array.from({ length: 200 }, (_, i) => [i + 1, 200 - i] as [number, number])); const lv = levelsByShare(scores); const count = (l: number) => [...lv.values()].filter((x) => x === l).length; expect(LEVEL_CUTS.map((_, i) => count(i + 1))).toEqual([6, 10, 20, 24, 30, 30, 24, 24, 22, 10]); const tied = levelsByShare(new Map([[1, 5], [2, 5], [3, 5], [4, 1]])); expect(new Set([tied.get(1), tied.get(2), tied.get(3)]).size).toBe(1); }); test('computeLevels writes all + big genre scopes, keeps admin levels', () => { const db = openDb(tempDbPath()); const c = new Catalog(db); for (let i = 0; i < 160; i++) { const [id] = c.upsert({ title: `곡${i}`, artists: [{ name: `가수${i % 40}` }], year: 1995 + (i % 10), genres: ['ballad'], source: 't', ref: String(i) }); db.query("INSERT INTO chart_entries (source, chart, period, rank, raw_title, raw_artist, song_id, fetched_at) VALUES ('melon', 'year-kpop', '2000', ?, 'x', 'y', ?, 0)").run(i + 1, id!); } const first = db.query<{ id: number }, []>("SELECT id FROM songs WHERE title = '곡0'").get()!.id; db.query("INSERT INTO song_levels (song_id, scope, level, source) VALUES (?, 'all', 9, 'admin')").run(first); const r = computeLevels(db); expect(Object.values(r.all).reduce((a, b) => a + b, 0)).toBe(160); expect(db.query<{ level: number; source: string }, [number]>("SELECT level, source FROM song_levels WHERE song_id = ? AND scope = 'all'").get(first)).toEqual({ level: 9, source: 'admin' }); // ballad has 160 ≥ 150 songs → own scope; decades have 80 each → none expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM song_levels WHERE scope = 'genre:ballad'").get()!.n).toBe(160); expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM song_levels WHERE scope LIKE 'decade:%'").get()!.n).toBe(0); const best = db.query<{ level: number }, []>("SELECT l.level FROM song_levels l JOIN songs s ON s.id = l.song_id WHERE s.title = '곡1' AND scope = 'all'").get()!.level; expect(best).toBe(1); }); });