All files / player-engine/src/core lane-layout.ts

95.91% Statements 258/269
92.69% Branches 203/219
98.46% Functions 64/65
96.38% Lines 213/221

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                                                                                      380x                                   380x                                                               380x                     9120x                                                                                                         10835x 7675x       2734x 2594x 2593x 2593x 2489x   4941x 232x 232x 232x 232x 148x     84x 84x 2x       4709x 4187x 4187x 4187x 4186x             1012x 10x   1002x 503x         3852x 3852x       3804x 733x 692x       509x 509x       380x 6080x       7x                 3377x 3300x 3377x 3269x 3237x                           1138x 182x       1138x         59280x 1993480x 972880x 992180x     380x 29640x                   3638x       2019x 4438x                   506x 492x 468x 456x       39684x     380x 7220x 6080x 380x       380x 380x 380x   3420x                           251x 251x   250x 6x 5x   245x   250x 4302x       380x                                       380x     380x   6080x             3420x                   3934x 3662x     380x                                   16x               380x                       3137x 3137x 55683x 3243x 3243x 3243x   52440x 29640x 29640x 27360x 29640x 29640x   22800x 6840x 6840x   15960x   3137x 55683x 55683x           55683x       380x                                       3934x 3934x 3934x 7x 7x 89x 89x 89x 89x 11x         27926x 3986x 52x     3934x 3934x         3986x 3986x 3986x 38755x   3986x 38755x 38755x 38755x               49880x     3934x 27485x 27320x   165x 165x 98x   67x   3934x   3934x 3934x 67x 67x 95x 95x   67x 67x 67x                 3934x               21952x 31835x   3503x 7006x 6914x   718x 92x     92x 326x 326x 326x 326x 326x         3503x 7006x         24997x 3694x 52x   3642x                       7576x     207x     7576x 7389x 6852x   537x                         38755x 3934x   3934x 3349x         3934x 539x     3934x                   3732x 3732x       3420x 3420x     537x 537x   537x 40x   497x       1074x 1074x 4296x 1880x     1074x       380x     165x 273x     380x   380x     2593x 2593x 10x   2583x       3524x 3524x 32024x 41852x 41852x 41852x 41852x     3524x    
import {
  PLAY_MODE_LAYOUTS,
  findPlayModeLane,
  getPlayModeLayouts,
  isPMSChartPath,
  resolveChartPlayVariant,
  type ChartPlayVariant,
  type PlayLane,
  type PlayModeLayout,
  type PlayModeLayoutId,
} from '@be-music/chart-model';
import { normalizeChannel } from '@be-music/chart-source';
 
export interface ChannelLike {
  channel: string;
}
 
export interface LaneBinding {
  channel: string;
  keyLabel: string;
  inputTokens: string[];
  side: '1P' | '2P' | 'OTHER';
  isScratch: boolean;
  /**
   * A scratch lane's physical keys in order, each as the tokens it arrives as: the main key (Shift), then the second
   * key (Ctrl, or Option / Alt on macOS terminals). Under the odd-even rule they spin the turntable in turn, so the
   * second key reverses a back-spin scratch the first one started (`createScratchSpinByToken` in `scratch-spin.ts`).
   * Absent on a lane with a single key.
   */
  inputKeys?: readonly (readonly string[])[];
}
 
export interface KeyboardCodeLike {
  code: string;
}
 
/**
 * The player's lane layouts and lanes all come from the play-mode table in `@be-music/chart-model` (`PLAY_MODE_LAYOUTS`);
 * this module only adds what is the player's own: default keys, the lane order the hosts index lanes by, and the
 * per-variant slot arithmetic the skins use.
 */
 
/** Physical key codes of the That-Which-Must-Not-Be-Named default keys, for hosts that receive DOM `KeyboardEvent.code`s. */
const CHANNEL_KEY_BINDINGS: Record<string, ReadonlySet<string>> = {
  '16': new Set(['ShiftLeft']),
  '11': new Set(['KeyZ']),
  '12': new Set(['KeyS']),
  '13': new Set(['KeyX']),
  '14': new Set(['KeyD']),
  '15': new Set(['KeyC']),
  '18': new Set(['KeyF']),
  '19': new Set(['KeyV']),
  '26': new Set(['ShiftRight']),
  '21': new Set(['KeyB']),
  '22': new Set(['KeyH']),
  '23': new Set(['KeyN']),
  '24': new Set(['KeyJ']),
  '25': new Set(['KeyM']),
  '28': new Set(['KeyK']),
};
 
