All files / player-terminal/src manual-input.ts

76.5% Statements 293/383
64.49% Branches 178/276
94.28% Functions 33/35
76.88% Lines 286/372

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                                                                                      4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     2x     2x 2x 2x 2x     2x 2x         2x     2x 2x 2x 2x     2x 2x                 3x 3x 3x 3x 3x 3x     3x 3x 3x               3x 3x 1x     2x 2x   1x           2x 1x           1x             167x       172x 172x 172x   172x   172x                                 172x 172x 81x                 91x 91x 91x 91x 92x 92x 31x 29x   63x 25x 25x   57x   91x                   172x 172x 94x                 78x 78x 78x 78x 78x 78x 53x 72x 53x   28x   78x                   172x                   172x 172x 172x 172x     172x         172x           172x 3x 3x 3x   3x   3x   3x         172x 1x 1x 1x 1x 1x 1x       172x                       172x 172x       172x   172x         172x   172x 92x 92x     92x 92x 92x         92x 36x 36x 36x 56x 6x 6x 6x   92x 92x 92x 92x 92x 92x 92x 92x 92x 92x   92x 92x 89x     92x               172x       172x 172x       172x   172x 172x 78x 78x 78x 78x 78x 78x               78x               172x       772x 187x   585x 585x       92x 92x 78x 78x   14x 14x 14x 14x 14x 14x   92x 2x 2x 2x   12x 4x 4x 4x   8x 1x 1x 1x 1x 1x   7x             7x             7x 1x 1x 1x 1x 1x     6x   6x     6x   6x       6x 6x 3x 3x 2x     6x 2x 2x 2x   6x 1x 1x 1x 1x     6x       78x   78x 72x 72x   6x 6x 6x 6x 6x 6x 78x   78x                 6x 1x       1x 1x   1x 1x 1x   5x 1x 1x 1x         1x 1x 1x     4x   4x     4x   4x       4x 4x 4x 4x 1x     4x 3x 3x   4x       4x 3x 3x 3x 3x     4x       4x       4x                 4x       4x 1x   3x 3x                 6x 6x     6x 6x     6x       172x       172x 172x       172x       172x 172x       179x       1x 1x                                                                
import readline from 'node:readline';
import {
  appendFreeZoneInputChannels,
  createInputTokenToChannelsMap,
  createLaneBindings,
  resolveLaneDisplayMode,
} from '@be-music/player-engine/lanes';
export { appendFreeZoneInputChannels, createInputTokenToChannelsMap, createLaneBindings, resolveLaneDisplayMode };
export type { LaneBinding, LaneModeOptions } from '@be-music/player-engine/lanes';
 
interface KittyKeyboardEvent {
  keyCode: number;
  shiftedKeyCode?: number;
  baseKeyCode?: number;
  modifiers: number;
  eventType: number;
}
 
export interface ResolvedInputTokenEvent {
  tokens: string[];
  repeatTokens: string[];
  releaseTokens: string[];
  protocol: 'legacy' | 'kitty' | 'win32';
  kittyProtocolEvent: boolean;
}
 
export interface InputProtocolInspection {
  protocol: 'legacy' | 'kitty' | 'win32';
  detected: boolean;
  tokens: string[];
  repeatTokens: string[];
  releaseTokens: string[];
}
 
export interface InspectedInputTokenEvent {
  selected: ResolvedInputTokenEvent;
  protocols: {
    legacy: InputProtocolInspection;
    kitty: InputProtocolInspection;
    win32: InputProtocolInspection;
  };
}
 
