All files / chart-parser/src/core bms-json-document.ts

96.49% Statements 385/399
87.28% Branches 453/519
90% Functions 18/20
96.93% Lines 379/391

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                                                73x 73x 73x 73x 73x 73x                 73x 73x 73x 73x 3x   73x       73x 17x       17x 18x 73x       73x 73x 73x 73x 9x 3x 6x 6x 11x 3x 8x   3x   67x         67x 1x   66x 66x 66x 66x 62x 62x 62x       62x       62x   62x 34x 34x 1x 1x   1x   33x 2x 2x 2x   2x   31x 1x 1x 1x   1x   30x 1x     1x 1x   1x   29x 1x 1x 1x   1x   28x 1x 1x 1x   1x   27x 1x 1x 1x   1x   26x 1x 1x   1x   25x 1x 1x 1x   1x   24x 1x 1x   1x   23x 1x 1x 1x   1x   22x 1x     1x 1x   1x 1x     1x   21x 1x 1x   1x   20x 1x 1x   1x   19x 1x 1x   1x   18x 1x 1x   1x   17x 1x 1x   1x   16x 1x 1x   1x       15x 15x 2x 2x 2x 1x   2x     13x 13x 1x 1x 1x   1x     12x 12x 1x 1x 1x   1x     11x 11x 1x 1x 1x   1x     10x 10x 1x 1x 1x   1x     9x 9x 1x 1x 1x   1x     8x 8x 1x 1x 1x   1x     7x 7x 1x 1x 1x   1x     6x 6x 1x 1x 1x 1x   1x     5x 5x 1x 1x 1x 1x   1x     4x 4x 1x 1x 1x   1x     3x     62x       66x                               66x 1x     65x     65x 10x   65x 66x 63x 63x 46x 46x 46x     63x     65x 1x     65x 65x 1x     65x 66x 1x     65x 66x 4x     65x 66x 2x     65x 65x 1x     65x 65x   65x 65x 1x     65x 66x 2x     65x 66x 3x     65x   65x 8x     65x 18x 4x 6x 6x 1x   61x   61x 66x 1x       61x 66x 1x     61x         66x 66x         66x     66x 61x         66x 66x 66x 66x           66x 66x 2x     61x 66x 1x     61x 66x 1x     61x 1x     61x 66x 1x     61x 1x   61x         4x   10x         61x       62x   62x   62x           62x           62x 62x 57x 57x 147x 147x 147x     57x     62x 62x 56x 56x 31x 31x 31x     56x     62x 62x 62x 62x 62x 3x   62x         62x       4250x 3852x   398x 381x   17x 17x               496x 30x     466x 466x 15x 15x 14x 14x   1x 1x     466x               122x 8x     114x 114x 3851x 3851x 3851x     114x       252x     252x 74x     178x 178x 10x 9x     178x       193x     193x 193x 193x 59x 59x       59x         59x           134x 97x     97x     97x 97x 97x               37x 37x 37x     37x                 68x     68x 68x     68x 68x   68x 68x     128x           128x 128x 128x 128x       68x       68x         68x              
import {
  type BMSControlFlowEntry,
  type BMSObjectLineEntry,
  type BMSSourceLineEntry,
  type BeMusicEvent,
  type BeMusicJSON,
  createEmptyJSON,
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
} from '@be-music/chart-source';
import { buildBMSObjectLineEntry, sortAndNormalizeEvents } from './event-utils.ts';
import {
  normalizeBmsonBPMEvents,
  normalizeBmsonExtensions,
  normalizeBmsonLines,
  normalizeBmsonScrollEvents,
  normalizeBmsonSoundChannels,
  normalizeBmsonStopEvents,
} from './bmson.ts';
import { normalizeControlFlowCommand } from './control-flow.ts';
import { normalizeLRXExtensions } from './lrx-extensions.ts';
 
