Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | 5x 5x 5x 4x 4x 4x 5x 5x 5x 5x 66x 66x 66x 1x 1x 65x 65x 65x 66x 38x 35x 4x 18x 18x 18x 18x 18x 18x 18x 149x 149x 149x 149x 149x 149x 149x 18x 149x 149x 145x 149x 149x 18x 14x 14x 18x 18x 149x 149x 149x 149x 149x 149x 149x 149x 4x 145x 145x 18x 1x 17x 17x 17x 17x 17x 25x 174x 174x 174x 25x 149x 149x 17x 18x 17x 17x 17x 2x 2x 15x 15x 15x 15x 15x 15x 16x 15x 15x 307x 15x 15x 147x 147x 131x 131x 16x 15x 1x 1x 1x 15x 15x 16x 16x 147x 16x 131x 131x 1x 130x 131x 130x 130x 130x 130x 130x 16x 16x 147x 147x 15x 261x 261x 261x 130x 131x 1x 130x 130x 130x 130x 130x 130x 130x 145x 145x 145x 145x 145x 1x 117x 145x 145x 145x 145x 145x 145x 1x 144x 144x 144x 1x 1x 1x 151x 2x 149x 149x 2x 147x 151x 149x 149x 149x 154x 294x 294x 294x 145x 145x 145x 9x 4x 1303x 1010x 293x 293x 145x 1x 2x 2x 1x 1x 144x 145x 145x 1x 144x 144x 1x 143x 145x 158x 158x 145x 145x 145x 145x 158x 2x 158x 3x 145x 32x 13x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 4x 5x 18x 18x 18x 13x 13x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 45x 15x 35x 29x 14x 14x 14x 14x | import { createHash } from 'node:crypto';
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import { availableParallelism, homedir } from 'node:os';
import { dirname, extname, relative, resolve } from 'node:path';
import { isAbortError, throwIfAborted } from '@be-music/shared-utils/core';
import { invokeWorkerizedFunction, workerize } from '@be-music/shared-utils/workerize';
import { type BeMusicJSON, type BeMusicPlayLevel } from '@be-music/chart-source';
import {
decodeBMSText,
parseChart,
parseChartFile,
parseN2SBytes,
resolveBMSControlFlow,
resolveLRXHeaderPath,
} from '@be-music/chart-parser';
import { resolveChart, type ResolvedChart } from '@be-music/chart-model';
import {
estimateDifficultyFromNames,
estimateDifficultyFromNoteCount,
resolveDisplayedDifficultyValue,
resolveDisplayedJudgeRankLabel,
resolveDisplayedJudgeRankValue,
resolveDisplayedPlayLevelValue,
type DifficultyBasis,
type DisplayedDifficulty,
} from '@be-music/player-engine/display';
import { resolvePreviewContinueKeyFromChart } from './chart-preview.ts';
interface ChartSummaryItem {
filePath: string;
relativePath: string;
directoryLabel: string;
fileLabel: string;
title?: string;
subtitle?: string;
artist?: string;
subartist?: string;
genre?: string;
comment?: string;
bannerPath?: string;
previewContinueKey?: string;
totalNotes?: number;
player?: number;
difficulty?: number;
rank?: number;
rankLabel?: string;
playLevel?: BeMusicPlayLevel;
bpmInitial?: number;
bpmMin?: number;
bpmMax?: number;
}
type PersistedChartSummaryItem = Omit<ChartSummaryItem, 'filePath' | 'relativePath' | 'directoryLabel' | 'fileLabel'>;
interface PersistedChartSelectionCacheFileEntry {
contentHash: string;
cacheHash: string;
summary: PersistedChartSummaryItem;
}
interface PersistedChartSelectionCache {
format: typeof CHART_SELECTION_CACHE_FORMAT;
entries: Record<string, PersistedChartSelectionCacheFileEntry>;
}
interface ResolvedChartSummaryCacheEntry {
summary: ChartSummaryItem;
contentHash?: string;
cacheEntry?: PersistedChartSelectionCacheFileEntry;
cacheHit: boolean;
}
type WorkerizedChartSelectionEntriesBuilder = ((
summaries: ChartSummaryItem[],
callback: (error: unknown, result: ChartSelectionEntry[]) => void,
) => void) & { close: () => void };
export type ChartSelectionEntry =
| {
kind: 'random';
label: string;
}
| {
kind: 'group';
label: string;
}
| {
kind: 'chart';
filePath: string;
fileLabel: string;
title?: string;
subtitle?: string;
artist?: string;
subartist?: string;
genre?: string;
comment?: string;
bannerPath?: string;
previewContinueKey?: string;
totalNotes?: number;
player?: number;
difficulty?: number;
/** Where an estimated `difficulty` comes from (`resolveChartSummaryDifficulty`); absent for the chart's own. */
difficultyBasis?: Exclude<DifficultyBasis, 'chart'>;
rank?: number;
rankLabel?: string;
playLevel?: BeMusicPlayLevel;
bpmInitial?: number;
bpmMin?: number;
bpmMax?: number;
};
export interface ChartSummaryLoadingProgress {
filePath: string;
currentIndex: number;
totalCount: number;
}
export interface BuildChartSelectionEntriesOptions {
onLoadingFile?: (progress: ChartSummaryLoadingProgress) => void;
signal?: AbortSignal;
}
export interface ListChartFilesOptions {
signal?: AbortSignal;
}
const SELECTABLE_CHART_EXTENSIONS = new Set(['.bms', '.bme', '.bml', '.pms', '.bmson', '.n2s', '.lrs']);
const CHART_SELECTION_CACHE_FORMAT = 'be-music-player-chart-selection-cache/7';
const CHART_SELECTION_BUILD_CONCURRENCY = Math.max(1, Math.min(8, availableParallelism()));
let buildChartSelectionEntriesWorker: WorkerizedChartSelectionEntriesBuilder | undefined;
export async function listChartFiles(rootDir: string, options: ListChartFilesOptions = {}): Promise<string[]> {
const files: string[] = [];
const queue: string[] = [rootDir];
for (let index = 0; index < queue.length; index += 1) {
throwIfAborted(options.signal);
const current = queue[index]!;
const entries = await readdir(current, { withFileTypes: true });
for (const entry of entries) {
throwIfAborted(options.signal);
const absolute = resolve(current, entry.name);
if (entry.isDirectory()) {
queue.push(absolute);
continue;
}
Iif (!entry.isFile()) {
continue;
}
const dot = entry.name.lastIndexOf('.');
const extension = dot >= 0 ? entry.name.slice(dot).toLowerCase() : '';
if (SELECTABLE_CHART_EXTENSIONS.has(extension)) {
files.push(absolute);
}
}
}
files.sort((left, right) => left.localeCompare(right, 'ja'));
return files;
}
export async function buildChartSelectionEntries(
rootDir: string,
files: string[],
options: BuildChartSelectionEntriesOptions = {},
): Promise<ChartSelectionEntry[]> {
throwIfAborted(options.signal);
const cache = await loadPersistedChartSelectionCache();
const cachedEntries = cache.entries;
const nextCachedEntries: Record<string, PersistedChartSelectionCacheFileEntry> = { ...cachedEntries };
let cacheDirty = false;
let completedFileCount = 0;
const resolvedEntries = await mapWithConcurrency(
files,
Math.min(files.length || 1, CHART_SELECTION_BUILD_CONCURRENCY),
async (filePath) => {
throwIfAborted(options.signal);
const relativePath = resolveChartSummaryRelativePath(rootDir, filePath);
const resolvedEntry = await buildChartSummaryWithCache(
rootDir,
filePath,
relativePath,
cachedEntries,
options.signal,
);
completedFileCount += 1;
options.onLoadingFile?.({
filePath,
currentIndex: completedFileCount,
totalCount: files.length,
});
return resolvedEntry;
},
options.signal,
);
const summaries = resolvedEntries.map((entry) => entry.summary);
for (let index = 0; index < files.length; index += 1) {
const resolvedEntry = resolvedEntries[index]!;
if (!resolvedEntry.cacheHit) {
cacheDirty = true;
}
Eif (resolvedEntry.contentHash && resolvedEntry.cacheEntry) {
nextCachedEntries[resolvedEntry.contentHash] = resolvedEntry.cacheEntry;
}
}
if (cacheDirty) {
cache.entries = nextCachedEntries;
await savePersistedChartSelectionCache(cache);
}
throwIfAborted(options.signal);
return buildChartSelectionEntriesFromSummariesOffThread(summaries, options.signal);
}
async function buildChartSummaryWithCache(
rootDir: string,
filePath: string,
relativePath: string,
cachedEntries: Readonly<Record<string, PersistedChartSelectionCacheFileEntry>>,
signal?: AbortSignal,
): Promise<ResolvedChartSummaryCacheEntry> {
throwIfAborted(signal);
const pathFields = createChartSummaryPathFields(rootDir, filePath, relativePath);
let sourceBuffer: Buffer | undefined;
try {
sourceBuffer = await readFile(filePath, { signal });
} catch (error) {
if (isAbortError(error)) {
throw error;
}
}
// An LRX chart's title and levels live in the `.lrh` beside it, so its bytes take part in the hash.
const headerBuffer =
sourceBuffer && extname(filePath).toLowerCase() === '.lrs'
? await readFile(resolveLRXHeaderPath(filePath), { signal }).catch(() => undefined)
: undefined;
const contentHash = sourceBuffer ? buildChartSelectionContentHash(sourceBuffer, headerBuffer) : undefined;
const cachedEntry = typeof contentHash === 'string' ? cachedEntries[contentHash] : undefined;
if (
cachedEntry &&
typeof contentHash === 'string' &&
cachedEntry.contentHash === contentHash &&
isPersistedChartSelectionCacheFileEntryValid(cachedEntry)
) {
return {
summary: restoreChartSummary(pathFields, cachedEntry.summary),
cacheEntry: cachedEntry,
contentHash,
cacheHit: true,
};
}
const summary = await buildChartSummary(rootDir, filePath, signal, sourceBuffer);
return {
summary,
cacheEntry:
typeof contentHash === 'string'
? createPersistedChartSelectionCacheFileEntry(persistChartSummary(summary), contentHash)
: undefined,
contentHash,
cacheHit: false,
};
}
async function mapWithConcurrency<TInput, TOutput>(
items: readonly TInput[],
concurrency: number,
worker: (item: TInput, index: number) => Promise<TOutput>,
signal?: AbortSignal,
): Promise<TOutput[]> {
if (items.length === 0) {
return [];
}
const results: TOutput[] = [];
results.length = items.length;
let nextIndex = 0;
const workerCount = Math.max(1, Math.min(concurrency, items.length));
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (true) {
throwIfAborted(signal);
const currentIndex = nextIndex;
if (currentIndex >= items.length) {
return;
}
nextIndex += 1;
results[currentIndex] = await worker(items[currentIndex]!, currentIndex);
}
}),
);
return results;
}
async function buildChartSelectionEntriesFromSummariesOffThread(
summaries: ChartSummaryItem[],
signal?: AbortSignal,
): Promise<ChartSelectionEntry[]> {
if (summaries.length === 0) return [];
const activeWorker = (buildChartSelectionEntriesWorker ??= createBuildChartSelectionEntriesWorker());
try {
const result = await invokeWorkerizedFunction(activeWorker, [summaries], {
signal,
onAbort: () => discardChartSelectionWorker(activeWorker),
});
Iif (!Array.isArray(result)) {
return buildChartSelectionEntriesFromSummaries(summaries);
}
return result;
} catch (error) {
Iif (isAbortError(error)) {
throw error;
}
discardChartSelectionWorker(activeWorker);
return buildChartSelectionEntriesFromSummaries(summaries);
}
}
function discardChartSelectionWorker(activeWorker: WorkerizedChartSelectionEntriesBuilder): void {
Iif (buildChartSelectionEntriesWorker !== activeWorker) return;
buildChartSelectionEntriesWorker = undefined;
activeWorker.close();
}
function createBuildChartSelectionEntriesWorker(): WorkerizedChartSelectionEntriesBuilder {
return workerize(
(summaries: ChartSummaryItem[]) => buildChartSelectionEntriesFromSummaries(summaries),
() => [buildChartSelectionEntriesFromSummaries, compareOptionalNumber, compareOptionalPlayLevel],
true,
) as WorkerizedChartSelectionEntriesBuilder;
}
function buildChartSelectionEntriesFromSummaries(summariesInput: readonly ChartSummaryItem[]): ChartSelectionEntry[] {
const summaries = [...summariesInput];
summaries.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'ja'));
const groupedByDirectory = new Map<string, ChartSummaryItem[]>();
for (const summary of summaries) {
const group = groupedByDirectory.get(summary.directoryLabel);
if (group) {
group.push(summary);
continue;
}
groupedByDirectory.set(summary.directoryLabel, [summary]);
}
const directoryLabels = [...groupedByDirectory.keys()].sort((left, right) => {
Iif (left === '.') {
return right === '.' ? 0 : -1;
}
Eif (right === '.') {
return 1;
}
return left.localeCompare(right, 'ja');
});
const entries: ChartSelectionEntry[] = [{ kind: 'random', label: '[Random] Select a chart randomly' }];
for (const directoryLabel of directoryLabels) {
const charts = groupedByDirectory.get(directoryLabel);
Iif (!charts || charts.length === 0) {
continue;
}
const difficulties = new Map(charts.map((chart) => [chart, resolveChartSummaryDifficulty(chart)]));
const sortedCharts = [...charts].sort((left, right) => {
const playerDiff = compareOptionalNumber(left.player, right.player);
if (playerDiff !== 0) {
return playerDiff;
}
const difficultyDiff = compareOptionalNumber(difficulties.get(left)?.value, difficulties.get(right)?.value);
Iif (difficultyDiff !== 0) {
return difficultyDiff;
}
const playLevelDiff = compareOptionalPlayLevel(left.playLevel, right.playLevel);
Iif (playLevelDiff !== 0) {
return playLevelDiff;
}
const fileDiff = left.fileLabel.localeCompare(right.fileLabel, 'ja');
Eif (fileDiff !== 0) {
return fileDiff;
}
return left.relativePath.localeCompare(right.relativePath, 'ja');
});
entries.push({
kind: 'group',
label: directoryLabel === '.' ? '[Folder] (root)' : `[Folder] ${directoryLabel}`,
});
for (const chart of sortedCharts) {
const difficulty = difficulties.get(chart);
entries.push({
kind: 'chart',
filePath: chart.filePath,
fileLabel: chart.fileLabel,
title: chart.title,
subtitle: chart.subtitle,
artist: chart.artist,
subartist: chart.subartist,
genre: chart.genre,
comment: chart.comment,
bannerPath: chart.bannerPath,
previewContinueKey: chart.previewContinueKey,
totalNotes: chart.totalNotes,
player: chart.player,
difficulty: difficulty?.value,
...(difficulty !== undefined && difficulty.basis !== 'chart' ? { difficultyBasis: difficulty.basis } : {}),
rank: chart.rank,
rankLabel: chart.rankLabel,
playLevel: chart.playLevel,
bpmInitial: chart.bpmInitial,
bpmMin: chart.bpmMin,
bpmMax: chart.bpmMax,
});
}
}
return entries;
}
function compareOptionalNumber(left: number | undefined, right: number | undefined): number {
const hasLeft = typeof left === 'number' && Number.isFinite(left);
const hasRight = typeof right === 'number' && Number.isFinite(right);
if (hasLeft && hasRight) {
return left - right;
}
if (hasLeft) {
return -1;
}
Iif (hasRight) {
return 1;
}
return 0;
}
function compareOptionalPlayLevel(left: BeMusicPlayLevel | undefined, right: BeMusicPlayLevel | undefined): number {
const hasLeft = typeof left === 'number' ? Number.isFinite(left) : typeof left === 'string' && left.trim().length > 0;
const hasRight =
typeof right === 'number' ? Number.isFinite(right) : typeof right === 'string' && right.trim().length > 0;
Eif (hasLeft && hasRight) {
Eif (typeof left === 'number' && typeof right === 'number') {
return left - right;
}
if (typeof left === 'string' && typeof right === 'string') {
return left.localeCompare(right, 'ja');
}
return typeof left === 'number' ? -1 : 1;
}
if (hasLeft) {
return -1;
}
if (hasRight) {
return 1;
}
return 0;
}
async function buildChartSummary(
rootDir: string,
filePath: string,
signal?: AbortSignal,
sourceBuffer?: Buffer,
): Promise<ChartSummaryItem> {
throwIfAborted(signal);
const pathFields = createChartSummaryPathFields(rootDir, filePath);
let player: number | undefined;
let rank: number | undefined;
let rankLabel: string | undefined;
let playLevel: BeMusicPlayLevel | undefined;
let totalNotes: number | undefined;
let bpmInitial: number | undefined;
let bpmMin: number | undefined;
let bpmMax: number | undefined;
let title: string | undefined;
let subtitle: string | undefined;
let artist: string | undefined;
let subartist: string | undefined;
let genre: string | undefined;
let comment: string | undefined;
let bannerPath: string | undefined;
let previewContinueKey: string | undefined;
let difficulty: number | undefined;
try {
throwIfAborted(signal);
const chart =
extname(filePath).toLowerCase() === '.lrs'
? await parseChartFile(filePath, { signal })
: sourceBuffer
? parseChartSelectionSourceBuffer(filePath, sourceBuffer)
: await parseChartFileWithCacheMiss(filePath, signal);
throwIfAborted(signal);
const resolvedChart = resolveBMSControlFlow(chart, { random: () => 0 });
const resolved = resolveChart(resolvedChart, { chartPath: filePath });
throwIfAborted(signal);
title = sanitizeChartSelectionMetadataText(chart.metadata.title);
subtitle = sanitizeChartSelectionMetadataText(chart.metadata.subtitle);
artist = sanitizeChartSelectionMetadataText(chart.metadata.artist);
subartist = resolveChartSelectionSubartist(chart);
genre = sanitizeChartSelectionMetadataText(chart.metadata.genre);
comment = sanitizeChartSelectionMetadataText(chart.metadata.comment);
bannerPath = resolveChartSelectionBannerPath(chart);
// The notes a play scores: FREE ZONE tails are judged by nobody (mines and invisible objects are not notes).
totalNotes = resolved.notes.filter((note) => note.freeZone !== true).length;
player = chart.bms.player;
difficulty = resolveDisplayedDifficultyValue(chart);
rank = resolveDisplayedJudgeRankValue(resolved);
rankLabel = resolveDisplayedJudgeRankLabel(resolved);
playLevel = resolveDisplayedPlayLevelValue(chart);
const bpmSummary = extractChartBPMSummary(resolved);
bpmInitial = bpmSummary?.initial;
bpmMin = bpmSummary?.min;
bpmMax = bpmSummary?.max;
previewContinueKey = await resolvePreviewContinueKeyFromChart(resolvedChart, filePath, signal);
} catch (error) {
if (isAbortError(error)) {
throw error;
}
// Treat metadata-extraction failures as a display-only concern, decoupled from whether the
// chart can be played — the entry continues with the missing fields blank.
}
return {
...pathFields,
title,
subtitle,
artist,
subartist,
genre,
comment,
bannerPath,
previewContinueKey,
totalNotes,
player,
difficulty,
rank,
rankLabel,
playLevel,
bpmInitial,
bpmMin,
bpmMax,
};
}
async function parseChartFileWithCacheMiss(filePath: string, signal?: AbortSignal): Promise<BeMusicJSON> {
const sourceBuffer = await readFile(filePath, { signal });
return parseChartSelectionSourceBuffer(filePath, sourceBuffer);
}
function parseChartSelectionSourceBuffer(filePath: string, sourceBuffer: Buffer): BeMusicJSON {
const extension = extname(filePath).toLowerCase();
if (extension === '.bmson') {
return parseChart(decodeUTF8Buffer(sourceBuffer), 'bmson');
}
Iif (extension === '.json') {
return parseChart(decodeUTF8Buffer(sourceBuffer), 'json');
}
Iif (extension === '.n2s') {
return parseN2SBytes(sourceBuffer);
}
return parseChart(decodeBMSText(sourceBuffer).text);
}
function decodeUTF8Buffer(buffer: Buffer): string {
let text = buffer.toString('utf8');
Iif (text.charCodeAt(0) === 0xfeff) {
text = text.slice(1);
}
return text;
}
/**
* The difficulty a chart is listed, sorted and filtered under: its `#DIFFICULTY`; else the one its title, subtitle and
* file name suggest (`estimateDifficultyFromNames`); else the one its note count gives (`estimateDifficultyFromNoteCount`).
* The estimate is worked out here rather than kept in the persisted summary, so a cached summary picks up changes to
* the estimate's rules.
*/
export function resolveChartSummaryDifficulty(chart: {
difficulty?: number;
title?: string;
subtitle?: string;
fileLabel: string;
totalNotes?: number;
}): DisplayedDifficulty | undefined {
if (chart.difficulty !== undefined) {
return { value: chart.difficulty, basis: 'chart' };
}
const named = estimateDifficultyFromNames({
title: chart.title,
subtitle: chart.subtitle,
fileName: chart.fileLabel,
});
if (named !== undefined) {
return { value: named, basis: 'names' };
}
const counted = chart.totalNotes !== undefined ? estimateDifficultyFromNoteCount(chart.totalNotes) : undefined;
return counted !== undefined ? { value: counted, basis: 'notes' } : undefined;
}
function buildChartSelectionContentHash(sourceBuffer: Buffer, headerBuffer?: Buffer): string {
const hash = createHash('sha256').update(sourceBuffer);
Iif (headerBuffer) hash.update(headerBuffer);
return hash.digest('hex');
}
function buildChartSelectionCacheHash(entry: { contentHash: string; summary: PersistedChartSummaryItem }): string {
return createHash('sha256')
.update(
JSON.stringify([
entry.contentHash,
entry.summary.title ?? null,
entry.summary.subtitle ?? null,
entry.summary.artist ?? null,
entry.summary.subartist ?? null,
entry.summary.genre ?? null,
entry.summary.comment ?? null,
entry.summary.bannerPath ?? null,
entry.summary.previewContinueKey ?? null,
entry.summary.totalNotes ?? null,
entry.summary.player ?? null,
entry.summary.difficulty ?? null,
entry.summary.rank ?? null,
entry.summary.rankLabel ?? null,
entry.summary.playLevel ?? null,
entry.summary.bpmInitial ?? null,
entry.summary.bpmMin ?? null,
entry.summary.bpmMax ?? null,
]),
)
.digest('hex');
}
function createChartSummaryPathFields(
rootDir: string,
filePath: string,
relativePath = resolveChartSummaryRelativePath(rootDir, filePath),
): Pick<ChartSummaryItem, 'filePath' | 'relativePath' | 'directoryLabel' | 'fileLabel'> {
const slashIndex = relativePath.lastIndexOf('/');
return {
filePath,
relativePath,
directoryLabel: slashIndex >= 0 ? relativePath.slice(0, slashIndex) : '.',
fileLabel: slashIndex >= 0 ? relativePath.slice(slashIndex + 1) : relativePath,
};
}
function resolveChartSummaryRelativePath(rootDir: string, filePath: string): string {
return relative(rootDir, filePath).replaceAll('\\', '/');
}
function persistChartSummary(summary: ChartSummaryItem): PersistedChartSummaryItem {
const {
filePath: _filePath,
relativePath: _relativePath,
directoryLabel: _directoryLabel,
fileLabel: _fileLabel,
...persisted
} = summary;
return persisted;
}
function createPersistedChartSelectionCacheFileEntry(
summary: PersistedChartSummaryItem,
contentHash: string,
): PersistedChartSelectionCacheFileEntry {
return {
contentHash,
cacheHash: buildChartSelectionCacheHash({ contentHash, summary }),
summary,
};
}
function isPersistedChartSelectionCacheFileEntryValid(entry: PersistedChartSelectionCacheFileEntry): boolean {
return (
entry.cacheHash ===
buildChartSelectionCacheHash({
contentHash: entry.contentHash,
summary: entry.summary,
})
);
}
function restoreChartSummary(
pathFields: Pick<ChartSummaryItem, 'filePath' | 'relativePath' | 'directoryLabel' | 'fileLabel'>,
summary: PersistedChartSummaryItem,
): ChartSummaryItem {
return {
...pathFields,
...summary,
};
}
function sanitizeChartSelectionMetadataText(value: string | undefined): string | undefined {
if (typeof value !== 'string') {
return undefined;
}
const normalized = value.trim();
return normalized.length > 0 ? normalized : undefined;
}
function resolveChartSelectionSubartist(json: BeMusicJSON): string | undefined {
if (Array.isArray(json.bmson.info.subartists) && json.bmson.info.subartists.length > 0) {
const subartists = json.bmson.info.subartists
.map((value) => sanitizeChartSelectionMetadataText(value))
.filter((value): value is string => value !== undefined);
Eif (subartists.length > 0) {
return subartists.join(', ');
}
}
return sanitizeChartSelectionMetadataText(json.metadata.extras.SUBARTIST);
}
function resolveChartSelectionBannerPath(json: BeMusicJSON): string | undefined {
const bmsonBanner = sanitizeChartSelectionMetadataText(json.bmson.info.bannerImage);
if (bmsonBanner) {
return bmsonBanner;
}
const bmsBanner = sanitizeChartSelectionMetadataText(json.metadata.banner);
if (bmsBanner) {
return bmsBanner;
}
return sanitizeChartSelectionMetadataText(json.metadata.extras.BANNER);
}
function extractChartBPMSummary(resolved: ResolvedChart): { initial: number; min: number; max: number } | undefined {
const bpmValues = resolved.timing.tempoPoints
.map((point) => point.bpm)
.filter((value) => Number.isFinite(value) && value > 0);
Iif (bpmValues.length === 0) {
return undefined;
}
let min = bpmValues[0];
let max = bpmValues[0];
for (const bpm of bpmValues) {
if (bpm < min) {
min = bpm;
}
if (bpm > max) {
max = bpm;
}
}
return {
initial: bpmValues[0],
min,
max,
};
}
function resolveChartSelectionCachePath(): string {
return resolve(homedir(), '.be-music', 'chart-selection-cache.json');
}
function createDefaultPersistedChartSelectionCache(): PersistedChartSelectionCache {
return {
format: CHART_SELECTION_CACHE_FORMAT,
entries: {},
};
}
function parsePersistedChartSelectionCache(value: unknown): PersistedChartSelectionCache {
Iif (typeof value !== 'object' || value === null) {
return createDefaultPersistedChartSelectionCache();
}
const objectValue = value as {
format?: unknown;
entries?: unknown;
};
Iif (objectValue.format !== CHART_SELECTION_CACHE_FORMAT) {
return createDefaultPersistedChartSelectionCache();
}
Iif (typeof objectValue.entries !== 'object' || objectValue.entries === null) {
return createDefaultPersistedChartSelectionCache();
}
const entries: PersistedChartSelectionCache['entries'] = {};
for (const [_contentHashKey, rawEntry] of Object.entries(objectValue.entries as Record<string, unknown>)) {
Iif (typeof rawEntry !== 'object' || rawEntry === null) {
continue;
}
const fileEntry = rawEntry as {
contentHash?: unknown;
cacheHash?: unknown;
summary?: unknown;
};
Iif (typeof fileEntry.contentHash !== 'string' || fileEntry.contentHash.length === 0) {
continue;
}
Iif (typeof fileEntry.cacheHash !== 'string' || fileEntry.cacheHash.length === 0) {
continue;
}
Iif (typeof fileEntry.summary !== 'object' || fileEntry.summary === null) {
continue;
}
const summary = parsePersistedChartSummary(fileEntry.summary);
Iif (!summary) {
continue;
}
const parsedEntry: PersistedChartSelectionCacheFileEntry = {
contentHash: fileEntry.contentHash,
cacheHash: fileEntry.cacheHash,
summary,
};
if (!isPersistedChartSelectionCacheFileEntryValid(parsedEntry)) {
continue;
}
entries[parsedEntry.contentHash] = parsedEntry;
}
return {
format: CHART_SELECTION_CACHE_FORMAT,
entries,
};
}
async function loadPersistedChartSelectionCache(): Promise<PersistedChartSelectionCache> {
const cachePath = resolveChartSelectionCachePath();
let content: string;
try {
content = await readFile(cachePath, 'utf8');
} catch (error) {
Eif ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {
return createDefaultPersistedChartSelectionCache();
}
return createDefaultPersistedChartSelectionCache();
}
try {
return parsePersistedChartSelectionCache(JSON.parse(content));
} catch {
return createDefaultPersistedChartSelectionCache();
}
}
function parsePersistedChartSummary(value: unknown): PersistedChartSummaryItem | undefined {
Iif (typeof value !== 'object' || value === null) {
return undefined;
}
const objectValue = value as Record<string, unknown>;
const summary: PersistedChartSummaryItem = {};
assignOptionalString(summary, 'title', objectValue.title);
assignOptionalString(summary, 'subtitle', objectValue.subtitle);
assignOptionalString(summary, 'artist', objectValue.artist);
assignOptionalString(summary, 'subartist', objectValue.subartist);
assignOptionalString(summary, 'genre', objectValue.genre);
assignOptionalString(summary, 'comment', objectValue.comment);
assignOptionalString(summary, 'bannerPath', objectValue.bannerPath);
assignOptionalString(summary, 'previewContinueKey', objectValue.previewContinueKey);
assignOptionalNumber(summary, 'totalNotes', objectValue.totalNotes);
assignOptionalNumber(summary, 'player', objectValue.player);
assignOptionalNumber(summary, 'difficulty', objectValue.difficulty);
assignOptionalNumber(summary, 'rank', objectValue.rank);
assignOptionalString(summary, 'rankLabel', objectValue.rankLabel);
if (typeof objectValue.playLevel === 'number' && Number.isFinite(objectValue.playLevel)) {
summary.playLevel = objectValue.playLevel;
} else Eif (typeof objectValue.playLevel === 'string') {
summary.playLevel = objectValue.playLevel;
}
assignOptionalNumber(summary, 'bpmInitial', objectValue.bpmInitial);
assignOptionalNumber(summary, 'bpmMin', objectValue.bpmMin);
assignOptionalNumber(summary, 'bpmMax', objectValue.bpmMax);
return summary;
}
function assignOptionalString<TKey extends keyof PersistedChartSummaryItem>(
target: PersistedChartSummaryItem,
key: TKey,
value: unknown,
): void {
if (typeof value === 'string') {
target[key] = value as PersistedChartSummaryItem[TKey];
}
}
function assignOptionalNumber<TKey extends keyof PersistedChartSummaryItem>(
target: PersistedChartSummaryItem,
key: TKey,
value: unknown,
): void {
if (typeof value === 'number' && Number.isFinite(value)) {
target[key] = value as PersistedChartSummaryItem[TKey];
}
}
async function savePersistedChartSelectionCache(cache: PersistedChartSelectionCache): Promise<void> {
const cachePath = resolveChartSelectionCachePath();
try {
await mkdir(dirname(cachePath), { recursive: true });
await writeFile(cachePath, `${JSON.stringify(cache, null, 2)}\n`, 'utf8');
} catch {
// Chart list caching is a performance optimization only.
}
}
|