const KITTY_KEYBOARD_PROTOCOL_ENABLE_FLAGS = 11;
const KITTY_KEYBOARD_PROTOCOL_ENABLE_SEQUENCE = `\u001b[>${KITTY_KEYBOARD_PROTOCOL_ENABLE_FLAGS}u`;
const KITTY_KEYBOARD_PROTOCOL_DISABLE_SEQUENCE = '\u001b[<u';
const KITTY_MODIFIER_SHIFT_MASK = 1;
const KITTY_MODIFIER_ALT_MASK = 2;
const KITTY_MODIFIER_CTRL_MASK = 4;
const KITTY_EVENT_TYPE_REPEAT = 2;
const KITTY_EVENT_TYPE_RELEASE = 3;
const KITTY_LEFT_SHIFT_KEY_CODES = new Set([57_441, 441]);
const KITTY_RIGHT_SHIFT_KEY_CODES = new Set([57_447, 447]);
const KITTY_LEFT_CTRL_KEY_CODES = new Set([57_442, 442]);
const KITTY_RIGHT_CTRL_KEY_CODES = new Set([57_448, 448]);
const KITTY_LEFT_ALT_KEY_CODES = new Set([57_443, 443]);
const KITTY_RIGHT_ALT_KEY_CODES = new Set([57_449, 449]);
const WIN32_INPUT_MODE_ENABLE_SEQUENCE = '\u001b[?9001h';
const WIN32_INPUT_MODE_DISABLE_SEQUENCE = '\u001b[?9001l';
const WIN32_CONTROL_STATE_RIGHT_ALT = 0x0001;
const WIN32_CONTROL_STATE_LEFT_ALT = 0x0002;
const WIN32_CONTROL_STATE_RIGHT_CTRL = 0x0004;
const WIN32_CONTROL_STATE_LEFT_CTRL = 0x0008;
const WIN32_CONTROL_STATE_SHIFT = 0x0010;
const WIN32_VK_SHIFT = 0x10;
const WIN32_VK_CONTROL = 0x11;
const WIN32_VK_MENU = 0x12;
const WIN32_VK_RETURN = 0x0d;
const WIN32_VK_ESCAPE = 0x1b;
const WIN32_VK_SPACE = 0x20;
const WIN32_VK_TAB = 0x09;
 
export function beginKittyKeyboardProtocolOptIn(stdout: NodeJS.WriteStream = process.stdout): () => void {
  Iif (!stdout.isTTY || !process.stdin.isTTY) {
    return () => undefined;
  }
  stdout.write(KITTY_KEYBOARD_PROTOCOL_ENABLE_SEQUENCE);
  let ended = false;
  return () => {
    Iif (ended) {
      return;
    }
    ended = true;
    stdout.write(KITTY_KEYBOARD_PROTOCOL_DISABLE_SEQUENCE);
  };
}
 
export function beginWin32InputModeOptIn(stdout: NodeJS.WriteStream = process.stdout): () => void {
  Iif (!stdout.isTTY || !process.stdin.isTTY) {
    return () => undefined;
  }
  stdout.write(WIN32_INPUT_MODE_ENABLE_SEQUENCE);
  let ended = false;
  return () => {
    Iif (ended) {
      return;
    }
    ended = true;
    stdout.write(WIN32_INPUT_MODE_DISABLE_SEQUENCE);
  };
}
 
export function beginStatefulKeyboardProtocolOptIn(
  stdout: NodeJS.WriteStream = process.stdout,
  platform: NodeJS.Platform = process.platform,
  env: NodeJS.ProcessEnv = process.env,
): () => void {
  const protocols = resolveEnabledStatefulKeyboardProtocols(platform, env);
  const stopKitty = protocols.kitty ? beginKittyKeyboardProtocolOptIn(stdout) : () => undefined;
  const stopWin32 = protocols.win32 ? beginWin32InputModeOptIn(stdout) : () => undefined;
  let ended = false;
  return () => {
    Iif (ended) {
      return;
    }
    ended = true;
    stopWin32();
    stopKitty();
  };
}
 