export function parseJSONDocument(raw: Partial<BeMusicJSON>): BeMusicJSON {
  const json = createEmptyJSON(raw.sourceFormat ?? 'json');
  const structured = raw as Record<string, unknown>;
  const rawBMS = structured.bms;
  const rawBmson = structured.bmson;
  json.sourceFormat = raw.sourceFormat ?? 'json';
  json.metadata = {
    ...json.metadata,
    ...raw.metadata,
    extras: {
      ...json.metadata.extras,
      ...(raw.metadata as { extras?: Record<string, string> } | undefined)?.extras,
    },
  };
  // Accept the former IR spelling on input, but emit only the canonical key.
  const metadata = raw.metadata as Record<string, unknown> | undefined;
  const backBMP = metadata?.backBMP ?? metadata?.backBmp;
  delete (json.metadata as unknown as Record<string, unknown>).backBmp;
  if (typeof backBMP === 'string') {
    json.metadata.backBMP = backBMP;
  }
  json.resources = {
    ...json.resources,
    ...raw.resources,
  };
  json.measures = (raw.measures ?? [])
    .map((measure) => ({
      index: Number.isFinite(measure.index) ? Number(measure.index) : 0,
      length: Number.isFinite(measure.length) && (measure.length ?? 0) > 0 ? Number(measure.length) : 1,
    }))
    .filter((measure) => measure.length > 0)
    .sort((left, right) => left.index - right.index);
  const rawEvents = Array.isArray(raw.events) ? raw.events : [];
  // When re-parsing a previously-emitted BMS-JSON, honor the chart's recorded base so case-sensitive base-62 IDs don't
  // get folded back to uppercase. The full `bms` extension is normalized a few lines below; we only need the `base`
  // hint here.
  const rawBMSBase = (rawBMS as { base?: unknown } | undefined)?.base;
  const reparseBase: 36 | 62 = rawBMSBase === 62 ? 62 : 36;
  const rawGains: unknown = raw.resources?.wavGain;
  if (rawGains !== undefined) {
    if (rawGains === null || typeof rawGains !== 'object' || Array.isArray(rawGains))
      throw new TypeError('resources.wavGain must be a slot-to-gain map');
    const gains: Record<string, number> = {};
    for (const [key, gain] of Object.entries(rawGains)) {
      if (typeof gain !== 'number' || !Number.isFinite(gain) || gain < 0)
        throw new TypeError(`resources.wavGain.${key} must be finite and nonnegative`);
      gains[normalizeObjectKey(key, reparseBase, json.sourceFormat === 'bmson')] = gain;
    }
    json.resources.wavGain = gains;
  }
  json.events = sortAndNormalizeEvents(
    rawEvents as Array<BeMusicEvent | Record<string, unknown>>,
    reparseBase,
    json.sourceFormat === 'bmson',
  );
  if (json.events.length !== rawEvents.length) {
    throw new Error('Invalid bms-json event: position [numerator, denominator] is required.');
  }
  json.bms = normalizeBMSExtensions(rawBMS, json.sourceFormat === 'bmson');
  json.bmson = normalizeBmsonExtensions(rawBmson);
  const lrx = normalizeLRXExtensions(structured.lrx);
  if (lrx) json.lrx = lrx;
  json.preservation = normalizePreservation(structured.preservation, rawBMS, rawBmson);
  migrateBMSExtensionHeadersFromExtras(json);
  return json;
}
 
