Design Token Linting Pipeline Plan
This plan outlines a robust CI/CD pipeline for validating design tokens before publishing to NPM registries (e.g., npmjs.com or private registries like Verdaccio/GitHub Packages). The pipeline enforces:
- Naming conventions: Consistent, semantic naming (e.g.,
color-background-primary-default, kebab-case, prefixed by category/type).
- Accessibility thresholds: WCAG 2.1 AA/AAA contrast ratios (e.g., 4.5:1 for normal text, 3:1 for large text) between foreground/background color pairs.
- Semantic mappings: Tokens correctly reference scales (e.g.,
color-primary-500 maps to semantic color-brand-primary), no orphans, and adherence to Figma Tokens spec or custom schema (e.g., $type, $category, $extensions).
The pipeline uses GitHub Actions for orchestration (adaptable to GitLab CI, CircleCI, etc.), Style Dictionary for token transformation/building, custom Node.js validators, and pre-commit hooks for DX. It assumes tokens are stored as JSON files in a tokens/ directory (Figma Tokens format) in a monorepo-like Node.js project.
Prerequisites & Setup
Project Structure
project-root/
├── tokens/
│ ├── source/ # Raw tokens (JSON)
│ │ ├── colors.json
│ │ ├── spacing.json
│ │ └── semantics.json # Semantic aliases (e.g., { "color-background-primary": { "value": "{color-primary-500}" } })
│ ├── config.json # Style Dictionary config
│ └── schema.json # JSON Schema for validation
├── scripts/
│ ├── lint-naming.js
│ ├── lint-accessibility.js
│ ├── lint-semantics.js
│ └── validate.js # Orchestrator
├── package.json
├── .github/workflows/tokens.yml # CI Pipeline
├── .pre-commit-config.yaml # Husky + lint-staged
└── README.md # Token guidelines
Dependencies (package.json)
{
"devDependencies": {
"style-dictionary": "^3.9.0",
"ajv": "^8.12.0", // JSON Schema validation
"@tokens-studio/validator": "^3.0.0", // Official token schema linting
"color": "^4.2.0", // Color manipulation
"chroma-js": "^2.5.0", // Contrast calculations
"husky": "^8.0.0",
"lint-staged": "^14.0.0"
},
"scripts": {
"tokens:lint": "node scripts/validate.js",
"tokens:build": "style-dictionary build",
"tokens:test": "npm run tokens:lint && npm run tokens:build && jest tokens.test.js",
"tokens:publish": "npm publish --access public"
}
}
Token Schema Example (tokens/schema.json)
JSON Schema for semantics (extend as needed):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"color-background-primary": {
"type": "object",
"properties": {
"value": { "const": "{color-primary-500}" },
"$type": { "const": "color" },
"$category": { "const": "background" }
},
"required": ["value", "$type", "$category"]
}
}
}
Local Development Workflow (Pre-Commit Hooks)
Use Husky + lint-staged for instant feedback:
.husky/pre-commit:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
.lintstagedrc.json:
{
"tokens/**/*.json": ["npm run tokens:lint", "git add"]
}
Run locally: npm run tokens:lint (fails fast on invalid tokens).
CI/CD Pipeline (GitHub Actions)
.github/workflows/tokens.yml:
name: Design Tokens Pipeline
on:
push:
branches: [main]
paths: ['tokens/**', 'scripts/**']
pull_request:
paths: ['tokens/**', 'scripts/**']
release:
types: [published] # Trigger on GitHub release/tag
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
# Stage 1: Naming Lint
- name: Lint Token Names
run: |
node scripts/lint-naming.js
env:
THRESHOLD: 'warning' # Fail on errors only
# Stage 2: Accessibility Lint
- name: Check Accessibility Thresholds
run: |
node scripts/lint-accessibility.js --min-ratio 4.5 --level AA
env:
COLOR_TOKENS_PATH: 'tokens/source/colors.json'
# Stage 3: Semantic Mappings Lint
- name: Validate Semantics
run: |
node scripts/lint-semantics.js
env:
SCHEMA_PATH: 'tokens/schema.json'
# Stage 4: Full Build & Test
- name: Build Tokens
run: npm run tokens:build
- name: Run Token Tests
run: npm run tokens:test
publish:
needs: validate
if: github.ref == 'refs/heads/main' || github.event_name == 'release'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org' # Or GitHub Packages
- run: npm ci
- run: npm run tokens:build
- run: npm run tokens:publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
Validation Scripts (Node.js)
-
scripts/lint-naming.js (Regex-based naming check):
const fs = require('fs');
const path = require('path');
const tokensPath = process.env.TOKENS_PATH || 'tokens/source';
const namingRegex = /^([a-z]+)-([a-z]+)-([a-z]+)-(\d+)$/; // e.g., color-primary-500
function lintNaming(dir) {
fs.readdirSync(dir).forEach(file => {
const tokens = JSON.parse(fs.readFileSync(path.join(dir, file)));
Object.keys(tokens).forEach(tokenName => {
if (!namingRegex.test(tokenName)) {
throw new Error(`Invalid name: ${tokenName}`);
}
});
});
}
lintNaming(tokensPath);
-
scripts/lint-accessibility.js (Contrast checks using Chroma.js):
const Chroma = require('chroma-js');
const fs = require('fs');
const colors = JSON.parse(fs.readFileSync(process.env.COLOR_TOKENS_PATH));
const minRatio = parseFloat(process.argv[2] || '4.5');
// Define pairs: e.g., text-on-primary-bg
const pairs = [
{ fg: '{color-text-primary}', bg: '{color-background-primary}' }
// Resolve values via Style Dictionary or recursive lookup
];
pairs.forEach(({ fg, bg }) => {
const fgColor = resolveTokenValue(colors, fg);
const bgColor = resolveTokenValue(colors, bg);
const ratio = Chroma.contrast(fgColor, bgColor);
if (ratio < minRatio) {
throw new Error(`Contrast failure: ${ratio}:1 < ${minRatio}:1`);
}
});
-
scripts/lint-semantics.js (Schema validation):
const Ajv = require('ajv');
const fs = require('fs');
const validator = require('@tokens-studio/validator');
const ajv = new Ajv();
const schema = JSON.parse(fs.readFileSync(process.env.SCHEMA_PATH));
const semantics = JSON.parse(fs.readFileSync('tokens/source/semantics.json'));
// Schema check
const valid = ajv.validate(schema, semantics);
if (!valid) throw new Error(ajv.errorsText());
// Tokens Studio validator for additional spec checks
validator.validate('tokens/source');
-
scripts/validate.js (Orchestrator):
require('./lint-naming');
require('./lint-accessibility');
require('./lint-semantics');
console.log('✅ All validations passed!');
Style Dictionary Config (tokens/config.json)
Transforms tokens to CSS/JS outputs:
{
"source": ["tokens/source/*.json"],
"platforms": {
"css": {
"transformGroup": "css",
"buildPath": "dist/css/",
"files": [{"destination": "_tokens.css", "format": "css/variables"}]
},
"js": {
"transformGroup": "js",
"buildPath": "dist/js/",
"files": [{"destination": "tokens.js", "format": "javascript/module"}]
}
}
}
Monitoring & Best Practices
- Failure Handling: Pipeline fails on lint errors; use Slack/Teams notifications via Actions.
- Threshold Customization: Env vars for ratios/levels (e.g.,
--level AAA for 7:1).
- Testing: Add Jest snapshots for token outputs (
tokens.test.js).
- Versioning: Semantic versioning on tags; changelog via
conventional-changelog.
- Scalability: For large token sets, parallelize jobs (matrix strategy).
- Security: NPM token as GitHub secret; semantic-release for automated versioning.
- Docs: Enforce via PR templates linking token guidelines.
This pipeline ensures tokens are production-ready, accessible, and consistent. Rollout: Start with local hooks, then CI. Estimated setup: 2-4 hours. Ping me for refinements! 🕵️♂️