function resolveEnabledStatefulKeyboardProtocols(
  platform: NodeJS.Platform,
  env: NodeJS.ProcessEnv,
): { kitty: boolean; win32: boolean } {
  const override = env.BE_MUSIC_KEYBOARD_PROTOCOLS?.trim().toLowerCase();
  if (override) {
    const values = new Set(
      override
        .split(',')
        .map((value) => value.trim())
        .filter((value) => value.length > 0),
    );
    return {
      kitty: values.has('kitty'),
      win32: values.has('win32'),
    };
  }
 
  if (platform === 'win32') {
    return {
      kitty: false,
      win32: true,
    };
  }
 
  return {
    kitty: true,
    win32: false,
  };
}
 
export function resolveInputTokenEvent(chunk: string, key: readline.Key): ResolvedInputTokenEvent {
  return inspectInputTokenEvent(chunk, key).selected;
}
 
export function inspectInputTokenEvent(chunk: string, key: readline.Key): InspectedInputTokenEvent {
  const kittyResolved = resolveKittyInputTokenEvent(chunk, key);
  const win32Resolved = resolveWin32InputTokenEvent(chunk, key);
  const legacyResolved = resolveLegacyInputTokenEvent(chunk, key);
 
  const selected = kittyResolved.detected ? kittyResolved : win32Resolved.detected ? win32Resolved : legacyResolved;
 
  return {
    selected: {
      tokens: [...selected.tokens],
      repeatTokens: [...selected.repeatTokens],
      releaseTokens: [...selected.releaseTokens],
      protocol: selected.protocol,
      kittyProtocolEvent: selected.protocol === 'kitty',
    },
    protocols: {
      legacy: legacyResolved,
      kitty: kittyResolved,
      win32: win32Resolved,
    },
  };
}
 
function resolveKittyInputTokenEvent(chunk: string, key: readline.Key): InputProtocolInspection {
  const kittyEvents = parseKittyKeyboardEvents(chunk, key);
  if (kittyEvents.length === 0) {
    return {
      protocol: 'kitty',
      detected: false,
      tokens: [],
      repeatTokens: [],
      releaseTokens: [],
    };
  }
 
  const tokens = new Set<string>();
  const repeatTokens = new Set<string>();
  const releaseTokens = new Set<string>();
  for (const kittyEvent of kittyEvents) {
    const kittyTokens = resolveKittyInputTokens(kittyEvent);
    if (kittyEvent.eventType === KITTY_EVENT_TYPE_RELEASE) {
      kittyTokens.forEach((token) => releaseTokens.add(token));
      continue;
    }
    if (kittyEvent.eventType === KITTY_EVENT_TYPE_REPEAT) {
      kittyTokens.forEach((token) => repeatTokens.add(token));
      continue;
    }
    kittyTokens.forEach((token) => tokens.add(token));
  }
  return {
    protocol: 'kitty',
    detected: true,
    tokens: [...tokens],
    repeatTokens: [...repeatTokens],
    releaseTokens: [...releaseTokens],
  };
}
 
function resolveWin32InputTokenEvent(chunk: string, key: readline.Key): InputProtocolInspection {
  const win32Events = parseWin32InputEvents(chunk, key);
  if (win32Events.length === 0) {
    return {
      protocol: 'win32',
      detected: false,
      tokens: [],
      repeatTokens: [],
      releaseTokens: [],
    };
  }
 
  const tokens = new Set<string>();
  const repeatTokens = new Set<string>();
  const releaseTokens = new Set<string>();
  for (const event of win32Events) {
    const eventTokens = resolveWin32InputTokens(event);
    if (event.keyDown) {
      const target = event.repeatCount > 1 ? repeatTokens : tokens;
      eventTokens.forEach((token) => target.add(token));
      continue;
    }
    eventTokens.forEach((token) => releaseTokens.add(token));
  }
  return {
    protocol: 'win32',
    detected: true,
    tokens: [...tokens],
    repeatTokens: [...repeatTokens],
    releaseTokens: [...releaseTokens],
  };
}
 