function migrateBMSExtensionHeadersFromExtras(json: BeMusicJSON): void {
  const migratedExtras: Record<string, string> = {};
  // Honor `#BASE 62` so any indexed-header keys that landed in `metadata.extras` (typically from a re-parsed JSON
  // whose upstream parser didn't recognize the directive) get preserved in their authored case rather than folded to
  // uppercase. The common base-36 case-insensitive path keeps its existing behavior because `idBase` is 36 by default.
  const idBase = resolveBMSBase(json);
 
  for (const [command, value] of Object.entries(json.metadata.extras ?? {})) {
    const upper = command.toUpperCase();
    if (upper === 'PREVIEW') {
      Eif (typeof json.bms.preview !== 'string' && value.length > 0) {
        json.bms.preview = value;
      }
      continue;
    }
    if (upper === 'LNTYPE') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.lnType !== 'number' && typeof parsed === 'number' && parsed > 0) {
        json.bms.lnType = Math.floor(parsed);
      }
      continue;
    }
    if (upper === 'LNMODE') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.lnMode !== 'number' && typeof parsed === 'number' && parsed > 0) {
        json.bms.lnMode = Math.floor(parsed);
      }
      continue;
    }
    if (upper === 'LNOBJ') {
      Eif (value.length > 0) {
        // The migration's `value` is the directive payload (e.g. `AA` for `#LNOBJ AA`), so the chart-base case-rule
        // applies just like for any other indexed key.
        const normalizedValue = normalizeObjectKey(value, idBase);
        json.bms.lnObjs = [...(json.bms.lnObjs ?? []), normalizedValue];
      }
      continue;
    }
    if (upper === 'VOLWAV') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.volWAV !== 'number' && typeof parsed === 'number' && parsed >= 0) {
        json.bms.volWAV = parsed;
      }
      continue;
    }
    if (upper === 'DEFEXRANK') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.defExRank !== 'number' && typeof parsed === 'number') {
        json.bms.defExRank = parsed;
      }
      continue;
    }
    if (upper === 'PLAYER') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.player !== 'number' && typeof parsed === 'number' && parsed > 0) {
        json.bms.player = Math.floor(parsed);
      }
      continue;
    }
    if (upper === 'PATH_WAV') {
      Eif (typeof json.bms.pathWAV !== 'string' && value.length > 0) {
        json.bms.pathWAV = value;
      }
      continue;
    }
    if (upper === 'BASEBPM') {
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (typeof json.bms.baseBPM !== 'number' && typeof parsed === 'number' && parsed > 0) {
        json.bms.baseBPM = parsed;
      }
      continue;
    }
    if (upper === 'STP') {
      Eif (value.length > 0 && !json.bms.stp.includes(value)) {
        json.bms.stp.push(value);
      }
      continue;
    }
    if (upper === 'OPTION') {
      Eif (typeof json.bms.option !== 'string' && value.length > 0) {
        json.bms.option = value;
        json.bms.options = [value];
      }
      continue;
    }
    if (upper === 'WAVCMD') {
      Eif (value.length > 0) {
        // Mirror the strict-path collection so non-strict ingestion (chart roundtrips through `metadata.extras`) also
        // retains every line of `#WAVCMD pp xx vv`.
        Eif (!json.bms.wavCmds.includes(value)) {
          json.bms.wavCmds.push(value);
        }
        Eif (typeof json.bms.wavCmd !== 'string') {
          json.bms.wavCmd = value;
        }
      }
      continue;
    }
    if (upper === 'POORBGA') {
      Eif (typeof json.bms.poorBGA !== 'string' && value.length > 0) {
        json.bms.poorBGA = value;
      }
      continue;
    }
    if (upper === 'VIDEOFILE') {
      Eif (typeof json.bms.videoFile !== 'string' && value.length > 0) {
        json.bms.videoFile = value;
      }
      continue;
    }
    if (upper === 'MIDIFILE') {
      Eif (typeof json.bms.midiFile !== 'string' && value.length > 0) {
        json.bms.midiFile = value;
      }
      continue;
    }
    if (upper === 'MATERIALS') {
      Eif (typeof json.bms.materials !== 'string' && value.length > 0) {
        json.bms.materials = value;
      }
      continue;
    }
    if (upper === 'DIVIDEPROP') {
      Eif (typeof json.bms.divideProp !== 'string' && value.length > 0) {
        json.bms.divideProp = value;
      }
      continue;
    }
    if (upper === 'CHARSET') {
      Eif (typeof json.bms.charset !== 'string' && value.length > 0) {
        json.bms.charset = value;
      }
      continue;
    }
 
    // Be-Music JSON written before `#EXBPMxx` became a `#BPMxx` alias kept it here; a `#BPMxx` definition still wins.
    const exBPMMatch = command.match(/^EXBPM([0-9A-Za-z]{2})$/i);
    if (exBPMMatch) {
      const key = normalizeObjectKey(exBPMMatch[1]!, idBase);
      const parsed = Number.parseFloat(value);
      if (!(key in json.resources.bpm) && Number.isFinite(parsed)) {
        json.resources.bpm[key] = parsed;
      }
      continue;
    }
 
    const exRankMatch = upper.match(/^EXRANK([0-9A-Z]{2})$/);
    if (exRankMatch) {
      const key = normalizeObjectKey(exRankMatch[1]);
      Eif (!(key in json.bms.exRank) && value.length > 0) {
        json.bms.exRank[key] = value;
      }
      continue;
    }
 
    const argbMatch = upper.match(/^ARGB([0-9A-Z]{2})$/);
    if (argbMatch) {
      const key = normalizeObjectKey(argbMatch[1]);
      Eif (!(key in json.bms.argb) && value.length > 0) {
        json.bms.argb[key] = value;
      }
      continue;
    }
 
    const songMatch = command.match(/^SONG([0-9A-Za-z]{2})$/i);
    if (songMatch) {
      const key = normalizeObjectKey(songMatch[1]!, idBase);
      Eif (!(key in json.bms.songText) && value.length > 0) {
        json.bms.songText[key] = value;
      }
      continue;
    }
 
    const changeOptionMatch = upper.match(/^CHANGEOPTION([0-9A-Z]{2})$/);
    if (changeOptionMatch) {
      const key = normalizeObjectKey(changeOptionMatch[1]);
      Eif (!(key in json.bms.changeOption) && value.length > 0) {
        json.bms.changeOption[key] = value;
      }
      continue;
    }
 
    const exWAVMatch = upper.match(/^EXWAV([0-9A-Z]{2})$/);
    if (exWAVMatch) {
      const key = normalizeObjectKey(exWAVMatch[1]);
      Eif (!(key in json.bms.exWAV) && value.length > 0) {
        json.bms.exWAV[key] = value;
      }
      continue;
    }
 
    const exBMPMatch = upper.match(/^EXBMP([0-9A-Z]{2})$/);
    if (exBMPMatch) {
      const key = normalizeObjectKey(exBMPMatch[1]);
      Eif (!(key in json.bms.exBMP) && value.length > 0) {
        json.bms.exBMP[key] = value;
      }
      continue;
    }
 
    const bgaMatch = upper.match(/^BGA([0-9A-Z]{2})$/);
    if (bgaMatch) {
      const key = normalizeObjectKey(bgaMatch[1]);
      Eif (!(key in json.bms.bga) && value.length > 0) {
        json.bms.bga[key] = value;
      }
      continue;
    }
 
    const scrollMatch = upper.match(/^SCROLL([0-9A-Z]{2})$/);
    if (scrollMatch) {
      const key = normalizeObjectKey(scrollMatch[1]);
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (!(key in json.bms.scroll) && typeof parsed === 'number') {
        json.bms.scroll[key] = parsed;
      }
      continue;
    }
 
    const speedMatch = upper.match(/^SPEED([0-9A-Z]{2})$/);
    if (speedMatch) {
      const key = normalizeObjectKey(speedMatch[1]);
      const parsed = normalizeNumericBMSExtensionValue(value);
      Eif (!(key in json.bms.speed) && typeof parsed === 'number') {
        json.bms.speed[key] = parsed;
      }
      continue;
    }
 
    const swBGAMatch = upper.match(/^SWBGA([0-9A-Z]{2})$/);
    if (swBGAMatch) {
      const key = normalizeObjectKey(swBGAMatch[1]);
      Eif (!(key in json.bms.swBGA) && value.length > 0) {
        json.bms.swBGA[key] = value;
      }
      continue;
    }
 
    migratedExtras[command] = value;
  }
 
  json.metadata.extras = migratedExtras;
}
 