const KEY_LAYOUT = [
  'a',
  's',
  'd',
  'f',
  'g',
  'h',
  'j',
  'k',
  'l',
  ';',
  'q',
  'w',
  'e',
  'r',
  'u',
  'i',
  'o',
  'p',
  'z',
  'x',
  'c',
  'v',
  'b',
  'n',
  'm',
  ',',
  '.',
  '/',
];
 
/** Generic layouts use only real keyboard tokens; the 70th lane must not acquire a fictional F42 key. */
const GENERIC_KEY_LAYOUT = [
  ...KEY_LAYOUT,
  ...'1234567890'.split(''),
  't',
  'y',
  '-',
  '=',
  '[',
  ']',
  '\\',
  '`',
  ...Array.from({ length: 24 }, (_, index) => `f${index + 1}`),
];
 
interface FixedLaneDefinition {
  channel: string;
  keyLabel: string;
  inputTokens: string[];
  side: '1P' | '2P' | 'OTHER';
  isScratch?: boolean;
}
 
export interface LaneModeOptions {
  player?: number;
  chartExtension?: string;
  platform?: NodeJS.Platform;
  /**
   * The chart's play variant when the caller already knows it (an explicit host declaration, or
   * `resolveChartPlayVariant` from `@be-music/chart-model` run over the chart's events). Without it the
   * lane mode is resolved by that same `resolveChartPlayVariant` rule over the given channels,
   * `chartExtension`, and `player`.
   */
  playVariant?: ChartPlayVariant;
  /** The player's own lane keys, over the defaults (`LANE_KEY_CONFIG`). */
  laneKeys?: LaneKeyOverrides;
}
 
/**
 * The lanes a player's own keys cover. The beatmania-style layouts (5 / 7 / 10 / 14 KEY) share their keys lane by lane
 * (`beat`, by channel), and the 9 KEY layouts by key number (`popn`, `1`..`9`); the 24 / 48 KEY layouts keep theirs.
 */
export type LaneKeyGroup = 'beat' | 'popn';
 
/** A player's own lane keys: for each group and lane (a channel, or a key number), the input tokens it takes. */
export type LaneKeyOverrides = Partial<Record<LaneKeyGroup, Readonly<Record<string, readonly string[]>>>>;
 
/** One lane of a key config: its id within its group, its side, whether it is a scratch, and its default token. */
export interface LaneKeyConfigLane {
  readonly id: string;
  readonly side: '1P' | '2P';
  readonly scratch: boolean;
  readonly defaultToken: string;
}
 
export function resolveKeyChannel(event: KeyboardCodeLike, channels: ReadonlyArray<string>): string | undefined {
  for (const channel of channels) {
    if (CHANNEL_KEY_BINDINGS[channel]?.has(event.code)) {
      return channel;
    }
  }
  return undefined;
}
 
export function resolveSideKeySlot(channel: string, playVariant?: ChartPlayVariant): number {
  if (playVariant?.startsWith('generic-')) return findPlayModeLane(playVariant, channel)?.slot ?? -1;
  if (playVariant === '24' || playVariant === '48') {
    // Keyboard modes have no scratch, so slot `0` is never produced and `isScratchLaneForVariant` stays false for
    // every channel. Lanes are the plain 1-based column index within the side (`11` → 1, `19` → 9, `1A` → 10, …,
    // `1O` → 24), then the wheel: `1P` → 25 (up), `1Q` → 26 (down) — beatoraja's keyboard lane offsets.
    if (channel.length !== 2) return -1;
    if (channel[0] !== '1' && channel[0] !== '2') return -1;
    const laneIndex = resolveLaneIndex(channel[1]!);
    if (laneIndex === undefined || laneIndex > KEYBOARD_MODE_SIDE_LANE_COUNT) return -1;
    return laneIndex;
  }
  if (playVariant === '9') {
    Iif (channel.length !== 2) return -1;
    const digit = Number.parseInt(channel[1]!, 10);
    Iif (!Number.isFinite(digit)) return -1;
    if (channel.startsWith('1')) {
      Eif (digit >= 1 && digit <= 9) return digit;
      return -1;
    }
    Eif (channel.startsWith('2')) {
      if (digit >= 2 && digit <= 5) return digit + 4;
      return -1;
    }
    return -1;
  }
  if (channel === '16' || channel === '26') return 0;
  Iif (channel.length !== 2) return -1;
  const digit = Number.parseInt(channel[1]!, 10);
  if (!Number.isFinite(digit)) return -1;
  if (digit >= 1 && digit <= 5) return digit;
  // Channels 18/19 are valid LANE notes only on the 7-key family (`'7'` SP / `'14'` DP).
  // 5-key family variants (`'5'` SP / `'10'` DP — 5 keys per side, no 6/7-key columns) reject
  // them: a malformed BMS that authors notes on 18/19 in a 5K chart shouldn't trip the
  // adapter into stamping ghost-lane bomb / keybeam / LN-hold timers for slots 6/7 that the
  // mounted skin doesn't render. Returning `-1` here cascades through `resolveLane`'s
  // `slot < 0 → undefined` guard, which all the lane-timer helpers already check.
  if (playVariant === '5' || playVariant === '10') {
    return -1;
  }
  if (digit === 8) return 6;
  Eif (digit === 9) return 7;
  return -1;
}
 