function resolveLegacyInputTokenEvent(chunk: string, key: readline.Key): InputProtocolInspection {
  return {
    protocol: 'legacy',
    detected: true,
    tokens: resolveLegacyInputTokens(chunk, key),
    repeatTokens: [],
    releaseTokens: [],
  };
}
 
function resolveLegacyInputTokens(chunk: string, key: readline.Key): string[] {
  const tokens = new Set<string>();
  const normalizedChunk = normalizeKey(chunk);
  Eif (normalizedChunk) {
    tokens.add(normalizedChunk);
  }
 
  Iif (isStandaloneShiftKeypress(chunk, key)) {
    tokens.add('shift');
    return [...tokens];
  }
 
  Iif (isStandaloneControlKeypress(chunk, key)) {
    tokens.add('ctrl');
    tokens.add('control');
    return [...tokens];
  }
 
  if (key.name) {
    const normalizedName = key.name.toLowerCase();
    tokens.add(normalizedName);
    Iif (normalizedName === 'return') {
      tokens.add('enter');
    } else Iif (normalizedName === 'enter') {
      tokens.add('return');
    } else Iif (normalizedName === 'ctrl') {
      tokens.add('control');
    } else Iif (normalizedName === 'control') {
      tokens.add('ctrl');
    }
  }
 
  if (key.meta) {
    tokens.add('alt');
    tokens.add('option');
    const altKeyToken = resolveLegacyModifierKeyToken(normalizedChunk, key.name);
    Eif (altKeyToken) {
      tokens.add(`alt+${altKeyToken}`);
      tokens.add(`option+${altKeyToken}`);
    }
  }
 
  return [...tokens];
}
 
interface Win32InputEvent {
  virtualKeyCode: number;
  unicodeChar: number;
  keyDown: boolean;
  controlState: number;
  repeatCount: number;
}
 