function normalizeBMSExtensions(input: unknown, allowLongKeys: boolean): BeMusicJSON['bms'] {
  const normalized: BeMusicJSON['bms'] = {
    controlFlow: [],
    lnObjs: [],
    exRank: {},
    argb: {},
    stp: [],
    wavCmds: [],
    changeOption: {},
    songText: {},
    exWAV: {},
    exBMP: {},
    bga: {},
    scroll: {},
    speed: {},
    swBGA: {},
  };
  if (!input || typeof input !== 'object') {
    return normalized;
  }
 
  const raw = input as Record<string, unknown>;
  // Honor `#BASE 62` on re-parsed JSON so the indexed maps below (`exRank`, `argb`, `wav`/`bmp`/…) preserve lowercase
  // keys instead of folding them through the default base-36 path.
  if (raw.base === 62) {
    normalized.base = 62;
  }
  const idBase: 36 | 62 = normalized.base === 62 ? 62 : 36;
  if (Array.isArray(raw.controlFlow)) {
    const entries: BMSControlFlowEntry[] = [];
    for (const item of raw.controlFlow) {
      const entry = normalizeBMSControlFlowEntry(item);
      Eif (entry) {
        entries.push(entry);
      }
    }
    normalized.controlFlow = entries;
  }
 
  if (typeof raw.preview === 'string' && raw.preview.length > 0) {
    normalized.preview = raw.preview;
  }
 
  const lnType = normalizeNumericBMSExtensionValue(raw.lnType);
  if (typeof lnType === 'number' && lnType > 0) {
    normalized.lnType = Math.floor(lnType);
  }
 
  const lnMode = normalizeNumericBMSExtensionValue(raw.lnMode ?? raw.lnmode ?? raw.ln_mode);
  if (typeof lnMode === 'number' && lnMode > 0) {
    normalized.lnMode = Math.floor(lnMode);
  }
 
  const lnObjs = normalizeBMSExtensionStringList(raw.lnObjs ?? raw.ln_objs);
  if (lnObjs.length > 0) {
    normalized.lnObjs = lnObjs.map((value) => normalizeObjectKey(value, idBase));
  }
 
  const volWAV = normalizeNumericBMSExtensionValue(raw.volWAV ?? raw.volWav ?? raw.volwav ?? raw.vol_wav);
  if (typeof volWAV === 'number' && volWAV >= 0) {
    normalized.volWAV = volWAV;
  }
 
  const defExRank = normalizeNumericBMSExtensionValue(raw.defExRank);
  if (typeof defExRank === 'number') {
    normalized.defExRank = defExRank;
  }
 
  normalized.exRank = normalizeIndexedBMSExtensionMap(raw.exRank, idBase, allowLongKeys);
  normalized.argb = normalizeIndexedBMSExtensionMap(raw.argb, idBase, allowLongKeys);
 
  const player = normalizeNumericBMSExtensionValue(raw.player);
  if (typeof player === 'number' && player > 0) {
    normalized.player = Math.floor(player);
  }
 
  const pathWAV = raw.pathWAV ?? raw.pathWav ?? raw.path_wav;
  if (typeof pathWAV === 'string' && pathWAV.length > 0) {
    normalized.pathWAV = pathWAV;
  }
 
  const baseBPM = normalizeNumericBMSExtensionValue(raw.baseBPM ?? raw.baseBpm ?? raw.base_bpm);
  if (typeof baseBPM === 'number' && baseBPM > 0) {
    normalized.baseBPM = baseBPM;
  }
 
  normalized.stp = normalizeBMSExtensionStringList(raw.stp);
 
  if (typeof raw.option === 'string' && raw.option.length > 0) {
    normalized.option = raw.option;
  }
 
  if (raw.options !== undefined) {
    if (!Array.isArray(raw.options) || raw.options.some((value) => typeof value !== 'string' || value.length === 0))
      throw new TypeError('bms.options must be an array of nonempty declaration strings');
    normalized.options = [...raw.options] as string[];
    if (normalized.options.length > 0) normalized.option = normalized.options.at(-1);
    else delete normalized.option;
  }
  if (raw.optionHeadersInControlFlow === true) normalized.optionHeadersInControlFlow = true;
 
  const wavCmd = raw.wavCmd ?? raw.wavcmd ?? raw.wav_cmd;
  if (typeof wavCmd === 'string' && wavCmd.length > 0) {
    normalized.wavCmd = wavCmd;
  }
  // Spec-faithful per-line list. Falls back to the legacy single string when only `wavCmd` was preserved (older
  // roundtripped JSON), so older fixtures keep round-tripping.
  normalized.wavCmds = normalizeBMSExtensionStringList(raw.wavCmds ?? raw.wav_cmds);
  if (normalized.wavCmds.length === 0 && typeof normalized.wavCmd === 'string') {
    normalized.wavCmds.push(normalized.wavCmd);
  }
 
  normalized.changeOption = normalizeIndexedBMSExtensionMap(
    raw.changeOption ?? raw.change_option ?? raw.changeoption,
    idBase,
    allowLongKeys,
  );
  normalized.songText = normalizeIndexedBMSExtensionMap(raw.songText ?? raw.song_text, idBase, allowLongKeys);
  normalized.exWAV = normalizeIndexedBMSExtensionMap(
    raw.exWAV ?? raw.exWav ?? raw.ex_wav ?? raw.exwav,
    idBase,
    allowLongKeys,
  );
  const exWAVOverridden = normalizeBMSExtensionStringList(raw.exWAVOverridden)
    .map((key) => normalizeObjectKey(key, idBase))
    .filter((key) => key in normalized.exWAV);
  Iif (exWAVOverridden.length > 0) normalized.exWAVOverridden = [...new Set(exWAVOverridden)];
  normalized.exBMP = normalizeIndexedBMSExtensionMap(
    raw.exBMP ?? raw.exBmp ?? raw.ex_bmp ?? raw.exbmp,
    idBase,
    allowLongKeys,
  );
  normalized.bga = normalizeIndexedBMSExtensionMap(raw.bga, idBase, allowLongKeys);
  normalized.scroll = normalizeIndexedBMSExtensionNumericMap(raw.scroll, idBase, allowLongKeys);
  normalized.speed = normalizeIndexedBMSExtensionNumericMap(raw.speed, idBase, allowLongKeys);
  normalized.swBGA = normalizeIndexedBMSExtensionMap(
    raw.swBGA ?? raw.swBga ?? raw.sw_bga ?? raw.swbga,
    idBase,
    allowLongKeys,
  );
 
  const poorBGA = raw.poorBGA ?? raw.poorBga ?? raw.poor_bga;
  if (typeof poorBGA === 'string' && poorBGA.length > 0) {
    normalized.poorBGA = poorBGA;
  }
 
  const videoFile = raw.videoFile ?? raw.video_file;
  if (typeof videoFile === 'string' && videoFile.length > 0) {
    normalized.videoFile = videoFile;
  }
 
  const midiFile = raw.midiFile ?? raw.midi_file;
  if (typeof midiFile === 'string' && midiFile.length > 0) {
    normalized.midiFile = midiFile;
  }
 
  if (typeof raw.materials === 'string' && raw.materials.length > 0) {
    normalized.materials = raw.materials;
  }
 
  const divideProp = raw.divideProp ?? raw.divide_prop;
  if (typeof divideProp === 'string' && divideProp.length > 0) {
    normalized.divideProp = divideProp;
  }
 
  if (typeof raw.charset === 'string' && raw.charset.length > 0) {
    normalized.charset = raw.charset;
  }
  if (
    raw.wavNameBytePrefixes !== null &&
    typeof raw.wavNameBytePrefixes === 'object' &&
    !Array.isArray(raw.wavNameBytePrefixes)
  ) {
    normalized.wavNameBytePrefixes = Object.fromEntries(
      Object.entries(raw.wavNameBytePrefixes).flatMap(([path, prefix]) =>
        typeof prefix === 'string' && /^(?:[0-9a-f]{2}){1,2}$/i.test(prefix) ? [[path, prefix.toLowerCase()]] : [],
      ),
    );
  }
 
  return normalized;
}
 
