#!/usr/bin/env node
/**
* Generate `ui/styles/tokens.css` from `src/design/tokens.ts`.
*
* The reporter inlines the tokens by calling `toCss()` at runtime; Vite and
* Tailwind cannot do that, so the same function is written to a file the
* stylesheet imports. The file is committed so a fresh clone renders before
* anything is generated, and regenerated by a Vite plugin on every build —
* `web:build`, `web:dev`, `electron:build` and `electron:dev` all invoke Vite
* directly, so a `prebuild` script would cover only one of the four.
*
* `--check` fails when the committed file is stale, for CI.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, resolve } from 'node:path';
import { createRequire } from 'node:module';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const target = resolve(root, 'ui/styles/tokens.css');
/** Load `toCss()` without a build step, by stripping the types. */
async function loadToCss() {
const source = readFileSync(resolve(root, 'src/design/tokens.ts'), 'utf8');
const js = source
.replace(/^export interface[\s\S]*?^}/gm, '')
.replace(/: readonly \w+\[\]/g, '')
.replace(/ as const/g, '')
.replace(/^function declarations\(tokens: Record<string, string>, indent = ' '\): string \{/m,
'function declarations(tokens, indent = " ") {')
.replace(/export function toCss\(\): string \{/, 'export function toCss() {');
const module = await import(`data:text/javascript,${encodeURIComponent(js)}`);
return module.toCss;
}
const toCss = await loadToCss();
const banner = `/*
* GENERATED FILE — do not edit.
*
* Source: src/design/tokens.ts Regenerate: npm run gen:tokens
*
* Emitted unlayered on purpose: the @theme block in tailwind.css aliases these
* custom properties to themselves, which resolves only because unlayered CSS
* outranks cascade layers.
*/
`;
const css = banner + toCss();
if (process.argv.includes('--check')) {
let current = '';
try {
current = readFileSync(target, 'utf8');
} catch {
console.error('gen-tokens: ui/styles/tokens.css is missing. Run `npm run gen:tokens`.');
process.exit(1);
}
if (current !== css) {
console.error('gen-tokens: ui/styles/tokens.css is stale. Run `npm run gen:tokens`.');
process.exit(1);
}
console.log('gen-tokens: tokens.css is up to date.');
} else {
writeFileSync(target, css, 'utf8');
console.log(`gen-tokens: wrote ${target.replace(root + '/', '')}`);
}
// Exported for the Vite plugin, which calls this file rather than shelling out.
export { toCss };
createRequire(import.meta.url);
pathToFileURL(target);