We are going to design a linting pipeline for design tokens. The pipeline should validate:
- Naming conventions (e.g., using a specific pattern)
- Accessibility thresholds (e.g., color contrast ratios for foreground and background)
- Semantic mappings (ensuring that tokens are mapped to the correct semantic names)
We assume we are working with a token format that is JSON (or similar) and we are using a tool like style-dictionary or custom scripts.
Steps:
-
Setup: We assume we have a directory with token files in JSON format. We might have multiple files (e.g., for different platforms) or a single source.
-
Linting Steps:
a. Naming Conventions:
- Define a naming pattern (e.g.,
category/subcategory/attribute/variant or similar). We can use regex to validate each token key.
- Example:
color/background/primary is valid, but color-primary might not be if we require slashes.
b. Accessibility Thresholds:
- For color tokens that are used for text or interactive elements, we need to check contrast ratios against their background (or against a default background if the token is a background color).
- We might need to know the context (foreground/background) and the intended use. This could be encoded in the token's metadata or naming.
- We can use a library like
color-contrast-checker to compute contrast ratios and ensure they meet WCAG AA or AAA levels.
c. Semantic Mappings:
- This could involve checking that certain tokens are mapped to the correct semantic names. For example, a token named
color/background/primary should be used as the primary background color in components.
- Alternatively, we might have a mapping file that defines which tokens are used for which semantic roles, and we check that all required semantic roles are covered and that the tokens used are valid.
-
Tooling:
- We can write a custom Node.js script that reads the token files and performs these checks.
- Alternatively, we can extend an existing tool like
style-dictionary with custom linting formatters or use a linter like eslint with custom rules.
-
Pipeline:
- We can set up a pre-publish hook (using npm scripts or a CI/CD pipeline) that runs the linter.
- If the linter fails, the publish step is aborted.
-
Configuration:
- We need a configuration file (e.g.,
.lintrcc.js or similar) that defines:
- The naming pattern (regex or a function that validates a token key)
- The accessibility thresholds (e.g., minimum contrast ratio for different token types)
- The semantic mappings (which tokens are required for which semantic roles, or a mapping from token names to semantic roles)
Example configuration:
{
"naming": {
"pattern": "^[a-z]+/[a-z]+/[a-z]+$"
},
"accessibility": {
"colorTokens": [
{
"tokenPath": "color/text/*",
"backgroundTokenPath": "color/background/default",
"minRatio": 4.5
}
]
},
"semantics": {
"requiredTokens": [
"color/background/primary",
"color/text/primary",
"spacing/margin/small"
]
}
}
Alternatively, we might want to define the accessibility checks by having a property in the token that indicates the intended use (foreground/background) and then check against a known background or against another token.
However, note that the token structure might not have this information. We might rely on naming conventions to infer.
Another approach for accessibility: we could have a separate file that defines which tokens are used together (foreground and background) and then check the contrast.
But note: the same foreground token might be used on multiple backgrounds. So we might need to define pairs.
Alternatively, we can have a rule that says: for any token that is a foreground color (by naming pattern, e.g., color/text/*), we must specify a corresponding background token (by pattern) and then check the contrast.
We can make the accessibility rules configurable.
-
Implementation Details:
-
We'll write a Node.js script that:
-
Reads all token JSON files in a directory (or a glob pattern).
-
Flattens the tokens (if they are nested) to have a single key (with slashes) and the value (which might be a color value, a number, etc.)
-
Then runs each check:
Naming:
For each token key, check against the configured regex pattern.
Accessibility:
For each rule in the accessibility configuration:
- Find all tokens that match the tokenPath pattern (foreground tokens).
- For each foreground token, find the corresponding background token (by backgroundTokenPath pattern, which might be a single token or a pattern that matches one token per foreground).
- Compute the contrast ratio and check if it's at least minRatio.
Semantics:
Check that all tokens listed in requiredTokens exist.
Additionally, we might want to check that there are no extra tokens? That might be too strict.
-
We can also check that the token values are of the correct type (e.g., color tokens must be hex or rgb, spacing must be numbers, etc.)
-
Extensibility:
- We should design the linter to be extensible so that more rules can be added.
-
Integration with Style Dictionary:
- If we are using Style Dictionary, we can write a custom formatter that runs after the build? Or we can run the linter as a separate step before building.
Alternatively, we can write a Style Dictionary plugin that adds these checks.
But note: the requirement is to lint before publishing to NPM. So we can run the linter on the source tokens (before building) or on the built tokens (if we want to check the output). It's better to check the source because the built tokens might be transformed (e.g., converted to different formats) and we want to enforce the source conventions.
However, the semantic mappings might be about the built tokens (e.g., which tokens are exported to which platform). But let's assume we want to check the source tokens.
-
Example:
Suppose we have a token file tokens/color.json:
{
"color": {
"background": {
"primary": "#ffffff",
"secondary": "#f0f0f0"
},
"text": {
"primary": "#000000",
"secondary": "#333333"
}
}
}
After flattening, we get:
color/background/primary: #ffffff
color/background/secondary: #f0f0f0
color/text/primary: #000000
color/text/secondary: #333333
Then, according to our accessibility rule:
- For
color/text/* (foreground) we check against color/background/default (but we don't have that). So we adjust the rule to use color/background/primary for color/text/primary? That's a bit arbitrary.
Alternatively, we can have a mapping that says: for color/text/primary the background is color/background/primary. We can define that in the configuration:
{
"accessibility": {
"rules": [
{
"foreground": "color/text/primary",
"background": "color/background/primary",
"minRatio": 4.5
},
{
"foreground": "color/text/secondary",
"background": "color/background/secondary",
"minRatio": 4.5
}
]
}
}
But then we have to list every pair. Alternatively, we can have a pattern that maps by the same last two parts? That might be too restrictive.
Let's think: in our example, the token names are parallel. We can write a rule that says:
{
"accessibility": {
"rules": [
{
"foregroundPattern": "color/text/(.*)",
"backgroundPattern": "color/background/$1",
"minRatio": 4.5
}
]
}
}
Then for color/text/primary, we capture primary and look for color/background/primary.
This is more flexible.
-
Implementation:
We'll write a function that, given a pattern with a capture group, finds the corresponding token.
Steps for accessibility:
For each rule:
- Find all foreground tokens that match
foregroundPattern.
- For each matched token, extract the capture group (or groups) and replace in
backgroundPattern to get the background token path.
- Then find the background token with that path.
- If found, compute contrast ratio and check.
If a foreground token doesn't have a corresponding background token, that's an error.
-
Contrast Calculation:
We need a function that takes two colors (hex, rgb, etc.) and returns the contrast ratio. We can use color-contrast-checker or implement the WCAG formula.
-
Color Parsing:
We assume the color tokens are in hex format. We might want to support other formats (rgb, hsl, named colors). We can use a library like color to parse.
-
Output:
The linter should output a list of errors and warnings, and exit with a non-zero code if there are errors.
-
Configuration File:
We'll look for a configuration file in the project root. We can name it .tokenslintrc.json or similar.
-
CLI:
We can create a CLI that runs the linter and takes arguments for the token directory and config file.
-
Integration:
We can add a script in package.json:
{
"scripts": {
"lint:tokens": "tokenslint"
}
}
And then in the prepublish script, run npm run lint:tokens.
-
Example Project Structure:
my-design-system/
├── tokens/
│ ├── color.json
│ ├── spacing.json
│ └── ...
├── .tokenslintrc.json
├── package.json
└── ...
-
Edge Cases:
-
What if a token is not a color but we have an accessibility rule for it? We should check the token value type and skip non-colors? Or error? We can make the rule conditional on the token being a color.
-
What about opacity? We might need to handle rgba colors. The contrast formula requires the relative luminance, which for rgba we need to blend with the background? That's complex. We might restrict to opaque colors.
-
Alternatively, we can require that color tokens are in hex or rgb without alpha. Or we can ignore tokens with alpha.
-
Semantic Mappings:
We might have a requirement that certain tokens must exist and be of a certain type. We can also check that the token value is within a range (e.g., spacing must be positive numbers).
We can extend the configuration for semantic checks:
{
"semantics": {
"requiredTokens": [
{
"path": "color/background/primary",
"type": "color"
},
{
"path": "spacing/margin/small",
"type": "number",
"min": 0
}
]
}
}
Then we check that the token exists and that its value matches the type and constraints.
-
Putting it together:
We'll create a Node.js module:
readTokens(directory): reads all JSON files and returns a flattened object with path->value.
validateNaming(tokens, config): validates each token key against the pattern.
validateAccessibility(tokens, config): runs the accessibility rules.
validateSemantics(tokens, config): checks required tokens and their values.
Then a main function that runs all and collects errors.
-
Dependencies:
We might need:
color for color manipulation and contrast.
glob to find token files.
But note: we are writing a CLI, so we can use commander or yargs for argument parsing, but we can also just use process.argv for simplicity.
-
Example Code:
We'll write a simplified version.
-
Publishing:
We can publish this linter as an NPM package (e.g., design-tokens-linter) and then use it in projects.
-
Alternative:
We can also write an ESLint plugin if we want to integrate with ESLint. But that might be overkill.
Given the complexity, let's outline the code structure:
index.js (the main script)
lib/
reader.js (reads and flattens tokens)
rules/
naming.js
accessibility.js
semantics.js
utils/
color.js (color contrast and parsing)
But for simplicity, we can write a single file script.
However, given the instruction to plan, we can describe the steps and then provide a sample implementation.
But note: the user asked to "plan", so we can describe the design and then provide a sample code.
Let's write a sample implementation in one file for simplicity.
Sample Implementation:
We assume Node.js and we'll use color for contrast. We can install it with npm install color.
We'll create a file tokens-lint.js:
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { glob } = require('glob');
const Color = require('color');
// Load config from .tokenslintrc.json in current working directory
const configPath = path.join(process.cwd(), '.tokenslintrc.json');
let config = {};
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} else {
console.error('No .tokenslintrc.json found. Using default config.');
// We can have default config? Or exit with error? Let's exit.
process.exit(1);
}
// Read token files
async function readTokens(tokenDir) {
const files = await glob(path.join(tokenDir, '**/*.json'));
const tokens = {};
for (const file of files) {
const content = JSON.parse(fs.readFileSync(file, 'utf8'));
flattenObject(content, '', tokens);
}
return tokens;
}
function flattenObject(obj, prefix, result) {
for (const key in obj) {
const value = obj[key];
const newKey = prefix ? `${prefix}/${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
flattenObject(value, newKey, result);
} else {
result[newKey] = value;
}
}
}
// Naming validation
function validateNaming(tokens, config) {
const errors = [];
const pattern = new RegExp(config.naming.pattern);
for (const tokenPath in tokens) {
if (!pattern.test(tokenPath)) {
errors.push(`Token path '${tokenPath}' does not match naming pattern.`);
}
}
return errors;
}
// Accessibility validation
function validateAccessibility(tokens, config) {
const errors = [];
for (const rule of config.accessibility.rules) {
const fgPattern = new RegExp(rule.foregroundPattern);
const bgPattern = new RegExp(rule.backgroundPattern);
// Find foreground tokens
for (const tokenPath in tokens) {
const fgMatch = tokenPath.match(fgPattern);
if (fgMatch) {
// Construct background token path by replacing the capture group?
// The rule.backgroundPattern might have a $1 for the first capture group.
// We can use the entire match and then replace? Actually, we want to replace the pattern with the captured part.
// But note: the foregroundPattern might have multiple capture groups. We'll use the first one for simplicity? Or we can do a string replace with all groups.
// Alternatively, we can have the backgroundPattern as a string that we format with the captured groups.
// Example: backgroundPattern: "color/background/$1"
// We can do:
let bgPath = rule.backgroundPattern;
for (let i = 1; i < fgMatch.length; i++) {
bgPath = bgPath.replace(`$${i}`, fgMatch[i]);
}
const bgToken = tokens[bgPath];
if (!bgToken) {
errors.push(`Missing background token: ${bgPath} for foreground token ${tokenPath}`);
continue;
}
// Check if both are color strings (we assume hex for now)
const fgColor = Color(tokens[tokenPath]);
const bgColor = Color(bgToken);
// Calculate contrast ratio
const ratio = fgColor.contrast(bgColor);
if (ratio < rule.minRatio) {
errors.push(`Contrast ratio for ${tokenPath} (${tokens[tokenPath]}) on ${bgPath} (${bgToken}) is ${ratio.toFixed(2)}, which is less than ${rule.minRatio}.`);
}
}
}
}
return errors;
}
// Semantics validation
function validateSemantics(tokens, config) {
const errors = [];
for (const required of config.semantics.requiredTokens) {
if (!tokens[required.path]) {
errors.push(`Missing required token: ${required.path}`);
} else {
// Check type and constraints if specified
const value = tokens[required.path];
if (required.type) {
if (required.type === 'color') {
// Check if it's a color? We can try to parse with Color
try {
Color(value);
} catch (e) {
errors.push(`Token ${required.path} is not a valid color.`);
}
} else if (required.type === 'number') {
if (typeof value !== 'number') {
errors.push(`Token ${required.path} is not a number.`);
} else {
if (required.min !== undefined && value < required.min) {
errors.push(`Token ${required.path} is less than minimum ${required.min}.`);
}
if (required.max !== undefined && value > required.max) {
errors.push(`Token ${required.path} is greater than maximum ${required.max}.`);
}
}
}
}
}
}
return errors;
}
// Main
async function main() {
const tokenDir = process.argv[2] || './tokens';
try {
const tokens = await readTokens(tokenDir);
const errors = [
...validateNaming(tokens, config),
...validateAccessibility(tokens, config),
...validateSemantics(tokens, config)
];
if (errors.length > 0) {
console.error('Design Token Linting Errors:');
errors.forEach(e => console.error(`- ${e}`));
process.exit(1);
} else {
console.log('All tokens passed validation.');
}
} catch (error) {
console.error(error);
process.exit(1);
}
}
main();
Configuration Example:
{
"naming": {
"pattern": "^[a-z]+(/[a-z]+)*$"
},
"accessibility": {
"rules": [
{
"foregroundPattern": "color/text/(.*)",
"backgroundPattern": "color/background/$1",
"minRatio": 4.5
}
]
},
"semantics": {
"requiredTokens": [
{
"path": "color/background/primary",
"type": "color"
},
{
"path": "color/text/primary",
"type": "color"
},
{
"path": "spacing/margin/small",
"type": "number",
"min": 0
}
]
}
}
Usage:
node tokens-lint.js ./tokens
Publishing to NPM:
We would package this as an NPM module and then in a design system project, add it as a dev dependency and add a script:
{
"scripts": {
"lint:tokens": "tokens-lint"
}
}
Then in the pre-publish hook:
{
"scripts": {
"prepublishOnly": "npm run lint:tokens"
}
}
Notes:
-
This is a basic implementation. It can be extended to support more token types, more complex patterns, and better error reporting.
-
The accessibility rule assumes that the foreground and background tokens are in the same token set and that the pattern mapping is 1:1. In reality, a foreground token might be used on multiple backgrounds. We might want to define multiple rules for the same foreground token with different backgrounds? Or have a list of backgrounds to check against? The above only checks one background per foreground.
-
We might want to have a way to specify that a token is a foreground or background by its naming pattern, and then automatically check all foreground tokens against a set of background tokens? That would be more complex.
-
The semantic check only checks for existence and simple type. We can extend to check value ranges, etc.
-
We are not checking for deprecated tokens or other custom rules.
This is a starting point.
I'll outline a comprehensive design token linting pipeline that validates naming conventions, accessibility thresholds, and semantic mappings before publishing to NPM registries.
Architecture Overview
┌─────────────────┐ ┌──────────────┐ ┌─────────────┐
│ Source Tokens │───▶│ Linting │───▶│ Validation │
│ (JSON/YAML) │ │ Pipeline │ │ Results │
└─────────────────┘ └──────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────┐ ┌─────────────┐
│ Design System │ │ CI/CD │ │ Publish │
│ Repository │ │ (GitHub │ │ Block │
│ │ │ Actions/ │ │ │
└─────────────────┘ │ GitLab CI) │ └─────────────┘
└──────────────┘
1. Token Structure & Configuration
Token Format (Example using Style Dictionary format):
{
"color": {
"brand": {
"primary": { "value": "#0066CC", "type": "color" },
"secondary": { "value": "#6B7280", "type": "color" }
},
"neutral": {
"text": { "value": "#1A202C", "type": "color", "semantic": "text-primary" }
}
},
"spacing": {
"sm": { "value": "8px", "type": "dimension" },
"md": { "value": "16px", "type": "dimension" }
}
}
Configuration File (.tokenslintrc.json):
{
"naming": {
"pattern": "^[a-z]+(/[a-z]+)*$",
"exceptions": ["color/brand/primary/base"],
"levels": ["base", "semantic", "component"]
},
"accessibility": {
"colorContrast": {
"minRatio": 4.5,
"fontSizeWeights": {
"large": { "minRatio": 3.0, "minSize": "18px" },
"normal": { "minRatio": 4.5, "minSize": "14px" }
},
"exemptTokens": ["color/background/decorative"]
},
"touchTargets": {
"minSize": "44px",
"spacingTokens": ["spacing/button/touch"]
}
},
"semantics": {
"requiredMappings": {
"color": {
"text/primary": ["color/neutral/text"],
"background/primary": ["color/brand/primary"]
},
"spacing": {
"component/margin": ["spacing/md"]
}
},
"prohibitedDuplicates": true,
"platformOverrides": {
"web": { "color/primary": "color/brand/primary" },
"ios": { "color/primary": "color/brand/primary/dark" }
}
},
"typeChecking": {
"color": ["hex", "rgb", "hsl"],
"dimension": ["px", "rem", "em", "%"],
"fontWeight": ["number", "string"],
"opacity": ["number"]
}
}
2. Pipeline Implementation
A. Naming Convention Validator
// validators/naming.js
const namingRules = {
// kebab-case for tokens
tokenName: /^[a-z]+(/[a-z]+)*$/,
// Value-specific patterns
colorValue: /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$|^rgb\(/,
// Semantic token prefix requirements
semanticToken: /^(color|spacing|typography|shadow)\/.+\/semantic\/.+/
};
function validateNaming(tokens, config) {
const errors = [];
for (const [path, token] of Object.entries(tokens)) {
// Check token path pattern
if (!namingRules.tokenName.test(path)) {
errors.push({
type: 'naming',
path,
message: `Invalid token path format. Expected pattern: ${config.naming.pattern}`
});
}
// Check value format based on token type
if (token.type === 'color' && !namingRules.colorValue.test(token.value)) {
errors.push({
type: 'naming',
path,
message: `Invalid color format: ${token.value}`
});
}
}
return errors;
}
B. Accessibility Validator
// validators/accessibility.js
const contrast = require('color-contrast-checker');
function validateAccessibility(tokens, config) {
const errors = [];
const colorTokens = Object.entries(tokens).filter(([_, t]) => t.type === 'color');
// 1. Color Contrast Validation
for (const [fgPath, fgToken] of colorTokens) {
if (config.accessibility.colorContrast.exemptTokens.includes(fgPath)) {
continue;
}
// Find background tokens (based on naming convention)
const bgPath = fgPath.replace('text/', 'background/').replace('foreground/', 'background/');
const bgToken = tokens[bgPath];
if (!bgToken) {
errors.push({
type: 'accessibility',
path: fgPath,
message: `Missing background token: ${bgPath} for contrast validation`
});
continue;
}
const ratio = contrast.getRatio(fgToken.value, bgToken.value);
const minRatio = config.accessibility.colorContrast.minRatio;
if (ratio < minRatio) {
errors.push({
type: 'accessibility',
path: fgPath,
message: `Insufficient contrast (${ratio.toFixed(2)}:1) against ${bgPath}. Minimum: ${minRatio}:1`,
severity: ratio < 3 ? 'error' : 'warning'
});
}
}
// 2. Touch Target Validation
for (const token of Object.values(tokens)) {
if (token.type === 'dimension' && config.accessibility.touchTargets.spacingTokens.includes(token.path)) {
const size = parseFloat(token.value);
if (size < parseFloat(config.accessibility.touchTargets.minSize)) {
errors.push({
type: 'accessibility',
path: token.path,
message: `Touch target size (${token.value}) below minimum (${config.accessibility.touchTargets.minSize})`
});
}
}
}
return errors;
}
C. Semantic Mapping Validator
// validators/semantics.js
function validateSemantics(tokens, config) {
const errors = [];
const requiredMappings = config.semantics.requiredMappings;
// 1. Check all required semantic mappings exist
for (const [category, mappings] of Object.entries(requiredMappings)) {
for (const [semanticName, expectedPaths] of Object.entries(mappings)) {
let found = false;
for (const expectedPath of expectedPaths) {
if (tokens[expectedPath]) {
found = true;
break;
}
}
if (!found) {
errors.push({
type: 'semantic',
path: `${category}/${semanticName}`,
message: `Missing required semantic mapping. Expected one of: ${expectedPaths.join(', ')}`
});
}
}
}
// 2. Check for duplicate values across different semantic contexts
if (config.semantics.prohibitedDuplicates) {
const valueMap = new Map();
for (const [path, token] of Object.entries(tokens)) {
if (token.type === 'color') {
if (!valueMap.has(token.value)) {
valueMap.set(token.value, []);
}
valueMap.get(token.value).push(path);
}
}
for (const [value, paths] of valueMap.entries()) {
if (paths.length > 1) {
// Check if they're semantically related (allowed duplicates)
const hasSemanticRelation = paths.some(p => p.includes('semantic')) &&
paths.some(p => !p.includes('semantic'));
if (hasSemanticRelation) {
errors.push({
type: 'semantic',
message: `Duplicate color value ${value} used across semantic and base tokens: ${paths.join(', ')}`
});
}
}
}
}
// 3. Platform-specific overrides validation
if (config.semantics.platformOverrides) {
for (const [platform, overrides] of Object.entries(config.semantics.platformOverrides)) {
for (const [targetToken, sourceToken] of Object.entries(overrides)) {
if (!tokens[sourceToken]) {
errors.push({
type: 'semantic',
path: `${platform}/${targetToken}`,
message: `Source token ${sourceToken} for platform override doesn't exist`
});
}
}
}
}
return errors;
}
3. Complete Pipeline Runner
// tokens-lint.js
const { readTokens } = require('./lib/reader');
const { validateNaming } = require('./validators/naming');
const { validateAccessibility } = require('./validators/accessibility');
const { validateSemantics } = require('./validators/semantics');
const { generateReport } = require('./lib/reporter');
async function runLintPipeline(tokenPath, configPath) {
try {
// 1. Load tokens and configuration
const tokens = await readTokens(tokenPath);
const config = require(configPath);
// 2. Run all validators
const namingErrors = validateNaming(tokens, config);
const accessibilityErrors = validateAccessibility(tokens, config);
const semanticErrors = validateSemantics(tokens, config);
const allErrors = [
...namingErrors.map(e => ({ ...e, category: 'naming' })),
...accessibilityErrors.map(e => ({ ...e, category: 'accessibility' })),
...semanticErrors.map(e => ({ ...e, category: 'semantics' }))
];
// 3. Generate report
const report = generateReport(allErrors, tokens, config);
// 4. Output and exit
console.log(report.formatted);
if (allErrors.length > 0) {
// Save detailed report for CI
fs.writeFileSync('tokens-lint-report.json', JSON.stringify(report.detailed, null, 2));
process.exit(1); // Fail for CI
}
return { success: true, errors: [] };
} catch (error) {
console.error('Linting pipeline failed:', error);
process.exit(1);
}
}
// CLI usage
if (require.main === module) {
const tokenPath = process.argv[2] || './tokens';
const configPath = process.argv[3] || './.tokenslintrc.json';
runLintPipeline(tokenPath, configPath);
}
4. CI/CD Integration (GitHub Actions)
# .github/workflows/token-lint.yml
name: Design Token Lint
on:
pull_request:
paths:
- 'tokens/**'
- '.tokenslintrc.json'
push:
branches: [main]
jobs:
lint-tokens:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
env:
CI: true
- name: Run token linter
run: npx tokens-lint ./tokens ./.tokenslintrc.json
- name: Upload lint report
if: always()
uses: actions/upload-artifact@v3
with:
name: token-lint-report
path: tokens-lint-report.json
- name: Comment PR with results
if: github.event_name == 'pull_request'
uses: marocchino/sticky-pull-request-comment@v2
with:
path: tokens-lint-report.json
5. Pre-publish Hook
// package.json
{
"name": "@your-org/design-tokens",
"version": "1.0.0",
"scripts": {
"lint:tokens": "tokens-lint ./tokens ./.tokenslintrc.json",
"build": "style-dictionary build",
"prepublishOnly": "npm run lint:tokens && npm run build"
},
"prepublishOnly": "npm run lint:tokens && npm run build",
"devDependencies": {
"color-contrast-checker": "^2.0.0",
"style-dictionary": "^3.7.0"
}
}
6. Advanced Features
A. Auto-fixing Capability
// fixers/naming.js
function autoFixNaming(tokens, config) {
const fixes = [];
for (const [path, token] of Object.entries(tokens)) {
// Convert camelCase to kebab-case
const fixedPath = path.replace(/([A-Z])/g, '-$1').toLowerCase();
if (fixedPath !== path) {
fixes.push({
type: 'rename',
from: path,
to: fixedPath,
token
});
}
}
return fixes;
}
B. Token Dependency Graph
// lib/dependency-graph.js
function buildDependencyGraph(tokens) {
const graph = {};
for (const [path, token] of Object.entries(tokens)) {
if (token.references) {
graph[path] = token.references; // tokens that this token depends on
}
}
return graph;
}
// Detect circular dependencies
function detectCircularDependencies(graph) {
const visited = new Set();
const recursionStack = new Set();
const cycles = [];
function dfs(node, path) {
if (recursionStack.has(node)) {
const cycleStart = path.indexOf(node);
cycles.push(path.slice(cycleStart).concat(node));
return;
}
if (visited.has(node)) return;
visited.add(node);
recursionStack.add(node);
const deps = graph[node] || [];
for (const dep of deps) {
dfs(dep, [...path, node]);
}
recursionStack.delete(node);
}
for (const node of Object.keys(graph)) {
dfs(node, []);
}
return cycles;
}
C. Custom Rule System
// rules/custom-rule.js
module.exports = {
name: 'no-duplicate-values',
description: 'Prevents duplicate values across different token categories',
validate(tokens, config) {
const errors = [];
const valueMap = new Map();
for (const [path, token] of Object.entries(tokens)) {
if (token.value && token.type === 'color') {
if (!valueMap.has(token.value)) {
valueMap.set(token.value, []);
}
valueMap.get(token.value).push(path);
}
}
for (const [value, paths] of valueMap.entries()) {
if (paths.length > 1 && paths.some(p => p.startsWith('color/brand')) &&
paths.some(p => p.startsWith('color/neutral'))) {
errors.push({
rule: 'no-duplicate-values',
message: `Duplicate color value ${value} across brand and neutral: ${paths.join(', ')}`
});
}
}
return errors;
}
};
7. NPM Package Publishing Security
{
"name": "@your-org/design-tokens",
"publishConfig": {
"access": "restricted",
"registry": "https://npm.your-company.com"
},
"scripts": {
"prepublishOnly": "npm run lint:tokens && npm run build && npm run test",
"postpublish": "npm run notify-publish"
}
}
.npmrc:
@your-org:registry=https://npm.your-company.com
//npm.your-company.com/:_authToken=${NPM_TOKEN}
8. Monitoring & Reporting
// lib/reporter.js
const chalk = require('chalk');
function generateReport(errors, tokens, config) {
const summary = {
totalTokens: Object.keys(tokens).length,
errors: errors.length,
warnings: errors.filter(e => e.severity === 'warning').length,
passed: Object.keys(tokens).length - errors.length
};
const formatted = `
${chalk.bold('🎨 Design Token Lint Report')}
${chalk.dim('═'.repeat(50))}
Total Tokens: ${summary.totalTokens}
${chalk.green(`✓ Passed: ${summary.passed}`)}
${chalk.yellow(`⚠ Warnings: ${summary.warnings}`)}
${chalk.red(`✗ Errors: ${summary.errors}`)}
${chalk.bold('📋 Issues:')}
${errors.map(e =>
` ${e.severity === 'error' ? chalk.red('✗') : chalk.yellow('⚠')} ${e.path || e.message}`
).join('\n')}
`;
return {
formatted,
detailed: {
summary,
errors,
tokenCount: summary.totalTokens,
configUsed: config
}
};
}
Key Benefits of This Pipeline:
- Fail-fast validation - Prevents invalid tokens from reaching NPM
- Comprehensive coverage - Naming, accessibility, semantics, type safety
- CI/CD integrated - Automatic validation on PR/merge
- Detailed reporting - Clear error messages with locations
- Extensible - Custom rules and fixers
- Multi-platform - Supports web, iOS, Android overrides
- Security - Private registry support, access control
- Automation - Pre-publish hooks, auto-fixing capabilities
Recommended Dependencies
{
"devDependencies": {
"color": "^4.2.3",
"color-contrast-checker": "^2.0.0",
"glob": "^10.3.10",
"chalk": "^4.1.2",
"commander": "^11.1.0",
"js-yaml": "^4.1.0",
"lodash": "^4.17.21"
}
}
This pipeline ensures design tokens meet organizational standards before publication, maintaining consistency, accessibility compliance, and semantic integrity across all platforms.