function normalizePreservation(input: unknown, bmsInput: unknown, bmsonInput: unknown): BeMusicJSON['preservation'] {
  const normalized = createEmptyJSON('json').preservation;
 
  const raw = input && typeof input === 'object' ? (input as Record<string, unknown>) : undefined;
  const rawBMS =
    raw?.bms && typeof raw.bms === 'object'
      ? (raw.bms as Record<string, unknown>)
      : bmsInput && typeof bmsInput === 'object'
        ? (bmsInput as Record<string, unknown>)
        : undefined;
  const rawBmson =
    raw?.bmson && typeof raw.bmson === 'object'
      ? (raw.bmson as Record<string, unknown>)
      : bmsonInput && typeof bmsonInput === 'object'
        ? (bmsonInput as Record<string, unknown>)
        : undefined;
 
  const rawSourceLines = rawBMS?.sourceLines ?? rawBMS?.source_lines;
  if (Array.isArray(rawSourceLines)) {
    const entries: BMSSourceLineEntry[] = [];
    for (const item of rawSourceLines) {
      const entry = normalizeBMSControlFlowEntry(item);
      Eif (entry) {
        entries.push(entry);
      }
    }
    normalized.bms.sourceLines = entries;
  }
 
  const rawObjectLines = rawBMS?.objectLines ?? rawBMS?.object_lines;
  if (Array.isArray(rawObjectLines)) {
    const entries: BMSObjectLineEntry[] = [];
    for (const item of rawObjectLines) {
      const entry = normalizeBMSObjectLineEntry(item);
      Eif (entry) {
        entries.push(entry);
      }
    }
    normalized.bms.objectLines = entries;
  }
 
  normalized.bmson.lines = normalizeBmsonLines(rawBmson?.lines);
  normalized.bmson.bpmEvents = normalizeBmsonBPMEvents(rawBmson?.bpmEvents ?? rawBmson?.bpm_events, true);
  normalized.bmson.stopEvents = normalizeBmsonStopEvents(rawBmson?.stopEvents ?? rawBmson?.stop_events, true);
  const scrollEvents = normalizeBmsonScrollEvents(rawBmson?.scrollEvents ?? rawBmson?.scroll_events, true);
  if (scrollEvents.length > 0) {
    normalized.bmson.scrollEvents = scrollEvents;
  }
  normalized.bmson.soundChannels = normalizeBmsonSoundChannels(
    rawBmson?.soundChannels ?? rawBmson?.sound_channels,
    true,
  );
 
  return normalized;
}
 
