src / fileSearch / web / encoding.ts

import { load } from "cheerio";

export type DocumentEncoding = "auto" | "utf-8" | "utf-16le" | "utf-16be" | "shift_jis";
export type EncodingSource = "manual" | "bom" | "html-meta" | "utf8" | "sjis-fallback";
const hint = 'Use @file-encoding auto, utf-8, utf-16le, utf-16be or sjis on its own line; optionally add a filename, e.g. @file-encoding sjis "page.html".';

export function normalizeEncoding(label: string): DocumentEncoding {
  const value = label.trim().toLowerCase();
  if (value === "auto") return value;
  // Node's TextDecoder recognizes windows-31j but not the common CP932 label.
  if (["cp932", "windows-932"].includes(value)) return "shift_jis";
  try {
    const encoding = new TextDecoder(value).encoding;
    if (["utf-8", "utf-16le", "utf-16be", "shift_jis"].includes(encoding)) return encoding as DocumentEncoding;
  } catch { /* Report the same actionable error for unknown/unsupported labels. */ }
  throw new Error(`Unsupported document encoding: ${label}. ${hint}`);
}

export interface EncodingPreferences { defaultEncoding: DocumentEncoding; overrides: Map<string, DocumentEncoding>; }
export function encodingForFile(preferences: EncodingPreferences, name: string): DocumentEncoding {
  return preferences.overrides.get(name) ?? preferences.defaultEncoding;
}

export function encodingPreferencesForMessages(messages: {isUserMessage(): boolean; getText(): string}[]): EncodingPreferences {
  const preferences: EncodingPreferences = { defaultEncoding: "auto", overrides: new Map() };
  for (const message of messages) {
    if (!message.isUserMessage()) continue;
    let fence: string | undefined;
    for (const line of message.getText().split(/\r?\n/)) {
      const delimiter = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
      if (delimiter) {
        if (!fence) fence = delimiter;
        else if (delimiter[0] === fence[0] && delimiter.length >= fence.length) fence = undefined;
        continue;
      }
      if (fence || !/^\s*@file-encoding(?:\s|$)/i.test(line)) continue;
      const match = /^\s*@file-encoding\s+(\S+)(?:\s+(.+?))?\s*$/i.exec(line);
      if (!match) throw new Error(hint);
      const encoding = normalizeEncoding(match[1]);
      let name = match[2]?.trim();
      if (name?.startsWith('"')) {
        try { name = JSON.parse(name); } catch { throw new Error(hint); }
      }
      if (name !== undefined) {
        if (typeof name !== "string" || !name.trim() || name.length > 512) throw new Error(hint);
        preferences.overrides.set(name, encoding);
      } else preferences.defaultEncoding = encoding;
    }
  }
  return preferences;
}

export function encodingForMessages(messages: {isUserMessage(): boolean; getText(): string}[]): DocumentEncoding {
  return encodingPreferencesForMessages(messages).defaultEncoding;
}

function declaredHtmlEncoding(bytes: Buffer): DocumentEncoding | undefined {
  // Read ASCII markup without first decoding its Japanese body. Parsing avoids
  // mistaking meta-like text in comments/scripts for an actual declaration.
  const $ = load(bytes.subarray(0, 64 * 1024).toString("latin1"));
  for (const el of $("meta").toArray()) {
    const meta = $(el);
    let label = meta.attr("charset")?.trim();
    if (!label && meta.attr("http-equiv")?.toLowerCase() === "content-type") {
      label = /(?:^|;)\s*charset\s*=\s*["']?([^\s;"']+)/i.exec(meta.attr("content") ?? "")?.[1];
    }
    if (label) {
      const encoding = normalizeEncoding(label);
      if (encoding === "auto") throw new Error(`Invalid HTML charset: auto. ${hint}`);
      return encoding;
    }
  }
  return undefined;
}

export function decodeDocument(name: string, bytes: Buffer, override: DocumentEncoding = "auto"):
  {text: string; encoding: Exclude<DocumentEncoding, "auto">; encodingSource: EncodingSource} {
  const manual = normalizeEncoding(override);
  const decode = (encoding: Exclude<DocumentEncoding, "auto">, encodingSource: EncodingSource) => {
    try {
      return {text: new TextDecoder(encoding, {fatal: true}).decode(bytes), encoding, encodingSource};
    } catch {
      throw new Error(`Cannot decode ${name} as ${encoding} (${encodingSource}). ${hint}`);
    }
  };
  if (manual !== "auto") return decode(manual, "manual");
  if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) return decode("utf-8", "bom");
  if (bytes[0] === 0xff && bytes[1] === 0xfe) return decode("utf-16le", "bom");
  if (bytes[0] === 0xfe && bytes[1] === 0xff) return decode("utf-16be", "bom");
  if (/\.html?$/i.test(name)) {
    const declared = declaredHtmlEncoding(bytes);
    if (declared && declared !== "auto") return decode(declared, "html-meta");
  }
  try { return decode("utf-8", "utf8"); }
  catch { return decode("shift_jis", "sjis-fallback"); }
}