export function resolveLR2LaneIndex(channel: string, playVariant?: ChartPlayVariant): number {
  const slot = resolveSideKeySlot(channel, playVariant);
  if (slot < 0) return -1;
  // LR2 skins only define the 20 That-Which-Must-Not-Be-Named lane rects (`0`/`10` scratch + `1..9`/`11..19` keys) — there is no
  // `play_24.lr2skin`. Returning `-1` routes keyboard-mode charts through the caller's fallback playfield instead of
  // squeezing 26 lanes into the 7-key rect table.
  if (playVariant === '24' || playVariant === '48' || playVariant?.startsWith('generic-')) return -1;
  if (playVariant === '9') return slot;
  return channel.startsWith('2') ? 10 + slot : slot;
}
 
export function resolveSideRelativeLaneIndex(channel: string, playVariant?: ChartPlayVariant): number {
  const slot = resolveSideKeySlot(channel, playVariant);
  return slot < 0 ? 0 : slot;
}
 
/** The That-Which-Must-Not-Be-Named scratch lanes (`16` / `26`), whatever the play variant. */
const _____SCRATCH_CHANNELS: ReadonlySet<string> = new Set(
  PLAY_MODE_LAYOUTS['14'].lanes.filter((lane) => lane.kind === 'scratch').map((lane) => lane.channel),
);
 
export function isScratch(channel: string): boolean {
  return _____SCRATCH_CHANNELS.has(channel);
}
 
/**
 * Which way a keyboard-mode wheel lane turns: `'up'` for `1P` / `2P`, `'down'` for `1Q` / `2Q`, `undefined` for every
 * other lane and for every channel outside the 24 / 48 KEY modes. The wheel is judged like a key, but it sits on the
 * outer edge of its side and the lane options leave it in place.
 */
export function resolveWheelLaneDirection(channel: string, playVariant?: ChartPlayVariant): 'up' | 'down' | undefined {
  if (playVariant === undefined) return undefined;
  const kind = findPlayModeLane(playVariant, channel)?.kind;
  if (kind === 'wheel-up') return 'up';
  if (kind === 'wheel-down') return 'down';
  return undefined;
}
 
/**
 * The complete key domain of one side, including unused lanes. Scratch and wheel lanes stay in place.
 * For 9 KEY, `channels` identifies PMS-STD versus PMS-COMPAT; passing full prepared bindings also resolves sparse
 * charts with no notes on the distinguishing columns. An omitted variant preserves the legacy 14-key side domains.
 */
export function resolveLaneOptionChannels(
  side: '1P' | '2P',
  playVariant?: ChartPlayVariant,
  channels: ReadonlyArray<ChannelLike> = [],
): readonly string[] {
  const layoutId: PlayModeLayoutId =
    playVariant === '9'
      ? channels.some(({ channel }) => PMS_STD_ONLY_CHANNELS.includes(channel))
        ? '9-pms'
        : '9-bme'
      : (playVariant ?? '14');
  return LANE_OPTION_CHANNELS_BY_LAYOUT[layoutId][side];
}
 
/** The keys of one side of a layout, by key number. */
function sideKeyChannels(layoutId: PlayModeLayoutId, side: '1P' | '2P'): readonly string[] {
  return PLAY_MODE_LAYOUTS[layoutId].lanes
    .filter((lane) => lane.side === side && lane.kind === 'key')
    .sort((left, right) => left.slot - right.slot)
    .map((lane) => lane.channel);
}
 
