AI Code Explainer — JavaScript source
Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* code-explainer — language guessing, depth-graded prompts, reply cleanup.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
* src/lib/code-explainer.ts (the canonical TypeScript implementation).
*
* Why this file exists: the whole explainer pipeline is three pure functions —
* guess which language a paste is, wrap it in a depth-graded chat prompt, and
* strip code fences from the reply — so the island stays a thin shell over the
* shared provider layer and every runtime can run the exact same heuristics.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
/** Depth knob for the prompt: how much explanation contract the model gets. */
export const EXPLANATION_LEVELS = ['beginner', 'developer', 'expert'];
/** Guess the language from (and prompt with) at most this many chars. */
const MAX_CODE_CHARS = 12000;
/** Per-level explanation contract, verbatim from the TS lib. */
const LEVEL_CONTRACT = {
beginner:
'Explain for a smart newcomer: no unexplained jargon, short sentences, one everyday analogy if it helps. Say what it does first, then how, step by step.',
developer:
'Explain for a working developer: concise and practical. Lead with what it does, then the flow, the patterns used, and the pitfalls an editor should catch.',
expert:
'Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.',
};
// Cheap keyword heuristics — enough to name the language in the prompt so the
// model starts right; never a language detector. First match wins, so order
// matters: go before rust before python before the web trio.
const RULES = [
['go', /\bpackage\s+\w+|\bfunc\s+\w+|:=/],
['rust', /\bfn\s+\w+|\blet\s+mut\b|\bimpl\b/],
['python', /\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$/m],
['sql', /\bSELECT\b.+\bFROM\b/i],
['typescript', /\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b/],
['javascript', /\bconst\s+\w+\s*=|=>|console\.log/],
['css', /[.#]?[\w-]+\s*\{[^}]*:[^}]*;/],
['html', /<\/?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?>/i],
];
/**
* Guess the language of a code sample. Falls back to 'text' when no rule
* matches, so the prompt can tell the model to reason about the paste as
* pseudocode instead of pretending to know better.
*/
export function guessLanguage(code) {
for (const [lang, re] of RULES) {
if (re.test(code)) return lang;
}
return 'text';
}
/**
* Build the [system, user] chat messages for the provider layer. The code is
* truncated BEFORE guessing: the heuristics only need a sample, and running
* them over a 30k-char paste is pure waste.
*/
export function buildPromptMessages(code, { level } = {}) {
const truncated = code.length > MAX_CODE_CHARS;
const body = truncated ? `${code.slice(0, MAX_CODE_CHARS)}\n… (code truncated)` : code;
const lang = guessLanguage(body);
const uncertainty =
lang === 'text' ? ' (no clear language — say so and reason about it as pseudocode)' : '';
return [
{
role: 'system',
content: `You explain code. ${LEVEL_CONTRACT[level]} The code appears to be ${lang}${uncertainty}. Use short paragraphs or bullets; markdown is fine.`,
},
{ role: 'user', content: body },
];
}
/**
* Clean the model's reply into displayable explanation text: strip markdown
* code fences, then trim. Returns null only when nothing survives cleaning —
* there is no strict format contract beyond "non-empty".
*/
export function parseExplanation(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 →