Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.2 KB
Raw Blame
import mime from 'mime';

import { sniffBinaryBuffer } from './isBinaryContent';

// Extensions where mime-db has no entry (or a wrong one) but a specific
// text/x-* mime helps downstream language detection.
const CUSTOM_MIME_TYPES: Record<string, string> = {
  '.clj': 'text/x-clojure',
  '.ex': 'text/x-elixir',
  '.exs': 'text/x-elixir',
  '.go': 'text/x-go',
  '.hs': 'text/x-haskell',
  '.kt': 'text/x-kotlin',
  '.lua': 'text/x-lua',
  '.pl': 'text/x-perl',
  '.py': 'text/x-python',
  '.r': 'text/x-r',
  '.rb': 'text/x-ruby',
  '.rs': 'text/x-rust',
  '.scala': 'text/x-scala',
  '.svelte': 'text/x-svelte',
  '.swift': 'text/x-swift',
  '.sv': 'text/x-systemverilog',
  '.v': 'text/x-verilog',
  '.vue': 'text/x-vue',
};

const SNIFF_BYTES = 8192;
const TEXT_FALLBACK_MIME = 'text/plain; charset=utf-8';
const BINARY_FALLBACK_MIME = 'application/octet-stream';

// mime.getType returns bare types (e.g. 'application/json'); text-like
// responses need an explicit charset for the renderer.
const TEXT_MIME_PATTERN =
  /^(?:text\/|application\/(?:ecmascript|graphql|javascript|json|toml|xhtml\+xml|xml|yaml))/;

// SVG is text on disk but must keep its registered type: browsers only render
// it as an image from `image/svg+xml`, never from text/plain or application/xml.
// Other `+xml` types (atom, rss, …) stay on the text downgrade so text previews
// keep working for them.
const SVG_MIME = 'image/svg+xml';

// A MIME charset label (RFC 2046), not a Node.js encoding name; `utf8` is not
// a registered label, so keep the hyphen.
// oxlint-disable-next-line unicorn/text-encoding-identifier-case
const DEFAULT_CHARSET = 'utf-8';

const withCharset = (mimeType: string, charset: string = DEFAULT_CHARSET): string =>
  TEXT_MIME_PATTERN.test(mimeType) && !mimeType.includes('charset=')
    ? `${mimeType}; charset=${charset}`
    : mimeType;

const getExtension = (filePath: string): string => {
  const fileName = filePath.replace(/^.*[/\\]/s, '');
  const dotIndex = fileName.lastIndexOf('.');

  return dotIndex > 0 ? fileName.slice(dotIndex).toLowerCase() : '';
};

const lookupExtensionMime = (filePath: string): string | null => {
  const ext = getExtension(filePath);
  return CUSTOM_MIME_TYPES[ext] ?? mime.getType(filePath);
};

// Trimmed binary sniff: any null byte in the first 8KB β†’ binary. Enough to
// disambiguate text sources from binary payloads for the downgrade rule.
const looksBinary = (buffer: Uint8Array): boolean => {
  const limit = Math.min(buffer.byteLength, SNIFF_BYTES);
  for (let i = 0; i < limit; i++) {
    if (buffer[i] === 0) return true;
  }
  return false;
};

type Utf16Charset = 'utf-16be' | 'utf-16le';

/**
 * Detect UTF-16 text marked by a byte order mark.
 *
 * The UTF-16LE BOM (0xFF 0xFE) is also a valid MPEG audio frame sync, so
 * file-type reports Windows PowerShell 5.1 output (`Tee-Object`, `Out-File`)
 * as audio/mpeg. The BOM alone is not proof: a real MPEG-1 Layer I frame can
 * start with the same bytes. Decode the bytes after the BOM strictly and
 * require them to read as text: compressed audio contains unpaired surrogates,
 * and a lenient decode would turn them into "printable" characters. `stream`
 * keeps a surrogate pair split by the sample boundary from failing the decode.
 */