const LANE_OPTION_CHANNELS_BY_LAYOUT = Object.fromEntries(
  (Object.keys(PLAY_MODE_LAYOUTS) as PlayModeLayoutId[]).map((layoutId) => [
    layoutId,
    {
      '1P': sideKeyChannels(layoutId, '1P'),
      '2P': sideKeyChannels(layoutId, '2P'),
    },
  ]),
) as Record<PlayModeLayoutId, Record<'1P' | '2P', readonly string[]>>;
 
export function isPlayableInputChannel(channel: string): boolean {
  return channel.startsWith('1') || channel.startsWith('2');
}
 
export function resolveLaneChannels(notes: ReadonlyArray<ChannelLike>, playVariant?: ChartPlayVariant): string[] {
  const used = new Set(notes.map((note) => note.channel).filter(isPlayableInputChannel));
  return preferredLaneOrder(playVariant).filter((channel) => used.has(channel));
}
 
/**
 * The order lanes are indexed in, for every lane a play variant can use. The keyboard modes keep the table's drawing
 * order (1P wheel, 1P keys, 2P keys, 2P wheel). 9 KEY lists the BME-type `11..19`, then the PMS-STD `22..25`. The That-Which-Must-Not-Be-Named
 * families list each side by slot — the scratch first — so the 2P scratch `26` comes before `21` here; the skins put it
 * on the outer edge when they draw.
 */
function preferredLaneOrder(playVariant?: ChartPlayVariant): readonly string[] {
  if (playVariant?.startsWith('generic-')) return layoutChannels(getPlayModeLayouts(playVariant)[0]!);
  if (playVariant === '24' || playVariant === '48') return KEYBOARD_LANE_ORDER[playVariant];
  if (playVariant === '9') return POPN_9KEY_LANE_ORDER;
  return _____LANE_ORDER;
}
 
function layoutChannels(layout: PlayModeLayout): readonly string[] {
  return layout.lanes.map((lane) => lane.channel);
}
 
const _____LANE_ORDER: readonly string[] = [...PLAY_MODE_LAYOUTS['14'].lanes]
  .sort((left, right) => left.side.localeCompare(right.side) || left.slot - right.slot)
  .map((lane) => lane.channel);
const KEYBOARD_LANE_ORDER: Record<'24' | '48', readonly string[]> = {
  '24': layoutChannels(PLAY_MODE_LAYOUTS['24']),
  '48': layoutChannels(PLAY_MODE_LAYOUTS['48']),
};
const POPN_9KEY_BME_LANES = layoutChannels(PLAY_MODE_LAYOUTS['9-bme']);
const POPN_9KEY_PMS_LANES = layoutChannels(PLAY_MODE_LAYOUTS['9-pms']);
const POPN_9KEY_LANE_ORDER: readonly string[] = [
  ...POPN_9KEY_BME_LANES,
  ...POPN_9KEY_PMS_LANES.filter((channel) => !POPN_9KEY_BME_LANES.includes(channel)),
];
 
/**
 * The full lane set of a chart's play variant, in rendering order — every lane of the 5 / 7 / 9 / 10 / 14 / 24 /
 * 48 KEY layout, whether or not the chart puts notes on it, so a chart that only uses a few lanes still plays on the
 * whole keyboard. 9 KEY takes the PMS layout (`22..25` on the right) when the chart uses any of those channels, the
 * BME layout (`11..19`) otherwise. Lanes the chart uses outside the variant's set are kept too, so no note loses its
 * lane. Without a variant this is {@link resolveLaneChannels}: just the lanes in use.
 */
export function resolvePlayVariantLaneChannels(
  notes: ReadonlyArray<ChannelLike>,
  playVariant?: ChartPlayVariant,
): string[] {
  const used = resolveLaneChannels(notes, playVariant);
  if (!playVariant) return used;
  let layoutId: PlayModeLayoutId;
  if (playVariant === '9') {
    const pms = used.some((channel) => POPN_9KEY_PMS_LANES.includes(channel) && !POPN_9KEY_BME_LANES.includes(channel));
    layoutId = pms ? '9-pms' : '9-bme';
  } else {
    layoutId = playVariant;
  }
  const lanes = new Set([...layoutChannels(PLAY_MODE_LAYOUTS[layoutId]), ...used]);
  return preferredLaneOrder(playVariant).filter((channel) => lanes.has(channel));
}
 
