Files
ipal-kit/src/modules/tokens/cli.ts
T
Radosław SmolińskiandClaude Opus 5.5 ca8e93eaf4 Design tokens: ipal-tokens CLI, components on single names, templates, tests
- bin ipal-tokens: src/design/tokens.ts → src/design/tokens.css, --check, WCAG
  contrast report (fails on AA errors; --report, --warn-only)
- CookieBanner / CookieButton read the single --ipal-* roles; the fallback follows
  color-scheme via light-dark() and still honours the legacy -dark variables
- lightbox fade reads --ipal-duration / --ipal-ease-out
- DESIGN.md and tokens.ts templates in ipal-setup/resources

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:55:59 +01:00

92 lines
4.3 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, relative, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { contrastReport, type ContrastRow } from './contrast.js'
import { tokensToCss } from './css.js'
import { defineTokens, type TokensInput } from './define.js'
export const TOKENS_CLI_USAGE = `Usage: ipal-tokens [--in src/design/tokens.ts] [--out src/design/tokens.css] [--check] [--report] [--warn-only]
Generates the brand CSS from the tokens file and checks WCAG contrast.
--check fail when the CSS file is out of date (CI, ipal-doctor); writes nothing
--report print every checked pair (for DESIGN.md), not only the failures
--warn-only report contrast failures without failing`
type Log = (line: string) => void
function arg(args: string[], name: string, fallback: string): string {
const i = args.indexOf(name)
const value = i >= 0 ? args[i + 1] : undefined
if (i >= 0 && (!value || value.startsWith('-'))) {throw new Error(`${name} needs a path`)}
return value ?? fallback
}
/** Contrast rows as aligned text lines; failures marked ✗ (error) or ! (warning). */
export function formatContrastReport(rows: ContrastRow[]): string[] {
return rows.map((r) => {
const mark = r.pass ? '✓' : r.level === 'warn' ? '!' : '✗'
const ratio = r.ratio === null ? 'n/a (colour not parsed)' : `${r.ratio.toFixed(2)}:1`
const where = `${r.theme}${r.scope === 'inverse' ? ' · inverse' : ''}`
return `${mark} ${`${r.fg} on ${r.bg}`.padEnd(36)} ${ratio.padEnd(10)} min ${r.min}:1 (${where})`
})
}
async function loadTokens(file: string): Promise<TokensInput> {
if (file.endsWith('.json')) {return JSON.parse(readFileSync(file, 'utf8')) as TokensInput}
try {
const mod = (await import(pathToFileURL(file).href)) as { default?: TokensInput; tokens?: TokensInput }
const tokens = mod.tokens ?? mod.default
if (!tokens) {throw new Error(`${file} must export \`tokens\` (or a default export)`)}
return tokens
} catch (error) {
if ((error as { code?: string }).code === 'ERR_UNKNOWN_FILE_EXTENSION') {
throw new Error(`this Node cannot import .ts files: use Node 22.18+ (or run with --experimental-strip-types)`)
}
throw error
}
}
/** The `ipal-tokens` command. Returns the exit code. */
export async function runTokensCli(args: string[], { cwd = process.cwd(), log = console.log }: { cwd?: string; log?: Log } = {}): Promise<number> {
if (args.includes('--help') || args.includes('-h')) {
log(TOKENS_CLI_USAGE)
return 0
}
try {
const input = resolve(cwd, arg(args, '--in', 'src/design/tokens.ts'))
const output = resolve(cwd, arg(args, '--out', 'src/design/tokens.css'))
if (!existsSync(input)) {
log(`ipal-tokens: ${relative(cwd, input)} not found (copy the template from .agents/skills/ipal-setup/resources/tokens.ts)`)
return 1
}
const tokens = defineTokens(await loadTokens(input))
const css = tokensToCss(tokens, { source: relative(cwd, input) })
const current = existsSync(output) ? readFileSync(output, 'utf8') : null
let code = 0
if (args.includes('--check')) {
if (current !== css) {
log(`✗ ${relative(cwd, output)} is out of date — run \`pnpm exec ipal-tokens\``)
code = 1
} else {log(`✓ ${relative(cwd, output)} is up to date`)}
} else if (current !== css) {
mkdirSync(dirname(output), { recursive: true })
writeFileSync(output, css)
log(`wrote ${relative(cwd, output)}`)
} else {log(`${relative(cwd, output)} unchanged`)}
const rows = contrastReport(tokens)
const errors = rows.filter((r) => !r.pass && r.level === 'error')
const shown = args.includes('--report') ? rows : rows.filter((r) => !r.pass || r.ratio === null)
log(`\nWCAG contrast: ${rows.filter((r) => r.pass && r.ratio !== null).length} of ${rows.length} pairs pass${args.includes('--report') ? ' (paste into DESIGN.md → Colour)' : ''}`)
for (const line of formatContrastReport(shown)) {log(` ${line}`)}
if (errors.length) {
log(`\n${errors.length} pair(s) below the WCAG AA minimum${args.includes('--warn-only') ? ' (--warn-only: not failing)' : ''}`)
if (!args.includes('--warn-only')) {code = 1}
}
return code
} catch (error) {
log(`ipal-tokens: ${(error as Error).message}`)
return 1
}
}