function normalizeNumericBMSExtensionValue(value: unknown): number | undefined {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value;
  }
  if (typeof value !== 'string' || value.length === 0) {
    return undefined;
  }
  const parsed = Number.parseFloat(value);
  return Number.isFinite(parsed) ? parsed : undefined;
}
 
function normalizeIndexedBMSExtensionMap(
  input: unknown,
  base: 36 | 62 = 36,
  allowLongKeys = false,
): Record<string, string> {
  if (!input || typeof input !== 'object') {
    return {};
  }
 
  const normalized: Record<string, string> = {};
  for (const [rawKey, rawValue] of Object.entries(input as Record<string, unknown>)) {
    const key = normalizeObjectKey(rawKey, base, allowLongKeys);
    if (typeof rawValue === 'string' && rawValue.length > 0) {
      normalized[key] = rawValue;
      continue;
    }
    Eif (typeof rawValue === 'number' && Number.isFinite(rawValue)) {
      normalized[key] = String(rawValue);
    }
  }
  return normalized;
}
 
function normalizeIndexedBMSExtensionNumericMap(
  input: unknown,
  base: 36 | 62 = 36,
  allowLongKeys = false,
): Record<string, number> {
  if (!input || typeof input !== 'object') {
    return {};
  }
 
  const normalized: Record<string, number> = {};
  for (const [rawKey, rawValue] of Object.entries(input as Record<string, unknown>)) {
    const parsed = normalizeNumericBMSExtensionValue(rawValue);
    Eif (typeof parsed === 'number') {
      normalized[normalizeObjectKey(rawKey, base, allowLongKeys)] = parsed;
    }
  }
  return normalized;
}
 
