Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Share theme palette reference generation (#7678)

rubyycheung813c1d59eefd
diff --git a/.changeset/palette-receipt-versions.md b/.changeset/palette-receipt-versions.md
new file mode 100644
index 0000000000..9424d8b3ca
--- /dev/null
+++ b/.changeset/palette-receipt-versions.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] `astryx theme palette generate` receipts now name the generator implementation (`generatorVersion: 'palette-generator-v1'`) and the format of the candidate bytes they hash (`candidateFormatVersion`: `'palette-typescript-v1'` for a `.ts` output, `'palette-json-v1'` for a `.json` output or a printed candidate). `candidateSha256` and every other receipt field keep their meaning, values, and order, so existing readers keep working.
+
+@rubyycheung
diff --git a/packages/cli/README.md b/packages/cli/README.md
index e77fb806dd..ccb184f020 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -517,7 +517,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `theme.eject` | A local source-fork receipt with the resolved slug, displayName, source theme maintained flag, source-selector package, outputDir, source entry, exportName, and every file written, including the descriptor. The written local descriptor always uses maintained: false. |
| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |
-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
+| `theme.palette.generate` | An author-reviewable OKLCH palette response: recipe (`astryx-oklch-v1`), status (`candidate`), familyCount, stopCount, modes, candidate (`TonalPaletteCandidate`), and generationReceipt. The generationReceipt contains schemaVersion (1), recipe, generatorVersion (`palette-generator-v1`), candidateFormatVersion (`palette-typescript-v1` or `palette-json-v1`), candidateSha256, optional preview, resolved request, and diagnostics. File-write fields are output, receipt, preview, written, and reason (`exists` or null). |
| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
diff --git a/packages/cli/api/theme/palette/generate/generate.mjs b/packages/cli/api/theme/palette/generate/generate.mjs
index d2cd98a035..925c881346 100644
--- a/packages/cli/api/theme/palette/generate/generate.mjs
+++ b/packages/cli/api/theme/palette/generate/generate.mjs
@@ -12,16 +12,23 @@ 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) {
@@ -90,10 +97,28 @@ export function serializePaletteCandidate(candidate) {
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`;
}
-/** @param {TonalPaletteCandidate} candidate @param {string} outputPath */
+/**
+ * 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.endsWith('.ts')) return serializePaletteModule(candidate);
- if (outputPath.endsWith('.json')) return serializePaletteCandidate(candidate);
+ 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,
@@ -101,12 +126,14 @@ function serializeCandidate(candidate, outputPath) {
);
}
-/** @param {PaletteGenerationResult} result @param {string} candidateText @param {string | null} [previewText] @returns {import('../../theme.type.mjs').TonalPaletteGenerationReceipt} */
-function receiptFor(result, candidateText, previewText = null) {
+/** @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,
- candidateSha256: createHash('sha256').update(candidateText).digest('hex'),
+ generatorVersion: PALETTE_GENERATOR_VERSION,
+ candidateFormatVersion: serialized.format,
+ candidateSha256: createHash('sha256').update(serialized.text).digest('hex'),
...(previewText
? {
preview: {
@@ -345,9 +372,9 @@ export function themePaletteGenerate(
}
const candidate = paletteSnapshot(result);
- let candidateText = serializePaletteCandidate(candidate);
+ let serialized = serializeCandidate(candidate, null);
const previewText = options.preview ? renderPalettePreview(candidate) : null;
- let receipt = receiptFor(result, candidateText, previewText);
+ let receipt = receiptFor(result, serialized, previewText);
/** @type {string | null} */
let output = null;
/** @type {string | null} */
@@ -363,13 +390,13 @@ export function themePaletteGenerate(
if (options.out) {
const resolvedOutput = resolveSafe(options.out, cwd, 'palette output path');
const resolvedReceipt = receiptPathFor(resolvedOutput);
- candidateText = serializeCandidate(candidate, resolvedOutput);
- receipt = receiptFor(result, candidateText, previewText);
+ 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: candidateText},
+ {path: resolvedOutput, next: serialized.text},
{path: resolvedReceipt, next: receiptText},
);
}
diff --git a/packages/cli/api/theme/palette/generate/generate.test.mjs b/packages/cli/api/theme/palette/generate/generate.test.mjs
index c426a67303..df425100e8 100644
--- a/packages/cli/api/theme/palette/generate/generate.test.mjs
+++ b/packages/cli/api/theme/palette/generate/generate.test.mjs
@@ -6,7 +6,12 @@ import * as os from 'node:os';
import * as path from 'node:path';
import {afterEach, describe, expect, it} from 'vitest';
import {isErrorCode} from '../../../../foundation/response/error-codes.mjs';
-import {themePaletteGenerate} from './generate.mjs';
+import {
+ PALETTE_JSON_FORMAT_VERSION,
+ PALETTE_TYPESCRIPT_FORMAT_VERSION,
+ themePaletteGenerate,
+} from './generate.mjs';
+import {PALETTE_GENERATOR_VERSION} from './generator.mjs';
const temporaryDirectories = [];
@@ -79,7 +84,12 @@ describe('themePaletteGenerate', () => {
fs.readFileSync(path.join(cwd, 'ocean.palette.receipt.json'), 'utf-8'),
);
expect(receipt.recipe).toBe('astryx-oklch-v1');
- expect(receipt.candidateSha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(receipt.generatorVersion).toBe('palette-generator-v1');
+ expect(receipt.candidateFormatVersion).toBe('palette-typescript-v1');
+ expect(receipt.candidateSha256).toBe(
+ createHash('sha256').update(candidate).digest('hex'),
+ );
+ expect(receipt).toEqual(result.data.generationReceipt);
expect(candidate).toContain('// prettier-ignore');
expect(candidate).toContain("export const black = '#000000' as const;");
expect(candidate).toContain("export const white = '#ffffff' as const;");
@@ -103,6 +113,69 @@ describe('themePaletteGenerate', () => {
expect(result.data.receipt).toBe('ocean.palette.receipt.json');
});
+ it('names the generator and the format of the exact bytes each receipt covers', () => {
+ expect(PALETTE_GENERATOR_VERSION).toBe('palette-generator-v1');
+ expect(PALETTE_TYPESCRIPT_FORMAT_VERSION).toBe('palette-typescript-v1');
+ expect(PALETTE_JSON_FORMAT_VERSION).toBe('palette-json-v1');
+
+ const cwd = fixture();
+ const sha256 = file =>
+ createHash('sha256')
+ .update(fs.readFileSync(path.join(cwd, file)))
+ .digest('hex');
+ const printed = themePaletteGenerate('palette.config.json', {}, {cwd}).data
+ .generationReceipt;
+ const typescript = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts'},
+ {cwd},
+ ).data.generationReceipt;
+ const json = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean-json.palette.json'},
+ {cwd},
+ ).data.generationReceipt;
+
+ // Existing receipt fields keep their positions; the versions sit beside
+ // the digest they qualify.
+ expect(Object.keys(typescript)).toEqual([
+ 'schemaVersion',
+ 'recipe',
+ 'generatorVersion',
+ 'candidateFormatVersion',
+ 'candidateSha256',
+ 'request',
+ 'diagnostics',
+ ]);
+ expect(typescript).toMatchObject({
+ generatorVersion: PALETTE_GENERATOR_VERSION,
+ candidateFormatVersion: PALETTE_TYPESCRIPT_FORMAT_VERSION,
+ candidateSha256: sha256('ocean.palette.ts'),
+ });
+ expect(json).toMatchObject({
+ generatorVersion: PALETTE_GENERATOR_VERSION,
+ candidateFormatVersion: PALETTE_JSON_FORMAT_VERSION,
+ candidateSha256: sha256('ocean-json.palette.json'),
+ });
+ // Without an output path, the receipt covers the canonical JSON bytes.
+ expect(printed).toEqual(json);
+ // Only the serialized bytes differ between formats, never the generation.
+ expect(typescript.candidateSha256).not.toBe(json.candidateSha256);
+ expect({
+ ...typescript,
+ candidateFormatVersion: null,
+ candidateSha256: null,
+ }).toEqual({...json, candidateFormatVersion: null, candidateSha256: null});
+ for (const [file, receipt] of [
+ ['ocean.palette.receipt.json', typescript],
+ ['ocean-json.palette.receipt.json', json],
+ ]) {
+ expect(
+ JSON.parse(fs.readFileSync(path.join(cwd, file), 'utf-8')),
+ ).toEqual(receipt);
+ }
+ });
+
it('writes candidate JSON byte-identical to the recipe fixtures', () => {
const families = [
{id: 'neutral', name: 'Neutral', seed: '#777777', kind: 'neutral'},
@@ -164,7 +237,10 @@ describe('themePaletteGenerate', () => {
);
const printed = themePaletteGenerate('palette.config.json', {}, {cwd});
- expect(printed.data.generationReceipt.candidateSha256).toBe(sha256);
+ expect(printed.data.generationReceipt).toMatchObject({
+ candidateFormatVersion: 'palette-json-v1',
+ candidateSha256: sha256,
+ });
const result = themePaletteGenerate(
'palette.config.json',
@@ -174,7 +250,10 @@ describe('themePaletteGenerate', () => {
const written = fs.readFileSync(path.join(cwd, 'candidate.json'));
expect(written.length).toBe(bytes);
expect(createHash('sha256').update(written).digest('hex')).toBe(sha256);
- expect(result.data.generationReceipt.candidateSha256).toBe(sha256);
+ expect(result.data.generationReceipt).toMatchObject({
+ candidateFormatVersion: 'palette-json-v1',
+ candidateSha256: sha256,
+ });
}
});
diff --git a/packages/cli/api/theme/palette/generate/generator.mjs b/packages/cli/api/theme/palette/generate/generator.mjs
index 9ad1752e5b..5a2f4f46e1 100644
--- a/packages/cli/api/theme/palette/generate/generator.mjs
+++ b/packages/cli/api/theme/palette/generate/generator.mjs
@@ -25,6 +25,12 @@ import {
/** @typedef {{recipe: typeof PALETTE_RECIPE, status: 'candidate', request: NormalizedRequest, families: GeneratedFamily[], coordination: TonalPaletteCoordinationDiagnostics[], errors: {familyId: string, message: string}[]}} PaletteGenerationResult */
export const PALETTE_RECIPE = 'astryx-oklch-v1';
+/**
+ * Identity of this generator implementation. `PALETTE_RECIPE` names the
+ * normative algorithm; this names the code that ran it, so a receipt can tell
+ * two implementations of one recipe apart.
+ */
+export const PALETTE_GENERATOR_VERSION = 'palette-generator-v1';
export const PALETTE_BLACK = '#000000';
export const PALETTE_WHITE = '#ffffff';
export const DEFAULT_21_STOPS = Object.freeze([
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
index b5c91e29f5..f027bccc60 100644
--- a/packages/cli/api/theme/theme.type.mjs
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -245,7 +245,13 @@
* @typedef {object} TonalPaletteGenerationReceipt
* @property {1} schemaVersion
* @property {'astryx-oklch-v1'} recipe Recipe that produced the candidate.
- * @property {string} candidateSha256 SHA-256 over the candidate bytes as written.
+ * @property {'palette-generator-v1'} generatorVersion Generator
+ * implementation that ran the recipe.
+ * @property {'palette-typescript-v1' | 'palette-json-v1'} candidateFormatVersion
+ * Format of the candidate bytes `candidateSha256` covers: the TypeScript
+ * module for a `.ts` output, otherwise canonical JSON.
+ * @property {string} candidateSha256 SHA-256 over the candidate bytes in
+ * `candidateFormatVersion`, exactly as written when an output path is given.
* @property {{version: string, sha256: string}} [preview] Present when preview
* content was generated for the request, even if no file was written because
* the target already exists.
diff --git a/packages/cli/api/theme/themePaletteGenerate.doc.mjs b/packages/cli/api/theme/themePaletteGenerate.doc.mjs
index ac84eacbd6..61d5dfe3ae 100644
--- a/packages/cli/api/theme/themePaletteGenerate.doc.mjs
+++ b/packages/cli/api/theme/themePaletteGenerate.doc.mjs
@@ -61,7 +61,7 @@ export const doc = {
{
type: 'theme.palette.generate',
description:
- 'The candidate, generation receipt, summary counts, and optional file-write receipt.',
+ 'The candidate, summary counts, optional file-write result, and generationReceipt. The generationReceipt identifies generatorVersion `palette-generator-v1` and candidateFormatVersion `palette-typescript-v1` or `palette-json-v1` beside the candidate digest.',
},
],
throws: [
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 9d166c929a..35734c6671 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -272,7 +272,7 @@ export const doc = {
{
value: 'theme.palette.generate',
description:
- 'An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result.',
+ 'An author-reviewable OKLCH palette response: recipe (`astryx-oklch-v1`), status (`candidate`), familyCount, stopCount, modes, candidate (`TonalPaletteCandidate`), and generationReceipt. The generationReceipt contains schemaVersion (1), recipe, generatorVersion (`palette-generator-v1`), candidateFormatVersion (`palette-typescript-v1` or `palette-json-v1`), candidateSha256, optional preview, resolved request, and diagnostics. File-write fields are output, receipt, preview, written, and reason (`exists` or null).',
},
// upgrade
diff --git a/packages/cli/foundation/response/response-types.doc.test.mjs b/packages/cli/foundation/response/response-types.doc.test.mjs
index 48333595cc..6012159aab 100644
--- a/packages/cli/foundation/response/response-types.doc.test.mjs
+++ b/packages/cli/foundation/response/response-types.doc.test.mjs
@@ -172,6 +172,35 @@ describe('response-types EnumDoc names every field', () => {
expectNamed('theme.targets', fieldsOf(res.data));
});
+ it('theme.palette.generate, including receipt provenance', async () => {
+ const cwd = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-response-types-palette-'),
+ );
+ fs.writeFileSync(
+ path.join(cwd, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'light-only',
+ stops: [20, 50, 80],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+ const res = await data(
+ ['theme', 'palette', 'generate', 'palette.config.json'],
+ cwd,
+ );
+ expect(res.type).toBe('theme.palette.generate');
+ expectNamed('theme.palette.generate', [
+ ...Object.keys(res.data),
+ ...Object.keys(res.data.generationReceipt),
+ ]);
+ expect(describedAs('theme.palette.generate')).toMatch(
+ /generatorVersion.*palette-generator-v1/,
+ );
+ expect(describedAs('theme.palette.generate')).toMatch(
+ /candidateFormatVersion.*palette-typescript-v1.*palette-json-v1/,
+ );
+ });
+
it('gap-report.file, including each delivery', async () => {
const res = await data([
'gap-report',
diff --git a/scripts/generate-neutral-palette-refs.mjs b/scripts/generate-neutral-palette-refs.mjs
index 8041113e2d..d01ab6a93d 100644
--- a/scripts/generate-neutral-palette-refs.mjs
+++ b/scripts/generate-neutral-palette-refs.mjs
@@ -12,10 +12,13 @@
* @position Repository maintenance command and Neutral build drift guard.
*/
-import * as fs from 'node:fs';
import * as path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
-import * as ts from 'typescript';
+import {
+ countSelectedRefs,
+ createSelectedPaletteRefGenerator,
+ syncOutputs,
+} from './generate-selected-palette-refs.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -27,363 +30,23 @@ export const SELECTED_REFS_REL =
export const TEMPLATE_REFS_REL =
'packages/cli/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts';
-const COPYRIGHT = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';
-const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
-const HEX = /^#[0-9a-f]{6}$/u;
-
-function assertNoParseDiagnostics(file, label) {
- const diagnostic = file.parseDiagnostics[0];
- if (!diagnostic) return;
- const position = file.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
- throw new Error(
- `${label}:${position.line + 1}:${position.character + 1}: ${message}`,
- );
-}
-
-function unwrap(expression) {
- let current = expression;
- while (
- ts.isAsExpression(current) ||
- ts.isSatisfiesExpression(current) ||
- ts.isParenthesizedExpression(current)
- ) {
- current = current.expression;
- }
- return current;
-}
-
-function propertyName(name) {
- if (
- ts.isIdentifier(name) ||
- ts.isStringLiteral(name) ||
- ts.isNumericLiteral(name)
- ) {
- return name.text;
- }
- throw new Error(`Unsupported computed palette key: ${name.getText()}`);
-}
-
-function literalValue(expression) {
- const value = unwrap(expression);
- if (ts.isStringLiteral(value)) return value.text;
- if (!ts.isObjectLiteralExpression(value)) {
- throw new Error(
- `Palette values must be object or string literals: ${value.getText()}`,
- );
- }
-
- const result = {};
- for (const property of value.properties) {
- if (!ts.isPropertyAssignment(property)) {
- throw new Error(`Unsupported palette member: ${property.getText()}`);
- }
- result[propertyName(property.name)] = literalValue(property.initializer);
- }
- return result;
-}
-
-/** Parse the `palette` object from its generated TypeScript source. */
-export function parseFullPalette(source) {
- const file = ts.createSourceFile(
- FULL_PALETTE_REL,
- source,
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TS,
- );
- assertNoParseDiagnostics(file, FULL_PALETTE_REL);
-
- let palette = null;
- const visit = node => {
- if (
- ts.isVariableDeclaration(node) &&
- ts.isIdentifier(node.name) &&
- node.name.text === 'palette' &&
- node.initializer
- ) {
- palette = literalValue(node.initializer);
- }
- ts.forEachChild(node, visit);
- };
- visit(file);
-
- if (!palette || typeof palette !== 'object') {
- throw new Error(`${FULL_PALETTE_REL} exports no literal palette object.`);
- }
- return palette;
-}
-
-function destructuredAliases(file) {
- const aliases = new Map();
- const visit = node => {
- if (
- ts.isVariableDeclaration(node) &&
- ts.isObjectBindingPattern(node.name) &&
- node.initializer &&
- ts.isIdentifier(unwrap(node.initializer)) &&
- unwrap(node.initializer).text === 'neutralPaletteRefs'
- ) {
- for (const element of node.name.elements) {
- if (!ts.isIdentifier(element.name)) {
- throw new Error(
- 'Neutral palette reference aliases must be identifiers.',
- );
- }
- const family = element.propertyName
- ? propertyName(element.propertyName)
- : element.name.text;
- aliases.set(element.name.text, family);
- }
- }
- ts.forEachChild(node, visit);
- };
- visit(file);
- return aliases;
-}
-
-function paletteAccess(expression, aliases) {
- if (!ts.isPropertyAccessExpression(expression)) return null;
- const mode = expression.name.text;
- if (mode !== 'light' && mode !== 'dark') return null;
-
- const owner = expression.expression;
- if (ts.isIdentifier(owner) && aliases.has(owner.text)) {
- return {family: aliases.get(owner.text), mode};
- }
- if (
- ts.isPropertyAccessExpression(owner) &&
- ts.isIdentifier(owner.expression) &&
- owner.expression.text === 'neutralPaletteRefs'
- ) {
- return {family: owner.name.text, mode};
- }
- return null;
-}
-
-function rootedInPalette(expression, aliases) {
- const node = unwrap(expression);
- if (ts.isIdentifier(node)) {
- return node.text === 'neutralPaletteRefs' || aliases.has(node.text);
- }
- if (
- ts.isPropertyAccessExpression(node) ||
- ts.isElementAccessExpression(node)
- ) {
- return rootedInPalette(node.expression, aliases);
- }
- return false;
-}
-
-function isNonReferenceIdentifier(node) {
- if (!ts.isIdentifier(node)) return false;
- const parent = node.parent;
- if (!parent) return false;
- return (
- (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
- (ts.isPropertyAssignment(parent) && parent.name === node) ||
- (ts.isBindingElement(parent) && parent.propertyName === node) ||
- ((ts.isMethodDeclaration(parent) ||
- ts.isPropertyDeclaration(parent) ||
- ts.isPropertySignature(parent) ||
- ts.isMethodSignature(parent)) &&
- parent.name === node)
- );
-}
-
-function validatePaletteUses(file, aliases) {
- const visit = node => {
- const isPaletteExpression =
- !isNonReferenceIdentifier(node) &&
- (ts.isIdentifier(node) ||
- ts.isPropertyAccessExpression(node) ||
- ts.isElementAccessExpression(node)) &&
- rootedInPalette(node, aliases);
- const parent = node.parent;
- const parentContinuesAccess =
- parent != null &&
- (ts.isPropertyAccessExpression(parent) ||
- ts.isElementAccessExpression(parent)) &&
- parent.expression === node;
-
- if (isPaletteExpression && !parentContinuesAccess) {
- const isBindingName =
- ts.isIdentifier(node) &&
- parent != null &&
- ts.isBindingElement(parent) &&
- parent.name === node;
- const isImportName =
- ts.isIdentifier(node) &&
- parent != null &&
- (ts.isImportSpecifier(parent) ||
- ts.isImportClause(parent) ||
- ts.isNamespaceImport(parent));
- const isRootDestructure =
- ts.isIdentifier(node) &&
- node.text === 'neutralPaletteRefs' &&
- parent != null &&
- ts.isVariableDeclaration(parent) &&
- parent.initializer === node &&
- ts.isObjectBindingPattern(parent.name);
- const isCompleteReference =
- ts.isElementAccessExpression(node) &&
- paletteAccess(node.expression, aliases) !== null;
-
- if (
- !isBindingName &&
- !isImportName &&
- !isRootDestructure &&
- !isCompleteReference
- ) {
- throw new Error(
- `Palette references must be used directly as family.light[25] or family.dark[25]; unsupported alias or escape: ${node.getText(file)}`,
- );
- }
- }
- ts.forEachChild(node, visit);
- };
- visit(file);
-}
-
-/**
- * Discover selected palette references in lexical order. Family and mode order
- * follow first use; stops are de-duplicated and sorted during rendering.
- */
-export function discoverSelectedRefs(source, fullPalette) {
- const file = ts.createSourceFile(
- THEME_SOURCE_REL,
- source,
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TS,
- );
- assertNoParseDiagnostics(file, THEME_SOURCE_REL);
- const aliases = destructuredAliases(file);
- validatePaletteUses(file, aliases);
- const families = new Map();
-
- const visit = node => {
- if (ts.isElementAccessExpression(node)) {
- const access = paletteAccess(node.expression, aliases);
- if (access) {
- const argument = node.argumentExpression;
- if (!argument || !ts.isNumericLiteral(argument)) {
- throw new Error(
- `Palette references must use literal numeric stops: ${node.getText(file)}`,
- );
- }
- const stop = Number(argument.text);
- const value =
- fullPalette?.[access.family]?.[access.mode]?.[String(stop)];
- if (typeof value !== 'string' || !HEX.test(value)) {
- throw new Error(
- `Palette reference ${access.family}.${access.mode}[${stop}] is missing or invalid in the committed full palette.`,
- );
- }
-
- if (!families.has(access.family))
- families.set(access.family, new Map());
- const modes = families.get(access.family);
- if (!modes.has(access.mode)) modes.set(access.mode, new Set());
- modes.get(access.mode).add(stop);
- } else if (rootedInPalette(node.expression, aliases)) {
- throw new Error(
- `Palette references must use family.light[25] or family.dark[25] with literal keys: ${node.getText(file)}`,
- );
- }
- }
- ts.forEachChild(node, visit);
- };
- visit(file);
-
- if (families.size === 0) {
- throw new Error(
- `${THEME_SOURCE_REL} contains no selected palette references.`,
- );
- }
- return families;
-}
-
-function renderedKey(key) {
- return IDENTIFIER.test(key) ? key : JSON.stringify(key);
-}
-
-/** Render the complete selected-reference artifact. */
-export function renderSelectedRefs(themeSource, fullPaletteSource) {
- const palette = parseFullPalette(fullPaletteSource);
- const selected = discoverSelectedRefs(themeSource, palette);
- const lines = [
- COPYRIGHT.trimEnd(),
- '',
- "// Generated from the committed full palette for the stops used by Neutral's",
- '// theme source. Regenerate with `pnpm generate:neutral-palette-refs`.',
- '// Keep the complete palette available for authoring and audits without',
- '// making consumers pay for unused palette stops.',
- '// prettier-ignore',
- 'export const neutralPaletteRefs = {',
- ];
-
- for (const [family, modes] of selected) {
- lines.push(` ${renderedKey(family)}: {`);
- for (const [mode, stops] of modes) {
- const entries = [...stops]
- .sort((a, b) => a - b)
- .map(stop => `${stop}: '${palette[family][mode][String(stop)]}'`)
- .join(', ');
- lines.push(` ${mode}: {${entries}},`);
- }
- lines.push(' },');
- }
-
- lines.push('} as const;', '', 'export default neutralPaletteRefs;', '');
- return {content: lines.join('\n'), selected};
-}
-
-/** Count unique family/mode/stop references. */
-export function countSelectedRefs(selected) {
- let count = 0;
- for (const modes of selected.values()) {
- for (const stops of modes.values()) count += stops.size;
- }
- return count;
-}
-
-/** Write or compare generated outputs. Returns mismatch descriptions in check mode. */
-export function syncOutputs(content, outputs, {check}) {
- const problems = [];
- for (const output of outputs) {
- if (!check) {
- fs.mkdirSync(path.dirname(output), {recursive: true});
- fs.writeFileSync(output, content);
- continue;
- }
- if (!fs.existsSync(output)) {
- problems.push({output, reason: 'is missing'});
- } else if (fs.readFileSync(output, 'utf-8') !== content) {
- problems.push({output, reason: 'differs'});
- }
- }
- return problems;
-}
+const generator = createSelectedPaletteRefGenerator({
+ themeDisplayName: 'Neutral',
+ paletteRefsIdentifier: 'neutralPaletteRefs',
+ themeSourceRel: THEME_SOURCE_REL,
+ fullPaletteRel: FULL_PALETTE_REL,
+ selectedRefsRel: SELECTED_REFS_REL,
+ templateRefsRel: TEMPLATE_REFS_REL,
+ regenerateCommand: 'pnpm generate:neutral-palette-refs',
+});
+
+export const parseFullPalette = generator.parseFullPalette;
+export const discoverSelectedRefs = generator.discoverSelectedRefs;
+export const renderSelectedRefs = generator.renderSelectedRefs;
+export {countSelectedRefs, syncOutputs};
export function generateNeutralPaletteRefs({root = ROOT, check = false} = {}) {
- const themeSource = fs.readFileSync(
- path.join(root, THEME_SOURCE_REL),
- 'utf-8',
- );
- const fullPaletteSource = fs.readFileSync(
- path.join(root, FULL_PALETTE_REL),
- 'utf-8',
- );
- const {content, selected} = renderSelectedRefs(
- themeSource,
- fullPaletteSource,
- );
- const outputs = [SELECTED_REFS_REL, TEMPLATE_REFS_REL].map(relative =>
- path.join(root, relative),
- );
- const problems = syncOutputs(content, outputs, {check});
- return {content, selected, outputs, problems};
+ return generator.generateSelectedPaletteRefs({root, check});
}
function main() {
diff --git a/scripts/generate-selected-palette-refs.mjs b/scripts/generate-selected-palette-refs.mjs
new file mode 100644
index 0000000000..5401e556d3
--- /dev/null
+++ b/scripts/generate-selected-palette-refs.mjs
@@ -0,0 +1,405 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Reusable generator for runtime-sized palette reference modules.
+ * @input A theme source, its committed full palette, and theme-specific paths.
+ * @output Selected palette-reference content plus synchronized package outputs.
+ * @position Shared implementation behind theme-specific palette-ref CLIs.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as ts from 'typescript';
+
+const COPYRIGHT = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n';
+const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
+const HEX = /^#[0-9a-f]{6}$/u;
+
+function assertNoParseDiagnostics(file, label) {
+ const diagnostic = file.parseDiagnostics[0];
+ if (!diagnostic) return;
+ const position = file.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
+ throw new Error(
+ `${label}:${position.line + 1}:${position.character + 1}: ${message}`,
+ );
+}
+
+function unwrap(expression) {
+ let current = expression;
+ while (
+ ts.isAsExpression(current) ||
+ ts.isSatisfiesExpression(current) ||
+ ts.isParenthesizedExpression(current)
+ ) {
+ current = current.expression;
+ }
+ return current;
+}
+
+function propertyName(name) {
+ if (
+ ts.isIdentifier(name) ||
+ ts.isStringLiteral(name) ||
+ ts.isNumericLiteral(name)
+ ) {
+ return name.text;
+ }
+ throw new Error(`Unsupported computed palette key: ${name.getText()}`);
+}
+
+function literalValue(expression) {
+ const value = unwrap(expression);
+ if (ts.isStringLiteral(value)) return value.text;
+ if (!ts.isObjectLiteralExpression(value)) {
+ throw new Error(
+ `Palette values must be object or string literals: ${value.getText()}`,
+ );
+ }
+
+ const result = {};
+ for (const property of value.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(`Unsupported palette member: ${property.getText()}`);
+ }
+ result[propertyName(property.name)] = literalValue(property.initializer);
+ }
+ return result;
+}
+
+function renderedKey(key) {
+ return IDENTIFIER.test(key) ? key : JSON.stringify(key);
+}
+
+/** Count unique family/mode/stop references. */
+export function countSelectedRefs(selected) {
+ let count = 0;
+ for (const modes of selected.values()) {
+ for (const stops of modes.values()) count += stops.size;
+ }
+ return count;
+}
+
+/** Write or compare generated outputs. Returns mismatch descriptions in check mode. */
+export function syncOutputs(content, outputs, {check}) {
+ const problems = [];
+ for (const output of outputs) {
+ if (!check) {
+ fs.mkdirSync(path.dirname(output), {recursive: true});
+ fs.writeFileSync(output, content);
+ continue;
+ }
+ if (!fs.existsSync(output)) {
+ problems.push({output, reason: 'is missing'});
+ } else if (fs.readFileSync(output, 'utf-8') !== content) {
+ problems.push({output, reason: 'differs'});
+ }
+ }
+ return problems;
+}
+
+/**
+ * Bind the selected-reference parser and renderer to one theme's identifier,
+ * source paths, output paths, and regeneration command.
+ */
+export function createSelectedPaletteRefGenerator({
+ themeDisplayName,
+ paletteRefsIdentifier,
+ themeSourceRel,
+ fullPaletteRel,
+ selectedRefsRel,
+ templateRefsRel,
+ regenerateCommand,
+}) {
+ if (!IDENTIFIER.test(paletteRefsIdentifier)) {
+ throw new Error(
+ `Palette reference export must be an identifier: ${paletteRefsIdentifier}`,
+ );
+ }
+
+ /** Parse the `palette` object from its generated TypeScript source. */
+ function parseFullPalette(source) {
+ const file = ts.createSourceFile(
+ fullPaletteRel,
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TS,
+ );
+ assertNoParseDiagnostics(file, fullPaletteRel);
+
+ let palette = null;
+ const visit = node => {
+ if (
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.name.text === 'palette' &&
+ node.initializer
+ ) {
+ palette = literalValue(node.initializer);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+
+ if (!palette || typeof palette !== 'object') {
+ throw new Error(`${fullPaletteRel} exports no literal palette object.`);
+ }
+ return palette;
+ }
+
+ function destructuredAliases(file) {
+ const aliases = new Map();
+ const visit = node => {
+ if (
+ ts.isVariableDeclaration(node) &&
+ ts.isObjectBindingPattern(node.name) &&
+ node.initializer &&
+ ts.isIdentifier(unwrap(node.initializer)) &&
+ unwrap(node.initializer).text === paletteRefsIdentifier
+ ) {
+ for (const element of node.name.elements) {
+ if (!ts.isIdentifier(element.name)) {
+ throw new Error(
+ `${themeDisplayName} palette reference aliases must be identifiers.`,
+ );
+ }
+ const family = element.propertyName
+ ? propertyName(element.propertyName)
+ : element.name.text;
+ aliases.set(element.name.text, family);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return aliases;
+ }
+
+ function paletteAccess(expression, aliases) {
+ if (!ts.isPropertyAccessExpression(expression)) return null;
+ const mode = expression.name.text;
+ if (mode !== 'light' && mode !== 'dark') return null;
+
+ const owner = expression.expression;
+ if (ts.isIdentifier(owner) && aliases.has(owner.text)) {
+ return {family: aliases.get(owner.text), mode};
+ }
+ if (
+ ts.isPropertyAccessExpression(owner) &&
+ ts.isIdentifier(owner.expression) &&
+ owner.expression.text === paletteRefsIdentifier
+ ) {
+ return {family: owner.name.text, mode};
+ }
+ return null;
+ }
+
+ function rootedInPalette(expression, aliases) {
+ const node = unwrap(expression);
+ if (ts.isIdentifier(node)) {
+ return node.text === paletteRefsIdentifier || aliases.has(node.text);
+ }
+ if (
+ ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)
+ ) {
+ return rootedInPalette(node.expression, aliases);
+ }
+ return false;
+ }
+
+ function isNonReferenceIdentifier(node) {
+ if (!ts.isIdentifier(node)) return false;
+ const parent = node.parent;
+ if (!parent) return false;
+ return (
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
+ (ts.isPropertyAssignment(parent) && parent.name === node) ||
+ (ts.isBindingElement(parent) && parent.propertyName === node) ||
+ ((ts.isMethodDeclaration(parent) ||
+ ts.isPropertyDeclaration(parent) ||
+ ts.isPropertySignature(parent) ||
+ ts.isMethodSignature(parent)) &&
+ parent.name === node)
+ );
+ }
+
+ function validatePaletteUses(file, aliases) {
+ const visit = node => {
+ const isPaletteExpression =
+ !isNonReferenceIdentifier(node) &&
+ (ts.isIdentifier(node) ||
+ ts.isPropertyAccessExpression(node) ||
+ ts.isElementAccessExpression(node)) &&
+ rootedInPalette(node, aliases);
+ const parent = node.parent;
+ const parentContinuesAccess =
+ parent != null &&
+ (ts.isPropertyAccessExpression(parent) ||
+ ts.isElementAccessExpression(parent)) &&
+ parent.expression === node;
+
+ if (isPaletteExpression && !parentContinuesAccess) {
+ const isBindingName =
+ ts.isIdentifier(node) &&
+ parent != null &&
+ ts.isBindingElement(parent) &&
+ parent.name === node;
+ const isImportName =
+ ts.isIdentifier(node) &&
+ parent != null &&
+ (ts.isImportSpecifier(parent) ||
+ ts.isImportClause(parent) ||
+ ts.isNamespaceImport(parent));
+ const isRootDestructure =
+ ts.isIdentifier(node) &&
+ node.text === paletteRefsIdentifier &&
+ parent != null &&
+ ts.isVariableDeclaration(parent) &&
+ parent.initializer === node &&
+ ts.isObjectBindingPattern(parent.name);
+ const isCompleteReference =
+ ts.isElementAccessExpression(node) &&
+ paletteAccess(node.expression, aliases) !== null;
+
+ if (
+ !isBindingName &&
+ !isImportName &&
+ !isRootDestructure &&
+ !isCompleteReference
+ ) {
+ throw new Error(
+ `Palette references must be used directly as family.light[25] or family.dark[25]; unsupported alias or escape: ${node.getText(file)}`,
+ );
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ }
+
+ /**
+ * Discover selected palette references in lexical order. Family and mode order
+ * follow first use; stops are de-duplicated and sorted during rendering.
+ */
+ function discoverSelectedRefs(source, fullPalette) {
+ const file = ts.createSourceFile(
+ themeSourceRel,
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TS,
+ );
+ assertNoParseDiagnostics(file, themeSourceRel);
+ const aliases = destructuredAliases(file);
+ validatePaletteUses(file, aliases);
+ const families = new Map();
+
+ const visit = node => {
+ if (ts.isElementAccessExpression(node)) {
+ const access = paletteAccess(node.expression, aliases);
+ if (access) {
+ const argument = node.argumentExpression;
+ if (!argument || !ts.isNumericLiteral(argument)) {
+ throw new Error(
+ `Palette references must use literal numeric stops: ${node.getText(file)}`,
+ );
+ }
+ const stop = Number(argument.text);
+ const value =
+ fullPalette?.[access.family]?.[access.mode]?.[String(stop)];
+ if (typeof value !== 'string' || !HEX.test(value)) {
+ throw new Error(
+ `Palette reference ${access.family}.${access.mode}[${stop}] is missing or invalid in the committed full palette.`,
+ );
+ }
+
+ if (!families.has(access.family)) {
+ families.set(access.family, new Map());
+ }
+ const modes = families.get(access.family);
+ if (!modes.has(access.mode)) modes.set(access.mode, new Set());
+ modes.get(access.mode).add(stop);
+ } else if (rootedInPalette(node.expression, aliases)) {
+ throw new Error(
+ `Palette references must use family.light[25] or family.dark[25] with literal keys: ${node.getText(file)}`,
+ );
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+
+ if (families.size === 0) {
+ throw new Error(
+ `${themeSourceRel} contains no selected palette references.`,
+ );
+ }
+ return families;
+ }
+
+ /** Render the complete selected-reference artifact. */
+ function renderSelectedRefs(themeSource, fullPaletteSource) {
+ const palette = parseFullPalette(fullPaletteSource);
+ const selected = discoverSelectedRefs(themeSource, palette);
+ const lines = [
+ COPYRIGHT.trimEnd(),
+ '',
+ `// Generated from the committed full palette for the stops used by ${themeDisplayName}'s`,
+ `// theme source. Regenerate with \`${regenerateCommand}\`.`,
+ '// Keep the complete palette available for authoring and audits without',
+ '// making consumers pay for unused palette stops.',
+ '// prettier-ignore',
+ `export const ${paletteRefsIdentifier} = {`,
+ ];
+
+ for (const [family, modes] of selected) {
+ lines.push(` ${renderedKey(family)}: {`);
+ for (const [mode, stops] of modes) {
+ const entries = [...stops]
+ .sort((a, b) => a - b)
+ .map(stop => `${stop}: '${palette[family][mode][String(stop)]}'`)
+ .join(', ');
+ lines.push(` ${mode}: {${entries}},`);
+ }
+ lines.push(' },');
+ }
+
+ lines.push(
+ '} as const;',
+ '',
+ `export default ${paletteRefsIdentifier};`,
+ '',
+ );
+ return {content: lines.join('\n'), selected};
+ }
+
+ /** Generate or check this theme's package and CLI template outputs. */
+ function generateSelectedPaletteRefs({root, check = false}) {
+ const themeSource = fs.readFileSync(
+ path.join(root, themeSourceRel),
+ 'utf-8',
+ );
+ const fullPaletteSource = fs.readFileSync(
+ path.join(root, fullPaletteRel),
+ 'utf-8',
+ );
+ const {content, selected} = renderSelectedRefs(
+ themeSource,
+ fullPaletteSource,
+ );
+ const outputs = [selectedRefsRel, templateRefsRel].map(relative =>
+ path.join(root, relative),
+ );
+ const problems = syncOutputs(content, outputs, {check});
+ return {content, selected, outputs, problems};
+ }
+
+ return {
+ parseFullPalette,
+ discoverSelectedRefs,
+ renderSelectedRefs,
+ generateSelectedPaletteRefs,
+ };
+}
diff --git a/scripts/palette-receipt-test-utils.mjs b/scripts/palette-receipt-test-utils.mjs
new file mode 100644
index 0000000000..e2217f6db1
--- /dev/null
+++ b/scripts/palette-receipt-test-utils.mjs
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Cross-platform assertions for generated palette receipts.
+ * @input A freshly generated receipt and its committed counterpart.
+ * @output Exact validation outside diagnostics and tolerant numeric diagnostics.
+ * @position Shared test support for reproducible theme-palette generation.
+ */
+
+import assert from 'node:assert/strict';
+
+function assertDiagnosticsClose(actual, expected, path, tolerance) {
+ if (typeof expected === 'number') {
+ assert.equal(typeof actual, 'number', `${path} must be numeric`);
+ const scale = Math.max(1, Math.abs(expected), Math.abs(actual));
+ assert.ok(
+ Math.abs(actual - expected) <= tolerance * scale,
+ `${path}: expected ${expected} ± ${tolerance * scale}, received ${actual}`,
+ );
+ return;
+ }
+
+ if (Array.isArray(expected)) {
+ assert.ok(Array.isArray(actual), `${path} must be an array`);
+ assert.equal(actual.length, expected.length, `${path} length`);
+ for (let index = 0; index < expected.length; index += 1) {
+ assertDiagnosticsClose(
+ actual[index],
+ expected[index],
+ `${path}[${index}]`,
+ tolerance,
+ );
+ }
+ return;
+ }
+
+ if (expected && typeof expected === 'object') {
+ assert.ok(
+ actual && typeof actual === 'object',
+ `${path} must be an object`,
+ );
+ assert.deepEqual(
+ Object.keys(actual).sort(),
+ Object.keys(expected).sort(),
+ `${path} keys`,
+ );
+ for (const key of Object.keys(expected)) {
+ assertDiagnosticsClose(
+ actual[key],
+ expected[key],
+ `${path}.${key}`,
+ tolerance,
+ );
+ }
+ return;
+ }
+
+ assert.deepEqual(actual, expected, path);
+}
+
+/**
+ * Compare stable receipt fields exactly while allowing insignificant differences
+ * in floating-point diagnostics across Node architectures.
+ */
+export function assertPaletteReceiptsMatch(
+ actual,
+ expected,
+ {diagnosticTolerance = 1e-12} = {},
+) {
+ const {diagnostics: actualDiagnostics, ...actualStable} = actual;
+ const {diagnostics: expectedDiagnostics, ...expectedStable} = expected;
+
+ assert.deepEqual(actualStable, expectedStable);
+ assertDiagnosticsClose(
+ actualDiagnostics,
+ expectedDiagnostics,
+ 'diagnostics',
+ diagnosticTolerance,
+ );
+}
diff --git a/scripts/palette-receipt-test-utils.test.mjs b/scripts/palette-receipt-test-utils.test.mjs
new file mode 100644
index 0000000000..8818fc44ea
--- /dev/null
+++ b/scripts/palette-receipt-test-utils.test.mjs
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for cross-platform palette-receipt comparison.
+ * @input Receipts with exact, near-equal, and materially different diagnostics.
+ * @output Proof that only insignificant diagnostic float drift is tolerated.
+ * @position Regression coverage for palette-receipt-test-utils.mjs.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {assertPaletteReceiptsMatch} from './palette-receipt-test-utils.mjs';
+
+const receipt = {
+ request: {recipe: 'astryx-oklch-v1'},
+ paletteSha256: 'palette',
+ requestSha256: 'request',
+ diagnostics: {
+ families: {
+ blue: {
+ light: {
+ monotonic: true,
+ maximumHueDrift: 12.345678901234,
+ anchors: [{stop: 50, deltaE: 0.000000000001}],
+ },
+ },
+ },
+ },
+};
+
+describe('palette receipt comparison', () => {
+ it('accepts insignificant floating-point drift in diagnostics', () => {
+ const generated = structuredClone(receipt);
+ generated.diagnostics.families.blue.light.maximumHueDrift += 1e-13;
+ generated.diagnostics.families.blue.light.anchors[0].deltaE += 1e-15;
+
+ expect(() => assertPaletteReceiptsMatch(generated, receipt)).not.toThrow();
+ });
+
+ it('rejects stable-field differences', () => {
+ const generated = structuredClone(receipt);
+ generated.paletteSha256 = 'different';
+
+ expect(() => assertPaletteReceiptsMatch(generated, receipt)).toThrow();
+ });
+
+ it('rejects material diagnostic differences', () => {
+ const generated = structuredClone(receipt);
+ generated.diagnostics.families.blue.light.maximumHueDrift += 0.01;
+
+ expect(() => assertPaletteReceiptsMatch(generated, receipt)).toThrow();
+ });
+});