All files / player-engine/src/course beatoraja.ts

91.8% Statements 56/61
88.31% Branches 68/77
93.33% Functions 14/15
98% Lines 49/50

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                          244x     607x               197x 197x 197x 197x 183x 183x 396x 396x 396x 396x 396x 395x   182x 182x                                 17x 17x   2x   15x 23x                 9x 9x 9x 12x 12x 12x         9x 7x 7x         3x                           8x 8x 8x   8x   6x 8x 8x                   5x 5x   1x   4x 7x 4x                 1x 2x 1x   2x                         1x    
import {
  type CourseDefinition,
  type CourseStageRef,
  courseConstraintEnumName,
  createCourseStageRef,
  isClassCourseConstraints,
  normalizeCourseConstraints,
  normalizeCourseTrophies,
  type RandomCourseDefinition,
  type RandomCourseStage,
} from './definition.ts';
import { decodeCourseText } from './text.ts';
 
const DEFAULT_COURSE_NAME = 'No Course Title';
 
function asArray(value: unknown): unknown[] {
  return Array.isArray(value) ? value : [];
}
 
/**
 * One beatoraja `CourseData` object, validated as `CourseData.validate` does: at least one stage, every stage with
 * an `md5` or a `sha256` (a missing title becomes `course N`), unknown constraints dropped and one kept per group.
 */
export function parseBeatorajaCourseData(value: unknown): CourseDefinition | undefined {
  Iif (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;
  const data = value as Record<string, unknown>;
  const chartEntries = asArray(data.hash);
  if (chartEntries.length === 0) return undefined;
  const stages: CourseStageRef[] = [];
  for (const [index, chartEntry] of chartEntries.entries()) {
    Iif (chartEntry === null || typeof chartEntry !== 'object') return undefined;
    const fields = chartEntry as Record<string, unknown>;
    const title = typeof fields.title === 'string' && fields.title.length > 0 ? fields.title : `course ${index + 1}`;
    const stage = createCourseStageRef({ ...fields, title });
    if (stage === undefined) return undefined;
    stages.push(stage);
  }
  const constraints = normalizeCourseConstraints(asArray(data.constraint));
  return {
    name: typeof data.name === 'string' && data.name.length > 0 ? data.name : DEFAULT_COURSE_NAME,
    kind: isClassCourseConstraints(constraints) ? 'grade' : 'expert',
    stages,
    constraints,
    trophies: normalizeCourseTrophies(asArray(data.trophy)),
    release: data.release !== false,
    source: { format: 'beatoraja-json' },
  };
}
 
/**
 * Parses a beatoraja `course/*.json` file: an array of `CourseData`, or a single object (beatoraja's fallback read).
 * Invalid courses are skipped; a file that is not JSON gives no course.
 */
export function parseBeatorajaCourseFile(input: Uint8Array | string): CourseDefinition[] {
  let json: unknown;
  try {
    json = JSON.parse(typeof input === 'string' ? input : decodeCourseText(input));
  } catch {
    return [];
  }
  const items = Array.isArray(json) ? json : [json];
  return items.map(parseBeatorajaCourseData).filter((course) => course !== undefined);
}
 
/**
 * One beatoraja `RandomCourseData` (an entry of a command folder's `rcourse` list): `name`, `stage[]` (`sql` and
 * `title`), `constraint`, `rconstraint` (`distinct`) and `trophy`. Stages keep their SQL filter as written;
 * `drawRandomCourse` draws the charts.
 */
export function parseBeatorajaRandomCourseData(value: unknown): RandomCourseDefinition | undefined {
  Iif (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;
  const data = value as Record<string, unknown>;
  const stages = asArray(data.stage).map((stage): RandomCourseStage => {
    const fields = stage !== null && typeof stage === 'object' ? (stage as Record<string, unknown>) : {};
    const { sql, title } = fields;
    return {
      ...(typeof sql === 'string' && sql.trim().length > 0 ? { filter: sql.trim() } : {}),
      ...(typeof title === 'string' && title.length > 0 ? { title } : {}),
    };
  });
  if (stages.length === 0) return undefined;
  const rconstraints = asArray(data.rconstraint);
  return {
    name: typeof data.name === 'string' && data.name.length > 0 ? data.name : DEFAULT_COURSE_NAME,
    stages,
    constraints: normalizeCourseConstraints(asArray(data.constraint)),
    trophies: normalizeCourseTrophies(asArray(data.trophy)),
    distinct: rconstraints.some((name) => name === 'distinct' || name === 'DISTINCT'),
  };
}
 
/**
 * The random courses of one beatoraja command folder, under its name: nested folders joined with ` > `, and
 * `RANDOM COURSE` for a folder without a name.
 */
export interface BeatorajaRandomCourseFolder {
  name: string;
  courses: RandomCourseDefinition[];
}
 
function collectRandomCourseFolders(value: unknown, parents: string[], out: BeatorajaRandomCourseFolder[]): void {
  Iif (value === null || typeof value !== 'object' || Array.isArray(value)) return;
  const data = value as Record<string, unknown>;
  const path = typeof data.name === 'string' && data.name.length > 0 ? [...parents, data.name] : parents;
  // beatoraja reads `folder/default.json` with libGDX's `JSON`, which maps keys onto field names: `rcourse`.
  const courses = asArray(data.rcourse)
    .map(parseBeatorajaRandomCourseData)
    .filter((course) => course !== undefined);
  if (courses.length > 0) out.push({ name: path.length > 0 ? path.join(' > ') : 'RANDOM COURSE', courses });
  for (const child of asArray(data.folder)) collectRandomCourseFolders(child, path, out);
}
 
/**
 * Reads beatoraja's command-folder file (`folder/default.json`, `BarManager.CommandFolder[]`) for its random
 * courses: each folder's `rcourse` list, nested `folder`s included. Folders without a random course (plain SQL folders)
 * are left out; a file that is not JSON gives none.
 */
export function parseBeatorajaCommandFolderFile(input: Uint8Array | string): BeatorajaRandomCourseFolder[] {
  let json: unknown;
  try {
    json = JSON.parse(typeof input === 'string' ? input : decodeCourseText(input));
  } catch {
    return [];
  }
  const folders: BeatorajaRandomCourseFolder[] = [];
  for (const folder of Array.isArray(json) ? json : [json]) collectRandomCourseFolders(folder, [], folders);
  return folders;
}
 
/**
 * Writes courses as a beatoraja `course/*.json` file (an array of `CourseData`) that `parseBeatorajaCourseFile` reads
 * back: each stage's `md5` / `sha256` and title, the constraints by beatoraja's enum names, the trophies and `release`.
 * beatoraja has no NONSTOP course, so NONSTOP courses are left out.
 */
export function serializeBeatorajaCourseFile(courses: readonly CourseDefinition[]): string {
  const data = courses
    .filter((course) => course.kind !== 'nonstop')
    .map((course) => ({
      name: course.name,
      hash: course.stages.map((stage) => ({
        ...(stage.title !== undefined ? { title: stage.title } : {}),
        ...(stage.md5 !== undefined ? { md5: stage.md5 } : {}),
        ...(stage.sha256 !== undefined ? { sha256: stage.sha256 } : {}),
      })),
      constraint: course.constraints.map(courseConstraintEnumName),
      trophy: course.trophies.map((trophy) => ({
        name: trophy.name,
        missrate: trophy.missRate,
        scorerate: trophy.scoreRate,
      })),
      release: course.release,
    }));
  return `${JSON.stringify(data, null, 2)}\n`;
}