Skip to content

CSS Minify & Beautify — TypeScript source

Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the CSS Minify & Beautify tool (slug: css-minify). One
// scanner splits the input into strings (opaque sentinels), comments
// (dropped) and text. Every textual rule below uses RE2-compatible regexes
// (no lookaround) so the Go CLI twin reproduces byte-identical output:
//   minify — collapse whitespace, strip spaces around {} ; : , >, drop the
//     last semicolon before }, lowercase and shorten #aabbcc hexes, strip
//     leading zeros (0.5 → .5) and trailing fraction zeros (1.50 → 1.5, 1.00 → 1).
//   beautify — one selector line per block, one declaration per line at
//     2-space depth, each declaration keeps its own semicolon.
export type CssFormatResult =
  | { output: string; error: null }
  /** Empty or whitespace-only input is NOT an error — the tool shows nothing. */
  | { output: ''; error: null }
  | { output: ''; error: string };

/** Scan CSS into a masked text where every string literal is replaced by a
 * \u0000n\u0000 sentinel (n = index into `strings`). Comments are dropped. */
function mask(raw: string): { masked: string; strings: string[] } | { error: string } {
  let out = '';
  const strings: string[] = [];
  let i = 0;
  while (i < raw.length) {
    const ch = raw[i];
    if (ch === '"' || ch === "'") {
      const start = i;
      i++;
      while (i < raw.length && raw[i] !== ch) {
        if (raw[i] === '\\' && i + 1 < raw.length) i++; // escaped char
        i++;
      }
      if (i >= raw.length) return { error: 'Unterminated string' };
      i++;
      strings.push(raw.slice(start, i));
      out += `\u0000${strings.length - 1}\u0000`;
    } else if (ch === '/' && raw[i + 1] === '*') {
      const end = raw.indexOf('*/', i + 2);
      if (end === -1) return { error: 'Unterminated comment' };
      i = end + 2;
    } else {
      out += ch;
      i++;
    }
  }
  return { masked: out, strings };
}

function unmask(text: string, strings: string[]): string {
  return text.replace(/\u0000(\d+)\u0000/g, (_, n) => strings[Number(n)]);
}

/** Conservative minification — see header for the exact rule list. */
export function minifyCss(raw: string): CssFormatResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  const m = mask(text);
  if ('error' in m) return { output: '', error: m.error };
  let css = m.masked;
  css = css
    .replace(/\s+/g, ' ')
    .replace(/\s*([{};:,>])\s*/g, '$1')
    .replace(/;+}/g, '}')
    .trim()
    .replace(/#[0-9a-fA-F]{3,8}/g, (h) => h.toLowerCase())
    .replace(/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)/g, '#$1$2$3$4')
    .replace(/(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/g, '$1$2')
    .replace(/(\.[0-9]*[1-9])0+([^0-9]|$)/g, '$1$2')
    .replace(/(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)/g, '$1$2$3')
    .replace(/(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)/g, '$10$2');
  return { output: unmask(css, m.strings), error: null };
}

/** Structural beautifier — 2-space indentation, declarations one per line. */
export function beautifyCss(raw: string): CssFormatResult {
  const text = raw.trim();
  if (!text) return { output: '', error: null };
  const m = mask(text);
  if ('error' in m) return { output: '', error: m.error };
  const css = m.masked.replace(/\s+/g, ' ');
  const strings = m.strings;
  let out = '';
  let buffer = '';
  let depth = 0;
  const pad = () => '  '.repeat(depth);
  const flushDecl = (semi: boolean) => {
    // Whitespace was already collapsed to single spaces by the global pass,
    // so only trimming remains here.
    const decl = buffer.trim();
    if (decl) out += `${pad()}${decl}${semi ? ';' : ''}\n`;
    buffer = '';
  };
  for (let i = 0; i < css.length; i++) {
    const ch = css[i];
    if (ch === '{') {
      const sel = buffer.trim();
      buffer = '';
      if (sel) out += `${pad()}${sel} {\n`;
      else return { output: '', error: 'Block without a selector' };
      depth++;
    } else if (ch === '}') {
      flushDecl(false);
      depth--;
      if (depth < 0) return { output: '', error: 'Unbalanced }' };
      out += `${pad()}}\n`;
    } else if (ch === ';') {
      flushDecl(true);
    } else {
      buffer += ch;
    }
  }
  if (depth !== 0) return { output: '', error: 'Unclosed block' };
  flushDecl(false);
  return { output: unmask(out, strings), error: null };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →