Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { defineConfig } from "@terrazzo/cli";
import { build, Logger, parse } from "@terrazzo/parser";
import { findRepoRoot } from "./paths.ts";
import {
flatten,
formatToken,
readBindings,
replaceRegion,
validateProduction,
} from "./production.ts";
export async function buildProductionFiles(root = findRepoRoot()) {
const sources = [
"reference/color.json",
"semantic/color.json",
"component/color.json",
"reference/foundations.json",
"semantic/foundations.json",
"reference/themes.json",
"themes/builtin.json",
"reference/shared.json",
"semantic/shared.json",
].map((file) => {
const path = join(root, "packages/design-tokens/src", file);
return { filename: pathToFileURL(path), src: readFileSync(path, "utf8") };
});
const source: ReturnType<typeof flatten> = {};
for (const input of sources)
for (const [id, token] of Object.entries(flatten(JSON.parse(input.src)))) {
if (source[id]) throw new Error(`Duplicate token: ${id}`);
source[id] = token;
}
const bindings = readBindings(root);
validateProduction(source, bindings);
const logger = new Logger({ level: "silent" });
const config = defineConfig({
alphabetize: false,
plugins: [
{
name: "cindy-desktop",
build({ tokens, outputFile }) {
const backingPath = "apps/desktop/src/shared/windowBackdrop.ts";
const backing = Object.entries(bindings.windowBacking)
.map(
([mode, id]) =>
` ${mode}: '${formatToken(id, tokens, source)}',`,
)
.join("\n");
outputFile(
backingPath,
replaceRegion(
readFileSync(join(root, backingPath), "utf8"),
"window-backing",
`export const CINDY_ACRYLIC_WINDOW_BACKING = {\n${backing}\n} as const;`,
),
);
const f = bindings.foundations;
const cssValue = (id: string) => formatToken(id, tokens, source);
const values = (map: Record<string, string>) =>
Object.fromEntries(
Object.entries(map).map(([key, id]) => [
key,
Number.parseFloat(cssValue(id)),
]),
);
const variable = (id: string) => {
const entry = Object.entries(f.css).find(
([, token]) => token === id,
);
if (!entry) throw new Error(`Missing CSS binding: ${id}`);
return `var(--${entry[0]})`;
};
const vars = (map: Record<string, string>) =>
Object.fromEntries(
Object.entries(map).map(([key, id]) => [key, variable(id)]),
);
const fontSize = {
...vars(f.numeric),
...Object.fromEntries(
Object.entries(f.text).map(([key, id]) => [
key,
[variable(id), { lineHeight: variable(f.lineHeight[key]) }],
]),
),
};
const radius = {
...vars(f.radius),
lg: "var(--radius)",
md: "calc(var(--radius) - var(--radius-offset-md))",
sm: "calc(var(--radius) - var(--radius-offset-sm))",
};
const header =
"// GENERATED by Terrazzo 2.7.1 — edit packages/design-tokens/src only.\n";
const declaration = (name: string, value: unknown) =>
`export const ${name} = ${JSON.stringify(value, null, 2)};\n`;
outputFile(
"apps/desktop/src/renderer/styles/generated/tokens.css",
"/* GENERATED by Terrazzo 2.7.1 — edit packages/design-tokens/src only. */\n@layer base {\n :root {\n" +
Object.entries(f.css)
.map(([name, id]) => ` --${name}: ${cssValue(id)};`)
.join("\n") +
"\n" +
bindings.bootstrapCss
.map(
(id) =>
` --${id}: ${cssValue(bindings.defaults[id].light!)};`,
)
.join("\n") +
"\n }\n .dark {\n" +
bindings.bootstrapCss
.map(
(id) =>
` --${id}: ${cssValue(bindings.defaults[id].dark!)};`,
)
.join("\n") +
"\n }\n}\n",
);
outputFile(
"apps/desktop/src/renderer/styles/generated/token-mappings.ts",
header +
declaration("UI_TEXT_TOKEN_SIZES", values(f.numeric)) +
declaration("SCALED_TAILWIND_TOKENS", values(f.text)) +
declaration("TAILWIND_LINE_HEIGHTS", values(f.lineHeight)) +
declaration("NUMERIC_TEXT_CLASSES", Object.keys(f.numeric)),
);
const tailwindPath = "apps/desktop/tailwind.config.ts";
const tailwindMappings =
`const TAILWIND_FONT_SIZE: Record<string, string | [string, { lineHeight: string }]> = ${JSON.stringify(fontSize, null, 2)};\n` +
declaration("TAILWIND_SPACING", vars(f.spacing)) +
declaration("TAILWIND_RADIUS", radius) +
declaration("TAILWIND_FONT_WEIGHT", vars(f.fontWeight)) +
declaration(
"MOTION_CSS",
Object.fromEntries(
Object.entries(f.motion).map(([key, id]) => [
key,
`var(--motion-${key}, ${cssValue(id)})`,
]),
),
);
outputFile(
tailwindPath,
replaceRegion(
readFileSync(join(root, tailwindPath), "utf8"),
"tailwind",
tailwindMappings.replaceAll("export const ", "const "),
),
);
outputFile(
"apps/desktop/src/shared/generated/appearance-tokens.ts",
header + declaration("DEFAULT_FONT_SIZES", values(f.defaults)),
);
for (const [file, theme] of Object.entries(bindings.themes)) {
const path = `apps/desktop/src/renderer/themes/builtin/${file}`;
const entries = Object.entries(theme.tokens).map(([id, token]) => {
const description = (source[token] as { $description?: string })
.$description;
return ` ${JSON.stringify(id)}: ${JSON.stringify(formatToken(token, tokens, source))},${description ? ` // ${description.replaceAll("\n", " ")}` : ""}`;
});
outputFile(
path,
replaceRegion(
readFileSync(join(root, path), "utf8"),
"theme",
`const GENERATED_OVERRIDES = {\n${entries.join("\n")}\n} as const;`,
),
);
}
const defaults = Object.fromEntries(
Object.entries(bindings.defaults).map(([id, modes]) => [
id,
Object.fromEntries(
Object.entries(modes).map(([mode, token]) => [
mode,
token === null ? null : formatToken(token, tokens, source),
]),
),
]),
);
const docPath = "docs/design-rules/DESIGN.md";
let doc = readFileSync(join(root, docPath), "utf8");
const docRegion = (name: string, body: string) => {
doc = replaceRegion(doc, name, body, "markdown");
};
docRegion(
"semantic-colors",
"| Category | Slot | Default Light | Default Dark | Primary use |\n| --- | --- | --- | --- | --- |\n" +
bindings.documentation.semanticColors
.map((row) => {
const modes = bindings.defaults[row.id];
return `| ${row.category} | \`--${row.id}\` | \`${formatToken(modes.light!, tokens, source)}\` | \`${formatToken(modes.dark!, tokens, source)}\` | ${row.use} |`;
})
.join("\n"),
);
docRegion(
"login-colors",
"| token | light | dark | 核验源 |\n| --- | --- | --- | --- |\n" +
bindings.documentation.loginColors
.map((row) => {
const values = (mode: "light" | "dark") =>
row.ids
.map(
(id) =>
`\`${formatToken(bindings.defaults[id][mode]!, tokens, source)}\``,
)
.join(" / ");
return `| ${row.label} | ${values("light")} | ${values("dark")} | ${row.use} |`;
})
.join("\n"),
);
const sizes = Object.values(f.numeric).map((id) =>
Number.parseFloat(formatToken(id, tokens, source)),
);
docRegion(
"numeric-type",
`- **UI 段:{${sizes.filter((n) => n <= 16).join(", ")}}px;标题 / 内容段:{${sizes.filter((n) => n > 16).join(", ")}}px。** 下限 10px —— 9px 及以下禁止(再小就不是文字是纹理)。`,
);
outputFile(docPath, doc);
const path = "apps/desktop/src/renderer/themes/colors.ts";
outputFile(
path,
replaceRegion(
readFileSync(join(root, path), "utf8"),
"defaults",
`const GENERATED_DEFAULTS = ${JSON.stringify(defaults, null, 2)} as const;\n\n` +
"export const EFFORT_TIER_COLORS = {\n" +
["minimal", "low", "medium", "high", "xhigh", "max", "ultra"]
.map(
(key) =>
` ${key}: GENERATED_DEFAULTS['effort-tier-${key}'].light,`,
)
.join("\n") +
"\n} as const;\n\n" +
"export const PRICE_TIER_COLORS = {\n t1: EFFORT_TIER_COLORS.low,\n t2: GENERATED_DEFAULTS['price-tier-t2'].light,\n t3: GENERATED_DEFAULTS['price-tier-t3'].light,\n} as const;",
),
);
},
},
],
});
const parsed = await parse(sources, { config, logger });
const result = await build(parsed.tokens, { ...parsed, config, logger });
return result.outputFiles.map((f) => ({
path: join(root, f.filename),
body: String(f.contents),
}));
}
export function assertFresh(
files: Array<{ path: string; body: string }>,
read: (path: string) => string | undefined = (path) => {
try {
return readFileSync(path, "utf8");
} catch {
return undefined;
}
},
): void {
for (const file of files)
if (read(file.path) !== file.body)
throw new Error(
`Stale generated output: ${file.path}. Run pnpm --filter @cindy/design-tokens generate`,
);
}
export async function generateProduction(root = findRepoRoot(), check = false) {
const files = await buildProductionFiles(root);
for (const file of files) {
if (check) {
assertFresh([file]);
} else {
mkdirSync(dirname(file.path), { recursive: true });
let current: string | undefined;
try {
current = readFileSync(file.path, "utf8");
} catch {
/* New full-file output. */
}
if (current !== file.body) {
const temporary = `${file.path}.ds8-${process.pid}.tmp`;
writeFileSync(temporary, file.body);
renameSync(temporary, file.path);
}
}
}
return files;
}
if (
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
await generateProduction(findRepoRoot(), process.argv.includes("--check"));
}