Skip to content

AI Text Summarizer — JavaScript source

Paste any text and get an LLM summary — TL;DR, bullets, or detailed — using your own free Groq key, called straight from your browser.

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

/**
 * text-summarizer - prompt building, reply cleanup, and text stats.
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
 * src/lib/summarize.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: the AI does the summarizing, but everything around
 * the model call is deterministic - sizing up the paste, framing the
 * system/user messages per style, and scrubbing code fences out of the
 * reply. Keeping those pure lets every language port agree byte-for-byte.
 *
 * display source - part of CosmoDev's polyglot tool pages.
 */

/** Styles mirror the SummaryStyle union in the TS lib. */
export const STYLES = ['tldr', 'bullets', 'detailed'];

/** The per-style system-prompt contract, byte-for-byte the TS lib's. */
export const STYLE_CONTRACT = {
  tldr: 'Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.',
  bullets:
    'Summarize the text as 3 to 6 markdown bullets, each starting with "- " and covering one distinct point. No preamble, no closing remark.',
  detailed:
    'Summarize the text as 2 to 4 short paragraphs: what it is about, the key facts, and the outcome or next step. No preamble, no headings.',
};

/** Input cap: longer pastes are cut (and marked) before they reach the model. */
export const MAX_INPUT_CHARS = 12000;

/**
 * Count words / sentences / characters; tolerant of empty input.
 *
 * Sentences count TERMINATOR runs ([.!?]+), not sentence bodies - the body
 * regex is quadratic on terminator-free input, the trap the TS lib's comment
 * documents. chars is text.length: UTF-16 code units, so astral characters
 * (emoji, etc.) count 2.
 */
export function textStats(text) {
  const trimmed = text.trim();
  const words = trimmed ? trimmed.split(/\s+/).length : 0;
  const sentences = (text.match(/[.!?]+/g) ?? []).length;
  return { words, sentences, chars: text.length };
}

/**
 * Build the [system, user] chat messages for the provider layer.
 * Pastes past MAX_INPUT_CHARS are truncated with a visible marker.
 *
 * @param {string} text
 * @param {{ style?: string }} [opts]
 * @returns {Array<{ role: 'system' | 'user', content: string }>}
 * @throws {Error} on a style outside STYLES (the TS union makes that
 *   state unrepresentable at compile time; JS throws instead).
 */
export function buildPromptMessages(text, opts = { style: 'tldr' }) {
  const contract = STYLE_CONTRACT[opts.style];
  if (!contract) throw new Error(`unknown style: ${opts.style}`);
  const stats = textStats(text);
  const truncated = text.length > MAX_INPUT_CHARS;
  const body = truncated ? `${text.slice(0, MAX_INPUT_CHARS)}\n… (text truncated)` : text;
  return [
    { role: 'system', content: `You summarize text faithfully. ${contract}` },
    {
      role: 'user',
      content: `Summarize the following text (${opts.style} style; ${stats.words} words, ${stats.sentences} sentences).\n\n${body}`,
    },
  ];
}

/**
 * Clean the model's reply into displayable summary text. Unlike the
 * commit-message parser there is no strict format contract - any non-empty
 * cleaned text is the summary; null only when nothing survives.
 */
export function parseSummary(text) {
  const cleaned = text.replace(/```[a-z]*\n?/g, '').trim();
  return cleaned.length > 0 ? cleaned : 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 →