@paths.design/w3c-tokens-validator
v1.0.0
Published
W3C Design Tokens Community Group (DTCG) 1.0 schema and validator
Maintainers
Readme
W3C Design Tokens Schema & Validator
A generic, reusable schema and validator for W3C Design Tokens Community Group (DTCG) 1.0 specification. This package can be used in any project without repository-specific dependencies.
Schema Variants
This package includes two schema variants:
schemas/w3c-schema-strict.json(default) - Strict DTCG 1.0 compliance, structured values onlyschemas/w3c-schema-permissive.json- Extended schema with custom types and string value support
See schemas/README.md for detailed comparison and usage.
Features
- ✅ W3C DTCG 1.0 Compliant: Full support for all standard token types
- ✅ Dual Schema Support: Choose strict (default) or permissive validation
- ✅ Type-Safe: TypeScript definitions included
- ✅ Comprehensive Validation: Schema validation + custom rules (circular references, type checking)
- ✅ Accessibility Validation: Optional WCAG 2.1 contrast ratio validation
- ✅ Framework Agnostic: Works with any JavaScript/TypeScript project
- ✅ CLI Support: Command-line interface for easy integration
- ✅ Zero Dependencies (except Ajv for validation)
Installation
npm install @paths.design/w3c-tokens-validator ajv ajv-formats
# or
yarn add @paths.design/w3c-tokens-validator ajv ajv-formats
# or
pnpm add @paths.design/w3c-tokens-validator ajv ajv-formatsNote: ajv and ajv-formats are peer dependencies and must be installed separately.
Usage
TypeScript/JavaScript Module
import { validateDesignTokens, setDefaultSchema } from '@paths.design/w3c-tokens-validator';
import schema from '@paths.design/w3c-tokens-validator/schema-strict'; // or '/schema-permissive'
// Set the schema (required before first use)
setDefaultSchema(schema);
const tokens = {
color: {
primary: {
$type: 'color',
$value: {
colorSpace: 'srgb',
components: [1, 0, 0],
},
},
},
spacing: {
small: {
$type: 'dimension',
$value: {
value: 8,
unit: 'px',
},
},
},
};
const result = validateDesignTokens(tokens);
if (!result.isValid) {
console.error('Validation errors:', result.errors);
result.errors.forEach((error) => {
console.error(` ${error.path}: ${error.message}`);
});
}
if (result.warnings.length > 0) {
console.warn('Warnings:', result.warnings);
}Note: You can also provide the schema directly in options:
import { validateDesignTokens } from '@paths.design/w3c-tokens-validator';
import schema from '@paths.design/w3c-tokens-validator/schema-strict';
const result = validateDesignTokens(tokens, {
customSchema: schema,
});Command Line Interface
# After building (npm run build)
node dist/cli.js tokens.json
# Validate all JSON files in a directory
node dist/cli.js ./tokens/
# Or use the npm script
npm run validate tokens.jsonValidate from File
import { validateDesignTokensFromFile } from '@paths.design/w3c-tokens-validator';
const result = await validateDesignTokensFromFile('./tokens.json');
if (result.isValid) {
console.log('✅ Tokens are valid!');
} else {
console.error('❌ Validation failed:', result.errors);
}Format Results
import { validateDesignTokens, formatValidationResult } from '@paths.design/w3c-tokens-validator';
const result = validateDesignTokens(tokens);
console.log(formatValidationResult(result));Supported Token Types
The validator supports all DTCG 1.0 standard token types:
color- Color values with color space supportdimension- Size and spacing values (px, rem)fontFamily- Font family names or stacksfontWeight- Font weight (numeric or named)duration- Time durations in millisecondscubicBezier- Easing functionsnumber- Numeric valuesborder- Border composite valuestransition- Transition composite valuesshadow- Box shadow valuesgradient- Gradient valuestypography- Typography composite valuesstrokeStyle- Stroke/border style values
Validation Features
Schema Validation
Validates tokens against the W3C DTCG 1.0 JSON Schema, checking:
- Required properties (
$type,$value) - Value structure matches token type
- Valid color spaces and components
- Valid dimension units
- Proper token reference format
Custom Validations
Beyond schema validation, the validator also checks:
- Circular References: Detects circular token dependencies
- Self-References: Prevents tokens from referencing themselves
- Type Consistency: Warns about potential type mismatches
- Format Warnings: Suggests improvements for color/dimension formats
TypeScript Types
import type {
DesignTokens,
Token,
TokenType,
ColorValue,
DimensionValue,
TokenReference,
} from './w3c-types';
const tokens: DesignTokens = {
color: {
primary: {
$type: 'color',
$value: {
colorSpace: 'srgb',
components: [1, 0, 0],
},
},
},
};Examples
Basic Color Token
{
"color": {
"primary": {
"$type": "color",
"$value": {
"colorSpace": "srgb",
"components": [0.2, 0.4, 0.8]
},
"$description": "Primary brand color"
}
}
}Dimension Token with Reference
{
"spacing": {
"base": {
"$type": "dimension",
"$value": {
"value": 16,
"unit": "px"
}
},
"large": {
"$type": "dimension",
"$value": "{spacing.base}"
}
}
}Typography Composite Token
{
"typography": {
"heading": {
"$type": "typography",
"$value": {
"fontFamily": "Inter, sans-serif",
"fontSize": {
"value": 24,
"unit": "px"
},
"fontWeight": "bold",
"lineHeight": 1.5
}
}
}
}Shadow Token
{
"shadow": {
"elevation": {
"$type": "shadow",
"$value": {
"offsetX": {
"value": 0,
"unit": "px"
},
"offsetY": {
"value": 4,
"unit": "px"
},
"blur": {
"value": 8,
"unit": "px"
},
"spread": {
"value": 0,
"unit": "px"
},
"color": {
"colorSpace": "srgb",
"components": [0, 0, 0],
"alpha": 0.1
}
}
}
}
}Validation Options
import { validateDesignTokens } from './w3c-validator';
const result = validateDesignTokens(tokens, {
// Disable custom validations (only schema validation)
customValidations: false,
// Use a custom schema instead of default
customSchema: myCustomSchema,
// Allow additional properties (default: true)
allowAdditionalProperties: true,
});Integration Examples
CI/CD Pipeline
# GitHub Actions example
- name: Validate Design Tokens
run: |
npm install @paths.design/w3c-tokens-validator ajv ajv-formats
npm run build --prefix node_modules/@paths.design/w3c-tokens-validator
node node_modules/@paths.design/w3c-tokens-validator/dist/cli.js ./tokens/Pre-commit Hook
#!/bin/sh
# .git/hooks/pre-commit
npm run validate --prefix node_modules/@paths.design/w3c-tokens-validator -- ./tokens/
if [ $? -ne 0 ]; then
echo "Design token validation failed!"
exit 1
finpm Scripts
{
"scripts": {
"validate:tokens": "w3c-validate ./tokens/",
"validate:tokens:watch": "chokidar 'tokens/**/*.json' -c 'npm run validate:tokens'"
}
}API Reference
validateDesignTokens(tokens, options?)
Validates design tokens against the W3C schema.
Parameters:
tokens(unknown): The design tokens object to validateoptions(ValidationOptions, optional): Validation options
Returns: ValidationResult
validateDesignTokensFromFile(filePath, options?)
Validates design tokens from a JSON file.
Parameters:
filePath(string): Path to the JSON fileoptions(ValidationOptions, optional): Validation options
Returns: Promise<ValidationResult>
formatValidationResult(result)
Formats validation results for console output.
Parameters:
result(ValidationResult): Validation result to format
Returns: string
Contributing
This is a generic, reusable package. To use it in your project:
- Copy the files to your project
- Install dependencies (
ajv,ajv-formats) - Import and use as needed
License
MIT
Author
Darian Rosebrook
GitHub: @darianrosebrook
This schema and validator are based on the W3C Design Tokens Community Group specification and can be used freely in any project.
Contrast Validation (Optional)
The validator includes optional WCAG 2.1 contrast ratio validation for accessibility:
import { validateDesignTokensWithContrast } from '@paths.design/w3c-tokens-validator/with-contrast';
import schema from '@paths.design/w3c-tokens-validator/schema-strict';
import { setDefaultSchema } from '@paths.design/w3c-tokens-validator';
setDefaultSchema(schema);
const result = validateDesignTokensWithContrast(tokens, {
contrastValidation: {
level: 'AA_NORMAL', // WCAG AA for normal text
colorPairs: [
{
foreground: '#000000',
background: '#ffffff',
context: 'Primary text on background',
level: 'AA_NORMAL',
},
],
},
});
if (result.contrast) {
console.log(
`Contrast validation: ${result.contrast.validPairs}/${result.contrast.totalPairs} pairs passing`
);
}WCAG Levels
AA_NORMAL: 4.5:1 (normal text, 14pt and smaller)AA_LARGE: 3.0:1 (large text, 18pt+ or 14pt+ bold)AAA_NORMAL: 7.0:1 (enhanced accessibility, normal text)AAA_LARGE: 4.5:1 (enhanced accessibility, large text)