/** Default keys of the That-Which-Must-Not-Be-Named lanes: `Z S X D C F V` (1P) and `B H N J M K ,` (2P), the scratches on the Shift keys. */
const _____DEFAULT_KEYS: Record<string, { keyLabel: string; token: string }> = {
  '16': { keyLabel: 'LShift', token: 'shift-left' },
  '11': { keyLabel: 'z', token: 'z' },
  '12': { keyLabel: 's', token: 's' },
  '13': { keyLabel: 'x', token: 'x' },
  '14': { keyLabel: 'd', token: 'd' },
  '15': { keyLabel: 'c', token: 'c' },
  '18': { keyLabel: 'f', token: 'f' },
  '19': { keyLabel: 'v', token: 'v' },
  '21': { keyLabel: 'b', token: 'b' },
  '22': { keyLabel: 'h', token: 'h' },
  '23': { keyLabel: 'n', token: 'n' },
  '24': { keyLabel: 'j', token: 'j' },
  '25': { keyLabel: 'm', token: 'm' },
  '28': { keyLabel: 'k', token: 'k' },
  '29': { keyLabel: ',', token: ',' },
  '26': { keyLabel: 'RShift', token: 'shift-right' },
};
 
/** Default keys of the 9 KEY layouts, by key number: `z s x d c f v g b`. */
const POPN_DEFAULT_KEYS = ['z', 's', 'x', 'd', 'c', 'f', 'v', 'g', 'b'];
 
/** The lanes each group's key config lists, in the order a player reads them: 1P scratch, keys, then 2P keys, scratch. */
export const LANE_KEY_CONFIG: Readonly<Record<LaneKeyGroup, readonly LaneKeyConfigLane[]>> = {
  beat: ['16', '11', '12', '13', '14', '15', '18', '19', '21', '22', '23', '24', '25', '28', '29', '26'].map(
    (channel) => ({
      id: channel,
      side: channel.startsWith('1') ? '1P' : '2P',
      scratch: channel === '16' || channel === '26',
      defaultToken: _____DEFAULT_KEYS[channel]!.token,
    }),
  ),
  popn: POPN_DEFAULT_KEYS.map((token, index) => ({
    id: String(index + 1),
    side: '1P',
    scratch: false,
    defaultToken: token,
  })),
};
 
/** The key config group a lane layout takes its keys from; the 24 / 48 KEY and generic layouts have none. */
function laneKeyGroupOf(layoutId: PlayModeLayoutId): LaneKeyGroup | undefined {
  if (layoutId === '9-pms' || layoutId === '9-bme') return 'popn';
  return layoutId === '5' || layoutId === '7' || layoutId === '10' || layoutId === '14' ? 'beat' : undefined;
}
 
const KEY_LABELS: Readonly<Record<string, string>> = {
  'shift-left': 'LShift',
  'shift-right': 'RShift',
  'ctrl-left': 'LCtrl',
  'ctrl-right': 'RCtrl',
  'alt-left': 'LAlt',
  'alt-right': 'RAlt',
  space: 'Space',
  enter: 'Enter',
  tab: 'Tab',
  up: '↑',
  down: '↓',
  left: '←',
  right: '→',
};
 
/** How a lane's key reads (`LShift`, `Tab`, `F5`, `z`), from its input token. */
export function laneKeyLabel(token: string): string {
  return KEY_LABELS[token] ?? (/^f\d+$/.test(token) ? token.toUpperCase() : token);
}
 
/**
 * Default wheel keys. They sit on the outer edges of the keyboard, off the 24 / 48-key pool (`KEY_LAYOUT`, then
 * `f1`…): Tab / Left Shift for the 1P wheel up / down, Enter / Right Shift for the 2P wheel. The arrow keys stay free
 * for the in-play hi-speed controls.
 */
const KEYBOARD_WHEEL_DEFAULT_KEYS: Record<string, { keyLabel: string; token: string }> = {
  '1P': { keyLabel: 'Tab', token: 'tab' },
  '1Q': { keyLabel: 'LShift', token: 'shift-left' },
  '2P': { keyLabel: 'Enter', token: 'enter' },
  '2Q': { keyLabel: 'RShift', token: 'shift-right' },
};
 
