A complete Guideline Rules configuration for automating, validating, transforming, and distributing design tokens across platforms with TypeScript, Style Dictionary, and CI/CD.
Every frontend team hits the same wall: designers update colors in Figma, developers manually copy hex codes, CSS variables drift from designs, and nobody knows which button variant is actually "primary" anymore. You're spending hours on token housekeeping instead of building features.
Here's what kills productivity in design systems:
Token Drift: Design updates don't reach code, leaving your product with inconsistent colors, spacing, and typography across platforms Manual Sync Hell: Copy-pasting values from Figma to CSS, then to iOS, then to Android - each with different formats Breaking Changes: No way to know if changing a token will break 47 components across 3 apps Zero Documentation: Developers guess which tokens to use, creating new ones instead of reusing existing ones
Your design system becomes a maintenance nightmare instead of a productivity accelerator.
This Cursor Rules configuration turns design tokens into a fully automated, bulletproof system that eliminates manual work and keeps design and code perfectly synchronized.
Single Source of Truth: All tokens live in /tokens/index.json with automatic validation, transformation, and distribution across every platform you support.
Bidirectional Figma Sync: Designers update tokens in Figma Tokens Studio, automatically creating PRs with validated changes ready for review and deployment.
Multi-Platform Generation: One token definition automatically generates CSS variables, SCSS maps, TypeScript modules, Android XML, and iOS JSON - no manual conversion ever again.
// One token definition...
{
"color": {
"surface": {
"primary": {
"value": "#2563eb",
"type": "color"
}
}
}
}
// ...generates for every platform:
/* CSS */ --color-surface-primary: #2563eb;
/* SCSS */ $color-surface-primary: #2563eb;
/* iOS */ "colorSurfacePrimary": "#2563eb"
/* Android */ <color name="color_surface_primary">#2563eb</color>
# Designer updates color in Figma
# Developer manually copies new hex code
# Updates CSS variables
# Updates SCSS variables
# Updates mobile app tokens
# Realizes they missed 3 other files
# Components break because of typos
# Spends 2 hours fixing inconsistencies
# Designer updates Figma token
# Tokens Studio creates PR automatically
# CI validates, tests, builds all platforms
# Code review focuses on design impact
# Merge deploys consistent tokens everywhere
# Documentation updates automatically
# Zero manual work, zero inconsistencies
// Add new brand tokens
{
"brand": {
"acme": {
"color": {
"primary": { "value": "#ff6b35", "type": "color" }
}
}
}
}
// Style Dictionary automatically generates:
// - CSS: --acme-color-primary: #ff6b35
// - All platform files with proper namespacing
// - Theme-specific documentation
// - Type definitions for TypeScript
npm install -D style-dictionary @types/style-dictionary
npm install -D zod jest ts-jest @types/jest
npm install -D husky lint-staged prettier
// tokens/index.json
{
"color": {
"surface": {
"primary": {
"value": "#2563eb",
"type": "color",
"description": "Primary surface color for buttons and CTAs"
}
}
},
"space": {
"medium": {
"value": "1rem",
"type": "dimension",
"description": "Standard spacing unit"
}
}
}
// style-dictionary.config.ts
import StyleDictionary from 'style-dictionary';
const sd = StyleDictionary.extend({
source: ['tokens/**/*.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'dist/css/',
files: [{
destination: 'tokens.css',
format: 'css/variables'
}]
},
ts: {
transformGroup: 'js',
buildPath: 'dist/ts/',
files: [{
destination: 'tokens.ts',
format: 'javascript/es6'
}]
}
}
});
export default sd;
// src/validators/tokens.ts
import { z } from 'zod';
const TokenSchema = z.object({
value: z.union([z.string(), z.number()]),
type: z.enum(['color', 'dimension', 'duration', 'font']),
description: z.string().optional(),
});
export const validateTokens = (tokens: unknown) => {
const result = TokenSchema.safeParse(tokens);
if (!result.success) {
throw new Error(`Token validation failed: ${result.error.message}`);
}
return result.data;
};
# .github/workflows/tokens.yml
name: Design Tokens Pipeline
on:
push:
paths: ["tokens/**", "src/**"]
pull_request:
paths: ["tokens/**", "src/**"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with: { version: 8 }
- run: pnpm install --frozen-lockfile
- run: pnpm run token:validate
- run: pnpm run token:test
- run: pnpm run token:build
- uses: actions/upload-artifact@v3
with:
name: token-dist
path: dist
/tokens/ directory structureStart with the core setup above, then gradually add advanced features like theme inheritance, custom transforms, and visual regression testing. Your design system transforms from a maintenance burden into a development accelerator that pays dividends on every feature you build.
# Technology Stack Declaration
You are an expert in:
- TypeScript (Node.js ≤ v18)
- JSON / YAML for token storage
- Style Dictionary for token transformation
- Tokens Studio (Figma Tokens) for bidirectional sync
- Git & GitHub Actions for version control and CI/CD
- Jest + ts-jest for automated testing
- Docusaurus or Zeroheight for automated documentation
# Key Principles
- **Single Source of Truth (SSOT)**: All tokens live in `/tokens/index.json` (or `.yaml`). No hard-coded values elsewhere.
- **Semantic & Hierarchical Naming**: `category.type.item.state` → `color.surface.primary.hover`.
- **Immutable Commits for Releases**: Treat a versioned token bundle as immutable; patch via semantic version bumps only.
- **Automation First**: Every change to tokens must pass linting, testing, build, and publish jobs before merge.
- **Platform Agnostic Output**: Generate CSS variables, SCSS maps, Android XML, iOS JSON, and JS/TS modules from the same source.
# TypeScript Rules
- `src/` contains all transformation, validation, and CLI utilities.
- Use `ESM` modules (`import/export`); **never** use default exports – favour `export const`.
- All interfaces live in `src/types/` and are re-exported through `src/types/index.ts`.
- Strict compiler options: `"strict": true`, `"noImplicitAny": true`, `"exactOptionalPropertyTypes": true`.
- Use **functional utilities**; avoid classes unless extending a library base (e.g., StyleDictionary). Prefer pure functions.
- Example folder structure:
```text
/tokens ← SSOT JSON/YAML
/scripts ← one-off migration or seeding scripts
/src
├─ build/ ← Style Dictionary wrappers
├─ validators/ ← token schema validation (zod)
├─ cli.ts ← yarn token:build / token:validate
jest.config.ts
tsconfig.json
```
# Error Handling & Validation
- Validate token files **before** transformation:
```ts
import { z } from 'zod';
const TokenSchema = z.object({
value: z.union([z.string(), z.number()]),
type: z.enum(['color','dimension','duration','font']),
description: z.string().optional(),
});
export const validateTokens = (tokens: unknown) => {
const result = TokenSchema.safeParse(tokens);
if (!result.success) throw new Error(result.error.message);
return result.data;
};
```
- **Fail‐fast**: Throw errors on first invalid token; CI must stop.
- Map caught exceptions to actionable messages (e.g., file path & token key).
- CI lint step (`npm run token:lint`) runs Prettier + custom eslint-plugin-json-schema-validator.
- Add Git pre-commit hook (`husky`) to run `token:validate` locally.
# Style Dictionary Rules
- One **root** SD config (`style-dictionary.config.ts`) that:
- Loads `tokens/**/*.{json,yaml}`
- Supports multi-brand themes using `brand` and `mode` attributes.
- Registers custom transforms:
- `size/pxToRem` → converts pixel dimensions to `rem` (16px base).
- `color/hex8rgba` → outputs 8-digit HEX to `rgba()`.
- Splits output:
```ts
buildPath: 'dist/',
platforms: {
css: { transformGroup: 'css', buildPath: 'dist/css/', files: [...] },
scss: { transformGroup: 'scss', buildPath: 'dist/scss/', files: [...] },
ts: { transformGroup: 'js', buildPath: 'dist/ts/', files: [...] },
}
```
- Always run `style-dictionary build --config style-dictionary.config.ts` from CI, never manually commit `dist/`.
# Tokens Studio Rules
- Token sets in Figma mirror `/tokens/` directory names.
- Enable **Read-only Personal Access Token** for GitHub; Tokens Studio pushes PRs automatically.
- Use sync mode `Overwrite remote` to avoid drift; manual merges only through PR review.
# CI/CD (GitHub Actions)
```yaml
name: Design Tokens Pipeline
on:
push:
paths: ["tokens/**", "src/**"]
pull_request:
paths: ["tokens/**", "src/**"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with: { version: 8 }
- run: pnpm install --frozen-lockfile
- run: pnpm run token:validate
- run: pnpm run token:test
- run: pnpm run token:build
- name: Publish artifact
uses: actions/upload-artifact@v3
with:
name: dist
path: dist
```
- Tagging: a merged PR that modifies `/tokens/**` triggers `release.yml` which bumps version via `changeset`, publishes package, and pushes git tag.
# Testing
- **Jest** for unit tests of transforms & validators.
- **Visual regression**: integrate Chromatic or Storybook with tokens applied to sample components; fail build on ≥1 pixel diff.
- Duplicate check:
```ts
test('no duplicate token values', () => {
const values = new Set<string>();
Object.values(tokens).forEach(t => {
expect(values.has(t.value)).toBeFalsy();
values.add(t.value);
});
});
```
# Performance
- Incremental builds: cache `node_modules` and `/tokens` hash in GitHub Actions; skip build if unchanged.
- Only regenerate platform outputs for modified themes using `--filter` in Style Dictionary.
# Documentation
- Auto-generate **MDX** docs in `/docs/tokens` using a custom script:
```bash
node scripts/generate-docs.mjs --source tokens/index.json --out docs/tokens
```
- Preview via Docusaurus; auto-deploy to GitHub Pages on release.
# Security
- CI secrets: Store Figma Personal Access Token & NPM token in **GitHub Secrets**, reference via `${{ secrets.FIGMA_PAT }}`.
- Review PRs from external contributors with SAST (CodeQL) to prevent malicious token payloads.
# Common Pitfalls & How to Avoid Them
- **Drift between design & code**: enforce Tokens Studio PR requirement; block manual edits to `/tokens/**` on `main`.
- **Unscoped global CSS vars**: prefix all generated CSS variables with brand namespace (`--acme-`) via SD transform.
- **Breaking changes without major bump**: `changeset` must categorise `token deletions` & `renames` as `major`.
# Quick Commands
```bash
pnpm token:validate # zod validation
pnpm token:test # jest tests
pnpm token:build # style-dictionary build
pnpm token:docs # generate docs
```
Follow these rules to deliver a robust, automated, and maintainable design-token pipeline that scales across brands and platforms.