function normalizeBMSExtensionStringList(input: unknown): string[] {
  Iif (typeof input === 'string') {
    return input.length > 0 ? [input] : [];
  }
  if (!Array.isArray(input)) {
    return [];
  }
 
  const normalized: string[] = [];
  for (const value of input) {
    if (typeof value === 'string' && value.length > 0) {
      normalized.push(value);
    }
  }
  return normalized;
}
 
function normalizeBMSControlFlowEntry(input: unknown): BMSControlFlowEntry | undefined {
  Iif (!input || typeof input !== 'object') {
    return undefined;
  }
  const raw = input as Record<string, unknown>;
  const kind = raw.kind;
  if (kind === 'directive') {
    const command = normalizeControlFlowCommand(raw.command);
    Iif (!command) {
      return undefined;
    }
    const value =
      typeof raw.value === 'string' && raw.value.length > 0
        ? raw.value
        : typeof raw.value === 'number' && Number.isFinite(raw.value)
          ? String(Math.floor(raw.value))
          : undefined;
    return {
      kind: 'directive',
      command,
      value,
    };
  }
  if (kind === 'header') {
    Iif (typeof raw.command !== 'string') {
      return undefined;
    }
    const command = raw.command.toUpperCase();
    // Honor `commandRaw` when present and actually case-different — that's the base-62 marker. Otherwise drop it to
    // keep the round-tripped JSON minimal.
    const rawCommandValue = typeof raw.commandRaw === 'string' ? raw.commandRaw : undefined;
    const commandRaw = rawCommandValue && rawCommandValue !== command ? rawCommandValue : undefined;
    return {
      kind: 'header',
      command,
      value: typeof raw.value === 'string' ? raw.value : '',
      ...(commandRaw ? { commandRaw } : {}),
      ...(raw.overriddenByLaterHeader === true ? { overriddenByLaterHeader: true as const } : {}),
    };
  }
  Eif (kind === 'object') {
    const objectLine = normalizeBMSObjectLineEntry(raw);
    Iif (!objectLine) {
      return undefined;
    }
    return {
      kind: 'object',
      ...objectLine,
    };
  }
  return undefined;
}
 
