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

93.33% Statements 56/60
77.58% Branches 45/58
100% Functions 4/4
100% Lines 54/54

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          33x 1x   32x 32x 32x 32x 33x 4x 4x         28x 28x   1x                     297x     788x 7x   4x 4x   3x                   57x 57x 57x 57x 788x 788x 788x 17x 17x   771x 771x 9x 9x 762x 1x 1x 1x 761x 22x 22x   739x 739x 739x 739x 739x 365x   365x 365x 365x 365x   374x 374x 739x 739x 739x     57x    
/**
 * Decodes a course file's bytes. A byte-order mark wins, then an XML `encoding` declaration, then strict UTF-8, and
 * Shift_JIS last: LR2's tools wrote `.lr2crs` files in the system code page.
 */
export function decodeCourseText(bytes: Uint8Array): string {
  if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
    return new TextDecoder('utf-8').decode(bytes.subarray(3));
  }
  Iif (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder('utf-16le').decode(bytes.subarray(2));
  Iif (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder('utf-16be').decode(bytes.subarray(2));
  const head = new TextDecoder('latin1').decode(bytes.subarray(0, 200));
  const declared = /<\?xml[^>]*\bencoding\s*=\s*["']([^"']+)["']/iu.exec(head)?.[1]?.toLowerCase();
  if (declared !== undefined) {
    try {
      return new TextDecoder(declared).decode(bytes);
    } catch {
      // An encoding the runtime does not know: fall through to detection.
    }
  }
  try {
    return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
  } catch {
    return new TextDecoder('shift_jis').decode(bytes);
  }
}
 
/** A parsed XML element: its name, its child elements and its own text (entities decoded, CDATA kept verbatim). */
export interface CourseXMLElement {
  name: string;
  children: CourseXMLElement[];
  text: string;
}
 
const ENTITIES: Readonly<Record<string, string>> = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
 
function decodeEntities(text: string): string {
  return text.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/giu, (match, entity: string) => {
    if (entity[0] === '#') {
      const code =
        entity[1] === 'x' || entity[1] === 'X' ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
      return Number.isFinite(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
    }
    return ENTITIES[entity] ?? match;
  });
}
 
/**
 * A small, tolerant XML reader for course files: elements, text, entities, CDATA, comments and processing
 * instructions. Attributes are skipped (no course format uses them). Returns the root element, or `undefined` when
 * the text holds none. Unclosed elements are closed at the end of the text.
 */
export function parseCourseXML(text: string): CourseXMLElement | undefined {
  const root: CourseXMLElement = { name: '', children: [], text: '' };
  const stack: CourseXMLElement[] = [root];
  let index = 0;
  while (index < text.length) {
    const open = text.indexOf('<', index);
    const top = stack[stack.length - 1]!;
    if (open < 0) {
      top.text += decodeEntities(text.slice(index));
      break;
    }
    top.text += decodeEntities(text.slice(index, open));
    if (text.startsWith('<!--', open)) {
      const end = text.indexOf('-->', open + 4);
      index = end < 0 ? text.length : end + 3;
    } else if (text.startsWith('<![CDATA[', open)) {
      const end = text.indexOf(']]>', open + 9);
      top.text += text.slice(open + 9, end < 0 ? text.length : end);
      index = end < 0 ? text.length : end + 3;
    } else if (text[open + 1] === '?' || text[open + 1] === '!') {
      const end = text.indexOf('>', open);
      index = end < 0 ? text.length : end + 1;
    } else {
      const end = text.indexOf('>', open);
      Iif (end < 0) break;
      const tag = text.slice(open + 1, end).trim();
      index = end + 1;
      if (tag.startsWith('/')) {
        const name = tag.slice(1).trim();
        // Close up to the matching element; a stray close tag is ignored.
        let at = stack.length - 1;
        while (at > 0 && stack[at]!.name !== name) at -= 1;
        Eif (at > 0) stack.length = at;
        continue;
      }
      const selfClosing = tag.endsWith('/');
      const name = /^[^\s/]+/u.exec(tag)?.[0] ?? '';
      const element: CourseXMLElement = { name, children: [], text: '' };
      top.children.push(element);
      if (!selfClosing) stack.push(element);
    }
  }
  return root.children[0];
}