Skip to content

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

TypeScript

feat(cli): generate reviewable tonal palettes (#5992)

rubyycheungfda3f56a0297
diff --git a/.changeset/cli-palette-generation.md b/.changeset/cli-palette-generation.md
new file mode 100644
index 0000000000..7e63c51bf4
--- /dev/null
+++ b/.changeset/cli-palette-generation.md
@@ -0,0 +1,10 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/theme-neutral': patch
+---
+
+[feat] Add an authoring-time OKLCH palette generator with a pure API, terminal and HTML previews, typed palette output, custom stops, deterministic receipts, and overwrite protection.
+
+[feat] Expose exact solid black and white values as `neutralPalettes.black` and `neutralPalettes.white` for use in semantic theme tokens.
+
+@rubyycheung
diff --git a/docs/specs/AST-008/spec.md b/docs/specs/AST-008/spec.md
index 8948b43d07..fb3af73cb7 100644
--- a/docs/specs/AST-008/spec.md
+++ b/docs/specs/AST-008/spec.md
@@ -3,12 +3,12 @@ schema_version: 1
template_version: 1
kind: system-spec
id: spec:AST-008
-authority: draft
+authority: current
archive_reason: null
superseded_by: null
-approved_by: null
-approved_at: null
-phase: proposed
+approved_by: cixzhang
+approved_at: 2026-09-08
+phase: accepted
owners: [cixzhang, rubyycheung, imdreamrunner]
affects_architecture:
[architecture:theme-authoring-contract, architecture:theme-compilation]
@@ -82,8 +82,11 @@ outside Core theme normalization and runtime behavior.
output-affecting parameter. Astryx tooling SHOULD default family ramps to the
21-stop `0, 5, …, 100` layout, while accepting any non-empty author-defined
numeric stop list. Compact and specialized layouts are valid author choices,
- not exceptions. Stops 0 and 100 resolve to exact black and white in generated
- families. Authors MAY omit those repeated endpoints with a custom stop list.
+ not exceptions. Every candidate exposes exact standalone black and white
+ values for direct theme authoring. Stops 0 and 100 repeat those values in
+ generated families. Authors MAY omit the repeated endpoints with a custom
+ stop list without losing the standalone values. The family identifiers
+ `black` and `white` are reserved for those standalone values.
- **FR2a — Custom stop syntax is exact.** Every stop MUST be a finite JSON number
from 0 through 100 inclusive. Stops MUST be unique and strictly increasing.
Integer and decimal stops are valid; equivalent numeric spellings such as `5`
@@ -127,11 +130,9 @@ outside Core theme normalization and runtime behavior.
control. Edited accepted data MUST NOT claim exact regeneration, and ordinary
theme builds MUST NOT rerun the generator.
- **FR8 — The selected recipe preserves complete-family evidence.** The first
- production recipe MUST preserve the intended results of
- `apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.ts` at
- repository commit `d77fd8b43bc3f40dd80e605248fd87c20ccdc03c` rather than
- reopening the OKLCH-versus-HCT visual decision.
- Before release, its version-pinned evidence MUST cover complete family sets,
+ production recipe MUST be pinned by its normative algorithm and canonical
+ fixtures rather than another implementation. Before release, its
+ version-pinned evidence MUST cover complete family sets,
rendered light/dark contexts, hue continuity, luminance and adjacent-stop
distinction, gamut, family balance, CVD simulations, reproducibility, and
performance. Fixtures cover blue-to-purple, yellow-to-brown, disproportionate
@@ -181,10 +182,8 @@ outside Core theme normalization and runtime behavior.
## Implementation contract
-1. The implementation PR pins the current Sandbox OKLCH behavior as
- `astryx-oklch-v1`, copies its constants and transformations into one owned
- engine, and adds exact regression vectors. The Sandbox remains a prototype,
- not the production import path.
+1. The implementation PR defines `astryx-oklch-v1` in one owned production
+ engine and pins its constants, transformations, and exact regression vectors.
2. The pure authoring API and CLI adapter use one deterministic engine and agree
on recipe semantics. The CLI follows `architecture:cli-surface` for its
command, response, error, documentation, support, and write contract.
@@ -200,7 +199,7 @@ outside Core theme normalization and runtime behavior.
### `astryx-oklch-v1` normative recipe
-The first production recipe is defined here rather than by mutable Sandbox code:
+The first production recipe is defined here and pinned by canonical fixtures:
- Normalize supported seed and anchor colors to lowercase six-digit sRGB hex.
- Convert sRGB through the standard D65 OKLab matrices, then express hue and
@@ -238,6 +237,8 @@ The first production recipe is defined here rather than by mutable Sandbox code:
- Convert final colors to sRGB by rounding each clamped channel to the nearest
8-bit integer. Emit lowercase `#rrggbb`. Canonical JSON uses two-space
indentation, insertion-ordered families and stops, and one trailing newline.
+ Candidates expose the requested stop layout as an ordered `stops` array;
+ family ramp objects are lookup maps and do not define iteration order.
- Invalid requests fail before producing a candidate. Family-local anchor
conflicts report the family and produce no adoptable output.
@@ -245,10 +246,10 @@ The following canonical candidate fixtures use SHA-256 over UTF-8 canonical JSON
| Fixture | Request summary | Candidate bytes | SHA-256 |
| ---------------------- | ---------------------------------------------------------------------------------------------- | --------------: | ------------------------------------------------------------------ |
-| `default-three-family` | Neutral `#777777`, blue `#0074e2`, orange `#d57113`; both modes; vibrancy 50; 21 default stops | 3527 | `78ca5bd2afe44d448dc7fd2889196c5a562a9d1f1ff8efcccc67aa1d8a94b76c` |
-| `exact-anchor` | Blue `#0074e2`; light only; stops 20, 50, 80; exact stop-50 anchor `#1682d5` | 242 | `e3dbd30b3eb1e4c2a0350e1321ef44bf16c3ae48ac46ada0dad04368cdd6e4a1` |
-| `single-custom-stop` | Red `#d62830`; dark only; stop 40 | 189 | `d54fe4d202d7bd49f8a286e97eadf9786fe71e21f15e0058975877581b7e025b` |
-| `high-tone-balance` | Green `#358a3a`, teal `#0c7365`, cyan `#0c6f82`; both modes; stops 60, 80, 95 | 825 | `991080568a4e1c1a4b1b23e1d9908fcdd688607aac6be4c55cd216b74ebe7c3d` |
+| `default-three-family` | Neutral `#777777`, blue `#0074e2`, orange `#d57113`; both modes; vibrancy 50; 21 default stops | 3755 | `11c40191d508274d89d631bb4e1cb662f70ff0dce6c0dec101c317f9f69d3e25` |
+| `exact-anchor` | Blue `#0074e2`; light only; stops 20, 50, 80; exact stop-50 anchor `#1682d5` | 327 | `c42929be3c4b5cb857cada078f62bb5a2242c1a22cfa4ae7546a18592540f7f3` |
+| `single-custom-stop` | Red `#d62830`; dark only; stop 40 | 258 | `88d3d69865c74c7fb14347b9967575285a7d44ab893087a08bc842bb66b29bbb` |
+| `high-tone-balance` | Green `#358a3a`, teal `#0c7365`, cyan `#0c6f82`; both modes; stops 60, 80, 95 | 910 | `873821574fdbe3357304dbc06986bd2e5ec88af80d0f36305626fd826c3cf07b` |
Exact fixture equality is the release gate for recipe compatibility. Monotonicity,
adjacent-stop distance, hue drift, family distinction, gamut events, and CVD
@@ -312,10 +313,15 @@ Both use the same `astryx-oklch-v1` engine. Neither enters Core or `defineTheme(
The first production generator defaults each family to the familiar 21-position
`0, 5, …, 100` layout and accepts any explicit non-empty numeric stop list.
-Stops 0 and 100 repeat exact black and white in each generated family so authors
-can retain a complete coordinate range or remove the endpoints explicitly. The
-generated candidate becomes author-owned after review and acceptance. Generator
-defaults therefore do not become palette-validity rules.
+Every candidate exposes exact black and white as standalone authoring values.
+Stops 0 and 100 repeat them in each generated family so authors can retain a
+complete coordinate range or remove the repeated endpoints explicitly without
+losing access to either solid. Generated TypeScript names the values `black`
+and `white`; theme-owned palette wrappers may expose them alongside families,
+for example as `neutralPalettes.black` and `neutralPalettes.white`. Those names
+are reserved from family identifiers. The generated candidate becomes
+author-owned after review and acceptance. Generator defaults therefore do not
+become palette-validity rules.
Generated palettes are reviewable starting points. Authors may adjust
family-level inputs and regenerate until the palette matches their intended
diff --git a/internal/vibe-tests/palette-authoring-test/README.md b/internal/vibe-tests/palette-authoring-test/README.md
new file mode 100644
index 0000000000..c39063da6f
--- /dev/null
+++ b/internal/vibe-tests/palette-authoring-test/README.md
@@ -0,0 +1,21 @@
+# Palette authoring agent test
+
+This focused prompt set checks whether an agent translates ordinary author
+language into the intended palette-generation controls.
+
+Run each entry in `prompts.json` with a fresh agent that can discover the
+shipped CLI docs. Keep `expected-decisions.json` hidden until scoring so the
+agent cannot see the answer key.
+
+Evaluate whether the response:
+
+- selects `exact`, `bounded`, or `flexible` from the author's stated intent;
+- changes vibrancy only when requested;
+- preserves explicit custom and decimal stops;
+- includes default black and white endpoints unless the author removes them;
+- omits an accent when none is requested;
+- asks whether an ambiguous accent is one theme value or a generated family;
+- generates an `accent` family only when a ramp is explicitly requested.
+
+Passing requires the expected decision without inventing additional palette or
+theme changes.
diff --git a/internal/vibe-tests/palette-authoring-test/expected-decisions.json b/internal/vibe-tests/palette-authoring-test/expected-decisions.json
new file mode 100644
index 0000000000..f535544053
--- /dev/null
+++ b/internal/vibe-tests/palette-authoring-test/expected-decisions.json
@@ -0,0 +1,19 @@
+{
+ "palette-anchor-exact": {"anchorPolicy": "exact"},
+ "palette-anchor-bounded": {"anchorPolicy": "bounded", "maxDeltaE": 2},
+ "palette-anchor-flexible": {"anchorPolicy": "flexible"},
+ "palette-vibrancy-muted": {"vibrancyDirection": "decrease"},
+ "palette-accent-absent": {"accent": "omit"},
+ "palette-accent-ambiguous": {
+ "action": "clarify",
+ "question": "Should this remain one theme accent color, or become a light and dark accent ramp?"
+ },
+ "palette-accent-ramp": {
+ "accent": "family",
+ "familyId": "accent",
+ "modeStrategy": "light-and-dark"
+ },
+ "palette-custom-stop": {"stopsInclude": 12.5},
+ "palette-custom-layout": {"customLayout": true, "stopCount": 5},
+ "palette-omit-endpoints": {"stopsOmit": [0, 100]}
+}
diff --git a/internal/vibe-tests/palette-authoring-test/prompts.json b/internal/vibe-tests/palette-authoring-test/prompts.json
new file mode 100644
index 0000000000..ef1ca60610
--- /dev/null
+++ b/internal/vibe-tests/palette-authoring-test/prompts.json
@@ -0,0 +1,46 @@
+{
+ "name": "palette-authoring",
+ "description": "Focused agent scenarios for choosing palette generator controls without inventing author intent.",
+ "prompts": [
+ {
+ "id": "palette-anchor-exact",
+ "prompt": "Create a palette from our brand blue #1682d5. That exact blue must not change."
+ },
+ {
+ "id": "palette-anchor-bounded",
+ "prompt": "Generate a blue palette, but keep #1682d5 within a perceptual distance of 2."
+ },
+ {
+ "id": "palette-anchor-flexible",
+ "prompt": "Use #ff4db8 as inspiration for the pink family, but it can move if that makes the ramp more balanced."
+ },
+ {
+ "id": "palette-vibrancy-muted",
+ "prompt": "Keep the same palette families but make the overall result more muted."
+ },
+ {
+ "id": "palette-accent-absent",
+ "prompt": "Create blue, green, and orange palette families."
+ },
+ {
+ "id": "palette-accent-ambiguous",
+ "prompt": "Use #ff4db8 as our accent."
+ },
+ {
+ "id": "palette-accent-ramp",
+ "prompt": "Generate a full light and dark accent ramp from #ff4db8."
+ },
+ {
+ "id": "palette-custom-stop",
+ "prompt": "Add an illustration color at stop 12.5 to the blue family."
+ },
+ {
+ "id": "palette-custom-layout",
+ "prompt": "Create a specialized five-stop palette for data visualization."
+ },
+ {
+ "id": "palette-omit-endpoints",
+ "prompt": "Generate the standard palette, but leave out the repeated black and white endpoints."
+ }
+ ]
+}
diff --git a/internal/vibe-tests/palette-authoring-test/prompts.test.mjs b/internal/vibe-tests/palette-authoring-test/prompts.test.mjs
new file mode 100644
index 0000000000..b50ccb5400
--- /dev/null
+++ b/internal/vibe-tests/palette-authoring-test/prompts.test.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+import {describe, expect, it} from 'vitest';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+function readJson(file) {
+ return JSON.parse(fs.readFileSync(path.join(here, file), 'utf8'));
+}
+
+describe('palette authoring agent fixtures', () => {
+ it('keeps the answer key out of the prompts shown to agents', () => {
+ const {prompts} = readJson('prompts.json');
+ const answers = readJson('expected-decisions.json');
+
+ expect(prompts.every(prompt => prompt.expectedDecision == null)).toBe(true);
+ expect(prompts.map(prompt => prompt.id).sort()).toEqual(
+ Object.keys(answers).sort(),
+ );
+ });
+});
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 3dbb73ef3f..1c0c3f5a76 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -175,6 +175,7 @@ if (isError(result)) {
| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |
+| `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |
| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
@@ -424,6 +425,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |
| `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, the component count, and one entry 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. |
| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index cf01082983..5f9626630a 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -25,7 +25,7 @@ export {docs} from './docs/docs.mjs';
export {blog} from './blog/blog.mjs';
export {discover} from './discover/discover.mjs';
export {template} from './template/template.mjs';
-export {themeBuild, themeAdd, themeList, themeTargets, listThemes} from './theme/theme.mjs';
+export {themeBuild, themeAdd, themeList, themeTargets, themePaletteGenerate, generateTonalPalette, listThemes} from './theme/theme.mjs';
export {hook} from './hook/hook.mjs';
export {search} from './search/search.mjs';
export {build} from './build/build.mjs';
diff --git a/packages/cli/api/theme/generateTonalPalette.doc.mjs b/packages/cli/api/theme/generateTonalPalette.doc.mjs
new file mode 100644
index 0000000000..b15bd6d708
--- /dev/null
+++ b/packages/cli/api/theme/generateTonalPalette.doc.mjs
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'generateTonalPalette',
+ displayName: 'generateTonalPalette()',
+ summary: 'Generate candidate tonal palette data without filesystem effects.',
+ description:
+ 'Runs the versioned astryx-oklch-v1 authoring recipe. The returned candidate ' +
+ 'contains exact hex values for review; it does not modify a theme, write files, ' +
+ 'perform semantic mapping, or make accessibility claims. Stop numbers remain ' +
+ 'stable across layouts, and requested decimal stops are emitted explicitly. ' +
+ 'Anchor policies are intentional: exact preserves the chosen color at its stop; ' +
+ 'bounded permits movement within maxDeltaE; flexible treats it as guidance. ' +
+ 'An anchor needs a mode and stop. Stops apply to every family in one request. ' +
+ 'The candidate always exposes standalone black and white values for direct theme authoring. ' +
+ 'Generated TypeScript exports them as `black` and `white`, so they can be assigned directly ' +
+ 'to semantic theme tokens. Those names are reserved and cannot be used as tonal family IDs. ' +
+ 'The default 0–100 layout also repeats them as family endpoints; a custom stop list can omit those repeated endpoints.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'generateTonalPalette(input: TonalPaletteGenerationInput): TonalPaletteCandidate',
+ keywords: ['palette', 'generate', 'OKLCH', 'authoring', 'candidate'],
+ params: [
+ {
+ name: 'input',
+ type: 'TonalPaletteGenerationInput',
+ description:
+ 'Families and seeds plus optional modes, shared stops, anchors, vibrancy from 0 to 100 (default 50), and neutral profile. Only generate an accent family when one is explicitly requested; clarify whether an ambiguous accent means one theme value or a tonal family.',
+ required: true,
+ },
+ ],
+ returns: [
+ {
+ type: 'TonalPaletteCandidate',
+ description:
+ 'Deterministic candidate data for author review, including a stops array that defines ramp iteration order and standalone black and white values outside the tonal families.',
+ },
+ ],
+ throws: [
+ {
+ code: 'Error',
+ when: 'the request, family, seed, stop layout, mode, or anchor is invalid',
+ },
+ ],
+ examples: [
+ {
+ label: 'Generate one family',
+ code: "generateTonalPalette({families: [{id: 'blue', seed: '#0074e2'}]});",
+ },
+ {
+ label: 'Preserve a required brand color',
+ code: "generateTonalPalette({stops: [50], families: [{id: 'brand', seed: '#0074e2', anchors: [{mode: 'light', stop: 50, color: '#1682d5', policy: 'exact'}]}]});",
+ },
+ {
+ label: 'Allow limited anchor movement',
+ code: "generateTonalPalette({stops: [50], families: [{id: 'brand', seed: '#0074e2', anchors: [{mode: 'light', stop: 50, color: '#1682d5', policy: 'bounded', maxDeltaE: 2}]}]});",
+ },
+ {
+ label: 'Use an anchor as guidance',
+ code: "generateTonalPalette({stops: [50], families: [{id: 'pink', seed: '#ff4db8', anchors: [{mode: 'light', stop: 50, color: '#ff4db8', policy: 'flexible'}]}]});",
+ },
+ {
+ label: 'Generate an optional accent family',
+ code: "generateTonalPalette({families: [{id: 'accent', seed: '#ff4db8'}]});",
+ },
+ {
+ label: 'Generate an explicit intermediate stop',
+ code: "generateTonalPalette({stops: [12.5, 50], families: [{id: 'blue', seed: '#0074e2'}]});",
+ },
+ ],
+ command: 'theme palette generate',
+ related: ['themePaletteGenerate'],
+};
diff --git a/packages/cli/api/theme/palette/generate/color.mjs b/packages/cli/api/theme/palette/generate/color.mjs
new file mode 100644
index 0000000000..f91a49c884
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/color.mjs
@@ -0,0 +1,188 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @typedef {[number, number, number]} ColorTriple */
+
+/** @param {number} channel @returns {number} */
+function srgbToLinear(channel) {
+ const value = channel / 255;
+ return value <= 0.04045
+ ? value / 12.92
+ : Math.pow((value + 0.055) / 1.055, 2.4);
+}
+
+/** @param {number} channel @returns {number} */
+function linearToSrgb(channel) {
+ const value =
+ channel <= 0.0031308
+ ? channel * 12.92
+ : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055;
+ return Math.round(Math.min(255, Math.max(0, value * 255)));
+}
+
+/** @param {string} hex @returns {ColorTriple} */
+function hexToRgb(hex) {
+ const value = hex.replace('#', '');
+ const full =
+ value.length === 3
+ ? value[0] + value[0] + value[1] + value[1] + value[2] + value[2]
+ : value.slice(0, 6);
+ const numeric = Number.parseInt(full, 16);
+ return [(numeric >> 16) & 0xff, (numeric >> 8) & 0xff, numeric & 0xff];
+}
+
+/** @param {number} red @param {number} green @param {number} blue @returns {string} */
+function rgbToHex(red, green, blue) {
+ return (
+ '#' +
+ [red, green, blue]
+ .map(channel =>
+ Math.round(Math.max(0, Math.min(255, channel)))
+ .toString(16)
+ .padStart(2, '0'),
+ )
+ .join('')
+ );
+}
+
+/** @param {number} red @param {number} green @param {number} blue @returns {ColorTriple} */
+function linearRgbToOklab(red, green, blue) {
+ const lRoot = Math.cbrt(
+ 0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue,
+ );
+ const mRoot = Math.cbrt(
+ 0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue,
+ );
+ const sRoot = Math.cbrt(
+ 0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue,
+ );
+ return [
+ 0.2104542553 * lRoot + 0.793617785 * mRoot - 0.0040720468 * sRoot,
+ 1.9779984951 * lRoot - 2.428592205 * mRoot + 0.4505937099 * sRoot,
+ 0.0259040371 * lRoot + 0.7827717662 * mRoot - 0.808675766 * sRoot,
+ ];
+}
+
+/** @param {number} lightness @param {number} a @param {number} b @returns {ColorTriple} */
+function oklabToLinearRgb(lightness, a, b) {
+ const lRoot = lightness + 0.3963377774 * a + 0.2158037573 * b;
+ const mRoot = lightness - 0.1055613458 * a - 0.0638541728 * b;
+ const sRoot = lightness - 0.0894841775 * a - 1.291485548 * b;
+ const l = lRoot ** 3;
+ const m = mRoot ** 3;
+ const s = sRoot ** 3;
+ return [
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
+ ];
+}
+
+/** @param {unknown} input @returns {string} */
+export function normalizeColor(input) {
+ const value = String(input).trim();
+ if (/^#?[0-9a-f]{3}$/i.test(value)) {
+ const hex = value.replace('#', '').toLowerCase();
+ return `#${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
+ }
+ if (/^#?[0-9a-f]{6}$/i.test(value)) {
+ return `#${value.replace('#', '').toLowerCase()}`;
+ }
+ throw new Error(`Invalid color: ${input}`);
+}
+
+/** @param {string} hex @returns {{L: number, C: number, H: number}} */
+export function hexToOklch(hex) {
+ const [red, green, blue] = hexToRgb(normalizeColor(hex));
+ const [lightness, a, b] = linearRgbToOklab(
+ srgbToLinear(red),
+ srgbToLinear(green),
+ srgbToLinear(blue),
+ );
+ let hue = (Math.atan2(b, a) * 180) / Math.PI;
+ if (hue < 0) hue += 360;
+ return {L: lightness, C: Math.sqrt(a * a + b * b), H: hue};
+}
+
+/** @param {number} lightness @param {number} chroma @param {number} hue @returns {boolean} */
+function oklchInGamut(lightness, chroma, hue) {
+ const radians = (hue * Math.PI) / 180;
+ const [red, green, blue] = oklabToLinearRgb(
+ lightness,
+ chroma * Math.cos(radians),
+ chroma * Math.sin(radians),
+ );
+ return (
+ red >= -0.001 &&
+ red <= 1.001 &&
+ green >= -0.001 &&
+ green <= 1.001 &&
+ blue >= -0.001 &&
+ blue <= 1.001
+ );
+}
+
+/** @param {number} lightness @param {number} chroma @param {number} hue @returns {string} */
+function oklchToHex(lightness, chroma, hue) {
+ if (lightness <= 0) return '#000000';
+ if (lightness >= 1) return '#ffffff';
+ const radians = (hue * Math.PI) / 180;
+ const [red, green, blue] = oklabToLinearRgb(
+ lightness,
+ chroma * Math.cos(radians),
+ chroma * Math.sin(radians),
+ );
+ return rgbToHex(
+ linearToSrgb(Math.max(0, red)),
+ linearToSrgb(Math.max(0, green)),
+ linearToSrgb(Math.max(0, blue)),
+ );
+}
+
+/** @param {number} hue @param {number} lightness @returns {number} */
+export function maxOklchChroma(hue, lightness) {
+ let low = 0;
+ let high = 0.4;
+ for (let index = 0; index < 20; index++) {
+ const middle = (low + high) / 2;
+ if (oklchInGamut(lightness, middle, hue)) low = middle;
+ else high = middle;
+ }
+ return low;
+}
+
+/** @param {number} lightness @param {number} chroma @param {number} hue @returns {string} */
+export function oklchClampedHex(lightness, chroma, hue) {
+ if (oklchInGamut(lightness, chroma, hue)) {
+ return oklchToHex(lightness, chroma, hue);
+ }
+ return oklchToHex(lightness, maxOklchChroma(hue, lightness), hue);
+}
+
+/** @param {number} tone @returns {number} */
+export function toneToOklabLightness(tone) {
+ if (tone <= 0) return 0;
+ if (tone >= 100) return 1;
+ const relative = tone > 8 ? Math.pow((tone + 16) / 116, 3) : tone / 903.3;
+ return Math.cbrt(relative);
+}
+
+/** @param {string} hex @returns {number} */
+export function luminance(hex) {
+ const [red, green, blue] = hexToRgb(hex).map(srgbToLinear);
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
+}
+
+/** @param {string} hex @returns {ColorTriple} */
+export function oklabCoordinates(hex) {
+ const value = hexToOklch(hex);
+ const radians = (value.H * Math.PI) / 180;
+ return [value.L, value.C * Math.cos(radians), value.C * Math.sin(radians)];
+}
+
+/** @param {ColorTriple} coordinates @returns {string} */
+export function oklabCoordinatesToHex(coordinates) {
+ const [lightness, a, b] = coordinates;
+ const chroma = Math.sqrt(a * a + b * b);
+ const hue = ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360;
+ return oklchClampedHex(Math.min(1, Math.max(0, lightness)), chroma, hue);
+}
diff --git a/packages/cli/api/theme/palette/generate/generate.mjs b/packages/cli/api/theme/palette/generate/generate.mjs
new file mode 100644
index 0000000000..80e2a1110e
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/generate.mjs
@@ -0,0 +1,429 @@
+// 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 {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
+import {AstryxError} from '../../../error.mjs';
+import {
+ generatePaletteSet,
+ PALETTE_BLACK,
+ PALETTE_WHITE,
+ serializeGenerationResult,
+} from './generator.mjs';
+import {PALETTE_PREVIEW_VERSION, renderPalettePreview} from './preview.mjs';
+
+/** @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 */
+
+/** @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) {
+ 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": ${JSON.stringify(candidate.stops)},\n "palette": ${serializePalette(candidate.palette, 2)}\n}\n`;
+}
+
+/** @param {TonalPaletteCandidate} candidate @param {string} outputPath */
+function serializeCandidate(candidate, outputPath) {
+ if (outputPath.endsWith('.ts')) return serializePaletteModule(candidate);
+ if (outputPath.endsWith('.json')) return serializePaletteCandidate(candidate);
+ throw new AstryxError(
+ 'Palette output must end in .ts or .json.',
+ undefined,
+ ERROR_CODES.ERR_PALETTE_GENERATION,
+ );
+}
+
+/** @param {PaletteGenerationResult} result @param {string} candidateText @param {string | null} [previewText] */
+function receiptFor(result, candidateText, previewText = null) {
+ return {
+ schemaVersion: 1,
+ recipe: result.recipe,
+ candidateSha256: createHash('sha256').update(candidateText).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 error;
+ }
+}
+
+/** @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.
+ fs.linkSync(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 candidateText = serializePaletteCandidate(candidate);
+ const previewText = options.preview ? renderPalettePreview(candidate) : null;
+ let receipt = receiptFor(result, candidateText, 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);
+ candidateText = serializeCandidate(candidate, resolvedOutput);
+ receipt = receiptFor(result, candidateText, previewText);
+ const receiptText = serializeGenerationResult(receipt);
+ output = path.relative(cwd, resolvedOutput);
+ receiptOutput = path.relative(cwd, resolvedReceipt);
+ files.push(
+ {path: resolvedOutput, next: candidateText},
+ {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,
+ },
+ };
+}
diff --git a/packages/cli/api/theme/palette/generate/generate.test.mjs b/packages/cli/api/theme/palette/generate/generate.test.mjs
new file mode 100644
index 0000000000..b5fbecfb1f
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/generate.test.mjs
@@ -0,0 +1,270 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {afterEach, describe, expect, it} from 'vitest';
+import {themePaletteGenerate} from './generate.mjs';
+
+const temporaryDirectories = [];
+
+function fixture() {
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-palette-'));
+ temporaryDirectories.push(cwd);
+ fs.writeFileSync(
+ path.join(cwd, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'light-only',
+ stops: [20, 50, 80],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+ return cwd;
+}
+
+afterEach(() => {
+ for (const directory of temporaryDirectories.splice(0)) {
+ fs.rmSync(directory, {recursive: true, force: true});
+ }
+});
+
+describe('themePaletteGenerate', () => {
+ it('returns a candidate without writing when no output is requested', () => {
+ const cwd = fixture();
+ const result = themePaletteGenerate('palette.config.json', {}, {cwd});
+
+ expect(result.type).toBe('theme.palette.generate');
+ expect(result.data).toMatchObject({
+ recipe: 'astryx-oklch-v1',
+ status: 'candidate',
+ familyCount: 1,
+ stopCount: 3,
+ modes: ['light'],
+ output: null,
+ written: false,
+ });
+ expect(result.data.candidate.palette.blue.light).toEqual({
+ 20: expect.stringMatching(/^#[0-9a-f]{6}$/),
+ 50: expect.stringMatching(/^#[0-9a-f]{6}$/),
+ 80: expect.stringMatching(/^#[0-9a-f]{6}$/),
+ });
+ expect(result.data.candidate).toMatchObject({
+ black: '#000000',
+ white: '#ffffff',
+ stops: [20, 50, 80],
+ });
+ });
+
+ it('writes a candidate and detached reproducibility receipt together', () => {
+ const cwd = fixture();
+ const result = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts'},
+ {cwd},
+ );
+
+ expect(result.data).toMatchObject({
+ output: 'ocean.palette.ts',
+ receipt: 'ocean.palette.receipt.json',
+ written: true,
+ reason: null,
+ });
+ const candidate = fs.readFileSync(
+ path.join(cwd, 'ocean.palette.ts'),
+ 'utf-8',
+ );
+ const receipt = JSON.parse(
+ 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(candidate).toContain('// prettier-ignore');
+ expect(candidate).toContain("export const black = '#000000' as const;");
+ expect(candidate).toContain("export const white = '#ffffff' as const;");
+ expect(candidate).toContain('export const palette =');
+ expect(candidate).not.toContain('generateTonalPalette');
+ });
+
+ it('supports JSON when an interoperable artifact is requested', () => {
+ const cwd = fixture();
+ const result = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.json'},
+ {cwd},
+ );
+
+ const written = JSON.parse(
+ fs.readFileSync(path.join(cwd, 'ocean.palette.json'), 'utf-8'),
+ );
+ expect(written).toEqual(result.data.candidate);
+ expect(written).toMatchObject({black: '#000000', white: '#ffffff'});
+ expect(result.data.receipt).toBe('ocean.palette.receipt.json');
+ });
+
+ it('preserves mixed decimal and integer stop order in every artifact', () => {
+ const cwd = fixture();
+ fs.writeFileSync(
+ path.join(cwd, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'light-only',
+ stops: [12.5, 50, 80],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+
+ themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts', preview: 'ocean.palette.html'},
+ {cwd},
+ );
+
+ const candidate = fs.readFileSync(
+ path.join(cwd, 'ocean.palette.ts'),
+ 'utf-8',
+ );
+ expect(candidate).toContain('"12.5":');
+ expect(candidate).toContain('export const palette =');
+ expect(candidate).toContain('as const');
+ expect(candidate.indexOf('"12.5":')).toBeLessThan(
+ candidate.indexOf('"50":'),
+ );
+ expect(candidate.indexOf('"50":')).toBeLessThan(candidate.indexOf('"80":'));
+ const preview = fs.readFileSync(
+ path.join(cwd, 'ocean.palette.html'),
+ 'utf-8',
+ );
+ expect(preview.indexOf('<strong>12.5</strong>')).toBeLessThan(
+ preview.indexOf('<strong>50</strong>'),
+ );
+ expect(preview.indexOf('<strong>50</strong>')).toBeLessThan(
+ preview.indexOf('<strong>80</strong>'),
+ );
+
+ themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean-json.palette.json'},
+ {cwd},
+ );
+ const json = fs.readFileSync(
+ path.join(cwd, 'ocean-json.palette.json'),
+ 'utf-8',
+ );
+ expect(json.indexOf('"12.5":')).toBeLessThan(json.indexOf('"50":'));
+ expect(json.indexOf('"50":')).toBeLessThan(json.indexOf('"80":'));
+ });
+
+ it('writes a standardized preview without requiring palette output', () => {
+ const cwd = fixture();
+ const result = themePaletteGenerate(
+ 'palette.config.json',
+ {preview: 'palette-preview.html'},
+ {cwd},
+ );
+
+ expect(result.data).toMatchObject({
+ output: null,
+ receipt: null,
+ preview: 'palette-preview.html',
+ written: true,
+ });
+ const preview = fs.readFileSync(
+ path.join(cwd, 'palette-preview.html'),
+ 'utf-8',
+ );
+ expect(preview).toContain('palette-preview-v1');
+ expect(preview).not.toContain('Generated candidate');
+ expect(preview).not.toContain('does not certify accessibility');
+ expect(preview).not.toMatch(/https?:\/\//);
+ });
+
+ it('rejects output formats that cannot preserve the palette contract', () => {
+ const cwd = fixture();
+ expect(() =>
+ themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.js'},
+ {cwd},
+ ),
+ ).toThrow('must end in .ts or .json');
+ });
+
+ it('does not overwrite an existing preview implicitly', () => {
+ const cwd = fixture();
+ fs.writeFileSync(path.join(cwd, 'palette-preview.html'), 'author edit\n');
+
+ const result = themePaletteGenerate(
+ 'palette.config.json',
+ {preview: 'palette-preview.html'},
+ {cwd},
+ );
+
+ expect(result.data).toMatchObject({written: false, reason: 'exists'});
+ expect(
+ fs.readFileSync(path.join(cwd, 'palette-preview.html'), 'utf-8'),
+ ).toBe('author edit\n');
+ });
+
+ it('leaves author-owned output untouched unless overwrite is explicit', () => {
+ const cwd = fixture();
+ fs.writeFileSync(path.join(cwd, 'ocean.palette.ts'), 'author edit\n');
+
+ const skipped = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts'},
+ {cwd},
+ );
+ expect(skipped.data).toMatchObject({written: false, reason: 'exists'});
+ expect(fs.readFileSync(path.join(cwd, 'ocean.palette.ts'), 'utf-8')).toBe(
+ 'author edit\n',
+ );
+
+ const replaced = themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts', overwrite: true},
+ {cwd},
+ );
+ expect(replaced.data.written).toBe(true);
+ expect(
+ fs.readFileSync(path.join(cwd, 'ocean.palette.ts'), 'utf-8'),
+ ).not.toBe('author edit\n');
+ });
+
+ it('rejects input and output aliases by filesystem identity', () => {
+ const cwd = fixture();
+ const config = path.join(cwd, 'palette.config.json');
+ const alias = path.join(cwd, 'Palette.config.json');
+ if (!fs.existsSync(alias)) fs.linkSync(config, alias);
+ const original = fs.readFileSync(config, 'utf-8');
+
+ expect(() =>
+ themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'Palette.config.json', overwrite: true},
+ {cwd},
+ ),
+ ).toThrow('must refer to distinct files');
+ expect(fs.readFileSync(config, 'utf-8')).toBe(original);
+ });
+
+ it('does not reuse or overwrite predictable temporary paths', () => {
+ const cwd = fixture();
+ const oldTemporary = path.join(cwd, `ocean.palette.ts.tmp-${process.pid}`);
+ fs.writeFileSync(oldTemporary, 'author file\n');
+
+ themePaletteGenerate(
+ 'palette.config.json',
+ {out: 'ocean.palette.ts', overwrite: true},
+ {cwd},
+ );
+
+ expect(fs.readFileSync(oldTemporary, 'utf-8')).toBe('author file\n');
+ });
+
+ it('returns stable errors for invalid input', () => {
+ const cwd = fixture();
+ fs.writeFileSync(path.join(cwd, 'palette.config.json'), '{');
+ expect(() =>
+ themePaletteGenerate('palette.config.json', {}, {cwd}),
+ ).toThrow('Could not parse palette config');
+ });
+});
diff --git a/packages/cli/api/theme/palette/generate/generator.mjs b/packages/cli/api/theme/palette/generate/generator.mjs
new file mode 100644
index 0000000000..f37a253e50
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/generator.mjs
@@ -0,0 +1,751 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {
+ hexToOklch,
+ luminance,
+ maxOklchChroma,
+ normalizeColor,
+ oklabCoordinates,
+ oklabCoordinatesToHex,
+ oklchClampedHex,
+ toneToOklabLightness,
+} from './color.mjs';
+
+/** @typedef {import('../../theme.type.mjs').TonalPaletteAnchor} TonalPaletteAnchor */
+/** @typedef {import('../../theme.type.mjs').TonalPaletteGenerationInput} TonalPaletteGenerationInput */
+/** @typedef {[number, number, number]} ColorTriple */
+/** @typedef {'light' | 'dark'} PaletteMode */
+/** @typedef {{lightness: number, chroma: number, hue: number}} PolarColor */
+/** @typedef {TonalPaletteAnchor & {color: string, generatedColor: string, deltaE: number}} AnchorResult */
+/** @typedef {{colors: Record<number, string>, diagnostics: Record<string, unknown>}} GeneratedRamp */
+/** @typedef {{id: string, name: string, seed: string, kind: 'chromatic' | 'neutral', anchors: TonalPaletteAnchor[]}} NormalizedFamily */
+/** @typedef {{recipe: typeof PALETTE_RECIPE, vibrancy: number, neutralProfile: string, modeStrategy: string, stops: number[], families: NormalizedFamily[]}} NormalizedRequest */
+/** @typedef {{id: string, name: string, seed: string, light?: GeneratedRamp, dark?: GeneratedRamp}} GeneratedFamily */
+/** @typedef {{recipe: typeof PALETTE_RECIPE, status: 'candidate', request: NormalizedRequest, families: GeneratedFamily[], coordination: Record<string, unknown>[], errors: {familyId: string, message: string}[]}} PaletteGenerationResult */
+
+export const PALETTE_RECIPE = 'astryx-oklch-v1';
+export const PALETTE_BLACK = '#000000';
+export const PALETTE_WHITE = '#ffffff';
+export const DEFAULT_21_STOPS = Object.freeze([
+ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,
+ 100,
+]);
+export const COMPACT_11_STOPS = Object.freeze([
+ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
+]);
+
+const DARK_CHROMA_FACTOR = 0.85;
+const RESERVED_FAMILY_IDS = new Set(['black', 'white']);
+
+/** @param {number} value @param {number} minimum @param {number} maximum */
+function clamp(value, minimum, maximum) {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+/** @param {number} hue */
+function normalizeHue(hue) {
+ return ((hue % 360) + 360) % 360;
+}
+
+/** @param {number} a @param {number} b */
+function hueDistance(a, b) {
+ const difference = Math.abs(normalizeHue(a) - normalizeHue(b));
+ return Math.min(difference, 360 - difference);
+}
+
+/** @param {number} from @param {number} to */
+function signedHueDelta(from, to) {
+ return ((normalizeHue(to) - normalizeHue(from) + 540) % 360) - 180;
+}
+
+/** @param {number} a @param {number} b @param {number} amount */
+function interpolateHue(a, b, amount) {
+ const delta = ((b - a + 540) % 360) - 180;
+ return normalizeHue(a + delta * amount);
+}
+
+/** @param {readonly number[]} stops @returns {number[]} */
+export function validateStops(stops) {
+ if (!Array.isArray(stops) || stops.length === 0) {
+ throw new Error('A palette requires at least one stop.');
+ }
+ for (const stop of stops) {
+ if (!Number.isFinite(stop) || stop < 0 || stop > 100) {
+ throw new Error(
+ `Stop ${String(stop)} must be a finite number from 0 to 100.`,
+ );
+ }
+ }
+ for (let index = 1; index < stops.length; index++) {
+ if (stops[index] <= stops[index - 1]) {
+ throw new Error('Stops must be unique and strictly increasing.');
+ }
+ }
+ return [...stops];
+}
+
+/** @param {unknown} input @returns {number[]} */
+export function parseStopList(input) {
+ const values = String(input)
+ .split(',')
+ .map(value => value.trim());
+ if (values.some(value => value === '' || !Number.isFinite(Number(value)))) {
+ throw new Error('Every custom stop must be a number from 0 to 100.');
+ }
+ return validateStops(values.map(Number));
+}
+
+/** @param {string} strategy @returns {PaletteMode[]} */
+function modesForStrategy(strategy) {
+ if (strategy === 'light-only') return ['light'];
+ if (strategy === 'dark-only') return ['dark'];
+ if (strategy === 'light-and-dark') return ['light', 'dark'];
+ throw new Error(`Unknown mode strategy: ${String(strategy)}`);
+}
+
+/** @param {number} hue */
+function hueBalanceFactor(hue) {
+ const normalized = normalizeHue(hue);
+ if (normalized >= 70 && normalized < 115) return 0.94;
+ if (normalized >= 115 && normalized < 175) return 0.78;
+ if (normalized >= 175 && normalized < 230) return 0.82;
+ if (normalized >= 285 && normalized < 340) return 0.9;
+ return 1;
+}
+
+/** @param {number} hue @param {number} tone */
+function highToneChromaFactor(hue, tone) {
+ if (tone <= 60) return 1;
+ const taper = smoothstep((tone - 60) / 35);
+ const normalized = normalizeHue(hue);
+ if (normalized >= 115 && normalized < 175) return 1 - 0.28 * taper;
+ if (normalized >= 175 && normalized < 200) return 1 - 0.4 * taper;
+ return 1;
+}
+
+/** @param {number} hue @param {number} tone */
+function toneAdjustedHue(hue, tone) {
+ const normalized = normalizeHue(hue);
+ if (normalized < 40 || normalized >= 70 || tone >= 50) return normalized;
+ const darkening = clamp((50 - tone) / 40, 0, 1);
+ return normalizeHue(normalized - 8 * Math.sqrt(darkening));
+}
+
+/** @param {number} tone */
+function toneChromaEnvelope(tone) {
+ const normalized = clamp(tone / 100, 0, 1);
+ return 0.18 + 0.82 * Math.sqrt(Math.max(0, Math.sin(Math.PI * normalized)));
+}
+
+/** @param {number} vibrancy */
+function vibrancyMultiplier(vibrancy) {
+ if (!Number.isFinite(vibrancy) || vibrancy < 0 || vibrancy > 100) {
+ throw new Error('Vibrancy must be a number from 0 to 100.');
+ }
+ if (vibrancy <= 25) return (vibrancy / 25) * 0.72;
+ if (vibrancy <= 50) return 0.72 + ((vibrancy - 25) / 25) * 0.28;
+ return 1 + (vibrancy - 50) * 0.0096;
+}
+
+/** @param {number} sourceChroma */
+function coordinatedChroma(sourceChroma) {
+ return sourceChroma * 0.35 + 0.18 * 0.65;
+}
+
+/** @param {string} color @returns {PolarColor} */
+function colorToPolar(color) {
+ const value = hexToOklch(color);
+ return {lightness: value.L, chroma: value.C, hue: value.H};
+}
+
+/** @param {string} profile @param {string} seed @returns {PolarColor} */
+function neutralPolar(profile, seed) {
+ if (profile === 'custom') return colorToPolar(seed);
+ const hue = profile === 'warm-v1' ? 75 : profile === 'cool-v1' ? 250 : 0;
+ if (!['neutral-v1', 'warm-v1', 'cool-v1'].includes(profile)) {
+ throw new Error(`Unknown neutral profile: ${String(profile)}`);
+ }
+ return {
+ lightness: 0.5,
+ chroma: profile === 'neutral-v1' ? 0 : 0.018,
+ hue,
+ };
+}
+
+/** @param {PolarColor} seed @param {TonalPaletteAnchor[]} anchors @param {number} stop @returns {PolarColor} */
+function anchorPolarAtStop(seed, anchors, stop) {
+ if (anchors.length === 0) return seed;
+ const sorted = [...anchors].sort((a, b) => a.stop - b.stop);
+ const lower = [...sorted].reverse().find(anchor => anchor.stop <= stop);
+ const upper = sorted.find(anchor => anchor.stop >= stop);
+ if (!lower || !upper || lower.stop === upper.stop) {
+ return colorToPolar(normalizeColor((lower ?? upper ?? sorted[0]).color));
+ }
+ const start = colorToPolar(normalizeColor(lower.color));
+ const end = colorToPolar(normalizeColor(upper.color));
+ const amount = (stop - lower.stop) / (upper.stop - lower.stop);
+ return {
+ lightness: start.lightness + (end.lightness - start.lightness) * amount,
+ chroma: start.chroma + (end.chroma - start.chroma) * amount,
+ hue: interpolateHue(start.hue, end.hue, amount),
+ };
+}
+
+/**
+ * @param {PolarColor} source
+ * @param {number} tone
+ * @param {PaletteMode} mode
+ * @param {number} vibrancy
+ * @param {boolean} coordinateWithOtherFamilies
+ */
+function generateCandidate(
+ source,
+ tone,
+ mode,
+ vibrancy,
+ coordinateWithOtherFamilies,
+) {
+ const adjustedTone = tone;
+ const adjustedHue = toneAdjustedHue(source.hue, adjustedTone);
+ const baseChroma = coordinateWithOtherFamilies
+ ? coordinatedChroma(source.chroma)
+ : source.chroma;
+ const chroma =
+ baseChroma *
+ vibrancyMultiplier(vibrancy) *
+ hueBalanceFactor(adjustedHue) *
+ highToneChromaFactor(adjustedHue, adjustedTone) *
+ toneChromaEnvelope(adjustedTone) *
+ (mode === 'dark' ? DARK_CHROMA_FACTOR : 1);
+ const lightness = toneToOklabLightness(adjustedTone);
+ return {
+ hex: oklchClampedHex(lightness, chroma, adjustedHue),
+ gamutMapped: chroma > maxOklchChroma(adjustedHue, lightness) + 0.000001,
+ };
+}
+
+/** @param {string} colorA @param {string} colorB */
+export function perceptualDelta(colorA, colorB) {
+ const [lightnessA, aA, bA] = oklabCoordinates(colorA);
+ const [lightnessB, aB, bB] = oklabCoordinates(colorB);
+ return (
+ Math.sqrt(
+ (lightnessA - lightnessB) ** 2 + (aA - aB) ** 2 + (bA - bB) ** 2,
+ ) * 100
+ );
+}
+
+/** @param {string} colorA @param {string} colorB @param {number} amount */
+function interpolateColor(colorA, colorB, amount) {
+ const start = hexToOklch(colorA);
+ const end = hexToOklch(colorB);
+ return oklchClampedHex(
+ start.L + (end.L - start.L) * amount,
+ start.C + (end.C - start.C) * amount,
+ interpolateHue(start.H, end.H, amount),
+ );
+}
+
+/** @param {string} candidate @param {TonalPaletteAnchor} anchor @returns {AnchorResult} */
+function applyAnchor(candidate, anchor) {
+ const target = normalizeColor(anchor.color);
+ let generatedColor = candidate;
+ if (anchor.policy === 'exact') {
+ generatedColor = target;
+ } else if (anchor.policy === 'bounded') {
+ const tolerance = Number(anchor.maxDeltaE);
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
+ throw new Error(
+ `Bounded anchor at stop ${anchor.stop} requires a non-negative maxDeltaE.`,
+ );
+ }
+ if (perceptualDelta(candidate, target) > tolerance) {
+ let low = 0;
+ let high = 1;
+ for (let index = 0; index < 18; index++) {
+ const amount = (low + high) / 2;
+ const mixed = interpolateColor(target, candidate, amount);
+ if (perceptualDelta(mixed, target) <= tolerance) low = amount;
+ else high = amount;
+ }
+ generatedColor = interpolateColor(target, candidate, low);
+ }
+ } else if (anchor.policy === 'flexible') {
+ generatedColor = interpolateColor(candidate, target, 0.35);
+ } else {
+ throw new Error(`Unknown anchor policy: ${String(anchor.policy)}`);
+ }
+ return {
+ ...anchor,
+ color: target,
+ generatedColor,
+ deltaE: perceptualDelta(generatedColor, target),
+ };
+}
+
+/** @param {number} amount */
+function smoothstep(amount) {
+ const value = clamp(amount, 0, 1);
+ return value * value * (3 - 2 * value);
+}
+
+/** @param {ColorTriple} start @param {ColorTriple} end @param {number} amount @returns {ColorTriple} */
+function interpolateDelta(start, end, amount) {
+ return [
+ start[0] + (end[0] - start[0]) * amount,
+ start[1] + (end[1] - start[1]) * amount,
+ start[2] + (end[2] - start[2]) * amount,
+ ];
+}
+
+/** @param {{stop: number, delta: ColorTriple}[]} corrections @param {number} stop @returns {ColorTriple} */
+function correctionAtStop(corrections, stop) {
+ /** @type {ColorTriple} */
+ const zero = [0, 0, 0];
+ if (corrections.length === 0) return zero;
+ const first = corrections[0];
+ if (stop <= first.stop) {
+ const boundary = Math.max(0, first.stop - 25);
+ if (stop <= boundary && boundary !== first.stop) return zero;
+ const amount =
+ boundary === first.stop
+ ? 1
+ : smoothstep((stop - boundary) / (first.stop - boundary));
+ return interpolateDelta(zero, first.delta, amount);
+ }
+ const last = corrections[corrections.length - 1];
+ if (stop >= last.stop) {
+ const boundary = Math.min(100, last.stop + 25);
+ if (stop >= boundary && boundary !== last.stop) return zero;
+ const amount =
+ boundary === last.stop
+ ? 1
+ : smoothstep((stop - last.stop) / (boundary - last.stop));
+ return interpolateDelta(last.delta, zero, amount);
+ }
+ const upperIndex = corrections.findIndex(item => item.stop > stop);
+ const lower = corrections[upperIndex - 1];
+ const upper = corrections[upperIndex];
+ return interpolateDelta(
+ lower.delta,
+ upper.delta,
+ smoothstep((stop - lower.stop) / (upper.stop - lower.stop)),
+ );
+}
+
+/** @param {Record<number, string>} colors @param {number[]} stops @param {TonalPaletteAnchor[]} anchors */
+function applyAnchorCorrections(colors, stops, anchors) {
+ if (anchors.length === 0) return {colors, anchors: []};
+ const corrections = anchors
+ .map(anchor => {
+ const candidate = colors[anchor.stop];
+ const result = applyAnchor(candidate, anchor);
+ const base = oklabCoordinates(candidate);
+ const target = oklabCoordinates(result.generatedColor);
+ /** @type {ColorTriple} */
+ const delta = [
+ target[0] - base[0],
+ target[1] - base[1],
+ target[2] - base[2],
+ ];
+ return {
+ stop: anchor.stop,
+ delta,
+ result,
+ };
+ })
+ .sort((a, b) => a.stop - b.stop);
+ /** @type {Record<number, string>} */
+ const corrected = {};
+ for (const stop of stops) {
+ const base = oklabCoordinates(colors[stop]);
+ const delta = correctionAtStop(corrections, stop);
+ corrected[stop] = oklabCoordinatesToHex([
+ base[0] + delta[0],
+ base[1] + delta[1],
+ base[2] + delta[2],
+ ]);
+ }
+ for (const correction of corrections) {
+ corrected[correction.stop] = correction.result.generatedColor;
+ }
+ return {
+ colors: corrected,
+ anchors: corrections.map(correction => correction.result),
+ };
+}
+
+/** @param {TonalPaletteAnchor[]} anchors @param {number[]} stops */
+function assertAnchorSet(anchors, stops) {
+ const seen = new Set();
+ for (const anchor of anchors) {
+ const color = normalizeColor(anchor.color);
+ if (!['light', 'dark'].includes(anchor.mode)) {
+ throw new Error(`Unknown anchor mode: ${String(anchor.mode)}`);
+ }
+ if (!stops.includes(anchor.stop)) {
+ throw new Error(
+ `Anchor stop ${anchor.stop} is not present in the requested stop layout.`,
+ );
+ }
+ if (
+ (anchor.stop === 0 && color !== PALETTE_BLACK) ||
+ (anchor.stop === 100 && color !== PALETTE_WHITE)
+ ) {
+ throw new Error(
+ `Anchor stop ${anchor.stop} is reserved for exact ${anchor.stop === 0 ? 'black' : 'white'}; use an interior stop for a tinted endpoint.`,
+ );
+ }
+ const key = `${anchor.mode}:${anchor.stop}`;
+ if (seen.has(key)) {
+ throw new Error(
+ `Duplicate anchor for ${anchor.mode} stop ${anchor.stop}.`,
+ );
+ }
+ seen.add(key);
+ }
+}
+
+/** @param {Record<number, string>} colors @param {number[]} stops @param {number} sourceHue @param {number[]} gamutMappedStops @param {AnchorResult[]} anchors */
+function buildDiagnostics(colors, stops, sourceHue, gamutMappedStops, anchors) {
+ let monotonic = true;
+ let minimumAdjacentDeltaE = Number.POSITIVE_INFINITY;
+ let maximumAdjacentDeltaE = 0;
+ let maximumHueDrift = 0;
+ let hueIdentityRisk = null;
+ for (let index = 0; index < stops.length; index++) {
+ const stop = stops[index];
+ const color = colors[stop];
+ const oklch = hexToOklch(color);
+ if (oklch.C >= 0.015) {
+ const drift = signedHueDelta(sourceHue, oklch.H);
+ maximumHueDrift = Math.max(
+ maximumHueDrift,
+ hueDistance(sourceHue, oklch.H),
+ );
+ if (sourceHue >= 230 && sourceHue < 285 && drift > 12) {
+ hueIdentityRisk = 'blue-to-purple';
+ }
+ if (sourceHue >= 70 && sourceHue < 115 && drift < -12) {
+ hueIdentityRisk = 'yellow-to-brown';
+ }
+ }
+ if (index === 0) continue;
+ const previous = colors[stops[index - 1]];
+ if (luminance(color) + 0.000001 < luminance(previous)) monotonic = false;
+ const adjacentDelta = perceptualDelta(previous, color);
+ minimumAdjacentDeltaE = Math.min(minimumAdjacentDeltaE, adjacentDelta);
+ maximumAdjacentDeltaE = Math.max(maximumAdjacentDeltaE, adjacentDelta);
+ }
+ return {
+ monotonic,
+ minimumAdjacentDeltaE:
+ minimumAdjacentDeltaE === Number.POSITIVE_INFINITY
+ ? 0
+ : minimumAdjacentDeltaE,
+ maximumAdjacentDeltaE,
+ maximumHueDrift,
+ hueIdentityRisk,
+ gamutMappedStops,
+ anchors,
+ };
+}
+
+/** @param {NormalizedRequest} request @param {NormalizedFamily} family @param {PaletteMode} mode @returns {GeneratedRamp} */
+function generateRamp(request, family, mode) {
+ const seedHex = normalizeColor(family.seed);
+ const anchors = (family.anchors ?? []).filter(anchor => anchor.mode === mode);
+ assertAnchorSet(family.anchors ?? [], request.stops);
+ const seed =
+ family.kind === 'neutral'
+ ? neutralPolar(request.neutralProfile, seedHex)
+ : colorToPolar(seedHex);
+ /** @type {Record<number, string>} */
+ const colors = {};
+ const gamutMappedStops = [];
+ const diagnosticReference = generateCandidate(
+ seed,
+ 50,
+ mode,
+ request.vibrancy,
+ family.kind !== 'neutral',
+ ).hex;
+ for (const stop of request.stops) {
+ const source = anchorPolarAtStop(seed, anchors, stop);
+ const generated = generateCandidate(
+ source,
+ stop,
+ mode,
+ request.vibrancy,
+ family.kind !== 'neutral',
+ );
+ colors[stop] = generated.hex;
+ if (generated.gamutMapped) gamutMappedStops.push(stop);
+ }
+ const corrected = applyAnchorCorrections(colors, request.stops, anchors);
+ const diagnostics = buildDiagnostics(
+ corrected.colors,
+ request.stops,
+ hexToOklch(diagnosticReference).H,
+ gamutMappedStops,
+ corrected.anchors,
+ );
+ if (!diagnostics.monotonic) {
+ throw new Error(
+ `${family.name} ${mode} ramp is not luminance-monotonic with the requested anchors.`,
+ );
+ }
+ return {colors: corrected.colors, diagnostics};
+}
+
+/** @param {number[]} stops @param {number} target */
+function nearestStop(stops, target) {
+ return stops.reduce((best, stop) =>
+ Math.abs(stop - target) < Math.abs(best - target) ? stop : best,
+ );
+}
+
+/** @param {NormalizedRequest} request @param {GeneratedFamily[]} families */
+function buildCoordinationDiagnostics(request, families) {
+ const stop = nearestStop(request.stops, 50);
+ const chromaticIds = new Set(
+ request.families
+ .filter(family => family.kind !== 'neutral')
+ .map(family => family.id),
+ );
+ return modesForStrategy(request.modeStrategy).map(mode => {
+ const samples = families
+ .filter(family => chromaticIds.has(family.id) && family[mode])
+ .map(family => {
+ const ramp = family[mode];
+ if (!ramp) throw new Error(`Missing ${mode} ramp for ${family.id}.`);
+ const color = ramp.colors[stop];
+ return {
+ id: family.id,
+ name: family.name,
+ color,
+ chroma: hexToOklch(color).C,
+ };
+ });
+ let closestFamilies = null;
+ let minimumFamilyDeltaE = Number.POSITIVE_INFINITY;
+ for (let index = 0; index < samples.length; index++) {
+ for (let next = index + 1; next < samples.length; next++) {
+ const delta = perceptualDelta(
+ samples[index].color,
+ samples[next].color,
+ );
+ if (delta < minimumFamilyDeltaE) {
+ minimumFamilyDeltaE = delta;
+ closestFamilies = [samples[index].name, samples[next].name];
+ }
+ }
+ }
+ const byChroma = [...samples].sort((a, b) => a.chroma - b.chroma);
+ const weakest = byChroma[0];
+ const strongest = byChroma[byChroma.length - 1];
+ return {
+ mode,
+ stop,
+ closestFamilies,
+ minimumFamilyDeltaE:
+ minimumFamilyDeltaE === Number.POSITIVE_INFINITY
+ ? null
+ : minimumFamilyDeltaE,
+ strongestFamily: strongest?.name ?? null,
+ weakestFamily: weakest?.name ?? null,
+ chromaRatio:
+ weakest && strongest && weakest.chroma > 0.0001
+ ? strongest.chroma / weakest.chroma
+ : null,
+ };
+ });
+}
+
+/** @param {TonalPaletteGenerationInput} input @returns {NormalizedRequest} */
+export function normalizeGenerationRequest(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw new Error('Palette generation config must be an object.');
+ }
+ const families = input.families;
+ if (!Array.isArray(families) || families.length === 0) {
+ throw new Error('Palette generation requires at least one family.');
+ }
+ const modeStrategy = input.modeStrategy ?? 'light-and-dark';
+ const modes = modesForStrategy(modeStrategy);
+ const stops = validateStops(input.stops ?? DEFAULT_21_STOPS);
+ const ids = new Set();
+ const normalizedFamilies = families.map((family, index) => {
+ if (!family || typeof family !== 'object' || Array.isArray(family)) {
+ throw new Error(`Family ${index} must be an object.`);
+ }
+ const id = String(family.id ?? '').trim();
+ if (!/^[a-z][a-z0-9-]*$/.test(id)) {
+ throw new Error(
+ `Family ${index} id must use lower-kebab-case characters.`,
+ );
+ }
+ if (RESERVED_FAMILY_IDS.has(id)) {
+ throw new Error(
+ `Family id ${id} is reserved for the standalone ${id} palette value.`,
+ );
+ }
+ if (ids.has(id)) throw new Error(`Duplicate family id: ${id}.`);
+ ids.add(id);
+ const kind = family.kind ?? 'chromatic';
+ if (!['chromatic', 'neutral'].includes(kind)) {
+ throw new Error(`Unknown family kind: ${String(kind)}`);
+ }
+ if (family.anchors != null && !Array.isArray(family.anchors)) {
+ throw new Error(`Family ${id} anchors must be an array.`);
+ }
+ const anchors = (family.anchors ?? []).map((anchor, anchorIndex) => {
+ if (!anchor || typeof anchor !== 'object' || Array.isArray(anchor)) {
+ throw new Error(
+ `Family ${id} anchor ${anchorIndex} must be an object.`,
+ );
+ }
+ if (!['light', 'dark'].includes(anchor.mode)) {
+ throw new Error(`Unknown anchor mode: ${String(anchor.mode)}`);
+ }
+ if (!modes.includes(anchor.mode)) {
+ throw new Error(
+ `Anchor mode ${anchor.mode} is not generated by mode strategy ${modeStrategy}.`,
+ );
+ }
+ if (!Number.isFinite(anchor.stop) || !stops.includes(anchor.stop)) {
+ throw new Error(
+ `Anchor stop ${String(anchor.stop)} is not present in the requested stop layout.`,
+ );
+ }
+ if (!['exact', 'bounded', 'flexible'].includes(anchor.policy)) {
+ throw new Error(`Unknown anchor policy: ${String(anchor.policy)}`);
+ }
+ const maxDeltaE = anchor.maxDeltaE;
+ if (
+ anchor.policy === 'bounded' &&
+ (typeof maxDeltaE !== 'number' ||
+ !Number.isFinite(maxDeltaE) ||
+ maxDeltaE < 0)
+ ) {
+ throw new Error(
+ `Bounded anchor at stop ${anchor.stop} requires a non-negative maxDeltaE.`,
+ );
+ }
+ if (anchor.policy !== 'bounded' && maxDeltaE != null) {
+ throw new Error(
+ `Anchor policy ${anchor.policy} does not accept maxDeltaE.`,
+ );
+ }
+ const color = normalizeColor(anchor.color);
+ if (
+ (anchor.stop === 0 && color !== PALETTE_BLACK) ||
+ (anchor.stop === 100 && color !== PALETTE_WHITE)
+ ) {
+ throw new Error(
+ `Anchor stop ${anchor.stop} is reserved for exact ${anchor.stop === 0 ? 'black' : 'white'}; use an interior stop for a tinted endpoint.`,
+ );
+ }
+ return {
+ mode: anchor.mode,
+ stop: anchor.stop,
+ color,
+ policy: anchor.policy,
+ ...(anchor.policy === 'bounded' ? {maxDeltaE} : {}),
+ };
+ });
+ return {
+ id,
+ name: String(family.name ?? id),
+ seed: normalizeColor(family.seed),
+ kind,
+ anchors,
+ };
+ });
+ /** @type {NormalizedRequest} */
+ const request = {
+ recipe: PALETTE_RECIPE,
+ vibrancy: input.vibrancy ?? 50,
+ neutralProfile: input.neutralProfile ?? 'neutral-v1',
+ modeStrategy,
+ stops,
+ families: normalizedFamilies,
+ };
+ vibrancyMultiplier(request.vibrancy);
+ return request;
+}
+
+/** @param {TonalPaletteGenerationInput} input @returns {PaletteGenerationResult} */
+export function generatePaletteSet(input) {
+ const request = normalizeGenerationRequest(input);
+ /** @type {GeneratedFamily[]} */
+ const families = [];
+ /** @type {{familyId: string, message: string}[]} */
+ const errors = [];
+ for (const family of request.families) {
+ try {
+ /** @type {GeneratedFamily} */
+ const generated = {
+ id: family.id,
+ name: family.name,
+ seed: family.seed,
+ };
+ for (const mode of modesForStrategy(request.modeStrategy)) {
+ generated[mode] = generateRamp(request, family, mode);
+ }
+ families.push(generated);
+ } catch (error) {
+ errors.push({
+ familyId: family.id,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return {
+ recipe: PALETTE_RECIPE,
+ status: 'candidate',
+ request,
+ families,
+ coordination: buildCoordinationDiagnostics(request, families),
+ errors,
+ };
+}
+
+/**
+ * Generate candidate palette data without reading or writing files.
+ *
+ * @param {import('../../theme.type.mjs').TonalPaletteGenerationInput} input
+ * @returns {import('../../theme.type.mjs').TonalPaletteCandidate}
+ */
+export function generateTonalPalette(input) {
+ const result = generatePaletteSet(input);
+ if (result.errors.length > 0) {
+ throw new Error(
+ result.errors
+ .map(error => `${error.familyId}: ${error.message}`)
+ .join('\n'),
+ );
+ }
+ return {
+ schemaVersion: 1,
+ status: 'candidate',
+ recipe: PALETTE_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 {unknown} result */
+export function serializeGenerationResult(result) {
+ return `${JSON.stringify(result, null, 2)}\n`;
+}
diff --git a/packages/cli/api/theme/palette/generate/generator.test.mjs b/packages/cli/api/theme/palette/generate/generator.test.mjs
new file mode 100644
index 0000000000..102cc4b232
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/generator.test.mjs
@@ -0,0 +1,375 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createHash} from 'node:crypto';
+import {describe, expect, it} from 'vitest';
+import {
+ COMPACT_11_STOPS,
+ DEFAULT_21_STOPS,
+ PALETTE_RECIPE,
+ generatePaletteSet,
+ generateTonalPalette,
+ perceptualDelta,
+ validateStops,
+} from './generator.mjs';
+import {hexToOklch} from './color.mjs';
+
+const families = [
+ {id: 'neutral', name: 'Neutral', seed: '#777777', kind: 'neutral'},
+ {id: 'blue', name: 'Blue', seed: '#0074e2'},
+ {id: 'orange', name: 'Orange', seed: '#d57113'},
+];
+
+function candidateDigest(request) {
+ const candidate = generateTonalPalette(request);
+ return createHash('sha256')
+ .update(`${JSON.stringify(candidate, null, 2)}\n`)
+ .digest('hex');
+}
+
+describe('astryx-oklch-v1 palette generator', () => {
+ it('returns directly usable candidate data without filesystem work', () => {
+ const candidate = generateTonalPalette({
+ families: [families[1]],
+ stops: [40],
+ });
+
+ expect(candidate).toMatchObject({
+ schemaVersion: 1,
+ status: 'candidate',
+ recipe: 'astryx-oklch-v1',
+ });
+ expect(candidate.palette.blue.light[40]).toMatch(/^#[0-9a-f]{6}$/);
+ expect(candidate.palette.blue.dark[40]).toMatch(/^#[0-9a-f]{6}$/);
+ expect(candidate.black).toBe('#000000');
+ expect(candidate.white).toBe('#ffffff');
+ expect(candidate.stops).toEqual([40]);
+ });
+
+ it('locks the normative recipe fixtures', () => {
+ expect(candidateDigest({families})).toBe(
+ '11c40191d508274d89d631bb4e1cb662f70ff0dce6c0dec101c317f9f69d3e25',
+ );
+ expect(
+ candidateDigest({
+ modeStrategy: 'light-only',
+ stops: [20, 50, 80],
+ families: [
+ {
+ id: 'blue',
+ name: 'Blue',
+ seed: '#0074e2',
+ anchors: [
+ {
+ mode: 'light',
+ stop: 50,
+ color: '#1682d5',
+ policy: 'exact',
+ },
+ ],
+ },
+ ],
+ }),
+ ).toBe('c42929be3c4b5cb857cada078f62bb5a2242c1a22cfa4ae7546a18592540f7f3');
+ expect(
+ candidateDigest({
+ modeStrategy: 'dark-only',
+ stops: [40],
+ families: [{id: 'red', name: 'Red', seed: '#d62830'}],
+ }),
+ ).toBe('88d3d69865c74c7fb14347b9967575285a7d44ab893087a08bc842bb66b29bbb');
+ expect(
+ candidateDigest({
+ stops: [60, 80, 95],
+ families: [
+ {id: 'green', name: 'Green', seed: '#358a3a'},
+ {id: 'teal', name: 'Teal', seed: '#0c7365'},
+ {id: 'cyan', name: 'Cyan', seed: '#0c6f82'},
+ ],
+ }),
+ ).toBe('873821574fdbe3357304dbc06986bd2e5ec88af80d0f36305626fd826c3cf07b');
+ });
+
+ it('defaults to 21 stops while allowing authors to omit endpoints', () => {
+ expect(generatePaletteSet({families: [families[1]]}).request.stops).toEqual(
+ DEFAULT_21_STOPS,
+ );
+ expect(DEFAULT_21_STOPS).toHaveLength(21);
+ expect(DEFAULT_21_STOPS[0]).toBe(0);
+ expect(DEFAULT_21_STOPS.at(-1)).toBe(100);
+ expect(
+ generatePaletteSet({families: [families[1]], stops: [15, 40, 72]}).request
+ .stops,
+ ).toEqual([15, 40, 72]);
+ expect(
+ generatePaletteSet({families: [families[1]], stops: [40]}).families[0]
+ .light.colors,
+ ).toEqual({40: expect.stringMatching(/^#[0-9a-f]{6}$/)});
+ });
+
+ it('keeps shared stop values stable across full, compact, and custom layouts', () => {
+ const family = {id: 'blue', name: 'Blue', seed: '#0074e2'};
+ const full = generateTonalPalette({
+ stops: [...DEFAULT_21_STOPS],
+ families: [family],
+ });
+ const compact = generateTonalPalette({
+ stops: [...COMPACT_11_STOPS],
+ families: [family],
+ });
+ const custom = generateTonalPalette({
+ stops: [12.5, 50, 80],
+ families: [family],
+ });
+
+ expect(custom.stops).toEqual([12.5, 50, 80]);
+ expect(custom.stops.map(stop => custom.palette.blue.light[stop])).toEqual([
+ custom.palette.blue.light[12.5],
+ custom.palette.blue.light[50],
+ custom.palette.blue.light[80],
+ ]);
+
+ for (const mode of ['light', 'dark']) {
+ for (const stop of COMPACT_11_STOPS) {
+ expect(compact.palette.blue[mode][stop]).toBe(
+ full.palette.blue[mode][stop],
+ );
+ }
+ expect(custom.palette.blue[mode][50]).toBe(full.palette.blue[mode][50]);
+ expect(custom.palette.blue[mode][80]).toBe(full.palette.blue[mode][80]);
+ expect(custom.palette.blue[mode][12.5]).toMatch(/^#[0-9a-f]{6}$/);
+ }
+ });
+
+ it('keeps default endpoints black and white and rejects tinted endpoint anchors', () => {
+ const candidate = generateTonalPalette({families: [families[1]]});
+ for (const mode of ['light', 'dark']) {
+ expect(candidate.palette.blue[mode][0]).toBe('#000000');
+ expect(candidate.palette.blue[mode][100]).toBe('#ffffff');
+ }
+ expect(() =>
+ generateTonalPalette({
+ families: [
+ {
+ ...families[1],
+ anchors: [
+ {
+ mode: 'light',
+ stop: 0,
+ color: '#001122',
+ policy: 'exact',
+ },
+ ],
+ },
+ ],
+ }),
+ ).toThrow('reserved for exact black');
+ });
+
+ it('rejects invalid stop layouts without prescribing a count', () => {
+ expect(() => validateStops([])).toThrow('at least one stop');
+ expect(() => validateStops([0, 40, 40, 100])).toThrow(
+ 'unique and strictly increasing',
+ );
+ expect(() => validateStops([-1, 50])).toThrow('from 0 to 100');
+ expect(() => validateStops([0, Number.NaN, 100])).toThrow('finite number');
+ expect(validateStops([0.5, 37.25, 99.75])).toEqual([0.5, 37.25, 99.75]);
+ });
+
+ it('uses literal stop tones in dark mode', () => {
+ const candidate = generateTonalPalette({
+ modeStrategy: 'light-and-dark',
+ stops: [0, 5, 100],
+ families: [families[1]],
+ });
+
+ expect(candidate.palette.blue.light[0]).toBe('#000000');
+ expect(candidate.palette.blue.dark[0]).toBe('#000000');
+ expect(candidate.palette.blue.dark[5]).toBe('#000f30');
+ expect(candidate.palette.blue.light[100]).toBe('#ffffff');
+ expect(candidate.palette.blue.dark[100]).toBe('#ffffff');
+ });
+
+ it('preserves exact anchors and rejects anchors outside the stop layout', () => {
+ const result = generatePaletteSet({
+ modeStrategy: 'light-only',
+ stops: [20, 50, 80],
+ families: [
+ {
+ id: 'blue',
+ name: 'Blue',
+ seed: '#0074e2',
+ anchors: [
+ {
+ mode: 'light',
+ stop: 50,
+ color: '#1682d5',
+ policy: 'exact',
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(result.families[0].light.colors[50]).toBe('#1682d5');
+ expect(() =>
+ generatePaletteSet({
+ modeStrategy: 'light-only',
+ stops: [20, 50, 80],
+ families: [
+ {
+ id: 'broken',
+ name: 'Broken',
+ seed: '#ff0000',
+ anchors: [
+ {
+ mode: 'light',
+ stop: 30,
+ color: '#ff0000',
+ policy: 'exact',
+ },
+ ],
+ },
+ ],
+ }),
+ ).toThrow('Anchor stop 30 is not present in the requested stop layout.');
+ });
+
+ it('distinguishes exact, bounded, and flexible authoring policies', () => {
+ const target = '#1682d5';
+ const generate = (policy, maxDeltaE) =>
+ generateTonalPalette({
+ modeStrategy: 'light-only',
+ stops: [50],
+ families: [
+ {
+ id: 'blue',
+ name: 'Blue',
+ seed: '#0074e2',
+ anchors: [
+ {
+ mode: 'light',
+ stop: 50,
+ color: target,
+ policy,
+ ...(maxDeltaE == null ? {} : {maxDeltaE}),
+ },
+ ],
+ },
+ ],
+ }).palette.blue.light[50];
+
+ const exact = generate('exact');
+ const bounded = generate('bounded', 2);
+ const flexible = generate('flexible');
+
+ expect(exact).toBe(target);
+ expect(perceptualDelta(bounded, target)).toBeLessThanOrEqual(2.01);
+ expect(flexible).not.toBe(target);
+ expect(new Set([exact, bounded, flexible]).size).toBe(3);
+ });
+
+ it('rejects malformed anchors instead of silently dropping author intent', () => {
+ expect(() =>
+ generateTonalPalette({
+ modeStrategy: 'light-only',
+ stops: [50],
+ families: [{...families[1], anchors: {}}],
+ }),
+ ).toThrow('anchors must be an array');
+
+ expect(() =>
+ generateTonalPalette({
+ modeStrategy: 'light-only',
+ stops: [50],
+ families: [
+ {
+ ...families[1],
+ anchors: [
+ {mode: 'dark', stop: 50, color: '#1682d5', policy: 'exact'},
+ ],
+ },
+ ],
+ }),
+ ).toThrow('Anchor mode dark is not generated by mode strategy light-only');
+ });
+
+ it('normalizes anchor colors in the generation receipt', () => {
+ const result = generatePaletteSet({
+ modeStrategy: 'light-only',
+ stops: [50],
+ families: [
+ {
+ ...families[1],
+ anchors: [
+ {mode: 'light', stop: 50, color: '#AABBCC', policy: 'exact'},
+ ],
+ },
+ ],
+ });
+
+ expect(result.request.families[0].anchors[0].color).toBe('#aabbcc');
+ });
+
+ it('requires bounded anchor tolerance to be a number', () => {
+ for (const maxDeltaE of [null, '2']) {
+ expect(() =>
+ generateTonalPalette({
+ modeStrategy: 'light-only',
+ stops: [50],
+ families: [
+ {
+ ...families[1],
+ anchors: [
+ {
+ mode: 'light',
+ stop: 50,
+ color: '#aabbcc',
+ policy: 'bounded',
+ maxDeltaE,
+ },
+ ],
+ },
+ ],
+ }),
+ ).toThrow('requires a non-negative maxDeltaE');
+ }
+ });
+
+ it('generates an accent family only when the author declares one', () => {
+ const withoutAccent = generateTonalPalette({
+ stops: [50],
+ families: [families[1]],
+ });
+ const withAccent = generateTonalPalette({
+ stops: [50],
+ families: [{id: 'accent', name: 'Accent', seed: '#ff4db8'}],
+ });
+
+ expect(withoutAccent.palette).not.toHaveProperty('accent');
+ expect(withAccent.palette.accent.light[50]).toMatch(/^#[0-9a-f]{6}$/);
+ expect(withAccent.palette.accent.dark[50]).toMatch(/^#[0-9a-f]{6}$/);
+ });
+
+ it('reserves black and white for the standalone palette values', () => {
+ for (const id of ['black', 'white']) {
+ expect(() =>
+ generateTonalPalette({
+ families: [{id, name: id, seed: '#777777'}],
+ }),
+ ).toThrow(
+ `Family id ${id} is reserved for the standalone ${id} palette value.`,
+ );
+ }
+ });
+
+ it('uses vibrancy to make the generated families more muted or vivid', () => {
+ const generate = vibrancy =>
+ generateTonalPalette({
+ vibrancy,
+ stops: [50],
+ families: [families[1]],
+ }).palette.blue.light[50];
+
+ expect(hexToOklch(generate(25)).C).toBeLessThan(hexToOklch(generate(75)).C);
+ });
+});
diff --git a/packages/cli/api/theme/palette/generate/preview.mjs b/packages/cli/api/theme/palette/generate/preview.mjs
new file mode 100644
index 0000000000..6eb9dcc14d
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/preview.mjs
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+export const PALETTE_PREVIEW_VERSION = 'palette-preview-v1';
+
+/** @typedef {'light' | 'dark'} PaletteMode */
+
+/** @param {unknown} value */
+function escapeHtml(value) {
+ return String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#039;');
+}
+
+/**
+ * @param {string} familyId
+ * @param {string} familyName
+ * @param {'light' | 'dark'} mode
+ * @param {Record<string, string>} colors
+ */
+function renderRamp(familyId, familyName, mode, colors) {
+ const orderedColors = Object.entries(colors).sort(
+ ([left], [right]) => Number(left) - Number(right),
+ );
+ const swatches = orderedColors
+ .map(
+ ([stop, color]) => `
+ <li class="swatch" title="${escapeHtml(`${familyId}.${mode}[${stop}] — ${color}`)}">
+ <span class="color" style="--swatch:${escapeHtml(color)}"></span>
+ <span class="meta"><strong>${escapeHtml(stop)}</strong><code>${escapeHtml(color)}</code></span>
+ </li>`,
+ )
+ .join('');
+ return `
+ <section class="family">
+ <h3>${escapeHtml(familyName)}</h3>
+ <ol class="ramp" style="--stop-count:${orderedColors.length}">${swatches}
+ </ol>
+ </section>`;
+}
+
+/**
+ * @param {import('../../theme.type.mjs').TonalPaletteCandidate} candidate
+ * @param {'light' | 'dark'} mode
+ */
+function renderMode(candidate, mode) {
+ const families = Object.entries(candidate.palette)
+ .map(([familyId, family]) => {
+ const colors = family[mode];
+ return colors ? renderRamp(familyId, family.name, mode, colors) : '';
+ })
+ .join('');
+ if (!families) return '';
+ return `
+ <article class="mode ${mode}">
+ <header class="mode-title">
+ <h2>${mode === 'light' ? 'Light mode' : 'Dark mode'}</h2>
+ </header>${families}
+ </article>`;
+}
+
+/** @param {import('../../theme.type.mjs').TonalPaletteCandidate} candidate */
+function renderThemeValues(candidate) {
+ return `
+ <section class="theme-values">
+ <div>
+ <h2>Exact theme values</h2>
+ <p>Always available. Default families repeat these values at stops 0 and 100; custom layouts may omit them.</p>
+ </div>
+ <ol>
+ <li><span class="color" style="--swatch:${escapeHtml(candidate.black)}"></span><span class="meta"><strong>Black</strong><code>${escapeHtml(candidate.black)}</code></span></li>
+ <li><span class="color" style="--swatch:${escapeHtml(candidate.white)}"></span><span class="meta"><strong>White</strong><code>${escapeHtml(candidate.white)}</code></span></li>
+ </ol>
+ </section>`;
+}
+
+/**
+ * Render a self-contained, deterministic review artifact.
+ *
+ * @param {import('../../theme.type.mjs').TonalPaletteCandidate} candidate
+ * @returns {string}
+ */
+export function renderPalettePreview(candidate) {
+ /** @type {PaletteMode[]} */
+ const paletteModes = ['light', 'dark'];
+ const modes = paletteModes
+ .map(mode => renderMode(candidate, mode))
+ .filter(Boolean)
+ .join('');
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="generator" content="${PALETTE_PREVIEW_VERSION}" />
+ <title>Astryx palette candidate</title>
+ <style>
+ :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; background: #111; }
+ * { box-sizing: border-box; }
+ body { margin: 0; background: #111; color: #f5f5f5; }
+ main { max-width: 1600px; margin: 0 auto; padding: 40px; }
+ h1, h2, h3, p { margin: 0; }
+ h1 { font-size: 30px; letter-spacing: -0.03em; }
+ .intro { margin: 8px 0 28px; color: #aaa; font-size: 15px; }
+ .theme-values { display: flex; align-items: center; justify-content: space-between; gap: 32px; margin-bottom: 24px; padding: 18px 20px; border-radius: 14px; background: #1b1b1b; }
+ .theme-values h2 { font-size: 18px; }
+ .theme-values p { margin-top: 4px; color: #999; font-size: 13px; }
+ .theme-values ol { display: grid; grid-template-columns: repeat(2, 96px); gap: 8px; margin: 0; padding: 0; list-style: none; }
+ .theme-values .color { height: 44px; }
+ .modes { display: grid; grid-template-columns: 1fr; gap: 24px; }
+ .mode { min-width: 0; border-radius: 20px; padding: 24px; overflow-x: auto; }
+ .mode.light { background: #f5f5f5; color: #171717; }
+ .mode.dark { background: #232323; color: #f5f5f5; border: 1px solid #393939; }
+ .mode-title { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 24px; }
+ .family + .family { margin-top: 28px; }
+ .family h3 { margin-bottom: 10px; font-size: 18px; }
+ .ramp { display: grid; grid-template-columns: repeat(var(--stop-count), minmax(52px, 1fr)); gap: 8px; margin: 0; padding: 0; list-style: none; }
+ .swatch { min-width: 0; }
+ .color { display: block; height: 58px; border: 1px solid rgb(127 127 127 / 20%); border-radius: 10px; background: var(--swatch); }
+ .meta { display: block; margin-top: 5px; font-size: 11px; line-height: 1.35; }
+ .meta strong, .meta code { display: block; overflow: hidden; text-overflow: ellipsis; }
+ .meta code { opacity: 0.65; font-family: ui-monospace, monospace; }
+ @media (max-width: 700px) { main { padding: 20px; } }
+ </style>
+ </head>
+ <body data-preview-version="${PALETTE_PREVIEW_VERSION}">
+ <main>
+ <h1>Astryx tonal palette</h1>
+ <p class="intro">Generated by <code>${escapeHtml(candidate.recipe)}</code></p>
+ ${renderThemeValues(candidate)}
+ <div class="modes">${modes}
+ </div>
+ </main>
+ </body>
+</html>
+`;
+}
diff --git a/packages/cli/api/theme/palette/generate/preview.test.mjs b/packages/cli/api/theme/palette/generate/preview.test.mjs
new file mode 100644
index 0000000000..4fa09c5ee4
--- /dev/null
+++ b/packages/cli/api/theme/palette/generate/preview.test.mjs
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {renderPalettePreview} from './preview.mjs';
+
+const candidate = {
+ schemaVersion: 1,
+ status: 'candidate',
+ recipe: 'astryx-oklch-v1',
+ black: '#000000',
+ white: '#ffffff',
+ palette: {
+ blue: {
+ name: 'Blue',
+ light: {5: '#000f30', 50: '#0074e2', 95: '#e8f2ff'},
+ dark: {5: '#000f30', 50: '#3b84de', 95: '#e8f2ff'},
+ },
+ },
+};
+
+describe('renderPalettePreview', () => {
+ it('renders a deterministic self-contained review artifact', () => {
+ const first = renderPalettePreview(candidate);
+ const second = renderPalettePreview(candidate);
+
+ expect(first).toBe(second);
+ expect(first).toContain('palette-preview-v1');
+ expect(first).toContain('Light mode');
+ expect(first).toContain('Dark mode');
+ expect(first).toContain('#0074e2');
+ expect(first).toContain('Exact theme values');
+ expect(first).toContain('#000000');
+ expect(first).toContain('#ffffff');
+ expect(first).toContain('Default families repeat these values');
+ expect(first).not.toContain('Shared endpoints');
+ expect(first).not.toContain('does not certify accessibility');
+ expect(first).toContain('grid-template-columns: 1fr');
+ expect(first).toContain('--stop-count:3');
+ expect(first).not.toMatch(/https?:\/\//);
+ expect(first).not.toContain('<script');
+ expect(first).not.toContain('Neutral guidance:');
+ });
+
+ it('escapes author-provided family names', () => {
+ const html = renderPalettePreview({
+ ...candidate,
+ palette: {
+ blue: {...candidate.palette.blue, name: '<script>alert(1)</script>'},
+ },
+ });
+
+ expect(html).not.toContain('<script>alert(1)</script>');
+ expect(html).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
+ });
+});
diff --git a/packages/cli/api/theme/theme.mjs b/packages/cli/api/theme/theme.mjs
index 88c5fa0d35..303985be1b 100644
--- a/packages/cli/api/theme/theme.mjs
+++ b/packages/cli/api/theme/theme.mjs
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file `theme` command barrel — re-exports the build/add/list/template/targets
+ * @file `theme` command barrel — re-exports the build/add/list/template/targets/palette
* leaves so the CLI
* (cli/commands/build-theme.mjs) and scripted callers import from one place.
* Each leaf is also importable directly (e.g. api/theme/add/add.mjs). `theme`
@@ -13,5 +13,15 @@ export {themeBuild, importSpecifier} from './build/build.mjs';
export {themeAdd} from './add/add.mjs';
export {themeTemplate} from './template/template.mjs';
export {themeTargets} from './targets/targets.mjs';
+export {themePaletteGenerate} from './palette/generate/generate.mjs';
+export {
+ COMPACT_11_STOPS,
+ DEFAULT_21_STOPS,
+ PALETTE_RECIPE,
+ generatePaletteSet,
+ generateTonalPalette,
+ parseStopList,
+ validateStops,
+} from './palette/generate/generator.mjs';
export {themeList} from './list/list.mjs';
export {listThemes} from './_adapter.mjs';
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
index 258412cbd3..005fa1641f 100644
--- a/packages/cli/api/theme/theme.type.mjs
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -15,6 +15,7 @@
* xds --json theme add <slug> -> theme.add
* xds --json theme template -> theme.template
* xds --json theme targets [filter] -> theme.targets
+ * xds --json theme palette generate <file> -> theme.palette.generate
* (file not found / parse error) -> CLIError
*
* @position api — colocated typedefs for api/theme/{theme,build,add,list,template,targets,_adapter}
@@ -98,6 +99,59 @@
* @property {{filter: string | null, componentCount: number, targets: ThemeTargetEntry[]}} data
*/
+/**
+ * A generated palette candidate. The palette is still subject to author review
+ * and is not connected to runtime theme values.
+ * @typedef {object} TonalPaletteAnchor
+ * @property {'light' | 'dark'} mode Mode containing the anchored stop.
+ * @property {number} stop Existing requested stop where the anchor applies.
+ * @property {string} color
+ * @property {'exact' | 'bounded' | 'flexible'} policy `exact` preserves the
+ * chosen color at that stop; `bounded` permits adjustment within `maxDeltaE`;
+ * `flexible` treats the color as guidance and blends toward it.
+ * @property {number} [maxDeltaE] Required non-negative perceptual-distance
+ * limit for a `bounded` anchor.
+ */
+
+/**
+ * @typedef {object} TonalPaletteFamilyInput
+ * @property {string} id
+ * @property {string} seed
+ * @property {string} [name]
+ * @property {'chromatic' | 'neutral'} [kind]
+ * @property {TonalPaletteAnchor[]} [anchors]
+ */
+
+/**
+ * @typedef {object} TonalPaletteGenerationInput
+ * @property {TonalPaletteFamilyInput[]} families
+ * @property {number} [vibrancy] Chroma control from 0 (most muted) through 50
+ * (default) to 100 (most vivid).
+ * @property {'neutral-v1' | 'warm-v1' | 'cool-v1' | 'custom'} [neutralProfile]
+ * @property {'light-only' | 'dark-only' | 'light-and-dark'} [modeStrategy]
+ * @property {number[]} [stops] Ordered stops shared by every requested family;
+ * defaults to 0 through 100 in increments of 5. Decimal stops are supported,
+ * and authors may omit the repeated black and white endpoints.
+ */
+
+/**
+ * @typedef {object} TonalPaletteCandidate
+ * @property {1} schemaVersion
+ * @property {'candidate'} status
+ * @property {'astryx-oklch-v1'} recipe
+ * @property {'#000000'} black Exact solid black for theme authoring outside a tonal family.
+ * @property {'#ffffff'} white Exact solid white for theme authoring outside a tonal family.
+ * @property {number[]} stops Canonical order for iterating the palette's stop lookup maps.
+ * @property {Record<string, {name: string, light?: Record<string, string>, dark?: Record<string, string>}>} palette
+ */
+
+/**
+ * xds --json theme palette generate <config>
+ * @typedef {object} ThemePaletteGenerateResponse
+ * @property {'theme.palette.generate'} type
+ * @property {{recipe: 'astryx-oklch-v1', status: 'candidate', familyCount: number, stopCount: number, modes: string[], output: string | null, receipt: string | null, preview: string | null, written: boolean, reason: 'exists' | null, candidate: TonalPaletteCandidate, generationReceipt: Record<string, unknown>}} data
+ */
+
// Make this a module so the @typedefs above are importable as types via
// `import('./theme.type.mjs').ThemeBuildResponse` (and re-exportable from a .d.ts).
export {};
diff --git a/packages/cli/api/theme/themePaletteGenerate.doc.mjs b/packages/cli/api/theme/themePaletteGenerate.doc.mjs
new file mode 100644
index 0000000000..154fa2c457
--- /dev/null
+++ b/packages/cli/api/theme/themePaletteGenerate.doc.mjs
@@ -0,0 +1,86 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themePaletteGenerate',
+ displayName: 'themePaletteGenerate()',
+ summary: 'Generate an author-reviewable palette candidate from JSON input.',
+ description:
+ 'Runs the versioned astryx-oklch-v1 recipe against an explicit generation request. ' +
+ 'It always emits standalone `black` and `white` values that generated TypeScript can import ' +
+ 'directly into semantic theme tokens; those names are reserved from tonal family IDs. It also ' +
+ 'defaults family ramps to 21 stops from 0 through 100, repeating exact black and white ' +
+ 'as endpoints, but accepts any non-empty ordered numeric stop list. Authors may omit ' +
+ 'those repeated endpoints while retaining the standalone values. The result is ' +
+ 'a candidate, not an adopted theme palette or an accessibility claim. With an output path ' +
+ 'it writes the candidate and a detached reproducibility receipt, and leaves existing ' +
+ 'author-owned files untouched unless overwrite is true. Shared stop numbers keep the same ' +
+ 'value across layouts, and decimal stops become explicit keys in generated output.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'themePaletteGenerate(configPath: string, options?: {out?: string, preview?: string, overwrite?: boolean}, ctx?: {cwd?: string}): ThemePaletteGenerateResponse',
+ keywords: ['theme', 'palette', 'generate', 'OKLCH', 'candidate', 'color'],
+ params: [
+ {
+ name: 'configPath',
+ type: 'string',
+ description: 'JSON generation request, resolved within cwd.',
+ required: true,
+ },
+ {
+ name: 'options.out',
+ type: 'string',
+ description:
+ 'Optional candidate JSON destination. A sibling .receipt.json path is derived from it.',
+ },
+ {
+ name: 'options.preview',
+ type: 'string',
+ description: 'Optional path for a self-contained HTML review artifact.',
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description: 'Replace existing candidate and receipt files.',
+ default: 'false',
+ },
+ {
+ name: 'ctx.cwd',
+ type: 'string',
+ description: 'Directory used to resolve the input and output paths.',
+ },
+ ],
+ returns: [
+ {
+ type: 'theme.palette.generate',
+ description:
+ 'The candidate, generation receipt, summary counts, and optional file-write receipt.',
+ },
+ ],
+ throws: [
+ {code: 'ERR_FILE_NOT_FOUND', when: 'the config file does not exist'},
+ {
+ code: 'ERR_PALETTE_GENERATION',
+ when: 'the request, seed, stop layout, mode, or anchor constraint is invalid',
+ },
+ {
+ code: 'ERR_PATH_TRAVERSAL',
+ when: 'an input or output path escapes cwd, or output would replace input',
+ },
+ {code: 'ERR_WRITE_FAILED', when: 'the candidate pair cannot be written'},
+ ],
+ examples: [
+ {
+ label: 'Preview a candidate',
+ code: "themePaletteGenerate('palette.config.json');",
+ },
+ {
+ label: 'Write candidate files',
+ code: "themePaletteGenerate('palette.config.json', {out: 'ocean.palette.ts', preview: 'ocean.palette.html'});",
+ },
+ ],
+ command: 'theme palette generate',
+ related: ['themeBuild', 'themeTemplate'],
+};
diff --git a/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json b/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json
index efc59e75b5..895723f2ca 100644
--- a/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json
+++ b/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"recipe": "astryx-oklch-v1",
- "candidateSha256": "114da1b89911392004e6a4fab88faf59124a6460483563debc93b2c682976a70",
+ "candidateSha256": "a9b186bd7aaffafe34bfabd5b76116115cf667e91066e59ff8f11bcdaaee69bf",
"request": {
"recipe": "astryx-oklch-v1",
"vibrancy": 50,
diff --git a/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.ts b/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.ts
index 9f2c23a112..da461a8006 100644
--- a/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.ts
+++ b/packages/cli/assets/templates/themes/neutral/neutralPalettes.generated.ts
@@ -1,6 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// Generated by astryx-oklch-v1. Review before committing.
+export const black = '#000000' as const;
+export const white = '#ffffff' as const;
+
// prettier-ignore
export const palette = {
"neutral": {
diff --git a/packages/cli/assets/templates/themes/neutral/neutralPalettes.ts b/packages/cli/assets/templates/themes/neutral/neutralPalettes.ts
index a59f27d941..009b0252bf 100644
--- a/packages/cli/assets/templates/themes/neutral/neutralPalettes.ts
+++ b/packages/cli/assets/templates/themes/neutral/neutralPalettes.ts
@@ -1,7 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {black, palette, white} from './neutralPalettes.generated';
+
/** Neutral's reviewed palette, generated from ../palette.config.json. */
-export {
- palette as neutralPalettes,
- palette as default,
-} from './neutralPalettes.generated';
+export const neutralPalettes = {
+ black,
+ white,
+ ...palette,
+} as const;
+
+export default neutralPalettes;
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 9ab69dc068..92b3fb0ef0 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -39,6 +39,10 @@ import {themeAdd} from '../../../api/theme/add/add.mjs';
import {themeTemplate} from '../../../api/theme/template/template.mjs';
import {themeList} from '../../../api/theme/list/list.mjs';
import {themeTargets} from '../../../api/theme/targets/targets.mjs';
+import {
+ serializePaletteCandidate,
+ themePaletteGenerate,
+} from '../../../api/theme/palette/generate/generate.mjs';
import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';
import {defineCommand} from '../lib/define-command.mjs';
import {doc as themeGroup} from './theme.doc.mjs';
@@ -47,11 +51,14 @@ import {doc as themeListCommand} from './theme-list.doc.mjs';
import {doc as themeAddCommand} from './theme-add.doc.mjs';
import {doc as themeTemplateCommand} from './theme-template.doc.mjs';
import {doc as themeTargetsCommand} from './theme-targets.doc.mjs';
+import {doc as themePaletteGroup} from './theme-palette.doc.mjs';
+import {doc as themePaletteGenerateCommand} from './theme-palette-generate.doc.mjs';
import {doc as themeBuildFn} from '../../../api/theme/themeBuild.doc.mjs';
import {doc as themeListFn} from '../../../api/theme/themeList.doc.mjs';
import {doc as themeAddFn} from '../../../api/theme/themeAdd.doc.mjs';
import {doc as themeTemplateFn} from '../../../api/theme/themeTemplate.doc.mjs';
import {doc as themeTargetsFn} from '../../../api/theme/themeTargets.doc.mjs';
+import {doc as themePaletteGenerateFn} from '../../../api/theme/themePaletteGenerate.doc.mjs';
/**
* Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from
@@ -77,7 +84,8 @@ function runThemeBuildOnceChild(file, options) {
const cliBin = resolveCliBin();
const args = [cliBin, 'theme', 'build', file];
if (options.out) args.push('--out', options.out);
- if (options.iconsSpecifier) args.push('--icons-specifier', options.iconsSpecifier);
+ if (options.iconsSpecifier)
+ args.push('--icons-specifier', options.iconsSpecifier);
return new Promise((/** @type {(code: number) => void} */ resolve) => {
const child = spawn(process.execPath, args, {
stdio: 'inherit',
@@ -211,10 +219,19 @@ function formatTargetsTable(targets) {
props: t.props.join(', ') || '-',
states: t.states.join(', ') || '-',
}));
- const head = {key: 'key', component: 'component', props: 'props', states: 'states'};
+ const head = {
+ key: 'key',
+ component: 'component',
+ props: 'props',
+ states: 'states',
+ };
const width = (/** @type {'key'|'component'|'props'} */ field) =>
[head, ...rows].reduce((max, r) => Math.max(max, r[field].length), 0);
- const w = {key: width('key'), component: width('component'), props: width('props')};
+ const w = {
+ key: width('key'),
+ component: width('component'),
+ props: width('props'),
+ };
const line = (/** @type {typeof head} */ r) =>
[
r.key.padEnd(w.key),
@@ -270,6 +287,87 @@ export function registerTheme(program) {
` ${getCliInvocation()} docs theme How component overrides work\n`,
);
+ const palette = defineCommand(theme, themePaletteGroup, {
+ action: (
+ /** @type {unknown} */ options,
+ /** @type {import('commander').Command} */ cmd,
+ ) => {
+ const extras = cmd?.args ?? [];
+ if (extras.length > 0) {
+ const suggestions = (palette.commands ?? []).map(command => ({
+ name: command.name(),
+ reason: 'available subcommand',
+ }));
+ cliError(`unknown subcommand 'theme palette ${String(extras[0])}'`, {
+ suggestions,
+ code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,
+ });
+ return;
+ }
+ palette.help();
+ },
+ });
+
+ defineCommand(palette, themePaletteGenerateCommand, {
+ fn: themePaletteGenerateFn,
+ action: (
+ /** @type {string} */ configPath,
+ /** @type {{out?: string, preview?: string, overwrite?: boolean}} */ options,
+ ) => {
+ const json = program.opts().json || false;
+ /** @type {import('../../../api/theme/theme.type.mjs').ThemePaletteGenerateResponse} */
+ let result;
+ try {
+ result = themePaletteGenerate(configPath, options, {
+ cwd: process.cwd(),
+ });
+ } catch (error) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (error);
+ cliError(err.message, {
+ suggestions: err.suggestions || [],
+ code: err.code,
+ });
+ return;
+ }
+
+ if (json) return jsonOut(result);
+ if (!result.data.output && !result.data.preview) {
+ emit(
+ section(
+ 'Palette candidate',
+ `${result.data.familyCount} families · ${result.data.stopCount} stops · ${result.data.modes.join(', ')}`,
+ ),
+ code(serializePaletteCandidate(result.data.candidate).trimEnd()),
+ );
+ return;
+ }
+ if (!result.data.written) {
+ emit(
+ text(
+ '[skip] One or more requested palette outputs already exist — left as is.',
+ ),
+ text('Pass --overwrite to replace both generated candidate files.'),
+ );
+ return;
+ }
+ emit(
+ ...(result.data.output
+ ? [text(`[ok] Wrote ${result.data.output}`)]
+ : []),
+ ...(result.data.receipt
+ ? [text(`[ok] Wrote ${result.data.receipt}`)]
+ : []),
+ ...(result.data.preview
+ ? [text(`[ok] Wrote ${result.data.preview}`)]
+ : []),
+ text(
+ 'Review and edit the candidate before adopting it as theme-owned palette data.',
+ ),
+ );
+ },
+ });
+
defineCommand(theme, themeBuildCommand, {
fn: themeBuildFn,
action: async (
diff --git a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs
new file mode 100644
index 0000000000..62157f6da5
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'theme palette generate',
+ displayName: 'astryx theme palette generate',
+ namespace: 'cli',
+ summary: 'Generate an OKLCH palette candidate for human review',
+ description:
+ 'Reads an explicit JSON request and runs the versioned astryx-oklch-v1 recipe. ' +
+ 'The command defaults to 21 stops (0 through 100) but accepts any non-empty ordered ' +
+ 'numeric stop list, including decimals. Stops apply to every family in the request. ' +
+ 'Authors may omit the repeated endpoints with a custom list; standalone exact black ' +
+ 'and white values remain available in every candidate. ' +
+ 'For anchors, exact preserves the chosen color at its mode and stop; bounded allows ' +
+ 'movement within maxDeltaE; flexible uses the color as guidance. ' +
+ 'Without --out it prints a preview. With --out it writes a candidate file and detached ' +
+ 'receipt. --preview writes a standardized, self-contained HTML review artifact. ' +
+ 'TypeScript output is directly importable and contains no generator dependency. ' +
+ 'JSON is also supported. Existing author-owned files are left untouched unless --overwrite is explicit.',
+ fn: 'themePaletteGenerate',
+ args: [{name: 'config', param: 'configPath', required: true}],
+ options: [
+ {
+ flag: '-o, --out <path>',
+ param: 'options.out',
+ description:
+ 'Write a candidate TypeScript or JSON file and a sibling receipt',
+ },
+ {
+ flag: '--preview <path>',
+ param: 'options.preview',
+ description: 'Write a standardized self-contained HTML preview',
+ },
+ {
+ flag: '-f, --overwrite',
+ param: 'options.overwrite',
+ description: 'Replace existing candidate and receipt files',
+ },
+ ],
+ examples: [
+ {
+ label: 'Preview candidate JSON',
+ cli: 'astryx theme palette generate palette.config.json',
+ },
+ {
+ label: 'Write candidate and receipt',
+ cli: 'astryx theme palette generate palette.config.json --out ocean.palette.ts',
+ },
+ {
+ label: 'Write candidate, receipt, and review preview',
+ cli: 'astryx theme palette generate palette.config.json --out ocean.palette.ts --preview ocean.palette.html',
+ },
+ ],
+ exitCodes: [
+ {
+ code: 0,
+ when: 'a candidate is produced or existing output is left untouched',
+ },
+ {
+ code: 1,
+ when: 'the request is invalid or output cannot be written safely',
+ },
+ ],
+ related: ['theme build', 'theme template'],
+};
diff --git a/packages/cli/clients/cli/commands/theme-palette-generate.test.mjs b/packages/cli/clients/cli/commands/theme-palette-generate.test.mjs
new file mode 100644
index 0000000000..62a3c754fd
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-palette-generate.test.mjs
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+let temporaryDirectory;
+
+beforeEach(() => {
+ temporaryDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-palette-cli-'),
+ );
+ fs.writeFileSync(
+ path.join(temporaryDirectory, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'dark-only',
+ stops: [10, 50, 90],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(temporaryDirectory, {recursive: true, force: true});
+});
+
+describe('astryx theme palette generate', () => {
+ it('previews a candidate without writing', async () => {
+ const {status, stdout} = await runCli(
+ ['theme', 'palette', 'generate', 'palette.config.json'],
+ {cwd: temporaryDirectory},
+ );
+
+ expect(status).toBe(0);
+ expect(stdout).toContain('Palette candidate');
+ expect(stdout).toContain('astryx-oklch-v1');
+ expect(fs.readdirSync(temporaryDirectory)).toEqual(['palette.config.json']);
+ });
+
+ it('preserves mixed stop order in the terminal preview', async () => {
+ fs.writeFileSync(
+ path.join(temporaryDirectory, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'light-only',
+ stops: [12.5, 50, 80],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+
+ const {status, stdout} = await runCli(
+ ['theme', 'palette', 'generate', 'palette.config.json'],
+ {cwd: temporaryDirectory},
+ );
+
+ expect(status).toBe(0);
+ expect(stdout.indexOf('"12.5":')).toBeLessThan(stdout.indexOf('"50":'));
+ expect(stdout.indexOf('"50":')).toBeLessThan(stdout.indexOf('"80":'));
+ });
+
+ it('writes candidate files and returns one JSON envelope', async () => {
+ const {status, stdout} = await runCli(
+ [
+ '--json',
+ 'theme',
+ 'palette',
+ 'generate',
+ 'palette.config.json',
+ '--out',
+ 'ocean.palette.ts',
+ '--preview',
+ 'ocean.palette.html',
+ ],
+ {cwd: temporaryDirectory},
+ );
+
+ expect(status).toBe(0);
+ const response = JSON.parse(stdout);
+ expect(response.type).toBe('theme.palette.generate');
+ expect(response.data).toMatchObject({
+ recipe: 'astryx-oklch-v1',
+ stopCount: 3,
+ modes: ['dark'],
+ output: 'ocean.palette.ts',
+ receipt: 'ocean.palette.receipt.json',
+ preview: 'ocean.palette.html',
+ written: true,
+ });
+ expect(
+ fs.existsSync(path.join(temporaryDirectory, response.data.output)),
+ ).toBe(true);
+ expect(
+ fs.existsSync(path.join(temporaryDirectory, response.data.receipt)),
+ ).toBe(true);
+ expect(
+ fs.existsSync(path.join(temporaryDirectory, response.data.preview)),
+ ).toBe(true);
+ });
+
+ it('preserves mixed stop order in the JSON response', async () => {
+ fs.writeFileSync(
+ path.join(temporaryDirectory, 'palette.config.json'),
+ JSON.stringify({
+ modeStrategy: 'light-only',
+ stops: [12.5, 50, 80],
+ families: [{id: 'blue', seed: '#0074e2'}],
+ }),
+ );
+
+ const {status, stdout} = await runCli(
+ ['--json', 'theme', 'palette', 'generate', 'palette.config.json'],
+ {cwd: temporaryDirectory},
+ );
+
+ expect(status).toBe(0);
+ expect(JSON.parse(stdout).data.candidate.stops).toEqual([12.5, 50, 80]);
+ });
+
+ it('returns the stable palette-generation error code', async () => {
+ fs.writeFileSync(
+ path.join(temporaryDirectory, 'palette.config.json'),
+ JSON.stringify({stops: [], families: [{id: 'blue', seed: '#0074e2'}]}),
+ );
+ const {status, stdout} = await runCli(
+ ['--json', 'theme', 'palette', 'generate', 'palette.config.json'],
+ {cwd: temporaryDirectory},
+ );
+
+ expect(status).toBe(1);
+ expect(JSON.parse(stdout)).toMatchObject({
+ code: 'ERR_PALETTE_GENERATION',
+ });
+ });
+});
diff --git a/packages/cli/clients/cli/commands/theme-palette.doc.mjs b/packages/cli/clients/cli/commands/theme-palette.doc.mjs
new file mode 100644
index 0000000000..e88366d299
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-palette.doc.mjs
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'theme palette',
+ displayName: 'astryx theme palette',
+ namespace: 'cli',
+ summary: 'Create and work with theme-owned color palettes',
+ description:
+ 'Palette authoring tools. The initial generate command creates reviewable candidates. ' +
+ 'Palette inspection and diagnostic commands are intentionally deferred to follow-up work.',
+ subcommands: ['generate'],
+ examples: [
+ {
+ label: 'Generate a candidate',
+ cli: 'astryx theme palette generate palette.config.json',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'help is shown or a subcommand succeeds'},
+ {code: 1, when: 'an unknown subcommand is provided'},
+ ],
+ related: ['theme build', 'theme template'],
+};
diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjs
index e72c1c4561..a75eab59c2 100644
--- a/packages/cli/clients/cli/commands/theme.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme.doc.mjs
@@ -18,11 +18,16 @@ export const doc = {
'The theme command group. Running astryx theme with no subcommand prints the ' +
'subcommand list; the work happens in the subcommands: compile a theme (build), ' +
'scaffold one into your project (add), start a custom one from the annotated template (template), ' +
- 'list the bundled themes (list), or list the component theming targets a theme can override (targets).',
- subcommands: ['build', 'add', 'list', 'template', 'targets'],
+ 'list the bundled themes (list), generate a palette candidate (palette), or list the ' +
+ 'component theming targets a theme can override (targets).',
+ subcommands: ['build', 'add', 'list', 'template', 'palette', 'targets'],
examples: [
{label: 'List bundled themes', cli: 'astryx theme list'},
{label: 'Scaffold a theme', cli: 'astryx theme add matcha'},
+ {
+ label: 'Generate a palette candidate',
+ cli: 'astryx theme palette generate palette.config.json',
+ },
{label: 'See what a theme can override', cli: 'astryx theme targets'},
],
exitCodes: [
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index 9b18eee452..3f5f3b1316 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -79,6 +79,7 @@ export const JSON_SUPPORTED = new Set([
'theme add',
'theme template',
'theme targets',
+ 'theme palette generate',
'upgrade',
'manifest',
'doctor',
diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjs
index 8ffe8e8e70..ae17921c48 100644
--- a/packages/cli/clients/cli/lib/manifest.mjs
+++ b/packages/cli/clients/cli/lib/manifest.mjs
@@ -79,6 +79,7 @@ export const RESPONSE_TYPES = {
'theme add': ['theme.list', 'theme.add'],
'theme template': ['theme.template'],
'theme targets': ['theme.targets'],
+ 'theme palette generate': ['theme.palette.generate'],
upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],
manifest: ['manifest'],
doctor: ['doctor'],
@@ -106,7 +107,11 @@ const EXAMPLES = {
],
build: ['astryx build', 'astryx build "analytics dashboard" --json'],
swizzle: ['astryx swizzle XDSButton'],
- template: ['astryx template --json', 'astryx template dashboard ./src/app', 'astryx template --cdn'],
+ template: [
+ 'astryx template --json',
+ 'astryx template dashboard ./src/app',
+ 'astryx template --cdn',
+ ],
hook: ['astryx hook', 'astryx hook useFocusTrap --json'],
'theme build': [
'astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',
@@ -118,7 +123,14 @@ const EXAMPLES = {
'astryx theme add matcha ./src/themes/matcha',
],
'theme template': ['astryx theme template', 'astryx theme template --json'],
- 'theme targets': ['astryx theme targets Switch', 'astryx --json theme targets'],
+ 'theme targets': [
+ 'astryx theme targets Switch',
+ 'astryx --json theme targets',
+ ],
+ 'theme palette generate': [
+ 'astryx theme palette generate palette.config.json',
+ 'astryx theme palette generate palette.config.json --out ocean.palette.json',
+ ],
upgrade: ['astryx upgrade --json'],
manifest: ['astryx manifest --json', 'astryx --json'],
doctor: ['astryx doctor', 'astryx doctor --json'],
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
index d3c35de2b3..bad2557b12 100644
--- a/packages/cli/foundation/response/error-codes.doc.mjs
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -191,6 +191,11 @@ export const doc = {
description:
'A theme file could not be loaded / parsed into a defineTheme result.',
},
+ {
+ value: 'ERR_PALETTE_GENERATION',
+ description:
+ 'A palette generation request or one of its constraints was invalid.',
+ },
// Upgrade
{
diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjs
index 01453711ba..8057ee55cf 100644
--- a/packages/cli/foundation/response/error-codes.mjs
+++ b/packages/cli/foundation/response/error-codes.mjs
@@ -71,6 +71,7 @@
* | 'ERR_WRITE_FAILED'
* | 'ERR_THEME_INVALID'
* | 'ERR_THEME_LOAD'
+ * | 'ERR_PALETTE_GENERATION'
* | 'ERR_VERSION_DETECT'
* | 'ERR_INVALID_VERSION'
* | 'ERR_DEP_MISSING'
@@ -173,6 +174,10 @@ export const ERROR_CODES = Object.freeze({
/** A theme file could not be loaded / parsed into a defineTheme result. */
ERR_THEME_LOAD: 'ERR_THEME_LOAD',
+ // ── Palette generation ──────────────────────────────────────────
+ /** A palette generation request or its constraints were invalid. */
+ ERR_PALETTE_GENERATION: 'ERR_PALETTE_GENERATION',
+
// ── Upgrade ──────────────────────────────────────────────────────
/** The current `@astryxdesign/core` version could not be detected. */
ERR_VERSION_DETECT: 'ERR_VERSION_DETECT',
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 68ec6557a9..1eee9efcc0 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -214,6 +214,11 @@ export const doc = {
description:
'The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys.',
},
+ {
+ value: 'theme.palette.generate',
+ description:
+ 'An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result.',
+ },
// upgrade
{
diff --git a/packages/themes/neutral/README.md b/packages/themes/neutral/README.md
index c1c3034d11..cc25eda5cb 100644
--- a/packages/themes/neutral/README.md
+++ b/packages/themes/neutral/README.md
@@ -40,6 +40,19 @@ theme-local import. Neutral currently uses 21 numbered stops in each light and
dark ramp, but that layout is a Neutral decision rather than a requirement for
other themes.
+Exact solid endpoints use the same stable palette namespace as the tonal
+families: `neutralPalettes.black` and `neutralPalettes.white`. Theme definitions
+can assign those values directly to semantic tokens without treating a neutral
+ramp endpoint as the named color.
+
+```ts
+import {neutralPalettes} from '@astryxdesign/theme-neutral';
+
+const tokens = {
+ '--color-background-inverted': [neutralPalettes.black, neutralPalettes.white],
+};
+```
+
Neutral opts into a muted dark edge for chromatic families. Stops 5 through 25
use 50% of their realized chroma, then recover smoothly to the standard dark
recipe at stop 60. Yellow uses a gentler 65% edge multiplier. Light ramps,
diff --git a/packages/themes/neutral/src/neutralPalettes.generated.receipt.json b/packages/themes/neutral/src/neutralPalettes.generated.receipt.json
index efc59e75b5..895723f2ca 100644
--- a/packages/themes/neutral/src/neutralPalettes.generated.receipt.json
+++ b/packages/themes/neutral/src/neutralPalettes.generated.receipt.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"recipe": "astryx-oklch-v1",
- "candidateSha256": "114da1b89911392004e6a4fab88faf59124a6460483563debc93b2c682976a70",
+ "candidateSha256": "a9b186bd7aaffafe34bfabd5b76116115cf667e91066e59ff8f11bcdaaee69bf",
"request": {
"recipe": "astryx-oklch-v1",
"vibrancy": 50,
diff --git a/packages/themes/neutral/src/neutralPalettes.generated.ts b/packages/themes/neutral/src/neutralPalettes.generated.ts
index 9f2c23a112..da461a8006 100644
--- a/packages/themes/neutral/src/neutralPalettes.generated.ts
+++ b/packages/themes/neutral/src/neutralPalettes.generated.ts
@@ -1,6 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// Generated by astryx-oklch-v1. Review before committing.
+export const black = '#000000' as const;
+export const white = '#ffffff' as const;
+
// prettier-ignore
export const palette = {
"neutral": {
diff --git a/packages/themes/neutral/src/neutralPalettes.test.ts b/packages/themes/neutral/src/neutralPalettes.test.ts
index 801db91c44..c7641158c4 100644
--- a/packages/themes/neutral/src/neutralPalettes.test.ts
+++ b/packages/themes/neutral/src/neutralPalettes.test.ts
@@ -10,7 +10,11 @@ const neutralPaletteStops = [
describe('neutral palette artifact', () => {
it('keeps the approved palette structurally valid', () => {
+ expect(neutralPalettes.black).toBe('#000000');
+ expect(neutralPalettes.white).toBe('#ffffff');
expect(Object.keys(neutralPalettes)).toEqual([
+ 'black',
+ 'white',
'neutral',
'red',
'orange',
@@ -23,7 +27,19 @@ describe('neutral palette artifact', () => {
'pink',
]);
- for (const family of Object.values(neutralPalettes)) {
+ for (const familyName of [
+ 'neutral',
+ 'red',
+ 'orange',
+ 'yellow',
+ 'green',
+ 'teal',
+ 'cyan',
+ 'blue',
+ 'purple',
+ 'pink',
+ ] as const) {
+ const family = neutralPalettes[familyName];
for (const stop of neutralPaletteStops) {
expect(family.light[stop]).toMatch(/^#[0-9a-f]{6}$/i);
expect(family.dark[stop]).toMatch(/^#[0-9a-f]{6}$/i);
diff --git a/packages/themes/neutral/src/neutralPalettes.ts b/packages/themes/neutral/src/neutralPalettes.ts
index a59f27d941..009b0252bf 100644
--- a/packages/themes/neutral/src/neutralPalettes.ts
+++ b/packages/themes/neutral/src/neutralPalettes.ts
@@ -1,7 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {black, palette, white} from './neutralPalettes.generated';
+
/** Neutral's reviewed palette, generated from ../palette.config.json. */
-export {
- palette as neutralPalettes,
- palette as default,
-} from './neutralPalettes.generated';
+export const neutralPalettes = {
+ black,
+ white,
+ ...palette,
+} as const;
+
+export default neutralPalettes;
diff --git a/packages/themes/neutral/src/source.ts b/packages/themes/neutral/src/source.ts
index 75be51b95b..51a9a8ec76 100644
--- a/packages/themes/neutral/src/source.ts
+++ b/packages/themes/neutral/src/source.ts
@@ -1,4 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
export {neutralTheme} from './neutralTheme';
+export {neutralPalettes} from './neutralPalettes';
export {neutralIconRegistry} from './icons';