Internals
Minification
Bascik features zero-dependency minifiers for HTML, CSS, and JavaScript, deterministic identifier hashing for scoped selectors, and custom minifier extensibility.
Overview
Minification reduces payload sizes without introducing heavy external bundlers or AST parsers. Bascik includes three specialized minification passes:
html-minifier.ts: Strips comments, consolidates eligible scripts, and collapses whitespace, deciding from a spec-following scan of the document (html-scanner.ts) what each part of the markup is.css-minifier.ts: Removes comments and structural whitespace while shielding string literals andurl()definitions.js-minifier.ts: Strips comments and unnecessary spaces while preserving string literals, template literals, and regex literals verbatim.- Identifier Hashing (
names.ts): Hashes scoped class names and element IDs using SHA-256 and Base62 encoding whenminify.identifiers: trueis configured. - BYO Minifier: Supports custom third-party minifier integrations (
esbuild,SWC,PostCSS,Lightning CSS) configured inbascik.config.ts.
Zero-AST Lexical Context Preservation
Traditional build tools rely on heavy Abstract Syntax Tree (AST) parsers to minify code safely. Bascik achieves equivalent safety and higher throughput using zero-dependency lexical context preservation:
- HTML Tokenizer Scan:
html-scanner.tswalks the document once, following the WHATWG HTML tokenizer states, and splits it into text, tags, raw text bodies, and other markup. Comment-like text inside a<script>or<style>, a quoted>in an attribute value, and malformed markup such as<scr<script>are all read the way a browser reads them, so they are never mistaken for document structure. - CSS String and Resource Shielding: Quoted string literals and
url(...)declarations in CSS can contain colons, semicolons, or multiple spaces (such as data URIs or content strings).shieldCssStringsextracts these values into temporary tokens before structural whitespace stripping, restoring them unchanged afterward. - JS Lexical Context and Regex Disambiguation: JavaScript code is segmented into literal regions (quoted strings, template literals, regexes) and minifiable code regions. To disambiguate the forward slash
/character (which can represent either a division operator or a regex literal),js-minifier.tstracks preceding keyword context (such asreturn,case,typeof,yield,await). Forward slashes following expression keywords are preserved as regex literals.
HTML Minification (html-minifier.ts)
minifyHtml makes two linear passes, each driven by the scanner:
- Scan the document, remove its comments, and take out the client scripts selected for consolidation.
- Scan the result and collapse whitespace token by token, then place the consolidated scripts.
The goal is that the minified page parses to the same document, with the same scripts able to run. The test suite checks this against parse5, a spec-compliant HTML parser, on random malformed markup.
Key HTML Minification Behaviors
- Comment Stripping: Every HTML comment the browser would parse is removed, including ones ending in
--!>, except inside<pre>and<listing>, whose content stays verbatim. Comment-like text inside raw text and RCDATA elements (<script>,<style>,<textarea>,<title>,<noscript>) is not a comment and is left in place, so CSS CDO/CDC tokens (<!--and-->) inside a<style>element survive. Removing markup never joins the text around it into new markup: where it could (<then<!-- c -->script>, or&am<!-- -->p;), an empty<!---->takes its place. - Verbatim Content:
<pre>and<listing>content, raw text and RCDATA bodies (<script>,<style>,<textarea>,<xmp>,<noscript>,<iframe>), SVG and MathML<script>and<style>, attribute values, DOCTYPEs, and CDATA sections are never changed. Whitespace between a tag's attributes collapses, since it never renders.<title>text collapses, becausedocument.titlecollapses it anyway. - Whitespace Collapsing: In other text, every line break and every run of spaces, tabs, and line breaks becomes one space. Only that whitespace is touched: U+00A0 (
written as a character), other Unicode spaces, and form feeds are content and stay. Whitespace-only text between two tags is removed, or kept as one space when both are elements the browser displays inline by default:INLINE_TAGS(a,span,b,strong,code,textarea,ins,svg,math,video,iframe, ...), any custom element (a name with a hyphen), and the SVG text content elements<tspan>,<textPath>, and<tref>, so</tspan> <tspan>inside an SVG<text>keeps its space. A comment renders nothing, so the whitespace around an<!---->a table keeps where a comment or script stood still separates two inline elements: one space stays, after the last comment. While a formatting element such as<a>or<b>may be open, it is kept as one space instead, because whitespace makes the parser re-create a misnested formatting element. - Script Consolidation: Eligible classic and module client scripts are moved to the end of the document, in their original order. Build, routes, server, and data scripts stay in place, as do scripts in
<template>,<pre>, SVG, or MathML. A script that must run in place (an import map, or one of those) keeps every earlier script before it. When the document ends inside markup where an appended script would not run, such as an unclosed tag, comment,<template>,<textarea>, or SVG, the scripts go just before it. Inside a table they go before the text in front of that markup too, because the parser moves text that is not all whitespace out of a table one run at a time: splitting\f</would leave the\fbehind in the table. An unclosed<svg>or<math>that a later<p>,<div>, or<span>closes, as the browser does, is not such markup, so the scripts still go at the end. Inside<foreignObject>or<mi>, the scan follows the HTML elements that decide whether</svg>or</math>closes it, as the browser builds them: a<div>or heading closes an open<p>first, and a stray<td>,<tr>,<head>, or<body>with no table open opens nothing.
If that table insertion point falls just after a <pre> or <listing> start tag and before its initial newline, scripts stay in place: inserting one there would stop the browser from ignoring that newline.
Known HTML Limits
- CSS-dependent whitespace: The minifier does not read your CSS. An element other than
<pre>or<listing>styledwhite-space: pre,pre-wrap,pre-line, orbreak-spacesloses its extra spaces and line breaks, and an element made inline with CSS can lose the space next to it. Use<pre>for preformatted text, or setminify.html: false. - Malformed markup the scan cannot follow: In a few rare constructs, such as raw text or SVG elements inside
<select>, an end tag other than</option>or</optgroup>inside a<select>in SVG or MathML,<frameset>, CDATA inside SVG<title>, SVG and MathML end tags that close elements outside them, or a table tag such as<tr>or</table>inside SVG or MathML that opened in a table (the browser may leave the SVG or MathML there, depending on where in the table it is), the scan stops and the rest of the document is left as written. Inside<pre>after a<table>or<select>, it keeps treating the content as preformatted until the next<template>boundary, which only keeps more whitespace.
JavaScript minification applies to scripts with no type and to text/javascript, module, application/javascript, text/ecmascript, and application/ecmascript. External src scripts and non-JavaScript data scripts are not minified.
CSS Minification (css-minifier.ts)
minifyCss reduces stylesheet sizes by stripping comments and collapsing whitespace around CSS syntax delimiters ({, }, :, ;, ,).
export const minifyCss = (css: string): string => {
const { css: shielded, restore } = shieldCssStrings(
removeCommentsFromCss(css),
);
const minified = shielded
.replace(/\n/g, " ")
.replace(/\s\s+/g, " ")
// Preserve the single space in an empty custom property (`--empty: ;`).
.replace(/(?<!-)--([\w-]+)\s*:\s+(?=[;}])/g, "--$1: ")
.replace(/\s*([{};,])\s*/g, "$1")
.replace(/:\s+/g, ":")
// A space before `:` is a descendant combinator in a selector
// (`.a :hover`), so strip it only in a declaration.
.replace(/\s+:(?![^;{}]*\{)/g, ":")
.replace(/(?<!-)--([\w-]+):(?=[;}])/g, "--$1: ")
.trim();
return restore(minified);
}; String and URL Shielding (shieldCssStrings)
CSS property values can contain strings, data URIs, or custom properties containing colons, semicolons, or multiple spaces:
.badge::after {
content: "Status: Active; Version 1.0";
}
.hero {
background-image: url("data:image/svg+xml;charset=utf-8,...");
} shieldCssStrings extracts quoted string literals and url(...) declarations before minification runs, replacing them with temporary tokens. After structural whitespace is stripped, restore() re-injects the original string content unchanged.
JavaScript Minification (js-minifier.ts)
minifyJs performs single-pass lexical scanning to strip comments and collapse whitespace in client-side scripts.
Lexical Segmenting
JavaScript source code is divided into literal segments (which must be preserved verbatim) and minifiable code segments:
type Segment = {
literal: boolean;
text: string;
controlHeaderCloses?: Set<number>; // `)` closing an if/while/for/with header
postfixUpdateEnds?: Set<number>; // end of each postfix `++`/`--`
arrowBodyCloses?: Set<number>; // `}` closing an arrow function body (`=> {...}`)
bodyHeaderEnds?: Set<number>; // end of a function, method, class or catch header whose `{` is on a later line
valueBraceCloses?: Set<number>; // `}` ending a value: an object literal, or an arrow, function or class expression body
fieldNameEnds?: Set<number>; // end of a class field name with no value, before a `[` or `*` member on a later line
bareBindingEnds?: Set<number>; // end of a var/let/const binding name with no initializer
numberDotEnds?: Set<number>; // `.` ending a number literal (`5.`)
integerBeforeDotLines?: Set<number>; // last digit of an integer a line break separates from a `.`
moduleFromBreaks?: Set<number>; // last character before a line break that a clause's `from` or `as`, or a for header's `of`, follows
contextualKeywordEnds?: Set<number>; // end of a clause's `as` or a for header's `of` that a line break follows
propertyKeywordEnds?: Set<number>; // end of a property spelled like a keyword that whitespace separates from its `.` (`o.\nreturn`)
letKeywordEnds?: Set<number>; // end of a `let` that starts a statement, which declares when a name, `[` or `{` follows
asiBefore?: boolean; // literal only: a line break before it ends the statement
keptComment?: "line" | "close" | "block"; // literal only: a comment kept as written
lineBreakBefore?: boolean; // literal only: keep the line break before it (`await\n"a"`, `yield\n`x``)
moduleSpecifier?: boolean; // literal only: an import or export's module specifier
classMemberName?: boolean; // literal only: a string naming a class member
}; Quoted strings ("...", '...'), template literals (`...`), and regex literals (/.../) are placed in literal segments. A hashbang (#!) first line is kept as written, with its line break, and only the rest of the script is minified. An HTML-like <!-- comment is a line comment in a classic script but the operators <, !, and -- in a module, and minifyJs is not told which it gets, so the comment is a literal segment (keptComment: "line") kept to the end of its line and followed by a line break: both kinds of script read the output as they read the source. Once a script holds a <!--, the HTML parser also reads -->, <script, and </script in it to find the </script> that ends the element, so a //, -->, or block comment holding one of them is kept as written too (HTML_SCRIPT_MARKER; a --> comment goes back to the start of a line). Joining code in such a script never writes <script or --> either: the line join keeps a space there, and normalization keeps one marked with \0 (a < script, a-- > b). A regex literal after < always keeps its space, since </script ends any inline script. A --> at the start of a line, a comment in a classic script and a syntax error in a module, is dropped like //, and a joined <!-- in code gets a space (a < !--b). Outside literals, a non-ASCII character that is not whitespace can only belong to a name (Unicode ID_Start or ID_Continue), and a \ only starts a \u escape in one, so the scanner counts both as word characters: removing a line break or comment between two names keeps a space or a ; between them (x = 值\ny = 1 is x=值;y=1). A \u{...} escape is rewritten to the same name without braces (\u0062, or the character itself above U+FFFF), so its } is never read as a brace. A . right after a decimal integer is part of that number (5.), so the scanner records it in numberDotEnds, where a line break ends the statement, and records an integer that a line break or comment separates from a . in integerBeforeDotLines, which keeps a space (1 .y).
Regex Disambiguation
A forward slash / can denote either a division operator or the start of a regular expression literal. To disambiguate, js-minifier.ts tracks preceding keyword context:
const REGEX_PRECEDING_KEYWORDS = new Set([
"return",
"case",
"throw",
"yield",
"await",
"delete",
"typeof",
"void",
"default",
"in",
"of",
"instanceof",
"new",
"do",
"else",
]); When / follows an operator or one of these keywords, it is parsed as a regular expression literal and preserved intact. A / after a value, ], a quote, a ) that does not close an if/while/for/with header, or a postfix ++/-- (count++ / 2) is division. After the } of a value (valueBraceCloses, other than an arrow body) a / is division. After any other } the scanner tries a regex, because a block can end there, and keeps it only when it closes on the same line. js-literal-spans.ts, which finds the string literals that attribute scoping reads, imports this keyword set but reads a / after } or any ) as division.
Line Breaks (ASI)
Collapsing a line break must keep the statement boundary that JavaScript's automatic semicolon insertion puts there, so the minified script runs the same program as the unminified one. A block comment that holds a line terminator is a line terminator to JavaScript, so the scanner replaces it with a line break rather than removing it. The scanner records what it needs for this on each segment (controlHeaderCloses, postfixUpdateEnds, arrowBodyCloses, bodyHeaderEnds, valueBraceCloses, fieldNameEnds, bareBindingEnds, asiBefore). bareBindingEnds marks a var, let, or const binding name with no initializer; the scanner keeps a stack of open declarations with the (, [, and { depth each was read at, so only the commas of the declaration itself start a new binding (var a = f(1, 2), b). valueBraceCloses marks each } that ends a value (an object literal, or the body of an arrow function, function expression, or class expression), after which an else or while on the next line needs a ; that it must not get after the } of a block. A {, function, or class is a value after an operator that takes an operand, delete, an arrow, or the : of a conditional; the scanner pairs each conditional ? with its : by nesting depth, so a label's or an object key's : is not taken for one. fieldNameEnds marks a class field name that has no value and is followed, on a later line, by a member starting with [ or *; the scanner finds it by tracking which word starts a member directly inside a class body (also after accessor), which [ opens a computed key, and which string names a member (classMemberName on its literal segment, so the ; goes in at the start of the next code segment). For bodyHeaderEnds it tracks, per open {, whether it is a class body, an object literal, or a block, so a { on its own line after m(a) is a method body inside a class or object literal and a separate block statement anywhere else; it also marks the line break before the extends of a class header (class D\nextends B). A keyword is the whole word before the line break, so $else and $return are names, and a word after . or # (x.class, this.#return), though not after a ... spread, is never a keyword, also when whitespace separates it from the . (propertyKeywordEnds marks o.\nreturn, where the text has no . right before the word); from and as count as keywords only while an import or export clause is open (as only after * or a name or string being imported or exported; inside the clause's braces every word is a name, so default or let there neither ends the clause nor declares anything), and of only directly inside a for header. A from or as that starts a line inside an open clause records the line break before it in moduleFromBreaks, a join (import { a }\nfrom "m"), as does a header's of (for (const x\nof y)), and an as or a header's of at the end of a line is recorded in contextualKeywordEnds, also a join, and a module specifier is a literal segment with moduleSpecifier, so a with line after it continues the import as its attributes. await is a keyword in modules and async functions and a name elsewhere, and yield a restricted production in generators and a name elsewhere, which the scanner does not track, so the output keeps a line break after either as written: a literal after one is a literal segment with lineBreakBefore, and a code line after one is joined with a placeholder that normalization turns back into a line break. The rules are listed in the minify.js (built-in) rows of the compatibility page.
Identifier Hashing (names.ts)
When production identifier minification is enabled (minify.identifiers: true), Bascik replaces long scoped class names and element IDs with compressed alphanumeric hashes.
Base62 Hash Encoding
names.ts computes SHA-256 digests of scoped attribute names, and the portable name-hash.ts (shared with request-time rendering on Workers) encodes the first 64 bits into a Base62 string:
const BASE62_ALPHABET =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
export const toBase62 = (num: bigint, length = 11): string => {
if (num === 0n) return "0".repeat(length);
let str = "";
let current = num;
while (current > 0n) {
const remainder = Number(current % 62n);
str = BASE62_ALPHABET[remainder] + str;
current = current / 62n;
}
return str.padStart(length, "0");
};
export const nameHashFromDigest = (digest: Uint8Array): string => {
let num = 0n;
for (let i = 0; i < 8; i++) num = (num << 8n) | BigInt(digest[i]);
return `b${toBase62(num, 11)}`;
};
// names.ts
export const getAttributeNameHash = (attributeName: string): string => {
const digest = createHash("sha256").update(attributeName).digest();
return nameHashFromDigest(digest); // memoized in hashCache
}; The output is prefixed with a b character to ensure class and ID names always begin with a valid CSS letter identifier rather than a digit (for example, b2Y4G9eD1K8b).
O(1) Hash Memoization (hashCache)
To eliminate redundant crypto and string allocations during builds, getAttributeNameHash caches computed Base62 hashes in an in-memory Map<string, string> (hashCache). Subsequent encounters of identical attribute names across pages or components return the cached hash instantly with 0 SHA-256 digests, BigInt conversions, or string creation overhead.
Bring Your Own Minifier (BYO Minifier)
For projects with specialized optimization needs, Bascik allows overriding the default minifiers in bascik.config.ts. Custom minifiers can be synchronous or asynchronous.
Integration Examples
JavaScript with esbuild
import { transform } from "esbuild";
export default {
minify: {
js: async (code: string) => {
const result = await transform(code, { loader: "js", minify: true });
return result.code.trim();
},
},
}; CSS with Lightning CSS or PostCSS
import postcss from "postcss";
import autoprefixer from "autoprefixer";
export default {
minify: {
css: async (code: string) => {
const result = await postcss([autoprefixer]).process(code, {
from: undefined,
});
return result.css;
},
},
}; When custom minifier functions are provided, Bascik routes compiled assets through the custom handlers during the final build phase.