All files / app-leaderboard/src/api schemas.ts

100% Statements 36/36
100% Branches 0/0
100% Functions 4/4
100% Lines 35/35

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                  12x 2112x           12x   12x 60x   12x                       12x         12x                           12x                                                                                 12x 504x         12x         60x 12x   12x               12x                       12x                                               12x                         12x                             12x             12x   12x                                                               12x                             12x             12x                   12x                                                     12x                           12x                                 12x                     12x                                                                                   12x                               12x           12x             12x                   12x                                                            
import * as v from 'valibot';
import { RULESET_IDS } from '../rulesets.ts';
 
/**
 * Request and response schemas of `/api/v0`. The request schemas validate what comes in; the response schemas describe
 * what goes out. Both feed the OpenAPI document (`GET /api/v0/openapi.json`), so the document cannot drift from the
 * validation the routes run.
 */
 
const described = <T extends v.GenericSchema>(schema: T, description: string) =>
  v.pipe(schema, v.description(description));
 
// ---------------------------------------------------------------------------------------------------------------------
// Requests
// ---------------------------------------------------------------------------------------------------------------------
 
export const rulesetSchema = described(v.picklist(RULESET_IDS), 'Ruleset the figures are simulated under.');
 
const flagSchema = (description: string) =>
  v.optional(described(v.picklist(['0', '1', 'true', 'false']), description), '0');
 
export const rankingQuery = v.object({
  ruleset: rulesetSchema,
  assisted: flagSchema('Rank assisted plays (their own ranking) instead of unassisted ones.'),
  anonymous: flagSchema('Include anonymous players.'),
  played: flagSchema('Only players who played the chart under this ruleset at least once.'),
  offset: v.optional(described(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(0)), 'Entries to skip.'), '0'),
  limit: v.optional(
    described(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1), v.maxValue(100)), 'Entries to return.'),
    '50',
  ),
});
 
export const myRankQuery = v.object({
  ruleset: rulesetSchema,
  assisted: flagSchema('My rank among assisted plays instead of unassisted ones.'),
});
 
export const submissionBody = v.object({
  replay: described(v.unknown(), 'The replay (`be-music-replay`, docs/replay.md).'),
  playDocument: described(
    v.unknown(),
    'Fingerprint document of the played chart (the rolled branches); it must hash to `chart.playFingerprint`.',
  ),
  chartDocument: v.optional(
    described(
      v.unknown(),
      'Fingerprint document of the whole chart (every branch). Required the first time the server sees the chart.',
    ),
  ),
});
 
export const courseSubmissionBody = v.object({
  courseReplay: described(v.unknown(), 'The course replay (`be-music-course-replay`, docs/replay.md).'),
  stages: described(
    v.array(
      v.object({
        playDocument: described(
          v.unknown(),
          'Fingerprint document of the stage chart as played; it must hash to the stage’s `chart.playFingerprint`.',
        ),
        chartDocument: v.optional(
          described(
            v.unknown(),
            'Fingerprint document of the whole stage chart. Required the first time the server sees the chart.',
          ),
        ),
      }),
    ),
    'The fingerprint documents of each played stage, in the order the stages were played. Empty for a NONSTOP run, whose stages are rebuilt from `stageCharts`.',
  ),
  stageCharts: v.optional(
    described(
      v.array(
        v.object({
          stage: described(v.pipe(v.number(), v.integer(), v.minValue(0)), 'The course stage, zero-based.'),
          chart: described(
            v.unknown(),
            'The stage chart as loaded (`BeMusicJSON`, `#RANDOM` still in); it must hash to the stage’s chart fingerprint. Used to verify the run, never stored.',
          ),
          pms: v.optional(described(v.boolean(), 'Whether the chart is a `.pms` file (a lane-mode input).')),
        }),
      ),
      'The charts of the stages the server rebuilds: every stage the run never reached (their notes count as BP), and every stage of a NONSTOP run (stitched again to verify the play).',
    ),
  ),
});
 
