hex-color-token-kit
v0.1.1
Published
Extract and validate CSS hex color tokens with spans and diagnostics.
Maintainers
Readme
hex-color-token-kit
Small TypeScript utility for extracting and validating CSS hex color tokens.
It focuses on one job: find #rgb, #rgba, #rrggbb, and #rrggbbaa tokens in text, return source spans, normalize them, and explain malformed candidates without requiring Node APIs.
Package quality
- TypeScript types are generated from the source.
- ESM-only package marked as side-effect free for bundlers.
- CI runs
npm ci,typecheck,build, andtest. - Tested on Node.js 20 and 22 with GitHub Actions.
Demo
Install
npm install hex-color-token-kitUsage
import {
extractHexColorTokens,
isHexColorToken,
parseHexColorToken
} from "hex-color-token-kit";
const tokens = extractHexColorTokens("color: #0f38; border: #336699;");
tokens.valid.map((token) => token.normalized);
// ["#00ff3388", "#336699"]
tokens.invalid;
// []
parseHexColorToken("#abc");
// { ok: true, value: { input: "#abc", normalized: "#aabbcc", channels: { r: 170, g: 187, b: 204 }, ... } }
isHexColorToken("#336699");
// trueAPI
parseHexColorToken(input, options?)
Validates one token. It returns a discriminated union instead of throwing.
Non-string runtime input returns a not_a_string diagnostic.
const result = parseHexColorToken("#ff8800", {
allowAlpha: true,
requireHash: true
});extractHexColorTokens(input, options?)
Scans text and returns valid and invalid token-like candidates with offsets.
Non-string source text returns an empty result with a not_a_string diagnostic.
const result = extractHexColorTokens("ok #fff bad #12zzzz", {
includeInvalid: true
});isHexColorToken(input, options?)
Returns true when a single token is valid. Use it for lightweight checks when
you do not need channels, normalized values, or diagnostics.
Options
allowAlpha: accept 4-digit and 8-digit alpha forms. Defaults totrue.requireHash: require a leading#. Defaults totrue.normalize: return expanded lowercase hex values. Defaults totrue.includeInvalid: include malformed candidates found while scanning. Defaults totrue.maxInputLength: guard scanning work. Defaults to100_000.
Invalid maxInputLength values are ignored with an invalid_options diagnostic.
When requireHash is false, extraction also considers standalone 3-8 digit
hex-like words. Keep the default for CSS text and enable loose matching only for
inputs where bare color tokens are expected.
Browser compatibility
The core uses only strings, arrays, regular expressions, and numbers. It has no runtime dependencies and no required Node APIs.
CLI
No CLI is included. The natural use is as a small parser inside CSS tooling, design-token checks, forms, and browser UIs; a CLI would add Node-only packaging without clear value for the core use case.
License
MPL-2.0