function parseKittyKeyboardEvents(chunk: string, key: readline.Key): KittyKeyboardEvent[] {
  const sequence = chunk.length > 0 ? chunk : (key.sequence ?? '');
  Iif (sequence.length === 0) {
    return [];
  }
 
  const events: KittyKeyboardEvent[] = [];
  // Preserve prefixless Ghostty modifier chunks, including concatenated press/release events.
  const normalizedSequence = sequence.replace(
    /(^|u)(44[123789](?::[0-9]+){0,2}(?:;[0-9]+(?::[0-9]+)?)?)(?=u)/g,
    '$1\u001b[$2',
  );
  // eslint-disable-next-line no-control-regex
  const regex = /\u001b\[([0-9]*(?::[0-9]+){0,2})(?:;([0-9]+(?::[0-9]+)?))?([u~PQS])/g;
 
  for (const match of normalizedSequence.matchAll(regex)) {
    const keyPart = match[1];
    Iif (typeof keyPart !== 'string') {
      continue;
    }
    const keyCodeParts = (keyPart || '1').split(':');
    let keyCode = parseNumericPart(keyCodeParts[0]);
    Iif (keyCode === undefined) {
      continue;
    }
    // kitty keeps the legacy encodings for F1–F12, including event-type suffixes on releases/repeats.
    // https://sw.kovidgoyal.net/kitty/keyboard-protocol/#functional-key-definitions
    if (match[3] === '~') {
      const index = [11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24].indexOf(keyCode);
      Iif (index < 0) continue;
      keyCode = 57364 + index;
    } else if (match[3] !== 'u') {
      const index = { P: 0, Q: 1, S: 3 }[match[3] as 'P' | 'Q' | 'S'];
      Iif (keyCode !== 1) continue;
      keyCode = 57364 + index;
    }
    const shiftedKeyCode = parseNumericPart(keyCodeParts[1]);
    const baseKeyCode = parseNumericPart(keyCodeParts[2]);
    let modifiers = 1;
    let eventType = 1;
    const modifierPart = match[2];
    Eif (typeof modifierPart === 'string') {
      const [rawModifiers, rawEventType] = modifierPart.split(':');
      const parsedModifiers = parseNumericPart(rawModifiers);
      Eif (parsedModifiers !== undefined) {
        modifiers = parsedModifiers;
      }
      const parsedEventType = parseNumericPart(rawEventType);
      if (parsedEventType !== undefined) {
        eventType = parsedEventType;
      }
    }
    events.push({
      keyCode,
      shiftedKeyCode,
      baseKeyCode,
      modifiers,
      eventType,
    });
  }
  return events;
}
 
function parseWin32InputEvents(chunk: string, key: readline.Key): Win32InputEvent[] {
  const sequence = chunk.length > 0 ? chunk : (key.sequence ?? '');
  Iif (sequence.length === 0) {
    return [];
  }
 
  const events: Win32InputEvent[] = [];
  // eslint-disable-next-line no-control-regex
  const regex = /\u001b\[([0-9]+);([0-9]+);([0-9]+);([01]);([0-9]+);([0-9]+)_/g;
  for (const match of sequence.matchAll(regex)) {
    const virtualKeyCode = parseNumericPart(match[1]);
    const unicodeChar = parseNumericPart(match[3]);
    const keyDown = match[4] === '1';
    const controlState = parseNumericPart(match[5]);
    const repeatCount = parseNumericPart(match[6]);
    Iif (
      virtualKeyCode === undefined ||
      unicodeChar === undefined ||
      controlState === undefined ||
      repeatCount === undefined
    ) {
      continue;
    }
    events.push({
      virtualKeyCode,
      unicodeChar,
      keyDown,
      controlState,
      repeatCount,
    });
  }
  return events;
}
 
function parseNumericPart(value: string | undefined): number | undefined {
  if (typeof value !== 'string' || value.length === 0 || !/^\d+$/.test(value)) {
    return undefined;
  }
  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) ? parsed : undefined;
}
 
function resolveKittyInputTokens(event: KittyKeyboardEvent): Set<string> {
  const tokens = new Set<string>();
  if (event.keyCode >= 57364 && event.keyCode <= 57387) {
    tokens.add(`f${event.keyCode - 57364 + 1}`);
    return tokens;
  }
  const modifierBits = Math.max(0, event.modifiers - 1);
  const hasShift = (modifierBits & KITTY_MODIFIER_SHIFT_MASK) !== 0;
  const hasAlt = (modifierBits & KITTY_MODIFIER_ALT_MASK) !== 0;
  const hasCtrl = (modifierBits & KITTY_MODIFIER_CTRL_MASK) !== 0;
  const hasNonShiftModifier = (modifierBits & ~KITTY_MODIFIER_SHIFT_MASK) !== 0;
  const implicitShiftByKeyCode = event.keyCode >= 65 && event.keyCode <= 90;
 
  if (KITTY_LEFT_SHIFT_KEY_CODES.has(event.keyCode)) {
    tokens.add('shift-left');
    tokens.add('shift');
    return tokens;
  }
  if (KITTY_RIGHT_SHIFT_KEY_CODES.has(event.keyCode)) {
    tokens.add('shift-right');
    tokens.add('shift');
    return tokens;
  }
  if (KITTY_LEFT_CTRL_KEY_CODES.has(event.keyCode)) {
    tokens.add('ctrl-left');
    tokens.add('control-left');
    tokens.add('ctrl');
    tokens.add('control');
    return tokens;
  }
  Iif (KITTY_RIGHT_CTRL_KEY_CODES.has(event.keyCode)) {
    tokens.add('ctrl-right');
    tokens.add('control-right');
    tokens.add('ctrl');
    tokens.add('control');
    return tokens;
  }
  Iif (KITTY_LEFT_ALT_KEY_CODES.has(event.keyCode)) {
    tokens.add('alt-left');
    tokens.add('option-left');
    tokens.add('alt');
    tokens.add('option');
    return tokens;
  }
  if (KITTY_RIGHT_ALT_KEY_CODES.has(event.keyCode)) {
    tokens.add('alt-right');
    tokens.add('option-right');
    tokens.add('alt');
    tokens.add('option');
    return tokens;
  }
 
  Iif (event.keyCode === 27) {
    tokens.add('escape');
  } else Iif (event.keyCode === 13) {
    tokens.add('enter');
    tokens.add('return');
  } else Iif (event.keyCode === 32) {
    tokens.add('space');
  } else Iif (event.keyCode === 9) {
    tokens.add('tab');
  }
 
  const printableToken = resolveKittyPrintableToken(event);
  if (printableToken && !hasNonShiftModifier) {
    tokens.add(printableToken);
    if ((hasShift || implicitShiftByKeyCode) && /^[a-z]$/.test(printableToken)) {
      tokens.add(`shift+${printableToken}`);
    }
  }
  if (hasCtrl && printableToken) {
    tokens.add('ctrl');
    tokens.add('control');
    tokens.add(`ctrl+${printableToken}`);
  }
  if (hasAlt && printableToken) {
    tokens.add('alt');
    tokens.add('option');
    tokens.add(`alt+${printableToken}`);
    tokens.add(`option+${printableToken}`);
  }
 
  return tokens;
}
 
function resolveWin32InputTokens(event: Win32InputEvent): Set<string> {
  const tokens = new Set<string>();
  // Winuser.h VK_F1 through VK_F24: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
  if (event.virtualKeyCode >= 0x70 && event.virtualKeyCode <= 0x87) {
    tokens.add(`f${event.virtualKeyCode - 0x70 + 1}`);
    return tokens;
  }
  const hasLeftAlt = (event.controlState & WIN32_CONTROL_STATE_LEFT_ALT) !== 0;
  const hasRightAlt = (event.controlState & WIN32_CONTROL_STATE_RIGHT_ALT) !== 0;
  const hasLeftCtrl = (event.controlState & WIN32_CONTROL_STATE_LEFT_CTRL) !== 0;
  const hasRightCtrl = (event.controlState & WIN32_CONTROL_STATE_RIGHT_CTRL) !== 0;
  const hasShift = (event.controlState & WIN32_CONTROL_STATE_SHIFT) !== 0;
  const hasAlt = hasLeftAlt || hasRightAlt;
  const hasCtrl = hasLeftCtrl || hasRightCtrl;
 
  Iif (event.virtualKeyCode === WIN32_VK_SHIFT) {
    if (hasRightAlt || hasRightCtrl) {
      tokens.add('shift-right');
    } else {
      tokens.add('shift-left');
    }
    tokens.add('shift');
    return tokens;
  }
  if (event.virtualKeyCode === WIN32_VK_CONTROL) {
    Iif (hasRightCtrl && !hasLeftCtrl) {
      tokens.add('ctrl-right');
      tokens.add('control-right');
    } else {
      tokens.add('ctrl-left');
      tokens.add('control-left');
    }
    tokens.add('ctrl');
    tokens.add('control');
    return tokens;
  }
  if (event.virtualKeyCode === WIN32_VK_MENU) {
    if (hasRightAlt && !hasLeftAlt) {
      tokens.add('alt-right');
      tokens.add('option-right');
    } else E{
      tokens.add('alt-left');
      tokens.add('option-left');
    }
    tokens.add('alt');
    tokens.add('option');
    return tokens;
  }
 
  Iif (event.virtualKeyCode === WIN32_VK_ESCAPE) {
    tokens.add('escape');
  } else Iif (event.virtualKeyCode === WIN32_VK_RETURN) {
    tokens.add('enter');
    tokens.add('return');
  } else Iif (event.virtualKeyCode === WIN32_VK_SPACE) {
    tokens.add('space');
  } else Iif (event.virtualKeyCode === WIN32_VK_TAB) {
    tokens.add('tab');
  }
 
  const printableToken = resolveWin32PrintableToken(event);
  Eif (printableToken) {
    tokens.add(printableToken);
    if (hasShift && /^[a-z]$/.test(printableToken)) {
      tokens.add(`shift+${printableToken}`);
    }
  }
  if (hasLeftCtrl) {
    tokens.add('ctrl-left');
    tokens.add('control-left');
  }
  Iif (hasRightCtrl) {
    tokens.add('ctrl-right');
    tokens.add('control-right');
  }
  if (hasCtrl) {
    tokens.add('ctrl');
    tokens.add('control');
    Eif (printableToken) {
      tokens.add(`ctrl+${printableToken}`);
    }
  }
  Iif (hasLeftAlt) {
    tokens.add('alt-left');
    tokens.add('option-left');
  }
  Iif (hasRightAlt) {
    tokens.add('alt-right');
    tokens.add('option-right');
  }
  Iif (hasAlt) {
    tokens.add('alt');
    tokens.add('option');
    if (printableToken) {
      tokens.add(`alt+${printableToken}`);
      tokens.add(`option+${printableToken}`);
    }
  }
 
  return tokens;
}
 
function resolveWin32PrintableToken(event: Win32InputEvent): string | undefined {
  if (event.unicodeChar >= 32 && event.unicodeChar <= 126) {
    return normalizeKey(String.fromCodePoint(event.unicodeChar));
  }
  Eif (event.virtualKeyCode >= 65 && event.virtualKeyCode <= 90) {
    return String.fromCodePoint(event.virtualKeyCode).toLowerCase();
  }
  if (event.virtualKeyCode >= 48 && event.virtualKeyCode <= 57) {
    return String.fromCodePoint(event.virtualKeyCode);
  }
  return undefined;
}
 
function resolveKittyPrintableToken(event: KittyKeyboardEvent): string | undefined {
  const codePoint = event.baseKeyCode ?? event.keyCode;
  Iif (!Number.isFinite(codePoint) || codePoint < 32 || codePoint > 126) {
    return undefined;
  }
  const value = String.fromCodePoint(codePoint);
  Iif (!value) {
    return undefined;
  }
  return normalizeKey(value);
}
 
function isStandaloneShiftKeypress(chunk: string, key: readline.Key): boolean {
  Iif (key.name === 'shift') {
    return true;
  }
 
  const sequence = key.sequence ?? '';
  return chunk.length === 0 && sequence.length === 0 && Boolean(key.shift) && !key.ctrl && !key.meta && !key.name;
}
 
function isStandaloneControlKeypress(chunk: string, key: readline.Key): boolean {
  Iif (key.name === 'ctrl' || key.name === 'control') {
    return true;
  }
 
  const sequence = key.sequence ?? '';
  return chunk.length === 0 && sequence.length === 0 && Boolean(key.ctrl) && !key.shift && !key.meta && !key.name;
}
 
function normalizeKey(value: string): string {
  return value.length === 1 ? value.toLowerCase() : value;
}
 
function resolveLegacyModifierKeyToken(chunk: string | undefined, keyName: string | undefined): string | undefined {
  Eif (typeof chunk === 'string' && chunk.length === 1) {
    return chunk;
  }
  if (typeof keyName !== 'string' || keyName.length === 0) {
    return undefined;
  }
  const lowered = keyName.toLowerCase();
  if (lowered.length === 1) {
    return lowered;
  }
  if (lowered === 'comma') {
    return ',';
  }
  if (lowered === 'period') {
    return '.';
  }
  if (lowered === 'slash') {
    return '/';
  }
  if (lowered === 'semicolon') {
    return ';';
  }
  if (lowered === 'quote') {
    return "'";
  }
  if (lowered === 'leftbracket') {
    return '[';
  }
  if (lowered === 'rightbracket') {
    return ']';
  }
  return undefined;
}