// ---------------------------------------------------------------------------------------------------------------------
// Responses
// ---------------------------------------------------------------------------------------------------------------------
 
/** Every error answers `{ error }`, a stable kebab-case code, plus a `detail` for some. */
export const errorResponse = (codes: readonly [string, ...string[]]) =>
  v.object({
    error: described(v.picklist(codes), 'Error code.'),
    detail: v.optional(described(v.string(), 'Human-readable detail, for some errors.')),
  });
 
const clearLamp = described(
  v.pipe(v.number(), v.integer(), v.minValue(0)),
  'Clear lamp, by its stored rank: 0 NO PLAY, 1 FAILED, 2 ASSIST EASY, 3 EASY, 4 CLEAR, 5 HARD, 6 EX HARD, 7 FULL COMBO, 8 PERFECT, 9 MAX, ' +
    '10 LIGHT ASSIST EASY. Ranks are append-only, not an order: LIGHT ASSIST EASY sits between ASSIST EASY and EASY.',
);
const epochMs = (description: string) => described(v.pipe(v.number(), v.integer()), `${description} (epoch ms).`);
const player = v.object({ handle: v.string(), displayName: v.string() });
 
export const accountResponse = v.object({
  handle: v.string(),
  displayName: v.string(),
  anonymous: described(v.boolean(), 'True until the account has a way back in (a passkey).'),
  passkeys: v.pipe(v.number(), v.integer()),
  avatarUrl: described(v.string(), 'The player icon: the uploaded one, or one generated from the account.'),
});
 
export const profileUpdateBody = v.object({
  handle: v.optional(
    described(
      v.string(),
      'New handle: letters, digits and `_`, 3 to 15 characters, case-insensitive. The old handle stays reserved for the player and its pages redirect.',
    ),
  ),
  displayName: v.optional(
    described(v.string(), 'New display name: 1 to 32 characters, no line breaks or control characters.'),
  ),
});
 
const rulesetOutcome = v.object({
  ruleset: rulesetSchema,
  rulesetRevision: described(v.string(), 'Revision of the ruleset the play was simulated under (`lr2/0`, ...).'),
  exScore: v.pipe(v.number(), v.integer()),
  noteCount: v.pipe(v.number(), v.integer()),
  clearLamp,
  missCount: described(v.pipe(v.number(), v.integer()), 'BP: BADs plus POORs.'),
  rank: described(
    v.pipe(v.number(), v.integer()),
    'The player’s rank on the chart after this play; 0 (and `players` 0) for an unranked play.',
  ),
  players: v.pipe(v.number(), v.integer()),
  improved: described(
    v.object({ exScore: v.boolean(), lamp: v.boolean(), missCount: v.boolean() }),
    'Which personal bests this play improved.',
  ),
  outcome: v.optional(
    described(
      v.picklist(['truncated']),
      'The play stopped where its played gauge emptied, and this ruleset’s gauge would have carried on: the figures go only up to that point, and it is not ranked (ADR 0019). Absent for a play simulated in full.',
    ),
  ),
});
 
const notSimulated = described(
  v.array(
    v.object({
      ruleset: rulesetSchema,
      reason: described(
        v.picklist(['gauge', 'custom-judge']),
        'Why: the gauge is not one the ruleset defines, or CUSTOM JUDGE (beatoraja only) has no reading under it.',
      ),
    }),
  ),
  'The rulesets the play cannot be judged under, with no figures (ADR 0019); absent when every ruleset judged it.',
);
 
export const submissionResponse = v.object({
  scoreId: v.string(),
  chartFingerprint: described(v.string(), 'Chart fingerprint (`bmfp0:…`), the ranking key.'),
  results: described(v.array(rulesetOutcome), 'The play under every ruleset that could judge it.'),
  notSimulated: v.optional(notSimulated),
  unranked: v.optional(
    described(
      v.picklist(['tempo', 'course-stage', 'bmson-total', 'no-save']),
      'Why the play was stored without ranking it: another tempo, a standalone course stage, bmson zero-total no recovery, ' +
        'or an option whose source saves no data from the play (no-save). ' +
        'It moves no personal best and stays out of the rankings and lists.',
    ),
  ),
});
 