/**
 * A layout's lanes with their default keys, in the table's lane order (the terminal player draws its lanes in this
 * order). The keyboard modes' keys take the `KEY_LAYOUT` pool in order across both sides, then `f1`…
 */
function createFixedBindings(layout: PlayModeLayout): FixedLaneDefinition[] {
  let poolIndex = 0;
  const defaultKey = (lane: PlayLane): { keyLabel: string; token: string } => {
    if (layout.variant.startsWith('generic-')) {
      const token = GENERIC_KEY_LAYOUT[poolIndex]!;
      poolIndex++;
      return { keyLabel: token, token };
    }
    if (layout.variant === '24' || layout.variant === '48') {
      const wheel = KEYBOARD_WHEEL_DEFAULT_KEYS[lane.channel];
      if (wheel !== undefined) return wheel;
      const token = KEY_LAYOUT[poolIndex] ?? `f${poolIndex - KEY_LAYOUT.length + 1}`;
      poolIndex += 1;
      return { keyLabel: token, token };
    }
    if (layout.variant === '9') {
      const key = POPN_DEFAULT_KEYS[lane.slot - 1]!;
      return { keyLabel: key, token: key };
    }
    return _____DEFAULT_KEYS[lane.channel]!;
  };
  return layout.lanes.map((lane) => {
    const key = defaultKey(lane);
    const definition: FixedLaneDefinition = {
      channel: lane.channel,
      keyLabel: key.keyLabel,
      inputTokens: [key.token],
      side: lane.side,
    };
    return lane.kind === 'scratch' ? { ...definition, isScratch: true } : definition;
  });
}
 
const FIXED_BINDINGS_BY_LAYOUT: Record<PlayModeLayoutId, FixedLaneDefinition[]> = {
  '5': createFixedBindings(PLAY_MODE_LAYOUTS['5']),
  '7': createFixedBindings(PLAY_MODE_LAYOUTS['7']),
  '9-pms': createFixedBindings(PLAY_MODE_LAYOUTS['9-pms']),
  '9-bme': createFixedBindings(PLAY_MODE_LAYOUTS['9-bme']),
  '10': createFixedBindings(PLAY_MODE_LAYOUTS['10']),
  '14': createFixedBindings(PLAY_MODE_LAYOUTS['14']),
  '24': createFixedBindings(PLAY_MODE_LAYOUTS['24']),
  '48': createFixedBindings(PLAY_MODE_LAYOUTS['48']),
};
 
/**
 * A layout's lanes with the player's own keys (`laneKeys`) over their defaults: a lane its group lists takes the keys set
 * for it. Each lane's definitions keep the table's order (`createFixedBindings` follows the layout's lanes).
 */
function applyLaneKeys(
  definitions: FixedLaneDefinition[],
  layoutId: PlayModeLayoutId,
  laneKeys: LaneKeyOverrides | undefined,
): FixedLaneDefinition[] {
  const group = laneKeyGroupOf(layoutId);
  const keys = group === undefined ? undefined : laneKeys?.[group];
  if (keys === undefined) return definitions;
  const lanes = PLAY_MODE_LAYOUTS[layoutId].lanes;
  return definitions.map((definition, index) => {
    const lane = lanes[index];
    const id = group === 'popn' ? String(lane?.slot ?? -1) : definition.channel;
    const tokens = keys[id]?.filter((token) => token !== '');
    if (tokens === undefined || tokens.length === 0) return definition;
    return { ...definition, keyLabel: laneKeyLabel(tokens[0]!), inputTokens: [...tokens] };
  });
}
 
