An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {createHash, randomUUID} from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {
assertWithin,
PathSafetyError,
} from '../../../../foundation/fs/path-safety.mjs';
import {publishNewFile} from '../../../../foundation/fs/publish-file.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
import {AstryxError} from '../../../error.mjs';
import {
generatePaletteSet,
PALETTE_BLACK,
PALETTE_GENERATOR_VERSION,
PALETTE_WHITE,
serializeGenerationResult,
} from './generator.mjs';
import {PALETTE_PREVIEW_VERSION, renderPalettePreview} from './preview.mjs';
/** Format of the TypeScript candidate module written for a `.ts` output. */
export const PALETTE_TYPESCRIPT_FORMAT_VERSION = 'palette-typescript-v1';
/** Format of the canonical JSON candidate the recipe fixtures pin. */
export const PALETTE_JSON_FORMAT_VERSION = 'palette-json-v1';
/** @typedef {import('../../theme.type.mjs').TonalPaletteCandidate} TonalPaletteCandidate */
/** @typedef {import('../../theme.type.mjs').TonalPaletteGenerationInput} TonalPaletteGenerationInput */
/** @typedef {'light' | 'dark'} PaletteMode */
/** @typedef {ReturnType<typeof generatePaletteSet>} PaletteGenerationResult */
/** @typedef {{path: string, next: string}} PendingFile */
/** @typedef {{format: typeof PALETTE_TYPESCRIPT_FORMAT_VERSION | typeof PALETTE_JSON_FORMAT_VERSION, text: string}} SerializedCandidate */
/** @param {PaletteGenerationResult} result @returns {TonalPaletteCandidate} */
function paletteSnapshot(result) {
return {
schemaVersion: 1,
status: 'candidate',
recipe: result.recipe,
black: PALETTE_BLACK,
white: PALETTE_WHITE,
stops: [...result.request.stops],
palette: Object.fromEntries(
result.families.map(family => [
family.id,
{
name: family.name,
...(family.light ? {light: family.light.colors} : {}),
...(family.dark ? {dark: family.dark.colors} : {}),
},
]),
),
};
}
/** @param {TonalPaletteCandidate} candidate */
function serializePaletteModule(candidate) {
return `// Generated by ${candidate.recipe}. Review before committing.\nexport const black = '${candidate.black}' as const;\nexport const white = '${candidate.white}' as const;\n\n// prettier-ignore\nexport const palette = ${serializePalette(candidate.palette)} as const;\n\nexport default palette;\n`;
}
/** @param {Record<string, string>} colors @param {number} indentation */
function serializeRamp(colors, indentation) {
const prefix = ' '.repeat(indentation);
const entries = Object.entries(colors).sort(
([left], [right]) => Number(left) - Number(right),
);
return `{\n${entries
.map(
([stop, color]) =>
`${prefix} ${JSON.stringify(stop)}: ${JSON.stringify(color)}`,
)
.join(',\n')}\n${prefix}}`;
}
/** @param {TonalPaletteCandidate['palette']} palette @param {number} [indentation] */
function serializePalette(palette, indentation = 0) {
const prefix = ' '.repeat(indentation);
return `{\n${Object.entries(palette)
.map(([familyId, family]) => {
const properties = [
`${prefix} "name": ${JSON.stringify(family.name)}`,
];
for (const mode of /** @type {PaletteMode[]} */ (['light', 'dark'])) {
if (family[mode]) {
properties.push(
`${prefix} "${mode}": ${serializeRamp(family[mode], indentation + 4)}`,
);
}
}
return `${prefix} ${JSON.stringify(familyId)}: {\n${properties.join(',\n')}\n${prefix} }`;
})
.join(',\n')}\n${prefix}}`;
}
/** @param {TonalPaletteCandidate} candidate */
export function serializePaletteCandidate(candidate) {
const stops = candidate.stops.map(stop => ` ${JSON.stringify(stop)}`);
return `{\n "schemaVersion": 1,\n "status": "candidate",\n "recipe": ${JSON.stringify(candidate.recipe)},\n "black": ${JSON.stringify(candidate.black)},\n "white": ${JSON.stringify(candidate.white)},\n "stops": [\n${stops.join(',\n')}\n ],\n "palette": ${serializePalette(candidate.palette, 2)}\n}\n`;
}
/**
* Serialize a candidate for its destination and name the format of the exact
* bytes produced. Without a destination, the canonical JSON form identifies
* the candidate.
*
* @param {TonalPaletteCandidate} candidate
* @param {string | null} outputPath
* @returns {SerializedCandidate}
*/
function serializeCandidate(candidate, outputPath) {
if (outputPath != null && outputPath.endsWith('.ts')) {
return {
format: PALETTE_TYPESCRIPT_FORMAT_VERSION,
text: serializePaletteModule(candidate),
};
}
if (outputPath == null || outputPath.endsWith('.json')) {
return {
format: PALETTE_JSON_FORMAT_VERSION,
text: serializePaletteCandidate(candidate),
};
}
throw new AstryxError(
'Palette output must end in .ts or .json.',
undefined,
ERROR_CODES.ERR_PALETTE_GENERATION,
);
}
/** @param {PaletteGenerationResult} result @param {SerializedCandidate} serialized @param {string | null} [previewText] @returns {import('../../theme.type.mjs').TonalPaletteGenerationReceipt} */
function receiptFor(result, serialized, previewText = null) {
return {
schemaVersion: 1,
recipe: result.recipe,
generatorVersion: PALETTE_GENERATOR_VERSION,
candidateFormatVersion: serialized.format,
candidateSha256: createHash('sha256').update(serialized.text).digest('hex'),
...(previewText
? {
preview: {
version: PALETTE_PREVIEW_VERSION,
sha256: createHash('sha256').update(previewText).digest('hex'),
},
}
: {}),
request: result.request,
diagnostics: {
families: Object.fromEntries(
result.families.map(family => [
family.id,
{
...(family.light ? {light: family.light.diagnostics} : {}),
...(family.dark ? {dark: family.dark.diagnostics} : {}),
},
]),
),
coordination: result.coordination,
},
};
}
/** @param {string} candidatePath */
function receiptPathFor(candidatePath) {
const extension = path.extname(candidatePath);
return extension
? `${candidatePath.slice(0, -extension.length)}.receipt.json`
: `${candidatePath}.receipt.json`;
}
/** @param {string} targetPath @param {string} cwd @param {string} label */
function resolveSafe(targetPath, cwd, label) {
try {
return assertWithin(targetPath, cwd, {label});
} catch (error) {
if (error instanceof PathSafetyError) {
throw new AstryxError(
error.message,
undefined,
ERROR_CODES.ERR_PATH_TRAVERSAL,
);
}
throw error;
}
}
/** @param {string} filePath */
function existingFileIdentity(filePath) {
try {
const stats = fs.statSync(filePath, {bigint: true});
return `${stats.dev}:${stats.ino}`;
} catch (error) {
if (
error &&
typeof error === 'object' &&
'code' in error &&
error.code === 'ENOENT'
) {
return null;
}
throw new AstryxError(
`Could not write palette candidate: ${error instanceof Error ? error.message : String(error)}`,
undefined,
ERROR_CODES.ERR_WRITE_FAILED,
);
}
}
/** @param {string} inputPath @param {PendingFile[]} files */
function assertDistinctFileIdentities(inputPath, files) {
const paths = [{path: inputPath}, ...files];
const seenPaths = new Set();
const seenIdentities = new Map();
for (const file of paths) {
if (seenPaths.has(file.path)) {
throw new AstryxError(
'Palette inputs and outputs must refer to distinct files.',
undefined,
ERROR_CODES.ERR_PATH_TRAVERSAL,
);
}
seenPaths.add(file.path);
const identity = existingFileIdentity(file.path);
if (identity != null && seenIdentities.has(identity)) {
throw new AstryxError(
'Palette inputs and outputs must refer to distinct files.',
undefined,
ERROR_CODES.ERR_PATH_TRAVERSAL,
);
}
if (identity != null) seenIdentities.set(identity, file.path);
}
}
/** @param {string} targetPath @param {string} contents */
function writeExclusiveTemporary(targetPath, contents) {
for (let attempt = 0; attempt < 10; attempt++) {
const temporary = path.join(
path.dirname(targetPath),
`.${path.basename(targetPath)}.tmp-${randomUUID()}`,
);
let created = false;
try {
const descriptor = fs.openSync(temporary, 'wx', 0o666);
created = true;
try {
fs.writeFileSync(descriptor, contents);
} finally {
fs.closeSync(descriptor);
}
return temporary;
} catch (error) {
if (created) {
try {
fs.unlinkSync(temporary);
} catch {
// Preserve the original write error.
}
}
if (
error &&
typeof error === 'object' &&
'code' in error &&
error.code === 'EEXIST'
) {
continue;
}
throw error;
}
}
throw new Error(`Could not reserve a temporary file for ${targetPath}.`);
}
/** @param {PendingFile[]} files @param {boolean} overwrite */
function writeFilesAtomically(files, overwrite) {
/** @type {Array<PendingFile & {existed: boolean, contents: Buffer | null, temporary: string | null, published: boolean}>} */
const originals = files.map(file => ({
...file,
existed: fs.existsSync(file.path),
contents: fs.existsSync(file.path) ? fs.readFileSync(file.path) : null,
temporary: null,
published: false,
}));
try {
for (const file of originals) {
fs.mkdirSync(path.dirname(file.path), {recursive: true});
file.temporary = writeExclusiveTemporary(file.path, file.next);
}
for (const file of originals) {
if (file.temporary == null) throw new Error('Missing temporary file.');
if (overwrite) {
fs.renameSync(file.temporary, file.path);
file.published = true;
} else {
// Publishing by hard link is an atomic no-replace operation. A target
// created after the initial existence check therefore remains safe.
publishNewFile(file.temporary, file.path);
file.published = true;
fs.unlinkSync(file.temporary);
}
file.temporary = null;
}
} catch (error) {
for (const file of originals) {
try {
if (file.temporary && fs.existsSync(file.temporary))
fs.unlinkSync(file.temporary);
if (file.published) {
if (file.existed && file.contents != null)
fs.writeFileSync(file.path, file.contents);
else if (fs.existsSync(file.path)) fs.unlinkSync(file.path);
}
} catch {
// Recovery is best effort; preserve the original write error.
}
}
throw error;
}
}
/**
* Generate an author-reviewable palette candidate from a JSON request.
*
* @param {string} configPath
* @param {{out?: string, preview?: string, overwrite?: boolean}} [options]
* @param {{cwd?: string}} [ctx]
* @returns {import('../../theme.type.mjs').ThemePaletteGenerateResponse}
*/
export function themePaletteGenerate(
configPath,
options = {},
{cwd = process.cwd()} = {},
) {
const resolvedConfig = resolveSafe(configPath, cwd, 'palette config path');
if (!fs.existsSync(resolvedConfig)) {
throw new AstryxError(
`Palette config not found: ${path.relative(cwd, resolvedConfig)}`,
undefined,
ERROR_CODES.ERR_FILE_NOT_FOUND,
);
}
/** @type {TonalPaletteGenerationInput} */
let request;
try {
request = JSON.parse(fs.readFileSync(resolvedConfig, 'utf-8'));
} catch (error) {
throw new AstryxError(
`Could not parse palette config: ${error instanceof Error ? error.message : String(error)}`,
undefined,
ERROR_CODES.ERR_PALETTE_GENERATION,
);
}
/** @type {PaletteGenerationResult} */
let result;
try {
result = generatePaletteSet(request);
} catch (error) {
throw new AstryxError(
error instanceof Error ? error.message : String(error),
undefined,
ERROR_CODES.ERR_PALETTE_GENERATION,
);
}
if (result.errors.length > 0) {
throw new AstryxError(
result.errors
.map(error => `${error.familyId}: ${error.message}`)
.join('\n'),
undefined,
ERROR_CODES.ERR_PALETTE_GENERATION,
);
}
const candidate = paletteSnapshot(result);
let serialized = serializeCandidate(candidate, null);
const previewText = options.preview ? renderPalettePreview(candidate) : null;
let receipt = receiptFor(result, serialized, previewText);
/** @type {string | null} */
let output = null;
/** @type {string | null} */
let receiptOutput = null;
/** @type {string | null} */
let previewOutput = null;
let written = false;
/** @type {'exists' | null} */
let reason = null;
/** @type {PendingFile[]} */
const files = [];
if (options.out) {
const resolvedOutput = resolveSafe(options.out, cwd, 'palette output path');
const resolvedReceipt = receiptPathFor(resolvedOutput);
serialized = serializeCandidate(candidate, resolvedOutput);
receipt = receiptFor(result, serialized, previewText);
const receiptText = serializeGenerationResult(receipt);
output = path.relative(cwd, resolvedOutput);
receiptOutput = path.relative(cwd, resolvedReceipt);
files.push(
{path: resolvedOutput, next: serialized.text},
{path: resolvedReceipt, next: receiptText},
);
}
if (options.preview) {
if (previewText == null) {
throw new Error('Palette preview content was not generated.');
}
const resolvedPreview = resolveSafe(
options.preview,
cwd,
'palette preview path',
);
if (!resolvedPreview.endsWith('.html')) {
throw new AstryxError(
'Palette preview output must end in .html.',
undefined,
ERROR_CODES.ERR_PALETTE_GENERATION,
);
}
previewOutput = path.relative(cwd, resolvedPreview);
files.push({path: resolvedPreview, next: previewText});
}
if (files.length > 0) {
assertDistinctFileIdentities(resolvedConfig, files);
if (!options.overwrite && files.some(file => fs.existsSync(file.path))) {
reason = 'exists';
} else {
try {
writeFilesAtomically(files, options.overwrite === true);
written = true;
} catch (error) {
throw new AstryxError(
`Could not write palette candidate: ${error instanceof Error ? error.message : String(error)}`,
undefined,
ERROR_CODES.ERR_WRITE_FAILED,
);
}
}
}
return {
type: 'theme.palette.generate',
data: {
recipe: result.recipe,
status: 'candidate',
familyCount: result.families.length,
stopCount: result.request.stops.length,
modes:
result.request.modeStrategy === 'light-and-dark'
? ['light', 'dark']
: [result.request.modeStrategy === 'light-only' ? 'light' : 'dark'],
output,
receipt: receiptOutput,
preview: previewOutput,
written,
reason,
candidate,
generationReceipt: receipt,
},
};
}