export const scoreVisibilityBody = v.object({
  hidden: described(
    v.boolean(),
    'Hide the play (`true`): it leaves the rankings, the personal bests, the figures and every list, and only its player can open it. `false` shows it again.',
  ),
});
 
export const scoreVisibilityResponse = v.object({ id: v.string(), hidden: v.boolean() });
 
export const scoreResponse = v.object({
  id: v.string(),
  chartFingerprint: v.string(),
  playFingerprint: described(v.string(), 'Fingerprint of the branches this play rolled.'),
  player: v.nullable(player),
  playedRuleset: rulesetSchema,
  gauge: v.string(),
  assisted: v.boolean(),
  assistFlags: v.array(v.string()),
  verification: described(v.string(), 'Highest verification layer passed (`L3`, `L4`, ...).'),
  createdAt: epochMs('When the play was accepted'),
  hidden: described(v.boolean(), 'Hidden by its player: only the player sees a hidden play.'),
  results: v.array(
    v.object({
      ruleset: rulesetSchema,
      rulesetRevision: v.string(),
      exScore: v.pipe(v.number(), v.integer()),
      noteCount: v.pipe(v.number(), v.integer()),
      clearLamp,
      missCount: v.pipe(v.number(), v.integer()),
      maxCombo: v.pipe(v.number(), v.integer()),
      gaugeType: v.string(),
      gaugeFinal: described(v.nullable(v.number()), 'Gauge at the end of the play, in percent.'),
      judges: described(v.record(v.string(), v.number()), 'Judgment counts.'),
      outcome: described(
        v.nullable(v.picklist(['truncated'])),
        '`truncated` for figures judged only up to where the play stopped (ADR 0019); null for a full simulation.',
      ),
    }),
  ),
});
 
const rankingEntry = v.object({
  rank: described(v.pipe(v.number(), v.integer()), 'Competition rank: ties share a rank.'),
  handle: v.string(),
  displayName: v.string(),
  anonymous: v.boolean(),
  avatarUrl: v.string(),
  exScore: v.pipe(v.number(), v.integer()),
  exScoreId: described(v.string(), 'The score that set the best EX-Score.'),
  clearLamp,
  missCount: v.pipe(v.number(), v.integer()),
  playCount: v.pipe(v.number(), v.integer()),
  playedHere: described(v.boolean(), 'Played under this ruleset at least once.'),
  achievedAt: epochMs('When the best EX-Score was set'),
});
 
export const rankingResponse = v.object({
  entries: v.array(rankingEntry),
  players: described(v.pipe(v.number(), v.integer()), 'Players matching the filters.'),
  offset: v.pipe(v.number(), v.integer()),
  limit: v.pipe(v.number(), v.integer()),
});
 
export const myRankResponse = v.object({
  rank: v.pipe(v.number(), v.integer()),
  players: v.pipe(v.number(), v.integer()),
  exScore: v.pipe(v.number(), v.integer()),
  exScoreId: v.string(),
  clearLamp: described(v.pipe(v.number(), v.integer()), 'Best clear lamp (see the score results).'),
  missCount: described(v.pipe(v.number(), v.integer()), 'Fewest BP.'),
  playCount: v.pipe(v.number(), v.integer()),
});
 