const detectUtf16BomText = (buffer: Uint8Array): Utf16Charset | null => {
  if (buffer.byteLength < 2) return null;

  let charset: Utf16Charset;
  if (buffer[0] === 0xff && buffer[1] === 0xfe) charset = 'utf-16le';
  else if (buffer[0] === 0xfe && buffer[1] === 0xff) charset = 'utf-16be';
  else return null;

  const sample = buffer.subarray(2, Math.min(buffer.byteLength, SNIFF_BYTES));
  let text: string;
  try {
    text = new TextDecoder(charset, { fatal: true }).decode(sample, { stream: true });
  } catch {
    return null;
  }

  return sniffBinaryBuffer(new TextEncoder().encode(text)).isBinary ? null : charset;
};

/**
 * Sync extension-only lookup. Falls back to `application/octet-stream` for
 * unknown extensions. Use this when a file buffer isn't available (URL input,
 * TRPC payload, filename-only records).
 */
export const getMimeType = (filePath: string): string => {
  return lookupExtensionMime(filePath) || BINARY_FALLBACK_MIME;
};

/**
 * Extension-only lookup with charset appended for text mimes. Returns
 * `undefined` for unknown extensions so the caller can leave `Content-Type`
 * unset instead of forcing a download via `application/octet-stream`.
 * Use this for HTTP responses over known-closed asset sets (Vite output,
 * bundled resources, …).
 */
export const tryGetMimeType = (filePath: string): string | undefined => {
  const detected = lookupExtensionMime(filePath);
  return detected ? withCharset(detected) : undefined;
};

/**
 * Resolve a MIME type from a file path and its content buffer.
 *
 * Extension alone is ambiguous β€” `.ts` is `video/mp2t` in mime-db and also a
 * TypeScript source; a `.pdf` header is printable ASCII for the first bytes.
 * Trust magic bytes first, then fall back to the extension, and let a text
 * sniff overrule mime-db when the two disagree.
 *
 * 0. UTF-16 BOM text β†’ text mime with the matching charset, before the
 *    magic-byte check (the UTF-16LE BOM looks like an MPEG audio frame).
 *    Keeps a text extension mime, otherwise falls back to text/plain.
 * 1. `fileTypeFromBuffer()` β€” magic-byte detection. Authoritative when it
 *    matches: real MPEG-TS media wins here regardless of extension. The one
 *    exception is a generic `application/xml` match, which yields to the
 *    `.svg` extension (an SVG with an `<?xml` prolog).
 * 2. Extension lookup (custom map + `mime.getType`) β€” the only signal for
 *    text formats file-type can't fingerprint (json/css/md/svg/…).
 *    - Text mime β†’ use as-is (with charset appended).
 *    - `image/svg+xml` β†’ use as-is; it is text but must render as an image.
 *    - Binary mime + non-empty buffer that sniffs as text β†’ downgrade to
 *      text/plain. Saves TypeScript source from mime-db's `video/mp2t`.
 *    - Otherwise β†’ use the extension mime.
 * 3. No extension mapping β†’ sniff-based fallback.
 */
export const resolveMimeType = async (filePath: string, buffer: Uint8Array): Promise<string> => {
  const fromExtension = lookupExtensionMime(filePath);

  const utf16Charset = detectUtf16BomText(buffer);
  if (utf16Charset) {
    if (fromExtension === SVG_MIME) return SVG_MIME;
    return fromExtension && TEXT_MIME_PATTERN.test(fromExtension)
      ? withCharset(fromExtension, utf16Charset)
      : `text/plain; charset=${utf16Charset}`;
  }

  const { fileTypeFromBuffer } = await import('file-type');
  const detected = await fileTypeFromBuffer(buffer);
  if (detected?.mime) {
    // file-type fingerprints any `<?xml` prolog as generic application/xml,
    // which would hide an SVG's image/svg+xml; the extension is more specific.
    if (detected.mime === 'application/xml' && fromExtension === SVG_MIME) return SVG_MIME;
    return detected.mime;
  }

  const isBinary = looksBinary(buffer);
  if (fromExtension) {
    if (TEXT_MIME_PATTERN.test(fromExtension)) return withCharset(fromExtension);
    if (fromExtension === SVG_MIME) return SVG_MIME;
    if (buffer.byteLength > 0 && !isBinary) return TEXT_FALLBACK_MIME;
    return fromExtension;
  }

  return isBinary ? BINARY_FALLBACK_MIME : TEXT_FALLBACK_MIME;
};