export function createLaneBindings(channels: string[], options: LaneModeOptions = {}): LaneBinding[] {
  const existing = new Set(channels.map((channel) => normalizeChannel(channel)));
  if (existing.size === 0 && !options.playVariant?.startsWith('generic-')) {
    return [];
  }
 
  const layoutId = resolveLaneLayout(existing, options);
  const modeBindings = applyLaneKeys(
    FIXED_BINDINGS_BY_LAYOUT[layoutId] ?? createFixedBindings(PLAY_MODE_LAYOUTS[layoutId]),
    layoutId,
    options.laneKeys,
  );
  const scratchReverseTokensByChannel = createScratchReverseTokensByChannel(modeBindings, options.platform);
  const bindings: LaneBinding[] = [];
  const usedTokens = new Set<string>();
  const definedChannels = new Set(modeBindings.map((definition) => definition.channel));
 
  for (const definition of modeBindings) {
    const reverseTokens = scratchReverseTokensByChannel.get(definition.channel);
    const inputTokens = [...definition.inputTokens, ...(reverseTokens ?? [])];
    bindings.push({
      channel: definition.channel,
      keyLabel: definition.keyLabel,
      inputTokens,
      side: definition.side,
      isScratch: definition.isScratch ?? false,
      ...(reverseTokens !== undefined ? { inputKeys: [definition.inputTokens, reverseTokens] } : {}),
    });
    inputTokens.forEach((token) => usedTokens.add(token));
  }
 
  const unknownChannels = [...existing].filter((channel) => {
    if (definedChannels.has(channel)) {
      return false;
    }
    const scratchChannel = resolveFreeZoneScratchChannel(channel);
    if (scratchChannel && definedChannels.has(scratchChannel)) {
      return false;
    }
    return true;
  });
  unknownChannels.sort();
 
  let fallbackIndex = 0;
  for (const channel of unknownChannels) {
    let token = KEY_LAYOUT[fallbackIndex] ?? `f${fallbackIndex + 1}`;
    while (usedTokens.has(token)) {
      fallbackIndex += 1;
      token = KEY_LAYOUT[fallbackIndex] ?? `f${fallbackIndex + 1}`;
    }
    fallbackIndex += 1;
    usedTokens.add(token);
    bindings.push({
      channel,
      keyLabel: token,
      inputTokens: [token],
      side: 'OTHER',
      isScratch: false,
    });
  }
 
  return bindings;
}
 
export function appendFreeZoneInputChannels(
  inputTokenToChannels: Map<string, string[]>,
  bindings: LaneBinding[],
  channels: string[],
): void {
  const existing = new Set(channels.map((channel) => normalizeChannel(channel)));
  const definedChannels = new Set(bindings.map((binding) => binding.channel));
 
  const appendAlias = (freeZoneChannel: string, scratchChannel: string): void => {
    if (!existing.has(freeZoneChannel) || definedChannels.has(freeZoneChannel)) {
      return;
    }
    const scratchBinding = bindings.find((binding) => binding.channel === scratchChannel);
    Iif (!scratchBinding) {
      return;
    }
    for (const token of scratchBinding.inputTokens) {
      const normalizedToken = token.toLowerCase();
      const mappedChannels = inputTokenToChannels.get(normalizedToken) ?? [];
      Eif (!mappedChannels.includes(freeZoneChannel)) {
        mappedChannels.push(freeZoneChannel);
        inputTokenToChannels.set(normalizedToken, mappedChannels);
      }
    }
  };
 
  for (const zone of _____FREE_ZONES) {
    appendAlias(zone.channel, zone.scratch);
  }
}
 
export function resolveLaneDisplayMode(channels: string[], options: LaneModeOptions = {}): string {
  const existing = new Set(channels.map((channel) => normalizeChannel(channel)));
  if (existing.size === 0 && !options.playVariant?.startsWith('generic-')) {
    return 'UNKNOWN';
  }
  return PLAY_MODE_LAYOUTS[resolveLaneLayout(existing, options)].label;
}
 
/**
 * Lane layout for a channel set. The play variant always comes from `resolveChartPlayVariant` (`@be-music/chart-model`), the
 * rule every host shares: the host-declared `playVariant` when there is one, otherwise the shared rule run over these
 * channels, `chartExtension`, and `player`. There is deliberately no second heuristic here, so the engine, the CLI, and
 * the web hosts cannot disagree on 5 KEY vs 7 KEY (and on the beatoraja judge windows that follow from it). 9 KEY then
 * picks its PMS-STD or BME-type layout from the channels.
 */
function resolveLaneLayout(existing: ReadonlySet<string>, options: LaneModeOptions): PlayModeLayoutId {
  const variant =
    options.playVariant ??
    resolveChartPlayVariant({
      chartPath: options.chartExtension,
      events: Array.from(existing, (channel) => ({ channel })),
      bms: { player: options.player },
    });
  if (variant.startsWith('generic-')) return getPlayModeLayouts(variant)[0]!.id;
  if (variant !== '9') {
    return variant;
  }
  return resolvePMS9KeyLayout(existing, options.chartExtension);
}
 
/**
 * The second key of each scratch lane, as the tokens it arrives as: Left / Right Ctrl, or Option (Alt) on macOS
 * terminals, and Space with the 1P one (LR2's default key config turns the 1P turntable down with Left Ctrl or Space).
 * It plays the lane like the Shift key does, and under the odd-even rule it is the reverse spin of a back-spin scratch
 * (`LaneBinding.inputKeys`).
 */