const courseRulesetOutcome = v.object({
  ruleset: rulesetSchema,
  rulesetRevision: described(v.string(), 'Revision of the ruleset the run was simulated under (`lr2/0`, ...).'),
  exScore: v.pipe(v.number(), v.integer()),
  noteCount: described(v.pipe(v.number(), v.integer()), 'Judgment notes over every stage, reached or not.'),
  clearLamp,
  missCount: described(v.pipe(v.number(), v.integer()), 'BP, with every note the run never judged.'),
  maxCombo: described(v.pipe(v.number(), v.integer()), 'The course-wide max combo.'),
  stagesPlayed: described(v.pipe(v.number(), v.integer()), 'Stages reached under this ruleset.'),
  trophy: described(v.nullable(v.string()), 'The best trophy the run earned, by name.'),
  rank: described(
    v.pipe(v.number(), v.integer()),
    'The player’s rank on the course after this run; 0 (and `players` 0) for an unranked run.',
  ),
  players: v.pipe(v.number(), v.integer()),
  improved: described(
    v.object({ exScore: v.boolean(), lamp: v.boolean(), missCount: v.boolean(), trophy: v.boolean() }),
    'Which personal bests on the course this run improved.',
  ),
  outcome: v.optional(
    described(
      v.picklist(['truncated']),
      'The run stopped at a failed stage, and this ruleset’s gauge would have carried on: the figures go only up to that point, and it is not ranked (ADR 0019). Absent for a run simulated in full.',
    ),
  ),
});
 
export const courseSubmissionResponse = v.object({
  courseScoreId: v.string(),
  courseFingerprint: described(v.string(), 'Course fingerprint (`bmcourse0:…`), the ranking key.'),
  results: described(v.array(courseRulesetOutcome), 'The run under every ruleset that could judge it.'),
  notSimulated: v.optional(notSimulated),
  unranked: v.optional(
    described(
      v.picklist(['tempo', 'unreleased', 'bmson-total', 'assist']),
      'Why the run was stored without ranking it (including bmson zero-total no recovery): a stage played at another tempo, a course that is not ' +
        'released (a made or a drawn random course), or a stage played with an assist option (assist). It moves no course best and stays out of the rankings and lists.',
    ),
  ),
});
 
export const courseResponse = v.object({
  courseFingerprint: v.string(),
  name: described(v.string(), 'The name the course was first submitted with.'),
  kind: described(v.picklist(['grade', 'expert', 'nonstop']), 'Course kind.'),
  constraints: described(v.array(v.string()), 'Constraints, normalized and sorted (`gauge_lr2`, `grade_mirror`, ...).'),
  stages: v.array(
    v.object({
      chartFingerprint: v.string(),
      title: described(v.nullable(v.string()), 'Null while the server has not seen the chart played.'),
      artist: v.nullable(v.string()),
      playLevel: v.nullable(v.string()),
      laneMode: described(v.nullable(v.string()), 'Lane mode (`7keys`, `14keys`, ...), null while unknown.'),
    }),
  ),
  createdAt: epochMs('When the first run was accepted'),
});
 
const courseStageFigures = v.object({
  exScore: v.pipe(v.number(), v.integer()),
  noteCount: v.pipe(v.number(), v.integer()),
  missCount: described(v.pipe(v.number(), v.integer()), 'BP, with the notes the stage never judged.'),
  maxCombo: v.pipe(v.number(), v.integer()),
  judges: described(v.record(v.string(), v.number()), 'Judgment counts, with `fast` and `slow`.'),
  gaugeType: v.string(),
  gaugeFinal: described(v.number(), 'Gauge the stage ended on, in percent.'),
  cleared: v.boolean(),
});
 