function normalizeBMSObjectLineEntry(input: unknown): BMSObjectLineEntry | undefined {
  Iif (!input || typeof input !== 'object') {
    return undefined;
  }
  const raw = input as Record<string, unknown>;
  Iif (typeof raw.measure !== 'number' || !Number.isFinite(raw.measure) || typeof raw.channel !== 'string') {
    return undefined;
  }
  const measure = Math.max(0, Math.floor(raw.measure));
  const channel = normalizeChannel(raw.channel);
 
  const rawEvents = Array.isArray(raw.events) ? raw.events : [];
  const normalizedEvents = sortAndNormalizeEvents(rawEvents as Array<BeMusicEvent | Record<string, unknown>>)
    .filter(
      (event) =>
        event.measure === measure &&
        normalizeChannel(event.channel) === channel &&
        normalizeObjectKey(event.value) !== '00',
    )
    .map((event) => {
      // Optional fields are assigned, not spread, to keep the hidden classes of parsed events.
      const copy: BeMusicEvent = { measure, channel, position: event.position, value: event.value };
      if (event.bmsLineOrder !== undefined) copy.bmsLineOrder = event.bmsLineOrder;
      Iif (event.bmson) copy.bmson = event.bmson;
      return copy;
    });
 
  const measureLength =
    typeof raw.measureLength === 'number' && Number.isFinite(raw.measureLength) && raw.measureLength > 0
      ? raw.measureLength
      : undefined;
 
  Iif (normalizedEvents.length === 0 && measureLength === undefined) {
    const fallbackData = typeof raw.data === 'string' ? raw.data.trim() : '';
    return buildBMSObjectLineEntry(measure, channel, fallbackData);
  }
 
  return {
    measure,
    channel,
    events: normalizedEvents,
    measureLength,
  };
}