function createScratchReverseTokensByChannel(
  bindings: readonly FixedLaneDefinition[],
  platform: NodeJS.Platform = resolveDefaultPlatform(),
): Map<string, readonly string[]> {
  const scratchChannels = bindings.filter((binding) => binding.isScratch).map((binding) => binding.channel);
  const tokenMap = new Map<string, readonly string[]>();
 
  if (scratchChannels.includes('16')) {
    tokenMap.set(
      '16',
      platform === 'darwin' ? ['option-left', 'alt-left', 'space'] : ['ctrl-left', 'control-left', 'space'],
    );
  }
  if (scratchChannels.includes('26')) {
    tokenMap.set('26', platform === 'darwin' ? ['option-right', 'alt-right'] : ['ctrl-right', 'control-right']);
  }
 
  return tokenMap;
}
 
/**
 * Browser-safe `process.platform` lookup. Falls back to `'linux'` when running outside Node — the value is only
 * consulted by the scratch-reverse token mapping (option / ctrl modifier choice), and `'linux'` produces the
 * non-darwin tokens the engine's web-based callers expect. Bare `process.platform` would throw a
 * `ReferenceError` on first chart load in a browser bundle that doesn't ship a `process` polyfill.
 */
function resolveDefaultPlatform(): NodeJS.Platform {
  const proc = (globalThis as { process?: { platform?: NodeJS.Platform } }).process;
  return proc?.platform ?? ('linux' as NodeJS.Platform);
}
 
/** The keys only one 9 KEY layout has: PMS-STD's `22..25` and the BME type's `16..19`. */
const PMS_STD_ONLY_CHANNELS = POPN_9KEY_PMS_LANES.filter((channel) => !POPN_9KEY_BME_LANES.includes(channel));
const PMS_BME_ONLY_CHANNELS = POPN_9KEY_BME_LANES.filter((channel) => !POPN_9KEY_PMS_LANES.includes(channel));
 
function resolvePMS9KeyLayout(existing: ReadonlySet<string>, chartExtension: string | undefined): '9-pms' | '9-bme' {
  const pmsLayoutScore = countExistingChannels(existing, PMS_STD_ONLY_CHANNELS);
  const bmeLayoutScore = countExistingChannels(existing, PMS_BME_ONLY_CHANNELS);
 
  if (pmsLayoutScore === 0 && bmeLayoutScore === 0) {
    return isPMSChartPath(chartExtension) ? '9-pms' : '9-bme';
  }
  return pmsLayoutScore >= bmeLayoutScore ? '9-pms' : '9-bme';
}
 
function countExistingChannels(existing: ReadonlySet<string>, channels: readonly string[]): number {
  let count = 0;
  for (const channel of channels) {
    if (existing.has(channel)) {
      count += 1;
    }
  }
  return count;
}
 
/** The That-Which-Must-Not-Be-Named FREE ZONE channels, each played on its side's scratch (`17` → `16`, `27` → `26`). */
const _____FREE_ZONES = PLAY_MODE_LAYOUTS['14'].freeZones;
 
function resolveFreeZoneScratchChannel(channel: string): string | undefined {
  const normalized = normalizeChannel(channel);
  return _____FREE_ZONES.find((zone) => zone.channel === normalized)?.scratch;
}
 
const EXTENDED_LANE_DIGITS = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
/** Lanes per side in the keyboard modes — the 24 keys, then the wheel up / down (`1P` / `1Q`). */
const KEYBOARD_MODE_SIDE_LANE_COUNT = PLAY_MODE_LAYOUTS['24'].lanes.length;
 
function resolveLaneIndex(lane: string): number | undefined {
  const index = EXTENDED_LANE_DIGITS.indexOf(lane.toUpperCase());
  if (index < 0) {
    return undefined;
  }
  return index + 1;
}
 
export function createInputTokenToChannelsMap(bindings: LaneBinding[]): Map<string, string[]> {
  const map = new Map<string, string[]>();
  for (const binding of bindings) {
    for (const token of binding.inputTokens) {
      const normalized = token.toLowerCase();
      const channels = map.get(normalized) ?? [];
      channels.push(binding.channel);
      map.set(normalized, channels);
    }
  }
  return map;
}