export const courseScoreResponse = v.object({
  id: v.string(),
  courseFingerprint: v.string(),
  player: v.nullable(player),
  playedRuleset: rulesetSchema,
  gauge: v.string(),
  assisted: v.boolean(),
  assistFlags: v.array(v.string()),
  verification: described(v.string(), 'Lowest verification layer its stages passed (`L3`, `L4`, ...).'),
  stagesPlayed: described(v.pipe(v.number(), v.integer()), 'Stages the run played.'),
  createdAt: epochMs('When the run was accepted'),
  hidden: v.boolean(),
  results: v.array(
    v.object({
      ruleset: rulesetSchema,
      rulesetRevision: v.string(),
      exScore: v.pipe(v.number(), v.integer()),
      noteCount: v.pipe(v.number(), v.integer()),
      clearLamp,
      missCount: v.pipe(v.number(), v.integer()),
      maxCombo: v.pipe(v.number(), v.integer()),
      stagesPlayed: v.pipe(v.number(), v.integer()),
      trophy: v.nullable(v.string()),
      trophyRank: described(
        v.pipe(v.number(), v.integer()),
        'Where the trophy stands in the run’s course definition, easiest first: 1 for the first, 0 for none.',
      ),
      gaugeType: v.string(),
      gaugeFinal: described(v.number(), 'Gauge the course ended on, in percent.'),
      judges: described(v.record(v.string(), v.number()), 'Judgment counts over the stages played.'),
      stages: described(
        v.nullable(v.array(courseStageFigures)),
        'Each reached stage’s own figures, in order; null for runs stored before they were kept.',
      ),
      outcome: described(
        v.nullable(v.picklist(['truncated'])),
        '`truncated` for figures judged only up to where the run stopped (ADR 0019); null for a full simulation.',
      ),
    }),
  ),
});
 
export const courseRankingResponse = v.object({
  ...rankingResponse.entries,
  entries: v.array(
    v.object({
      ...rankingEntry.entries,
      exScoreId: described(v.string(), 'The course run that set the best EX-Score.'),
      noteCount: described(
        v.pipe(v.number(), v.integer()),
        'Judgment notes of the course under this ruleset, the DJ LEVEL’s scale.',
      ),
      trophy: described(v.nullable(v.string()), 'The best trophy the player earned on the course, by name.'),
      trophyScoreId: described(v.nullable(v.string()), 'The course run that earned it.'),
    }),
  ),
});
 
export const myCourseRankResponse = v.object({
  ...myRankResponse.entries,
  trophy: described(v.nullable(v.string()), 'My best trophy on the course, by name.'),
  trophyScoreId: described(v.nullable(v.string()), 'The course run that earned it.'),
});
 
export const courseVisibilityBody = v.object({
  hidden: described(
    v.boolean(),
    'Hide the run (`true`): it leaves the course rankings, the personal bests, the figures and every list, and only its player can open it. `false` shows it again.',
  ),
});
 
export const courseRunsQuery = v.object({
  ruleset: rulesetSchema,
  player: v.optional(described(v.string(), 'Only this player’s runs, by handle; anonymous or not.')),
  anonymous: flagSchema('Include anonymous players’ runs.'),
  limit: v.optional(
    described(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1), v.maxValue(100)), 'Runs to return.'),
    '50',
  ),
});
 
export const courseRunsResponse = v.object({
  runs: v.array(
    v.object({
      id: v.string(),
      createdAt: epochMs('When the run was accepted'),
      courseFingerprint: v.string(),
      courseName: v.string(),
      courseKind: v.picklist(['grade', 'expert', 'nonstop']),
      stageCount: described(v.pipe(v.number(), v.integer()), 'Stages of the course.'),
      handle: v.string(),
      displayName: v.string(),
      anonymous: v.boolean(),
      avatarUrl: v.string(),
      playedRuleset: rulesetSchema,
      assisted: v.boolean(),
      hidden: described(v.boolean(), 'Hidden by its player: listed only to the player.'),
      exScore: v.pipe(v.number(), v.integer()),
      noteCount: v.pipe(v.number(), v.integer()),
      clearLamp,
      missCount: v.pipe(v.number(), v.integer()),
      stagesPlayed: described(v.pipe(v.number(), v.integer()), 'Stages reached under this ruleset.'),
      trophy: v.nullable(v.string()),
      rank: described(
        v.pipe(v.number(), v.integer()),
        'Where the run’s EX-Score stands among the other players’ bests on the course.',
      ),
      players: v.pipe(v.number(), v.integer()),
    }),
  ),
});